UNPKG

19.9 kBJavaScriptView Raw
1"use strict";
2
3var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
5Object.defineProperty(exports, "__esModule", {
6 value: true
7});
8exports.driver = driver;
9Object.defineProperty(exports, "Neo4jError", {
10 enumerable: true,
11 get: function get() {
12 return _neo4jDriverCore.Neo4jError;
13 }
14});
15Object.defineProperty(exports, "error", {
16 enumerable: true,
17 get: function get() {
18 return _neo4jDriverCore.error;
19 }
20});
21Object.defineProperty(exports, "int", {
22 enumerable: true,
23 get: function get() {
24 return _neo4jDriverCore["int"];
25 }
26});
27Object.defineProperty(exports, "isInt", {
28 enumerable: true,
29 get: function get() {
30 return _neo4jDriverCore.isInt;
31 }
32});
33Object.defineProperty(exports, "isPoint", {
34 enumerable: true,
35 get: function get() {
36 return _neo4jDriverCore.isPoint;
37 }
38});
39Object.defineProperty(exports, "isDate", {
40 enumerable: true,
41 get: function get() {
42 return _neo4jDriverCore.isDate;
43 }
44});
45Object.defineProperty(exports, "isDateTime", {
46 enumerable: true,
47 get: function get() {
48 return _neo4jDriverCore.isDateTime;
49 }
50});
51Object.defineProperty(exports, "isDuration", {
52 enumerable: true,
53 get: function get() {
54 return _neo4jDriverCore.isDuration;
55 }
56});
57Object.defineProperty(exports, "isLocalDateTime", {
58 enumerable: true,
59 get: function get() {
60 return _neo4jDriverCore.isLocalDateTime;
61 }
62});
63Object.defineProperty(exports, "isLocalTime", {
64 enumerable: true,
65 get: function get() {
66 return _neo4jDriverCore.isLocalTime;
67 }
68});
69Object.defineProperty(exports, "isTime", {
70 enumerable: true,
71 get: function get() {
72 return _neo4jDriverCore.isTime;
73 }
74});
75exports["default"] = exports.temporal = exports.spatial = exports.session = exports.types = exports.logging = exports.auth = exports.integer = void 0;
76
77var _driver = require("./driver");
78
79var _version = _interopRequireDefault(require("./version"));
80
81var _neo4jDriverCore = require("neo4j-driver-core");
82
83var _neo4jDriverBoltConnection = require("neo4j-driver-bolt-connection");
84
85/**
86 * Copyright (c) "Neo4j"
87 * Neo4j Sweden AB [http://neo4j.com]
88 *
89 * This file is part of Neo4j.
90 *
91 * Licensed under the Apache License, Version 2.0 (the "License");
92 * you may not use this file except in compliance with the License.
93 * You may obtain a copy of the License at
94 *
95 * http://www.apache.org/licenses/LICENSE-2.0
96 *
97 * Unless required by applicable law or agreed to in writing, software
98 * distributed under the License is distributed on an "AS IS" BASIS,
99 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
100 * See the License for the specific language governing permissions and
101 * limitations under the License.
102 */
103var _internal$util = _neo4jDriverCore.internal.util,
104 ENCRYPTION_ON = _internal$util.ENCRYPTION_ON,
105 ENCRYPTION_OFF = _internal$util.ENCRYPTION_OFF,
106 assertString = _internal$util.assertString,
107 isEmptyObjectOrNull = _internal$util.isEmptyObjectOrNull,
108 ServerAddress = _neo4jDriverCore.internal.serverAddress.ServerAddress,
109 urlUtil = _neo4jDriverCore.internal.urlUtil;
110/**
111 * Construct a new Neo4j Driver. This is your main entry point for this
112 * library.
113 *
114 * ## Configuration
115 *
116 * This function optionally takes a configuration argument. Available configuration
117 * options are as follows:
118 *
119 * {
120 * // Encryption level: ENCRYPTION_ON or ENCRYPTION_OFF.
121 * encrypted: ENCRYPTION_ON|ENCRYPTION_OFF
122 *
123 * // Trust strategy to use if encryption is enabled. There is no mode to disable
124 * // trust other than disabling encryption altogether. The reason for
125 * // this is that if you don't know who you are talking to, it is easy for an
126 * // attacker to hijack your encrypted connection, rendering encryption pointless.
127 * //
128 * // TRUST_SYSTEM_CA_SIGNED_CERTIFICATES is the default choice. For NodeJS environments, this
129 * // means that you trust whatever certificates are in the default trusted certificate
130 * // store of the underlying system. For Browser environments, the trusted certificate
131 * // store is usually managed by the browser. Refer to your system or browser documentation
132 * // if you want to explicitly add a certificate as trusted.
133 * //
134 * // TRUST_CUSTOM_CA_SIGNED_CERTIFICATES is another option for trust verification -
135 * // whenever we establish an encrypted connection, we ensure the host is using
136 * // an encryption certificate that is in, or is signed by, a certificate given
137 * // as trusted through configuration. This option is only available for NodeJS environments.
138 * //
139 * // TRUST_ALL_CERTIFICATES means that you trust everything without any verifications
140 * // steps carried out. This option is only available for NodeJS environments and should not
141 * // be used on production systems.
142 * trust: "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES" | "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES" |
143 * "TRUST_ALL_CERTIFICATES",
144 *
145 * // List of one or more paths to trusted encryption certificates. This only
146 * // works in the NodeJS bundle, and only matters if you use "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES".
147 * // The certificate files should be in regular X.509 PEM format.
148 * // For instance, ['./trusted.pem']
149 * trustedCertificates: [],
150 *
151 * // The maximum total number of connections allowed to be managed by the connection pool, per host.
152 * // This includes both in-use and idle connections. No maximum connection pool size is imposed
153 * // by default.
154 * maxConnectionPoolSize: 100,
155 *
156 * // The maximum allowed lifetime for a pooled connection in milliseconds. Pooled connections older than this
157 * // threshold will be closed and removed from the pool. Such discarding happens during connection acquisition
158 * // so that new session is never backed by an old connection. Setting this option to a low value will cause
159 * // a high connection churn and might result in a performance hit. It is recommended to set maximum lifetime
160 * // to a slightly smaller value than the one configured in network equipment (load balancer, proxy, firewall,
161 * // etc. can also limit maximum connection lifetime). No maximum lifetime limit is imposed by default. Zero
162 * // and negative values result in lifetime not being checked.
163 * maxConnectionLifetime: 60 * 60 * 1000, // 1 hour
164 *
165 * // The maximum amount of time to wait to acquire a connection from the pool (to either create a new
166 * // connection or borrow an existing one.
167 * connectionAcquisitionTimeout: 60000, // 1 minute
168 *
169 * // Specify the maximum time in milliseconds transactions are allowed to retry via
170 * // `Session#readTransaction()` and `Session#writeTransaction()` functions.
171 * // These functions will retry the given unit of work on `ServiceUnavailable`, `SessionExpired` and transient
172 * // errors with exponential backoff using initial delay of 1 second.
173 * // Default value is 30000 which is 30 seconds.
174 * maxTransactionRetryTime: 30000, // 30 seconds
175 *
176 * // Specify socket connection timeout in milliseconds. Numeric values are expected. Negative and zero values
177 * // result in no timeout being applied. Connection establishment will be then bound by the timeout configured
178 * // on the operating system level. Default value is 30000, which is 30 seconds.
179 * connectionTimeout: 30000, // 30 seconds
180 *
181 * // Make this driver always return native JavaScript numbers for integer values, instead of the
182 * // dedicated {@link Integer} class. Values that do not fit in native number bit range will be represented as
183 * // `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`.
184 * // **Warning:** ResultSummary It is not always safe to enable this setting when JavaScript applications are not the only ones
185 * // interacting with the database. Stored numbers might in such case be not representable by native
186 * // {@link Number} type and thus driver will return lossy values. This might also happen when data was
187 * // initially imported using neo4j import tool and contained numbers larger than
188 * // `Number.MAX_SAFE_INTEGER`. Driver will then return positive infinity, which is lossy.
189 * // Default value for this option is `false` because native JavaScript numbers might result
190 * // in loss of precision in the general case.
191 * disableLosslessIntegers: false,
192 *
193 * // Make this driver always return native Javascript {@link BigInt} for integer values, instead of the dedicated {@link Integer} class or {@link Number}.
194 * //
195 * // Default value for this option is `false` for backwards compatibility.
196 * //
197 * // **Warning:** `BigInt` doesn't implement the method `toJSON`. In maner of serialize it as `json`, It's needed to add a custom implementation of the `toJSON` on the
198 * // `BigInt.prototype` {@see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#use_within_json}
199 * useBigInt: false,
200 *
201 * // Specify the logging configuration for the driver. Object should have two properties `level` and `logger`.
202 * //
203 * // Property `level` represents the logging level which should be one of: 'error', 'warn', 'info' or 'debug'. This property is optional and
204 * // its default value is 'info'. Levels have priorities: 'error': 0, 'warn': 1, 'info': 2, 'debug': 3. Enabling a certain level also enables all
205 * // levels with lower priority. For example: 'error', 'warn' and 'info' will be logged when 'info' level is configured.
206 * //
207 * // Property `logger` represents the logging function which will be invoked for every log call with an acceptable level. The function should
208 * // take two string arguments `level` and `message`. The function should not execute any blocking or long-running operations
209 * // because it is often executed on a hot path.
210 * //
211 * // No logging is done by default. See `neo4j.logging` object that contains predefined logging implementations.
212 * logging: {
213 * level: 'info',
214 * logger: (level, message) => console.log(level + ' ' + message)
215 * },
216 *
217 * // Specify a custom server address resolver function used by the routing driver to resolve the initial address used to create the driver.
218 * // Such resolution happens:
219 * // * during the very first rediscovery when driver is created
220 * // * when all the known routers from the current routing table have failed and driver needs to fallback to the initial address
221 * //
222 * // In NodeJS environment driver defaults to performing a DNS resolution of the initial address using 'dns' module.
223 * // In browser environment driver uses the initial address as-is.
224 * // Value should be a function that takes a single string argument - the initial address. It should return an array of new addresses.
225 * // Address is a string of shape '<host>:<port>'. Provided function can return either a Promise resolved with an array of addresses
226 * // or array of addresses directly.
227 * resolver: function(address) {
228 * return ['127.0.0.1:8888', 'fallback.db.com:7687'];
229 * },
230 *
231 * // Optionally override the default user agent name.
232 * userAgent: USER_AGENT
233 * }
234 *
235 * @param {string} url The URL for the Neo4j database, for instance "neo4j://localhost" and/or "bolt://localhost"
236 * @param {Map<string,string>} authToken Authentication credentials. See {@link auth} for helpers.
237 * @param {Object} config Configuration object. See the configuration section above for details.
238 * @returns {Driver}
239 */
240
241function driver(url, authToken) {
242 var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
243 assertString(url, 'Bolt URL');
244 var parsedUrl = urlUtil.parseDatabaseUrl(url); // Determine entryption/trust options from the URL.
245
246 var routing = false;
247 var encrypted = false;
248 var trust;
249
250 switch (parsedUrl.scheme) {
251 case 'bolt':
252 break;
253
254 case 'bolt+s':
255 encrypted = true;
256 trust = 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES';
257 break;
258
259 case 'bolt+ssc':
260 encrypted = true;
261 trust = 'TRUST_ALL_CERTIFICATES';
262 break;
263
264 case 'neo4j':
265 routing = true;
266 break;
267
268 case 'neo4j+s':
269 encrypted = true;
270 trust = 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES';
271 routing = true;
272 break;
273
274 case 'neo4j+ssc':
275 encrypted = true;
276 trust = 'TRUST_ALL_CERTIFICATES';
277 routing = true;
278 break;
279
280 default:
281 throw new Error("Unknown scheme: ".concat(parsedUrl.scheme));
282 } // Encryption enabled on URL, propagate trust to the config.
283
284
285 if (encrypted) {
286 // Check for configuration conflict between URL and config.
287 if ('encrypted' in config || 'trust' in config) {
288 throw new Error('Encryption/trust can only be configured either through URL or config, not both');
289 }
290
291 config.encrypted = ENCRYPTION_ON;
292 config.trust = trust;
293 } // Sanitize authority token. Nicer error from server when a scheme is set.
294
295
296 authToken = authToken || {};
297 authToken.scheme = authToken.scheme || 'none'; // Use default user agent or user agent specified by user.
298
299 config.userAgent = config.userAgent || USER_AGENT;
300 var address = ServerAddress.fromUrl(parsedUrl.hostAndPort);
301 var meta = {
302 address: address,
303 typename: routing ? 'Routing' : 'Direct',
304 routing: routing
305 };
306 return new _driver.Driver(meta, config, createConnectionProviderFunction());
307
308 function createConnectionProviderFunction() {
309 if (routing) {
310 return function (id, config, log, hostNameResolver) {
311 return new _neo4jDriverBoltConnection.RoutingConnectionProvider({
312 id: id,
313 config: config,
314 log: log,
315 hostNameResolver: hostNameResolver,
316 authToken: authToken,
317 address: address,
318 userAgent: config.userAgent,
319 routingContext: parsedUrl.query
320 });
321 };
322 } else {
323 if (!isEmptyObjectOrNull(parsedUrl.query)) {
324 throw new Error("Parameters are not supported with none routed scheme. Given URL: '".concat(url, "'"));
325 }
326
327 return function (id, config, log) {
328 return new _neo4jDriverBoltConnection.DirectConnectionProvider({
329 id: id,
330 config: config,
331 log: log,
332 authToken: authToken,
333 address: address,
334 userAgent: config.userAgent
335 });
336 };
337 }
338 }
339}
340/**
341 * @property {function(username: string, password: string, realm: ?string)} basic the function to create a
342 * basic authentication token.
343 * @property {function(base64EncodedTicket: string)} kerberos the function to create a Kerberos authentication token.
344 * Accepts a single string argument - base64 encoded Kerberos ticket.
345 * @property {function(principal: string, credentials: string, realm: string, scheme: string, parameters: ?object)} custom
346 * the function to create a custom authentication token.
347 */
348
349
350var auth = {
351 basic: function basic(username, password) {
352 var realm = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined;
353
354 if (realm) {
355 return {
356 scheme: 'basic',
357 principal: username,
358 credentials: password,
359 realm: realm
360 };
361 } else {
362 return {
363 scheme: 'basic',
364 principal: username,
365 credentials: password
366 };
367 }
368 },
369 kerberos: function kerberos(base64EncodedTicket) {
370 return {
371 scheme: 'kerberos',
372 principal: '',
373 // This empty string is required for backwards compatibility.
374 credentials: base64EncodedTicket
375 };
376 },
377 custom: function custom(principal, credentials, realm, scheme) {
378 var parameters = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined;
379
380 if (parameters) {
381 return {
382 scheme: scheme,
383 principal: principal,
384 credentials: credentials,
385 realm: realm,
386 parameters: parameters
387 };
388 } else {
389 return {
390 scheme: scheme,
391 principal: principal,
392 credentials: credentials,
393 realm: realm
394 };
395 }
396 }
397};
398exports.auth = auth;
399var USER_AGENT = 'neo4j-javascript/' + _version["default"];
400/**
401 * Object containing predefined logging configurations. These are expected to be used as values of the driver config's `logging` property.
402 * @property {function(level: ?string): object} console the function to create a logging config that prints all messages to `console.log` with
403 * timestamp, level and message. It takes an optional `level` parameter which represents the maximum log level to be logged. Default value is 'info'.
404 */
405
406var logging = {
407 console: function (_console) {
408 function console(_x) {
409 return _console.apply(this, arguments);
410 }
411
412 console.toString = function () {
413 return _console.toString();
414 };
415
416 return console;
417 }(function (level) {
418 return {
419 level: level,
420 logger: function logger(level, message) {
421 return console.log("".concat(global.Date.now(), " ").concat(level.toUpperCase(), " ").concat(message));
422 }
423 };
424 })
425};
426/**
427 * Object containing constructors for all neo4j types.
428 */
429
430exports.logging = logging;
431var types = {
432 Node: _neo4jDriverCore.Node,
433 Relationship: _neo4jDriverCore.Relationship,
434 UnboundRelationship: _neo4jDriverCore.UnboundRelationship,
435 PathSegment: _neo4jDriverCore.PathSegment,
436 Path: _neo4jDriverCore.Path,
437 Result: _neo4jDriverCore.Result,
438 ResultSummary: _neo4jDriverCore.ResultSummary,
439 Record: _neo4jDriverCore.Record,
440 Point: _neo4jDriverCore.Point,
441 Date: _neo4jDriverCore.Date,
442 DateTime: _neo4jDriverCore.DateTime,
443 Duration: _neo4jDriverCore.Duration,
444 LocalDateTime: _neo4jDriverCore.LocalDateTime,
445 LocalTime: _neo4jDriverCore.LocalTime,
446 Time: _neo4jDriverCore.Time,
447 Integer: _neo4jDriverCore.Integer
448};
449/**
450 * Object containing string constants representing session access modes.
451 */
452
453exports.types = types;
454var session = {
455 READ: _driver.READ,
456 WRITE: _driver.WRITE
457};
458/**
459 * Object containing functions to work with {@link Integer} objects.
460 */
461
462exports.session = session;
463var integer = {
464 toNumber: _neo4jDriverCore.toNumber,
465 toString: _neo4jDriverCore.toString,
466 inSafeRange: _neo4jDriverCore.inSafeRange
467};
468/**
469 * Object containing functions to work with spatial types, like {@link Point}.
470 */
471
472exports.integer = integer;
473var spatial = {
474 isPoint: _neo4jDriverCore.isPoint
475};
476/**
477 * Object containing functions to work with temporal types, like {@link Time} or {@link Duration}.
478 */
479
480exports.spatial = spatial;
481var temporal = {
482 isDuration: _neo4jDriverCore.isDuration,
483 isLocalTime: _neo4jDriverCore.isLocalTime,
484 isTime: _neo4jDriverCore.isTime,
485 isDate: _neo4jDriverCore.isDate,
486 isLocalDateTime: _neo4jDriverCore.isLocalDateTime,
487 isDateTime: _neo4jDriverCore.isDateTime
488};
489/**
490 * @private
491 */
492
493exports.temporal = temporal;
494var forExport = {
495 driver: driver,
496 "int": _neo4jDriverCore["int"],
497 isInt: _neo4jDriverCore.isInt,
498 isPoint: _neo4jDriverCore.isPoint,
499 isDuration: _neo4jDriverCore.isDuration,
500 isLocalTime: _neo4jDriverCore.isLocalTime,
501 isTime: _neo4jDriverCore.isTime,
502 isDate: _neo4jDriverCore.isDate,
503 isLocalDateTime: _neo4jDriverCore.isLocalDateTime,
504 isDateTime: _neo4jDriverCore.isDateTime,
505 integer: integer,
506 Neo4jError: _neo4jDriverCore.Neo4jError,
507 auth: auth,
508 logging: logging,
509 types: types,
510 session: session,
511 error: _neo4jDriverCore.error,
512 spatial: spatial,
513 temporal: temporal
514};
515var _default = forExport;
516exports["default"] = _default;
\No newline at end of file