From 5a270d8aeebc9d0f08b818985d94244293ce7d19 Mon Sep 17 00:00:00 2001 From: Ooker Date: Wed, 29 Sep 2021 13:33:51 +0700 Subject: [PATCH 1/8] Update documentary Remove old doc for Neo4j Graph View, add new doc for Neo4j Stream Co-Authored-By: Emile van Krieken --- .obsidian/app.json | 4 + .obsidian/appearance.json | 3 + .obsidian/core-plugins.json | 14 + .obsidian/hotkeys.json | 1 + .obsidian/workspace | 102 + Neo4j Graph View settings.md | 0 Neo4j Graph View.md | 0 Neo4j.md | 0 Obsidian.md | 0 Roadmap^.md | 0 .../Edge styling.md | 0 ...Installation of Neo4j Graph View Plugin.md | 0 .../Neo4j Graph View Plugin.md | 0 .../Neo4j graph visualizations.md | 0 .../Node styling.md | 0 .../Semantic Markdown Converter Semantics.md | 0 .../Semantic Markdown Converter.md | 0 .../Semantic Obsidian edge styling.md | 0 .../Semantic Obsidian node styling.md | 0 .../Using the Neo4j Graph View.md | 0 docs/Features/Styling/CSS Styling.md | 4 - .../Install Neo4j Stream Plugin.md | 79 + docs/Neo4j Stream/Neo4j Stream Plugin.md | 19 + .../Neo4j graph visualizations.md | 34 + docs/Neo4j Stream/main.js | 38536 ++++++++++++++++ docs/Neo4j Stream/manifest.json | 10 + docs/Roadmap.md | 4 +- 27 files changed, 38804 insertions(+), 6 deletions(-) create mode 100644 .obsidian/app.json create mode 100644 .obsidian/appearance.json create mode 100644 .obsidian/core-plugins.json create mode 100644 .obsidian/hotkeys.json create mode 100644 .obsidian/workspace create mode 100644 Neo4j Graph View settings.md create mode 100644 Neo4j Graph View.md create mode 100644 Neo4j.md create mode 100644 Obsidian.md create mode 100644 Roadmap^.md rename docs/{Neo4j Graph View => Archieved}/Edge styling.md (100%) rename docs/{Neo4j Graph View => Archieved}/Installation of Neo4j Graph View Plugin.md (100%) rename docs/{Neo4j Graph View => Archieved}/Neo4j Graph View Plugin.md (100%) rename docs/{Neo4j Graph View => Archieved}/Neo4j graph visualizations.md (100%) rename docs/{Neo4j Graph View => Archieved}/Node styling.md (100%) rename docs/{Neo4j Graph View => Archieved}/Semantic Markdown Converter Semantics.md (100%) rename docs/{Neo4j Graph View => Archieved}/Semantic Markdown Converter.md (100%) rename docs/{Neo4j Graph View => Archieved}/Semantic Obsidian edge styling.md (100%) rename docs/{Neo4j Graph View => Archieved}/Semantic Obsidian node styling.md (100%) rename docs/{Neo4j Graph View => Archieved}/Using the Neo4j Graph View.md (100%) create mode 100644 docs/Neo4j Stream/Install Neo4j Stream Plugin.md create mode 100644 docs/Neo4j Stream/Neo4j Stream Plugin.md create mode 100644 docs/Neo4j Stream/Neo4j graph visualizations.md create mode 100644 docs/Neo4j Stream/main.js create mode 100644 docs/Neo4j Stream/manifest.json diff --git a/.obsidian/app.json b/.obsidian/app.json new file mode 100644 index 0000000..4d49ab3 --- /dev/null +++ b/.obsidian/app.json @@ -0,0 +1,4 @@ +{ + "promptDelete": false, + "alwaysUpdateLinks": true +} \ No newline at end of file diff --git a/.obsidian/appearance.json b/.obsidian/appearance.json new file mode 100644 index 0000000..990f337 --- /dev/null +++ b/.obsidian/appearance.json @@ -0,0 +1,3 @@ +{ + "baseFontSize": 16 +} \ No newline at end of file diff --git a/.obsidian/core-plugins.json b/.obsidian/core-plugins.json new file mode 100644 index 0000000..26bc70e --- /dev/null +++ b/.obsidian/core-plugins.json @@ -0,0 +1,14 @@ +[ + "file-explorer", + "global-search", + "switcher", + "graph", + "backlink", + "page-preview", + "note-composer", + "command-palette", + "markdown-importer", + "word-count", + "open-with-default-app", + "file-recovery" +] \ No newline at end of file diff --git a/.obsidian/hotkeys.json b/.obsidian/hotkeys.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/.obsidian/hotkeys.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/.obsidian/workspace b/.obsidian/workspace new file mode 100644 index 0000000..7a717f1 --- /dev/null +++ b/.obsidian/workspace @@ -0,0 +1,102 @@ +{ + "main": { + "id": "d13b041b8342f362", + "type": "split", + "children": [ + { + "id": "f115cb69bdb5c6c8", + "type": "leaf", + "state": { + "type": "markdown", + "state": { + "file": "docs/Neo4j Stream/Install Neo4j Stream Plugin.md", + "mode": "source" + } + } + } + ], + "direction": "vertical" + }, + "left": { + "id": "93bfacddf0364031", + "type": "split", + "children": [ + { + "id": "5b4877b1c8bd0811", + "type": "tabs", + "children": [ + { + "id": "2e5f52a1b8eb32e4", + "type": "leaf", + "state": { + "type": "file-explorer", + "state": {} + } + }, + { + "id": "e4fcc2a575d3634d", + "type": "leaf", + "state": { + "type": "search", + "state": { + "query": "", + "matchingCase": false, + "explainSearch": false, + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical" + } + } + } + ] + } + ], + "direction": "horizontal", + "width": 300 + }, + "right": { + "id": "7f3a0fb38d3bb8d3", + "type": "split", + "children": [ + { + "id": "2bff59fdb21c113b", + "type": "tabs", + "children": [ + { + "id": "8f597588ddd527d6", + "type": "leaf", + "state": { + "type": "backlink", + "state": { + "file": "docs/Neo4j Stream/Install Neo4j Stream Plugin.md", + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical", + "showSearch": false, + "searchQuery": "", + "backlinkCollapsed": false, + "unlinkedCollapsed": true + } + } + } + ] + } + ], + "direction": "horizontal", + "width": 300, + "collapsed": true + }, + "active": "f115cb69bdb5c6c8", + "lastOpenFiles": [ + "docs/Neo4j Stream/Install Neo4j Stream Plugin.md", + "docs/Neo4j Stream/Neo4j graph visualizations.md", + "docs/Neo4j Stream/Neo4j Stream Plugin.md", + "docs/Neo4j Stream/Installation of Neo4j Stream Plugin.md", + "docs/files/Pasted image 20201231181103.png", + "docs/files/Pasted image 20201231180930.png", + "Obsidian.md", + "Neo4j Graph View settings.md", + "docs/files/Pasted image 20201231175530.png", + "docs/Archieved/Installation of Neo4j Graph View Plugin.md" + ] +} \ No newline at end of file diff --git a/Neo4j Graph View settings.md b/Neo4j Graph View settings.md new file mode 100644 index 0000000..e69de29 diff --git a/Neo4j Graph View.md b/Neo4j Graph View.md new file mode 100644 index 0000000..e69de29 diff --git a/Neo4j.md b/Neo4j.md new file mode 100644 index 0000000..e69de29 diff --git a/Obsidian.md b/Obsidian.md new file mode 100644 index 0000000..e69de29 diff --git a/Roadmap^.md b/Roadmap^.md new file mode 100644 index 0000000..e69de29 diff --git a/docs/Neo4j Graph View/Edge styling.md b/docs/Archieved/Edge styling.md similarity index 100% rename from docs/Neo4j Graph View/Edge styling.md rename to docs/Archieved/Edge styling.md diff --git a/docs/Neo4j Graph View/Installation of Neo4j Graph View Plugin.md b/docs/Archieved/Installation of Neo4j Graph View Plugin.md similarity index 100% rename from docs/Neo4j Graph View/Installation of Neo4j Graph View Plugin.md rename to docs/Archieved/Installation of Neo4j Graph View Plugin.md diff --git a/docs/Neo4j Graph View/Neo4j Graph View Plugin.md b/docs/Archieved/Neo4j Graph View Plugin.md similarity index 100% rename from docs/Neo4j Graph View/Neo4j Graph View Plugin.md rename to docs/Archieved/Neo4j Graph View Plugin.md diff --git a/docs/Neo4j Graph View/Neo4j graph visualizations.md b/docs/Archieved/Neo4j graph visualizations.md similarity index 100% rename from docs/Neo4j Graph View/Neo4j graph visualizations.md rename to docs/Archieved/Neo4j graph visualizations.md diff --git a/docs/Neo4j Graph View/Node styling.md b/docs/Archieved/Node styling.md similarity index 100% rename from docs/Neo4j Graph View/Node styling.md rename to docs/Archieved/Node styling.md diff --git a/docs/Neo4j Graph View/Semantic Markdown Converter Semantics.md b/docs/Archieved/Semantic Markdown Converter Semantics.md similarity index 100% rename from docs/Neo4j Graph View/Semantic Markdown Converter Semantics.md rename to docs/Archieved/Semantic Markdown Converter Semantics.md diff --git a/docs/Neo4j Graph View/Semantic Markdown Converter.md b/docs/Archieved/Semantic Markdown Converter.md similarity index 100% rename from docs/Neo4j Graph View/Semantic Markdown Converter.md rename to docs/Archieved/Semantic Markdown Converter.md diff --git a/docs/Neo4j Graph View/Semantic Obsidian edge styling.md b/docs/Archieved/Semantic Obsidian edge styling.md similarity index 100% rename from docs/Neo4j Graph View/Semantic Obsidian edge styling.md rename to docs/Archieved/Semantic Obsidian edge styling.md diff --git a/docs/Neo4j Graph View/Semantic Obsidian node styling.md b/docs/Archieved/Semantic Obsidian node styling.md similarity index 100% rename from docs/Neo4j Graph View/Semantic Obsidian node styling.md rename to docs/Archieved/Semantic Obsidian node styling.md diff --git a/docs/Neo4j Graph View/Using the Neo4j Graph View.md b/docs/Archieved/Using the Neo4j Graph View.md similarity index 100% rename from docs/Neo4j Graph View/Using the Neo4j Graph View.md rename to docs/Archieved/Using the Neo4j Graph View.md diff --git a/docs/Features/Styling/CSS Styling.md b/docs/Features/Styling/CSS Styling.md index e984a8f..37b919a 100644 --- a/docs/Features/Styling/CSS Styling.md +++ b/docs/Features/Styling/CSS Styling.md @@ -153,10 +153,6 @@ edge.inline { ![[Pasted image 20210414182140.png|400]] -# Current limitations -- CSS variables like `var(--background-primary)` will not be recognized. If this is something you need, please add a pull request. -- `not()` does not seem to work. - --- #feature diff --git a/docs/Neo4j Stream/Install Neo4j Stream Plugin.md b/docs/Neo4j Stream/Install Neo4j Stream Plugin.md new file mode 100644 index 0000000..ae8ce85 --- /dev/null +++ b/docs/Neo4j Stream/Install Neo4j Stream Plugin.md @@ -0,0 +1,79 @@ +--- +aliases: [installation, install] +--- +The general steps to install the plugin are as follows: +1. Make sure you have [[Neo4j Desktop]] installed. See [[Install Neo4j Stream Plugin#Install Neo4j Desktop]]. +3. Create a new database in Neo4j desktop and start it. See [[Install Neo4j Stream Plugin#Creating a Neo4j database]]. +5. Install the Obsidian plugin from the Third-party plugins list. See [[Install Neo4j Stream Plugin#Installing the Obsidian plugin]] +6. In the settings of the plugin, enter the password. Then run the restart command. See [[Install Neo4j Stream Plugin#Configuring the Obsidian plugin]]. + +If you are still running into problems after thorougly following these steps, see the [[Install Neo4j Stream Plugin#Troubleshooting]] section. + +## 1. Install Neo4j Desktop +Download [Neo4j desktop](https://neo4j.com/download/). Neo4j wants you to fill a form before giving you the link. Save the Neo4j Desktop Activation Key they provide for later. + +![[Pasted image 20210112215108.png]] + +One user reported the activation key doesn't appear. [According to the Neo4j developers](https://community.neo4j.com/t/installing-and-activation-key/6173), that doesn't actually matter and you can proceed without using a key, curiously. I haven't tried this, though. + +The download can take a while because it's a pretty big file and the servers aren't very quick. + +Installation of Neo4j desktop is pretty straightforward. You have to input the key Neo4j gave you after registration. There's an [installation video](https://www.youtube.com/watch?v=pPhJi9twN9Q&feature=emb_title) if you need more help. + + +## 2. Creating a Neo4j database +In a Project in Neo4j Desktop, click "+ Add Database" under projects: +![[Pasted image 20201231174344.png|300]] + +Then select "Create a Local Database". Next follows this screen: + +![[Pasted image 20201231174425.png|300]] + +You have to set a password here. We're also going to use it in the plugin. Make sure not to choose a sensitive password here! [[Neo4j Stream Plugin]] doesn't store passwords encrypted. You can choose any name. For the Neo4j version, I have tested on 4.2.0, but it should not matter much. + +It'll create your database! Then, click the "Start" button. Note that you have to start your database every time whenever your computer reboots: It needs to remain active while you use the plugin. + +### Possible problems +Every now and then, the Graph database fails to start. +- Sometimes, it just says it 'timed out'. Retrying it a few times may help. +- Port in use: It's unlikely the port is actually in use. Restart Neo4j desktop and try again. It's currently not possible to set a port different than the default port (request on [[Github]] if needed). +- "Could not change the password": This has been reported with a [[Windows]] user. See [this post](https://stackoverflow.com/questions/49342422/neo4j-database-failed-to-create-error-could-not-change-password) for possible guidance. + +## 3. Installing the Obsidian plugin +Time to install the plugin! Since Neo4j Stream is unfinished, you will have to download and install it manually. + +1. Download the plugin from [this link](https://github.com/HEmile/obsidian-neo4j-graph-view/releases/tag/0.2.5). +1. Open the Obsidian settings, and go to Third-party plugins. Disable the "Safe mode" toggle, then click "Turn off safe mode" to confirm this. +2. Now, more options appear. Click on the "open plugin folders" icon +3. In the resulting folder, create a new directory called `neo4j-stream` +4. Extract the downloaded file into this folder. +5. Close the current screen. In the Third-party plugins settings, enable Neo4j Stream with the slider. + +## 4. Configuring Neo4j Stream +We need to do one more thing before we can get playing with the plugin: Setting the password. +1. Go to the Neo4j Stream settings, which has appeared under Plugin options in the Obsidian settings. +2. In the password field, input the password you set during [[Install Neo4j Stream Plugin#Creating a Neo4j database]]. ![[Pasted image 20201231180930.png]] +3. Close the settings view. +4. Run the Obsidian command: "Neo4j Graph View: Restart Neo4j stream". You can run a command by using ctrl/cmd + p. ![[Pasted image 20201231181003.png]] +5. The plugin is succesfully installed if the following notice appears in the top-right corner: ![[Pasted image 20201231181103.png|300]] (note: for some reason, it doesn't always appear even though the server did properly start...) + +If a different notice appears, something went wrong. Let's try to figure out what! + +## Troubleshooting +If a notice appears that doesn't say the Neo4j stream is online, something went wrong. Two simple notices are +- "Please provide a password in the Neo4j Stream settings": This means your user credentials weren't accepted by the Neo4j database. Check if the password is set correctly during [[Install Neo4j Stream Plugin#Configuring the Obsidian plugin]]. +- "No connection to Neo4j database. Please start Neo4j Database in Neo4j Desktop": This means there's no connection to a Neo4j database on port 7687. Check Neo4j desktop if the database is online. + +The third notice is scariest: "Error during initialization of the Neo4j stream. Check the console for crash report.". Here are some steps to help figure out how to resolve this: +1. Enable "Debug" mode in the Neo4j Stream settings ![[Pasted image 20201231181917.png]] +2. Open the Developer Tools. This option is under the View menu. If the View menu doesn't show, the keyboard shortcut to open it is Ctrl+Shift+I on windows and Option+Cmd+I on mac. +3. Look at the error in the Console. + +Otherwise, it's likely that there's some bug in the plugin in that it cannot handle something that's present in your vault. Since this version is unfinished, you will have to fork the plugin to fix this. + +You can also contact [[Emile van Krieken|me]] on Twitter, Github or [[Discord]] if you need help. + +--- +#howto +- hasTopic [[Neo4j Graph View]] +- author [[Emile van Krieken]] \ No newline at end of file diff --git a/docs/Neo4j Stream/Neo4j Stream Plugin.md b/docs/Neo4j Stream/Neo4j Stream Plugin.md new file mode 100644 index 0000000..368a129 --- /dev/null +++ b/docs/Neo4j Stream/Neo4j Stream Plugin.md @@ -0,0 +1,19 @@ +This plugin helps streaming your vault to a [Neo4j](https://neo4j.com/) database. This is a separate plugin to ensure non-advanced users of [[Juggl]] will not have to deal with installing Neo4j, and is completely optional for advanced users. + +⚠ Note: This is an unfinshed pluggin. Absolutely no guarantees that this works. + +Please refer to [[Install Neo4j Stream Plugin]] and [[Neo4j graph visualizations]] for more information + +## Development +[[Roadmap]]: [[Roadmap#^2d1fd7]] + +Contributions are very much welcomed. The easiest way to get started is to join the [[Discord]] server! See [[Contributing]] for an overview of ways you can help. + +[HEmile/obsidian-neo4j-stream](https://github.com/HEmile/obsidian-neo4j-stream "HEmile/obsidian-neo4j-stream") + +--- +#plugin +- hasTopic [[Neo4j]] +- hasTopic [[Obsidian]] + + diff --git a/docs/Neo4j Stream/Neo4j graph visualizations.md b/docs/Neo4j Stream/Neo4j graph visualizations.md new file mode 100644 index 0000000..0326c0b --- /dev/null +++ b/docs/Neo4j Stream/Neo4j graph visualizations.md @@ -0,0 +1,34 @@ +--- +aliases: [] +--- + +Another use case for the [[Neo4j Stream Plugin]] is to use your Obsidian vault in one of the many apps in the [[Neo4j Desktop]] +Graph Apps Store. Using with this plugin active will automatically connect it to your vault. Here are some suggestions: + +### Neo4j Bloom +[Neo4j Bloom](https://neo4j.com/product/bloom/) is very powerful graph visualization software. Compared to the embedded +graph view in Obsidian, it offers much more freedom in customization. + +![[bloom_screenshot.jpg]] + + +### GraphXR +[GraphXR](https://www.kineviz.com/) is a 3D graph view, which looks quite gorgeous! + +![[graphxr.gif]] + + +### Neo4j Browser +A query browser that uses the [[Cypher]] language to query your vault. Can be used for advanced queries or data anlysis of your vault. + +![[browser_screenshot.png]] + +### Gephi +Neo4j can export to the graph visualization software [[Gephi]]. See the [Neo4j document](https://neo4j.com/labs/apoc/4.1/export/gephi/) for help on how to do this. Note that it requires installing the "APOC" plugin to your Neo4j Graph Database. + + + +--- +#topic +- hasTopic [[Neo4j]], [[Neo4j Stream Plugin]] +- author [[Emile van Krieken]] \ No newline at end of file diff --git a/docs/Neo4j Stream/main.js b/docs/Neo4j Stream/main.js new file mode 100644 index 0000000..8f15d3f --- /dev/null +++ b/docs/Neo4j Stream/main.js @@ -0,0 +1,38536 @@ +'use strict'; + +var obsidian = require('obsidian'); +var require$$6 = require('buffer'); +var require$$2 = require('net'); +var require$$3 = require('tls'); +var require$$4 = require('fs'); +var require$$6$1 = require('dns'); +var _string_decoder = require('string_decoder'); +var path = require('path'); + +function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + +var require$$6__default = /*#__PURE__*/_interopDefaultLegacy(require$$6); +var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); +var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3); +var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4); +var require$$6__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$6$1); +var _string_decoder__default = /*#__PURE__*/_interopDefaultLegacy(_string_decoder); + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function getAugmentedNamespace(n) { + if (n.__esModule) return n; + var a = Object.defineProperty({}, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +function createCommonjsModule(fn) { + var module = { exports: {} }; + return fn(module, module.exports), module.exports; +} + +/** Detect free variable `global` from Node.js. */ + +var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + +var _freeGlobal = freeGlobal; + +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + +/** Used as a reference to the global object. */ +var root = _freeGlobal || freeSelf || Function('return this')(); + +var _root = root; + +/** Built-in value references. */ +var Symbol$1 = _root.Symbol; + +var _Symbol = Symbol$1; + +/** Used for built-in method references. */ +var objectProto = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; + +/** Built-in value references. */ +var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; + +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; +} + +var _getRawTag = getRawTag; + +/** Used for built-in method references. */ +var objectProto$1 = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString$1 = objectProto$1.toString; + +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString$1.call(value); +} + +var _objectToString = objectToString; + +/** `Object#toString` result references. */ +var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; + +/** Built-in value references. */ +var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; + } + return (symToStringTag$1 && symToStringTag$1 in Object(value)) + ? _getRawTag(value) + : _objectToString(value); +} + +var _baseGetTag = baseGetTag; + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +var isObject_1 = isObject; + +/** `Object#toString` result references. */ +var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject_1(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = _baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; +} + +var isFunction_1 = isFunction; + +/** Used to detect overreaching core-js shims. */ +var coreJsData = _root['__core-js_shared__']; + +var _coreJsData = coreJsData; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +var _isMasked = isMasked; + +/** Used for built-in method references. */ +var funcProto = Function.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +var _toSource = toSource; + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used for built-in method references. */ +var funcProto$1 = Function.prototype, + objectProto$2 = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString$1 = funcProto$1.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty$1 = objectProto$2.hasOwnProperty; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject_1(value) || _isMasked(value)) { + return false; + } + var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; + return pattern.test(_toSource(value)); +} + +var _baseIsNative = baseIsNative; + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +var _getValue = getValue; + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = _getValue(object, key); + return _baseIsNative(value) ? value : undefined; +} + +var _getNative = getNative; + +var defineProperty = (function() { + try { + var func = _getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} +}()); + +var _defineProperty = defineProperty; + +/** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function baseAssignValue(object, key, value) { + if (key == '__proto__' && _defineProperty) { + _defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } +} + +var _baseAssignValue = baseAssignValue; + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +var eq_1 = eq; + +/** Used for built-in method references. */ +var objectProto$3 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$2 = objectProto$3.hasOwnProperty; + +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty$2.call(object, key) && eq_1(objValue, value)) || + (value === undefined && !(key in object))) { + _baseAssignValue(object, key, value); + } +} + +var _assignValue = assignValue; + +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + _baseAssignValue(object, key, newValue); + } else { + _assignValue(object, key, newValue); + } + } + return object; +} + +var _copyObject = copyObject; + +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; +} + +var identity_1 = identity; + +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +var _apply = apply; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; + +/** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ +function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return _apply(func, this, otherArgs); + }; +} + +var _overRest = overRest; + +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ +function constant(value) { + return function() { + return value; + }; +} + +var constant_1 = constant; + +/** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var baseSetToString = !_defineProperty ? identity_1 : function(func, string) { + return _defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant_1(string), + 'writable': true + }); +}; + +var _baseSetToString = baseSetToString; + +/** Used to detect hot functions by number of calls within a span of milliseconds. */ +var HOT_COUNT = 800, + HOT_SPAN = 16; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeNow = Date.now; + +/** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ +function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; +} + +var _shortOut = shortOut; + +/** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var setToString = _shortOut(_baseSetToString); + +var _setToString = setToString; + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + return _setToString(_overRest(func, start, identity_1), func + ''); +} + +var _baseRest = baseRest; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} + +var isLength_1 = isLength; + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength_1(value.length) && !isFunction_1(value); +} + +var isArrayLike_1 = isArrayLike; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER$1 = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER$1 : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); +} + +var _isIndex = isIndex; + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject_1(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike_1(object) && _isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq_1(object[index], value); + } + return false; +} + +var _isIterateeCall = isIterateeCall; + +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner(assigner) { + return _baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && _isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} + +var _createAssigner = createAssigner; + +/** Used for built-in method references. */ +var objectProto$4 = Object.prototype; + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$4; + + return value === proto; +} + +var _isPrototype = isPrototype; + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +var _baseTimes = baseTimes; + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +var isObjectLike_1 = isObjectLike; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike_1(value) && _baseGetTag(value) == argsTag; +} + +var _baseIsArguments = baseIsArguments; + +/** Used for built-in method references. */ +var objectProto$5 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$3 = objectProto$5.hasOwnProperty; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto$5.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { + return isObjectLike_1(value) && hasOwnProperty$3.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; + +var isArguments_1 = isArguments; + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +var isArray_1 = isArray; + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +var stubFalse_1 = stubFalse; + +var isBuffer_1 = createCommonjsModule(function (module, exports) { +/** Detect free variable `exports`. */ +var freeExports = exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Built-in value references. */ +var Buffer = moduleExports ? _root.Buffer : undefined; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse_1; + +module.exports = isBuffer; +}); + +/** `Object#toString` result references. */ +var argsTag$1 = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag$1 = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike_1(value) && + isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; +} + +var _baseIsTypedArray = baseIsTypedArray; + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + +var _baseUnary = baseUnary; + +var _nodeUtil = createCommonjsModule(function (module, exports) { +/** Detect free variable `exports`. */ +var freeExports = exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports && _freeGlobal.process; + +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); + +module.exports = nodeUtil; +}); + +/* Node.js helper references. */ +var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; + +var isTypedArray_1 = isTypedArray; + +/** Used for built-in method references. */ +var objectProto$6 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$4 = objectProto$6.hasOwnProperty; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray_1(value), + isArg = !isArr && isArguments_1(value), + isBuff = !isArr && !isArg && isBuffer_1(value), + isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? _baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$4.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + _isIndex(key, length) + ))) { + result.push(key); + } + } + return result; +} + +var _arrayLikeKeys = arrayLikeKeys; + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +var _overArg = overArg; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = _overArg(Object.keys, Object); + +var _nativeKeys = nativeKeys; + +/** Used for built-in method references. */ +var objectProto$7 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$5 = objectProto$7.hasOwnProperty; + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!_isPrototype(object)) { + return _nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$5.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +var _baseKeys = baseKeys; + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); +} + +var keys_1 = keys; + +/** Used for built-in method references. */ +var objectProto$8 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$6 = objectProto$8.hasOwnProperty; + +/** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ +var assign = _createAssigner(function(object, source) { + if (_isPrototype(source) || isArrayLike_1(source)) { + _copyObject(source, keys_1(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty$6.call(source, key)) { + _assignValue(object, key, source[key]); + } + } +}); + +var assign_1 = assign; + +/*! ***************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; + return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (_) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +/** @deprecated */ +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +var _arrayMap = arrayMap; + +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike_1(value) && _baseGetTag(value) == symbolTag); +} + +var isSymbol_1 = isSymbol; + +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = _Symbol ? _Symbol.prototype : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray_1(value)) { + // Recursively convert values (susceptible to call stack limits). + return _arrayMap(value, baseToString) + ''; + } + if (isSymbol_1(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; +} + +var _baseToString = baseToString; + +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; +} + +var _baseSlice = baseSlice; + +/** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ +function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : _baseSlice(array, start, end); +} + +var _castSlice = castSlice; + +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; +} + +var _baseFindIndex = baseFindIndex; + +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} + +var _baseIsNaN = baseIsNaN; + +/** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +var _strictIndexOf = strictIndexOf; + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + return value === value + ? _strictIndexOf(array, value, fromIndex) + : _baseFindIndex(array, _baseIsNaN, fromIndex); +} + +var _baseIndexOf = baseIndexOf; + +/** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ +function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + + while (index-- && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +var _charsEndIndex = charsEndIndex; + +/** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ +function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; +} + +var _charsStartIndex = charsStartIndex; + +/** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function asciiToArray(string) { + return string.split(''); +} + +var _asciiToArray = asciiToArray; + +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsVarRange = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsZWJ = '\\u200d'; + +/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ +var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + +/** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ +function hasUnicode(string) { + return reHasUnicode.test(string); +} + +var _hasUnicode = hasUnicode; + +/** Used to compose unicode character classes. */ +var rsAstralRange$1 = '\\ud800-\\udfff', + rsComboMarksRange$1 = '\\u0300-\\u036f', + reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', + rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', + rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, + rsVarRange$1 = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsAstral = '[' + rsAstralRange$1 + ']', + rsCombo = '[' + rsComboRange$1 + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange$1 + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsZWJ$1 = '\\u200d'; + +/** Used to compose unicode regexes. */ +var reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange$1 + ']?', + rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + +/** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function unicodeToArray(string) { + return string.match(reUnicode) || []; +} + +var _unicodeToArray = unicodeToArray; + +/** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function stringToArray(string) { + return _hasUnicode(string) + ? _unicodeToArray(string) + : _asciiToArray(string); +} + +var _stringToArray = stringToArray; + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString(value) { + return value == null ? '' : _baseToString(value); +} + +var toString_1 = toString; + +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; + +/** + * Removes leading and trailing whitespace or specified characters from `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to trim. + * @param {string} [chars=whitespace] The characters to trim. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the trimmed string. + * @example + * + * _.trim(' abc '); + * // => 'abc' + * + * _.trim('-_-abc-_-', '_-'); + * // => 'abc' + * + * _.map([' foo ', ' bar '], _.trim); + * // => ['foo', 'bar'] + */ +function trim(string, chars, guard) { + string = toString_1(string); + if (string && (guard || chars === undefined)) { + return string.replace(reTrim, ''); + } + if (!string || !(chars = _baseToString(chars))) { + return string; + } + var strSymbols = _stringToArray(string), + chrSymbols = _stringToArray(chars), + start = _charsStartIndex(strSymbols, chrSymbols), + end = _charsEndIndex(strSymbols, chrSymbols) + 1; + + return _castSlice(strSymbols, start, end).join(''); +} + +var trim_1 = trim; + +/** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ +function isNil(value) { + return value == null; +} + +var isNil_1 = isNil; + +/** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ +function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray_1(value) ? value : [value]; +} + +var castArray_1 = castArray; + +/** `Object#toString` result references. */ +var stringTag$1 = '[object String]'; + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$1); +} + +var isString_1 = isString; + +/* Built-in method references that are verified to be native. */ +var DataView = _getNative(_root, 'DataView'); + +var _DataView = DataView; + +/* Built-in method references that are verified to be native. */ +var Map$1 = _getNative(_root, 'Map'); + +var _Map = Map$1; + +/* Built-in method references that are verified to be native. */ +var Promise$1 = _getNative(_root, 'Promise'); + +var _Promise = Promise$1; + +/* Built-in method references that are verified to be native. */ +var Set$1 = _getNative(_root, 'Set'); + +var _Set = Set$1; + +/* Built-in method references that are verified to be native. */ +var WeakMap$1 = _getNative(_root, 'WeakMap'); + +var _WeakMap = WeakMap$1; + +/** `Object#toString` result references. */ +var mapTag$1 = '[object Map]', + objectTag$1 = '[object Object]', + promiseTag = '[object Promise]', + setTag$1 = '[object Set]', + weakMapTag$1 = '[object WeakMap]'; + +var dataViewTag$1 = '[object DataView]'; + +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = _toSource(_DataView), + mapCtorString = _toSource(_Map), + promiseCtorString = _toSource(_Promise), + setCtorString = _toSource(_Set), + weakMapCtorString = _toSource(_WeakMap); + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = _baseGetTag; + +// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. +if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$1) || + (_Map && getTag(new _Map) != mapTag$1) || + (_Promise && getTag(_Promise.resolve()) != promiseTag) || + (_Set && getTag(new _Set) != setTag$1) || + (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) { + getTag = function(value) { + var result = _baseGetTag(value), + Ctor = result == objectTag$1 ? value.constructor : undefined, + ctorString = Ctor ? _toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag$1; + case mapCtorString: return mapTag$1; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag$1; + case weakMapCtorString: return weakMapTag$1; + } + } + return result; + }; +} + +var _getTag = getTag; + +/** `Object#toString` result references. */ +var mapTag$2 = '[object Map]', + setTag$2 = '[object Set]'; + +/** Used for built-in method references. */ +var objectProto$9 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$7 = objectProto$9.hasOwnProperty; + +/** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ +function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike_1(value) && + (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) { + return !value.length; + } + var tag = _getTag(value); + if (tag == mapTag$2 || tag == setTag$2) { + return !value.size; + } + if (_isPrototype(value)) { + return !_baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty$7.call(value, key)) { + return false; + } + } + return true; +} + +var isEmpty_1 = isEmpty; + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} + +var _listCacheClear = listCacheClear; + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq_1(array[length][0], key)) { + return length; + } + } + return -1; +} + +var _assocIndexOf = assocIndexOf; + +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto.splice; + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = _assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; +} + +var _listCacheDelete = listCacheDelete; + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = _assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +var _listCacheGet = listCacheGet; + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return _assocIndexOf(this.__data__, key) > -1; +} + +var _listCacheHas = listCacheHas; + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = _assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +var _listCacheSet = listCacheSet; + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = _listCacheClear; +ListCache.prototype['delete'] = _listCacheDelete; +ListCache.prototype.get = _listCacheGet; +ListCache.prototype.has = _listCacheHas; +ListCache.prototype.set = _listCacheSet; + +var _ListCache = ListCache; + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new _ListCache; + this.size = 0; +} + +var _stackClear = stackClear; + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; +} + +var _stackDelete = stackDelete; + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +var _stackGet = stackGet; + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +var _stackHas = stackHas; + +/* Built-in method references that are verified to be native. */ +var nativeCreate = _getNative(Object, 'create'); + +var _nativeCreate = nativeCreate; + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; + this.size = 0; +} + +var _hashClear = hashClear; + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +var _hashDelete = hashDelete; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** Used for built-in method references. */ +var objectProto$a = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$8 = objectProto$a.hasOwnProperty; + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (_nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty$8.call(data, key) ? data[key] : undefined; +} + +var _hashGet = hashGet; + +/** Used for built-in method references. */ +var objectProto$b = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$9 = objectProto$b.hasOwnProperty; + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$9.call(data, key); +} + +var _hashHas = hashHas; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; + return this; +} + +var _hashSet = hashSet; + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `Hash`. +Hash.prototype.clear = _hashClear; +Hash.prototype['delete'] = _hashDelete; +Hash.prototype.get = _hashGet; +Hash.prototype.has = _hashHas; +Hash.prototype.set = _hashSet; + +var _Hash = Hash; + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new _Hash, + 'map': new (_Map || _ListCache), + 'string': new _Hash + }; +} + +var _mapCacheClear = mapCacheClear; + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +var _isKeyable = isKeyable; + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return _isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +var _getMapData = getMapData; + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = _getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +var _mapCacheDelete = mapCacheDelete; + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return _getMapData(this, key).get(key); +} + +var _mapCacheGet = mapCacheGet; + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return _getMapData(this, key).has(key); +} + +var _mapCacheHas = mapCacheHas; + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = _getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +var _mapCacheSet = mapCacheSet; + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = _mapCacheClear; +MapCache.prototype['delete'] = _mapCacheDelete; +MapCache.prototype.get = _mapCacheGet; +MapCache.prototype.has = _mapCacheHas; +MapCache.prototype.set = _mapCacheSet; + +var _MapCache = MapCache; + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var data = this.__data__; + if (data instanceof _ListCache) { + var pairs = data.__data__; + if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new _MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} + +var _stackSet = stackSet; + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + var data = this.__data__ = new _ListCache(entries); + this.size = data.size; +} + +// Add methods to `Stack`. +Stack.prototype.clear = _stackClear; +Stack.prototype['delete'] = _stackDelete; +Stack.prototype.get = _stackGet; +Stack.prototype.has = _stackHas; +Stack.prototype.set = _stackSet; + +var _Stack = Stack; + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; + +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED$2); + return this; +} + +var _setCacheAdd = setCacheAdd; + +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} + +var _setCacheHas = setCacheHas; + +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new _MapCache; + while (++index < length) { + this.add(values[index]); + } +} + +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; +SetCache.prototype.has = _setCacheHas; + +var _SetCache = SetCache; + +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; +} + +var _arraySome = arraySome; + +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} + +var _cacheHas = cacheHas; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!_arraySome(other, function(othValue, othIndex) { + if (!_cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; +} + +var _equalArrays = equalArrays; + +/** Built-in value references. */ +var Uint8Array = _root.Uint8Array; + +var _Uint8Array = Uint8Array; + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +var _mapToArray = mapToArray; + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +var _setToArray = setToArray; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$1 = 1, + COMPARE_UNORDERED_FLAG$1 = 2; + +/** `Object#toString` result references. */ +var boolTag$1 = '[object Boolean]', + dateTag$1 = '[object Date]', + errorTag$1 = '[object Error]', + mapTag$3 = '[object Map]', + numberTag$1 = '[object Number]', + regexpTag$1 = '[object RegExp]', + setTag$3 = '[object Set]', + stringTag$2 = '[object String]', + symbolTag$1 = '[object Symbol]'; + +var arrayBufferTag$1 = '[object ArrayBuffer]', + dataViewTag$2 = '[object DataView]'; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined, + symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; + +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag$2: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag$1: + if ((object.byteLength != other.byteLength) || + !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { + return false; + } + return true; + + case boolTag$1: + case dateTag$1: + case numberTag$1: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq_1(+object, +other); + + case errorTag$1: + return object.name == other.name && object.message == other.message; + + case regexpTag$1: + case stringTag$2: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag$3: + var convert = _mapToArray; + + case setTag$3: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; + convert || (convert = _setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG$1; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag$1: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; +} + +var _equalByTag = equalByTag; + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +var _arrayPush = arrayPush; + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); +} + +var _baseGetAllKeys = baseGetAllKeys; + +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; +} + +var _arrayFilter = arrayFilter; + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ +function stubArray() { + return []; +} + +var stubArray_1 = stubArray; + +/** Used for built-in method references. */ +var objectProto$c = Object.prototype; + +/** Built-in value references. */ +var propertyIsEnumerable$1 = objectProto$c.propertyIsEnumerable; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols; + +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return _arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable$1.call(object, symbol); + }); +}; + +var _getSymbols = getSymbols; + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys(object) { + return _baseGetAllKeys(object, keys_1, _getSymbols); +} + +var _getAllKeys = getAllKeys; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$2 = 1; + +/** Used for built-in method references. */ +var objectProto$d = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$a = objectProto$d.hasOwnProperty; + +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, + objProps = _getAllKeys(object), + objLength = objProps.length, + othProps = _getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty$a.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; +} + +var _equalObjects = equalObjects; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$3 = 1; + +/** `Object#toString` result references. */ +var argsTag$2 = '[object Arguments]', + arrayTag$1 = '[object Array]', + objectTag$2 = '[object Object]'; + +/** Used for built-in method references. */ +var objectProto$e = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$b = objectProto$e.hasOwnProperty; + +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray_1(object), + othIsArr = isArray_1(other), + objTag = objIsArr ? arrayTag$1 : _getTag(object), + othTag = othIsArr ? arrayTag$1 : _getTag(other); + + objTag = objTag == argsTag$2 ? objectTag$2 : objTag; + othTag = othTag == argsTag$2 ? objectTag$2 : othTag; + + var objIsObj = objTag == objectTag$2, + othIsObj = othTag == objectTag$2, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer_1(object)) { + if (!isBuffer_1(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new _Stack); + return (objIsArr || isTypedArray_1(object)) + ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { + var objIsWrapped = objIsObj && hasOwnProperty$b.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty$b.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new _Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new _Stack); + return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} + +var _baseIsEqualDeep = baseIsEqualDeep; + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { + return value !== value && other !== other; + } + return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); +} + +var _baseIsEqual = baseIsEqual; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$4 = 1, + COMPARE_UNORDERED_FLAG$2 = 2; + +/** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ +function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new _Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) + : result + )) { + return false; + } + } + } + return true; +} + +var _baseIsMatch = baseIsMatch; + +/** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ +function isStrictComparable(value) { + return value === value && !isObject_1(value); +} + +var _isStrictComparable = isStrictComparable; + +/** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ +function getMatchData(object) { + var result = keys_1(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, _isStrictComparable(value)]; + } + return result; +} + +var _getMatchData = getMatchData; + +/** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; +} + +var _matchesStrictComparable = matchesStrictComparable; + +/** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatches(source) { + var matchData = _getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return _matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || _baseIsMatch(object, source, matchData); + }; +} + +var _baseMatches = baseMatches; + +/** Used to match property names within property paths. */ +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ +function isKey(value, object) { + if (isArray_1(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol_1(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +} + +var _isKey = isKey; + +/** Error message constants. */ +var FUNC_ERROR_TEXT = 'Expected a function'; + +/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ +function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || _MapCache); + return memoized; +} + +// Expose `MapCache`. +memoize.Cache = _MapCache; + +var memoize_1 = memoize; + +/** Used as the maximum memoize cache size. */ +var MAX_MEMOIZE_SIZE = 500; + +/** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ +function memoizeCapped(func) { + var result = memoize_1(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; +} + +var _memoizeCapped = memoizeCapped; + +/** Used to match property names within property paths. */ +var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + +/** Used to match backslashes in property paths. */ +var reEscapeChar = /\\(\\)?/g; + +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ +var stringToPath = _memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; +}); + +var _stringToPath = stringToPath; + +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ +function castPath(value, object) { + if (isArray_1(value)) { + return value; + } + return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); +} + +var _castPath = castPath; + +/** Used as references for various `Number` constants. */ +var INFINITY$1 = 1 / 0; + +/** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ +function toKey(value) { + if (typeof value == 'string' || isSymbol_1(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; +} + +var _toKey = toKey; + +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ +function baseGet(object, path) { + path = _castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[_toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; +} + +var _baseGet = baseGet; + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ +function get(object, path, defaultValue) { + var result = object == null ? undefined : _baseGet(object, path); + return result === undefined ? defaultValue : result; +} + +var get_1 = get; + +/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHasIn(object, key) { + return object != null && key in Object(object); +} + +var _baseHasIn = baseHasIn; + +/** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ +function hasPath(object, path, hasFunc) { + path = _castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = _toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength_1(length) && _isIndex(key, length) && + (isArray_1(object) || isArguments_1(object)); +} + +var _hasPath = hasPath; + +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ +function hasIn(object, path) { + return object != null && _hasPath(object, path, _baseHasIn); +} + +var hasIn_1 = hasIn; + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$5 = 1, + COMPARE_UNORDERED_FLAG$3 = 2; + +/** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatchesProperty(path, srcValue) { + if (_isKey(path) && _isStrictComparable(srcValue)) { + return _matchesStrictComparable(_toKey(path), srcValue); + } + return function(object) { + var objValue = get_1(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn_1(object, path) + : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); + }; +} + +var _baseMatchesProperty = baseMatchesProperty; + +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; +} + +var _baseProperty = baseProperty; + +/** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyDeep(path) { + return function(object) { + return _baseGet(object, path); + }; +} + +var _basePropertyDeep = basePropertyDeep; + +/** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ +function property(path) { + return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); +} + +var property_1 = property; + +/** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ +function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity_1; + } + if (typeof value == 'object') { + return isArray_1(value) + ? _baseMatchesProperty(value[0], value[1]) + : _baseMatches(value); + } + return property_1(value); +} + +var _baseIteratee = baseIteratee; + +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} + +var _createBaseFor = createBaseFor; + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor = _createBaseFor(); + +var _baseFor = baseFor; + +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwn(object, iteratee) { + return object && _baseFor(object, iteratee, keys_1); +} + +var _baseForOwn = baseForOwn; + +/** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike_1(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; +} + +var _createBaseEach = createBaseEach; + +/** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ +var baseEach = _createBaseEach(_baseForOwn); + +var _baseEach = baseEach; + +/** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike_1(collection) ? Array(collection.length) : []; + + _baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; +} + +var _baseMap = baseMap; + +/** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ +function map(collection, iteratee) { + var func = isArray_1(collection) ? _arrayMap : _baseMap; + return func(collection, _baseIteratee(iteratee)); +} + +var map_1 = map; + +/** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ +function mapValues(object, iteratee) { + var result = {}; + iteratee = _baseIteratee(iteratee); + + _baseForOwn(object, function(value, key, object) { + _baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; +} + +var mapValues_1 = mapValues; + +/** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; +} + +var _arrayReduce = arrayReduce; + +/** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ +function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; +} + +var _baseReduce = baseReduce; + +/** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ +function reduce(collection, iteratee, accumulator) { + var func = isArray_1(collection) ? _arrayReduce : _baseReduce, + initAccum = arguments.length < 3; + + return func(collection, _baseIteratee(iteratee), accumulator, initAccum, _baseEach); +} + +var reduce_1 = reduce; + +/** `Object#toString` result references. */ +var numberTag$2 = '[object Number]'; + +/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber(value) { + return typeof value == 'number' || + (isObjectLike_1(value) && _baseGetTag(value) == numberTag$2); +} + +var isNumber_1 = isNumber; + +/** `Object#toString` result references. */ +var boolTag$2 = '[object Boolean]'; + +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean(value) { + return value === true || value === false || + (isObjectLike_1(value) && _baseGetTag(value) == boolTag$2); +} + +var isBoolean_1 = isBoolean; + +/** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ +function createCaseFirst(methodName) { + return function(string) { + string = toString_1(string); + + var strSymbols = _hasUnicode(string) + ? _stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? _castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; +} + +var _createCaseFirst = createCaseFirst; + +/** + * Converts the first character of `string` to upper case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.upperFirst('fred'); + * // => 'Fred' + * + * _.upperFirst('FRED'); + * // => 'FRED' + */ +var upperFirst = _createCaseFirst('toUpperCase'); + +var upperFirst_1 = upperFirst; + +/** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ +function capitalize(string) { + return upperFirst_1(toString_1(string).toLowerCase()); +} + +var capitalize_1 = capitalize; + +/** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; +} + +var _basePropertyOf = basePropertyOf; + +/** Used to map Latin Unicode letters to basic Latin letters. */ +var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' +}; + +/** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ +var deburrLetter = _basePropertyOf(deburredLetters); + +var _deburrLetter = deburrLetter; + +/** Used to match Latin Unicode letters (excluding mathematical operators). */ +var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + +/** Used to compose unicode character classes. */ +var rsComboMarksRange$2 = '\\u0300-\\u036f', + reComboHalfMarksRange$2 = '\\ufe20-\\ufe2f', + rsComboSymbolsRange$2 = '\\u20d0-\\u20ff', + rsComboRange$2 = rsComboMarksRange$2 + reComboHalfMarksRange$2 + rsComboSymbolsRange$2; + +/** Used to compose unicode capture groups. */ +var rsCombo$1 = '[' + rsComboRange$2 + ']'; + +/** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ +var reComboMark = RegExp(rsCombo$1, 'g'); + +/** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ +function deburr(string) { + string = toString_1(string); + return string && string.replace(reLatin, _deburrLetter).replace(reComboMark, ''); +} + +var deburr_1 = deburr; + +/** Used to match words composed of alphanumeric characters. */ +var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + +/** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function asciiWords(string) { + return string.match(reAsciiWord) || []; +} + +var _asciiWords = asciiWords; + +/** Used to detect strings that need a more robust regexp to match words. */ +var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + +/** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ +function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); +} + +var _hasUnicodeWord = hasUnicodeWord; + +/** Used to compose unicode character classes. */ +var rsAstralRange$2 = '\\ud800-\\udfff', + rsComboMarksRange$3 = '\\u0300-\\u036f', + reComboHalfMarksRange$3 = '\\ufe20-\\ufe2f', + rsComboSymbolsRange$3 = '\\u20d0-\\u20ff', + rsComboRange$3 = rsComboMarksRange$3 + reComboHalfMarksRange$3 + rsComboSymbolsRange$3, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange$2 = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + +/** Used to compose unicode capture groups. */ +var rsApos = "['\u2019]", + rsBreak = '[' + rsBreakRange + ']', + rsCombo$2 = '[' + rsComboRange$3 + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange$2 + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz$1 = '\\ud83c[\\udffb-\\udfff]', + rsModifier$1 = '(?:' + rsCombo$2 + '|' + rsFitz$1 + ')', + rsNonAstral$1 = '[^' + rsAstralRange$2 + ']', + rsRegional$1 = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair$1 = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ$2 = '\\u200d'; + +/** Used to compose unicode regexes. */ +var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod$1 = rsModifier$1 + '?', + rsOptVar$1 = '[' + rsVarRange$2 + ']?', + rsOptJoin$1 = '(?:' + rsZWJ$2 + '(?:' + [rsNonAstral$1, rsRegional$1, rsSurrPair$1].join('|') + ')' + rsOptVar$1 + reOptMod$1 + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq$1 = rsOptVar$1 + reOptMod$1 + rsOptJoin$1, + rsEmoji = '(?:' + [rsDingbat, rsRegional$1, rsSurrPair$1].join('|') + ')' + rsSeq$1; + +/** Used to match complex or compound words. */ +var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji +].join('|'), 'g'); + +/** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function unicodeWords(string) { + return string.match(reUnicodeWord) || []; +} + +var _unicodeWords = unicodeWords; + +/** + * Splits `string` into an array of its words. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {RegExp|string} [pattern] The pattern to match words. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the words of `string`. + * @example + * + * _.words('fred, barney, & pebbles'); + * // => ['fred', 'barney', 'pebbles'] + * + * _.words('fred, barney, & pebbles', /[^, ]+/g); + * // => ['fred', 'barney', '&', 'pebbles'] + */ +function words(string, pattern, guard) { + string = toString_1(string); + pattern = guard ? undefined : pattern; + + if (pattern === undefined) { + return _hasUnicodeWord(string) ? _unicodeWords(string) : _asciiWords(string); + } + return string.match(pattern) || []; +} + +var words_1 = words; + +/** Used to compose unicode capture groups. */ +var rsApos$1 = "['\u2019]"; + +/** Used to match apostrophes. */ +var reApos = RegExp(rsApos$1, 'g'); + +/** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ +function createCompounder(callback) { + return function(string) { + return _arrayReduce(words_1(deburr_1(string).replace(reApos, '')), callback, ''); + }; +} + +var _createCompounder = createCompounder; + +/** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ +var camelCase = _createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize_1(word) : word); +}); + +var camelCase_1 = camelCase; + +/** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ +function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; +} + +var _arrayEvery = arrayEvery; + +/** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ +function baseEvery(collection, predicate) { + var result = true; + _baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; +} + +var _baseEvery = baseEvery; + +/** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ +function every(collection, predicate, guard) { + var func = isArray_1(collection) ? _arrayEvery : _baseEvery; + if (guard && _isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, _baseIteratee(predicate)); +} + +var every_1 = every; + +/** Built-in value references. */ +var getPrototype = _overArg(Object.getPrototypeOf, Object); + +var _getPrototype = getPrototype; + +/** `Object#toString` result references. */ +var objectTag$3 = '[object Object]'; + +/** Used for built-in method references. */ +var funcProto$2 = Function.prototype, + objectProto$f = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString$2 = funcProto$2.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty$c = objectProto$f.hasOwnProperty; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString$2.call(Object); + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) { + return false; + } + var proto = _getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty$c.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString$2.call(Ctor) == objectCtorString; +} + +var isPlainObject_1 = isPlainObject; + +/** Built-in value references. */ +var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; + +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray_1(value) || isArguments_1(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); +} + +var _isFlattenable = isFlattenable; + +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = _isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + _arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; +} + +var _baseFlatten = baseFlatten; + +/** Used as references for various `Number` constants. */ +var INFINITY$2 = 1 / 0; + +/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ +function flatMapDeep(collection, iteratee) { + return _baseFlatten(map_1(collection, iteratee), INFINITY$2); +} + +var flatMapDeep_1 = flatMapDeep; + +/** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ +function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; +} + +var _copyArray = copyArray; + +/** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ +function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return _arrayPush(isArray_1(array) ? _copyArray(array) : [array], _baseFlatten(args, 1)); +} + +var concat_1 = concat; + +/** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ +function flatMap(collection, iteratee) { + return _baseFlatten(map_1(collection, iteratee), 1); +} + +var flatMap_1 = flatMap; + +var interopRequireDefault = createCommonjsModule(function (module) { +function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { + "default": obj + }; +} + +module.exports = _interopRequireDefault; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var _typeof_1 = createCommonjsModule(function (module) { +function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + module.exports = _typeof = function _typeof(obj) { + return typeof obj; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + } else { + module.exports = _typeof = function _typeof(obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + } + + return _typeof(obj); +} + +module.exports = _typeof; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var interopRequireWildcard = createCommonjsModule(function (module) { +var _typeof = _typeof_1["default"]; + +function _getRequireWildcardCache() { + if (typeof WeakMap !== "function") return null; + var cache = new WeakMap(); + + _getRequireWildcardCache = function _getRequireWildcardCache() { + return cache; + }; + + return cache; +} + +function _interopRequireWildcard(obj) { + if (obj && obj.__esModule) { + return obj; + } + + if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { + return { + "default": obj + }; + } + + var cache = _getRequireWildcardCache(); + + if (cache && cache.has(obj)) { + return cache.get(obj); + } + + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + + newObj["default"] = obj; + + if (cache) { + cache.set(obj, newObj); + } + + return newObj; +} + +module.exports = _interopRequireWildcard; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var classCallCheck = createCommonjsModule(function (module) { +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} + +module.exports = _classCallCheck; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var createClass = createCommonjsModule(function (module) { +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} + +module.exports = _createClass; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var assertThisInitialized = createCommonjsModule(function (module) { +function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +} + +module.exports = _assertThisInitialized; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var possibleConstructorReturn = createCommonjsModule(function (module) { +var _typeof = _typeof_1["default"]; + + + +function _possibleConstructorReturn(self, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; + } + + return assertThisInitialized(self); +} + +module.exports = _possibleConstructorReturn; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var getPrototypeOf = createCommonjsModule(function (module) { +function _getPrototypeOf(o) { + module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + module.exports["default"] = module.exports, module.exports.__esModule = true; + return _getPrototypeOf(o); +} + +module.exports = _getPrototypeOf; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var setPrototypeOf = createCommonjsModule(function (module) { +function _setPrototypeOf(o, p) { + module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + return _setPrototypeOf(o, p); +} + +module.exports = _setPrototypeOf; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var inherits = createCommonjsModule(function (module) { +function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) setPrototypeOf(subClass, superClass); +} + +module.exports = _inherits; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var isNativeFunction = createCommonjsModule(function (module) { +function _isNativeFunction(fn) { + return Function.toString.call(fn).indexOf("[native code]") !== -1; +} + +module.exports = _isNativeFunction; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var isNativeReflectConstruct = createCommonjsModule(function (module) { +function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } +} + +module.exports = _isNativeReflectConstruct; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var construct = createCommonjsModule(function (module) { +function _construct(Parent, args, Class) { + if (isNativeReflectConstruct()) { + module.exports = _construct = Reflect.construct; + module.exports["default"] = module.exports, module.exports.__esModule = true; + } else { + module.exports = _construct = function _construct(Parent, args, Class) { + var a = [null]; + a.push.apply(a, args); + var Constructor = Function.bind.apply(Parent, a); + var instance = new Constructor(); + if (Class) setPrototypeOf(instance, Class.prototype); + return instance; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + } + + return _construct.apply(null, arguments); +} + +module.exports = _construct; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var wrapNativeSuper = createCommonjsModule(function (module) { +function _wrapNativeSuper(Class) { + var _cache = typeof Map === "function" ? new Map() : undefined; + + module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { + if (Class === null || !isNativeFunction(Class)) return Class; + + if (typeof Class !== "function") { + throw new TypeError("Super expression must either be null or a function"); + } + + if (typeof _cache !== "undefined") { + if (_cache.has(Class)) return _cache.get(Class); + + _cache.set(Class, Wrapper); + } + + function Wrapper() { + return construct(Class, arguments, getPrototypeOf(this).constructor); + } + + Wrapper.prototype = Object.create(Class.prototype, { + constructor: { + value: Wrapper, + enumerable: false, + writable: true, + configurable: true + } + }); + return setPrototypeOf(Wrapper, Class); + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + return _wrapNativeSuper(Class); +} + +module.exports = _wrapNativeSuper; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var error = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.newError = newError; +exports.PROTOCOL_ERROR = exports.SESSION_EXPIRED = exports.SERVICE_UNAVAILABLE = exports.Neo4jError = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _wrapNativeSuper2 = interopRequireDefault(wrapNativeSuper); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// A common place for constructing error objects, to keep them +// uniform across the driver surface. + +/** + * Error code representing complete loss of service. Used by {@link Neo4jError#code}. + * @type {string} + */ +var SERVICE_UNAVAILABLE = 'ServiceUnavailable'; +/** + * Error code representing transient loss of service. Used by {@link Neo4jError#code}. + * @type {string} + */ + +exports.SERVICE_UNAVAILABLE = SERVICE_UNAVAILABLE; +var SESSION_EXPIRED = 'SessionExpired'; +/** + * Error code representing serialization/deserialization issue in the Bolt protocol. Used by {@link Neo4jError#code}. + * @type {string} + */ + +exports.SESSION_EXPIRED = SESSION_EXPIRED; +var PROTOCOL_ERROR = 'ProtocolError'; +/** + * Create a new error from a message and error code + * @param message the error message + * @param code the error code + * @return {Neo4jError} an {@link Neo4jError} + * @private + */ + +exports.PROTOCOL_ERROR = PROTOCOL_ERROR; + +function newError(message) { + var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'N/A'; + // TODO: Idea is that we can check the code here and throw sub-classes + // of Neo4jError as appropriate + return new Neo4jError(message, code); +} +/** + * Class for all errors thrown/returned by the driver. + */ + + +var Neo4jError = +/*#__PURE__*/ +function (_Error) { + (0, _inherits2["default"])(Neo4jError, _Error); + + /** + * @constructor + * @param {string} message - The error message. + * @param {string} code - Optional error code. Will be populated when error originates in the database. + */ + function Neo4jError(message) { + var _this; + + var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'N/A'; + (0, _classCallCheck2["default"])(this, Neo4jError); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(Neo4jError).call(this, message)); + /** + * The error message + * @type {string} + */ + + _this.message = message; + /** + * Optional error code. Will be populated when error originates in the database. + * @type {string} + */ + + _this.code = code; + /** + * The name of the error. + * @type {string} + */ + + _this.name = 'Neo4jError'; + return _this; + } + + return Neo4jError; +}((0, _wrapNativeSuper2["default"])(Error)); + +exports.Neo4jError = Neo4jError; +}); + +var integer = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = exports.toString = exports.toNumber = exports.inSafeRange = exports.isInt = exports["int"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// 64-bit Integer library, originally from Long.js by dcodeIO +// https://github.com/dcodeIO/Long.js +// License Apache 2 + +/** + * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. + * See exported functions for more convenient ways of operating integers. + * Use `int()` function to create new integers, `isInt()` to check if given object is integer, + * `inSafeRange()` to check if it is safe to convert given value to native number, + * `toNumber()` and `toString()` to convert given integer to number or string respectively. + * @access public + * @exports Integer + * @class A Integer class for representing a 64 bit two's-complement integer value. + * @param {number} low The low (signed) 32 bits of the long + * @param {number} high The high (signed) 32 bits of the long + * @constructor + */ +var Integer = +/*#__PURE__*/ +function () { + function Integer(low, high) { + (0, _classCallCheck2["default"])(this, Integer); + + /** + * The low 32 bits as a signed value. + * @type {number} + * @expose + */ + this.low = low | 0; + /** + * The high 32 bits as a signed value. + * @type {number} + * @expose + */ + + this.high = high | 0; + } // The internal representation of an Integer is the two given signed, 32-bit values. + // We use 32-bit pieces because these are the size of integers on which + // JavaScript performs bit-operations. For operations like addition and + // multiplication, we split each number into 16 bit pieces, which can easily be + // multiplied within JavaScript's floating-point representation without overflow + // or change in sign. + // + // In the algorithms below, we frequently reduce the negative case to the + // positive case by negating the input(s) and then post-processing the result. + // Note that we must ALWAYS check specially whether those values are MIN_VALUE + // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as + // a positive number, it overflows back into a negative). Not handling this + // case would often result in infinite recursion. + // + // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from* + // methods on which they depend. + + + (0, _createClass2["default"])(Integer, [{ + key: "inSafeRange", + value: function inSafeRange() { + return this.greaterThanOrEqual(Integer.MIN_SAFE_VALUE) && this.lessThanOrEqual(Integer.MAX_SAFE_VALUE); + } + /** + * Converts the Integer to an exact javascript Number, assuming it is a 32 bit integer. + * @returns {number} + * @expose + */ + + }, { + key: "toInt", + value: function toInt() { + return this.low; + } + /** + * Converts the Integer to a the nearest floating-point representation of this value (double, 53 bit mantissa). + * @returns {number} + * @expose + */ + + }, { + key: "toNumber", + value: function toNumber() { + return this.high * TWO_PWR_32_DBL + (this.low >>> 0); + } + /** + * Converts the Integer to native number or -Infinity/+Infinity when it does not fit. + * @return {number} + * @package + */ + + }, { + key: "toNumberOrInfinity", + value: function toNumberOrInfinity() { + if (this.lessThan(Integer.MIN_SAFE_VALUE)) { + return Number.NEGATIVE_INFINITY; + } else if (this.greaterThan(Integer.MAX_SAFE_VALUE)) { + return Number.POSITIVE_INFINITY; + } else { + return this.toNumber(); + } + } + /** + * Converts the Integer to a string written in the specified radix. + * @param {number=} radix Radix (2-36), defaults to 10 + * @returns {string} + * @override + * @throws {RangeError} If `radix` is out of range + * @expose + */ + + }, { + key: "toString", + value: function toString(radix) { + radix = radix || 10; + + if (radix < 2 || radix > 36) { + throw RangeError('radix out of range: ' + radix); + } + + if (this.isZero()) { + return '0'; + } + + var rem; + + if (this.isNegative()) { + if (this.equals(Integer.MIN_VALUE)) { + // We need to change the Integer value before it can be negated, so we remove + // the bottom-most digit in this base and then recurse to do the rest. + var radixInteger = Integer.fromNumber(radix); + var div = this.div(radixInteger); + rem = div.multiply(radixInteger).subtract(this); + return div.toString(radix) + rem.toInt().toString(radix); + } else { + return '-' + this.negate().toString(radix); + } + } // Do several (6) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + + + var radixToPower = Integer.fromNumber(Math.pow(radix, 6)); + rem = this; + var result = ''; + + while (true) { + var remDiv = rem.div(radixToPower); + var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0; + var digits = intval.toString(radix); + rem = remDiv; + + if (rem.isZero()) { + return digits + result; + } else { + while (digits.length < 6) { + digits = '0' + digits; + } + + result = '' + digits + result; + } + } + } + /** + * Gets the high 32 bits as a signed integer. + * @returns {number} Signed high bits + * @expose + */ + + }, { + key: "getHighBits", + value: function getHighBits() { + return this.high; + } + /** + * Gets the low 32 bits as a signed integer. + * @returns {number} Signed low bits + * @expose + */ + + }, { + key: "getLowBits", + value: function getLowBits() { + return this.low; + } + /** + * Gets the number of bits needed to represent the absolute value of this Integer. + * @returns {number} + * @expose + */ + + }, { + key: "getNumBitsAbs", + value: function getNumBitsAbs() { + if (this.isNegative()) { + return this.equals(Integer.MIN_VALUE) ? 64 : this.negate().getNumBitsAbs(); + } + + var val = this.high !== 0 ? this.high : this.low; + + for (var bit = 31; bit > 0; bit--) { + if ((val & 1 << bit) !== 0) { + break; + } + } + + return this.high !== 0 ? bit + 33 : bit + 1; + } + /** + * Tests if this Integer's value equals zero. + * @returns {boolean} + * @expose + */ + + }, { + key: "isZero", + value: function isZero() { + return this.high === 0 && this.low === 0; + } + /** + * Tests if this Integer's value is negative. + * @returns {boolean} + * @expose + */ + + }, { + key: "isNegative", + value: function isNegative() { + return this.high < 0; + } + /** + * Tests if this Integer's value is positive. + * @returns {boolean} + * @expose + */ + + }, { + key: "isPositive", + value: function isPositive() { + return this.high >= 0; + } + /** + * Tests if this Integer's value is odd. + * @returns {boolean} + * @expose + */ + + }, { + key: "isOdd", + value: function isOdd() { + return (this.low & 1) === 1; + } + /** + * Tests if this Integer's value is even. + * @returns {boolean} + * @expose + */ + + }, { + key: "isEven", + value: function isEven() { + return (this.low & 1) === 0; + } + /** + * Tests if this Integer's value equals the specified's. + * @param {!Integer|number|string} other Other value + * @returns {boolean} + * @expose + */ + + }, { + key: "equals", + value: function equals(other) { + if (!Integer.isInteger(other)) { + other = Integer.fromValue(other); + } + + return this.high === other.high && this.low === other.low; + } + /** + * Tests if this Integer's value differs from the specified's. + * @param {!Integer|number|string} other Other value + * @returns {boolean} + * @expose + */ + + }, { + key: "notEquals", + value: function notEquals(other) { + return !this.equals( + /* validates */ + other); + } + /** + * Tests if this Integer's value is less than the specified's. + * @param {!Integer|number|string} other Other value + * @returns {boolean} + * @expose + */ + + }, { + key: "lessThan", + value: function lessThan(other) { + return this.compare( + /* validates */ + other) < 0; + } + /** + * Tests if this Integer's value is less than or equal the specified's. + * @param {!Integer|number|string} other Other value + * @returns {boolean} + * @expose + */ + + }, { + key: "lessThanOrEqual", + value: function lessThanOrEqual(other) { + return this.compare( + /* validates */ + other) <= 0; + } + /** + * Tests if this Integer's value is greater than the specified's. + * @param {!Integer|number|string} other Other value + * @returns {boolean} + * @expose + */ + + }, { + key: "greaterThan", + value: function greaterThan(other) { + return this.compare( + /* validates */ + other) > 0; + } + /** + * Tests if this Integer's value is greater than or equal the specified's. + * @param {!Integer|number|string} other Other value + * @returns {boolean} + * @expose + */ + + }, { + key: "greaterThanOrEqual", + value: function greaterThanOrEqual(other) { + return this.compare( + /* validates */ + other) >= 0; + } + /** + * Compares this Integer's value with the specified's. + * @param {!Integer|number|string} other Other value + * @returns {number} 0 if they are the same, 1 if the this is greater and -1 + * if the given one is greater + * @expose + */ + + }, { + key: "compare", + value: function compare(other) { + if (!Integer.isInteger(other)) { + other = Integer.fromValue(other); + } + + if (this.equals(other)) { + return 0; + } + + var thisNeg = this.isNegative(); + var otherNeg = other.isNegative(); + + if (thisNeg && !otherNeg) { + return -1; + } + + if (!thisNeg && otherNeg) { + return 1; + } // At this point the sign bits are the same + + + return this.subtract(other).isNegative() ? -1 : 1; + } + /** + * Negates this Integer's value. + * @returns {!Integer} Negated Integer + * @expose + */ + + }, { + key: "negate", + value: function negate() { + if (this.equals(Integer.MIN_VALUE)) { + return Integer.MIN_VALUE; + } + + return this.not().add(Integer.ONE); + } + /** + * Returns the sum of this and the specified Integer. + * @param {!Integer|number|string} addend Addend + * @returns {!Integer} Sum + * @expose + */ + + }, { + key: "add", + value: function add(addend) { + if (!Integer.isInteger(addend)) { + addend = Integer.fromValue(addend); + } // Divide each number into 4 chunks of 16 bits, and then sum the chunks. + + + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = addend.high >>> 16; + var b32 = addend.high & 0xffff; + var b16 = addend.low >>> 16; + var b00 = addend.low & 0xffff; + var c48 = 0; + var c32 = 0; + var c16 = 0; + var c00 = 0; + c00 += a00 + b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 + b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 + b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 + b48; + c48 &= 0xffff; + return Integer.fromBits(c16 << 16 | c00, c48 << 16 | c32); + } + /** + * Returns the difference of this and the specified Integer. + * @param {!Integer|number|string} subtrahend Subtrahend + * @returns {!Integer} Difference + * @expose + */ + + }, { + key: "subtract", + value: function subtract(subtrahend) { + if (!Integer.isInteger(subtrahend)) { + subtrahend = Integer.fromValue(subtrahend); + } + + return this.add(subtrahend.negate()); + } + /** + * Returns the product of this and the specified Integer. + * @param {!Integer|number|string} multiplier Multiplier + * @returns {!Integer} Product + * @expose + */ + + }, { + key: "multiply", + value: function multiply(multiplier) { + if (this.isZero()) { + return Integer.ZERO; + } + + if (!Integer.isInteger(multiplier)) { + multiplier = Integer.fromValue(multiplier); + } + + if (multiplier.isZero()) { + return Integer.ZERO; + } + + if (this.equals(Integer.MIN_VALUE)) { + return multiplier.isOdd() ? Integer.MIN_VALUE : Integer.ZERO; + } + + if (multiplier.equals(Integer.MIN_VALUE)) { + return this.isOdd() ? Integer.MIN_VALUE : Integer.ZERO; + } + + if (this.isNegative()) { + if (multiplier.isNegative()) { + return this.negate().multiply(multiplier.negate()); + } else { + return this.negate().multiply(multiplier).negate(); + } + } else if (multiplier.isNegative()) { + return this.multiply(multiplier.negate()).negate(); + } // If both longs are small, use float multiplication + + + if (this.lessThan(TWO_PWR_24) && multiplier.lessThan(TWO_PWR_24)) { + return Integer.fromNumber(this.toNumber() * multiplier.toNumber()); + } // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. + // We can skip products that would overflow. + + + var a48 = this.high >>> 16; + var a32 = this.high & 0xffff; + var a16 = this.low >>> 16; + var a00 = this.low & 0xffff; + var b48 = multiplier.high >>> 16; + var b32 = multiplier.high & 0xffff; + var b16 = multiplier.low >>> 16; + var b00 = multiplier.low & 0xffff; + var c48 = 0; + var c32 = 0; + var c16 = 0; + var c00 = 0; + c00 += a00 * b00; + c16 += c00 >>> 16; + c00 &= 0xffff; + c16 += a16 * b00; + c32 += c16 >>> 16; + c16 &= 0xffff; + c16 += a00 * b16; + c32 += c16 >>> 16; + c16 &= 0xffff; + c32 += a32 * b00; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a16 * b16; + c48 += c32 >>> 16; + c32 &= 0xffff; + c32 += a00 * b32; + c48 += c32 >>> 16; + c32 &= 0xffff; + c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; + c48 &= 0xffff; + return Integer.fromBits(c16 << 16 | c00, c48 << 16 | c32); + } + /** + * Returns this Integer divided by the specified. + * @param {!Integer|number|string} divisor Divisor + * @returns {!Integer} Quotient + * @expose + */ + + }, { + key: "div", + value: function div(divisor) { + if (!Integer.isInteger(divisor)) { + divisor = Integer.fromValue(divisor); + } + + if (divisor.isZero()) { + throw (0, error.newError)('division by zero'); + } + + if (this.isZero()) { + return Integer.ZERO; + } + + var approx, rem, res; + + if (this.equals(Integer.MIN_VALUE)) { + if (divisor.equals(Integer.ONE) || divisor.equals(Integer.NEG_ONE)) { + return Integer.MIN_VALUE; + } + + if (divisor.equals(Integer.MIN_VALUE)) { + return Integer.ONE; + } else { + // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. + var halfThis = this.shiftRight(1); + approx = halfThis.div(divisor).shiftLeft(1); + + if (approx.equals(Integer.ZERO)) { + return divisor.isNegative() ? Integer.ONE : Integer.NEG_ONE; + } else { + rem = this.subtract(divisor.multiply(approx)); + res = approx.add(rem.div(divisor)); + return res; + } + } + } else if (divisor.equals(Integer.MIN_VALUE)) { + return Integer.ZERO; + } + + if (this.isNegative()) { + if (divisor.isNegative()) { + return this.negate().div(divisor.negate()); + } + + return this.negate().div(divisor).negate(); + } else if (divisor.isNegative()) { + return this.div(divisor.negate()).negate(); + } // Repeat the following until the remainder is less than other: find a + // floating-point that approximates remainder / other *from below*, add this + // into the result, and subtract it from the remainder. It is critical that + // the approximate value is less than or equal to the real value so that the + // remainder never becomes negative. + + + res = Integer.ZERO; + rem = this; + + while (rem.greaterThanOrEqual(divisor)) { + // Approximate the result of division. This may be a little greater or + // smaller than the actual value. + approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); // We will tweak the approximate result by changing it in the 48-th digit or + // the smallest non-fractional digit, whichever is larger. + + var log2 = Math.ceil(Math.log(approx) / Math.LN2); + var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); // Decrease the approximation until it is smaller than the remainder. Note + // that if it is too large, the product overflows and is negative. + + var approxRes = Integer.fromNumber(approx); + var approxRem = approxRes.multiply(divisor); + + while (approxRem.isNegative() || approxRem.greaterThan(rem)) { + approx -= delta; + approxRes = Integer.fromNumber(approx); + approxRem = approxRes.multiply(divisor); + } // We know the answer can't be zero... and actually, zero would cause + // infinite recursion since we would make no progress. + + + if (approxRes.isZero()) { + approxRes = Integer.ONE; + } + + res = res.add(approxRes); + rem = rem.subtract(approxRem); + } + + return res; + } + /** + * Returns this Integer modulo the specified. + * @param {!Integer|number|string} divisor Divisor + * @returns {!Integer} Remainder + * @expose + */ + + }, { + key: "modulo", + value: function modulo(divisor) { + if (!Integer.isInteger(divisor)) { + divisor = Integer.fromValue(divisor); + } + + return this.subtract(this.div(divisor).multiply(divisor)); + } + /** + * Returns the bitwise NOT of this Integer. + * @returns {!Integer} + * @expose + */ + + }, { + key: "not", + value: function not() { + return Integer.fromBits(~this.low, ~this.high); + } + /** + * Returns the bitwise AND of this Integer and the specified. + * @param {!Integer|number|string} other Other Integer + * @returns {!Integer} + * @expose + */ + + }, { + key: "and", + value: function and(other) { + if (!Integer.isInteger(other)) { + other = Integer.fromValue(other); + } + + return Integer.fromBits(this.low & other.low, this.high & other.high); + } + /** + * Returns the bitwise OR of this Integer and the specified. + * @param {!Integer|number|string} other Other Integer + * @returns {!Integer} + * @expose + */ + + }, { + key: "or", + value: function or(other) { + if (!Integer.isInteger(other)) { + other = Integer.fromValue(other); + } + + return Integer.fromBits(this.low | other.low, this.high | other.high); + } + /** + * Returns the bitwise XOR of this Integer and the given one. + * @param {!Integer|number|string} other Other Integer + * @returns {!Integer} + * @expose + */ + + }, { + key: "xor", + value: function xor(other) { + if (!Integer.isInteger(other)) { + other = Integer.fromValue(other); + } + + return Integer.fromBits(this.low ^ other.low, this.high ^ other.high); + } + /** + * Returns this Integer with bits shifted to the left by the given amount. + * @param {number|!Integer} numBits Number of bits + * @returns {!Integer} Shifted Integer + * @expose + */ + + }, { + key: "shiftLeft", + value: function shiftLeft(numBits) { + if (Integer.isInteger(numBits)) { + numBits = numBits.toInt(); + } + + if ((numBits &= 63) === 0) { + return this; + } else if (numBits < 32) { + return Integer.fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits); + } else { + return Integer.fromBits(0, this.low << numBits - 32); + } + } + /** + * Returns this Integer with bits arithmetically shifted to the right by the given amount. + * @param {number|!Integer} numBits Number of bits + * @returns {!Integer} Shifted Integer + * @expose + */ + + }, { + key: "shiftRight", + value: function shiftRight(numBits) { + if (Integer.isInteger(numBits)) { + numBits = numBits.toInt(); + } + + if ((numBits &= 63) === 0) { + return this; + } else if (numBits < 32) { + return Integer.fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits); + } else { + return Integer.fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1); + } + } + }]); + return Integer; +}(); +/** + * An indicator used to reliably determine if an object is a Integer or not. + * @type {boolean} + * @const + * @expose + * @private + */ + + +Integer.__isInteger__ = true; +Object.defineProperty(Integer.prototype, '__isInteger__', { + value: true, + enumerable: false, + configurable: false +}); +/** + * Tests if the specified object is a Integer. + * @access private + * @param {*} obj Object + * @returns {boolean} + * @expose + */ + +Integer.isInteger = function (obj) { + return (obj && obj.__isInteger__) === true; +}; +/** + * A cache of the Integer representations of small integer values. + * @type {!Object} + * @inner + * @private + */ + + +var INT_CACHE = {}; +/** + * Returns a Integer representing the given 32 bit integer value. + * @access private + * @param {number} value The 32 bit integer in question + * @returns {!Integer} The corresponding Integer value + * @expose + */ + +Integer.fromInt = function (value) { + var obj, cachedObj; + value = value | 0; + + if (value >= -128 && value < 128) { + cachedObj = INT_CACHE[value]; + + if (cachedObj) { + return cachedObj; + } + } + + obj = new Integer(value, value < 0 ? -1 : 0, false); + + if (value >= -128 && value < 128) { + INT_CACHE[value] = obj; + } + + return obj; +}; +/** + * Returns a Integer representing the given value, provided that it is a finite number. Otherwise, zero is returned. + * @access private + * @param {number} value The number in question + * @returns {!Integer} The corresponding Integer value + * @expose + */ + + +Integer.fromNumber = function (value) { + if (isNaN(value) || !isFinite(value)) { + return Integer.ZERO; + } + + if (value <= -TWO_PWR_63_DBL) { + return Integer.MIN_VALUE; + } + + if (value + 1 >= TWO_PWR_63_DBL) { + return Integer.MAX_VALUE; + } + + if (value < 0) { + return Integer.fromNumber(-value).negate(); + } + + return new Integer(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0); +}; +/** + * Returns a Integer representing the 64 bit integer that comes by concatenating the given low and high bits. Each is + * assumed to use 32 bits. + * @access private + * @param {number} lowBits The low 32 bits + * @param {number} highBits The high 32 bits + * @returns {!Integer} The corresponding Integer value + * @expose + */ + + +Integer.fromBits = function (lowBits, highBits) { + return new Integer(lowBits, highBits); +}; +/** + * Returns a Integer representation of the given string, written using the specified radix. + * @access private + * @param {string} str The textual representation of the Integer + * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 + * @returns {!Integer} The corresponding Integer value + * @expose + */ + + +Integer.fromString = function (str, radix) { + if (str.length === 0) { + throw (0, error.newError)('number format error: empty string'); + } + + if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') { + return Integer.ZERO; + } + + radix = radix || 10; + + if (radix < 2 || radix > 36) { + throw (0, error.newError)('radix out of range: ' + radix); + } + + var p; + + if ((p = str.indexOf('-')) > 0) { + throw (0, error.newError)('number format error: interior "-" character: ' + str); + } else if (p === 0) { + return Integer.fromString(str.substring(1), radix).negate(); + } // Do several (8) digits each time through the loop, so as to + // minimize the calls to the very expensive emulated div. + + + var radixToPower = Integer.fromNumber(Math.pow(radix, 8)); + var result = Integer.ZERO; + + for (var i = 0; i < str.length; i += 8) { + var size = Math.min(8, str.length - i); + var value = parseInt(str.substring(i, i + size), radix); + + if (size < 8) { + var power = Integer.fromNumber(Math.pow(radix, size)); + result = result.multiply(power).add(Integer.fromNumber(value)); + } else { + result = result.multiply(radixToPower); + result = result.add(Integer.fromNumber(value)); + } + } + + return result; +}; +/** + * Converts the specified value to a Integer. + * @access private + * @param {!Integer|number|string|!{low: number, high: number}} val Value + * @returns {!Integer} + * @expose + */ + + +Integer.fromValue = function (val) { + if (val + /* is compatible */ + instanceof Integer) { + return val; + } + + if (typeof val === 'number') { + return Integer.fromNumber(val); + } + + if (typeof val === 'string') { + return Integer.fromString(val); + } // Throws for non-objects, converts non-instanceof Integer: + + + return new Integer(val.low, val.high); +}; +/** + * Converts the specified value to a number. + * @access private + * @param {!Integer|number|string|!{low: number, high: number}} val Value + * @returns {number} + * @expose + */ + + +Integer.toNumber = function (val) { + return Integer.fromValue(val).toNumber(); +}; +/** + * Converts the specified value to a string. + * @access private + * @param {!Integer|number|string|!{low: number, high: number}} val Value + * @param {number} radix optional radix for string conversion, defaults to 10 + * @returns {string} + * @expose + */ + + +Integer.toString = function (val, radix) { + return Integer.fromValue(val).toString(radix); +}; +/** + * Checks if the given value is in the safe range in order to be converted to a native number + * @access private + * @param {!Integer|number|string|!{low: number, high: number}} val Value + * @param {number} radix optional radix for string conversion, defaults to 10 + * @returns {boolean} + * @expose + */ + + +Integer.inSafeRange = function (val) { + return Integer.fromValue(val).inSafeRange(); +}; +/** + * @type {number} + * @const + * @inner + * @private + */ + + +var TWO_PWR_16_DBL = 1 << 16; +/** + * @type {number} + * @const + * @inner + * @private + */ + +var TWO_PWR_24_DBL = 1 << 24; +/** + * @type {number} + * @const + * @inner + * @private + */ + +var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; +/** + * @type {number} + * @const + * @inner + * @private + */ + +var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; +/** + * @type {number} + * @const + * @inner + * @private + */ + +var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; +/** + * @type {!Integer} + * @const + * @inner + * @private + */ + +var TWO_PWR_24 = Integer.fromInt(TWO_PWR_24_DBL); +/** + * Signed zero. + * @type {!Integer} + * @expose + */ + +Integer.ZERO = Integer.fromInt(0); +/** + * Signed one. + * @type {!Integer} + * @expose + */ + +Integer.ONE = Integer.fromInt(1); +/** + * Signed negative one. + * @type {!Integer} + * @expose + */ + +Integer.NEG_ONE = Integer.fromInt(-1); +/** + * Maximum signed value. + * @type {!Integer} + * @expose + */ + +Integer.MAX_VALUE = Integer.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); +/** + * Minimum signed value. + * @type {!Integer} + * @expose + */ + +Integer.MIN_VALUE = Integer.fromBits(0, 0x80000000 | 0, false); +/** + * Minimum safe value. + * @type {!Integer} + * @expose + */ + +Integer.MIN_SAFE_VALUE = Integer.fromBits(0x1 | 0, 0xffffffffffe00000 | 0); +/** + * Maximum safe value. + * @type {!Integer} + * @expose + */ + +Integer.MAX_SAFE_VALUE = Integer.fromBits(0xffffffff | 0, 0x1fffff | 0); +/** + * Cast value to Integer type. + * @access public + * @param {Mixed} value - The value to use. + * @return {Integer} - An object of type Integer. + */ + +var _int = Integer.fromValue; +/** + * Check if a variable is of Integer type. + * @access public + * @param {Mixed} value - The variable to check. + * @return {Boolean} - Is it of the Integer type? + */ + +exports["int"] = _int; +var isInt = Integer.isInteger; +/** + * Check if a variable can be safely converted to a number + * @access public + * @param {Mixed} value - The variable to check + * @return {Boolean} - true if it is safe to call toNumber on variable otherwise false + */ + +exports.isInt = isInt; +var inSafeRange = Integer.inSafeRange; +/** + * Converts a variable to a number + * @access public + * @param {Mixed} value - The variable to convert + * @return {number} - the variable as a number + */ + +exports.inSafeRange = inSafeRange; +var toNumber = Integer.toNumber; +/** + * Converts the integer to a string representation + * @access public + * @param {Mixed} value - The variable to convert + * @param {number} radix - radix to use in string conversion, defaults to 10 + * @return {string} - returns a string representation of the integer + */ + +exports.toNumber = toNumber; +var toString = Integer.toString; +exports.toString = toString; +var _default = Integer; +exports["default"] = _default; +}); + +var graphTypes = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isNode = isNode; +exports.isRelationship = isRelationship; +exports.isUnboundRelationship = isUnboundRelationship; +exports.isPath = isPath; +exports.isPathSegment = isPathSegment; +exports.PathSegment = exports.Path = exports.UnboundRelationship = exports.Relationship = exports.Node = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var IDENTIFIER_PROPERTY_ATTRIBUTES = { + value: true, + enumerable: false, + configurable: false, + writable: false +}; +var NODE_IDENTIFIER_PROPERTY = '__isNode__'; +var RELATIONSHIP_IDENTIFIER_PROPERTY = '__isRelationship__'; +var UNBOUND_RELATIONSHIP_IDENTIFIER_PROPERTY = '__isUnboundRelationship__'; +var PATH_IDENTIFIER_PROPERTY = '__isPath__'; +var PATH_SEGMENT_IDENTIFIER_PROPERTY = '__isPathSegment__'; + +function hasIdentifierProperty(obj, property) { + return (obj && obj[property]) === true; +} +/** + * Class for Node Type. + */ + + +var Node = +/*#__PURE__*/ +function () { + /** + * @constructor + * @protected + * @param {Integer} identity - Unique identity + * @param {Array} labels - Array for all labels + * @param {Object} properties - Map with node properties + */ + function Node(identity, labels, properties) { + (0, _classCallCheck2["default"])(this, Node); + + /** + * Identity of the node. + * @type {Integer} + */ + this.identity = identity; + /** + * Labels of the node. + * @type {string[]} + */ + + this.labels = labels; + /** + * Properties of the node. + * @type {Object} + */ + + this.properties = properties; + } + /** + * @ignore + */ + + + (0, _createClass2["default"])(Node, [{ + key: "toString", + value: function toString() { + var s = '(' + this.identity; + + for (var i = 0; i < this.labels.length; i++) { + s += ':' + this.labels[i]; + } + + var keys = Object.keys(this.properties); + + if (keys.length > 0) { + s += ' {'; + + for (var _i = 0; _i < keys.length; _i++) { + if (_i > 0) s += ','; + s += keys[_i] + ':' + JSON.stringify(this.properties[keys[_i]]); + } + + s += '}'; + } + + s += ')'; + return s; + } + }]); + return Node; +}(); + +exports.Node = Node; +Object.defineProperty(Node.prototype, NODE_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); +/** + * Test if given object is an instance of {@link Node} class. + * @param {Object} obj the object to test. + * @return {boolean} `true` if given object is a {@link Node}, `false` otherwise. + */ + +function isNode(obj) { + return hasIdentifierProperty(obj, NODE_IDENTIFIER_PROPERTY); +} +/** + * Class for Relationship Type. + */ + + +var Relationship = +/*#__PURE__*/ +function () { + /** + * @constructor + * @protected + * @param {Integer} identity - Unique identity + * @param {Integer} start - Identity of start Node + * @param {Integer} end - Identity of end Node + * @param {string} type - Relationship type + * @param {Object} properties - Map with relationship properties + */ + function Relationship(identity, start, end, type, properties) { + (0, _classCallCheck2["default"])(this, Relationship); + + /** + * Identity of the relationship. + * @type {Integer} + */ + this.identity = identity; + /** + * Identity of the start node. + * @type {Integer} + */ + + this.start = start; + /** + * Identity of the end node. + * @type {Integer} + */ + + this.end = end; + /** + * Type of the relationship. + * @type {string} + */ + + this.type = type; + /** + * Properties of the relationship. + * @type {Object} + */ + + this.properties = properties; + } + /** + * @ignore + */ + + + (0, _createClass2["default"])(Relationship, [{ + key: "toString", + value: function toString() { + var s = '(' + this.start + ')-[:' + this.type; + var keys = Object.keys(this.properties); + + if (keys.length > 0) { + s += ' {'; + + for (var i = 0; i < keys.length; i++) { + if (i > 0) s += ','; + s += keys[i] + ':' + JSON.stringify(this.properties[keys[i]]); + } + + s += '}'; + } + + s += ']->(' + this.end + ')'; + return s; + } + }]); + return Relationship; +}(); + +exports.Relationship = Relationship; +Object.defineProperty(Relationship.prototype, RELATIONSHIP_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); +/** + * Test if given object is an instance of {@link Relationship} class. + * @param {Object} obj the object to test. + * @return {boolean} `true` if given object is a {@link Relationship}, `false` otherwise. + */ + +function isRelationship(obj) { + return hasIdentifierProperty(obj, RELATIONSHIP_IDENTIFIER_PROPERTY); +} +/** + * Class for UnboundRelationship Type. + * @access private + */ + + +var UnboundRelationship = +/*#__PURE__*/ +function () { + /** + * @constructor + * @protected + * @param {Integer} identity - Unique identity + * @param {string} type - Relationship type + * @param {Object} properties - Map with relationship properties + */ + function UnboundRelationship(identity, type, properties) { + (0, _classCallCheck2["default"])(this, UnboundRelationship); + + /** + * Identity of the relationship. + * @type {Integer} + */ + this.identity = identity; + /** + * Type of the relationship. + * @type {string} + */ + + this.type = type; + /** + * Properties of the relationship. + * @type {Object} + */ + + this.properties = properties; + } + /** + * Bind relationship + * + * @protected + * @param {Integer} start - Identity of start node + * @param {Integer} end - Identity of end node + * @return {Relationship} - Created relationship + */ + + + (0, _createClass2["default"])(UnboundRelationship, [{ + key: "bind", + value: function bind(start, end) { + return new Relationship(this.identity, start, end, this.type, this.properties); + } + /** + * @ignore + */ + + }, { + key: "toString", + value: function toString() { + var s = '-[:' + this.type; + var keys = Object.keys(this.properties); + + if (keys.length > 0) { + s += ' {'; + + for (var i = 0; i < keys.length; i++) { + if (i > 0) s += ','; + s += keys[i] + ':' + JSON.stringify(this.properties[keys[i]]); + } + + s += '}'; + } + + s += ']->'; + return s; + } + }]); + return UnboundRelationship; +}(); + +exports.UnboundRelationship = UnboundRelationship; +Object.defineProperty(UnboundRelationship.prototype, UNBOUND_RELATIONSHIP_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); +/** + * Test if given object is an instance of {@link UnboundRelationship} class. + * @param {Object} obj the object to test. + * @return {boolean} `true` if given object is a {@link UnboundRelationship}, `false` otherwise. + */ + +function isUnboundRelationship(obj) { + return hasIdentifierProperty(obj, UNBOUNT_RELATIONSHIP_IDENTIFIER_PROPERTY); +} +/** + * Class for PathSegment Type. + */ + + +var PathSegment = +/** + * @constructor + * @protected + * @param {Node} start - start node + * @param {Relationship} rel - relationship that connects start and end node + * @param {Node} end - end node + */ +function PathSegment(start, rel, end) { + (0, _classCallCheck2["default"])(this, PathSegment); + + /** + * Start node. + * @type {Node} + */ + this.start = start; + /** + * Relationship. + * @type {Relationship} + */ + + this.relationship = rel; + /** + * End node. + * @type {Node} + */ + + this.end = end; +}; + +exports.PathSegment = PathSegment; +Object.defineProperty(PathSegment.prototype, PATH_SEGMENT_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); +/** + * Test if given object is an instance of {@link PathSegment} class. + * @param {Object} obj the object to test. + * @return {boolean} `true` if given object is a {@link PathSegment}, `false` otherwise. + */ + +function isPathSegment(obj) { + return hasIdentifierProperty(obj, PATH_SEGMENT_IDENTIFIER_PROPERTY); +} +/** + * Class for Path Type. + */ + + +var Path = +/** + * @constructor + * @protected + * @param {Node} start - start node + * @param {Node} end - end node + * @param {Array} segments - Array of Segments + */ +function Path(start, end, segments) { + (0, _classCallCheck2["default"])(this, Path); + + /** + * Start node. + * @type {Node} + */ + this.start = start; + /** + * End node. + * @type {Node} + */ + + this.end = end; + /** + * Segments. + * @type {Array} + */ + + this.segments = segments; + /** + * Length of the segments. + * @type {Number} + */ + + this.length = segments.length; +}; + +exports.Path = Path; +Object.defineProperty(Path.prototype, PATH_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); +/** + * Test if given object is an instance of {@link Path} class. + * @param {Object} obj the object to test. + * @return {boolean} `true` if given object is a {@link Path}, `false` otherwise. + */ + +function isPath(obj) { + return hasIdentifierProperty(obj, PATH_IDENTIFIER_PROPERTY); +} +}); + +var resultSummary = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = exports.queryType = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A ResultSummary instance contains structured metadata for a {@link Result}. + * @access public + */ +var ResultSummary = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {string} query - The query this summary is for + * @param {Object} parameters - Parameters for the query + * @param {Object} metadata - Query metadata + * @param {number} protocolVersion - Bolt protocol version + */ + function ResultSummary(query, parameters, metadata, protocolVersion) { + (0, _classCallCheck2["default"])(this, ResultSummary); + + /** + * The query and parameters this summary is for. + * @type {{text: string, parameters: Object}} + * @public + */ + this.query = { + text: query, + parameters: parameters + /** + * The type of query executed. Can be "r" for read-only query, "rw" for read-write query, + * "w" for write-only query and "s" for schema-write query. + * String constants are available in {@link queryType} object. + * @type {string} + * @public + */ + + }; + this.queryType = metadata.type; + /** + * Counters for operations the query triggered. + * @type {QueryStatistics} + * @public + */ + + this.counters = new QueryStatistics(metadata.stats || {}); // for backwards compatibility, remove in future version + + /** + * Use {@link ResultSummary.counters} instead. + * @type {QueryStatistics} + * @deprecated + */ + + this.updateStatistics = this.counters; + /** + * This describes how the database will execute the query. + * Query plan for the executed query if available, otherwise undefined. + * Will only be populated for queries that start with "EXPLAIN". + * @type {Plan} + * @public + */ + + this.plan = metadata.plan || metadata.profile ? new Plan(metadata.plan || metadata.profile) : false; + /** + * This describes how the database did execute your query. This will contain detailed information about what + * each step of the plan did. Profiled query plan for the executed query if available, otherwise undefined. + * Will only be populated for queries that start with "PROFILE". + * @type {ProfiledPlan} + * @public + */ + + this.profile = metadata.profile ? new ProfiledPlan(metadata.profile) : false; + /** + * An array of notifications that might arise when executing the query. Notifications can be warnings about + * problematic queries or other valuable information that can be presented in a client. Unlike failures + * or errors, notifications do not affect the execution of a query. + * @type {Array} + * @public + */ + + this.notifications = this._buildNotifications(metadata.notifications); + /** + * The basic information of the server where the result is obtained from. + * @type {ServerInfo} + * @public + */ + + this.server = new ServerInfo(metadata.server, protocolVersion); + /** + * The time it took the server to consume the result. + * @type {number} + * @public + */ + + this.resultConsumedAfter = metadata.result_consumed_after; + /** + * The time it took the server to make the result available for consumption in milliseconds. + * @type {number} + * @public + */ + + this.resultAvailableAfter = metadata.result_available_after; + /** + * The database name where this summary is obtained from. + * @type {{name: string}} + * @public + */ + + this.database = { + name: metadata.db || null + }; + } + + (0, _createClass2["default"])(ResultSummary, [{ + key: "_buildNotifications", + value: function _buildNotifications(notifications) { + if (!notifications) { + return []; + } + + return notifications.map(function (n) { + return new Notification(n); + }); + } + /** + * Check if the result summary has a plan + * @return {boolean} + */ + + }, { + key: "hasPlan", + value: function hasPlan() { + return this.plan instanceof Plan; + } + /** + * Check if the result summary has a profile + * @return {boolean} + */ + + }, { + key: "hasProfile", + value: function hasProfile() { + return this.profile instanceof ProfiledPlan; + } + }]); + return ResultSummary; +}(); +/** + * Class for execution plan received by prepending Cypher with EXPLAIN. + * @access public + */ + + +var Plan = +/** + * Create a Plan instance + * @constructor + * @param {Object} plan - Object with plan data + */ +function Plan(plan) { + (0, _classCallCheck2["default"])(this, Plan); + this.operatorType = plan.operatorType; + this.identifiers = plan.identifiers; + this.arguments = plan.args; + this.children = plan.children ? plan.children.map(function (child) { + return new Plan(child); + }) : []; +}; +/** + * Class for execution plan received by prepending Cypher with PROFILE. + * @access public + */ + + +var ProfiledPlan = +/*#__PURE__*/ +function () { + /** + * Create a ProfiledPlan instance + * @constructor + * @param {Object} profile - Object with profile data + */ + function ProfiledPlan(profile) { + (0, _classCallCheck2["default"])(this, ProfiledPlan); + this.operatorType = profile.operatorType; + this.identifiers = profile.identifiers; + this.arguments = profile.args; + this.dbHits = valueOrDefault('dbHits', profile); + this.rows = valueOrDefault('rows', profile); + this.pageCacheMisses = valueOrDefault('pageCacheMisses', profile); + this.pageCacheHits = valueOrDefault('pageCacheHits', profile); + this.pageCacheHitRatio = valueOrDefault('pageCacheHitRatio', profile); + this.time = valueOrDefault('time', profile); + this.children = profile.children ? profile.children.map(function (child) { + return new ProfiledPlan(child); + }) : []; + } + + (0, _createClass2["default"])(ProfiledPlan, [{ + key: "hasPageCacheStats", + value: function hasPageCacheStats() { + return this.pageCacheMisses > 0 || this.pageCacheHits > 0 || this.pageCacheHitRatio > 0; + } + }]); + return ProfiledPlan; +}(); +/** + * Get statistical information for a {@link Result}. + * @access public + */ + + +var QueryStatistics = +/*#__PURE__*/ +function () { + /** + * Structurize the statistics + * @constructor + * @param {Object} statistics - Result statistics + */ + function QueryStatistics(statistics) { + var _this = this; + + (0, _classCallCheck2["default"])(this, QueryStatistics); + this._stats = { + nodesCreated: 0, + nodesDeleted: 0, + relationshipsCreated: 0, + relationshipsDeleted: 0, + propertiesSet: 0, + labelsAdded: 0, + labelsRemoved: 0, + indexesAdded: 0, + indexesRemoved: 0, + constraintsAdded: 0, + constraintsRemoved: 0 + }; + this._systemUpdates = 0; + Object.keys(statistics).forEach(function (index) { + // To camelCase + var camelCaseIndex = index.replace(/(-\w)/g, function (m) { + return m[1].toUpperCase(); + }); + + if (camelCaseIndex in _this._stats) { + _this._stats[camelCaseIndex] = intValue(statistics[index]); + } else if (camelCaseIndex === 'systemUpdates') { + _this._systemUpdates = intValue(statistics[index]); + } + }); + this._stats = Object.freeze(this._stats); + } + /** + * Did the database get updated? + * @return {boolean} + */ + + + (0, _createClass2["default"])(QueryStatistics, [{ + key: "containsUpdates", + value: function containsUpdates() { + var _this2 = this; + + return Object.keys(this._stats).reduce(function (last, current) { + return last + _this2._stats[current]; + }, 0) > 0; + } + /** + * Returns the query statistics updates in a dictionary. + * @returns {*} + */ + + }, { + key: "updates", + value: function updates() { + return this._stats; + } + /** + * Return true if the system database get updated, otherwise false + * @returns {boolean} - If the system database get updated or not. + */ + + }, { + key: "containsSystemUpdates", + value: function containsSystemUpdates() { + return this._systemUpdates > 0; + } + /** + * @returns {number} - Number of system updates + */ + + }, { + key: "systemUpdates", + value: function systemUpdates() { + return this._systemUpdates; + } + }]); + return QueryStatistics; +}(); +/** + * Class for Cypher notifications + * @access public + */ + + +var Notification = +/*#__PURE__*/ +function () { + /** + * Create a Notification instance + * @constructor + * @param {Object} notification - Object with notification data + */ + function Notification(notification) { + (0, _classCallCheck2["default"])(this, Notification); + this.code = notification.code; + this.title = notification.title; + this.description = notification.description; + this.severity = notification.severity; + this.position = Notification._constructPosition(notification.position); + } + + (0, _createClass2["default"])(Notification, null, [{ + key: "_constructPosition", + value: function _constructPosition(pos) { + if (!pos) { + return {}; + } + + return { + offset: intValue(pos.offset), + line: intValue(pos.line), + column: intValue(pos.column) + }; + } + }]); + return Notification; +}(); +/** + * Class for exposing server info from a result. + * @access public + */ + + +var ServerInfo = +/** + * Create a ServerInfo instance + * @constructor + * @param {Object} serverMeta - Object with serverMeta data + * @param {number} protocolVersion - Bolt protocol version + */ +function ServerInfo(serverMeta, protocolVersion) { + (0, _classCallCheck2["default"])(this, ServerInfo); + + if (serverMeta) { + this.address = serverMeta.address; + this.version = serverMeta.version; + } + + this.protocolVersion = protocolVersion; +}; + +function intValue(value) { + return (0, integer.isInt)(value) ? value.toInt() : value; +} + +function valueOrDefault(key, values) { + var defaultValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; + + if (key in values) { + var value = values[key]; + return (0, integer.isInt)(value) ? value.toInt() : value; + } else { + return defaultValue; + } +} +/** + * The constants for query types + * @type {{SCHEMA_WRITE: string, WRITE_ONLY: string, READ_ONLY: string, READ_WRITE: string}} + */ + + +var queryType = { + READ_ONLY: 'r', + READ_WRITE: 'rw', + WRITE_ONLY: 'w', + SCHEMA_WRITE: 's' +}; +exports.queryType = queryType; +var _default = ResultSummary; +exports["default"] = _default; +}); + +var util = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isEmptyObjectOrNull = isEmptyObjectOrNull; +exports.isObject = isObject; +exports.isString = isString; +exports.assertObject = assertObject; +exports.assertString = assertString; +exports.assertNumber = assertNumber; +exports.assertNumberOrInteger = assertNumberOrInteger; +exports.assertValidDate = assertValidDate; +exports.validateQueryAndParameters = validateQueryAndParameters; +exports.ENCRYPTION_OFF = exports.ENCRYPTION_ON = void 0; + +var _typeof2 = interopRequireDefault(_typeof_1); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var ENCRYPTION_ON = 'ENCRYPTION_ON'; +exports.ENCRYPTION_ON = ENCRYPTION_ON; +var ENCRYPTION_OFF = 'ENCRYPTION_OFF'; +exports.ENCRYPTION_OFF = ENCRYPTION_OFF; + +function isEmptyObjectOrNull(obj) { + if (obj === null) { + return true; + } + + if (!isObject(obj)) { + return false; + } + + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + return false; + } + } + + return true; +} + +function isObject(obj) { + return (0, _typeof2["default"])(obj) === 'object' && !Array.isArray(obj) && obj !== null; +} +/** + * Check and normalize given query and parameters. + * @param {string|{text: string, parameters: object}} query the query to check. + * @param {Object} parameters + * @return {{query: string, params: object}} the normalized query with parameters. + * @throws TypeError when either given query or parameters are invalid. + */ + + +function validateQueryAndParameters(query, parameters) { + var validatedQuery = query; + var params = parameters || {}; + + if ((0, _typeof2["default"])(query) === 'object' && query.text) { + validatedQuery = query.text; + params = query.parameters || {}; + } + + assertCypherQuery(validatedQuery); + assertQueryParameters(params); + return { + validatedQuery: validatedQuery, + params: params + }; +} + +function assertObject(obj, objName) { + if (!isObject(obj)) { + throw new TypeError(objName + ' expected to be an object but was: ' + JSON.stringify(obj)); + } + + return obj; +} + +function assertString(obj, objName) { + if (!isString(obj)) { + throw new TypeError(objName + ' expected to be string but was: ' + JSON.stringify(obj)); + } + + return obj; +} + +function assertNumber(obj, objName) { + if (typeof obj !== 'number') { + throw new TypeError(objName + ' expected to be a number but was: ' + JSON.stringify(obj)); + } + + return obj; +} + +function assertNumberOrInteger(obj, objName) { + if (typeof obj !== 'number' && !(0, integer.isInt)(obj)) { + throw new TypeError(objName + ' expected to be either a number or an Integer object but was: ' + JSON.stringify(obj)); + } + + return obj; +} + +function assertValidDate(obj, objName) { + if (Object.prototype.toString.call(obj) !== '[object Date]') { + throw new TypeError(objName + ' expected to be a standard JavaScript Date but was: ' + JSON.stringify(obj)); + } + + if (Number.isNaN(obj.getTime())) { + throw new TypeError(objName + ' expected to be valid JavaScript Date but its time was NaN: ' + JSON.stringify(obj)); + } + + return obj; +} + +function assertCypherQuery(obj) { + assertString(obj, 'Cypher query'); + + if (obj.trim().length === 0) { + throw new TypeError('Cypher query is expected to be a non-empty string.'); + } +} + +function assertQueryParameters(obj) { + if (!isObject(obj)) { + // objects created with `Object.create(null)` do not have a constructor property + var _constructor = obj.constructor ? ' ' + obj.constructor.name : ''; + + throw new TypeError("Query parameters are expected to either be undefined/null or an object, given:".concat(_constructor, " ").concat(obj)); + } +} + +function isString(str) { + return Object.prototype.toString.call(str) === '[object String]'; +} +}); + +var constants = createCommonjsModule(function (module, exports) { + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.BOLT_PROTOCOL_V4_2 = exports.BOLT_PROTOCOL_V4_1 = exports.BOLT_PROTOCOL_V4_0 = exports.BOLT_PROTOCOL_V3 = exports.BOLT_PROTOCOL_V2 = exports.BOLT_PROTOCOL_V1 = exports.ACCESS_MODE_WRITE = exports.ACCESS_MODE_READ = void 0; + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var ACCESS_MODE_READ = 'READ'; +exports.ACCESS_MODE_READ = ACCESS_MODE_READ; +var ACCESS_MODE_WRITE = 'WRITE'; +exports.ACCESS_MODE_WRITE = ACCESS_MODE_WRITE; +var BOLT_PROTOCOL_V1 = 1; +exports.BOLT_PROTOCOL_V1 = BOLT_PROTOCOL_V1; +var BOLT_PROTOCOL_V2 = 2; +exports.BOLT_PROTOCOL_V2 = BOLT_PROTOCOL_V2; +var BOLT_PROTOCOL_V3 = 3; +exports.BOLT_PROTOCOL_V3 = BOLT_PROTOCOL_V3; +var BOLT_PROTOCOL_V4_0 = 4.0; +exports.BOLT_PROTOCOL_V4_0 = BOLT_PROTOCOL_V4_0; +var BOLT_PROTOCOL_V4_1 = 4.1; +exports.BOLT_PROTOCOL_V4_1 = BOLT_PROTOCOL_V4_1; +var BOLT_PROTOCOL_V4_2 = 4.2; +exports.BOLT_PROTOCOL_V4_2 = BOLT_PROTOCOL_V4_2; +}); + +var defineProperty$1 = createCommonjsModule(function (module) { +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +module.exports = _defineProperty; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var bookmark = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _defineProperty2 = interopRequireDefault(defineProperty$1); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var util$1 = interopRequireWildcard(util); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var BOOKMARKS_KEY = 'bookmarks'; + +var Bookmark = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {string|string[]} values single bookmark as string or multiple bookmarks as a string array. + */ + function Bookmark(values) { + (0, _classCallCheck2["default"])(this, Bookmark); + this._values = asStringArray(values); + } + + (0, _createClass2["default"])(Bookmark, [{ + key: "isEmpty", + + /** + * Check if the given bookmark is meaningful and can be send to the database. + * @return {boolean} returns `true` bookmark has a value, `false` otherwise. + */ + value: function isEmpty() { + return this._values.length === 0; + } + /** + * Get all bookmark values as an array. + * @return {string[]} all values. + */ + + }, { + key: "values", + value: function values() { + return this._values; + } + /** + * Get this bookmark as an object for begin transaction call. + * @return {Object} the value of this bookmark as object. + */ + + }, { + key: "asBeginTransactionParameters", + value: function asBeginTransactionParameters() { + if (this.isEmpty()) { + return {}; + } // Driver sends {bookmark: "max", bookmarks: ["one", "two", "max"]} instead of simple + // {bookmarks: ["one", "two", "max"]} for backwards compatibility reasons. Old servers can only accept single + // bookmark that is why driver has to parse and compare given list of bookmarks. This functionality will + // eventually be removed. + + + return (0, _defineProperty2["default"])({}, BOOKMARKS_KEY, this._values); + } + }], [{ + key: "empty", + value: function empty() { + return EMPTY_BOOKMARK; + } + }]); + return Bookmark; +}(); + +exports["default"] = Bookmark; +var EMPTY_BOOKMARK = new Bookmark(null); +/** + * Converts given value to an array. + * @param {string|string[]|Array} [value=undefined] argument to convert. + * @return {string[]} value converted to an array. + */ + +function asStringArray(value) { + if (!value) { + return []; + } + + if (util$1.isString(value)) { + return [value]; + } + + if (Array.isArray(value)) { + var result = []; + var flattenedValue = flattenArray(value); + + for (var i = 0; i < flattenedValue.length; i++) { + var element = flattenedValue[i]; // if it is undefined or null, ignore it + + if (element !== undefined && element !== null) { + if (!util$1.isString(element)) { + throw new TypeError("Bookmark value should be a string, given: '".concat(element, "'")); + } + + result.push(element); + } + } + + return result; + } + + throw new TypeError("Bookmark should either be a string or a string array, given: '".concat(value, "'")); +} +/** + * Recursively flattens an array so that the result becomes a single array + * of values, which does not include any sub-arrays + * + * @param {Array} value + */ + + +function flattenArray(values) { + return values.reduce(function (dest, value) { + return Array.isArray(value) ? dest.concat(flattenArray(value)) : dest.concat(value); + }, []); +} +}); + +var connectionHolder = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.EMPTY_CONNECTION_HOLDER = exports["default"] = void 0; + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + + + + + +var _bookmark = interopRequireDefault(bookmark); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Utility to lazily initialize connections and return them back to the pool when unused. + */ +var ConnectionHolder = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {string} mode - the access mode for new connection holder. + * @param {string} database - the target database name. + * @param {ConnectionProvider} connectionProvider - the connection provider to acquire connections from. + */ + function ConnectionHolder() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$mode = _ref.mode, + mode = _ref$mode === void 0 ? constants.ACCESS_MODE_WRITE : _ref$mode, + _ref$database = _ref.database, + database = _ref$database === void 0 ? '' : _ref$database, + bookmark = _ref.bookmark, + connectionProvider = _ref.connectionProvider; + + (0, _classCallCheck2["default"])(this, ConnectionHolder); + this._mode = mode; + this._database = database ? (0, util.assertString)(database, 'database') : ''; + this._bookmark = bookmark || _bookmark["default"].empty(); + this._connectionProvider = connectionProvider; + this._referenceCount = 0; + this._connectionPromise = Promise.resolve(null); + } + /** + * Returns the assigned access mode. + * @returns {string} access mode + */ + + + (0, _createClass2["default"])(ConnectionHolder, [{ + key: "mode", + value: function mode() { + return this._mode; + } + /** + * Returns the target database name + * @returns {string} the database name + */ + + }, { + key: "database", + value: function database() { + return this._database; + } + /** + * Make this holder initialize new connection if none exists already. + * @return {boolean} + */ + + }, { + key: "initializeConnection", + value: function initializeConnection() { + if (this._referenceCount === 0) { + this._connectionPromise = this._connectionProvider.acquireConnection({ + accessMode: this._mode, + database: this._database, + bookmark: this._bookmark + }); + } else { + this._referenceCount++; + return false; + } + + this._referenceCount++; + return true; + } + /** + * Get the current connection promise. + * @return {Promise} promise resolved with the current connection. + */ + + }, { + key: "getConnection", + value: function getConnection() { + return this._connectionPromise; + } + /** + * Notify this holder that single party does not require current connection any more. + * @return {Promise} promise resolved with the current connection, never a rejected promise. + */ + + }, { + key: "releaseConnection", + value: function releaseConnection() { + if (this._referenceCount === 0) { + return this._connectionPromise; + } + + this._referenceCount--; + + if (this._referenceCount === 0) { + return this._releaseConnection(); + } + + return this._connectionPromise; + } + /** + * Closes this holder and releases current connection (if any) despite any existing users. + * @return {Promise} promise resolved when current connection is released to the pool. + */ + + }, { + key: "close", + value: function close() { + if (this._referenceCount === 0) { + return this._connectionPromise; + } + + this._referenceCount = 0; + return this._releaseConnection(); + } + /** + * Return the current pooled connection instance to the connection pool. + * We don't pool Session instances, to avoid users using the Session after they've called close. + * The `Session` object is just a thin wrapper around Connection anyway, so it makes little difference. + * @return {Promise} - promise resolved then connection is returned to the pool. + * @private + */ + + }, { + key: "_releaseConnection", + value: function _releaseConnection() { + this._connectionPromise = this._connectionPromise.then(function (connection) { + if (connection) { + return connection.resetAndFlush()["catch"](ignoreError).then(function () { + return connection._release(); + }); + } else { + return Promise.resolve(); + } + })["catch"](ignoreError); + return this._connectionPromise; + } + }]); + return ConnectionHolder; +}(); + +exports["default"] = ConnectionHolder; + +var EmptyConnectionHolder = +/*#__PURE__*/ +function (_ConnectionHolder) { + (0, _inherits2["default"])(EmptyConnectionHolder, _ConnectionHolder); + + function EmptyConnectionHolder() { + (0, _classCallCheck2["default"])(this, EmptyConnectionHolder); + return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(EmptyConnectionHolder).apply(this, arguments)); + } + + (0, _createClass2["default"])(EmptyConnectionHolder, [{ + key: "initializeConnection", + value: function initializeConnection() { + // nothing to initialize + return true; + } + }, { + key: "getConnection", + value: function getConnection() { + return Promise.reject((0, error.newError)('This connection holder does not serve connections')); + } + }, { + key: "releaseConnection", + value: function releaseConnection() { + return Promise.resolve(); + } + }, { + key: "close", + value: function close() { + return Promise.resolve(); + } + }]); + return EmptyConnectionHolder; +}(ConnectionHolder); // eslint-disable-next-line handle-callback-err + + +function ignoreError(error) {} +/** + * Connection holder that does not manage any connections. + * @type {ConnectionHolder} + */ + + +var EMPTY_CONNECTION_HOLDER = new EmptyConnectionHolder(); +exports.EMPTY_CONNECTION_HOLDER = EMPTY_CONNECTION_HOLDER; +}); + +var superPropBase = createCommonjsModule(function (module) { +function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = getPrototypeOf(object); + if (object === null) break; + } + + return object; +} + +module.exports = _superPropBase; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var get$1 = createCommonjsModule(function (module) { +function _get(target, property, receiver) { + if (typeof Reflect !== "undefined" && Reflect.get) { + module.exports = _get = Reflect.get; + module.exports["default"] = module.exports, module.exports.__esModule = true; + } else { + module.exports = _get = function _get(target, property, receiver) { + var base = superPropBase(target, property); + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.get) { + return desc.get.call(receiver); + } + + return desc.value; + }; + + module.exports["default"] = module.exports, module.exports.__esModule = true; + } + + return _get(target, property, receiver || target); +} + +module.exports = _get; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +/** + * Copyright (c) 2014-present, Facebook, Inc. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +var runtime_1 = createCommonjsModule(function (module) { +var runtime = (function (exports) { + + var Op = Object.prototype; + var hasOwn = Op.hasOwnProperty; + var undefined$1; // More compressible than void 0. + var $Symbol = typeof Symbol === "function" ? Symbol : {}; + var iteratorSymbol = $Symbol.iterator || "@@iterator"; + var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; + var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; + + function define(obj, key, value) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + return obj[key]; + } + try { + // IE 8 has a broken Object.defineProperty that only works on DOM objects. + define({}, ""); + } catch (err) { + define = function(obj, key, value) { + return obj[key] = value; + }; + } + + function wrap(innerFn, outerFn, self, tryLocsList) { + // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. + var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; + var generator = Object.create(protoGenerator.prototype); + var context = new Context(tryLocsList || []); + + // The ._invoke method unifies the implementations of the .next, + // .throw, and .return methods. + generator._invoke = makeInvokeMethod(innerFn, self, context); + + return generator; + } + exports.wrap = wrap; + + // Try/catch helper to minimize deoptimizations. Returns a completion + // record like context.tryEntries[i].completion. This interface could + // have been (and was previously) designed to take a closure to be + // invoked without arguments, but in all the cases we care about we + // already have an existing method we want to call, so there's no need + // to create a new function object. We can even get away with assuming + // the method takes exactly one argument, since that happens to be true + // in every case, so we don't have to touch the arguments object. The + // only additional allocation required is the completion record, which + // has a stable shape and so hopefully should be cheap to allocate. + function tryCatch(fn, obj, arg) { + try { + return { type: "normal", arg: fn.call(obj, arg) }; + } catch (err) { + return { type: "throw", arg: err }; + } + } + + var GenStateSuspendedStart = "suspendedStart"; + var GenStateSuspendedYield = "suspendedYield"; + var GenStateExecuting = "executing"; + var GenStateCompleted = "completed"; + + // Returning this object from the innerFn has the same effect as + // breaking out of the dispatch switch statement. + var ContinueSentinel = {}; + + // Dummy constructor functions that we use as the .constructor and + // .constructor.prototype properties for functions that return Generator + // objects. For full spec compliance, you may wish to configure your + // minifier not to mangle the names of these two functions. + function Generator() {} + function GeneratorFunction() {} + function GeneratorFunctionPrototype() {} + + // This is a polyfill for %IteratorPrototype% for environments that + // don't natively support it. + var IteratorPrototype = {}; + IteratorPrototype[iteratorSymbol] = function () { + return this; + }; + + var getProto = Object.getPrototypeOf; + var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); + if (NativeIteratorPrototype && + NativeIteratorPrototype !== Op && + hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { + // This environment has a native %IteratorPrototype%; use it instead + // of the polyfill. + IteratorPrototype = NativeIteratorPrototype; + } + + var Gp = GeneratorFunctionPrototype.prototype = + Generator.prototype = Object.create(IteratorPrototype); + GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; + GeneratorFunctionPrototype.constructor = GeneratorFunction; + GeneratorFunction.displayName = define( + GeneratorFunctionPrototype, + toStringTagSymbol, + "GeneratorFunction" + ); + + // Helper for defining the .next, .throw, and .return methods of the + // Iterator interface in terms of a single ._invoke method. + function defineIteratorMethods(prototype) { + ["next", "throw", "return"].forEach(function(method) { + define(prototype, method, function(arg) { + return this._invoke(method, arg); + }); + }); + } + + exports.isGeneratorFunction = function(genFun) { + var ctor = typeof genFun === "function" && genFun.constructor; + return ctor + ? ctor === GeneratorFunction || + // For the native GeneratorFunction constructor, the best we can + // do is to check its .name property. + (ctor.displayName || ctor.name) === "GeneratorFunction" + : false; + }; + + exports.mark = function(genFun) { + if (Object.setPrototypeOf) { + Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); + } else { + genFun.__proto__ = GeneratorFunctionPrototype; + define(genFun, toStringTagSymbol, "GeneratorFunction"); + } + genFun.prototype = Object.create(Gp); + return genFun; + }; + + // Within the body of any async function, `await x` is transformed to + // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test + // `hasOwn.call(value, "__await")` to determine if the yielded value is + // meant to be awaited. + exports.awrap = function(arg) { + return { __await: arg }; + }; + + function AsyncIterator(generator, PromiseImpl) { + function invoke(method, arg, resolve, reject) { + var record = tryCatch(generator[method], generator, arg); + if (record.type === "throw") { + reject(record.arg); + } else { + var result = record.arg; + var value = result.value; + if (value && + typeof value === "object" && + hasOwn.call(value, "__await")) { + return PromiseImpl.resolve(value.__await).then(function(value) { + invoke("next", value, resolve, reject); + }, function(err) { + invoke("throw", err, resolve, reject); + }); + } + + return PromiseImpl.resolve(value).then(function(unwrapped) { + // When a yielded Promise is resolved, its final value becomes + // the .value of the Promise<{value,done}> result for the + // current iteration. + result.value = unwrapped; + resolve(result); + }, function(error) { + // If a rejected Promise was yielded, throw the rejection back + // into the async generator function so it can be handled there. + return invoke("throw", error, resolve, reject); + }); + } + } + + var previousPromise; + + function enqueue(method, arg) { + function callInvokeWithMethodAndArg() { + return new PromiseImpl(function(resolve, reject) { + invoke(method, arg, resolve, reject); + }); + } + + return previousPromise = + // If enqueue has been called before, then we want to wait until + // all previous Promises have been resolved before calling invoke, + // so that results are always delivered in the correct order. If + // enqueue has not been called before, then it is important to + // call invoke immediately, without waiting on a callback to fire, + // so that the async generator function has the opportunity to do + // any necessary setup in a predictable way. This predictability + // is why the Promise constructor synchronously invokes its + // executor callback, and why async functions synchronously + // execute code before the first await. Since we implement simple + // async functions in terms of async generators, it is especially + // important to get this right, even though it requires care. + previousPromise ? previousPromise.then( + callInvokeWithMethodAndArg, + // Avoid propagating failures to Promises returned by later + // invocations of the iterator. + callInvokeWithMethodAndArg + ) : callInvokeWithMethodAndArg(); + } + + // Define the unified helper method that is used to implement .next, + // .throw, and .return (see defineIteratorMethods). + this._invoke = enqueue; + } + + defineIteratorMethods(AsyncIterator.prototype); + AsyncIterator.prototype[asyncIteratorSymbol] = function () { + return this; + }; + exports.AsyncIterator = AsyncIterator; + + // Note that simple async functions are implemented on top of + // AsyncIterator objects; they just return a Promise for the value of + // the final result produced by the iterator. + exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { + if (PromiseImpl === void 0) PromiseImpl = Promise; + + var iter = new AsyncIterator( + wrap(innerFn, outerFn, self, tryLocsList), + PromiseImpl + ); + + return exports.isGeneratorFunction(outerFn) + ? iter // If outerFn is a generator, return the full iterator. + : iter.next().then(function(result) { + return result.done ? result.value : iter.next(); + }); + }; + + function makeInvokeMethod(innerFn, self, context) { + var state = GenStateSuspendedStart; + + return function invoke(method, arg) { + if (state === GenStateExecuting) { + throw new Error("Generator is already running"); + } + + if (state === GenStateCompleted) { + if (method === "throw") { + throw arg; + } + + // Be forgiving, per 25.3.3.3.3 of the spec: + // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume + return doneResult(); + } + + context.method = method; + context.arg = arg; + + while (true) { + var delegate = context.delegate; + if (delegate) { + var delegateResult = maybeInvokeDelegate(delegate, context); + if (delegateResult) { + if (delegateResult === ContinueSentinel) continue; + return delegateResult; + } + } + + if (context.method === "next") { + // Setting context._sent for legacy support of Babel's + // function.sent implementation. + context.sent = context._sent = context.arg; + + } else if (context.method === "throw") { + if (state === GenStateSuspendedStart) { + state = GenStateCompleted; + throw context.arg; + } + + context.dispatchException(context.arg); + + } else if (context.method === "return") { + context.abrupt("return", context.arg); + } + + state = GenStateExecuting; + + var record = tryCatch(innerFn, self, context); + if (record.type === "normal") { + // If an exception is thrown from innerFn, we leave state === + // GenStateExecuting and loop back for another invocation. + state = context.done + ? GenStateCompleted + : GenStateSuspendedYield; + + if (record.arg === ContinueSentinel) { + continue; + } + + return { + value: record.arg, + done: context.done + }; + + } else if (record.type === "throw") { + state = GenStateCompleted; + // Dispatch the exception by looping back around to the + // context.dispatchException(context.arg) call above. + context.method = "throw"; + context.arg = record.arg; + } + } + }; + } + + // Call delegate.iterator[context.method](context.arg) and handle the + // result, either by returning a { value, done } result from the + // delegate iterator, or by modifying context.method and context.arg, + // setting context.delegate to null, and returning the ContinueSentinel. + function maybeInvokeDelegate(delegate, context) { + var method = delegate.iterator[context.method]; + if (method === undefined$1) { + // A .throw or .return when the delegate iterator has no .throw + // method always terminates the yield* loop. + context.delegate = null; + + if (context.method === "throw") { + // Note: ["return"] must be used for ES3 parsing compatibility. + if (delegate.iterator["return"]) { + // If the delegate iterator has a return method, give it a + // chance to clean up. + context.method = "return"; + context.arg = undefined$1; + maybeInvokeDelegate(delegate, context); + + if (context.method === "throw") { + // If maybeInvokeDelegate(context) changed context.method from + // "return" to "throw", let that override the TypeError below. + return ContinueSentinel; + } + } + + context.method = "throw"; + context.arg = new TypeError( + "The iterator does not provide a 'throw' method"); + } + + return ContinueSentinel; + } + + var record = tryCatch(method, delegate.iterator, context.arg); + + if (record.type === "throw") { + context.method = "throw"; + context.arg = record.arg; + context.delegate = null; + return ContinueSentinel; + } + + var info = record.arg; + + if (! info) { + context.method = "throw"; + context.arg = new TypeError("iterator result is not an object"); + context.delegate = null; + return ContinueSentinel; + } + + if (info.done) { + // Assign the result of the finished delegate to the temporary + // variable specified by delegate.resultName (see delegateYield). + context[delegate.resultName] = info.value; + + // Resume execution at the desired location (see delegateYield). + context.next = delegate.nextLoc; + + // If context.method was "throw" but the delegate handled the + // exception, let the outer generator proceed normally. If + // context.method was "next", forget context.arg since it has been + // "consumed" by the delegate iterator. If context.method was + // "return", allow the original .return call to continue in the + // outer generator. + if (context.method !== "return") { + context.method = "next"; + context.arg = undefined$1; + } + + } else { + // Re-yield the result returned by the delegate method. + return info; + } + + // The delegate iterator is finished, so forget it and continue with + // the outer generator. + context.delegate = null; + return ContinueSentinel; + } + + // Define Generator.prototype.{next,throw,return} in terms of the + // unified ._invoke helper method. + defineIteratorMethods(Gp); + + define(Gp, toStringTagSymbol, "Generator"); + + // A Generator should always return itself as the iterator object when the + // @@iterator function is called on it. Some browsers' implementations of the + // iterator prototype chain incorrectly implement this, causing the Generator + // object to not be returned from this call. This ensures that doesn't happen. + // See https://github.com/facebook/regenerator/issues/274 for more details. + Gp[iteratorSymbol] = function() { + return this; + }; + + Gp.toString = function() { + return "[object Generator]"; + }; + + function pushTryEntry(locs) { + var entry = { tryLoc: locs[0] }; + + if (1 in locs) { + entry.catchLoc = locs[1]; + } + + if (2 in locs) { + entry.finallyLoc = locs[2]; + entry.afterLoc = locs[3]; + } + + this.tryEntries.push(entry); + } + + function resetTryEntry(entry) { + var record = entry.completion || {}; + record.type = "normal"; + delete record.arg; + entry.completion = record; + } + + function Context(tryLocsList) { + // The root entry object (effectively a try statement without a catch + // or a finally block) gives us a place to store values thrown from + // locations where there is no enclosing try statement. + this.tryEntries = [{ tryLoc: "root" }]; + tryLocsList.forEach(pushTryEntry, this); + this.reset(true); + } + + exports.keys = function(object) { + var keys = []; + for (var key in object) { + keys.push(key); + } + keys.reverse(); + + // Rather than returning an object with a next method, we keep + // things simple and return the next function itself. + return function next() { + while (keys.length) { + var key = keys.pop(); + if (key in object) { + next.value = key; + next.done = false; + return next; + } + } + + // To avoid creating an additional object, we just hang the .value + // and .done properties off the next function object itself. This + // also ensures that the minifier will not anonymize the function. + next.done = true; + return next; + }; + }; + + function values(iterable) { + if (iterable) { + var iteratorMethod = iterable[iteratorSymbol]; + if (iteratorMethod) { + return iteratorMethod.call(iterable); + } + + if (typeof iterable.next === "function") { + return iterable; + } + + if (!isNaN(iterable.length)) { + var i = -1, next = function next() { + while (++i < iterable.length) { + if (hasOwn.call(iterable, i)) { + next.value = iterable[i]; + next.done = false; + return next; + } + } + + next.value = undefined$1; + next.done = true; + + return next; + }; + + return next.next = next; + } + } + + // Return an iterator with no values. + return { next: doneResult }; + } + exports.values = values; + + function doneResult() { + return { value: undefined$1, done: true }; + } + + Context.prototype = { + constructor: Context, + + reset: function(skipTempReset) { + this.prev = 0; + this.next = 0; + // Resetting context._sent for legacy support of Babel's + // function.sent implementation. + this.sent = this._sent = undefined$1; + this.done = false; + this.delegate = null; + + this.method = "next"; + this.arg = undefined$1; + + this.tryEntries.forEach(resetTryEntry); + + if (!skipTempReset) { + for (var name in this) { + // Not sure about the optimal order of these conditions: + if (name.charAt(0) === "t" && + hasOwn.call(this, name) && + !isNaN(+name.slice(1))) { + this[name] = undefined$1; + } + } + } + }, + + stop: function() { + this.done = true; + + var rootEntry = this.tryEntries[0]; + var rootRecord = rootEntry.completion; + if (rootRecord.type === "throw") { + throw rootRecord.arg; + } + + return this.rval; + }, + + dispatchException: function(exception) { + if (this.done) { + throw exception; + } + + var context = this; + function handle(loc, caught) { + record.type = "throw"; + record.arg = exception; + context.next = loc; + + if (caught) { + // If the dispatched exception was caught by a catch block, + // then let that catch block handle the exception normally. + context.method = "next"; + context.arg = undefined$1; + } + + return !! caught; + } + + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + var record = entry.completion; + + if (entry.tryLoc === "root") { + // Exception thrown outside of any try block that could handle + // it, so set the completion value of the entire function to + // throw the exception. + return handle("end"); + } + + if (entry.tryLoc <= this.prev) { + var hasCatch = hasOwn.call(entry, "catchLoc"); + var hasFinally = hasOwn.call(entry, "finallyLoc"); + + if (hasCatch && hasFinally) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } else if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else if (hasCatch) { + if (this.prev < entry.catchLoc) { + return handle(entry.catchLoc, true); + } + + } else if (hasFinally) { + if (this.prev < entry.finallyLoc) { + return handle(entry.finallyLoc); + } + + } else { + throw new Error("try statement without catch or finally"); + } + } + } + }, + + abrupt: function(type, arg) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc <= this.prev && + hasOwn.call(entry, "finallyLoc") && + this.prev < entry.finallyLoc) { + var finallyEntry = entry; + break; + } + } + + if (finallyEntry && + (type === "break" || + type === "continue") && + finallyEntry.tryLoc <= arg && + arg <= finallyEntry.finallyLoc) { + // Ignore the finally entry if control is not jumping to a + // location outside the try/catch block. + finallyEntry = null; + } + + var record = finallyEntry ? finallyEntry.completion : {}; + record.type = type; + record.arg = arg; + + if (finallyEntry) { + this.method = "next"; + this.next = finallyEntry.finallyLoc; + return ContinueSentinel; + } + + return this.complete(record); + }, + + complete: function(record, afterLoc) { + if (record.type === "throw") { + throw record.arg; + } + + if (record.type === "break" || + record.type === "continue") { + this.next = record.arg; + } else if (record.type === "return") { + this.rval = this.arg = record.arg; + this.method = "return"; + this.next = "end"; + } else if (record.type === "normal" && afterLoc) { + this.next = afterLoc; + } + + return ContinueSentinel; + }, + + finish: function(finallyLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.finallyLoc === finallyLoc) { + this.complete(entry.completion, entry.afterLoc); + resetTryEntry(entry); + return ContinueSentinel; + } + } + }, + + "catch": function(tryLoc) { + for (var i = this.tryEntries.length - 1; i >= 0; --i) { + var entry = this.tryEntries[i]; + if (entry.tryLoc === tryLoc) { + var record = entry.completion; + if (record.type === "throw") { + var thrown = record.arg; + resetTryEntry(entry); + } + return thrown; + } + } + + // The context.catch method must only be called with a location + // argument that corresponds to a known catch block. + throw new Error("illegal catch attempt"); + }, + + delegateYield: function(iterable, resultName, nextLoc) { + this.delegate = { + iterator: values(iterable), + resultName: resultName, + nextLoc: nextLoc + }; + + if (this.method === "next") { + // Deliberately forget the last sent value so that we don't + // accidentally pass it on to the delegate. + this.arg = undefined$1; + } + + return ContinueSentinel; + } + }; + + // Regardless of whether this script is executing as a CommonJS module + // or not, return the runtime object so that we can declare the variable + // regeneratorRuntime in the outer scope, which allows this module to be + // injected easily by `bin/regenerator --include-runtime script.js`. + return exports; + +}( + // If this script is executing as a CommonJS module, use module.exports + // as the regeneratorRuntime namespace. Otherwise create a new empty + // object. Either way, the resulting object will be used to initialize + // the regeneratorRuntime variable at the top of this file. + module.exports +)); + +try { + regeneratorRuntime = runtime; +} catch (accidentalStrictMode) { + // This module should not be running in strict mode, so the above + // assignment should always work unless something is misconfigured. Just + // in case runtime.js accidentally runs in strict mode, we can escape + // strict mode using a global Function call. This could conceivably fail + // if a Content Security Policy forbids using Function, but in that case + // the proper solution is to fix the accidental strict mode problem. If + // you've misconfigured your bundler to force strict mode and applied a + // CSP to forbid Function, and you're not willing to fix either of those + // problems, please detail your unique predicament in a GitHub issue. + Function("r", "regeneratorRuntime = r")(runtime); +} +}); + +var regenerator = runtime_1; + +var arrayWithHoles = createCommonjsModule(function (module) { +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} + +module.exports = _arrayWithHoles; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var iterableToArrayLimit = createCommonjsModule(function (module) { +function _iterableToArrayLimit(arr, i) { + if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; +} + +module.exports = _iterableToArrayLimit; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var arrayLikeToArray = createCommonjsModule(function (module) { +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) { + arr2[i] = arr[i]; + } + + return arr2; +} + +module.exports = _arrayLikeToArray; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var unsupportedIterableToArray = createCommonjsModule(function (module) { +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); +} + +module.exports = _unsupportedIterableToArray; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var nonIterableRest = createCommonjsModule(function (module) { +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +module.exports = _nonIterableRest; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var slicedToArray = createCommonjsModule(function (module) { +function _slicedToArray(arr, i) { + return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); +} + +module.exports = _slicedToArray; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var record = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _regenerator = interopRequireDefault(regenerator); + +var _slicedToArray2 = interopRequireDefault(slicedToArray); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function generateFieldLookup(keys) { + var lookup = {}; + keys.forEach(function (name, idx) { + lookup[name] = idx; + }); + return lookup; +} +/** + * Records make up the contents of the {@link Result}, and is how you access + * the output of a query. A simple query might yield a result stream + * with a single record, for instance: + * + * MATCH (u:User) RETURN u.name, u.age + * + * This returns a stream of records with two fields, named `u.name` and `u.age`, + * each record represents one user found by the query above. You can access + * the values of each field either by name: + * + * record.get("u.name") + * + * Or by it's position: + * + * record.get(0) + * + * @access public + */ + + +var Record = +/*#__PURE__*/ +function () { + /** + * Create a new record object. + * @constructor + * @protected + * @param {string[]} keys An array of field keys, in the order the fields appear in the record + * @param {Array} fields An array of field values + * @param {Object} fieldLookup An object of fieldName -> value index, used to map + * field names to values. If this is null, one will be + * generated. + */ + function Record(keys, fields) { + var fieldLookup = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + (0, _classCallCheck2["default"])(this, Record); + + /** + * Field keys, in the order the fields appear in the record. + * @type {string[]} + */ + this.keys = keys; + /** + * Number of fields + * @type {Number} + */ + + this.length = keys.length; + this._fields = fields; + this._fieldLookup = fieldLookup || generateFieldLookup(keys); + } + /** + * Run the given function for each field in this record. The function + * will get three arguments - the value, the key and this record, in that + * order. + * + * @param {function(value: Object, key: string, record: Record)} visitor the function to apply to each field. + */ + + + (0, _createClass2["default"])(Record, [{ + key: "forEach", + value: function forEach(visitor) { + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = this.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _step$value = (0, _slicedToArray2["default"])(_step.value, 2), + key = _step$value[0], + value = _step$value[1]; + + visitor(value, key, this); + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator["return"] != null) { + _iterator["return"](); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + } + /** + * Run the given function for each field in this record. The function + * will get three arguments - the value, the key and this record, in that + * order. + * + * @param {function(value: Object, key: string, record: Record)} visitor the function to apply on each field + * and return a value that is saved to the returned Array. + * + * @returns {Array} + */ + + }, { + key: "map", + value: function map(visitor) { + var resultArray = []; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = this.entries()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var _step2$value = (0, _slicedToArray2["default"])(_step2.value, 2), + key = _step2$value[0], + value = _step2$value[1]; + + resultArray.push(visitor(value, key, this)); + } + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { + _iterator2["return"](); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + return resultArray; + } + /** + * Iterate over results. Each iteration will yield an array + * of exactly two items - the key, and the value (in order). + * + * @generator + * @returns {IterableIterator} + */ + + }, { + key: "entries", + value: + /*#__PURE__*/ + _regenerator["default"].mark(function entries() { + var i; + return _regenerator["default"].wrap(function entries$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + i = 0; + + case 1: + if (!(i < this.keys.length)) { + _context.next = 7; + break; + } + + _context.next = 4; + return [this.keys[i], this._fields[i]]; + + case 4: + i++; + _context.next = 1; + break; + + case 7: + case "end": + return _context.stop(); + } + } + }, entries, this); + }) + /** + * Iterate over values. + * + * @generator + * @returns {IterableIterator} + */ + + }, { + key: "values", + value: + /*#__PURE__*/ + _regenerator["default"].mark(function values() { + var i; + return _regenerator["default"].wrap(function values$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + i = 0; + + case 1: + if (!(i < this.keys.length)) { + _context2.next = 7; + break; + } + + _context2.next = 4; + return this._fields[i]; + + case 4: + i++; + _context2.next = 1; + break; + + case 7: + case "end": + return _context2.stop(); + } + } + }, values, this); + }) + /** + * Iterate over values. Delegates to {@link Record#values} + * + * @generator + * @returns {IterableIterator} + */ + + }, { + key: Symbol.iterator, + value: + /*#__PURE__*/ + _regenerator["default"].mark(function value() { + return _regenerator["default"].wrap(function value$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + return _context3.delegateYield(this.values(), "t0", 1); + + case 1: + case "end": + return _context3.stop(); + } + } + }, value, this); + }) + /** + * Generates an object out of the current Record + * + * @returns {Object} + */ + + }, { + key: "toObject", + value: function toObject() { + var object = {}; + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = this.entries()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _step3$value = (0, _slicedToArray2["default"])(_step3.value, 2), + key = _step3$value[0], + _value = _step3$value[1]; + + object[key] = _value; + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) { + _iterator3["return"](); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + return object; + } + /** + * Get a value from this record, either by index or by field key. + * + * @param {string|Number} key Field key, or the index of the field. + * @returns {*} + */ + + }, { + key: "get", + value: function get(key) { + var index; + + if (!(typeof key === 'number')) { + index = this._fieldLookup[key]; + + if (index === undefined) { + throw (0, error.newError)("This record has no field with key '" + key + "', available key are: [" + this.keys + '].'); + } + } else { + index = key; + } + + if (index > this._fields.length - 1 || index < 0) { + throw (0, error.newError)("This record has no field with index '" + index + "'. Remember that indexes start at `0`, " + 'and make sure your query returns records in the shape you meant it to.'); + } + + return this._fields[index]; + } + /** + * Check if a value from this record, either by index or by field key, exists. + * + * @param {string|Number} key Field key, or the index of the field. + * @returns {boolean} + */ + + }, { + key: "has", + value: function has(key) { + // if key is a number, we check if it is in the _fields array + if (typeof key === 'number') { + return key >= 0 && key < this._fields.length; + } // if it's not a number, we check _fieldLookup dictionary directly + + + return this._fieldLookup[key] !== undefined; + } + }]); + return Record; +}(); + +var _default = Record; +exports["default"] = _default; +}); + +var assertDatabaseIsEmpty_1 = assertDatabaseIsEmpty; +var assertTxConfigIsEmpty_1 = assertTxConfigIsEmpty; + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @param {TxConfig} txConfig the auto-commit transaction configuration. + * @param {Connection} connection the connection. + * @param {ResultStreamObserver} observer the response observer. + */ +function assertTxConfigIsEmpty(txConfig, connection, observer) { + if (txConfig && !txConfig.isEmpty()) { + var error$1 = (0, error.newError)('Driver is connected to the database that does not support transaction configuration. ' + 'Please upgrade to neo4j 3.5.0 or later in order to use this functionality'); // unsupported API was used, consider this a fatal error for the current connection + + connection._handleFatalError(error$1); + + observer.onError(error$1); + throw error$1; + } +} +/** + * Asserts that the passed-in database name is empty. + * @param {string} database + * @param {Connection} connection + */ + + +function assertDatabaseIsEmpty(database, connection, observer) { + if (database) { + var error$1 = (0, error.newError)('Driver is connected to the database that does not support multiple databases. ' + 'Please upgrade to neo4j 4.0.0 or later in order to use this functionality'); // unsupported API was used, consider this a fatal error for the current connection + + connection._handleFatalError(error$1); + + observer.onError(error$1); + throw error$1; + } +} + +var boltProtocolUtil = /*#__PURE__*/Object.defineProperty({ + assertDatabaseIsEmpty: assertDatabaseIsEmpty_1, + assertTxConfigIsEmpty: assertTxConfigIsEmpty_1 +}, '__esModule', {value: true}); + +var baseBuf = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Common base with default implementation for most buffer methods. + * Buffers are stateful - they track a current "position", this helps greatly + * when reading and writing from them incrementally. You can also ignore the + * stateful read/write methods. + * readXXX and writeXXX-methods move the inner position of the buffer. + * putXXX and getXXX-methods do not. + * @access private + */ +var BaseBuffer = +/*#__PURE__*/ +function () { + /** + * Create a instance with the injected size. + * @constructor + * @param {Integer} size + */ + function BaseBuffer(size) { + (0, _classCallCheck2["default"])(this, BaseBuffer); + this.position = 0; + this.length = size; + } + + (0, _createClass2["default"])(BaseBuffer, [{ + key: "getUInt8", + value: function getUInt8(position) { + throw new Error('Not implemented'); + } + }, { + key: "getInt8", + value: function getInt8(position) { + throw new Error('Not implemented'); + } + }, { + key: "getFloat64", + value: function getFloat64(position) { + throw new Error('Not implemented'); + } + }, { + key: "putUInt8", + value: function putUInt8(position, val) { + throw new Error('Not implemented'); + } + }, { + key: "putInt8", + value: function putInt8(position, val) { + throw new Error('Not implemented'); + } + }, { + key: "putFloat64", + value: function putFloat64(position, val) { + throw new Error('Not implemented'); + } + /** + * @param p + */ + + }, { + key: "getInt16", + value: function getInt16(p) { + return this.getInt8(p) << 8 | this.getUInt8(p + 1); + } + /** + * @param p + */ + + }, { + key: "getUInt16", + value: function getUInt16(p) { + return this.getUInt8(p) << 8 | this.getUInt8(p + 1); + } + /** + * @param p + */ + + }, { + key: "getInt32", + value: function getInt32(p) { + return this.getInt8(p) << 24 | this.getUInt8(p + 1) << 16 | this.getUInt8(p + 2) << 8 | this.getUInt8(p + 3); + } + /** + * @param p + */ + + }, { + key: "getUInt32", + value: function getUInt32(p) { + return this.getUInt8(p) << 24 | this.getUInt8(p + 1) << 16 | this.getUInt8(p + 2) << 8 | this.getUInt8(p + 3); + } + /** + * @param p + */ + + }, { + key: "getInt64", + value: function getInt64(p) { + return this.getInt8(p) << 56 | this.getUInt8(p + 1) << 48 | this.getUInt8(p + 2) << 40 | this.getUInt8(p + 3) << 32 | this.getUInt8(p + 4) << 24 | this.getUInt8(p + 5) << 16 | this.getUInt8(p + 6) << 8 | this.getUInt8(p + 7); + } + /** + * Get a slice of this buffer. This method does not copy any data, + * but simply provides a slice view of this buffer + * @param start + * @param length + */ + + }, { + key: "getSlice", + value: function getSlice(start, length) { + return new SliceBuffer(start, length, this); + } + /** + * @param p + * @param val + */ + + }, { + key: "putInt16", + value: function putInt16(p, val) { + this.putInt8(p, val >> 8); + this.putUInt8(p + 1, val & 0xff); + } + /** + * @param p + * @param val + */ + + }, { + key: "putUInt16", + value: function putUInt16(p, val) { + this.putUInt8(p, val >> 8 & 0xff); + this.putUInt8(p + 1, val & 0xff); + } + /** + * @param p + * @param val + */ + + }, { + key: "putInt32", + value: function putInt32(p, val) { + this.putInt8(p, val >> 24); + this.putUInt8(p + 1, val >> 16 & 0xff); + this.putUInt8(p + 2, val >> 8 & 0xff); + this.putUInt8(p + 3, val & 0xff); + } + /** + * @param p + * @param val + */ + + }, { + key: "putUInt32", + value: function putUInt32(p, val) { + this.putUInt8(p, val >> 24 & 0xff); + this.putUInt8(p + 1, val >> 16 & 0xff); + this.putUInt8(p + 2, val >> 8 & 0xff); + this.putUInt8(p + 3, val & 0xff); + } + /** + * @param p + * @param val + */ + + }, { + key: "putInt64", + value: function putInt64(p, val) { + this.putInt8(p, val >> 48); + this.putUInt8(p + 1, val >> 42 & 0xff); + this.putUInt8(p + 2, val >> 36 & 0xff); + this.putUInt8(p + 3, val >> 30 & 0xff); + this.putUInt8(p + 4, val >> 24 & 0xff); + this.putUInt8(p + 5, val >> 16 & 0xff); + this.putUInt8(p + 6, val >> 8 & 0xff); + this.putUInt8(p + 7, val & 0xff); + } + /** + * @param position + * @param other + */ + + }, { + key: "putBytes", + value: function putBytes(position, other) { + for (var i = 0, end = other.remaining(); i < end; i++) { + this.putUInt8(position + i, other.readUInt8()); + } + } + /** + * Read from state position. + */ + + }, { + key: "readUInt8", + value: function readUInt8() { + return this.getUInt8(this._updatePos(1)); + } + /** + * Read from state position. + */ + + }, { + key: "readInt8", + value: function readInt8() { + return this.getInt8(this._updatePos(1)); + } + /** + * Read from state position. + */ + + }, { + key: "readUInt16", + value: function readUInt16() { + return this.getUInt16(this._updatePos(2)); + } + /** + * Read from state position. + */ + + }, { + key: "readUInt32", + value: function readUInt32() { + return this.getUInt32(this._updatePos(4)); + } + /** + * Read from state position. + */ + + }, { + key: "readInt16", + value: function readInt16() { + return this.getInt16(this._updatePos(2)); + } + /** + * Read from state position. + */ + + }, { + key: "readInt32", + value: function readInt32() { + return this.getInt32(this._updatePos(4)); + } + /** + * Read from state position. + */ + + }, { + key: "readInt64", + value: function readInt64() { + return this.getInt32(this._updatePos(8)); + } + /** + * Read from state position. + */ + + }, { + key: "readFloat64", + value: function readFloat64() { + return this.getFloat64(this._updatePos(8)); + } + /** + * Write to state position. + * @param val + */ + + }, { + key: "writeUInt8", + value: function writeUInt8(val) { + this.putUInt8(this._updatePos(1), val); + } + /** + * Write to state position. + * @param val + */ + + }, { + key: "writeInt8", + value: function writeInt8(val) { + this.putInt8(this._updatePos(1), val); + } + /** + * Write to state position. + * @param val + */ + + }, { + key: "writeInt16", + value: function writeInt16(val) { + this.putInt16(this._updatePos(2), val); + } + /** + * Write to state position. + * @param val + */ + + }, { + key: "writeInt32", + value: function writeInt32(val) { + this.putInt32(this._updatePos(4), val); + } + /** + * Write to state position. + * @param val + */ + + }, { + key: "writeUInt32", + value: function writeUInt32(val) { + this.putUInt32(this._updatePos(4), val); + } + /** + * Write to state position. + * @param val + */ + + }, { + key: "writeInt64", + value: function writeInt64(val) { + this.putInt64(this._updatePos(8), val); + } + /** + * Write to state position. + * @param val + */ + + }, { + key: "writeFloat64", + value: function writeFloat64(val) { + this.putFloat64(this._updatePos(8), val); + } + /** + * Write to state position. + * @param val + */ + + }, { + key: "writeBytes", + value: function writeBytes(val) { + this.putBytes(this._updatePos(val.remaining()), val); + } + /** + * Get a slice of this buffer. This method does not copy any data, + * but simply provides a slice view of this buffer + * @param length + */ + + }, { + key: "readSlice", + value: function readSlice(length) { + return this.getSlice(this._updatePos(length), length); + } + }, { + key: "_updatePos", + value: function _updatePos(length) { + var p = this.position; + this.position += length; + return p; + } + /** + * Get remaining + */ + + }, { + key: "remaining", + value: function remaining() { + return this.length - this.position; + } + /** + * Has remaining + */ + + }, { + key: "hasRemaining", + value: function hasRemaining() { + return this.remaining() > 0; + } + /** + * Reset position state + */ + + }, { + key: "reset", + value: function reset() { + this.position = 0; + } + /** + * Get string representation of buffer and it's state. + * @return {string} Buffer as a string + */ + + }, { + key: "toString", + value: function toString() { + return this.constructor.name + '( position=' + this.position + ' )\n ' + this.toHex(); + } + /** + * Get string representation of buffer. + * @return {string} Buffer as a string + */ + + }, { + key: "toHex", + value: function toHex() { + var out = ''; + + for (var i = 0; i < this.length; i++) { + var hexByte = this.getUInt8(i).toString(16); + + if (hexByte.length === 1) { + hexByte = '0' + hexByte; + } + + out += hexByte; + + if (i !== this.length - 1) { + out += ' '; + } + } + + return out; + } + }]); + return BaseBuffer; +}(); +/** + * Represents a view as slice of another buffer. + * @access private + */ + + +exports["default"] = BaseBuffer; + +var SliceBuffer = +/*#__PURE__*/ +function (_BaseBuffer) { + (0, _inherits2["default"])(SliceBuffer, _BaseBuffer); + + function SliceBuffer(start, length, inner) { + var _this; + + (0, _classCallCheck2["default"])(this, SliceBuffer); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(SliceBuffer).call(this, length)); + _this._start = start; + _this._inner = inner; + return _this; + } + + (0, _createClass2["default"])(SliceBuffer, [{ + key: "putUInt8", + value: function putUInt8(position, val) { + this._inner.putUInt8(this._start + position, val); + } + }, { + key: "getUInt8", + value: function getUInt8(position) { + return this._inner.getUInt8(this._start + position); + } + }, { + key: "putInt8", + value: function putInt8(position, val) { + this._inner.putInt8(this._start + position, val); + } + }, { + key: "putFloat64", + value: function putFloat64(position, val) { + this._inner.putFloat64(this._start + position, val); + } + }, { + key: "getInt8", + value: function getInt8(position) { + return this._inner.getInt8(this._start + position); + } + }, { + key: "getFloat64", + value: function getFloat64(position) { + return this._inner.getFloat64(this._start + position); + } + }]); + return SliceBuffer; +}(BaseBuffer); +}); + +var nodeBuf = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _get2 = interopRequireDefault(get$1); + +var _inherits2 = interopRequireDefault(inherits); + +var _buffer = interopRequireDefault(require$$6__default['default']); + +var _baseBuf = interopRequireDefault(baseBuf); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var NodeBuffer = +/*#__PURE__*/ +function (_BaseBuffer) { + (0, _inherits2["default"])(NodeBuffer, _BaseBuffer); + + function NodeBuffer(arg) { + var _this; + + (0, _classCallCheck2["default"])(this, NodeBuffer); + var buffer = newNodeJSBuffer(arg); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(NodeBuffer).call(this, buffer.length)); + _this._buffer = buffer; + return _this; + } + + (0, _createClass2["default"])(NodeBuffer, [{ + key: "getUInt8", + value: function getUInt8(position) { + return this._buffer.readUInt8(position); + } + }, { + key: "getInt8", + value: function getInt8(position) { + return this._buffer.readInt8(position); + } + }, { + key: "getFloat64", + value: function getFloat64(position) { + return this._buffer.readDoubleBE(position); + } + }, { + key: "putUInt8", + value: function putUInt8(position, val) { + this._buffer.writeUInt8(val, position); + } + }, { + key: "putInt8", + value: function putInt8(position, val) { + this._buffer.writeInt8(val, position); + } + }, { + key: "putFloat64", + value: function putFloat64(position, val) { + this._buffer.writeDoubleBE(val, position); + } + }, { + key: "putBytes", + value: function putBytes(position, val) { + if (val instanceof NodeBuffer) { + var bytesToCopy = Math.min(val.length - val.position, this.length - position); + + val._buffer.copy(this._buffer, position, val.position, val.position + bytesToCopy); + + val.position += bytesToCopy; + } else { + (0, _get2["default"])((0, _getPrototypeOf2["default"])(NodeBuffer.prototype), "putBytes", this).call(this, position, val); + } + } + }, { + key: "getSlice", + value: function getSlice(start, length) { + return new NodeBuffer(this._buffer.slice(start, start + length)); + } + }]); + return NodeBuffer; +}(_baseBuf["default"]); + +exports["default"] = NodeBuffer; + +function newNodeJSBuffer(arg) { + if (arg instanceof _buffer["default"].Buffer) { + return arg; + } else if (typeof arg === 'number' && typeof _buffer["default"].Buffer.alloc === 'function') { + // use static factory function present in newer NodeJS versions to allocate new buffer with specified size + return _buffer["default"].Buffer.alloc(arg); + } else { + // fallback to the old, potentially deprecated constructor + // eslint-disable-next-line node/no-deprecated-api + return new _buffer["default"].Buffer(arg); + } +} +}); + +var nodeChannel = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _net = interopRequireDefault(require$$2__default['default']); + +var _tls = interopRequireDefault(require$$3__default['default']); + +var _fs = interopRequireDefault(require$$4__default['default']); + +var _nodeBuf = interopRequireDefault(nodeBuf); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var _CONNECTION_IDGEN = 0; +var TrustStrategy = { + TRUST_CUSTOM_CA_SIGNED_CERTIFICATES: function TRUST_CUSTOM_CA_SIGNED_CERTIFICATES(config, onSuccess, onFailure) { + if (!config.trustedCertificates || config.trustedCertificates.length === 0) { + onFailure((0, error.newError)('You are using TRUST_CUSTOM_CA_SIGNED_CERTIFICATES as the method ' + 'to verify trust for encrypted connections, but have not configured any ' + 'trustedCertificates. You must specify the path to at least one trusted ' + 'X.509 certificate for this to work. Two other alternatives is to use ' + 'TRUST_ALL_CERTIFICATES or to disable encryption by setting encrypted="' + util.ENCRYPTION_OFF + '"' + 'in your driver configuration.')); + return; + } + + var tlsOpts = newTlsOptions(config.address.host(), config.trustedCertificates.map(function (f) { + return _fs["default"].readFileSync(f); + })); + + var socket = _tls["default"].connect(config.address.port(), config.address.resolvedHost(), tlsOpts, function () { + if (!socket.authorized) { + onFailure((0, error.newError)('Server certificate is not trusted. If you trust the database you are connecting to, add' + ' the signing certificate, or the server certificate, to the list of certificates trusted by this driver' + " using `neo4j.driver(.., { trustedCertificates:['path/to/certificate.crt']}). This " + ' is a security measure to protect against man-in-the-middle attacks. If you are just trying ' + ' Neo4j out and are not concerned about encryption, simply disable it using `encrypted="' + util.ENCRYPTION_OFF + '"`' + ' in the driver options. Socket responded with: ' + socket.authorizationError)); + } else { + onSuccess(); + } + }); + + socket.on('error', onFailure); + return configureSocket(socket); + }, + TRUST_SYSTEM_CA_SIGNED_CERTIFICATES: function TRUST_SYSTEM_CA_SIGNED_CERTIFICATES(config, onSuccess, onFailure) { + var tlsOpts = newTlsOptions(config.address.host()); + + var socket = _tls["default"].connect(config.address.port(), config.address.resolvedHost(), tlsOpts, function () { + if (!socket.authorized) { + onFailure((0, error.newError)('Server certificate is not trusted. If you trust the database you are connecting to, use ' + 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES and add' + ' the signing certificate, or the server certificate, to the list of certificates trusted by this driver' + " using `neo4j.driver(.., { trustedCertificates:['path/to/certificate.crt']}). This " + ' is a security measure to protect against man-in-the-middle attacks. If you are just trying ' + ' Neo4j out and are not concerned about encryption, simply disable it using `encrypted="' + util.ENCRYPTION_OFF + '"`' + ' in the driver options. Socket responded with: ' + socket.authorizationError)); + } else { + onSuccess(); + } + }); + + socket.on('error', onFailure); + return configureSocket(socket); + }, + TRUST_ALL_CERTIFICATES: function TRUST_ALL_CERTIFICATES(config, onSuccess, onFailure) { + var tlsOpts = newTlsOptions(config.address.host()); + + var socket = _tls["default"].connect(config.address.port(), config.address.resolvedHost(), tlsOpts, function () { + var certificate = socket.getPeerCertificate(); + + if ((0, util.isEmptyObjectOrNull)(certificate)) { + onFailure((0, error.newError)('Secure connection was successful but server did not return any valid ' + 'certificates. Such connection can not be trusted. If you are just trying ' + ' Neo4j out and are not concerned about encryption, simply disable it using ' + '`encrypted="' + util.ENCRYPTION_OFF + '"` in the driver options. ' + 'Socket responded with: ' + socket.authorizationError)); + } else { + onSuccess(); + } + }); + + socket.on('error', onFailure); + return configureSocket(socket); + } + /** + * Connect using node socket. + * @param {ChannelConfig} config - configuration of this channel. + * @param {function} onSuccess - callback to execute on connection success. + * @param {function} onFailure - callback to execute on connection failure. + * @return {*} socket connection. + */ + +}; + +function connect(config, onSuccess) { + var onFailure = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () { + return null; + }; + var trustStrategy = trustStrategyName(config); + + if (!isEncrypted(config)) { + var socket = _net["default"].connect(config.address.port(), config.address.resolvedHost(), onSuccess); + + socket.on('error', onFailure); + return configureSocket(socket); + } else if (TrustStrategy[trustStrategy]) { + return TrustStrategy[trustStrategy](config, onSuccess, onFailure); + } else { + onFailure((0, error.newError)('Unknown trust strategy: ' + config.trust + '. Please use either ' + "trust:'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' or trust:'TRUST_ALL_CERTIFICATES' in your driver " + 'configuration. Alternatively, you can disable encryption by setting ' + '`encrypted:"' + util.ENCRYPTION_OFF + '"`. There is no mechanism to use encryption without trust verification, ' + 'because this incurs the overhead of encryption without improving security. If ' + 'the driver does not verify that the peer it is connected to is really Neo4j, it ' + 'is very easy for an attacker to bypass the encryption by pretending to be Neo4j.')); + } +} + +function isEncrypted(config) { + var encryptionNotConfigured = config.encrypted == null || config.encrypted === undefined; + + if (encryptionNotConfigured) { + // default to using encryption if trust-all-certificates is available + return false; + } + + return config.encrypted === true || config.encrypted === util.ENCRYPTION_ON; +} + +function trustStrategyName(config) { + if (config.trust) { + return config.trust; + } + + return 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'; +} +/** + * Create a new configuration options object for the {@code tls.connect()} call. + * @param {string} hostname the target hostname. + * @param {string|undefined} ca an optional CA. + * @return {Object} a new options object. + */ + + +function newTlsOptions(hostname) { + var ca = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + return { + rejectUnauthorized: false, + // we manually check for this in the connect callback, to give a more helpful error to the user + servername: hostname, + // server name for the SNI (Server Name Indication) TLS extension + ca: ca // optional CA useful for TRUST_CUSTOM_CA_SIGNED_CERTIFICATES trust mode + + }; +} +/** + * Update socket options for the newly created socket. Accepts either `net.Socket` or its subclass `tls.TLSSocket`. + * @param {net.Socket} socket the socket to configure. + * @return {net.Socket} the given socket. + */ + + +function configureSocket(socket) { + socket.setKeepAlive(true); + return socket; +} +/** + * In a Node.js environment the 'net' module is used + * as transport. + * @access private + */ + + +var NodeChannel = +/*#__PURE__*/ +function () { + /** + * Create new instance + * @param {ChannelConfig} config - configuration for this channel. + */ + function NodeChannel(config) { + (0, _classCallCheck2["default"])(this, NodeChannel); + var self = this; + this.id = _CONNECTION_IDGEN++; + this._pending = []; + this._open = true; + this._error = null; + this._handleConnectionError = this._handleConnectionError.bind(this); + this._handleConnectionTerminated = this._handleConnectionTerminated.bind(this); + this._connectionErrorCode = config.connectionErrorCode; + this._conn = connect(config, function () { + if (!self._open) { + return; + } + + self._conn.on('data', function (buffer) { + if (self.onmessage) { + self.onmessage(new _nodeBuf["default"](buffer)); + } + }); + + self._conn.on('error', self._handleConnectionError); + + self._conn.on('end', self._handleConnectionTerminated); // Drain all pending messages + + + var pending = self._pending; + self._pending = null; + + for (var i = 0; i < pending.length; i++) { + self.write(pending[i]); + } + }, this._handleConnectionError); + + this._setupConnectionTimeout(config, this._conn); + } + + (0, _createClass2["default"])(NodeChannel, [{ + key: "_handleConnectionError", + value: function _handleConnectionError(err) { + var msg = 'Failed to connect to server. ' + 'Please ensure that your database is listening on the correct host and port ' + 'and that you have compatible encryption settings both on Neo4j server and driver. ' + 'Note that the default encryption setting has changed in Neo4j 4.0.'; + if (err.message) msg += ' Caused by: ' + err.message; + this._error = (0, error.newError)(msg, this._connectionErrorCode); + + if (this.onerror) { + this.onerror(this._error); + } + } + }, { + key: "_handleConnectionTerminated", + value: function _handleConnectionTerminated() { + this._open = false; + this._error = (0, error.newError)('Connection was closed by server', this._connectionErrorCode); + + if (this.onerror) { + this.onerror(this._error); + } + } + /** + * Setup connection timeout on the socket, if configured. + * @param {ChannelConfig} config - configuration of this channel. + * @param {Object} socket - `net.Socket` or `tls.TLSSocket` object. + * @private + */ + + }, { + key: "_setupConnectionTimeout", + value: function _setupConnectionTimeout(config, socket) { + var timeout = config.connectionTimeout; + + if (timeout) { + socket.on('connect', function () { + // connected - clear connection timeout + socket.setTimeout(0); + }); + socket.on('timeout', function () { + // timeout fired - not connected within configured time. cancel timeout and destroy socket + socket.setTimeout(0); + socket.destroy((0, error.newError)("Failed to establish connection in ".concat(timeout, "ms"), config.connectionErrorCode)); + }); + socket.setTimeout(timeout); + } + } + /** + * Write the passed in buffer to connection + * @param {NodeBuffer} buffer - Buffer to write + */ + + }, { + key: "write", + value: function write(buffer) { + // If there is a pending queue, push this on that queue. This means + // we are not yet connected, so we queue things locally. + if (this._pending !== null) { + this._pending.push(buffer); + } else if (buffer instanceof _nodeBuf["default"]) { + this._conn.write(buffer._buffer); + } else { + throw (0, error.newError)("Don't know how to write: " + buffer); + } + } + /** + * Close the connection + * @returns {Promise} A promise that will be resolved after channel is closed + */ + + }, { + key: "close", + value: function close() { + var _this = this; + + return new Promise(function (resolve, reject) { + var cleanup = function cleanup() { + if (!_this._conn.destroyed) { + _this._conn.destroy(); + } + + resolve(); + }; + + if (_this._open) { + _this._open = false; + + _this._conn.removeListener('end', _this._handleConnectionTerminated); + + _this._conn.on('end', function () { + return cleanup(); + }); + + _this._conn.on('close', function () { + return cleanup(); + }); + + _this._conn.end(); + + _this._conn.destroy(); + } else { + cleanup(); + } + }); + } + }]); + return NodeChannel; +}(); + +exports["default"] = NodeChannel; +}); + +var baseHostNameResolver = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var BaseHostNameResolver = +/*#__PURE__*/ +function () { + function BaseHostNameResolver() { + (0, _classCallCheck2["default"])(this, BaseHostNameResolver); + } + + (0, _createClass2["default"])(BaseHostNameResolver, [{ + key: "resolve", + value: function resolve() { + throw new Error('Abstract function'); + } + /** + * @protected + */ + + }, { + key: "_resolveToItself", + value: function _resolveToItself(address) { + return Promise.resolve([address]); + } + }]); + return BaseHostNameResolver; +}(); + +exports["default"] = BaseHostNameResolver; +}); + +var nodeHostNameResolver = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _baseHostNameResolver = interopRequireDefault(baseHostNameResolver); + +var _dns = interopRequireDefault(require$$6__default$1['default']); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var NodeHostNameResolver = +/*#__PURE__*/ +function (_BaseHostNameResolver) { + (0, _inherits2["default"])(NodeHostNameResolver, _BaseHostNameResolver); + + function NodeHostNameResolver() { + (0, _classCallCheck2["default"])(this, NodeHostNameResolver); + return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(NodeHostNameResolver).apply(this, arguments)); + } + + (0, _createClass2["default"])(NodeHostNameResolver, [{ + key: "resolve", + value: function resolve(address) { + return new Promise(function (resolve) { + _dns["default"].lookup(address.host(), { + all: true + }, function (error, resolvedTo) { + if (error) { + resolve([address]); + } else { + var resolvedAddresses = resolvedTo.map(function (a) { + return address.resolveWith(a.address); + }); + resolve(resolvedAddresses); + } + }); + }); + } + }]); + return NodeHostNameResolver; +}(_baseHostNameResolver["default"]); + +exports["default"] = NodeHostNameResolver; +}); + +var combinedBuf = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _baseBuf = interopRequireDefault(baseBuf); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Buffer that combines multiple buffers, exposing them as one single buffer. + */ +var CombinedBuffer = +/*#__PURE__*/ +function (_BaseBuffer) { + (0, _inherits2["default"])(CombinedBuffer, _BaseBuffer); + + function CombinedBuffer(buffers) { + var _this; + + (0, _classCallCheck2["default"])(this, CombinedBuffer); + var length = 0; + + for (var i = 0; i < buffers.length; i++) { + length += buffers[i].length; + } + + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(CombinedBuffer).call(this, length)); + _this._buffers = buffers; + return _this; + } + + (0, _createClass2["default"])(CombinedBuffer, [{ + key: "getUInt8", + value: function getUInt8(position) { + // Surely there's a faster way to do this.. some sort of lookup table thing? + for (var i = 0; i < this._buffers.length; i++) { + var buffer = this._buffers[i]; // If the position is not in the current buffer, skip the current buffer + + if (position >= buffer.length) { + position -= buffer.length; + } else { + return buffer.getUInt8(position); + } + } + } + }, { + key: "getInt8", + value: function getInt8(position) { + // Surely there's a faster way to do this.. some sort of lookup table thing? + for (var i = 0; i < this._buffers.length; i++) { + var buffer = this._buffers[i]; // If the position is not in the current buffer, skip the current buffer + + if (position >= buffer.length) { + position -= buffer.length; + } else { + return buffer.getInt8(position); + } + } + } + }, { + key: "getFloat64", + value: function getFloat64(position) { + // At some point, a more efficient impl. For now, we copy the 8 bytes + // we want to read and depend on the platform impl of IEEE 754. + var b = (0, node.alloc)(8); + + for (var i = 0; i < 8; i++) { + b.putUInt8(i, this.getUInt8(position + i)); + } + + return b.getFloat64(0); + } + }]); + return CombinedBuffer; +}(_baseBuf["default"]); + +exports["default"] = CombinedBuffer; +}); + +var nodeUtf8 = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _combinedBuf = interopRequireDefault(combinedBuf); + +var _nodeBuf = interopRequireDefault(nodeBuf); + + + +var _buffer = interopRequireDefault(require$$6__default['default']); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var decoder = new _string_decoder__default['default'].StringDecoder('utf8'); + +function encode(str) { + return new _nodeBuf["default"](newNodeJSBuffer(str)); +} + +function decode(buffer, length) { + if (buffer instanceof _nodeBuf["default"]) { + return decodeNodeBuffer(buffer, length); + } else if (buffer instanceof _combinedBuf["default"]) { + return decodeCombinedBuffer(buffer, length); + } else { + throw (0, error.newError)("Don't know how to decode strings from '".concat(buffer, "'")); + } +} + +function decodeNodeBuffer(buffer, length) { + var start = buffer.position; + var end = start + length; + buffer.position = Math.min(end, buffer.length); + return buffer._buffer.toString('utf8', start, end); +} + +function decodeCombinedBuffer(buffer, length) { + return streamDecodeCombinedBuffer(buffer, length, function (partBuffer) { + return decoder.write(partBuffer._buffer); + }, function () { + return decoder.end(); + }); +} + +function streamDecodeCombinedBuffer(combinedBuffers, length, decodeFn, endFn) { + var remainingBytesToRead = length; + var position = combinedBuffers.position; + + combinedBuffers._updatePos(Math.min(length, combinedBuffers.length - position)); // Reduce CombinedBuffers to a decoded string + + + var out = combinedBuffers._buffers.reduce(function (last, partBuffer) { + if (remainingBytesToRead <= 0) { + return last; + } else if (position >= partBuffer.length) { + position -= partBuffer.length; + return ''; + } else { + partBuffer._updatePos(position - partBuffer.position); + + var bytesToRead = Math.min(partBuffer.length - position, remainingBytesToRead); + var lastSlice = partBuffer.readSlice(bytesToRead); + + partBuffer._updatePos(bytesToRead); + + remainingBytesToRead = Math.max(remainingBytesToRead - lastSlice.length, 0); + position = 0; + return last + decodeFn(lastSlice); + } + }, ''); + + return out + endFn(); +} + +function newNodeJSBuffer(str) { + // use static factory function present in newer NodeJS versions to create a buffer containing the given string + // or fallback to the old, potentially deprecated constructor + if (typeof _buffer["default"].Buffer.from === 'function') { + return _buffer["default"].Buffer.from(str, 'utf8'); + } else { + // eslint-disable-next-line node/no-deprecated-api + return new _buffer["default"].Buffer(str, 'utf8'); + } +} + +var _default = { + encode: encode, + decode: decode +}; +exports["default"] = _default; +}); + +var node = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.utf8 = exports.HostNameResolver = exports.Channel = exports.alloc = void 0; + +var _nodeBuf = interopRequireDefault(nodeBuf); + +var _nodeChannel = interopRequireDefault(nodeChannel); + +var _nodeHostNameResolver = interopRequireDefault(nodeHostNameResolver); + +var _nodeUtf = interopRequireDefault(nodeUtf8); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + +This module exports a set of components to be used in NodeJS environment. +They are not compatible with browser environment. +All files that require environment-dependent APIs should import this file by default. +Imports/requires are replaced at build time with `browser/index.js` when building a browser bundle. + +NOTE: exports in this module should have exactly the same names/structure as exports in `browser/index.js`. + + */ +var alloc = function alloc(arg) { + return new _nodeBuf["default"](arg); +}; + +exports.alloc = alloc; +var Channel = _nodeChannel["default"]; +exports.Channel = Channel; +var HostNameResolver = _nodeHostNameResolver["default"]; +exports.HostNameResolver = HostNameResolver; +var utf8 = _nodeUtf["default"]; +exports.utf8 = utf8; +}); + +var chunking = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Dechunker = exports.Chunker = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _baseBuf = interopRequireDefault(baseBuf); + + + +var _combinedBuf = interopRequireDefault(combinedBuf); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var _CHUNK_HEADER_SIZE = 2; +var _MESSAGE_BOUNDARY = 0x00; +var _DEFAULT_BUFFER_SIZE = 1400; // http://stackoverflow.com/questions/2613734/maximum-packet-size-for-a-tcp-connection + +/** + * Looks like a writable buffer, chunks output transparently into a channel below. + * @access private + */ + +var Chunker = +/*#__PURE__*/ +function (_BaseBuffer) { + (0, _inherits2["default"])(Chunker, _BaseBuffer); + + function Chunker(channel, bufferSize) { + var _this; + + (0, _classCallCheck2["default"])(this, Chunker); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(Chunker).call(this, 0)); + _this._bufferSize = bufferSize || _DEFAULT_BUFFER_SIZE; + _this._ch = channel; + _this._buffer = (0, node.alloc)(_this._bufferSize); + _this._currentChunkStart = 0; + _this._chunkOpen = false; + return _this; + } + + (0, _createClass2["default"])(Chunker, [{ + key: "putUInt8", + value: function putUInt8(position, val) { + this._ensure(1); + + this._buffer.writeUInt8(val); + } + }, { + key: "putInt8", + value: function putInt8(position, val) { + this._ensure(1); + + this._buffer.writeInt8(val); + } + }, { + key: "putFloat64", + value: function putFloat64(position, val) { + this._ensure(8); + + this._buffer.writeFloat64(val); + } + }, { + key: "putBytes", + value: function putBytes(position, data) { + // TODO: If data is larger than our chunk size or so, we're very likely better off just passing this buffer on + // rather than doing the copy here TODO: *however* note that we need some way to find out when the data has been + // written (and thus the buffer can be re-used) if we take that approach + while (data.remaining() > 0) { + // Ensure there is an open chunk, and that it has at least one byte of space left + this._ensure(1); + + if (this._buffer.remaining() > data.remaining()) { + this._buffer.writeBytes(data); + } else { + this._buffer.writeBytes(data.readSlice(this._buffer.remaining())); + } + } + + return this; + } + }, { + key: "flush", + value: function flush() { + if (this._buffer.position > 0) { + this._closeChunkIfOpen(); // Local copy and clear the buffer field. This ensures that the buffer is not re-released if the flush call fails + + + var out = this._buffer; + this._buffer = null; + + this._ch.write(out.getSlice(0, out.position)); // Alloc a new output buffer. We assume we're using NodeJS's buffer pooling under the hood here! + + + this._buffer = (0, node.alloc)(this._bufferSize); + this._chunkOpen = false; + } + + return this; + } + /** + * Bolt messages are encoded in one or more chunks, and the boundary between two messages + * is encoded as a 0-length chunk, `00 00`. This inserts such a message boundary, closing + * any currently open chunk as needed + */ + + }, { + key: "messageBoundary", + value: function messageBoundary() { + this._closeChunkIfOpen(); + + if (this._buffer.remaining() < _CHUNK_HEADER_SIZE) { + this.flush(); + } // Write message boundary + + + this._buffer.writeInt16(_MESSAGE_BOUNDARY); + } + /** Ensure at least the given size is available for writing */ + + }, { + key: "_ensure", + value: function _ensure(size) { + var toWriteSize = this._chunkOpen ? size : size + _CHUNK_HEADER_SIZE; + + if (this._buffer.remaining() < toWriteSize) { + this.flush(); + } + + if (!this._chunkOpen) { + this._currentChunkStart = this._buffer.position; + this._buffer.position = this._buffer.position + _CHUNK_HEADER_SIZE; + this._chunkOpen = true; + } + } + }, { + key: "_closeChunkIfOpen", + value: function _closeChunkIfOpen() { + if (this._chunkOpen) { + var chunkSize = this._buffer.position - (this._currentChunkStart + _CHUNK_HEADER_SIZE); + + this._buffer.putUInt16(this._currentChunkStart, chunkSize); + + this._chunkOpen = false; + } + } + }]); + return Chunker; +}(_baseBuf["default"]); +/** + * Combines chunks until a complete message is gathered up, and then forwards that + * message to an 'onmessage' listener. + * @access private + */ + + +exports.Chunker = Chunker; + +var Dechunker = +/*#__PURE__*/ +function () { + function Dechunker() { + (0, _classCallCheck2["default"])(this, Dechunker); + this._currentMessage = []; + this._partialChunkHeader = 0; + this._state = this.AWAITING_CHUNK; + } + + (0, _createClass2["default"])(Dechunker, [{ + key: "AWAITING_CHUNK", + value: function AWAITING_CHUNK(buf) { + if (buf.remaining() >= 2) { + // Whole header available, read that + return this._onHeader(buf.readUInt16()); + } else { + // Only one byte available, read that and wait for the second byte + this._partialChunkHeader = buf.readUInt8() << 8; + return this.IN_HEADER; + } + } + }, { + key: "IN_HEADER", + value: function IN_HEADER(buf) { + // First header byte read, now we read the next one + return this._onHeader((this._partialChunkHeader | buf.readUInt8()) & 0xffff); + } + }, { + key: "IN_CHUNK", + value: function IN_CHUNK(buf) { + if (this._chunkSize <= buf.remaining()) { + // Current packet is larger than current chunk, or same size: + this._currentMessage.push(buf.readSlice(this._chunkSize)); + + return this.AWAITING_CHUNK; + } else { + // Current packet is smaller than the chunk we're reading, split the current chunk itself up + this._chunkSize -= buf.remaining(); + + this._currentMessage.push(buf.readSlice(buf.remaining())); + + return this.IN_CHUNK; + } + } + }, { + key: "CLOSED", + value: function CLOSED(buf) {} // no-op + + /** Called when a complete chunk header has been received */ + + }, { + key: "_onHeader", + value: function _onHeader(header) { + if (header === 0) { + // Message boundary + var message; + + switch (this._currentMessage.length) { + case 0: + // Keep alive chunk, sent by server to keep network alive. + return this.AWAITING_CHUNK; + + case 1: + // All data in one chunk, this signals the end of that chunk. + message = this._currentMessage[0]; + break; + + default: + // A large chunk of data received, this signals that the last chunk has been received. + message = new _combinedBuf["default"](this._currentMessage); + break; + } + + this._currentMessage = []; + this.onmessage(message); + return this.AWAITING_CHUNK; + } else { + this._chunkSize = header; + return this.IN_CHUNK; + } + } + }, { + key: "write", + value: function write(buf) { + while (buf.hasRemaining()) { + this._state = this._state(buf); + } + } + }]); + return Dechunker; +}(); + +exports.Dechunker = Dechunker; +}); + +var packstreamV1 = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Structure = exports.Unpacker = exports.Packer = void 0; + +var _typeof2 = interopRequireDefault(_typeof_1); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +var _integer = interopRequireWildcard(integer); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var TINY_STRING = 0x80; +var TINY_LIST = 0x90; +var TINY_MAP = 0xa0; +var TINY_STRUCT = 0xb0; +var NULL = 0xc0; +var FLOAT_64 = 0xc1; +var FALSE = 0xc2; +var TRUE = 0xc3; +var INT_8 = 0xc8; +var INT_16 = 0xc9; +var INT_32 = 0xca; +var INT_64 = 0xcb; +var STRING_8 = 0xd0; +var STRING_16 = 0xd1; +var STRING_32 = 0xd2; +var LIST_8 = 0xd4; +var LIST_16 = 0xd5; +var LIST_32 = 0xd6; +var BYTES_8 = 0xcc; +var BYTES_16 = 0xcd; +var BYTES_32 = 0xce; +var MAP_8 = 0xd8; +var MAP_16 = 0xd9; +var MAP_32 = 0xda; +var STRUCT_8 = 0xdc; +var STRUCT_16 = 0xdd; +var NODE = 0x4e; +var NODE_STRUCT_SIZE = 3; +var RELATIONSHIP = 0x52; +var RELATIONSHIP_STRUCT_SIZE = 5; +var UNBOUND_RELATIONSHIP = 0x72; +var UNBOUND_RELATIONSHIP_STRUCT_SIZE = 3; +var PATH = 0x50; +var PATH_STRUCT_SIZE = 3; +/** + * A Structure have a signature and fields. + * @access private + */ + +var Structure = +/*#__PURE__*/ +function () { + /** + * Create new instance + */ + function Structure(signature, fields) { + (0, _classCallCheck2["default"])(this, Structure); + this.signature = signature; + this.fields = fields; + } + + (0, _createClass2["default"])(Structure, [{ + key: "toString", + value: function toString() { + var fieldStr = ''; + + for (var i = 0; i < this.fields.length; i++) { + if (i > 0) { + fieldStr += ', '; + } + + fieldStr += this.fields[i]; + } + + return 'Structure(' + this.signature + ', [' + fieldStr + '])'; + } + }]); + return Structure; +}(); +/** + * Class to pack + * @access private + */ + + +exports.Structure = Structure; + +var Packer = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {Chunker} channel the chunker backed by a network channel. + */ + function Packer(channel) { + (0, _classCallCheck2["default"])(this, Packer); + this._ch = channel; + this._byteArraysSupported = true; + } + /** + * Creates a packable function out of the provided value + * @param x the value to pack + * @returns Function + */ + + + (0, _createClass2["default"])(Packer, [{ + key: "packable", + value: function packable(x) { + var _this = this; + + if (x === null) { + return function () { + return _this._ch.writeUInt8(NULL); + }; + } else if (x === true) { + return function () { + return _this._ch.writeUInt8(TRUE); + }; + } else if (x === false) { + return function () { + return _this._ch.writeUInt8(FALSE); + }; + } else if (typeof x === 'number') { + return function () { + return _this.packFloat(x); + }; + } else if (typeof x === 'string') { + return function () { + return _this.packString(x); + }; + } else if ((0, _integer.isInt)(x)) { + return function () { + return _this.packInteger(x); + }; + } else if (x instanceof Int8Array) { + return function () { + return _this.packBytes(x); + }; + } else if (x instanceof Array) { + return function () { + _this.packListHeader(x.length); + + for (var _i = 0; _i < x.length; _i++) { + _this.packable(x[_i] === undefined ? null : x[_i])(); + } + }; + } else if (isIterable(x)) { + return this.packableIterable(x); + } else if (x instanceof graphTypes.Node) { + return this._nonPackableValue("It is not allowed to pass nodes in query parameters, given: ".concat(x)); + } else if (x instanceof graphTypes.Relationship) { + return this._nonPackableValue("It is not allowed to pass relationships in query parameters, given: ".concat(x)); + } else if (x instanceof graphTypes.Path) { + return this._nonPackableValue("It is not allowed to pass paths in query parameters, given: ".concat(x)); + } else if (x instanceof Structure) { + var packableFields = []; + + for (var i = 0; i < x.fields.length; i++) { + packableFields[i] = this.packable(x.fields[i]); + } + + return function () { + return _this.packStruct(x.signature, packableFields); + }; + } else if ((0, _typeof2["default"])(x) === 'object') { + return function () { + var keys = Object.keys(x); + var count = 0; + + for (var _i2 = 0; _i2 < keys.length; _i2++) { + if (x[keys[_i2]] !== undefined) { + count++; + } + } + + _this.packMapHeader(count); + + for (var _i3 = 0; _i3 < keys.length; _i3++) { + var key = keys[_i3]; + + if (x[key] !== undefined) { + _this.packString(key); + + _this.packable(x[key])(); + } + } + }; + } else { + return this._nonPackableValue("Unable to pack the given value: ".concat(x)); + } + } + }, { + key: "packableIterable", + value: function packableIterable(iterable) { + try { + var array = Array.from(iterable); + return this.packable(array); + } catch (e) { + // handle errors from iterable to array conversion + throw (0, error.newError)("Cannot pack given iterable, ".concat(e.message, ": ").concat(iterable)); + } + } + /** + * Packs a struct + * @param signature the signature of the struct + * @param packableFields the fields of the struct, make sure you call `packable on all fields` + */ + + }, { + key: "packStruct", + value: function packStruct(signature, packableFields) { + packableFields = packableFields || []; + this.packStructHeader(packableFields.length, signature); + + for (var i = 0; i < packableFields.length; i++) { + packableFields[i](); + } + } + }, { + key: "packInteger", + value: function packInteger(x) { + var high = x.high; + var low = x.low; + + if (x.greaterThanOrEqual(-0x10) && x.lessThan(0x80)) { + this._ch.writeInt8(low); + } else if (x.greaterThanOrEqual(-0x80) && x.lessThan(-0x10)) { + this._ch.writeUInt8(INT_8); + + this._ch.writeInt8(low); + } else if (x.greaterThanOrEqual(-0x8000) && x.lessThan(0x8000)) { + this._ch.writeUInt8(INT_16); + + this._ch.writeInt16(low); + } else if (x.greaterThanOrEqual(-0x80000000) && x.lessThan(0x80000000)) { + this._ch.writeUInt8(INT_32); + + this._ch.writeInt32(low); + } else { + this._ch.writeUInt8(INT_64); + + this._ch.writeInt32(high); + + this._ch.writeInt32(low); + } + } + }, { + key: "packFloat", + value: function packFloat(x) { + this._ch.writeUInt8(FLOAT_64); + + this._ch.writeFloat64(x); + } + }, { + key: "packString", + value: function packString(x) { + var bytes = node.utf8.encode(x); + + var size = bytes.length; + + if (size < 0x10) { + this._ch.writeUInt8(TINY_STRING | size); + + this._ch.writeBytes(bytes); + } else if (size < 0x100) { + this._ch.writeUInt8(STRING_8); + + this._ch.writeUInt8(size); + + this._ch.writeBytes(bytes); + } else if (size < 0x10000) { + this._ch.writeUInt8(STRING_16); + + this._ch.writeUInt8(size / 256 >> 0); + + this._ch.writeUInt8(size % 256); + + this._ch.writeBytes(bytes); + } else if (size < 0x100000000) { + this._ch.writeUInt8(STRING_32); + + this._ch.writeUInt8((size / 16777216 >> 0) % 256); + + this._ch.writeUInt8((size / 65536 >> 0) % 256); + + this._ch.writeUInt8((size / 256 >> 0) % 256); + + this._ch.writeUInt8(size % 256); + + this._ch.writeBytes(bytes); + } else { + throw (0, error.newError)('UTF-8 strings of size ' + size + ' are not supported'); + } + } + }, { + key: "packListHeader", + value: function packListHeader(size) { + if (size < 0x10) { + this._ch.writeUInt8(TINY_LIST | size); + } else if (size < 0x100) { + this._ch.writeUInt8(LIST_8); + + this._ch.writeUInt8(size); + } else if (size < 0x10000) { + this._ch.writeUInt8(LIST_16); + + this._ch.writeUInt8((size / 256 >> 0) % 256); + + this._ch.writeUInt8(size % 256); + } else if (size < 0x100000000) { + this._ch.writeUInt8(LIST_32); + + this._ch.writeUInt8((size / 16777216 >> 0) % 256); + + this._ch.writeUInt8((size / 65536 >> 0) % 256); + + this._ch.writeUInt8((size / 256 >> 0) % 256); + + this._ch.writeUInt8(size % 256); + } else { + throw (0, error.newError)('Lists of size ' + size + ' are not supported'); + } + } + }, { + key: "packBytes", + value: function packBytes(array) { + if (this._byteArraysSupported) { + this.packBytesHeader(array.length); + + for (var i = 0; i < array.length; i++) { + this._ch.writeInt8(array[i]); + } + } else { + throw (0, error.newError)('Byte arrays are not supported by the database this driver is connected to'); + } + } + }, { + key: "packBytesHeader", + value: function packBytesHeader(size) { + if (size < 0x100) { + this._ch.writeUInt8(BYTES_8); + + this._ch.writeUInt8(size); + } else if (size < 0x10000) { + this._ch.writeUInt8(BYTES_16); + + this._ch.writeUInt8((size / 256 >> 0) % 256); + + this._ch.writeUInt8(size % 256); + } else if (size < 0x100000000) { + this._ch.writeUInt8(BYTES_32); + + this._ch.writeUInt8((size / 16777216 >> 0) % 256); + + this._ch.writeUInt8((size / 65536 >> 0) % 256); + + this._ch.writeUInt8((size / 256 >> 0) % 256); + + this._ch.writeUInt8(size % 256); + } else { + throw (0, error.newError)('Byte arrays of size ' + size + ' are not supported'); + } + } + }, { + key: "packMapHeader", + value: function packMapHeader(size) { + if (size < 0x10) { + this._ch.writeUInt8(TINY_MAP | size); + } else if (size < 0x100) { + this._ch.writeUInt8(MAP_8); + + this._ch.writeUInt8(size); + } else if (size < 0x10000) { + this._ch.writeUInt8(MAP_16); + + this._ch.writeUInt8(size / 256 >> 0); + + this._ch.writeUInt8(size % 256); + } else if (size < 0x100000000) { + this._ch.writeUInt8(MAP_32); + + this._ch.writeUInt8((size / 16777216 >> 0) % 256); + + this._ch.writeUInt8((size / 65536 >> 0) % 256); + + this._ch.writeUInt8((size / 256 >> 0) % 256); + + this._ch.writeUInt8(size % 256); + } else { + throw (0, error.newError)('Maps of size ' + size + ' are not supported'); + } + } + }, { + key: "packStructHeader", + value: function packStructHeader(size, signature) { + if (size < 0x10) { + this._ch.writeUInt8(TINY_STRUCT | size); + + this._ch.writeUInt8(signature); + } else if (size < 0x100) { + this._ch.writeUInt8(STRUCT_8); + + this._ch.writeUInt8(size); + + this._ch.writeUInt8(signature); + } else if (size < 0x10000) { + this._ch.writeUInt8(STRUCT_16); + + this._ch.writeUInt8(size / 256 >> 0); + + this._ch.writeUInt8(size % 256); + } else { + throw (0, error.newError)('Structures of size ' + size + ' are not supported'); + } + } + }, { + key: "disableByteArrays", + value: function disableByteArrays() { + this._byteArraysSupported = false; + } + }, { + key: "_nonPackableValue", + value: function _nonPackableValue(message) { + return function () { + throw (0, error.newError)(message, error.PROTOCOL_ERROR); + }; + } + }]); + return Packer; +}(); +/** + * Class to unpack + * @access private + */ + + +exports.Packer = Packer; + +var Unpacker = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {boolean} disableLosslessIntegers if this unpacker should convert all received integers to native JS numbers. + */ + function Unpacker() { + var disableLosslessIntegers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + (0, _classCallCheck2["default"])(this, Unpacker); + this._disableLosslessIntegers = disableLosslessIntegers; + } + + (0, _createClass2["default"])(Unpacker, [{ + key: "unpack", + value: function unpack(buffer) { + var marker = buffer.readUInt8(); + var markerHigh = marker & 0xf0; + var markerLow = marker & 0x0f; + + if (marker === NULL) { + return null; + } + + var _boolean = this._unpackBoolean(marker); + + if (_boolean !== null) { + return _boolean; + } + + var numberOrInteger = this._unpackNumberOrInteger(marker, buffer); + + if (numberOrInteger !== null) { + if (this._disableLosslessIntegers && (0, _integer.isInt)(numberOrInteger)) { + return numberOrInteger.toNumberOrInfinity(); + } + + return numberOrInteger; + } + + var string = this._unpackString(marker, markerHigh, markerLow, buffer); + + if (string !== null) { + return string; + } + + var list = this._unpackList(marker, markerHigh, markerLow, buffer); + + if (list !== null) { + return list; + } + + var byteArray = this._unpackByteArray(marker, buffer); + + if (byteArray !== null) { + return byteArray; + } + + var map = this._unpackMap(marker, markerHigh, markerLow, buffer); + + if (map !== null) { + return map; + } + + var struct = this._unpackStruct(marker, markerHigh, markerLow, buffer); + + if (struct !== null) { + return struct; + } + + throw (0, error.newError)('Unknown packed value with marker ' + marker.toString(16)); + } + }, { + key: "unpackInteger", + value: function unpackInteger(buffer) { + var marker = buffer.readUInt8(); + + var result = this._unpackInteger(marker, buffer); + + if (result == null) { + throw (0, error.newError)('Unable to unpack integer value with marker ' + marker.toString(16)); + } + + return result; + } + }, { + key: "_unpackBoolean", + value: function _unpackBoolean(marker) { + if (marker === TRUE) { + return true; + } else if (marker === FALSE) { + return false; + } else { + return null; + } + } + }, { + key: "_unpackNumberOrInteger", + value: function _unpackNumberOrInteger(marker, buffer) { + if (marker === FLOAT_64) { + return buffer.readFloat64(); + } else { + return this._unpackInteger(marker, buffer); + } + } + }, { + key: "_unpackInteger", + value: function _unpackInteger(marker, buffer) { + if (marker >= 0 && marker < 128) { + return (0, _integer["int"])(marker); + } else if (marker >= 240 && marker < 256) { + return (0, _integer["int"])(marker - 256); + } else if (marker === INT_8) { + return (0, _integer["int"])(buffer.readInt8()); + } else if (marker === INT_16) { + return (0, _integer["int"])(buffer.readInt16()); + } else if (marker === INT_32) { + var b = buffer.readInt32(); + return (0, _integer["int"])(b); + } else if (marker === INT_64) { + var high = buffer.readInt32(); + var low = buffer.readInt32(); + return new _integer["default"](low, high); + } else { + return null; + } + } + }, { + key: "_unpackString", + value: function _unpackString(marker, markerHigh, markerLow, buffer) { + if (markerHigh === TINY_STRING) { + return node.utf8.decode(buffer, markerLow); + } else if (marker === STRING_8) { + return node.utf8.decode(buffer, buffer.readUInt8()); + } else if (marker === STRING_16) { + return node.utf8.decode(buffer, buffer.readUInt16()); + } else if (marker === STRING_32) { + return node.utf8.decode(buffer, buffer.readUInt32()); + } else { + return null; + } + } + }, { + key: "_unpackList", + value: function _unpackList(marker, markerHigh, markerLow, buffer) { + if (markerHigh === TINY_LIST) { + return this._unpackListWithSize(markerLow, buffer); + } else if (marker === LIST_8) { + return this._unpackListWithSize(buffer.readUInt8(), buffer); + } else if (marker === LIST_16) { + return this._unpackListWithSize(buffer.readUInt16(), buffer); + } else if (marker === LIST_32) { + return this._unpackListWithSize(buffer.readUInt32(), buffer); + } else { + return null; + } + } + }, { + key: "_unpackListWithSize", + value: function _unpackListWithSize(size, buffer) { + var value = []; + + for (var i = 0; i < size; i++) { + value.push(this.unpack(buffer)); + } + + return value; + } + }, { + key: "_unpackByteArray", + value: function _unpackByteArray(marker, buffer) { + if (marker === BYTES_8) { + return this._unpackByteArrayWithSize(buffer.readUInt8(), buffer); + } else if (marker === BYTES_16) { + return this._unpackByteArrayWithSize(buffer.readUInt16(), buffer); + } else if (marker === BYTES_32) { + return this._unpackByteArrayWithSize(buffer.readUInt32(), buffer); + } else { + return null; + } + } + }, { + key: "_unpackByteArrayWithSize", + value: function _unpackByteArrayWithSize(size, buffer) { + var value = new Int8Array(size); + + for (var i = 0; i < size; i++) { + value[i] = buffer.readInt8(); + } + + return value; + } + }, { + key: "_unpackMap", + value: function _unpackMap(marker, markerHigh, markerLow, buffer) { + if (markerHigh === TINY_MAP) { + return this._unpackMapWithSize(markerLow, buffer); + } else if (marker === MAP_8) { + return this._unpackMapWithSize(buffer.readUInt8(), buffer); + } else if (marker === MAP_16) { + return this._unpackMapWithSize(buffer.readUInt16(), buffer); + } else if (marker === MAP_32) { + return this._unpackMapWithSize(buffer.readUInt32(), buffer); + } else { + return null; + } + } + }, { + key: "_unpackMapWithSize", + value: function _unpackMapWithSize(size, buffer) { + var value = {}; + + for (var i = 0; i < size; i++) { + var key = this.unpack(buffer); + value[key] = this.unpack(buffer); + } + + return value; + } + }, { + key: "_unpackStruct", + value: function _unpackStruct(marker, markerHigh, markerLow, buffer) { + if (markerHigh === TINY_STRUCT) { + return this._unpackStructWithSize(markerLow, buffer); + } else if (marker === STRUCT_8) { + return this._unpackStructWithSize(buffer.readUInt8(), buffer); + } else if (marker === STRUCT_16) { + return this._unpackStructWithSize(buffer.readUInt16(), buffer); + } else { + return null; + } + } + }, { + key: "_unpackStructWithSize", + value: function _unpackStructWithSize(structSize, buffer) { + var signature = buffer.readUInt8(); + + if (signature === NODE) { + return this._unpackNode(structSize, buffer); + } else if (signature === RELATIONSHIP) { + return this._unpackRelationship(structSize, buffer); + } else if (signature === UNBOUND_RELATIONSHIP) { + return this._unpackUnboundRelationship(structSize, buffer); + } else if (signature === PATH) { + return this._unpackPath(structSize, buffer); + } else { + return this._unpackUnknownStruct(signature, structSize, buffer); + } + } + }, { + key: "_unpackNode", + value: function _unpackNode(structSize, buffer) { + this._verifyStructSize('Node', NODE_STRUCT_SIZE, structSize); + + return new graphTypes.Node(this.unpack(buffer), // Identity + this.unpack(buffer), // Labels + this.unpack(buffer) // Properties + ); + } + }, { + key: "_unpackRelationship", + value: function _unpackRelationship(structSize, buffer) { + this._verifyStructSize('Relationship', RELATIONSHIP_STRUCT_SIZE, structSize); + + return new graphTypes.Relationship(this.unpack(buffer), // Identity + this.unpack(buffer), // Start Node Identity + this.unpack(buffer), // End Node Identity + this.unpack(buffer), // Type + this.unpack(buffer) // Properties + ); + } + }, { + key: "_unpackUnboundRelationship", + value: function _unpackUnboundRelationship(structSize, buffer) { + this._verifyStructSize('UnboundRelationship', UNBOUND_RELATIONSHIP_STRUCT_SIZE, structSize); + + return new graphTypes.UnboundRelationship(this.unpack(buffer), // Identity + this.unpack(buffer), // Type + this.unpack(buffer) // Properties + ); + } + }, { + key: "_unpackPath", + value: function _unpackPath(structSize, buffer) { + this._verifyStructSize('Path', PATH_STRUCT_SIZE, structSize); + + var nodes = this.unpack(buffer); + var rels = this.unpack(buffer); + var sequence = this.unpack(buffer); + var segments = []; + var prevNode = nodes[0]; + + for (var i = 0; i < sequence.length; i += 2) { + var nextNode = nodes[sequence[i + 1]]; + var relIndex = sequence[i]; + var rel = void 0; + + if (relIndex > 0) { + rel = rels[relIndex - 1]; + + if (rel instanceof graphTypes.UnboundRelationship) { + // To avoid duplication, relationships in a path do not contain + // information about their start and end nodes, that's instead + // inferred from the path sequence. This is us inferring (and, + // for performance reasons remembering) the start/end of a rel. + rels[relIndex - 1] = rel = rel.bind(prevNode.identity, nextNode.identity); + } + } else { + rel = rels[-relIndex - 1]; + + if (rel instanceof graphTypes.UnboundRelationship) { + // See above + rels[-relIndex - 1] = rel = rel.bind(nextNode.identity, prevNode.identity); + } + } // Done hydrating one path segment. + + + segments.push(new graphTypes.PathSegment(prevNode, rel, nextNode)); + prevNode = nextNode; + } + + return new graphTypes.Path(nodes[0], nodes[nodes.length - 1], segments); + } + }, { + key: "_unpackUnknownStruct", + value: function _unpackUnknownStruct(signature, structSize, buffer) { + var result = new Structure(signature, []); + + for (var i = 0; i < structSize; i++) { + result.fields.push(this.unpack(buffer)); + } + + return result; + } + }, { + key: "_verifyStructSize", + value: function _verifyStructSize(structName, expectedSize, actualSize) { + if (expectedSize !== actualSize) { + throw (0, error.newError)("Wrong struct size for ".concat(structName, ", expected ").concat(expectedSize, " but was ").concat(actualSize), error.PROTOCOL_ERROR); + } + } + }]); + return Unpacker; +}(); + +exports.Unpacker = Unpacker; + +function isIterable(obj) { + if (obj == null) { + return false; + } + + return typeof obj[Symbol.iterator] === 'function'; +} +}); + +var requestMessage = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = exports.ALL = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* eslint-disable no-unused-vars */ +// Signature bytes for each request message type +var INIT = 0x01; // 0000 0001 // INIT + +var RESET = 0x0f; // 0000 1111 // RESET + +var RUN = 0x10; // 0001 0000 // RUN + +var PULL_ALL = 0x3f; // 0011 1111 // PULL_ALL + +var HELLO = 0x01; // 0000 0001 // HELLO + +var GOODBYE = 0x02; // 0000 0010 // GOODBYE + +var BEGIN = 0x11; // 0001 0001 // BEGIN + +var COMMIT = 0x12; // 0001 0010 // COMMIT + +var ROLLBACK = 0x13; // 0001 0011 // ROLLBACK + +var DISCARD = 0x2f; // 0010 1111 // DISCARD + +var PULL = 0x3f; // 0011 1111 // PULL + +var READ_MODE = 'r'; +/* eslint-enable no-unused-vars */ + +var NO_STATEMENT_ID = -1; +var ALL = -1; +exports.ALL = ALL; + +var RequestMessage = +/*#__PURE__*/ +function () { + function RequestMessage(signature, fields, toString) { + (0, _classCallCheck2["default"])(this, RequestMessage); + this.signature = signature; + this.fields = fields; + this.toString = toString; + } + /** + * Create a new INIT message. + * @param {string} clientName the client name. + * @param {Object} authToken the authentication token. + * @return {RequestMessage} new INIT message. + */ + + + (0, _createClass2["default"])(RequestMessage, null, [{ + key: "init", + value: function init(clientName, authToken) { + return new RequestMessage(INIT, [clientName, authToken], function () { + return "INIT ".concat(clientName, " {...}"); + }); + } + /** + * Create a new RUN message. + * @param {string} query the cypher query. + * @param {Object} parameters the query parameters. + * @return {RequestMessage} new RUN message. + */ + + }, { + key: "run", + value: function run(query, parameters) { + return new RequestMessage(RUN, [query, parameters], function () { + return "RUN ".concat(query, " ").concat(JSON.stringify(parameters)); + }); + } + /** + * Get a PULL_ALL message. + * @return {RequestMessage} the PULL_ALL message. + */ + + }, { + key: "pullAll", + value: function pullAll() { + return PULL_ALL_MESSAGE; + } + /** + * Get a RESET message. + * @return {RequestMessage} the RESET message. + */ + + }, { + key: "reset", + value: function reset() { + return RESET_MESSAGE; + } + /** + * Create a new HELLO message. + * @param {string} userAgent the user agent. + * @param {Object} authToken the authentication token. + * @param {Object} optional server side routing, set to routing context to turn on server side routing (> 4.1) + * @return {RequestMessage} new HELLO message. + */ + + }, { + key: "hello", + value: function hello(userAgent, authToken) { + var routing = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; + var metadata = Object.assign({ + user_agent: userAgent + }, authToken); + + if (routing != null) { + metadata.routing = routing; + } + + return new RequestMessage(HELLO, [metadata], function () { + return "HELLO {user_agent: '".concat(userAgent, "', ...}"); + }); + } + /** + * Create a new BEGIN message. + * @param {Bookmark} bookmark the bookmark. + * @param {TxConfig} txConfig the configuration. + * @param {string} database the database name. + * @param {string} mode the access mode. + * @return {RequestMessage} new BEGIN message. + */ + + }, { + key: "begin", + value: function begin() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + bookmark = _ref.bookmark, + txConfig = _ref.txConfig, + database = _ref.database, + mode = _ref.mode; + + var metadata = buildTxMetadata(bookmark, txConfig, database, mode); + return new RequestMessage(BEGIN, [metadata], function () { + return "BEGIN ".concat(JSON.stringify(metadata)); + }); + } + /** + * Get a COMMIT message. + * @return {RequestMessage} the COMMIT message. + */ + + }, { + key: "commit", + value: function commit() { + return COMMIT_MESSAGE; + } + /** + * Get a ROLLBACK message. + * @return {RequestMessage} the ROLLBACK message. + */ + + }, { + key: "rollback", + value: function rollback() { + return ROLLBACK_MESSAGE; + } + /** + * Create a new RUN message with additional metadata. + * @param {string} query the cypher query. + * @param {Object} parameters the query parameters. + * @param {Bookmark} bookmark the bookmark. + * @param {TxConfig} txConfig the configuration. + * @param {string} database the database name. + * @param {string} mode the access mode. + * @return {RequestMessage} new RUN message with additional metadata. + */ + + }, { + key: "runWithMetadata", + value: function runWithMetadata(query, parameters) { + var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + bookmark = _ref2.bookmark, + txConfig = _ref2.txConfig, + database = _ref2.database, + mode = _ref2.mode; + + var metadata = buildTxMetadata(bookmark, txConfig, database, mode); + return new RequestMessage(RUN, [query, parameters, metadata], function () { + return "RUN ".concat(query, " ").concat(JSON.stringify(parameters), " ").concat(JSON.stringify(metadata)); + }); + } + /** + * Get a GOODBYE message. + * @return {RequestMessage} the GOODBYE message. + */ + + }, { + key: "goodbye", + value: function goodbye() { + return GOODBYE_MESSAGE; + } + /** + * Generates a new PULL message with additional metadata. + * @param {Integer|number} stmtId + * @param {Integer|number} n + * @return {RequestMessage} the PULL message. + */ + + }, { + key: "pull", + value: function pull() { + var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref3$stmtId = _ref3.stmtId, + stmtId = _ref3$stmtId === void 0 ? NO_STATEMENT_ID : _ref3$stmtId, + _ref3$n = _ref3.n, + n = _ref3$n === void 0 ? ALL : _ref3$n; + + var metadata = buildStreamMetadata(stmtId || NO_STATEMENT_ID, n || ALL); + return new RequestMessage(PULL, [metadata], function () { + return "PULL ".concat(JSON.stringify(metadata)); + }); + } + /** + * Generates a new DISCARD message with additional metadata. + * @param {Integer|number} stmtId + * @param {Integer|number} n + * @return {RequestMessage} the PULL message. + */ + + }, { + key: "discard", + value: function discard() { + var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref4$stmtId = _ref4.stmtId, + stmtId = _ref4$stmtId === void 0 ? NO_STATEMENT_ID : _ref4$stmtId, + _ref4$n = _ref4.n, + n = _ref4$n === void 0 ? ALL : _ref4$n; + + var metadata = buildStreamMetadata(stmtId || NO_STATEMENT_ID, n || ALL); + return new RequestMessage(DISCARD, [metadata], function () { + return "DISCARD ".concat(JSON.stringify(metadata)); + }); + } + }]); + return RequestMessage; +}(); +/** + * Create an object that represent transaction metadata. + * @param {Bookmark} bookmark the bookmark. + * @param {TxConfig} txConfig the configuration. + * @param {string} database the database name. + * @param {string} mode the access mode. + * @return {Object} a metadata object. + */ + + +exports["default"] = RequestMessage; + +function buildTxMetadata(bookmark, txConfig, database, mode) { + var metadata = {}; + + if (!bookmark.isEmpty()) { + metadata.bookmarks = bookmark.values(); + } + + if (txConfig.timeout) { + metadata.tx_timeout = txConfig.timeout; + } + + if (txConfig.metadata) { + metadata.tx_metadata = txConfig.metadata; + } + + if (database) { + metadata.db = (0, util.assertString)(database, 'database'); + } + + if (mode === constants.ACCESS_MODE_READ) { + metadata.mode = READ_MODE; + } + + return metadata; +} +/** + * Create an object that represents streaming metadata. + * @param {Integer|number} stmtId The query id to stream its results. + * @param {Integer|number} n The number of records to stream. + * @returns {Object} a metadata object. + */ + + +function buildStreamMetadata(stmtId, n) { + var metadata = { + n: (0, integer["int"])(n) + }; + + if (stmtId !== NO_STATEMENT_ID) { + metadata.qid = (0, integer["int"])(stmtId); + } + + return metadata; +} // constants for messages that never change + + +var PULL_ALL_MESSAGE = new RequestMessage(PULL_ALL, [], function () { + return 'PULL_ALL'; +}); +var RESET_MESSAGE = new RequestMessage(RESET, [], function () { + return 'RESET'; +}); +var COMMIT_MESSAGE = new RequestMessage(COMMIT, [], function () { + return 'COMMIT'; +}); +var ROLLBACK_MESSAGE = new RequestMessage(ROLLBACK, [], function () { + return 'ROLLBACK'; +}); +var GOODBYE_MESSAGE = new RequestMessage(GOODBYE, [], function () { + return 'GOODBYE'; +}); +}); + +var txConfig = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var util$1 = interopRequireWildcard(util); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Internal holder of the transaction configuration. + * It performs input validation and value conversion for further serialization by the Bolt protocol layer. + * Users of the driver provide transaction configuration as regular objects `{timeout: 10, metadata: {key: 'value'}}`. + * Driver converts such objects to {@link TxConfig} immediately and uses converted values everywhere. + */ +var TxConfig = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {Object} config the raw configuration object. + */ + function TxConfig(config) { + (0, _classCallCheck2["default"])(this, TxConfig); + assertValidConfig(config); + this.timeout = extractTimeout(config); + this.metadata = extractMetadata(config); + } + /** + * Get an empty config object. + * @return {TxConfig} an empty config. + */ + + + (0, _createClass2["default"])(TxConfig, [{ + key: "isEmpty", + + /** + * Check if this config object is empty. I.e. has no configuration values specified. + * @return {boolean} `true` if this object is empty, `false` otherwise. + */ + value: function isEmpty() { + return Object.values(this).every(function (value) { + return value == null; + }); + } + }], [{ + key: "empty", + value: function empty() { + return EMPTY_CONFIG; + } + }]); + return TxConfig; +}(); + +exports["default"] = TxConfig; +var EMPTY_CONFIG = new TxConfig({}); +/** + * @return {Integer|null} + */ + +function extractTimeout(config) { + if (util$1.isObject(config) && (config.timeout || config.timeout === 0)) { + util$1.assertNumberOrInteger(config.timeout, 'Transaction timeout'); + var timeout = (0, integer["int"])(config.timeout); + + if (timeout.isZero()) { + throw (0, error.newError)('Transaction timeout should not be zero'); + } + + if (timeout.isNegative()) { + throw (0, error.newError)('Transaction timeout should not be negative'); + } + + return timeout; + } + + return null; +} +/** + * @return {object|null} + */ + + +function extractMetadata(config) { + if (util$1.isObject(config) && config.metadata) { + var metadata = config.metadata; + util$1.assertObject(metadata); + + if (Object.keys(metadata).length !== 0) { + // not an empty object + return metadata; + } + } + + return null; +} + +function assertValidConfig(config) { + if (config) { + util$1.assertObject(config, 'Transaction config'); + } +} +}); + +var boltProtocolV1 = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +var _bookmark = interopRequireDefault(bookmark); + + + +interopRequireDefault(connection); + + + +var v1 = interopRequireWildcard(packstreamV1); + +var _requestMessage = interopRequireDefault(requestMessage); + + + +var _txConfig = interopRequireDefault(txConfig); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var BoltProtocol = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {Connection} connection the connection. + * @param {Chunker} chunker the chunker. + * @param {boolean} disableLosslessIntegers if this connection should convert all received integers to native JS numbers. + */ + function BoltProtocol(connection, chunker, disableLosslessIntegers) { + (0, _classCallCheck2["default"])(this, BoltProtocol); + this._connection = connection; + this._packer = this._createPacker(chunker); + this._unpacker = this._createUnpacker(disableLosslessIntegers); + } + /** + * Returns the numerical version identifier for this protocol + */ + + + (0, _createClass2["default"])(BoltProtocol, [{ + key: "packer", + + /** + * Get the packer. + * @return {Packer} the protocol's packer. + */ + value: function packer() { + return this._packer; + } + /** + * Get the unpacker. + * @return {Unpacker} the protocol's unpacker. + */ + + }, { + key: "unpacker", + value: function unpacker() { + return this._unpacker; + } + /** + * Transform metadata received in SUCCESS message before it is passed to the handler. + * @param {Object} metadata the received metadata. + * @return {Object} transformed metadata. + */ + + }, { + key: "transformMetadata", + value: function transformMetadata(metadata) { + return metadata; + } + /** + * Perform initialization and authentication of the underlying connection. + * @param {Object} param + * @param {string} param.userAgent the user agent. + * @param {Object} param.authToken the authentication token. + * @param {function(err: Error)} param.onError the callback to invoke on error. + * @param {function()} param.onComplete the callback to invoke on completion. + * @returns {StreamObserver} the stream observer that monitors the corresponding server response. + */ + + }, { + key: "initialize", + value: function initialize() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + userAgent = _ref.userAgent, + authToken = _ref.authToken, + onError = _ref.onError, + onComplete = _ref.onComplete; + + var observer = new streamObservers.LoginObserver({ + connection: this._connection, + afterError: onError, + afterComplete: onComplete + }); + + this._connection.write(_requestMessage["default"].init(userAgent, authToken), observer, true); + + return observer; + } + /** + * Perform protocol related operations for closing this connection + */ + + }, { + key: "prepareToClose", + value: function prepareToClose() {} // no need to notify the database in this protocol version + + /** + * Begin an explicit transaction. + * @param {Object} param + * @param {Bookmark} param.bookmark the bookmark. + * @param {TxConfig} param.txConfig the configuration. + * @param {string} param.database the target database name. + * @param {string} param.mode the access mode. + * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error. + * @param {function(err: Error)} param.afterError the callback to invoke after handling the error. + * @param {function()} param.beforeComplete the callback to invoke before handling the completion. + * @param {function()} param.afterComplete the callback to invoke after handling the completion. + * @returns {StreamObserver} the stream observer that monitors the corresponding server response. + */ + + }, { + key: "beginTransaction", + value: function beginTransaction() { + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + bookmark = _ref2.bookmark, + txConfig = _ref2.txConfig, + database = _ref2.database, + mode = _ref2.mode, + beforeError = _ref2.beforeError, + afterError = _ref2.afterError, + beforeComplete = _ref2.beforeComplete, + afterComplete = _ref2.afterComplete; + + return this.run('BEGIN', bookmark ? bookmark.asBeginTransactionParameters() : {}, { + bookmark: bookmark, + txConfig: txConfig, + database: database, + mode: mode, + beforeError: beforeError, + afterError: afterError, + beforeComplete: beforeComplete, + afterComplete: afterComplete, + flush: false + }); + } + /** + * Commit the explicit transaction. + * @param {Object} param + * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error. + * @param {function(err: Error)} param.afterError the callback to invoke after handling the error. + * @param {function()} param.beforeComplete the callback to invoke before handling the completion. + * @param {function()} param.afterComplete the callback to invoke after handling the completion. + * @returns {StreamObserver} the stream observer that monitors the corresponding server response. + */ + + }, { + key: "commitTransaction", + value: function commitTransaction() { + var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + beforeError = _ref3.beforeError, + afterError = _ref3.afterError, + beforeComplete = _ref3.beforeComplete, + afterComplete = _ref3.afterComplete; + + // WRITE access mode is used as a place holder here, it has + // no effect on behaviour for Bolt V1 & V2 + return this.run('COMMIT', {}, { + bookmark: _bookmark["default"].empty(), + txConfig: _txConfig["default"].empty(), + mode: constants.ACCESS_MODE_WRITE, + beforeError: beforeError, + afterError: afterError, + beforeComplete: beforeComplete, + afterComplete: afterComplete + }); + } + /** + * Rollback the explicit transaction. + * @param {Object} param + * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error. + * @param {function(err: Error)} param.afterError the callback to invoke after handling the error. + * @param {function()} param.beforeComplete the callback to invoke before handling the completion. + * @param {function()} param.afterComplete the callback to invoke after handling the completion. + * @returns {StreamObserver} the stream observer that monitors the corresponding server response. + */ + + }, { + key: "rollbackTransaction", + value: function rollbackTransaction() { + var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + beforeError = _ref4.beforeError, + afterError = _ref4.afterError, + beforeComplete = _ref4.beforeComplete, + afterComplete = _ref4.afterComplete; + + // WRITE access mode is used as a place holder here, it has + // no effect on behaviour for Bolt V1 & V2 + return this.run('ROLLBACK', {}, { + bookmark: _bookmark["default"].empty(), + txConfig: _txConfig["default"].empty(), + mode: constants.ACCESS_MODE_WRITE, + beforeError: beforeError, + afterError: afterError, + beforeComplete: beforeComplete, + afterComplete: afterComplete + }); + } + /** + * Send a Cypher query through the underlying connection. + * @param {string} query the cypher query. + * @param {Object} parameters the query parameters. + * @param {Object} param + * @param {Bookmark} param.bookmark the bookmark. + * @param {TxConfig} param.txConfig the transaction configuration. + * @param {string} param.database the target database name. + * @param {string} param.mode the access mode. + * @param {function(keys: string[])} param.beforeKeys the callback to invoke before handling the keys. + * @param {function(keys: string[])} param.afterKeys the callback to invoke after handling the keys. + * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error. + * @param {function(err: Error)} param.afterError the callback to invoke after handling the error. + * @param {function()} param.beforeComplete the callback to invoke before handling the completion. + * @param {function()} param.afterComplete the callback to invoke after handling the completion. + * @param {boolean} param.flush whether to flush the buffered messages. + * @returns {StreamObserver} the stream observer that monitors the corresponding server response. + */ + + }, { + key: "run", + value: function run(query, parameters) { + var _ref5 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + _ref5.bookmark; + var txConfig = _ref5.txConfig, + database = _ref5.database; + _ref5.mode; + var beforeKeys = _ref5.beforeKeys, + afterKeys = _ref5.afterKeys, + beforeError = _ref5.beforeError, + afterError = _ref5.afterError, + beforeComplete = _ref5.beforeComplete, + afterComplete = _ref5.afterComplete, + _ref5$flush = _ref5.flush, + flush = _ref5$flush === void 0 ? true : _ref5$flush; + + var observer = new streamObservers.ResultStreamObserver({ + connection: this._connection, + beforeKeys: beforeKeys, + afterKeys: afterKeys, + beforeError: beforeError, + afterError: afterError, + beforeComplete: beforeComplete, + afterComplete: afterComplete + }); // bookmark and mode are ignored in this version of the protocol + + (0, boltProtocolUtil.assertTxConfigIsEmpty)(txConfig, this._connection, observer); // passing in a database name on this protocol version throws an error + + (0, boltProtocolUtil.assertDatabaseIsEmpty)(database, this._connection, observer); + + this._connection.write(_requestMessage["default"].run(query, parameters), observer, false); + + this._connection.write(_requestMessage["default"].pullAll(), observer, flush); + + return observer; + } + /** + * Send a RESET through the underlying connection. + * @param {Object} param + * @param {function(err: Error)} param.onError the callback to invoke on error. + * @param {function()} param.onComplete the callback to invoke on completion. + * @returns {StreamObserver} the stream observer that monitors the corresponding server response. + */ + + }, { + key: "reset", + value: function reset() { + var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + onError = _ref6.onError, + onComplete = _ref6.onComplete; + + var observer = new streamObservers.ResetObserver({ + connection: this._connection, + onError: onError, + onComplete: onComplete + }); + + this._connection.write(_requestMessage["default"].reset(), observer, true); + + return observer; + } + }, { + key: "_createPacker", + value: function _createPacker(chunker) { + return new v1.Packer(chunker); + } + }, { + key: "_createUnpacker", + value: function _createUnpacker(disableLosslessIntegers) { + return new v1.Unpacker(disableLosslessIntegers); + } + }, { + key: "version", + get: function get() { + return constants.BOLT_PROTOCOL_V1; + } + }]); + return BoltProtocol; +}(); + +exports["default"] = BoltProtocol; +}); + +var connection = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +interopRequireDefault(boltProtocolV1); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var Connection = +/*#__PURE__*/ +function () { + /** + * @param {ConnectionErrorHandler} errorHandler the error handler + */ + function Connection(errorHandler) { + (0, _classCallCheck2["default"])(this, Connection); + this._errorHandler = errorHandler; + } + + (0, _createClass2["default"])(Connection, [{ + key: "isOpen", + + /** + * @returns {boolean} whether this connection is in a working condition + */ + value: function isOpen() { + throw new Error('not implemented'); + } + /** + * @returns {BoltProtocol} the underlying bolt protocol assigned to this connection + */ + + }, { + key: "protocol", + value: function protocol() { + throw new Error('not implemented'); + } + /** + * @returns {ServerAddress} the server address this connection is opened against + */ + + }, { + key: "connect", + + /** + * Connect to the target address, negotiate Bolt protocol and send initialization message. + * @param {string} userAgent the user agent for this driver. + * @param {Object} authToken the object containing auth information. + * @return {Promise} promise resolved with the current connection if connection is successful. Rejected promise otherwise. + */ + value: function connect(userAgent, authToken) { + throw new Error('not implemented'); + } + /** + * Write a message to the network channel. + * @param {RequestMessage} message the message to write. + * @param {ResultStreamObserver} observer the response observer. + * @param {boolean} flush `true` if flush should happen after the message is written to the buffer. + */ + + }, { + key: "write", + value: function write(message, observer, flush) { + throw new Error('not implemented'); + } + /** + * Send a RESET-message to the database. Message is immediately flushed to the network. + * @return {Promise} promise resolved when SUCCESS-message response arrives, or failed when other response messages arrives. + */ + + }, { + key: "resetAndFlush", + value: function resetAndFlush() { + throw new Error('not implemented'); + } + /** + * Call close on the channel. + * @returns {Promise} - A promise that will be resolved when the connection is closed. + * + */ + + }, { + key: "close", + value: function close() { + throw new Error('not implemented'); + } + /** + * + * @param error + * @param address + * @returns {Neo4jError|*} + */ + + }, { + key: "handleAndTransformError", + value: function handleAndTransformError(error, address) { + if (this._errorHandler) { + return this._errorHandler.handleAndTransformError(error, address); + } + + return error; + } + }, { + key: "id", + get: function get() { + throw new Error('not implemented'); + } + }, { + key: "databaseId", + get: function get() { + throw new Error('not implemented'); + }, + set: function set(value) { + throw new Error('not implemented'); + } + }, { + key: "address", + get: function get() { + throw new Error('not implemented'); + } + /** + * @returns {ServerVersion} the version of the server this connection is connected to + */ + + }, { + key: "version", + get: function get() { + throw new Error('not implemented'); + }, + set: function set(value) { + throw new Error('not implemented'); + } + }, { + key: "server", + get: function get() { + throw new Error('not implemented'); + } + }]); + return Connection; +}(); + +exports["default"] = Connection; +}); + +var streamObservers = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.CompletedObserver = exports.FailedObserver = exports.ResetObserver = exports.LoginObserver = exports.ResultStreamObserver = exports.StreamObserver = void 0; + +var _assertThisInitialized2 = interopRequireDefault(assertThisInitialized); + +var _get2 = interopRequireDefault(get$1); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _record = interopRequireDefault(record); + +interopRequireDefault(connection); + + + +interopRequireDefault(integer); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var StreamObserver = +/*#__PURE__*/ +function () { + function StreamObserver() { + (0, _classCallCheck2["default"])(this, StreamObserver); + } + + (0, _createClass2["default"])(StreamObserver, [{ + key: "onNext", + value: function onNext(rawRecord) {} + }, { + key: "onError", + value: function onError(error) {} + }, { + key: "onCompleted", + value: function onCompleted(meta) {} + }]); + return StreamObserver; +}(); +/** + * Handles a RUN/PULL_ALL, or RUN/DISCARD_ALL requests, maps the responses + * in a way that a user-provided observer can see these as a clean Stream + * of records. + * This class will queue up incoming messages until a user-provided observer + * for the incoming stream is registered. Thus, we keep fields around + * for tracking head/records/tail. These are only used if there is no + * observer registered. + * @access private + */ + + +exports.StreamObserver = StreamObserver; + +var ResultStreamObserver = +/*#__PURE__*/ +function (_StreamObserver) { + (0, _inherits2["default"])(ResultStreamObserver, _StreamObserver); + + /** + * + * @param {Object} param + * @param {Connection} param.connection + * @param {boolean} param.reactive + * @param {function(connection: Connection, stmtId: number|Integer, n: number|Integer, observer: StreamObserver)} param.moreFunction - + * @param {function(connection: Connection, stmtId: number|Integer, observer: StreamObserver)} param.discardFunction - + * @param {number|Integer} param.fetchSize - + * @param {function(err: Error): Promise|void} param.beforeError - + * @param {function(err: Error): Promise|void} param.afterError - + * @param {function(keys: string[]): Promise|void} param.beforeKeys - + * @param {function(keys: string[]): Promise|void} param.afterKeys - + * @param {function(metadata: Object): Promise|void} param.beforeComplete - + * @param {function(metadata: Object): Promise|void} param.afterComplete - + */ + function ResultStreamObserver() { + var _this; + + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + connection = _ref.connection, + _ref$reactive = _ref.reactive, + reactive = _ref$reactive === void 0 ? false : _ref$reactive, + moreFunction = _ref.moreFunction, + discardFunction = _ref.discardFunction, + _ref$fetchSize = _ref.fetchSize, + fetchSize = _ref$fetchSize === void 0 ? requestMessage.ALL : _ref$fetchSize, + beforeError = _ref.beforeError, + afterError = _ref.afterError, + beforeKeys = _ref.beforeKeys, + afterKeys = _ref.afterKeys, + beforeComplete = _ref.beforeComplete, + afterComplete = _ref.afterComplete; + + (0, _classCallCheck2["default"])(this, ResultStreamObserver); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ResultStreamObserver).call(this)); + _this._connection = connection; + _this._fieldKeys = null; + _this._fieldLookup = null; + _this._head = null; + _this._queuedRecords = []; + _this._tail = null; + _this._error = null; + _this._observers = []; + _this._meta = {}; + _this._beforeError = beforeError; + _this._afterError = afterError; + _this._beforeKeys = beforeKeys; + _this._afterKeys = afterKeys; + _this._beforeComplete = beforeComplete; + _this._afterComplete = afterComplete; + _this._queryId = null; + _this._moreFunction = moreFunction; + _this._discardFunction = discardFunction; + _this._discard = false; + _this._fetchSize = fetchSize; + + _this._setState(reactive ? _states.READY : _states.READY_STREAMING); + + _this._setupAuoPull(fetchSize); + + return _this; + } + /** + * Will be called on every record that comes in and transform a raw record + * to a Object. If user-provided observer is present, pass transformed record + * to it's onNext method, otherwise, push to record que. + * @param {Array} rawRecord - An array with the raw record + */ + + + (0, _createClass2["default"])(ResultStreamObserver, [{ + key: "onNext", + value: function onNext(rawRecord) { + var record = new _record["default"](this._fieldKeys, rawRecord, this._fieldLookup); + + if (this._observers.some(function (o) { + return o.onNext; + })) { + this._observers.forEach(function (o) { + if (o.onNext) { + o.onNext(record); + } + }); + } else { + this._queuedRecords.push(record); + + if (this._queuedRecords.length > this._highRecordWatermark) { + this._autoPull = false; + } + } + } + }, { + key: "onCompleted", + value: function onCompleted(meta) { + this._state.onSuccess(this, meta); + } + /** + * Will be called on errors. + * If user-provided observer is present, pass the error + * to it's onError method, otherwise set instance variable _error. + * @param {Object} error - An error object + */ + + }, { + key: "onError", + value: function onError(error) { + this._state.onError(this, error); + } + /** + * Cancel pending record stream + */ + + }, { + key: "cancel", + value: function cancel() { + this._discard = true; + } + /** + * Stream observer defaults to handling responses for two messages: RUN + PULL_ALL or RUN + DISCARD_ALL. + * Response for RUN initializes query keys. Response for PULL_ALL / DISCARD_ALL exposes the result stream. + * + * However, some operations can be represented as a single message which receives full metadata in a single response. + * For example, operations to begin, commit and rollback an explicit transaction use two messages in Bolt V1 but a single message in Bolt V3. + * Messages are `RUN "BEGIN" {}` + `PULL_ALL` in Bolt V1 and `BEGIN` in Bolt V3. + * + * This function prepares the observer to only handle a single response message. + */ + + }, { + key: "prepareToHandleSingleResponse", + value: function prepareToHandleSingleResponse() { + this._head = []; + this._fieldKeys = []; + + this._setState(_states.STREAMING); + } + /** + * Mark this observer as if it has completed with no metadata. + */ + + }, { + key: "markCompleted", + value: function markCompleted() { + this._head = []; + this._fieldKeys = []; + this._tail = {}; + + this._setState(_states.SUCCEEDED); + } + /** + * Subscribe to events with provided observer. + * @param {Object} observer - Observer object + * @param {function(keys: String[])} observer.onKeys - Handle stream header, field keys. + * @param {function(record: Object)} observer.onNext - Handle records, one by one. + * @param {function(metadata: Object)} observer.onCompleted - Handle stream tail, the metadata. + * @param {function(error: Object)} observer.onError - Handle errors, should always be provided. + */ + + }, { + key: "subscribe", + value: function subscribe(observer) { + if (this._error) { + observer.onError(this._error); + return; + } + + if (this._head && observer.onKeys) { + observer.onKeys(this._head); + } + + if (this._queuedRecords.length > 0 && observer.onNext) { + for (var i = 0; i < this._queuedRecords.length; i++) { + observer.onNext(this._queuedRecords[i]); + + if (this._queuedRecords.length - i - 1 <= this._lowRecordWatermark) { + this._autoPull = true; + + if (this._state === _states.READY) { + this._handleStreaming(); + } + } + } + } + + if (this._tail && observer.onCompleted) { + observer.onCompleted(this._tail); + } + + this._observers.push(observer); + + if (this._state === _states.READY) { + this._handleStreaming(); + } + } + }, { + key: "_handleHasMore", + value: function _handleHasMore(meta) { + // We've consumed current batch and server notified us that there're more + // records to stream. Let's invoke more or discard function based on whether + // the user wants to discard streaming or not + this._setState(_states.READY); // we've done streaming + + + this._handleStreaming(); + + delete meta.has_more; + } + }, { + key: "_handlePullSuccess", + value: function _handlePullSuccess(meta) { + var _this2 = this; + + this._setState(_states.SUCCEEDED); + + var completionMetadata = Object.assign(this._connection ? { + server: this._connection.server + } : {}, this._meta, meta); + var beforeHandlerResult = null; + + if (this._beforeComplete) { + beforeHandlerResult = this._beforeComplete(completionMetadata); + } + + var continuation = function continuation() { + // End of stream + _this2._tail = completionMetadata; + + if (_this2._observers.some(function (o) { + return o.onCompleted; + })) { + _this2._observers.forEach(function (o) { + if (o.onCompleted) { + o.onCompleted(completionMetadata); + } + }); + } + + if (_this2._afterComplete) { + _this2._afterComplete(completionMetadata); + } + }; + + if (beforeHandlerResult) { + Promise.resolve(beforeHandlerResult).then(function () { + return continuation(); + }); + } else { + continuation(); + } + } + }, { + key: "_handleRunSuccess", + value: function _handleRunSuccess(meta, afterSuccess) { + var _this3 = this; + + if (this._fieldKeys === null) { + // Stream header, build a name->index field lookup table + // to be used by records. This is an optimization to make it + // faster to look up fields in a record by name, rather than by index. + // Since the records we get back via Bolt are just arrays of values. + this._fieldKeys = []; + this._fieldLookup = {}; + + if (meta.fields && meta.fields.length > 0) { + this._fieldKeys = meta.fields; + + for (var i = 0; i < meta.fields.length; i++) { + this._fieldLookup[meta.fields[i]] = i; + } // remove fields key from metadata object + + + delete meta.fields; + } // Extract server generated query id for use in requestMore and discard + // functions + + + if (meta.qid) { + this._queryId = meta.qid; // remove qid from metadata object + + delete meta.qid; + } + + this._storeMetadataForCompletion(meta); + + var beforeHandlerResult = null; + + if (this._beforeKeys) { + beforeHandlerResult = this._beforeKeys(this._fieldKeys); + } + + var continuation = function continuation() { + _this3._head = _this3._fieldKeys; + + if (_this3._observers.some(function (o) { + return o.onKeys; + })) { + _this3._observers.forEach(function (o) { + if (o.onKeys) { + o.onKeys(_this3._fieldKeys); + } + }); + } + + if (_this3._afterKeys) { + _this3._afterKeys(_this3._fieldKeys); + } + + afterSuccess(); + }; + + if (beforeHandlerResult) { + Promise.resolve(beforeHandlerResult).then(function () { + return continuation(); + }); + } else { + continuation(); + } + } + } + }, { + key: "_handleError", + value: function _handleError(error) { + var _this4 = this; + + this._setState(_states.FAILED); + + this._error = error; + var beforeHandlerResult = null; + + if (this._beforeError) { + beforeHandlerResult = this._beforeError(error); + } + + var continuation = function continuation() { + if (_this4._observers.some(function (o) { + return o.onError; + })) { + _this4._observers.forEach(function (o) { + if (o.onError) { + o.onError(error); + } + }); + } + + if (_this4._afterError) { + _this4._afterError(error); + } + }; + + if (beforeHandlerResult) { + Promise.resolve(beforeHandlerResult).then(function () { + return continuation(); + }); + } else { + continuation(); + } + } + }, { + key: "_handleStreaming", + value: function _handleStreaming() { + if (this._head && this._observers.some(function (o) { + return o.onNext || o.onCompleted; + })) { + if (this._discard) { + this._discardFunction(this._connection, this._queryId, this); + + this._setState(_states.STREAMING); + } else if (this._autoPull) { + this._moreFunction(this._connection, this._queryId, this._fetchSize, this); + + this._setState(_states.STREAMING); + } + } + } + }, { + key: "_storeMetadataForCompletion", + value: function _storeMetadataForCompletion(meta) { + var keys = Object.keys(meta); + var index = keys.length; + var key = ''; + + while (index--) { + key = keys[index]; + this._meta[key] = meta[key]; + } + } + }, { + key: "_setState", + value: function _setState(state) { + this._state = state; + } + }, { + key: "_setupAuoPull", + value: function _setupAuoPull(fetchSize) { + this._autoPull = true; + + if (fetchSize === requestMessage.ALL) { + this._lowRecordWatermark = Number.MAX_VALUE; // we shall always lower than this number to enable auto pull + + this._highRecordWatermark = Number.MAX_VALUE; // we shall never reach this number to disable auto pull + } else { + this._lowRecordWatermark = 0.3 * fetchSize; + this._highRecordWatermark = 0.7 * fetchSize; + } + } + }]); + return ResultStreamObserver; +}(StreamObserver); + +exports.ResultStreamObserver = ResultStreamObserver; + +var LoginObserver = +/*#__PURE__*/ +function (_StreamObserver2) { + (0, _inherits2["default"])(LoginObserver, _StreamObserver2); + + /** + * + * @param {Object} param - + * @param {Connection} param.connection + * @param {function(err: Error)} param.beforeError + * @param {function(err: Error)} param.afterError + * @param {function(metadata)} param.beforeComplete + * @param {function(metadata)} param.afterComplete + */ + function LoginObserver() { + var _this5; + + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + connection = _ref2.connection, + beforeError = _ref2.beforeError, + afterError = _ref2.afterError, + beforeComplete = _ref2.beforeComplete, + afterComplete = _ref2.afterComplete; + + (0, _classCallCheck2["default"])(this, LoginObserver); + _this5 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(LoginObserver).call(this)); + _this5._connection = connection; + _this5._beforeError = beforeError; + _this5._afterError = afterError; + _this5._beforeComplete = beforeComplete; + _this5._afterComplete = afterComplete; + return _this5; + } + + (0, _createClass2["default"])(LoginObserver, [{ + key: "onNext", + value: function onNext(record) { + this.onError((0, error.newError)('Received RECORD when initializing ' + JSON.stringify(record))); + } + }, { + key: "onError", + value: function onError(error) { + if (this._beforeError) { + this._beforeError(error); + } + + this._connection._updateCurrentObserver(); // make sure this exact observer will not be called again + + + this._connection._handleFatalError(error); // initialization errors are fatal + + + if (this._afterError) { + this._afterError(error); + } + } + }, { + key: "onCompleted", + value: function onCompleted(metadata) { + if (this._beforeComplete) { + this._beforeComplete(metadata); + } + + if (metadata) { + // read server version from the response metadata, if it is available + var serverVersion = metadata.server; + + if (!this._connection.version) { + this._connection.version = serverVersion; + } // read database connection id from the response metadata, if it is available + + + var dbConnectionId = metadata.connection_id; + + if (!this._connection.databaseId) { + this._connection.databaseId = dbConnectionId; + } + } + + if (this._afterComplete) { + this._afterComplete(metadata); + } + } + }]); + return LoginObserver; +}(StreamObserver); + +exports.LoginObserver = LoginObserver; + +var ResetObserver = +/*#__PURE__*/ +function (_StreamObserver3) { + (0, _inherits2["default"])(ResetObserver, _StreamObserver3); + + /** + * + * @param {Object} param - + * @param {Connection} param.connection + * @param {function(err: Error)} param.onError + * @param {function(metadata)} param.onComplete + */ + function ResetObserver() { + var _this6; + + var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + connection = _ref3.connection, + onError = _ref3.onError, + onComplete = _ref3.onComplete; + + (0, _classCallCheck2["default"])(this, ResetObserver); + _this6 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ResetObserver).call(this)); + _this6._connection = connection; + _this6._onError = onError; + _this6._onComplete = onComplete; + return _this6; + } + + (0, _createClass2["default"])(ResetObserver, [{ + key: "onNext", + value: function onNext(record) { + this.onError((0, error.newError)('Received RECORD when resetting: received record is: ' + JSON.stringify(record), error.PROTOCOL_ERROR)); + } + }, { + key: "onError", + value: function onError(error$1) { + if (error$1.code === error.PROTOCOL_ERROR) { + this._connection._handleProtocolError(error$1.message); + } + + if (this._onError) { + this._onError(error$1); + } + } + }, { + key: "onCompleted", + value: function onCompleted(metadata) { + if (this._onComplete) { + this._onComplete(metadata); + } + } + }]); + return ResetObserver; +}(StreamObserver); + +exports.ResetObserver = ResetObserver; + +var FailedObserver = +/*#__PURE__*/ +function (_ResultStreamObserver) { + (0, _inherits2["default"])(FailedObserver, _ResultStreamObserver); + + function FailedObserver(_ref4) { + var _this7; + + var error = _ref4.error, + onError = _ref4.onError; + (0, _classCallCheck2["default"])(this, FailedObserver); + _this7 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(FailedObserver).call(this, { + beforeError: onError + })); + + _this7.onError(error); + + return _this7; + } + + return FailedObserver; +}(ResultStreamObserver); + +exports.FailedObserver = FailedObserver; + +var CompletedObserver = +/*#__PURE__*/ +function (_ResultStreamObserver2) { + (0, _inherits2["default"])(CompletedObserver, _ResultStreamObserver2); + + function CompletedObserver() { + var _this8; + + (0, _classCallCheck2["default"])(this, CompletedObserver); + _this8 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(CompletedObserver).call(this)); + (0, _get2["default"])((0, _getPrototypeOf2["default"])(CompletedObserver.prototype), "markCompleted", (0, _assertThisInitialized2["default"])(_this8)).call((0, _assertThisInitialized2["default"])(_this8)); + return _this8; + } + + return CompletedObserver; +}(ResultStreamObserver); + +exports.CompletedObserver = CompletedObserver; +var _states = { + READY_STREAMING: { + // async start state + onSuccess: function onSuccess(streamObserver, meta) { + streamObserver._handleRunSuccess(meta, function () { + streamObserver._setState(_states.STREAMING); + } // after run succeeded, async directly move to streaming + // state + ); + }, + onError: function onError(streamObserver, error) { + streamObserver._handleError(error); + }, + name: function name() { + return 'READY_STREAMING'; + } + }, + READY: { + // reactive start state + onSuccess: function onSuccess(streamObserver, meta) { + streamObserver._handleRunSuccess(meta, function () { + return streamObserver._handleStreaming(); + } // after run succeeded received, reactive shall start pulling + ); + }, + onError: function onError(streamObserver, error) { + streamObserver._handleError(error); + }, + name: function name() { + return 'READY'; + } + }, + STREAMING: { + onSuccess: function onSuccess(streamObserver, meta) { + if (meta.has_more) { + streamObserver._handleHasMore(meta); + } else { + streamObserver._handlePullSuccess(meta); + } + }, + onError: function onError(streamObserver, error) { + streamObserver._handleError(error); + }, + name: function name() { + return 'STREAMING'; + } + }, + FAILED: { + onError: function onError(error) {// more errors are ignored + }, + name: function name() { + return 'FAILED'; + } + }, + SUCCEEDED: { + name: function name() { + return 'SUCCEEDED'; + } + } +}; +}); + +var result = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _resultSummary = interopRequireDefault(resultSummary); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var DEFAULT_ON_ERROR = function DEFAULT_ON_ERROR(error) { + console.log('Uncaught error when processing result: ' + error); +}; + +var DEFAULT_ON_COMPLETED = function DEFAULT_ON_COMPLETED(summary) {}; +/** + * A stream of {@link Record} representing the result of a query. + * Can be consumed eagerly as {@link Promise} resolved with array of records and {@link ResultSummary} + * summary, or rejected with error that contains {@link string} code and {@link string} message. + * Alternatively can be consumed lazily using {@link Result#subscribe} function. + * @access public + */ + + +var Result = +/*#__PURE__*/ +function () { + /** + * Inject the observer to be used. + * @constructor + * @access private + * @param {Promise} streamObserverPromise + * @param {mixed} query - Cypher query to execute + * @param {Object} parameters - Map with parameters to use in query + * @param {ConnectionHolder} connectionHolder - to be notified when result is either fully consumed or error happened. + */ + function Result(streamObserverPromise, query, parameters, connectionHolder$1) { + (0, _classCallCheck2["default"])(this, Result); + this._stack = captureStacktrace(); + this._streamObserverPromise = streamObserverPromise; + this._p = null; + this._query = query; + this._parameters = parameters || {}; + this._connectionHolder = connectionHolder$1 || connectionHolder.EMPTY_CONNECTION_HOLDER; + } + /** + * Returns a promise for the field keys. + * + * *Should not be combined with {@link Result#subscribe} function.* + * + * @public + * @returns {Promise} - Field keys, in the order they will appear in records. + } + */ + + + (0, _createClass2["default"])(Result, [{ + key: "keys", + value: function keys() { + var _this = this; + + return new Promise(function (resolve, reject) { + _this._streamObserverPromise.then(function (observer) { + return observer.subscribe({ + onKeys: function onKeys(keys) { + return resolve(keys); + }, + onError: function onError(err) { + return reject(err); + } + }); + }); + }); + } + /** + * Returns a promise for the result summary. + * + * *Should not be combined with {@link Result#subscribe} function.* + * + * @public + * @returns {Promise} - Result summary. + * + */ + + }, { + key: "summary", + value: function summary() { + var _this2 = this; + + return new Promise(function (resolve, reject) { + _this2._streamObserverPromise.then(function (o) { + o.cancel(); + o.subscribe({ + onCompleted: function onCompleted(metadata) { + return resolve(metadata); + }, + onError: function onError(err) { + return reject(err); + } + }); + }); + }); + } + /** + * Create and return new Promise + * + * @private + * @return {Promise} new Promise. + */ + + }, { + key: "_getOrCreatePromise", + value: function _getOrCreatePromise() { + var _this3 = this; + + if (!this._p) { + this._p = new Promise(function (resolve, reject) { + var records = []; + var observer = { + onNext: function onNext(record) { + records.push(record); + }, + onCompleted: function onCompleted(summary) { + resolve({ + records: records, + summary: summary + }); + }, + onError: function onError(error) { + reject(error); + } + }; + + _this3.subscribe(observer); + }); + } + + return this._p; + } + /** + * Waits for all results and calls the passed in function with the results. + * + * *Should not be combined with {@link Result#subscribe} function.* + * + * @param {function(result: {records:Array, summary: ResultSummary})} onFulfilled - function to be called + * when finished. + * @param {function(error: {message:string, code:string})} onRejected - function to be called upon errors. + * @return {Promise} promise. + */ + + }, { + key: "then", + value: function then(onFulfilled, onRejected) { + return this._getOrCreatePromise().then(onFulfilled, onRejected); + } + /** + * Catch errors when using promises. + * + * *Should not be combined with {@link Result#subscribe} function.* + * + * @param {function(error: Neo4jError)} onRejected - Function to be called upon errors. + * @return {Promise} promise. + */ + + }, { + key: "catch", + value: function _catch(onRejected) { + return this._getOrCreatePromise()["catch"](onRejected); + } + /** + * Stream records to observer as they come in, this is a more efficient method + * of handling the results, and allows you to handle arbitrarily large results. + * + * @param {Object} observer - Observer object + * @param {function(keys: string[])} observer.onKeys - handle stream head, the field keys. + * @param {function(record: Record)} observer.onNext - handle records, one by one. + * @param {function(summary: ResultSummary)} observer.onCompleted - handle stream tail, the result summary. + * @param {function(error: {message:string, code:string})} observer.onError - handle errors. + * @return + */ + + }, { + key: "subscribe", + value: function subscribe(observer) { + var _this4 = this; + + var onCompletedOriginal = observer.onCompleted || DEFAULT_ON_COMPLETED; + + var onCompletedWrapper = function onCompletedWrapper(metadata) { + var connectionHolder = _this4._connectionHolder; + var query = _this4._query; + var parameters = _this4._parameters; + + function complete(protocolVersion) { + onCompletedOriginal.call(observer, new _resultSummary["default"](query, parameters, metadata, protocolVersion)); + } + + function release() { + // notify connection holder that the used connection is not needed any more because result has + // been fully consumed; call the original onCompleted callback after that + return connectionHolder.releaseConnection(); + } + + connectionHolder.getConnection().then( // onFulfilled: + function (connection) { + release().then(function () { + return complete(connection !== undefined ? connection.protocol().version : undefined); + }); + }, // onRejected: + function (_) { + complete(); + }); + }; + + observer.onCompleted = onCompletedWrapper; + var onErrorOriginal = observer.onError || DEFAULT_ON_ERROR; + + var onErrorWrapper = function onErrorWrapper(error) { + // notify connection holder that the used connection is not needed any more because error happened + // and result can't bee consumed any further; call the original onError callback after that + _this4._connectionHolder.releaseConnection().then(function () { + replaceStacktrace(error, _this4._stack); + onErrorOriginal.call(observer, error); + }); + }; + + observer.onError = onErrorWrapper; + + this._streamObserverPromise.then(function (o) { + return o.subscribe(observer); + }); + } + /** + * Signals the stream observer that the future records should be discarded on the server. + * + * @protected + * @since 4.0.0 + */ + + }, { + key: "_cancel", + value: function _cancel() { + this._streamObserverPromise.then(function (o) { + return o.cancel(); + }); + } + }]); + return Result; +}(); + +function captureStacktrace() { + var error = new Error(''); + + if (error.stack) { + return error.stack.replace(/^Error(\n\r)*/, ''); // we don't need the 'Error\n' part, if only it exists + } + + return null; +} + +function replaceStacktrace(error, newStack) { + if (newStack) { + // Error.prototype.toString() concatenates error.name and error.message nicely + // then we add the rest of the stack trace + error.stack = error.toString() + '\n' + newStack; + } +} + +var _default = Result; +exports["default"] = _default; +}); + +var connectionProvider = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +interopRequireDefault(bookmark); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var ConnectionProvider = +/*#__PURE__*/ +function () { + function ConnectionProvider() { + (0, _classCallCheck2["default"])(this, ConnectionProvider); + } + + (0, _createClass2["default"])(ConnectionProvider, [{ + key: "acquireConnection", + + /** + * This method acquires a connection against the specified database. + * + * Access mode and Bookmarks only applies to routing driver. Access mode only + * differentiates the target server for the connection, where WRITE selects a + * WRITER server, whereas READ selects a READ server. Bookmarks, when specified, + * is only passed to the routing discovery procedure, for the system database to + * synchronize on creation of databases and is never used in direct drivers. + * + * @param {object} param - object parameter + * @param {string} param.accessMode - the access mode for the to-be-acquired connection + * @param {string} param.database - the target database for the to-be-acquired connection + * @param {Bookmark} param.bookmarks - the bookmarks to send to routing discovery + */ + value: function acquireConnection() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _ref.accessMode; + _ref.database; + _ref.bookmarks; + + throw new Error('not implemented'); + } + /** + * This method checks whether the backend database supports multi database functionality + * by checking protocol handshake result. + * + * @returns {Promise} + */ + + }, { + key: "supportsMultiDb", + value: function supportsMultiDb() { + throw new Error('not implemented'); + } + /** + * This method checks whether the backend database supports transaction config functionality + * by checking protocol handshake result. + * + * @returns {Promise} + */ + + }, { + key: "supportsTransactionConfig", + value: function supportsTransactionConfig() { + throw new Error('not implemented'); + } + /** + * Closes this connection provider along with its internals (connections, pools, etc.) + * + * @returns {Promise} + */ + + }, { + key: "close", + value: function close() { + throw new Error('not implemented'); + } + }]); + return ConnectionProvider; +}(); + +exports["default"] = ConnectionProvider; +}); + +var asyncToGenerator = createCommonjsModule(function (module) { +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value = info.value; + } catch (error) { + reject(error); + return; + } + + if (info.done) { + resolve(value); + } else { + Promise.resolve(value).then(_next, _throw); + } +} + +function _asyncToGenerator(fn) { + return function () { + var self = this, + args = arguments; + return new Promise(function (resolve, reject) { + var gen = fn.apply(self, args); + + function _next(value) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); + } + + function _throw(err) { + asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); + } + + _next(undefined); + }); + }; +} + +module.exports = _asyncToGenerator; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var channelConfig = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var DEFAULT_CONNECTION_TIMEOUT_MILLIS = 30000; // 30 seconds by default + +var ALLOWED_VALUES_ENCRYPTED = [null, undefined, true, false, util.ENCRYPTION_ON, util.ENCRYPTION_OFF]; +var ALLOWED_VALUES_TRUST = [null, undefined, 'TRUST_ALL_CERTIFICATES', 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES', 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES']; + +var ChannelConfig = +/** + * @constructor + * @param {ServerAddress} address the address for the channel to connect to. + * @param {Object} driverConfig the driver config provided by the user when driver is created. + * @param {string} connectionErrorCode the default error code to use on connection errors. + */ +function ChannelConfig(address, driverConfig, connectionErrorCode) { + (0, _classCallCheck2["default"])(this, ChannelConfig); + this.address = address; + this.encrypted = extractEncrypted(driverConfig); + this.trust = extractTrust(driverConfig); + this.trustedCertificates = extractTrustedCertificates(driverConfig); + this.knownHostsPath = extractKnownHostsPath(driverConfig); + this.connectionErrorCode = connectionErrorCode || error.SERVICE_UNAVAILABLE; + this.connectionTimeout = extractConnectionTimeout(driverConfig); +}; + +exports["default"] = ChannelConfig; + +function extractEncrypted(driverConfig) { + var value = driverConfig.encrypted; + + if (ALLOWED_VALUES_ENCRYPTED.indexOf(value) === -1) { + throw (0, error.newError)("Illegal value of the encrypted setting ".concat(value, ". Expected one of ").concat(ALLOWED_VALUES_ENCRYPTED)); + } + + return value; +} + +function extractTrust(driverConfig) { + var value = driverConfig.trust; + + if (ALLOWED_VALUES_TRUST.indexOf(value) === -1) { + throw (0, error.newError)("Illegal value of the trust setting ".concat(value, ". Expected one of ").concat(ALLOWED_VALUES_TRUST)); + } + + return value; +} + +function extractTrustedCertificates(driverConfig) { + return driverConfig.trustedCertificates || []; +} + +function extractKnownHostsPath(driverConfig) { + return driverConfig.knownHosts || null; +} + +function extractConnectionTimeout(driverConfig) { + var configuredTimeout = parseInt(driverConfig.connectionTimeout, 10); + + if (configuredTimeout === 0) { + // timeout explicitly configured to 0 + return null; + } else if (configuredTimeout && configuredTimeout < 0) { + // timeout explicitly configured to a negative value + return null; + } else if (!configuredTimeout) { + // timeout not configured, use default value + return DEFAULT_CONNECTION_TIMEOUT_MILLIS; + } else { + // timeout configured, use the provided value + return configuredTimeout; + } +} +}); + +var spatialTypes = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isPoint = isPoint; +exports.Point = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var POINT_IDENTIFIER_PROPERTY = '__isPoint__'; +/** + * Represents a single two or three-dimensional point in a particular coordinate reference system. + * Created `Point` objects are frozen with `Object.freeze()` in constructor and thus immutable. + */ + +var Point = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {Integer|number} srid - The coordinate reference system identifier. + * @param {number} x - The `x` coordinate of the point. + * @param {number} y - The `y` coordinate of the point. + * @param {number} [z=undefined] - The `z` coordinate of the point or `undefined` if point has 2 dimensions. + */ + function Point(srid, x, y, z) { + (0, _classCallCheck2["default"])(this, Point); + + /** + * The coordinate reference system identifier. + * @type {Integer|number} + */ + this.srid = (0, util.assertNumberOrInteger)(srid, 'SRID'); + /** + * The `x` coordinate of the point. + * @type {number} + */ + + this.x = (0, util.assertNumber)(x, 'X coordinate'); + /** + * The `y` coordinate of the point. + * @type {number} + */ + + this.y = (0, util.assertNumber)(y, 'Y coordinate'); + /** + * The `z` coordinate of the point or `undefined` if point is 2-dimensional. + * @type {number} + */ + + this.z = z === null || z === undefined ? z : (0, util.assertNumber)(z, 'Z coordinate'); + Object.freeze(this); + } + /** + * @ignore + */ + + + (0, _createClass2["default"])(Point, [{ + key: "toString", + value: function toString() { + return this.z || this.z === 0 ? "Point{srid=".concat(formatAsFloat(this.srid), ", x=").concat(formatAsFloat(this.x), ", y=").concat(formatAsFloat(this.y), ", z=").concat(formatAsFloat(this.z), "}") : "Point{srid=".concat(formatAsFloat(this.srid), ", x=").concat(formatAsFloat(this.x), ", y=").concat(formatAsFloat(this.y), "}"); + } + }]); + return Point; +}(); + +exports.Point = Point; + +function formatAsFloat(number) { + return Number.isInteger(number) ? number + '.0' : number.toString(); +} + +Object.defineProperty(Point.prototype, POINT_IDENTIFIER_PROPERTY, { + value: true, + enumerable: false, + configurable: false, + writable: false +}); +/** + * Test if given object is an instance of {@link Point} class. + * @param {Object} obj the object to test. + * @return {boolean} `true` if given object is a {@link Point}, `false` otherwise. + */ + +function isPoint(obj) { + return (obj && obj[POINT_IDENTIFIER_PROPERTY]) === true; +} +}); + +var normalizeSecondsForDuration_1 = normalizeSecondsForDuration; +var normalizeNanosecondsForDuration_1 = normalizeNanosecondsForDuration; +var localTimeToNanoOfDay_1 = localTimeToNanoOfDay; +var nanoOfDayToLocalTime_1 = nanoOfDayToLocalTime; +var localDateTimeToEpochSecond_1 = localDateTimeToEpochSecond; +var epochSecondAndNanoToLocalDateTime_1 = epochSecondAndNanoToLocalDateTime; +var dateToEpochDay_1 = dateToEpochDay; +var epochDayToDate_1 = epochDayToDate; +var durationToIsoString_1 = durationToIsoString; +var timeToIsoString_1 = timeToIsoString; +var timeZoneOffsetToIsoString_1 = timeZoneOffsetToIsoString; +var dateToIsoString_1 = dateToIsoString; +var totalNanoseconds_1 = totalNanoseconds; +var timeZoneOffsetInSeconds_1 = timeZoneOffsetInSeconds; +var assertValidYear_1 = assertValidYear; +var assertValidMonth_1 = assertValidMonth; +var assertValidDay_1 = assertValidDay; +var assertValidHour_1 = assertValidHour; +var assertValidMinute_1 = assertValidMinute; +var assertValidSecond_1 = assertValidSecond; +var assertValidNanosecond_1 = assertValidNanosecond; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + + + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* + Code in this util should be compatible with code in the database that uses JSR-310 java.time APIs. + + It is based on a library called ThreeTen (https://github.com/ThreeTen/threetenbp) which was derived + from JSR-310 reference implementation previously hosted on GitHub. Code uses `Integer` type everywhere + to correctly handle large integer values that are greater than `Number.MAX_SAFE_INTEGER`. + + Please consult either ThreeTen or js-joda (https://github.com/js-joda/js-joda) when working with the + conversion functions. + */ +var ValueRange = +/*#__PURE__*/ +function () { + function ValueRange(min, max) { + (0, _classCallCheck2["default"])(this, ValueRange); + this._minNumber = min; + this._maxNumber = max; + this._minInteger = (0, integer["int"])(min); + this._maxInteger = (0, integer["int"])(max); + } + + (0, _createClass2["default"])(ValueRange, [{ + key: "contains", + value: function contains(value) { + if ((0, integer.isInt)(value)) { + return value.greaterThanOrEqual(this._minInteger) && value.lessThanOrEqual(this._maxInteger); + } else { + return value >= this._minNumber && value <= this._maxNumber; + } + } + }, { + key: "toString", + value: function toString() { + return "[".concat(this._minNumber, ", ").concat(this._maxNumber, "]"); + } + }]); + return ValueRange; +}(); + +var YEAR_RANGE = new ValueRange(-999999999, 999999999); +var MONTH_OF_YEAR_RANGE = new ValueRange(1, 12); +var DAY_OF_MONTH_RANGE = new ValueRange(1, 31); +var HOUR_OF_DAY_RANGE = new ValueRange(0, 23); +var MINUTE_OF_HOUR_RANGE = new ValueRange(0, 59); +var SECOND_OF_MINUTE_RANGE = new ValueRange(0, 59); +var NANOSECOND_OF_SECOND_RANGE = new ValueRange(0, 999999999); +var MINUTES_PER_HOUR = 60; +var SECONDS_PER_MINUTE = 60; +var SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; +var NANOS_PER_SECOND = 1000000000; +var NANOS_PER_MILLISECOND = 1000000; +var NANOS_PER_MINUTE = NANOS_PER_SECOND * SECONDS_PER_MINUTE; +var NANOS_PER_HOUR = NANOS_PER_MINUTE * MINUTES_PER_HOUR; +var DAYS_0000_TO_1970 = 719528; +var DAYS_PER_400_YEAR_CYCLE = 146097; +var SECONDS_PER_DAY = 86400; + +function normalizeSecondsForDuration(seconds, nanoseconds) { + return (0, integer["int"])(seconds).add(floorDiv(nanoseconds, NANOS_PER_SECOND)); +} + +function normalizeNanosecondsForDuration(nanoseconds) { + return floorMod(nanoseconds, NANOS_PER_SECOND); +} +/** + * Converts given local time into a single integer representing this same time in nanoseconds of the day. + * @param {Integer|number|string} hour the hour of the local time to convert. + * @param {Integer|number|string} minute the minute of the local time to convert. + * @param {Integer|number|string} second the second of the local time to convert. + * @param {Integer|number|string} nanosecond the nanosecond of the local time to convert. + * @return {Integer} nanoseconds representing the given local time. + */ + + +function localTimeToNanoOfDay(hour, minute, second, nanosecond) { + hour = (0, integer["int"])(hour); + minute = (0, integer["int"])(minute); + second = (0, integer["int"])(second); + nanosecond = (0, integer["int"])(nanosecond); + var totalNanos = hour.multiply(NANOS_PER_HOUR); + totalNanos = totalNanos.add(minute.multiply(NANOS_PER_MINUTE)); + totalNanos = totalNanos.add(second.multiply(NANOS_PER_SECOND)); + return totalNanos.add(nanosecond); +} +/** + * Converts nanoseconds of the day into local time. + * @param {Integer|number|string} nanoOfDay the nanoseconds of the day to convert. + * @return {LocalTime} the local time representing given nanoseconds of the day. + */ + + +function nanoOfDayToLocalTime(nanoOfDay) { + nanoOfDay = (0, integer["int"])(nanoOfDay); + var hour = nanoOfDay.div(NANOS_PER_HOUR); + nanoOfDay = nanoOfDay.subtract(hour.multiply(NANOS_PER_HOUR)); + var minute = nanoOfDay.div(NANOS_PER_MINUTE); + nanoOfDay = nanoOfDay.subtract(minute.multiply(NANOS_PER_MINUTE)); + var second = nanoOfDay.div(NANOS_PER_SECOND); + var nanosecond = nanoOfDay.subtract(second.multiply(NANOS_PER_SECOND)); + return new temporalTypes.LocalTime(hour, minute, second, nanosecond); +} +/** + * Converts given local date time into a single integer representing this same time in epoch seconds UTC. + * @param {Integer|number|string} year the year of the local date-time to convert. + * @param {Integer|number|string} month the month of the local date-time to convert. + * @param {Integer|number|string} day the day of the local date-time to convert. + * @param {Integer|number|string} hour the hour of the local date-time to convert. + * @param {Integer|number|string} minute the minute of the local date-time to convert. + * @param {Integer|number|string} second the second of the local date-time to convert. + * @param {Integer|number|string} nanosecond the nanosecond of the local date-time to convert. + * @return {Integer} epoch second in UTC representing the given local date time. + */ + + +function localDateTimeToEpochSecond(year, month, day, hour, minute, second, nanosecond) { + var epochDay = dateToEpochDay(year, month, day); + var localTimeSeconds = localTimeToSecondOfDay(hour, minute, second); + return epochDay.multiply(SECONDS_PER_DAY).add(localTimeSeconds); +} +/** + * Converts given epoch second and nanosecond adjustment into a local date time object. + * @param {Integer|number|string} epochSecond the epoch second to use. + * @param {Integer|number|string} nano the nanosecond to use. + * @return {LocalDateTime} the local date time representing given epoch second and nano. + */ + + +function epochSecondAndNanoToLocalDateTime(epochSecond, nano) { + var epochDay = floorDiv(epochSecond, SECONDS_PER_DAY); + var secondsOfDay = floorMod(epochSecond, SECONDS_PER_DAY); + var nanoOfDay = secondsOfDay.multiply(NANOS_PER_SECOND).add(nano); + var localDate = epochDayToDate(epochDay); + var localTime = nanoOfDayToLocalTime(nanoOfDay); + return new temporalTypes.LocalDateTime(localDate.year, localDate.month, localDate.day, localTime.hour, localTime.minute, localTime.second, localTime.nanosecond); +} +/** + * Converts given local date into a single integer representing it's epoch day. + * @param {Integer|number|string} year the year of the local date to convert. + * @param {Integer|number|string} month the month of the local date to convert. + * @param {Integer|number|string} day the day of the local date to convert. + * @return {Integer} epoch day representing the given date. + */ + + +function dateToEpochDay(year, month, day) { + year = (0, integer["int"])(year); + month = (0, integer["int"])(month); + day = (0, integer["int"])(day); + var epochDay = year.multiply(365); + + if (year.greaterThanOrEqual(0)) { + epochDay = epochDay.add(year.add(3).div(4).subtract(year.add(99).div(100)).add(year.add(399).div(400))); + } else { + epochDay = epochDay.subtract(year.div(-4).subtract(year.div(-100)).add(year.div(-400))); + } + + epochDay = epochDay.add(month.multiply(367).subtract(362).div(12)); + epochDay = epochDay.add(day.subtract(1)); + + if (month.greaterThan(2)) { + epochDay = epochDay.subtract(1); + + if (!isLeapYear(year)) { + epochDay = epochDay.subtract(1); + } + } + + return epochDay.subtract(DAYS_0000_TO_1970); +} +/** + * Converts given epoch day to a local date. + * @param {Integer|number|string} epochDay the epoch day to convert. + * @return {Date} the date representing the epoch day in years, months and days. + */ + + +function epochDayToDate(epochDay) { + epochDay = (0, integer["int"])(epochDay); + var zeroDay = epochDay.add(DAYS_0000_TO_1970).subtract(60); + var adjust = (0, integer["int"])(0); + + if (zeroDay.lessThan(0)) { + var adjustCycles = zeroDay.add(1).div(DAYS_PER_400_YEAR_CYCLE).subtract(1); + adjust = adjustCycles.multiply(400); + zeroDay = zeroDay.add(adjustCycles.multiply(-DAYS_PER_400_YEAR_CYCLE)); + } + + var year = zeroDay.multiply(400).add(591).div(DAYS_PER_400_YEAR_CYCLE); + var dayOfYearEst = zeroDay.subtract(year.multiply(365).add(year.div(4)).subtract(year.div(100)).add(year.div(400))); + + if (dayOfYearEst.lessThan(0)) { + year = year.subtract(1); + dayOfYearEst = zeroDay.subtract(year.multiply(365).add(year.div(4)).subtract(year.div(100)).add(year.div(400))); + } + + year = year.add(adjust); + var marchDayOfYear = dayOfYearEst; + var marchMonth = marchDayOfYear.multiply(5).add(2).div(153); + var month = marchMonth.add(2).modulo(12).add(1); + var day = marchDayOfYear.subtract(marchMonth.multiply(306).add(5).div(10)).add(1); + year = year.add(marchMonth.div(10)); + return new temporalTypes.Date(year, month, day); +} +/** + * Format given duration to an ISO 8601 string. + * @param {Integer|number|string} months the number of months. + * @param {Integer|number|string} days the number of days. + * @param {Integer|number|string} seconds the number of seconds. + * @param {Integer|number|string} nanoseconds the number of nanoseconds. + * @return {string} ISO string that represents given duration. + */ + + +function durationToIsoString(months, days, seconds, nanoseconds) { + var monthsString = formatNumber(months); + var daysString = formatNumber(days); + var secondsAndNanosecondsString = formatSecondsAndNanosecondsForDuration(seconds, nanoseconds); + return "P".concat(monthsString, "M").concat(daysString, "DT").concat(secondsAndNanosecondsString, "S"); +} +/** + * Formats given time to an ISO 8601 string. + * @param {Integer|number|string} hour the hour value. + * @param {Integer|number|string} minute the minute value. + * @param {Integer|number|string} second the second value. + * @param {Integer|number|string} nanosecond the nanosecond value. + * @return {string} ISO string that represents given time. + */ + + +function timeToIsoString(hour, minute, second, nanosecond) { + var hourString = formatNumber(hour, 2); + var minuteString = formatNumber(minute, 2); + var secondString = formatNumber(second, 2); + var nanosecondString = formatNanosecond(nanosecond); + return "".concat(hourString, ":").concat(minuteString, ":").concat(secondString).concat(nanosecondString); +} +/** + * Formats given time zone offset in seconds to string representation like '±HH:MM', '±HH:MM:SS' or 'Z' for UTC. + * @param {Integer|number|string} offsetSeconds the offset in seconds. + * @return {string} ISO string that represents given offset. + */ + + +function timeZoneOffsetToIsoString(offsetSeconds) { + offsetSeconds = (0, integer["int"])(offsetSeconds); + + if (offsetSeconds.equals(0)) { + return 'Z'; + } + + var isNegative = offsetSeconds.isNegative(); + + if (isNegative) { + offsetSeconds = offsetSeconds.multiply(-1); + } + + var signPrefix = isNegative ? '-' : '+'; + var hours = formatNumber(offsetSeconds.div(SECONDS_PER_HOUR), 2); + var minutes = formatNumber(offsetSeconds.div(SECONDS_PER_MINUTE).modulo(MINUTES_PER_HOUR), 2); + var secondsValue = offsetSeconds.modulo(SECONDS_PER_MINUTE); + var seconds = secondsValue.equals(0) ? null : formatNumber(secondsValue, 2); + return seconds ? "".concat(signPrefix).concat(hours, ":").concat(minutes, ":").concat(seconds) : "".concat(signPrefix).concat(hours, ":").concat(minutes); +} +/** + * Formats given date to an ISO 8601 string. + * @param {Integer|number|string} year the date year. + * @param {Integer|number|string} month the date month. + * @param {Integer|number|string} day the date day. + * @return {string} ISO string that represents given date. + */ + + +function dateToIsoString(year, month, day) { + year = (0, integer["int"])(year); + var isNegative = year.isNegative(); + + if (isNegative) { + year = year.multiply(-1); + } + + var yearString = formatNumber(year, 4); + + if (isNegative) { + yearString = '-' + yearString; + } + + var monthString = formatNumber(month, 2); + var dayString = formatNumber(day, 2); + return "".concat(yearString, "-").concat(monthString, "-").concat(dayString); +} +/** + * Get the total number of nanoseconds from the milliseconds of the given standard JavaScript date and optional nanosecond part. + * @param {global.Date} standardDate the standard JavaScript date. + * @param {Integer|number|undefined} nanoseconds the optional number of nanoseconds. + * @return {Integer|number} the total amount of nanoseconds. + */ + + +function totalNanoseconds(standardDate, nanoseconds) { + nanoseconds = nanoseconds || 0; + var nanosFromMillis = standardDate.getMilliseconds() * NANOS_PER_MILLISECOND; + return (0, integer.isInt)(nanoseconds) ? nanoseconds.add(nanosFromMillis) : nanoseconds + nanosFromMillis; +} +/** + * Get the time zone offset in seconds from the given standard JavaScript date. + * + * Implementation note: + * Time zone offset returned by the standard JavaScript date is the difference, in minutes, from local time to UTC. + * So positive value means offset is behind UTC and negative value means it is ahead. + * For Neo4j temporal types, like `Time` or `DateTime` offset is in seconds and represents difference from UTC to local time. + * This is different from standard JavaScript dates and that's why implementation negates the returned value. + * + * @param {global.Date} standardDate the standard JavaScript date. + * @return {number} the time zone offset in seconds. + */ + + +function timeZoneOffsetInSeconds(standardDate) { + var offsetInMinutes = standardDate.getTimezoneOffset(); + + if (offsetInMinutes === 0) { + return 0; + } + + return -1 * offsetInMinutes * SECONDS_PER_MINUTE; +} +/** + * Assert that the year value is valid. + * @param {Integer|number} year the value to check. + * @return {Integer|number} the value of the year if it is valid. Exception is thrown otherwise. + */ + + +function assertValidYear(year) { + return assertValidTemporalValue(year, YEAR_RANGE, 'Year'); +} +/** + * Assert that the month value is valid. + * @param {Integer|number} month the value to check. + * @return {Integer|number} the value of the month if it is valid. Exception is thrown otherwise. + */ + + +function assertValidMonth(month) { + return assertValidTemporalValue(month, MONTH_OF_YEAR_RANGE, 'Month'); +} +/** + * Assert that the day value is valid. + * @param {Integer|number} day the value to check. + * @return {Integer|number} the value of the day if it is valid. Exception is thrown otherwise. + */ + + +function assertValidDay(day) { + return assertValidTemporalValue(day, DAY_OF_MONTH_RANGE, 'Day'); +} +/** + * Assert that the hour value is valid. + * @param {Integer|number} hour the value to check. + * @return {Integer|number} the value of the hour if it is valid. Exception is thrown otherwise. + */ + + +function assertValidHour(hour) { + return assertValidTemporalValue(hour, HOUR_OF_DAY_RANGE, 'Hour'); +} +/** + * Assert that the minute value is valid. + * @param {Integer|number} minute the value to check. + * @return {Integer|number} the value of the minute if it is valid. Exception is thrown otherwise. + */ + + +function assertValidMinute(minute) { + return assertValidTemporalValue(minute, MINUTE_OF_HOUR_RANGE, 'Minute'); +} +/** + * Assert that the second value is valid. + * @param {Integer|number} second the value to check. + * @return {Integer|number} the value of the second if it is valid. Exception is thrown otherwise. + */ + + +function assertValidSecond(second) { + return assertValidTemporalValue(second, SECOND_OF_MINUTE_RANGE, 'Second'); +} +/** + * Assert that the nanosecond value is valid. + * @param {Integer|number} nanosecond the value to check. + * @return {Integer|number} the value of the nanosecond if it is valid. Exception is thrown otherwise. + */ + + +function assertValidNanosecond(nanosecond) { + return assertValidTemporalValue(nanosecond, NANOSECOND_OF_SECOND_RANGE, 'Nanosecond'); +} +/** + * Check if the given value is of expected type and is in the expected range. + * @param {Integer|number} value the value to check. + * @param {ValueRange} range the range. + * @param {string} name the name of the value. + * @return {Integer|number} the value if valid. Exception is thrown otherwise. + */ + + +function assertValidTemporalValue(value, range, name) { + (0, util.assertNumberOrInteger)(value, name); + + if (!range.contains(value)) { + throw (0, error.newError)("".concat(name, " is expected to be in range ").concat(range, " but was: ").concat(value)); + } + + return value; +} +/** + * Converts given local time into a single integer representing this same time in seconds of the day. Nanoseconds are skipped. + * @param {Integer|number|string} hour the hour of the local time. + * @param {Integer|number|string} minute the minute of the local time. + * @param {Integer|number|string} second the second of the local time. + * @return {Integer} seconds representing the given local time. + */ + + +function localTimeToSecondOfDay(hour, minute, second) { + hour = (0, integer["int"])(hour); + minute = (0, integer["int"])(minute); + second = (0, integer["int"])(second); + var totalSeconds = hour.multiply(SECONDS_PER_HOUR); + totalSeconds = totalSeconds.add(minute.multiply(SECONDS_PER_MINUTE)); + return totalSeconds.add(second); +} +/** + * Check if given year is a leap year. Uses algorithm described here {@link https://en.wikipedia.org/wiki/Leap_year#Algorithm}. + * @param {Integer|number|string} year the year to check. Will be converted to {@link Integer} for all calculations. + * @return {boolean} `true` if given year is a leap year, `false` otherwise. + */ + + +function isLeapYear(year) { + year = (0, integer["int"])(year); + + if (!year.modulo(4).equals(0)) { + return false; + } else if (!year.modulo(100).equals(0)) { + return true; + } else if (!year.modulo(400).equals(0)) { + return false; + } else { + return true; + } +} +/** + * @param {Integer|number|string} x the divident. + * @param {Integer|number|string} y the divisor. + * @return {Integer} the result. + */ + + +function floorDiv(x, y) { + x = (0, integer["int"])(x); + y = (0, integer["int"])(y); + var result = x.div(y); + + if (x.isPositive() !== y.isPositive() && result.multiply(y).notEquals(x)) { + result = result.subtract(1); + } + + return result; +} +/** + * @param {Integer|number|string} x the divident. + * @param {Integer|number|string} y the divisor. + * @return {Integer} the result. + */ + + +function floorMod(x, y) { + x = (0, integer["int"])(x); + y = (0, integer["int"])(y); + return x.subtract(floorDiv(x, y).multiply(y)); +} +/** + * @param {Integer|number|string} seconds the number of seconds to format. + * @param {Integer|number|string} nanoseconds the number of nanoseconds to format. + * @return {string} formatted value. + */ + + +function formatSecondsAndNanosecondsForDuration(seconds, nanoseconds) { + seconds = (0, integer["int"])(seconds); + nanoseconds = (0, integer["int"])(nanoseconds); + var secondsString; + var nanosecondsString; + var secondsNegative = seconds.isNegative(); + var nanosecondsGreaterThanZero = nanoseconds.greaterThan(0); + + if (secondsNegative && nanosecondsGreaterThanZero) { + if (seconds.equals(-1)) { + secondsString = '-0'; + } else { + secondsString = seconds.add(1).toString(); + } + } else { + secondsString = seconds.toString(); + } + + if (nanosecondsGreaterThanZero) { + if (secondsNegative) { + nanosecondsString = formatNanosecond(nanoseconds.negate().add(2 * NANOS_PER_SECOND).modulo(NANOS_PER_SECOND)); + } else { + nanosecondsString = formatNanosecond(nanoseconds.add(NANOS_PER_SECOND).modulo(NANOS_PER_SECOND)); + } + } + + return nanosecondsString ? secondsString + nanosecondsString : secondsString; +} +/** + * @param {Integer|number|string} value the number of nanoseconds to format. + * @return {string} formatted and possibly left-padded nanoseconds part as string. + */ + + +function formatNanosecond(value) { + value = (0, integer["int"])(value); + return value.equals(0) ? '' : '.' + formatNumber(value, 9); +} +/** + * @param {Integer|number|string} num the number to format. + * @param {number} [stringLength=undefined] the string length to left-pad to. + * @return {string} formatted and possibly left-padded number as string. + */ + + +function formatNumber(num) { + var stringLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; + num = (0, integer["int"])(num); + var isNegative = num.isNegative(); + + if (isNegative) { + num = num.negate(); + } + + var numString = num.toString(); + + if (stringLength) { + // left pad the string with zeroes + while (numString.length < stringLength) { + numString = '0' + numString; + } + } + + return isNegative ? '-' + numString : numString; +} + +var temporalUtil = /*#__PURE__*/Object.defineProperty({ + normalizeSecondsForDuration: normalizeSecondsForDuration_1, + normalizeNanosecondsForDuration: normalizeNanosecondsForDuration_1, + localTimeToNanoOfDay: localTimeToNanoOfDay_1, + nanoOfDayToLocalTime: nanoOfDayToLocalTime_1, + localDateTimeToEpochSecond: localDateTimeToEpochSecond_1, + epochSecondAndNanoToLocalDateTime: epochSecondAndNanoToLocalDateTime_1, + dateToEpochDay: dateToEpochDay_1, + epochDayToDate: epochDayToDate_1, + durationToIsoString: durationToIsoString_1, + timeToIsoString: timeToIsoString_1, + timeZoneOffsetToIsoString: timeZoneOffsetToIsoString_1, + dateToIsoString: dateToIsoString_1, + totalNanoseconds: totalNanoseconds_1, + timeZoneOffsetInSeconds: timeZoneOffsetInSeconds_1, + assertValidYear: assertValidYear_1, + assertValidMonth: assertValidMonth_1, + assertValidDay: assertValidDay_1, + assertValidHour: assertValidHour_1, + assertValidMinute: assertValidMinute_1, + assertValidSecond: assertValidSecond_1, + assertValidNanosecond: assertValidNanosecond_1 +}, '__esModule', {value: true}); + +var temporalTypes = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.isDuration = isDuration; +exports.isLocalTime = isLocalTime; +exports.isTime = isTime; +exports.isDate = isDate; +exports.isLocalDateTime = isLocalDateTime; +exports.isDateTime = isDateTime; +exports.DateTime = exports.LocalDateTime = exports.Date = exports.Time = exports.LocalTime = exports.Duration = void 0; + +var _slicedToArray2 = interopRequireDefault(slicedToArray); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var util$1 = interopRequireWildcard(temporalUtil); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var IDENTIFIER_PROPERTY_ATTRIBUTES = { + value: true, + enumerable: false, + configurable: false, + writable: false +}; +var DURATION_IDENTIFIER_PROPERTY = '__isDuration__'; +var LOCAL_TIME_IDENTIFIER_PROPERTY = '__isLocalTime__'; +var TIME_IDENTIFIER_PROPERTY = '__isTime__'; +var DATE_IDENTIFIER_PROPERTY = '__isDate__'; +var LOCAL_DATE_TIME_IDENTIFIER_PROPERTY = '__isLocalDateTime__'; +var DATE_TIME_IDENTIFIER_PROPERTY = '__isDateTime__'; +/** + * Represents an ISO 8601 duration. Contains both date-based values (years, months, days) and time-based values (seconds, nanoseconds). + * Created `Duration` objects are frozen with `Object.freeze()` in constructor and thus immutable. + */ + +var Duration = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {Integer|number} months - The number of months for the new duration. + * @param {Integer|number} days - The number of days for the new duration. + * @param {Integer|number} seconds - The number of seconds for the new duration. + * @param {Integer|number} nanoseconds - The number of nanoseconds for the new duration. + */ + function Duration(months, days, seconds, nanoseconds) { + (0, _classCallCheck2["default"])(this, Duration); + + /** + * The number of months. + * @type {Integer|number} + */ + this.months = (0, util.assertNumberOrInteger)(months, 'Months'); + /** + * The number of days. + * @type {Integer|number} + */ + + this.days = (0, util.assertNumberOrInteger)(days, 'Days'); + (0, util.assertNumberOrInteger)(seconds, 'Seconds'); + (0, util.assertNumberOrInteger)(nanoseconds, 'Nanoseconds'); + /** + * The number of seconds. + * @type {Integer|number} + */ + + this.seconds = util$1.normalizeSecondsForDuration(seconds, nanoseconds); + /** + * The number of nanoseconds. + * @type {Integer|number} + */ + + this.nanoseconds = util$1.normalizeNanosecondsForDuration(nanoseconds); + Object.freeze(this); + } + /** + * @ignore + */ + + + (0, _createClass2["default"])(Duration, [{ + key: "toString", + value: function toString() { + return util$1.durationToIsoString(this.months, this.days, this.seconds, this.nanoseconds); + } + }]); + return Duration; +}(); + +exports.Duration = Duration; +Object.defineProperty(Duration.prototype, DURATION_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); +/** + * Test if given object is an instance of {@link Duration} class. + * @param {Object} obj the object to test. + * @return {boolean} `true` if given object is a {@link Duration}, `false` otherwise. + */ + +function isDuration(obj) { + return hasIdentifierProperty(obj, DURATION_IDENTIFIER_PROPERTY); +} +/** + * Represents an instant capturing the time of day, but not the date, nor the timezone. + * Created {@link LocalTime} objects are frozen with `Object.freeze()` in constructor and thus immutable. + */ + + +var LocalTime = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {Integer|number} hour - The hour for the new local time. + * @param {Integer|number} minute - The minute for the new local time. + * @param {Integer|number} second - The second for the new local time. + * @param {Integer|number} nanosecond - The nanosecond for the new local time. + */ + function LocalTime(hour, minute, second, nanosecond) { + (0, _classCallCheck2["default"])(this, LocalTime); + + /** + * The hour. + * @type {Integer|number} + */ + this.hour = util$1.assertValidHour(hour); + /** + * The minute. + * @type {Integer|number} + */ + + this.minute = util$1.assertValidMinute(minute); + /** + * The second. + * @type {Integer|number} + */ + + this.second = util$1.assertValidSecond(second); + /** + * The nanosecond. + * @type {Integer|number} + */ + + this.nanosecond = util$1.assertValidNanosecond(nanosecond); + Object.freeze(this); + } + /** + * Create a {@link LocalTime} object from the given standard JavaScript `Date` and optional nanoseconds. + * Year, month, day and time zone offset components of the given date are ignored. + * @param {global.Date} standardDate - The standard JavaScript date to convert. + * @param {Integer|number|undefined} nanosecond - The optional amount of nanoseconds. + * @return {LocalTime} New LocalTime. + */ + + + (0, _createClass2["default"])(LocalTime, [{ + key: "toString", + + /** + * @ignore + */ + value: function toString() { + return util$1.timeToIsoString(this.hour, this.minute, this.second, this.nanosecond); + } + }], [{ + key: "fromStandardDate", + value: function fromStandardDate(standardDate, nanosecond) { + verifyStandardDateAndNanos(standardDate, nanosecond); + return new LocalTime(standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util$1.totalNanoseconds(standardDate, nanosecond)); + } + }]); + return LocalTime; +}(); + +exports.LocalTime = LocalTime; +Object.defineProperty(LocalTime.prototype, LOCAL_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); +/** + * Test if given object is an instance of {@link LocalTime} class. + * @param {Object} obj the object to test. + * @return {boolean} `true` if given object is a {@link LocalTime}, `false` otherwise. + */ + +function isLocalTime(obj) { + return hasIdentifierProperty(obj, LOCAL_TIME_IDENTIFIER_PROPERTY); +} +/** + * Represents an instant capturing the time of day, and the timezone offset in seconds, but not the date. + * Created {@link Time} objects are frozen with `Object.freeze()` in constructor and thus immutable. + */ + + +var Time = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {Integer|number} hour - The hour for the new local time. + * @param {Integer|number} minute - The minute for the new local time. + * @param {Integer|number} second - The second for the new local time. + * @param {Integer|number} nanosecond - The nanosecond for the new local time. + * @param {Integer|number} timeZoneOffsetSeconds - The time zone offset in seconds. Value represents the difference, in seconds, from UTC to local time. + * This is different from standard JavaScript `Date.getTimezoneOffset()` which is the difference, in minutes, from local time to UTC. + */ + function Time(hour, minute, second, nanosecond, timeZoneOffsetSeconds) { + (0, _classCallCheck2["default"])(this, Time); + + /** + * The hour. + * @type {Integer|number} + */ + this.hour = util$1.assertValidHour(hour); + /** + * The minute. + * @type {Integer|number} + */ + + this.minute = util$1.assertValidMinute(minute); + /** + * The second. + * @type {Integer|number} + */ + + this.second = util$1.assertValidSecond(second); + /** + * The nanosecond. + * @type {Integer|number} + */ + + this.nanosecond = util$1.assertValidNanosecond(nanosecond); + /** + * The time zone offset in seconds. + * @type {Integer|number} + */ + + this.timeZoneOffsetSeconds = (0, util.assertNumberOrInteger)(timeZoneOffsetSeconds, 'Time zone offset in seconds'); + Object.freeze(this); + } + /** + * Create a {@link Time} object from the given standard JavaScript `Date` and optional nanoseconds. + * Year, month and day components of the given date are ignored. + * @param {global.Date} standardDate - The standard JavaScript date to convert. + * @param {Integer|number|undefined} nanosecond - The optional amount of nanoseconds. + * @return {Time} New Time. + */ + + + (0, _createClass2["default"])(Time, [{ + key: "toString", + + /** + * @ignore + */ + value: function toString() { + return util$1.timeToIsoString(this.hour, this.minute, this.second, this.nanosecond) + util$1.timeZoneOffsetToIsoString(this.timeZoneOffsetSeconds); + } + }], [{ + key: "fromStandardDate", + value: function fromStandardDate(standardDate, nanosecond) { + verifyStandardDateAndNanos(standardDate, nanosecond); + return new Time(standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util$1.totalNanoseconds(standardDate, nanosecond), util$1.timeZoneOffsetInSeconds(standardDate)); + } + }]); + return Time; +}(); + +exports.Time = Time; +Object.defineProperty(Time.prototype, TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); +/** + * Test if given object is an instance of {@link Time} class. + * @param {Object} obj the object to test. + * @return {boolean} `true` if given object is a {@link Time}, `false` otherwise. + */ + +function isTime(obj) { + return hasIdentifierProperty(obj, TIME_IDENTIFIER_PROPERTY); +} +/** + * Represents an instant capturing the date, but not the time, nor the timezone. + * Created {@link Date} objects are frozen with `Object.freeze()` in constructor and thus immutable. + */ + + +var Date = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {Integer|number} year - The year for the new local date. + * @param {Integer|number} month - The month for the new local date. + * @param {Integer|number} day - The day for the new local date. + */ + function Date(year, month, day) { + (0, _classCallCheck2["default"])(this, Date); + + /** + * The year. + * @type {Integer|number} + */ + this.year = util$1.assertValidYear(year); + /** + * The month. + * @type {Integer|number} + */ + + this.month = util$1.assertValidMonth(month); + /** + * The day. + * @type {Integer|number} + */ + + this.day = util$1.assertValidDay(day); + Object.freeze(this); + } + /** + * Create a {@link Date} object from the given standard JavaScript `Date`. + * Hour, minute, second, millisecond and time zone offset components of the given date are ignored. + * @param {global.Date} standardDate - The standard JavaScript date to convert. + * @return {Date} New Date. + */ + + + (0, _createClass2["default"])(Date, [{ + key: "toString", + + /** + * @ignore + */ + value: function toString() { + return util$1.dateToIsoString(this.year, this.month, this.day); + } + }], [{ + key: "fromStandardDate", + value: function fromStandardDate(standardDate) { + verifyStandardDateAndNanos(standardDate, null); + return new Date(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate()); + } + }]); + return Date; +}(); + +exports.Date = Date; +Object.defineProperty(Date.prototype, DATE_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); +/** + * Test if given object is an instance of {@link Date} class. + * @param {Object} obj - The object to test. + * @return {boolean} `true` if given object is a {@link Date}, `false` otherwise. + */ + +function isDate(obj) { + return hasIdentifierProperty(obj, DATE_IDENTIFIER_PROPERTY); +} +/** + * Represents an instant capturing the date and the time, but not the timezone. + * Created {@link LocalDateTime} objects are frozen with `Object.freeze()` in constructor and thus immutable. + */ + + +var LocalDateTime = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {Integer|number} year - The year for the new local date. + * @param {Integer|number} month - The month for the new local date. + * @param {Integer|number} day - The day for the new local date. + * @param {Integer|number} hour - The hour for the new local time. + * @param {Integer|number} minute - The minute for the new local time. + * @param {Integer|number} second - The second for the new local time. + * @param {Integer|number} nanosecond - The nanosecond for the new local time. + */ + function LocalDateTime(year, month, day, hour, minute, second, nanosecond) { + (0, _classCallCheck2["default"])(this, LocalDateTime); + + /** + * The year. + * @type {Integer|number} + */ + this.year = util$1.assertValidYear(year); + /** + * The month. + * @type {Integer|number} + */ + + this.month = util$1.assertValidMonth(month); + /** + * The day. + * @type {Integer|number} + */ + + this.day = util$1.assertValidDay(day); + /** + * The hour. + * @type {Integer|number} + */ + + this.hour = util$1.assertValidHour(hour); + /** + * The minute. + * @type {Integer|number} + */ + + this.minute = util$1.assertValidMinute(minute); + /** + * The second. + * @type {Integer|number} + */ + + this.second = util$1.assertValidSecond(second); + /** + * The nanosecond. + * @type {Integer|number} + */ + + this.nanosecond = util$1.assertValidNanosecond(nanosecond); + Object.freeze(this); + } + /** + * Create a {@link LocalDateTime} object from the given standard JavaScript `Date` and optional nanoseconds. + * Time zone offset component of the given date is ignored. + * @param {global.Date} standardDate - The standard JavaScript date to convert. + * @param {Integer|number|undefined} nanosecond - The optional amount of nanoseconds. + * @return {LocalDateTime} New LocalDateTime. + */ + + + (0, _createClass2["default"])(LocalDateTime, [{ + key: "toString", + + /** + * @ignore + */ + value: function toString() { + return localDateTimeToString(this.year, this.month, this.day, this.hour, this.minute, this.second, this.nanosecond); + } + }], [{ + key: "fromStandardDate", + value: function fromStandardDate(standardDate, nanosecond) { + verifyStandardDateAndNanos(standardDate, nanosecond); + return new LocalDateTime(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate(), standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util$1.totalNanoseconds(standardDate, nanosecond)); + } + }]); + return LocalDateTime; +}(); + +exports.LocalDateTime = LocalDateTime; +Object.defineProperty(LocalDateTime.prototype, LOCAL_DATE_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); +/** + * Test if given object is an instance of {@link LocalDateTime} class. + * @param {Object} obj - The object to test. + * @return {boolean} `true` if given object is a {@link LocalDateTime}, `false` otherwise. + */ + +function isLocalDateTime(obj) { + return hasIdentifierProperty(obj, LOCAL_DATE_TIME_IDENTIFIER_PROPERTY); +} +/** + * Represents an instant capturing the date, the time and the timezone identifier. + * Created {@ DateTime} objects are frozen with `Object.freeze()` in constructor and thus immutable. + */ + + +var DateTime = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {Integer|number} year - The year for the new date-time. + * @param {Integer|number} month - The month for the new date-time. + * @param {Integer|number} day - The day for the new date-time. + * @param {Integer|number} hour - The hour for the new date-time. + * @param {Integer|number} minute - The minute for the new date-time. + * @param {Integer|number} second - The second for the new date-time. + * @param {Integer|number} nanosecond - The nanosecond for the new date-time. + * @param {Integer|number} timeZoneOffsetSeconds - The time zone offset in seconds. Either this argument or `timeZoneId` should be defined. + * Value represents the difference, in seconds, from UTC to local time. + * This is different from standard JavaScript `Date.getTimezoneOffset()` which is the difference, in minutes, from local time to UTC. + * @param {string|null} timeZoneId - The time zone id for the new date-time. Either this argument or `timeZoneOffsetSeconds` should be defined. + */ + function DateTime(year, month, day, hour, minute, second, nanosecond, timeZoneOffsetSeconds, timeZoneId) { + (0, _classCallCheck2["default"])(this, DateTime); + + /** + * The year. + * @type {Integer|number} + */ + this.year = util$1.assertValidYear(year); + /** + * The month. + * @type {Integer|number} + */ + + this.month = util$1.assertValidMonth(month); + /** + * The day. + * @type {Integer|number} + */ + + this.day = util$1.assertValidDay(day); + /** + * The hour. + * @type {Integer|number} + */ + + this.hour = util$1.assertValidHour(hour); + /** + * The minute. + * @type {Integer|number} + */ + + this.minute = util$1.assertValidMinute(minute); + /** + * The second. + * @type {Integer|number} + */ + + this.second = util$1.assertValidSecond(second); + /** + * The nanosecond. + * @type {Integer|number} + */ + + this.nanosecond = util$1.assertValidNanosecond(nanosecond); + + var _verifyTimeZoneArgume = verifyTimeZoneArguments(timeZoneOffsetSeconds, timeZoneId), + _verifyTimeZoneArgume2 = (0, _slicedToArray2["default"])(_verifyTimeZoneArgume, 2), + offset = _verifyTimeZoneArgume2[0], + id = _verifyTimeZoneArgume2[1]; + /** + * The time zone offset in seconds. + * + * *Either this or {@link timeZoneId} is defined.* + * + * @type {Integer|number} + */ + + + this.timeZoneOffsetSeconds = offset; + /** + * The time zone id. + * + * *Either this or {@link timeZoneOffsetSeconds} is defined.* + * + * @type {string} + */ + + this.timeZoneId = id; + Object.freeze(this); + } + /** + * Create a {@link DateTime} object from the given standard JavaScript `Date` and optional nanoseconds. + * @param {global.Date} standardDate - The standard JavaScript date to convert. + * @param {Integer|number|undefined} nanosecond - The optional amount of nanoseconds. + * @return {DateTime} New DateTime. + */ + + + (0, _createClass2["default"])(DateTime, [{ + key: "toString", + + /** + * @ignore + */ + value: function toString() { + var localDateTimeStr = localDateTimeToString(this.year, this.month, this.day, this.hour, this.minute, this.second, this.nanosecond); + var timeZoneStr = this.timeZoneId ? "[".concat(this.timeZoneId, "]") : util$1.timeZoneOffsetToIsoString(this.timeZoneOffsetSeconds); + return localDateTimeStr + timeZoneStr; + } + }], [{ + key: "fromStandardDate", + value: function fromStandardDate(standardDate, nanosecond) { + verifyStandardDateAndNanos(standardDate, nanosecond); + return new DateTime(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate(), standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util$1.totalNanoseconds(standardDate, nanosecond), util$1.timeZoneOffsetInSeconds(standardDate), null + /* no time zone id */ + ); + } + }]); + return DateTime; +}(); + +exports.DateTime = DateTime; +Object.defineProperty(DateTime.prototype, DATE_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); +/** + * Test if given object is an instance of {@link DateTime} class. + * @param {Object} obj - The object to test. + * @return {boolean} `true` if given object is a {@link DateTime}, `false` otherwise. + */ + +function isDateTime(obj) { + return hasIdentifierProperty(obj, DATE_TIME_IDENTIFIER_PROPERTY); +} + +function hasIdentifierProperty(obj, property) { + return (obj && obj[property]) === true; +} + +function localDateTimeToString(year, month, day, hour, minute, second, nanosecond) { + return util$1.dateToIsoString(year, month, day) + 'T' + util$1.timeToIsoString(hour, minute, second, nanosecond); +} + +function verifyTimeZoneArguments(timeZoneOffsetSeconds, timeZoneId) { + var offsetDefined = timeZoneOffsetSeconds || timeZoneOffsetSeconds === 0; + var idDefined = timeZoneId && timeZoneId !== ''; + + if (offsetDefined && !idDefined) { + (0, util.assertNumberOrInteger)(timeZoneOffsetSeconds, 'Time zone offset in seconds'); + return [timeZoneOffsetSeconds, null]; + } else if (!offsetDefined && idDefined) { + (0, util.assertString)(timeZoneId, 'Time zone ID'); + return [null, timeZoneId]; + } else if (offsetDefined && idDefined) { + throw (0, error.newError)("Unable to create DateTime with both time zone offset and id. Please specify either of them. Given offset: ".concat(timeZoneOffsetSeconds, " and id: ").concat(timeZoneId)); + } else { + throw (0, error.newError)("Unable to create DateTime without either time zone offset or id. Please specify either of them. Given offset: ".concat(timeZoneOffsetSeconds, " and id: ").concat(timeZoneId)); + } +} + +function verifyStandardDateAndNanos(standardDate, nanosecond) { + (0, util.assertValidDate)(standardDate, 'Standard date'); + + if (nanosecond !== null && nanosecond !== undefined) { + (0, util.assertNumberOrInteger)(nanosecond, 'Nanosecond'); + } +} +}); + +var packstreamV2 = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.Unpacker = exports.Packer = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _get2 = interopRequireDefault(get$1); + +var _inherits2 = interopRequireDefault(inherits); + +var v1 = interopRequireWildcard(packstreamV1); + + + + + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var POINT_2D = 0x58; +var POINT_2D_STRUCT_SIZE = 3; +var POINT_3D = 0x59; +var POINT_3D_STRUCT_SIZE = 4; +var DURATION = 0x45; +var DURATION_STRUCT_SIZE = 4; +var LOCAL_TIME = 0x74; +var LOCAL_TIME_STRUCT_SIZE = 1; +var TIME = 0x54; +var TIME_STRUCT_SIZE = 2; +var DATE = 0x44; +var DATE_STRUCT_SIZE = 1; +var LOCAL_DATE_TIME = 0x64; +var LOCAL_DATE_TIME_STRUCT_SIZE = 2; +var DATE_TIME_WITH_ZONE_OFFSET = 0x46; +var DATE_TIME_WITH_ZONE_OFFSET_STRUCT_SIZE = 3; +var DATE_TIME_WITH_ZONE_ID = 0x66; +var DATE_TIME_WITH_ZONE_ID_STRUCT_SIZE = 3; + +var Packer = +/*#__PURE__*/ +function (_v1$Packer) { + (0, _inherits2["default"])(Packer, _v1$Packer); + + function Packer() { + (0, _classCallCheck2["default"])(this, Packer); + return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(Packer).apply(this, arguments)); + } + + (0, _createClass2["default"])(Packer, [{ + key: "disableByteArrays", + value: function disableByteArrays() { + throw new Error('Bolt V2 should always support byte arrays'); + } + }, { + key: "packable", + value: function packable(obj) { + var _this = this; + + if ((0, spatialTypes.isPoint)(obj)) { + return function () { + return packPoint(obj, _this); + }; + } else if ((0, temporalTypes.isDuration)(obj)) { + return function () { + return packDuration(obj, _this); + }; + } else if ((0, temporalTypes.isLocalTime)(obj)) { + return function () { + return packLocalTime(obj, _this); + }; + } else if ((0, temporalTypes.isTime)(obj)) { + return function () { + return packTime(obj, _this); + }; + } else if ((0, temporalTypes.isDate)(obj)) { + return function () { + return packDate(obj, _this); + }; + } else if ((0, temporalTypes.isLocalDateTime)(obj)) { + return function () { + return packLocalDateTime(obj, _this); + }; + } else if ((0, temporalTypes.isDateTime)(obj)) { + return function () { + return packDateTime(obj, _this); + }; + } else { + return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Packer.prototype), "packable", this).call(this, obj); + } + } + }]); + return Packer; +}(v1.Packer); + +exports.Packer = Packer; + +var Unpacker = +/*#__PURE__*/ +function (_v1$Unpacker) { + (0, _inherits2["default"])(Unpacker, _v1$Unpacker); + + /** + * @constructor + * @param {boolean} disableLosslessIntegers if this unpacker should convert all received integers to native JS numbers. + */ + function Unpacker() { + var disableLosslessIntegers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; + (0, _classCallCheck2["default"])(this, Unpacker); + return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(Unpacker).call(this, disableLosslessIntegers)); + } + + (0, _createClass2["default"])(Unpacker, [{ + key: "_unpackUnknownStruct", + value: function _unpackUnknownStruct(signature, structSize, buffer) { + if (signature === POINT_2D) { + return unpackPoint2D(this, structSize, buffer); + } else if (signature === POINT_3D) { + return unpackPoint3D(this, structSize, buffer); + } else if (signature === DURATION) { + return unpackDuration(this, structSize, buffer); + } else if (signature === LOCAL_TIME) { + return unpackLocalTime(this, structSize, buffer, this._disableLosslessIntegers); + } else if (signature === TIME) { + return unpackTime(this, structSize, buffer, this._disableLosslessIntegers); + } else if (signature === DATE) { + return unpackDate(this, structSize, buffer, this._disableLosslessIntegers); + } else if (signature === LOCAL_DATE_TIME) { + return unpackLocalDateTime(this, structSize, buffer, this._disableLosslessIntegers); + } else if (signature === DATE_TIME_WITH_ZONE_OFFSET) { + return unpackDateTimeWithZoneOffset(this, structSize, buffer, this._disableLosslessIntegers); + } else if (signature === DATE_TIME_WITH_ZONE_ID) { + return unpackDateTimeWithZoneId(this, structSize, buffer, this._disableLosslessIntegers); + } else { + return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Unpacker.prototype), "_unpackUnknownStruct", this).call(this, signature, structSize, buffer, this._disableLosslessIntegers); + } + } + }]); + return Unpacker; +}(v1.Unpacker); +/** + * Pack given 2D or 3D point. + * @param {Point} point the point value to pack. + * @param {Packer} packer the packer to use. + */ + + +exports.Unpacker = Unpacker; + +function packPoint(point, packer) { + var is2DPoint = point.z === null || point.z === undefined; + + if (is2DPoint) { + packPoint2D(point, packer); + } else { + packPoint3D(point, packer); + } +} +/** + * Pack given 2D point. + * @param {Point} point the point value to pack. + * @param {Packer} packer the packer to use. + */ + + +function packPoint2D(point, packer) { + var packableStructFields = [packer.packable((0, integer["int"])(point.srid)), packer.packable(point.x), packer.packable(point.y)]; + packer.packStruct(POINT_2D, packableStructFields); +} +/** + * Pack given 3D point. + * @param {Point} point the point value to pack. + * @param {Packer} packer the packer to use. + */ + + +function packPoint3D(point, packer) { + var packableStructFields = [packer.packable((0, integer["int"])(point.srid)), packer.packable(point.x), packer.packable(point.y), packer.packable(point.z)]; + packer.packStruct(POINT_3D, packableStructFields); +} +/** + * Unpack 2D point value using the given unpacker. + * @param {Unpacker} unpacker the unpacker to use. + * @param {number} structSize the retrieved struct size. + * @param {BaseBuffer} buffer the buffer to unpack from. + * @return {Point} the unpacked 2D point value. + */ + + +function unpackPoint2D(unpacker, structSize, buffer) { + unpacker._verifyStructSize('Point2D', POINT_2D_STRUCT_SIZE, structSize); + + return new spatialTypes.Point(unpacker.unpack(buffer), // srid + unpacker.unpack(buffer), // x + unpacker.unpack(buffer), // y + undefined // z + ); +} +/** + * Unpack 3D point value using the given unpacker. + * @param {Unpacker} unpacker the unpacker to use. + * @param {number} structSize the retrieved struct size. + * @param {BaseBuffer} buffer the buffer to unpack from. + * @return {Point} the unpacked 3D point value. + */ + + +function unpackPoint3D(unpacker, structSize, buffer) { + unpacker._verifyStructSize('Point3D', POINT_3D_STRUCT_SIZE, structSize); + + return new spatialTypes.Point(unpacker.unpack(buffer), // srid + unpacker.unpack(buffer), // x + unpacker.unpack(buffer), // y + unpacker.unpack(buffer) // z + ); +} +/** + * Pack given duration. + * @param {Duration} value the duration value to pack. + * @param {Packer} packer the packer to use. + */ + + +function packDuration(value, packer) { + var months = (0, integer["int"])(value.months); + var days = (0, integer["int"])(value.days); + var seconds = (0, integer["int"])(value.seconds); + var nanoseconds = (0, integer["int"])(value.nanoseconds); + var packableStructFields = [packer.packable(months), packer.packable(days), packer.packable(seconds), packer.packable(nanoseconds)]; + packer.packStruct(DURATION, packableStructFields); +} +/** + * Unpack duration value using the given unpacker. + * @param {Unpacker} unpacker the unpacker to use. + * @param {number} structSize the retrieved struct size. + * @param {BaseBuffer} buffer the buffer to unpack from. + * @return {Duration} the unpacked duration value. + */ + + +function unpackDuration(unpacker, structSize, buffer) { + unpacker._verifyStructSize('Duration', DURATION_STRUCT_SIZE, structSize); + + var months = unpacker.unpack(buffer); + var days = unpacker.unpack(buffer); + var seconds = unpacker.unpack(buffer); + var nanoseconds = unpacker.unpack(buffer); + return new temporalTypes.Duration(months, days, seconds, nanoseconds); +} +/** + * Pack given local time. + * @param {LocalTime} value the local time value to pack. + * @param {Packer} packer the packer to use. + */ + + +function packLocalTime(value, packer) { + var nanoOfDay = (0, temporalUtil.localTimeToNanoOfDay)(value.hour, value.minute, value.second, value.nanosecond); + var packableStructFields = [packer.packable(nanoOfDay)]; + packer.packStruct(LOCAL_TIME, packableStructFields); +} +/** + * Unpack local time value using the given unpacker. + * @param {Unpacker} unpacker the unpacker to use. + * @param {number} structSize the retrieved struct size. + * @param {BaseBuffer} buffer the buffer to unpack from. + * @param {boolean} disableLosslessIntegers if integer properties in the result local time should be native JS numbers. + * @return {LocalTime} the unpacked local time value. + */ + + +function unpackLocalTime(unpacker, structSize, buffer, disableLosslessIntegers) { + unpacker._verifyStructSize('LocalTime', LOCAL_TIME_STRUCT_SIZE, structSize); + + var nanoOfDay = unpacker.unpackInteger(buffer); + var result = (0, temporalUtil.nanoOfDayToLocalTime)(nanoOfDay); + return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); +} +/** + * Pack given time. + * @param {Time} value the time value to pack. + * @param {Packer} packer the packer to use. + */ + + +function packTime(value, packer) { + var nanoOfDay = (0, temporalUtil.localTimeToNanoOfDay)(value.hour, value.minute, value.second, value.nanosecond); + var offsetSeconds = (0, integer["int"])(value.timeZoneOffsetSeconds); + var packableStructFields = [packer.packable(nanoOfDay), packer.packable(offsetSeconds)]; + packer.packStruct(TIME, packableStructFields); +} +/** + * Unpack time value using the given unpacker. + * @param {Unpacker} unpacker the unpacker to use. + * @param {number} structSize the retrieved struct size. + * @param {BaseBuffer} buffer the buffer to unpack from. + * @param {boolean} disableLosslessIntegers if integer properties in the result time should be native JS numbers. + * @return {Time} the unpacked time value. + */ + + +function unpackTime(unpacker, structSize, buffer, disableLosslessIntegers) { + unpacker._verifyStructSize('Time', TIME_STRUCT_SIZE, structSize); + + var nanoOfDay = unpacker.unpackInteger(buffer); + var offsetSeconds = unpacker.unpackInteger(buffer); + var localTime = (0, temporalUtil.nanoOfDayToLocalTime)(nanoOfDay); + var result = new temporalTypes.Time(localTime.hour, localTime.minute, localTime.second, localTime.nanosecond, offsetSeconds); + return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); +} +/** + * Pack given neo4j date. + * @param {Date} value the date value to pack. + * @param {Packer} packer the packer to use. + */ + + +function packDate(value, packer) { + var epochDay = (0, temporalUtil.dateToEpochDay)(value.year, value.month, value.day); + var packableStructFields = [packer.packable(epochDay)]; + packer.packStruct(DATE, packableStructFields); +} +/** + * Unpack neo4j date value using the given unpacker. + * @param {Unpacker} unpacker the unpacker to use. + * @param {number} structSize the retrieved struct size. + * @param {BaseBuffer} buffer the buffer to unpack from. + * @param {boolean} disableLosslessIntegers if integer properties in the result date should be native JS numbers. + * @return {Date} the unpacked neo4j date value. + */ + + +function unpackDate(unpacker, structSize, buffer, disableLosslessIntegers) { + unpacker._verifyStructSize('Date', DATE_STRUCT_SIZE, structSize); + + var epochDay = unpacker.unpackInteger(buffer); + var result = (0, temporalUtil.epochDayToDate)(epochDay); + return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); +} +/** + * Pack given local date time. + * @param {LocalDateTime} value the local date time value to pack. + * @param {Packer} packer the packer to use. + */ + + +function packLocalDateTime(value, packer) { + var epochSecond = (0, temporalUtil.localDateTimeToEpochSecond)(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond); + var nano = (0, integer["int"])(value.nanosecond); + var packableStructFields = [packer.packable(epochSecond), packer.packable(nano)]; + packer.packStruct(LOCAL_DATE_TIME, packableStructFields); +} +/** + * Unpack local date time value using the given unpacker. + * @param {Unpacker} unpacker the unpacker to use. + * @param {number} structSize the retrieved struct size. + * @param {BaseBuffer} buffer the buffer to unpack from. + * @param {boolean} disableLosslessIntegers if integer properties in the result local date-time should be native JS numbers. + * @return {LocalDateTime} the unpacked local date time value. + */ + + +function unpackLocalDateTime(unpacker, structSize, buffer, disableLosslessIntegers) { + unpacker._verifyStructSize('LocalDateTime', LOCAL_DATE_TIME_STRUCT_SIZE, structSize); + + var epochSecond = unpacker.unpackInteger(buffer); + var nano = unpacker.unpackInteger(buffer); + var result = (0, temporalUtil.epochSecondAndNanoToLocalDateTime)(epochSecond, nano); + return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); +} +/** + * Pack given date time. + * @param {DateTime} value the date time value to pack. + * @param {Packer} packer the packer to use. + */ + + +function packDateTime(value, packer) { + if (value.timeZoneId) { + packDateTimeWithZoneId(value, packer); + } else { + packDateTimeWithZoneOffset(value, packer); + } +} +/** + * Pack given date time with zone offset. + * @param {DateTime} value the date time value to pack. + * @param {Packer} packer the packer to use. + */ + + +function packDateTimeWithZoneOffset(value, packer) { + var epochSecond = (0, temporalUtil.localDateTimeToEpochSecond)(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond); + var nano = (0, integer["int"])(value.nanosecond); + var timeZoneOffsetSeconds = (0, integer["int"])(value.timeZoneOffsetSeconds); + var packableStructFields = [packer.packable(epochSecond), packer.packable(nano), packer.packable(timeZoneOffsetSeconds)]; + packer.packStruct(DATE_TIME_WITH_ZONE_OFFSET, packableStructFields); +} +/** + * Unpack date time with zone offset value using the given unpacker. + * @param {Unpacker} unpacker the unpacker to use. + * @param {number} structSize the retrieved struct size. + * @param {BaseBuffer} buffer the buffer to unpack from. + * @param {boolean} disableLosslessIntegers if integer properties in the result date-time should be native JS numbers. + * @return {DateTime} the unpacked date time with zone offset value. + */ + + +function unpackDateTimeWithZoneOffset(unpacker, structSize, buffer, disableLosslessIntegers) { + unpacker._verifyStructSize('DateTimeWithZoneOffset', DATE_TIME_WITH_ZONE_OFFSET_STRUCT_SIZE, structSize); + + var epochSecond = unpacker.unpackInteger(buffer); + var nano = unpacker.unpackInteger(buffer); + var timeZoneOffsetSeconds = unpacker.unpackInteger(buffer); + var localDateTime = (0, temporalUtil.epochSecondAndNanoToLocalDateTime)(epochSecond, nano); + var result = new temporalTypes.DateTime(localDateTime.year, localDateTime.month, localDateTime.day, localDateTime.hour, localDateTime.minute, localDateTime.second, localDateTime.nanosecond, timeZoneOffsetSeconds, null); + return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); +} +/** + * Pack given date time with zone id. + * @param {DateTime} value the date time value to pack. + * @param {Packer} packer the packer to use. + */ + + +function packDateTimeWithZoneId(value, packer) { + var epochSecond = (0, temporalUtil.localDateTimeToEpochSecond)(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond); + var nano = (0, integer["int"])(value.nanosecond); + var timeZoneId = value.timeZoneId; + var packableStructFields = [packer.packable(epochSecond), packer.packable(nano), packer.packable(timeZoneId)]; + packer.packStruct(DATE_TIME_WITH_ZONE_ID, packableStructFields); +} +/** + * Unpack date time with zone id value using the given unpacker. + * @param {Unpacker} unpacker the unpacker to use. + * @param {number} structSize the retrieved struct size. + * @param {BaseBuffer} buffer the buffer to unpack from. + * @param {boolean} disableLosslessIntegers if integer properties in the result date-time should be native JS numbers. + * @return {DateTime} the unpacked date time with zone id value. + */ + + +function unpackDateTimeWithZoneId(unpacker, structSize, buffer, disableLosslessIntegers) { + unpacker._verifyStructSize('DateTimeWithZoneId', DATE_TIME_WITH_ZONE_ID_STRUCT_SIZE, structSize); + + var epochSecond = unpacker.unpackInteger(buffer); + var nano = unpacker.unpackInteger(buffer); + var timeZoneId = unpacker.unpack(buffer); + var localDateTime = (0, temporalUtil.epochSecondAndNanoToLocalDateTime)(epochSecond, nano); + var result = new temporalTypes.DateTime(localDateTime.year, localDateTime.month, localDateTime.day, localDateTime.hour, localDateTime.minute, localDateTime.second, localDateTime.nanosecond, null, timeZoneId); + return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); +} + +function convertIntegerPropsIfNeeded(obj, disableLosslessIntegers) { + if (!disableLosslessIntegers) { + return obj; + } + + var clone = Object.create(Object.getPrototypeOf(obj)); + + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + var value = obj[prop]; + clone[prop] = (0, integer.isInt)(value) ? value.toNumberOrInfinity() : value; + } + } + + Object.freeze(clone); + return clone; +} +}); + +var boltProtocolV2 = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _boltProtocolV = interopRequireDefault(boltProtocolV1); + +var v2 = interopRequireWildcard(packstreamV2); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var BoltProtocol = +/*#__PURE__*/ +function (_BoltProtocolV) { + (0, _inherits2["default"])(BoltProtocol, _BoltProtocolV); + + function BoltProtocol() { + (0, _classCallCheck2["default"])(this, BoltProtocol); + return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(BoltProtocol).apply(this, arguments)); + } + + (0, _createClass2["default"])(BoltProtocol, [{ + key: "_createPacker", + value: function _createPacker(chunker) { + return new v2.Packer(chunker); + } + }, { + key: "_createUnpacker", + value: function _createUnpacker(disableLosslessIntegers) { + return new v2.Unpacker(disableLosslessIntegers); + } + }, { + key: "version", + get: function get() { + return constants.BOLT_PROTOCOL_V2; + } + }]); + return BoltProtocol; +}(_boltProtocolV["default"]); + +exports["default"] = BoltProtocol; +}); + +var boltProtocolV3 = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _boltProtocolV = interopRequireDefault(boltProtocolV2); + +var _requestMessage = interopRequireDefault(requestMessage); + + + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var noOpObserver = new streamObservers.StreamObserver(); + +var BoltProtocol = +/*#__PURE__*/ +function (_BoltProtocolV) { + (0, _inherits2["default"])(BoltProtocol, _BoltProtocolV); + + function BoltProtocol() { + (0, _classCallCheck2["default"])(this, BoltProtocol); + return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(BoltProtocol).apply(this, arguments)); + } + + (0, _createClass2["default"])(BoltProtocol, [{ + key: "transformMetadata", + value: function transformMetadata(metadata) { + if ('t_first' in metadata) { + // Bolt V3 uses shorter key 't_first' to represent 'result_available_after' + // adjust the key to be the same as in Bolt V1 so that ResultSummary can retrieve the value + metadata.result_available_after = metadata.t_first; + delete metadata.t_first; + } + + if ('t_last' in metadata) { + // Bolt V3 uses shorter key 't_last' to represent 'result_consumed_after' + // adjust the key to be the same as in Bolt V1 so that ResultSummary can retrieve the value + metadata.result_consumed_after = metadata.t_last; + delete metadata.t_last; + } + + return metadata; + } + }, { + key: "initialize", + value: function initialize() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + userAgent = _ref.userAgent, + authToken = _ref.authToken, + onError = _ref.onError, + onComplete = _ref.onComplete; + + var observer = new streamObservers.LoginObserver({ + connection: this._connection, + afterError: onError, + afterComplete: onComplete + }); + + this._connection.write(_requestMessage["default"].hello(userAgent, authToken), observer, true); + + return observer; + } + }, { + key: "prepareToClose", + value: function prepareToClose() { + this._connection.write(_requestMessage["default"].goodbye(), noOpObserver, true); + } + }, { + key: "beginTransaction", + value: function beginTransaction() { + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + bookmark = _ref2.bookmark, + txConfig = _ref2.txConfig, + database = _ref2.database, + mode = _ref2.mode, + beforeError = _ref2.beforeError, + afterError = _ref2.afterError, + beforeComplete = _ref2.beforeComplete, + afterComplete = _ref2.afterComplete; + + var observer = new streamObservers.ResultStreamObserver({ + connection: this._connection, + beforeError: beforeError, + afterError: afterError, + beforeComplete: beforeComplete, + afterComplete: afterComplete + }); + observer.prepareToHandleSingleResponse(); // passing in a database name on this protocol version throws an error + + (0, boltProtocolUtil.assertDatabaseIsEmpty)(database, this._connection, observer); + + this._connection.write(_requestMessage["default"].begin({ + bookmark: bookmark, + txConfig: txConfig, + mode: mode + }), observer, true); + + return observer; + } + }, { + key: "commitTransaction", + value: function commitTransaction() { + var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + beforeError = _ref3.beforeError, + afterError = _ref3.afterError, + beforeComplete = _ref3.beforeComplete, + afterComplete = _ref3.afterComplete; + + var observer = new streamObservers.ResultStreamObserver({ + connection: this._connection, + beforeError: beforeError, + afterError: afterError, + beforeComplete: beforeComplete, + afterComplete: afterComplete + }); + observer.prepareToHandleSingleResponse(); + + this._connection.write(_requestMessage["default"].commit(), observer, true); + + return observer; + } + }, { + key: "rollbackTransaction", + value: function rollbackTransaction() { + var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + beforeError = _ref4.beforeError, + afterError = _ref4.afterError, + beforeComplete = _ref4.beforeComplete, + afterComplete = _ref4.afterComplete; + + var observer = new streamObservers.ResultStreamObserver({ + connection: this._connection, + beforeError: beforeError, + afterError: afterError, + beforeComplete: beforeComplete, + afterComplete: afterComplete + }); + observer.prepareToHandleSingleResponse(); + + this._connection.write(_requestMessage["default"].rollback(), observer, true); + + return observer; + } + }, { + key: "run", + value: function run(query, parameters) { + var _ref5 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + bookmark = _ref5.bookmark, + txConfig = _ref5.txConfig, + database = _ref5.database, + mode = _ref5.mode, + beforeKeys = _ref5.beforeKeys, + afterKeys = _ref5.afterKeys, + beforeError = _ref5.beforeError, + afterError = _ref5.afterError, + beforeComplete = _ref5.beforeComplete, + afterComplete = _ref5.afterComplete, + _ref5$flush = _ref5.flush, + flush = _ref5$flush === void 0 ? true : _ref5$flush; + + var observer = new streamObservers.ResultStreamObserver({ + connection: this._connection, + beforeKeys: beforeKeys, + afterKeys: afterKeys, + beforeError: beforeError, + afterError: afterError, + beforeComplete: beforeComplete, + afterComplete: afterComplete + }); // passing in a database name on this protocol version throws an error + + (0, boltProtocolUtil.assertDatabaseIsEmpty)(database, this._connection, observer); + + this._connection.write(_requestMessage["default"].runWithMetadata(query, parameters, { + bookmark: bookmark, + txConfig: txConfig, + mode: mode + }), observer, false); + + this._connection.write(_requestMessage["default"].pullAll(), observer, flush); + + return observer; + } + }, { + key: "version", + get: function get() { + return constants.BOLT_PROTOCOL_V3; + } + }]); + return BoltProtocol; +}(_boltProtocolV["default"]); + +exports["default"] = BoltProtocol; +}); + +var boltProtocolV4x0 = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _boltProtocolV = interopRequireDefault(boltProtocolV3); + +var _requestMessage = interopRequireWildcard(requestMessage); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var BoltProtocol = +/*#__PURE__*/ +function (_BoltProtocolV) { + (0, _inherits2["default"])(BoltProtocol, _BoltProtocolV); + + function BoltProtocol() { + (0, _classCallCheck2["default"])(this, BoltProtocol); + return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(BoltProtocol).apply(this, arguments)); + } + + (0, _createClass2["default"])(BoltProtocol, [{ + key: "beginTransaction", + value: function beginTransaction() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + bookmark = _ref.bookmark, + txConfig = _ref.txConfig, + database = _ref.database, + mode = _ref.mode, + beforeError = _ref.beforeError, + afterError = _ref.afterError, + beforeComplete = _ref.beforeComplete, + afterComplete = _ref.afterComplete; + + var observer = new streamObservers.ResultStreamObserver({ + connection: this._connection, + beforeError: beforeError, + afterError: afterError, + beforeComplete: beforeComplete, + afterComplete: afterComplete + }); + observer.prepareToHandleSingleResponse(); + + this._connection.write(_requestMessage["default"].begin({ + bookmark: bookmark, + txConfig: txConfig, + database: database, + mode: mode + }), observer, true); + + return observer; + } + }, { + key: "run", + value: function run(query, parameters) { + var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, + bookmark = _ref2.bookmark, + txConfig = _ref2.txConfig, + database = _ref2.database, + mode = _ref2.mode, + beforeKeys = _ref2.beforeKeys, + afterKeys = _ref2.afterKeys, + beforeError = _ref2.beforeError, + afterError = _ref2.afterError, + beforeComplete = _ref2.beforeComplete, + afterComplete = _ref2.afterComplete, + _ref2$flush = _ref2.flush, + flush = _ref2$flush === void 0 ? true : _ref2$flush, + _ref2$reactive = _ref2.reactive, + reactive = _ref2$reactive === void 0 ? false : _ref2$reactive, + _ref2$fetchSize = _ref2.fetchSize, + fetchSize = _ref2$fetchSize === void 0 ? _requestMessage.ALL : _ref2$fetchSize; + + var observer = new streamObservers.ResultStreamObserver({ + connection: this._connection, + reactive: reactive, + fetchSize: fetchSize, + moreFunction: this._requestMore, + discardFunction: this._requestDiscard, + beforeKeys: beforeKeys, + afterKeys: afterKeys, + beforeError: beforeError, + afterError: afterError, + beforeComplete: beforeComplete, + afterComplete: afterComplete + }); + var flushRun = reactive; + + this._connection.write(_requestMessage["default"].runWithMetadata(query, parameters, { + bookmark: bookmark, + txConfig: txConfig, + database: database, + mode: mode + }), observer, flushRun && flush); + + if (!reactive) { + this._connection.write(_requestMessage["default"].pull({ + n: fetchSize + }), observer, flush); + } + + return observer; + } + }, { + key: "_requestMore", + value: function _requestMore(connection, stmtId, n, observer) { + connection.write(_requestMessage["default"].pull({ + stmtId: stmtId, + n: n + }), observer, true); + } + }, { + key: "_requestDiscard", + value: function _requestDiscard(connection, stmtId, observer) { + connection.write(_requestMessage["default"].discard({ + stmtId: stmtId + }), observer, true); + } + }, { + key: "_noOp", + value: function _noOp() {} + }, { + key: "version", + get: function get() { + return constants.BOLT_PROTOCOL_V4_0; + } + }]); + return BoltProtocol; +}(_boltProtocolV["default"]); + +exports["default"] = BoltProtocol; +}); + +var boltProtocolV4x1 = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _boltProtocolV4x = interopRequireDefault(boltProtocolV4x0); + +var _requestMessage = interopRequireWildcard(requestMessage); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var BoltProtocol = +/*#__PURE__*/ +function (_BoltProtocolV) { + (0, _inherits2["default"])(BoltProtocol, _BoltProtocolV); + + /** + * @constructor + * @param {Connection} connection the connection. + * @param {Chunker} chunker the chunker. + * @param {boolean} disableLosslessIntegers if this connection should convert all received integers to native JS numbers. + * @param {Object} serversideRouting + */ + function BoltProtocol(connection, chunker, disableLosslessIntegers, serversideRouting) { + var _this; + + (0, _classCallCheck2["default"])(this, BoltProtocol); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(BoltProtocol).call(this, connection, chunker, disableLosslessIntegers)); + _this._serversideRouting = serversideRouting; + return _this; + } + + (0, _createClass2["default"])(BoltProtocol, [{ + key: "initialize", + value: function initialize() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + userAgent = _ref.userAgent, + authToken = _ref.authToken, + onError = _ref.onError, + onComplete = _ref.onComplete; + + var observer = new streamObservers.LoginObserver({ + connection: this._connection, + afterError: onError, + afterComplete: onComplete + }); + + this._connection.write(_requestMessage["default"].hello(userAgent, authToken, this._serversideRouting), observer, true); + + return observer; + } + }, { + key: "version", + get: function get() { + return constants.BOLT_PROTOCOL_V4_1; + } + }]); + return BoltProtocol; +}(_boltProtocolV4x["default"]); + +exports["default"] = BoltProtocol; +}); + +var boltProtocolV4x2 = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _boltProtocolV4x = interopRequireDefault(boltProtocolV4x1); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var BoltProtocol = +/*#__PURE__*/ +function (_BoltProtocolV) { + (0, _inherits2["default"])(BoltProtocol, _BoltProtocolV); + + /** + * @constructor + * @param {Connection} connection the connection. + * @param {Chunker} chunker the chunker. + * @param {boolean} disableLosslessIntegers if this connection should convert all received integers to native JS numbers. + * @param {Object} serversideRouting + */ + function BoltProtocol(connection, chunker, disableLosslessIntegers, serversideRouting) { + (0, _classCallCheck2["default"])(this, BoltProtocol); + return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(BoltProtocol).call(this, connection, chunker, disableLosslessIntegers, serversideRouting)); + } + + (0, _createClass2["default"])(BoltProtocol, [{ + key: "version", + get: function get() { + return constants.BOLT_PROTOCOL_V4_2; + } + }]); + return BoltProtocol; +}(_boltProtocolV4x["default"]); + +exports["default"] = BoltProtocol; +}); + +var protocolHandshaker = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + + + +var _boltProtocolV = interopRequireDefault(boltProtocolV1); + +var _boltProtocolV2 = interopRequireDefault(boltProtocolV2); + +var _boltProtocolV3 = interopRequireDefault(boltProtocolV3); + +var _boltProtocolV4x = interopRequireDefault(boltProtocolV4x0); + +var _boltProtocolV4x2 = interopRequireDefault(boltProtocolV4x1); + +var _boltProtocolV4x3 = interopRequireDefault(boltProtocolV4x2); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var BOLT_MAGIC_PREAMBLE = 0x6060b017; + +var ProtocolHandshaker = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {Connection} connection the connection owning this protocol. + * @param {Channel} channel the network channel. + * @param {Chunker} chunker the message chunker. + * @param {boolean} disableLosslessIntegers flag to use native JS numbers. + * @param {Logger} log the logger. + */ + function ProtocolHandshaker(connection, channel, chunker, disableLosslessIntegers, log) { + var serversideRouting = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + (0, _classCallCheck2["default"])(this, ProtocolHandshaker); + this._connection = connection; + this._channel = channel; + this._chunker = chunker; + this._disableLosslessIntegers = disableLosslessIntegers; + this._log = log; + this._serversideRouting = serversideRouting; + } + /** + * Write a Bolt handshake into the underlying network channel. + */ + + + (0, _createClass2["default"])(ProtocolHandshaker, [{ + key: "writeHandshakeRequest", + value: function writeHandshakeRequest() { + this._channel.write(newHandshakeBuffer()); + } + /** + * Read the given handshake response and create the negotiated bolt protocol. + * @param {BaseBuffer} buffer byte buffer containing the handshake response. + * @return {BoltProtocol} bolt protocol corresponding to the version suggested by the database. + * @throws {Neo4jError} when bolt protocol can't be instantiated. + */ + + }, { + key: "createNegotiatedProtocol", + value: function createNegotiatedProtocol(buffer) { + var h = [buffer.readUInt8(), buffer.readUInt8(), buffer.readUInt8(), buffer.readUInt8()]; + + if (h[0] === 0x48 && h[1] === 0x54 && h[2] === 0x54 && h[3] === 0x50) { + throw (0, error.newError)('Server responded HTTP. Make sure you are not trying to connect to the http endpoint ' + '(HTTP defaults to port 7474 whereas BOLT defaults to port 7687)'); + } + + var negotiatedVersion = Number(h[3] + '.' + h[2]); + + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(this._connection, " negotiated protocol version ").concat(negotiatedVersion)); + } + + return this._createProtocolWithVersion(negotiatedVersion); + } + /** + * @return {BoltProtocol} + * @private + */ + + }, { + key: "_createProtocolWithVersion", + value: function _createProtocolWithVersion(version) { + switch (version) { + case 1: + return new _boltProtocolV["default"](this._connection, this._chunker, this._disableLosslessIntegers); + + case 2: + return new _boltProtocolV2["default"](this._connection, this._chunker, this._disableLosslessIntegers); + + case 3: + return new _boltProtocolV3["default"](this._connection, this._chunker, this._disableLosslessIntegers); + + case 4.0: + return new _boltProtocolV4x["default"](this._connection, this._chunker, this._disableLosslessIntegers); + + case 4.1: + return new _boltProtocolV4x2["default"](this._connection, this._chunker, this._disableLosslessIntegers, this._serversideRouting); + + case 4.2: + return new _boltProtocolV4x3["default"](this._connection, this._chunker, this._disableLosslessIntegers, this._serversideRouting); + + default: + throw (0, error.newError)('Unknown Bolt protocol version: ' + version); + } + } + }]); + return ProtocolHandshaker; +}(); +/** + * @return {BaseBuffer} + * @private + */ + + +exports["default"] = ProtocolHandshaker; + +function newHandshakeBuffer() { + var handshakeBuffer = (0, node.alloc)(5 * 4); // magic preamble + + handshakeBuffer.writeInt32(BOLT_MAGIC_PREAMBLE); // proposed versions + + handshakeBuffer.writeInt32(2 << 8 | 4); + handshakeBuffer.writeInt32(1 << 8 | 4); + handshakeBuffer.writeInt32(4); + handshakeBuffer.writeInt32(3); // reset the reader position + + handshakeBuffer.reset(); + return handshakeBuffer; +} +}); + +var connectionChannel = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _regenerator = interopRequireDefault(regenerator); + +var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _assertThisInitialized2 = interopRequireDefault(assertThisInitialized); + +var _inherits2 = interopRequireDefault(inherits); + + + + + + + +var _channelConfig = interopRequireDefault(channelConfig); + +var _protocolHandshaker = interopRequireDefault(protocolHandshaker); + +var _connection = interopRequireDefault(connection); + +interopRequireDefault(boltProtocolV1); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// Signature bytes for each response message type +var SUCCESS = 0x70; // 0111 0000 // SUCCESS + +var RECORD = 0x71; // 0111 0001 // RECORD + +var IGNORED = 0x7e; // 0111 1110 // IGNORED + +var FAILURE = 0x7f; // 0111 1111 // FAILURE + +function NO_OP() {} + +var NO_OP_OBSERVER = { + onNext: NO_OP, + onCompleted: NO_OP, + onError: NO_OP +}; +var idGenerator = 0; + +var ChannelConnection = +/*#__PURE__*/ +function (_Connection) { + (0, _inherits2["default"])(ChannelConnection, _Connection); + + /** + * @constructor + * @param {Channel} channel - channel with a 'write' function and a 'onmessage' callback property. + * @param {ConnectionErrorHandler} errorHandler the error handler. + * @param {ServerAddress} address - the server address to connect to. + * @param {Logger} log - the configured logger. + * @param {boolean} disableLosslessIntegers if this connection should convert all received integers to native JS numbers. + */ + function ChannelConnection(channel, errorHandler, address, log) { + var _this; + + var disableLosslessIntegers = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; + var serversideRouting = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; + (0, _classCallCheck2["default"])(this, ChannelConnection); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ChannelConnection).call(this, errorHandler)); + _this._id = idGenerator++; + _this._address = address; + _this._server = { + address: address.asHostPort() + }; + _this.creationTimestamp = Date.now(); + _this._disableLosslessIntegers = disableLosslessIntegers; + _this._pendingObservers = []; + _this._currentObserver = undefined; + _this._ch = channel; + _this._dechunker = new chunking.Dechunker(); + _this._chunker = new chunking.Chunker(channel); + _this._log = log; + _this._serversideRouting = serversideRouting; // connection from the database, returned in response for HELLO message and might not be available + + _this._dbConnectionId = null; // bolt protocol is initially not initialized + + /** + * @private + * @type {BoltProtocol} + */ + + _this._protocol = null; // error extracted from a FAILURE message + + _this._currentFailure = null; // Set to true on fatal errors, to get this out of connection pool. + + _this._isBroken = false; + + if (_this._log.isDebugEnabled()) { + _this._log.debug("".concat((0, _assertThisInitialized2["default"])(_this), " created towards ").concat(address)); + } + + return _this; + } + /** + * Crete new connection to the provided address. Returned connection is not connected. + * @param {ServerAddress} address - the Bolt endpoint to connect to. + * @param {Object} config - the driver configuration. + * @param {ConnectionErrorHandler} errorHandler - the error handler for connection errors. + * @param {Logger} log - configured logger. + * @return {Connection} - new connection. + */ + + + (0, _createClass2["default"])(ChannelConnection, [{ + key: "connect", + + /** + * Connect to the target address, negotiate Bolt protocol and send initialization message. + * @param {string} userAgent the user agent for this driver. + * @param {Object} authToken the object containing auth information. + * @return {Promise} promise resolved with the current connection if connection is successful. Rejected promise otherwise. + */ + value: function connect(userAgent, authToken) { + var _this2 = this; + + return this._negotiateProtocol().then(function () { + return _this2._initialize(userAgent, authToken); + }); + } + /** + * Execute Bolt protocol handshake to initialize the protocol version. + * @return {Promise} promise resolved with the current connection if handshake is successful. Rejected promise otherwise. + */ + + }, { + key: "_negotiateProtocol", + value: function _negotiateProtocol() { + var _this3 = this; + + var protocolHandshaker = new _protocolHandshaker["default"](this, this._ch, this._chunker, this._disableLosslessIntegers, this._log, this._serversideRouting); + return new Promise(function (resolve, reject) { + var handshakeErrorHandler = function handshakeErrorHandler(error) { + _this3._handleFatalError(error); + + reject(error); + }; + + _this3._ch.onerror = handshakeErrorHandler.bind(_this3); + + if (_this3._ch._error) { + // channel is already broken + handshakeErrorHandler(_this3._ch._error); + } + + _this3._ch.onmessage = function (buffer) { + try { + // read the response buffer and initialize the protocol + _this3._protocol = protocolHandshaker.createNegotiatedProtocol(buffer); // reset the error handler to just handle errors and forget about the handshake promise + + _this3._ch.onerror = _this3._handleFatalError.bind(_this3); // Ok, protocol running. Simply forward all messages to the dechunker + + _this3._ch.onmessage = function (buf) { + return _this3._dechunker.write(buf); + }; // setup dechunker to dechunk messages and forward them to the message handler + + + _this3._dechunker.onmessage = function (buf) { + _this3._handleMessage(_this3._protocol.unpacker().unpack(buf)); + }; // forward all pending bytes to the dechunker + + + if (buffer.hasRemaining()) { + _this3._dechunker.write(buffer.readSlice(buffer.remaining())); + } + + resolve(_this3); + } catch (e) { + _this3._handleFatalError(e); + + reject(e); + } + }; + + protocolHandshaker.writeHandshakeRequest(); + }); + } + /** + * Perform protocol-specific initialization which includes authentication. + * @param {string} userAgent the user agent for this driver. + * @param {Object} authToken the object containing auth information. + * @return {Promise} promise resolved with the current connection if initialization is successful. Rejected promise otherwise. + */ + + }, { + key: "_initialize", + value: function _initialize(userAgent, authToken) { + var _this4 = this; + + var self = this; + return new Promise(function (resolve, reject) { + _this4._protocol.initialize({ + userAgent: userAgent, + authToken: authToken, + onError: function onError(err) { + return reject(err); + }, + onComplete: function onComplete() { + return resolve(self); + } + }); + }); + } + /** + * Get the Bolt protocol for the connection. + * @return {BoltProtocol} the protocol. + */ + + }, { + key: "protocol", + value: function protocol() { + return this._protocol; + } + }, { + key: "write", + + /** + * Write a message to the network channel. + * @param {RequestMessage} message the message to write. + * @param {ResultStreamObserver} observer the response observer. + * @param {boolean} flush `true` if flush should happen after the message is written to the buffer. + */ + value: function write(message, observer, flush) { + var _this5 = this; + + var queued = this._queueObserver(observer); + + if (queued) { + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(this, " C: ").concat(message)); + } + + this._protocol.packer().packStruct(message.signature, message.fields.map(function (field) { + return _this5._packable(field); + })); + + this._chunker.messageBoundary(); + + if (flush) { + this._chunker.flush(); + } + } + } + /** + * "Fatal" means the connection is dead. Only call this if something + * happens that cannot be recovered from. This will lead to all subscribers + * failing, and the connection getting ejected from the session pool. + * + * @param error an error object, forwarded to all current and future subscribers + */ + + }, { + key: "_handleFatalError", + value: function _handleFatalError(error) { + this._isBroken = true; + this._error = this.handleAndTransformError(error, this._address); + + if (this._log.isErrorEnabled()) { + this._log.error("".concat(this, " experienced a fatal error ").concat(JSON.stringify(this._error))); + } + + if (this._currentObserver && this._currentObserver.onError) { + this._currentObserver.onError(this._error); + } + + while (this._pendingObservers.length > 0) { + var observer = this._pendingObservers.shift(); + + if (observer && observer.onError) { + observer.onError(this._error); + } + } + } + }, { + key: "_handleMessage", + value: function _handleMessage(msg) { + if (this._isBroken) { + // ignore all incoming messages when this connection is broken. all previously pending observers failed + // with the fatal error. all future observers will fail with same fatal error. + return; + } + + var payload = msg.fields[0]; + + switch (msg.signature) { + case RECORD: + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(this, " S: RECORD ").concat(JSON.stringify(msg))); + } + + this._currentObserver.onNext(payload); + + break; + + case SUCCESS: + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(this, " S: SUCCESS ").concat(JSON.stringify(msg))); + } + + try { + var metadata = this._protocol.transformMetadata(payload); + + this._currentObserver.onCompleted(metadata); + } finally { + this._updateCurrentObserver(); + } + + break; + + case FAILURE: + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(this, " S: FAILURE ").concat(JSON.stringify(msg))); + } + + try { + var error$1 = (0, error.newError)(payload.message, payload.code); + this._currentFailure = this.handleAndTransformError(error$1, this._address); + + this._currentObserver.onError(this._currentFailure); + } finally { + this._updateCurrentObserver(); // Things are now broken. Pending observers will get FAILURE messages routed until we are done handling this failure. + + + this._resetOnFailure(); + } + + break; + + case IGNORED: + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(this, " S: IGNORED ").concat(JSON.stringify(msg))); + } + + try { + if (this._currentFailure && this._currentObserver.onError) { + this._currentObserver.onError(this._currentFailure); + } else if (this._currentObserver.onError) { + this._currentObserver.onError((0, error.newError)('Ignored either because of an error or RESET')); + } + } finally { + this._updateCurrentObserver(); + } + + break; + + default: + this._handleFatalError((0, error.newError)('Unknown Bolt protocol message: ' + msg)); + + } + } + /** + * Send a RESET-message to the database. Message is immediately flushed to the network. + * @return {Promise} promise resolved when SUCCESS-message response arrives, or failed when other response messages arrives. + */ + + }, { + key: "resetAndFlush", + value: function resetAndFlush() { + var _this6 = this; + + return new Promise(function (resolve, reject) { + _this6._protocol.reset({ + onError: function onError(error) { + if (_this6._isBroken) { + // handling a fatal error, no need to raise a protocol violation + reject(error); + } else { + var neo4jError = _this6._handleProtocolError('Received FAILURE as a response for RESET: ' + error); + + reject(neo4jError); + } + }, + onComplete: function onComplete() { + resolve(); + } + }); + }); + } + }, { + key: "_resetOnFailure", + value: function _resetOnFailure() { + var _this7 = this; + + this._protocol.reset({ + onError: function onError() { + _this7._currentFailure = null; + }, + onComplete: function onComplete() { + _this7._currentFailure = null; + } + }); + } + }, { + key: "_queueObserver", + value: function _queueObserver(observer) { + if (this._isBroken) { + if (observer && observer.onError) { + observer.onError(this._error); + } + + return false; + } + + observer = observer || NO_OP_OBSERVER; + observer.onCompleted = observer.onCompleted || NO_OP; + observer.onError = observer.onError || NO_OP; + observer.onNext = observer.onNext || NO_OP; + + if (this._currentObserver === undefined) { + this._currentObserver = observer; + } else { + this._pendingObservers.push(observer); + } + + return true; + } + /* + * Pop next pending observer form the list of observers and make it current observer. + * @protected + */ + + }, { + key: "_updateCurrentObserver", + value: function _updateCurrentObserver() { + this._currentObserver = this._pendingObservers.shift(); + } + /** Check if this connection is in working condition */ + + }, { + key: "isOpen", + value: function isOpen() { + return !this._isBroken && this._ch._open; + } + /** + * Call close on the channel. + * @returns {Promise} - A promise that will be resolved when the underlying channel is closed. + */ + + }, { + key: "close", + value: function () { + var _close = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee() { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(this, " closing")); + } + + if (this._protocol && this.isOpen()) { + // protocol has been initialized and this connection is healthy + // notify the database about the upcoming close of the connection + this._protocol.prepareToClose(); + } + + _context.next = 4; + return this._ch.close(); + + case 4: + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(this, " closed")); + } + + case 5: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function close() { + return _close.apply(this, arguments); + } + + return close; + }() + }, { + key: "toString", + value: function toString() { + return "Connection [".concat(this.id, "][").concat(this.databaseId || '', "]"); + } + }, { + key: "_packable", + value: function _packable(value) { + return this._protocol.packer().packable(value); + } + }, { + key: "_handleProtocolError", + value: function _handleProtocolError(message) { + this._currentFailure = null; + + this._updateCurrentObserver(); + + var error$1 = (0, error.newError)(message, error.PROTOCOL_ERROR); + + this._handleFatalError(error$1); + + return error$1; + } + }, { + key: "id", + get: function get() { + return this._id; + } + }, { + key: "databaseId", + get: function get() { + return this._dbConnectionId; + }, + set: function set(value) { + this._dbConnectionId = value; + } + }, { + key: "address", + get: function get() { + return this._address; + } + /** + * Get the version of the connected server. + * Available only after initialization + * + * @returns {ServerVersion} version + */ + + }, { + key: "version", + get: function get() { + return this._server.version; + }, + set: function set(value) { + this._server.version = value; + } + }, { + key: "server", + get: function get() { + return this._server; + } + }], [{ + key: "create", + value: function create(address, config, errorHandler, log) { + var serversideRouting = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; + var channelConfig = new _channelConfig["default"](address, config, errorHandler.errorCode()); + return new ChannelConnection(new node.Channel(channelConfig), errorHandler, address, log, config.disableLosslessIntegers, serversideRouting); + } + }]); + return ChannelConnection; +}(_connection["default"]); + +exports["default"] = ChannelConnection; +}); + +var poolConfig = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.DEFAULT_ACQUISITION_TIMEOUT = exports.DEFAULT_MAX_SIZE = exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var DEFAULT_MAX_SIZE = 100; +exports.DEFAULT_MAX_SIZE = DEFAULT_MAX_SIZE; +var DEFAULT_ACQUISITION_TIMEOUT = 60 * 1000; // 60 seconds + +exports.DEFAULT_ACQUISITION_TIMEOUT = DEFAULT_ACQUISITION_TIMEOUT; + +var PoolConfig = +/*#__PURE__*/ +function () { + function PoolConfig(maxSize, acquisitionTimeout) { + (0, _classCallCheck2["default"])(this, PoolConfig); + this.maxSize = valueOrDefault(maxSize, DEFAULT_MAX_SIZE); + this.acquisitionTimeout = valueOrDefault(acquisitionTimeout, DEFAULT_ACQUISITION_TIMEOUT); + } + + (0, _createClass2["default"])(PoolConfig, null, [{ + key: "defaultConfig", + value: function defaultConfig() { + return new PoolConfig(DEFAULT_MAX_SIZE, DEFAULT_ACQUISITION_TIMEOUT); + } + }, { + key: "fromDriverConfig", + value: function fromDriverConfig(config) { + var maxSizeConfigured = isConfigured(config.maxConnectionPoolSize); + var maxSize = maxSizeConfigured ? config.maxConnectionPoolSize : DEFAULT_MAX_SIZE; + var acquisitionTimeoutConfigured = isConfigured(config.connectionAcquisitionTimeout); + var acquisitionTimeout = acquisitionTimeoutConfigured ? config.connectionAcquisitionTimeout : DEFAULT_ACQUISITION_TIMEOUT; + return new PoolConfig(maxSize, acquisitionTimeout); + } + }]); + return PoolConfig; +}(); + +exports["default"] = PoolConfig; + +function valueOrDefault(value, defaultValue) { + return value === 0 || value ? value : defaultValue; +} + +function isConfigured(value) { + return value === 0 || value; +} +}); + +var logger = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _defineProperty2 = interopRequireDefault(defineProperty$1); + + + +var _levels; + +var ERROR = 'error'; +var WARN = 'warn'; +var INFO = 'info'; +var DEBUG = 'debug'; +var DEFAULT_LEVEL = INFO; +var levels = (_levels = {}, (0, _defineProperty2["default"])(_levels, ERROR, 0), (0, _defineProperty2["default"])(_levels, WARN, 1), (0, _defineProperty2["default"])(_levels, INFO, 2), (0, _defineProperty2["default"])(_levels, DEBUG, 3), _levels); +/** + * Logger used by the driver to notify about various internal events. Single logger should be used per driver. + */ + +var Logger = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {string} level the enabled logging level. + * @param {function(level: string, message: string)} loggerFunction the function to write the log level and message. + */ + function Logger(level, loggerFunction) { + (0, _classCallCheck2["default"])(this, Logger); + this._level = level; + this._loggerFunction = loggerFunction; + } + /** + * Create a new logger based on the given driver configuration. + * @param {Object} driverConfig the driver configuration as supplied by the user. + * @return {Logger} a new logger instance or a no-op logger when not configured. + */ + + + (0, _createClass2["default"])(Logger, [{ + key: "isErrorEnabled", + + /** + * Check if error logging is enabled, i.e. it is not a no-op implementation. + * @return {boolean} `true` when enabled, `false` otherwise. + */ + value: function isErrorEnabled() { + return isLevelEnabled(this._level, ERROR); + } + /** + * Log an error message. + * @param {string} message the message to log. + */ + + }, { + key: "error", + value: function error(message) { + if (this.isErrorEnabled()) { + this._loggerFunction(ERROR, message); + } + } + /** + * Check if warn logging is enabled, i.e. it is not a no-op implementation. + * @return {boolean} `true` when enabled, `false` otherwise. + */ + + }, { + key: "isWarnEnabled", + value: function isWarnEnabled() { + return isLevelEnabled(this._level, WARN); + } + /** + * Log an warning message. + * @param {string} message the message to log. + */ + + }, { + key: "warn", + value: function warn(message) { + if (this.isWarnEnabled()) { + this._loggerFunction(WARN, message); + } + } + /** + * Check if info logging is enabled, i.e. it is not a no-op implementation. + * @return {boolean} `true` when enabled, `false` otherwise. + */ + + }, { + key: "isInfoEnabled", + value: function isInfoEnabled() { + return isLevelEnabled(this._level, INFO); + } + /** + * Log an info message. + * @param {string} message the message to log. + */ + + }, { + key: "info", + value: function info(message) { + if (this.isInfoEnabled()) { + this._loggerFunction(INFO, message); + } + } + /** + * Check if debug logging is enabled, i.e. it is not a no-op implementation. + * @return {boolean} `true` when enabled, `false` otherwise. + */ + + }, { + key: "isDebugEnabled", + value: function isDebugEnabled() { + return isLevelEnabled(this._level, DEBUG); + } + /** + * Log a debug message. + * @param {string} message the message to log. + */ + + }, { + key: "debug", + value: function debug(message) { + if (this.isDebugEnabled()) { + this._loggerFunction(DEBUG, message); + } + } + }], [{ + key: "create", + value: function create(driverConfig) { + if (driverConfig && driverConfig.logging) { + var loggingConfig = driverConfig.logging; + var level = extractConfiguredLevel(loggingConfig); + var loggerFunction = extractConfiguredLogger(loggingConfig); + return new Logger(level, loggerFunction); + } + + return this.noOp(); + } + /** + * Create a no-op logger implementation. + * @return {Logger} the no-op logger implementation. + */ + + }, { + key: "noOp", + value: function noOp() { + return noOpLogger; + } + }]); + return Logger; +}(); + +var NoOpLogger = +/*#__PURE__*/ +function (_Logger) { + (0, _inherits2["default"])(NoOpLogger, _Logger); + + function NoOpLogger() { + (0, _classCallCheck2["default"])(this, NoOpLogger); + return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(NoOpLogger).call(this, null, null)); + } + + (0, _createClass2["default"])(NoOpLogger, [{ + key: "isErrorEnabled", + value: function isErrorEnabled() { + return false; + } + }, { + key: "error", + value: function error(message) {} + }, { + key: "isWarnEnabled", + value: function isWarnEnabled() { + return false; + } + }, { + key: "warn", + value: function warn(message) {} + }, { + key: "isInfoEnabled", + value: function isInfoEnabled() { + return false; + } + }, { + key: "info", + value: function info(message) {} + }, { + key: "isDebugEnabled", + value: function isDebugEnabled() { + return false; + } + }, { + key: "debug", + value: function debug(message) {} + }]); + return NoOpLogger; +}(Logger); + +var noOpLogger = new NoOpLogger(); +/** + * Check if the given logging level is enabled. + * @param {string} configuredLevel the configured level. + * @param {string} targetLevel the level to check. + * @return {boolean} value of `true` when enabled, `false` otherwise. + */ + +function isLevelEnabled(configuredLevel, targetLevel) { + return levels[configuredLevel] >= levels[targetLevel]; +} +/** + * Extract the configured logging level from the driver's logging configuration. + * @param {Object} loggingConfig the logging configuration. + * @return {string} the configured log level or default when none configured. + */ + + +function extractConfiguredLevel(loggingConfig) { + if (loggingConfig && loggingConfig.level) { + var configuredLevel = loggingConfig.level; + var value = levels[configuredLevel]; + + if (!value && value !== 0) { + throw (0, error.newError)("Illegal logging level: ".concat(configuredLevel, ". Supported levels are: ").concat(Object.keys(levels))); + } + + return configuredLevel; + } + + return DEFAULT_LEVEL; +} +/** + * Extract the configured logger function from the driver's logging configuration. + * @param {Object} loggingConfig the logging configuration. + * @return {function(level: string, message: string)} the configured logging function. + */ + + +function extractConfiguredLogger(loggingConfig) { + if (loggingConfig && loggingConfig.logger) { + var configuredLogger = loggingConfig.logger; + + if (configuredLogger && typeof configuredLogger === 'function') { + return configuredLogger; + } + } + + throw (0, error.newError)("Illegal logger function: ".concat(loggingConfig.logger)); +} + +var _default = Logger; +exports["default"] = _default; +}); + +var pool = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _regenerator = interopRequireDefault(regenerator); + +var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _poolConfig = interopRequireDefault(poolConfig); + + + +var _logger = interopRequireDefault(logger); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var Pool = +/*#__PURE__*/ +function () { + /** + * @param {function(address: ServerAddress, function(address: ServerAddress, resource: object): Promise): Promise} create + * an allocation function that creates a promise with a new resource. It's given an address for which to + * allocate the connection and a function that will return the resource to the pool if invoked, which is + * meant to be called on .dispose or .close or whatever mechanism the resource uses to finalize. + * @param {function(resource: object): Promise} destroy + * called with the resource when it is evicted from this pool + * @param {function(resource: object): boolean} validate + * called at various times (like when an instance is acquired and when it is returned. + * If this returns false, the resource will be evicted + * @param {function(resource: object, observer: { onError }): void} installIdleObserver + * called when the resource is released back to pool + * @param {function(resource: object): void} removeIdleObserver + * called when the resource is acquired from the pool + * @param {PoolConfig} config configuration for the new driver. + * @param {Logger} log the driver logger. + */ + function Pool() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$create = _ref.create, + create = _ref$create === void 0 ? function (address, release) { + return Promise.resolve(); + } : _ref$create, + _ref$destroy = _ref.destroy, + destroy = _ref$destroy === void 0 ? function (conn) { + return Promise.resolve(); + } : _ref$destroy, + _ref$validate = _ref.validate, + validate = _ref$validate === void 0 ? function (conn) { + return true; + } : _ref$validate, + _ref$installIdleObser = _ref.installIdleObserver, + installIdleObserver = _ref$installIdleObser === void 0 ? function (conn, observer) {} : _ref$installIdleObser, + _ref$removeIdleObserv = _ref.removeIdleObserver, + removeIdleObserver = _ref$removeIdleObserv === void 0 ? function (conn) {} : _ref$removeIdleObserv, + _ref$config = _ref.config, + config = _ref$config === void 0 ? _poolConfig["default"].defaultConfig() : _ref$config, + _ref$log = _ref.log, + log = _ref$log === void 0 ? _logger["default"].noOp() : _ref$log; + + (0, _classCallCheck2["default"])(this, Pool); + this._create = create; + this._destroy = destroy; + this._validate = validate; + this._installIdleObserver = installIdleObserver; + this._removeIdleObserver = removeIdleObserver; + this._maxSize = config.maxSize; + this._acquisitionTimeout = config.acquisitionTimeout; + this._pools = {}; + this._pendingCreates = {}; + this._acquireRequests = {}; + this._activeResourceCounts = {}; + this._release = this._release.bind(this); + this._log = log; + this._closed = false; + } + /** + * Acquire and idle resource fom the pool or create a new one. + * @param {ServerAddress} address the address for which we're acquiring. + * @return {Object} resource that is ready to use. + */ + + + (0, _createClass2["default"])(Pool, [{ + key: "acquire", + value: function acquire(address) { + var _this = this; + + return this._acquire(address).then(function (resource) { + var key = address.asKey(); + + if (resource) { + // New or existing resource acquired + return resource; + } // We're out of resources and will try to acquire later on when an existing resource is released. + + + var allRequests = _this._acquireRequests; + var requests = allRequests[key]; + + if (!requests) { + allRequests[key] = []; + } + + return new Promise(function (resolve, reject) { + var request; + var timeoutId = setTimeout(function () { + // acquisition timeout fired + // remove request from the queue of pending requests, if it's still there + // request might've been taken out by the release operation + var pendingRequests = allRequests[key]; + + if (pendingRequests) { + allRequests[key] = pendingRequests.filter(function (item) { + return item !== request; + }); + } + + if (request.isCompleted()) ; else { + // request is still pending and needs to be failed + var activeCount = _this.activeResourceCount(address); + + var idleCount = _this.has(address) ? _this._pools[key].length : 0; + request.reject((0, error.newError)("Connection acquisition timed out in ".concat(_this._acquisitionTimeout, " ms. Poos status: Active conn count = ").concat(activeCount, ", Idle conn count = ").concat(idleCount, "."))); + } + }, _this._acquisitionTimeout); + request = new PendingRequest(key, resolve, reject, timeoutId, _this._log); + allRequests[key].push(request); + }); + }); + } + /** + * Destroy all idle resources for the given address. + * @param {ServerAddress} address the address of the server to purge its pool. + * @returns {Promise} A promise that is resolved when the resources are purged + */ + + }, { + key: "purge", + value: function purge(address) { + return this._purgeKey(address.asKey()); + } + /** + * Destroy all idle resources in this pool. + * @returns {Promise} A promise that is resolved when the resources are purged + */ + + }, { + key: "close", + value: function close() { + var _this2 = this; + + this._closed = true; + return Promise.all(Object.keys(this._pools).map(function (key) { + return _this2._purgeKey(key); + })); + } + /** + * Keep the idle resources for the provided addresses and purge the rest. + * @returns {Promise} A promise that is resolved when the other resources are purged + */ + + }, { + key: "keepAll", + value: function keepAll(addresses) { + var _this3 = this; + + var keysToKeep = addresses.map(function (a) { + return a.asKey(); + }); + var keysPresent = Object.keys(this._pools); + var keysToPurge = keysPresent.filter(function (k) { + return keysToKeep.indexOf(k) === -1; + }); + return Promise.all(keysToPurge.map(function (key) { + return _this3._purgeKey(key); + })); + } + /** + * Check if this pool contains resources for the given address. + * @param {ServerAddress} address the address of the server to check. + * @return {boolean} `true` when pool contains entries for the given key, false otherwise. + */ + + }, { + key: "has", + value: function has(address) { + return address.asKey() in this._pools; + } + /** + * Get count of active (checked out of the pool) resources for the given key. + * @param {ServerAddress} address the address of the server to check. + * @return {number} count of resources acquired by clients. + */ + + }, { + key: "activeResourceCount", + value: function activeResourceCount(address) { + return this._activeResourceCounts[address.asKey()] || 0; + } + }, { + key: "_acquire", + value: function () { + var _acquire2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee(address) { + var key, pool, _resource, numConnections, resource; + + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (!this._closed) { + _context.next = 2; + break; + } + + throw (0, error.newError)('Pool is closed, it is no more able to serve requests.'); + + case 2: + key = address.asKey(); + pool = this._pools[key]; + + if (!pool) { + pool = []; + this._pools[key] = pool; + this._pendingCreates[key] = 0; + } + + case 5: + if (!pool.length) { + _context.next = 18; + break; + } + + _resource = pool.pop(); + + if (!this._validate(_resource)) { + _context.next = 14; + break; + } + + if (this._removeIdleObserver) { + this._removeIdleObserver(_resource); + } // idle resource is valid and can be acquired + + + resourceAcquired(key, this._activeResourceCounts); + + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(_resource, " acquired from the pool ").concat(key)); + } + + return _context.abrupt("return", _resource); + + case 14: + _context.next = 16; + return this._destroy(_resource); + + case 16: + _context.next = 5; + break; + + case 18: + if (!(this._maxSize > 0)) { + _context.next = 22; + break; + } + + // Include pending creates when checking pool size since these probably will add + // to the number when fulfilled. + numConnections = this.activeResourceCount(address) + this._pendingCreates[key]; + + if (!(numConnections >= this._maxSize)) { + _context.next = 22; + break; + } + + return _context.abrupt("return", null); + + case 22: + // there exist no idle valid resources, create a new one for acquisition + // Keep track of how many pending creates there are to avoid making too many connections. + this._pendingCreates[key] = this._pendingCreates[key] + 1; + _context.prev = 23; + _context.next = 26; + return this._create(address, this._release); + + case 26: + resource = _context.sent; + resourceAcquired(key, this._activeResourceCounts); + + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(resource, " created for the pool ").concat(key)); + } + + case 29: + _context.prev = 29; + this._pendingCreates[key] = this._pendingCreates[key] - 1; + return _context.finish(29); + + case 32: + return _context.abrupt("return", resource); + + case 33: + case "end": + return _context.stop(); + } + } + }, _callee, this, [[23,, 29, 32]]); + })); + + function _acquire(_x) { + return _acquire2.apply(this, arguments); + } + + return _acquire; + }() + }, { + key: "_release", + value: function () { + var _release2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee2(address, resource) { + var _this4 = this; + + var key, pool; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + key = address.asKey(); + pool = this._pools[key]; + + if (!pool) { + _context2.next = 14; + break; + } + + if (this._validate(resource)) { + _context2.next = 9; + break; + } + + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(resource, " destroyed and can't be released to the pool ").concat(key, " because it is not functional")); + } + + _context2.next = 7; + return this._destroy(resource); + + case 7: + _context2.next = 12; + break; + + case 9: + if (this._installIdleObserver) { + this._installIdleObserver(resource, { + onError: function onError(error) { + _this4._log.debug("Idle connection ".concat(resource, " destroyed because of error: ").concat(error)); + + var pool = _this4._pools[key]; + + if (pool) { + _this4._pools[key] = pool.filter(function (r) { + return r !== resource; + }); + } // let's not care about background clean-ups due to errors but just trigger the destroy + // process for the resource, we especially catch any errors and ignore them to avoid + // unhandled promise rejection warnings + + + _this4._destroy(resource)["catch"](function () {}); + } + }); + } + + pool.push(resource); + + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(resource, " released to the pool ").concat(key)); + } + + case 12: + _context2.next = 17; + break; + + case 14: + // key has been purged, don't put it back, just destroy the resource + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(resource, " destroyed and can't be released to the pool ").concat(key, " because pool has been purged")); + } + + _context2.next = 17; + return this._destroy(resource); + + case 17: + resourceReleased(key, this._activeResourceCounts); + + this._processPendingAcquireRequests(address); + + case 19: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function _release(_x2, _x3) { + return _release2.apply(this, arguments); + } + + return _release; + }() + }, { + key: "_purgeKey", + value: function () { + var _purgeKey2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee3(key) { + var pool, resource; + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + pool = this._pools[key] || []; + + case 1: + if (!pool.length) { + _context3.next = 8; + break; + } + + resource = pool.pop(); + + if (this._removeIdleObserver) { + this._removeIdleObserver(resource); + } + + _context3.next = 6; + return this._destroy(resource); + + case 6: + _context3.next = 1; + break; + + case 8: + delete this._pools[key]; + + case 9: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function _purgeKey(_x4) { + return _purgeKey2.apply(this, arguments); + } + + return _purgeKey; + }() + }, { + key: "_processPendingAcquireRequests", + value: function _processPendingAcquireRequests(address) { + var _this5 = this; + + var key = address.asKey(); + var requests = this._acquireRequests[key]; + + if (requests) { + var pendingRequest = requests.shift(); // pop a pending acquire request + + if (pendingRequest) { + this._acquire(address)["catch"](function (error) { + // failed to acquire/create a new connection to resolve the pending acquire request + // propagate the error by failing the pending request + pendingRequest.reject(error); + return null; + }).then(function (resource) { + if (resource) { + // managed to acquire a valid resource from the pool + if (pendingRequest.isCompleted()) { + // request has been completed, most likely failed by a timeout + // return the acquired resource back to the pool + _this5._release(address, resource); + } else { + // request is still pending and can be resolved with the newly acquired resource + pendingRequest.resolve(resource); // resolve the pending request with the acquired resource + } + } + }); + } else { + delete this._acquireRequests[key]; + } + } + } + }]); + return Pool; +}(); +/** + * Increment active (checked out of the pool) resource counter. + * @param {string} key the resource group identifier (server address for connections). + * @param {Object.} activeResourceCounts the object holding active counts per key. + */ + + +function resourceAcquired(key, activeResourceCounts) { + var currentCount = activeResourceCounts[key] || 0; + activeResourceCounts[key] = currentCount + 1; +} +/** + * Decrement active (checked out of the pool) resource counter. + * @param {string} key the resource group identifier (server address for connections). + * @param {Object.} activeResourceCounts the object holding active counts per key. + */ + + +function resourceReleased(key, activeResourceCounts) { + var currentCount = activeResourceCounts[key] || 0; + var nextCount = currentCount - 1; + + if (nextCount > 0) { + activeResourceCounts[key] = nextCount; + } else { + delete activeResourceCounts[key]; + } +} + +var PendingRequest = +/*#__PURE__*/ +function () { + function PendingRequest(key, resolve, reject, timeoutId, log) { + (0, _classCallCheck2["default"])(this, PendingRequest); + this._key = key; + this._resolve = resolve; + this._reject = reject; + this._timeoutId = timeoutId; + this._log = log; + this._completed = false; + } + + (0, _createClass2["default"])(PendingRequest, [{ + key: "isCompleted", + value: function isCompleted() { + return this._completed; + } + }, { + key: "resolve", + value: function resolve(resource) { + if (this._completed) { + return; + } + + this._completed = true; + clearTimeout(this._timeoutId); + + if (this._log.isDebugEnabled()) { + this._log.debug("".concat(resource, " acquired from the pool ").concat(this._key)); + } + + this._resolve(resource); + } + }, { + key: "reject", + value: function reject(error) { + if (this._completed) { + return; + } + + this._completed = true; + clearTimeout(this._timeoutId); + + this._reject(error); + } + }]); + return PendingRequest; +}(); + +var _default = Pool; +exports["default"] = _default; +}); + +var connectionErrorHandler = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var ConnectionErrorHandler = +/*#__PURE__*/ +function () { + function ConnectionErrorHandler(errorCode, handleUnavailability, handleWriteFailure) { + (0, _classCallCheck2["default"])(this, ConnectionErrorHandler); + this._errorCode = errorCode; + this._handleUnavailability = handleUnavailability || noOpHandler; + this._handleWriteFailure = handleWriteFailure || noOpHandler; + } + /** + * Error code to use for network errors. + * @return {string} the error code. + */ + + + (0, _createClass2["default"])(ConnectionErrorHandler, [{ + key: "errorCode", + value: function errorCode() { + return this._errorCode; + } + /** + * Handle and transform the error. + * @param {Neo4jError} error the original error. + * @param {ServerAddress} address the address of the connection where the error happened. + * @return {Neo4jError} new error that should be propagated to the user. + */ + + }, { + key: "handleAndTransformError", + value: function handleAndTransformError(error, address) { + if (isAvailabilityError(error)) { + return this._handleUnavailability(error, address); + } + + if (isFailureToWrite(error)) { + return this._handleWriteFailure(error, address); + } + + return error; + } + }]); + return ConnectionErrorHandler; +}(); + +exports["default"] = ConnectionErrorHandler; + +function isAvailabilityError(error$1) { + if (error$1) { + return error$1.code === error.SESSION_EXPIRED || error$1.code === error.SERVICE_UNAVAILABLE || error$1.code === 'Neo.TransientError.General.DatabaseUnavailable'; + } + + return false; +} + +function isFailureToWrite(error) { + if (error) { + return error.code === 'Neo.ClientError.Cluster.NotALeader' || error.code === 'Neo.ClientError.General.ForbiddenOnReadOnlyDatabase'; + } + + return false; +} + +function noOpHandler(error) { + return error; +} +}); + +var connectionProviderPooled = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _regenerator = interopRequireDefault(regenerator); + +var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _assertThisInitialized2 = interopRequireDefault(assertThisInitialized); + +var _inherits2 = interopRequireDefault(inherits); + +var _connectionChannel = interopRequireDefault(connectionChannel); + +var _pool = interopRequireDefault(pool); + +var _poolConfig = interopRequireDefault(poolConfig); + +var _connectionErrorHandler = interopRequireDefault(connectionErrorHandler); + + + +var _connectionProvider = interopRequireDefault(connectionProvider); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var PooledConnectionProvider = +/*#__PURE__*/ +function (_ConnectionProvider) { + (0, _inherits2["default"])(PooledConnectionProvider, _ConnectionProvider); + + function PooledConnectionProvider(_ref) { + var _this; + + var id = _ref.id, + config = _ref.config, + log = _ref.log, + userAgent = _ref.userAgent, + authToken = _ref.authToken; + var createChannelConnectionHook = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; + (0, _classCallCheck2["default"])(this, PooledConnectionProvider); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(PooledConnectionProvider).call(this)); + _this._id = id; + _this._config = config; + _this._log = log; + _this._userAgent = userAgent; + _this._authToken = authToken; + + _this._createChannelConnection = createChannelConnectionHook || function (address) { + return _connectionChannel["default"].create(address, _this._config, _this._createConnectionErrorHandler(), _this._log); + }; + + _this._connectionPool = new _pool["default"]({ + create: _this._createConnection.bind((0, _assertThisInitialized2["default"])(_this)), + destroy: _this._destroyConnection.bind((0, _assertThisInitialized2["default"])(_this)), + validate: _this._validateConnection.bind((0, _assertThisInitialized2["default"])(_this)), + installIdleObserver: PooledConnectionProvider._installIdleObserverOnConnection.bind((0, _assertThisInitialized2["default"])(_this)), + removeIdleObserver: PooledConnectionProvider._removeIdleObserverOnConnection.bind((0, _assertThisInitialized2["default"])(_this)), + config: _poolConfig["default"].fromDriverConfig(config), + log: _this._log + }); + _this._openConnections = {}; + return _this; + } + + (0, _createClass2["default"])(PooledConnectionProvider, [{ + key: "_createConnectionErrorHandler", + value: function _createConnectionErrorHandler() { + return new _connectionErrorHandler["default"](error.SERVICE_UNAVAILABLE); + } + /** + * Create a new connection and initialize it. + * @return {Promise} promise resolved with a new connection or rejected when failed to connect. + * @access private + */ + + }, { + key: "_createConnection", + value: function _createConnection(address, release) { + var _this2 = this; + + var connection = this._createChannelConnection(address); + + connection._release = function () { + return release(address, connection); + }; + + this._openConnections[connection.id] = connection; + return connection.connect(this._userAgent, this._authToken)["catch"](function (error) { + // let's destroy this connection + _this2._destroyConnection(connection); // propagate the error because connection failed to connect / initialize + + + throw error; + }); + } + /** + * Check that a connection is usable + * @return {boolean} true if the connection is open + * @access private + **/ + + }, { + key: "_validateConnection", + value: function _validateConnection(conn) { + if (!conn.isOpen()) { + return false; + } + + var maxConnectionLifetime = this._config.maxConnectionLifetime; + var lifetime = Date.now() - conn.creationTimestamp; + return lifetime <= maxConnectionLifetime; + } + /** + * Dispose of a connection. + * @return {Connection} the connection to dispose. + * @access private + */ + + }, { + key: "_destroyConnection", + value: function _destroyConnection(conn) { + delete this._openConnections[conn.id]; + return conn.close(); + } + }, { + key: "close", + value: function () { + var _close = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee() { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this._connectionPool.close(); + + case 2: + _context.next = 4; + return Promise.all(Object.values(this._openConnections).map(function (c) { + return c.close(); + })); + + case 4: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function close() { + return _close.apply(this, arguments); + } + + return close; + }() + }], [{ + key: "_installIdleObserverOnConnection", + value: function _installIdleObserverOnConnection(conn, observer) { + conn._queueObserver(observer); + } + }, { + key: "_removeIdleObserverOnConnection", + value: function _removeIdleObserverOnConnection(conn) { + conn._updateCurrentObserver(); + } + }]); + return PooledConnectionProvider; +}(_connectionProvider["default"]); + +exports["default"] = PooledConnectionProvider; +}); + +var connectionDelegate = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _connection = interopRequireDefault(connection); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var DelegateConnection = +/*#__PURE__*/ +function (_Connection) { + (0, _inherits2["default"])(DelegateConnection, _Connection); + + /** + * @param delegate {Connection} the delegated connection + * @param errorHandler {ConnectionErrorHandler} the error handler + */ + function DelegateConnection(delegate, errorHandler) { + var _this; + + (0, _classCallCheck2["default"])(this, DelegateConnection); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(DelegateConnection).call(this, errorHandler)); + + if (errorHandler) { + _this._originalErrorHandler = delegate._errorHandler; + delegate._errorHandler = _this._errorHandler; + } + + _this._delegate = delegate; + return _this; + } + + (0, _createClass2["default"])(DelegateConnection, [{ + key: "isOpen", + value: function isOpen() { + return this._delegate.isOpen(); + } + }, { + key: "protocol", + value: function protocol() { + return this._delegate.protocol(); + } + }, { + key: "connect", + value: function connect(userAgent, authToken) { + return this._delegate.connect(userAgent, authToken); + } + }, { + key: "write", + value: function write(message, observer, flush) { + return this._delegate.write(message, observer, flush); + } + }, { + key: "resetAndFlush", + value: function resetAndFlush() { + return this._delegate.resetAndFlush(); + } + }, { + key: "close", + value: function close() { + return this._delegate.close(); + } + }, { + key: "_release", + value: function _release() { + if (this._originalErrorHandler) { + this._delegate._errorHandler = this._originalErrorHandler; + } + + return this._delegate._release(); + } + }, { + key: "id", + get: function get() { + return this._delegate.id; + } + }, { + key: "databaseId", + get: function get() { + return this._delegate.databaseId; + }, + set: function set(value) { + this._delegate.databaseId = value; + } + }, { + key: "server", + get: function get() { + return this._delegate.server; + } + }, { + key: "address", + get: function get() { + return this._delegate.address; + } + }, { + key: "version", + get: function get() { + return this._delegate.version; + }, + set: function set(value) { + this._delegate.version = value; + } + }]); + return DelegateConnection; +}(_connection["default"]); + +exports["default"] = DelegateConnection; +}); + +var connectionProviderDirect = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _regenerator = interopRequireDefault(regenerator); + +var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _connectionProviderPooled = interopRequireDefault(connectionProviderPooled); + +var _connectionDelegate = interopRequireDefault(connectionDelegate); + +var _connectionChannel = interopRequireDefault(connectionChannel); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var DirectConnectionProvider = +/*#__PURE__*/ +function (_PooledConnectionProv) { + (0, _inherits2["default"])(DirectConnectionProvider, _PooledConnectionProv); + + function DirectConnectionProvider(_ref) { + var _this; + + var id = _ref.id, + config = _ref.config, + log = _ref.log, + address = _ref.address, + userAgent = _ref.userAgent, + authToken = _ref.authToken; + (0, _classCallCheck2["default"])(this, DirectConnectionProvider); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(DirectConnectionProvider).call(this, { + id: id, + config: config, + log: log, + userAgent: userAgent, + authToken: authToken + })); + _this._address = address; + return _this; + } + /** + * See {@link ConnectionProvider} for more information about this method and + * its arguments. + */ + + + (0, _createClass2["default"])(DirectConnectionProvider, [{ + key: "acquireConnection", + value: function acquireConnection() { + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _ref2.accessMode; + _ref2.database; + _ref2.bookmarks; + + return this._connectionPool.acquire(this._address).then(function (connection) { + return new _connectionDelegate["default"](connection, null); + }); + } + }, { + key: "_hasProtocolVersion", + value: function () { + var _hasProtocolVersion2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee(versionPredicate) { + var connection, protocol; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + connection = _connectionChannel["default"].create(this._address, this._config, this._createConnectionErrorHandler(), this._log); + _context.prev = 1; + _context.next = 4; + return connection._negotiateProtocol(); + + case 4: + protocol = connection.protocol(); + + if (!protocol) { + _context.next = 7; + break; + } + + return _context.abrupt("return", versionPredicate(protocol.version)); + + case 7: + return _context.abrupt("return", false); + + case 8: + _context.prev = 8; + _context.next = 11; + return connection.close(); + + case 11: + return _context.finish(8); + + case 12: + case "end": + return _context.stop(); + } + } + }, _callee, this, [[1,, 8, 12]]); + })); + + function _hasProtocolVersion(_x) { + return _hasProtocolVersion2.apply(this, arguments); + } + + return _hasProtocolVersion; + }() + }, { + key: "supportsMultiDb", + value: function () { + var _supportsMultiDb = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee2() { + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this._hasProtocolVersion(function (version) { + return version >= constants.BOLT_PROTOCOL_V4_0; + }); + + case 2: + return _context2.abrupt("return", _context2.sent); + + case 3: + case "end": + return _context2.stop(); + } + } + }, _callee2, this); + })); + + function supportsMultiDb() { + return _supportsMultiDb.apply(this, arguments); + } + + return supportsMultiDb; + }() + }, { + key: "supportsTransactionConfig", + value: function () { + var _supportsTransactionConfig = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee3() { + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this._hasProtocolVersion(function (version) { + return version >= constants.BOLT_PROTOCOL_V3; + }); + + case 2: + return _context3.abrupt("return", _context3.sent); + + case 3: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function supportsTransactionConfig() { + return _supportsTransactionConfig.apply(this, arguments); + } + + return supportsTransactionConfig; + }() + }]); + return DirectConnectionProvider; +}(_connectionProviderPooled["default"]); + +exports["default"] = DirectConnectionProvider; +}); + +var connectivityVerifier = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _connectionHolder = interopRequireDefault(connectionHolder); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Verifies connectivity using the given connection provider. + */ +var ConnectivityVerifier = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {ConnectionProvider} connectionProvider the provider to obtain connections from. + */ + function ConnectivityVerifier(connectionProvider) { + (0, _classCallCheck2["default"])(this, ConnectivityVerifier); + this._connectionProvider = connectionProvider; + } + /** + * Try to obtain a working connection from the connection provider. + * @returns {Promise} promise resolved with server info or rejected with error. + */ + + + (0, _createClass2["default"])(ConnectivityVerifier, [{ + key: "verify", + value: function verify() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$database = _ref.database, + database = _ref$database === void 0 ? '' : _ref$database; + + return acquireAndReleaseDummyConnection(this._connectionProvider, database); + } + }]); + return ConnectivityVerifier; +}(); +/** + * @private + * @param {ConnectionProvider} connectionProvider the provider to obtain connections from. + * @return {Promise} promise resolved with server info or rejected with error. + */ + + +exports["default"] = ConnectivityVerifier; + +function acquireAndReleaseDummyConnection(connectionProvider, database) { + var connectionHolder = new _connectionHolder["default"]({ + mode: driver.READ, + database: database, + connectionProvider: connectionProvider + }); + connectionHolder.initializeConnection(); + return connectionHolder.getConnection().then(function (connection) { + // able to establish a connection + return connectionHolder.close().then(function () { + return connection.server; + }); + })["catch"](function (error) { + // failed to establish a connection + return connectionHolder.close()["catch"](function (ignoredError) {// ignore connection release error + }).then(function () { + return Promise.reject(error); + }); + }); +} +}); + +var connectionHolderReadonly = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _connectionHolder = interopRequireDefault(connectionHolder); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Provides a interaction with a ConnectionHolder without change it state by + * releasing or initilizing + */ +var ReadOnlyConnectionHolder = +/*#__PURE__*/ +function (_ConnectionHolder) { + (0, _inherits2["default"])(ReadOnlyConnectionHolder, _ConnectionHolder); + + /** + * Contructor + * @param {ConnectionHolder} connectionHolder the connection holder which will treat the requests + */ + function ReadOnlyConnectionHolder(connectionHolder) { + var _this; + + (0, _classCallCheck2["default"])(this, ReadOnlyConnectionHolder); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ReadOnlyConnectionHolder).call(this, { + mode: connectionHolder._mode, + database: connectionHolder._database, + bookmark: connectionHolder._bookmark, + connectionProvider: connectionHolder._connectionProvider + })); + _this._connectionHolder = connectionHolder; + return _this; + } + /** + * Return the true if the connection is suppose to be initilized with the command. + * + * @return {boolean} + */ + + + (0, _createClass2["default"])(ReadOnlyConnectionHolder, [{ + key: "initializeConnection", + value: function initializeConnection() { + if (this._connectionHolder._referenceCount === 0) { + return false; + } + + return true; + } + /** + * Get the current connection promise. + * @return {Promise} promise resolved with the current connection. + */ + + }, { + key: "getConnection", + value: function getConnection() { + return this._connectionHolder.getConnection(); + } + /** + * Get the current connection promise, doesn't performs the release + * @return {Promise} promise with the resolved current connection + */ + + }, { + key: "releaseConnection", + value: function releaseConnection() { + return this._connectionHolder.getConnection()["catch"](function () { + return Promise.resolve(); + }); + } + /** + * Get the current connection promise, doesn't performs the connection close + * @return {Promise} promise with the resolved current connection + */ + + }, { + key: "close", + value: function close() { + return this._connectionHolder.getConnection()["catch"](function () { + return function () { + return Promise.resolve(); + }; + }); + } + }]); + return ReadOnlyConnectionHolder; +}(_connectionHolder["default"]); + +exports["default"] = ReadOnlyConnectionHolder; +}); + +var transaction = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _result = interopRequireDefault(result); + + + +var _connectionHolder = interopRequireWildcard(connectionHolder); + +var _connectionHolderReadonly = interopRequireDefault(connectionHolderReadonly); + +var _bookmark = interopRequireDefault(bookmark); + +var _txConfig = interopRequireDefault(txConfig); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Represents a transaction in the Neo4j database. + * + * @access public + */ +var Transaction = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {ConnectionHolder} connectionHolder - the connection holder to get connection from. + * @param {function()} onClose - Function to be called when transaction is committed or rolled back. + * @param {function(bookmark: Bookmark)} onBookmark callback invoked when new bookmark is produced. + * * @param {function()} onConnection - Function to be called when a connection is obtained to ensure the conneciton + * is not yet released. + * @param {boolean} reactive whether this transaction generates reactive streams + * @param {number} fetchSize - the record fetch size in each pulling batch. + */ + function Transaction(_ref) { + var connectionHolder = _ref.connectionHolder, + onClose = _ref.onClose, + onBookmark = _ref.onBookmark, + onConnection = _ref.onConnection, + reactive = _ref.reactive, + fetchSize = _ref.fetchSize; + (0, _classCallCheck2["default"])(this, Transaction); + this._connectionHolder = connectionHolder; + this._reactive = reactive; + this._state = _states.ACTIVE; + this._onClose = onClose; + this._onBookmark = onBookmark; + this._onConnection = onConnection; + this._onError = this._onErrorCallback.bind(this); + this._onComplete = this._onCompleteCallback.bind(this); + this._fetchSize = fetchSize; + this._results = []; + } + + (0, _createClass2["default"])(Transaction, [{ + key: "_begin", + value: function _begin(bookmark, txConfig) { + var _this = this; + + this._connectionHolder.getConnection().then(function (conn) { + _this._onConnection(); + + return conn.protocol().beginTransaction({ + bookmark: bookmark, + txConfig: txConfig, + mode: _this._connectionHolder.mode(), + database: _this._connectionHolder.database(), + beforeError: _this._onError, + afterComplete: _this._onComplete + }); + })["catch"](function (error) { + return _this._onError(error); + }); + } + /** + * Run Cypher query + * Could be called with a query object i.e.: `{text: "MATCH ...", parameters: {param: 1}}` + * or with the query and parameters as separate arguments. + * @param {mixed} query - Cypher query to execute + * @param {Object} parameters - Map with parameters to use in query + * @return {Result} New Result + */ + + }, { + key: "run", + value: function run(query, parameters) { + var _validateQueryAndPara = (0, util.validateQueryAndParameters)(query, parameters), + validatedQuery = _validateQueryAndPara.validatedQuery, + params = _validateQueryAndPara.params; + + var result = this._state.run(validatedQuery, params, { + connectionHolder: this._connectionHolder, + onError: this._onError, + onComplete: this._onComplete, + onConnection: this._onConnection, + reactive: this._reactive, + fetchSize: this._fetchSize + }); + + this._results.push(result); + + return result; + } + /** + * Commits the transaction and returns the result. + * + * After committing the transaction can no longer be used. + * + * @returns {Promise} An empty promise if committed successfully or error if any error happened during commit. + */ + + }, { + key: "commit", + value: function commit() { + var committed = this._state.commit({ + connectionHolder: this._connectionHolder, + onError: this._onError, + onComplete: this._onComplete, + onConnection: this._onConnection, + pendingResults: this._results + }); + + this._state = committed.state; // clean up + + this._onClose(); + + return new Promise(function (resolve, reject) { + committed.result.subscribe({ + onCompleted: function onCompleted() { + return resolve(); + }, + onError: function onError(error) { + return reject(error); + } + }); + }); + } + /** + * Rollbacks the transaction. + * + * After rolling back, the transaction can no longer be used. + * + * @returns {Promise} An empty promise if rolled back successfully or error if any error happened during + * rollback. + */ + + }, { + key: "rollback", + value: function rollback() { + var rolledback = this._state.rollback({ + connectionHolder: this._connectionHolder, + onError: this._onError, + onComplete: this._onComplete, + onConnection: this._onConnection, + pendingResults: this._results + }); + + this._state = rolledback.state; // clean up + + this._onClose(); + + return new Promise(function (resolve, reject) { + rolledback.result.subscribe({ + onCompleted: function onCompleted() { + return resolve(); + }, + onError: function onError(error) { + return reject(error); + } + }); + }); + } + /** + * Check if this transaction is active, which means commit and rollback did not happen. + * @return {boolean} `true` when not committed and not rolled back, `false` otherwise. + */ + + }, { + key: "isOpen", + value: function isOpen() { + return this._state === _states.ACTIVE; + } + }, { + key: "_onErrorCallback", + value: function _onErrorCallback(err) { + // error will be "acknowledged" by sending a RESET message + // database will then forget about this transaction and cleanup all corresponding resources + // it is thus safe to move this transaction to a FAILED state and disallow any further interactions with it + this._state = _states.FAILED; + + this._onClose(); // release connection back to the pool + + + return this._connectionHolder.releaseConnection(); + } + }, { + key: "_onCompleteCallback", + value: function _onCompleteCallback(meta) { + this._onBookmark(new _bookmark["default"](meta.bookmark)); + } + }]); + return Transaction; +}(); + +var _states = { + // The transaction is running with no explicit success or failure marked + ACTIVE: { + commit: function commit(_ref2) { + var connectionHolder = _ref2.connectionHolder, + onError = _ref2.onError, + onComplete = _ref2.onComplete, + onConnection = _ref2.onConnection, + pendingResults = _ref2.pendingResults; + return { + result: finishTransaction(true, connectionHolder, onError, onComplete, onConnection, pendingResults), + state: _states.SUCCEEDED + }; + }, + rollback: function rollback(_ref3) { + var connectionHolder = _ref3.connectionHolder, + onError = _ref3.onError, + onComplete = _ref3.onComplete, + onConnection = _ref3.onConnection, + pendingResults = _ref3.pendingResults; + return { + result: finishTransaction(false, connectionHolder, onError, onComplete, onConnection, pendingResults), + state: _states.ROLLED_BACK + }; + }, + run: function run(query, parameters, _ref4) { + var connectionHolder = _ref4.connectionHolder, + onError = _ref4.onError, + onComplete = _ref4.onComplete, + onConnection = _ref4.onConnection, + reactive = _ref4.reactive, + fetchSize = _ref4.fetchSize; + // RUN in explicit transaction can't contain bookmarks and transaction configuration + // No need to include mode and database name as it shall be inclued in begin + var observerPromise = connectionHolder.getConnection().then(function (conn) { + onConnection(); + return conn.protocol().run(query, parameters, { + bookmark: _bookmark["default"].empty(), + txConfig: _txConfig["default"].empty(), + beforeError: onError, + afterComplete: onComplete, + reactive: reactive, + fetchSize: fetchSize + }); + })["catch"](function (error) { + return new streamObservers.FailedObserver({ + error: error, + onError: onError + }); + }); + return newCompletedResult(observerPromise, query, parameters, connectionHolder); + } + }, + // An error has occurred, transaction can no longer be used and no more messages will + // be sent for this transaction. + FAILED: { + commit: function commit(_ref5) { + var connectionHolder = _ref5.connectionHolder, + onError = _ref5.onError; + _ref5.onComplete; + return { + result: newCompletedResult(new streamObservers.FailedObserver({ + error: (0, error.newError)('Cannot commit this transaction, because it has been rolled back either because of an error or explicit termination.'), + onError: onError + }), 'COMMIT', {}, connectionHolder), + state: _states.FAILED + }; + }, + rollback: function rollback(_ref6) { + var connectionHolder = _ref6.connectionHolder; + _ref6.onError; + _ref6.onComplete; + return { + result: newCompletedResult(new streamObservers.CompletedObserver(), 'ROLLBACK', {}, connectionHolder), + state: _states.FAILED + }; + }, + run: function run(query, parameters, _ref7) { + var connectionHolder = _ref7.connectionHolder, + onError = _ref7.onError; + _ref7.onComplete; + return newCompletedResult(new streamObservers.FailedObserver({ + error: (0, error.newError)('Cannot run query in this transaction, because it has been rolled back either because of an error or explicit termination.'), + onError: onError + }), query, parameters, connectionHolder); + } + }, + // This transaction has successfully committed + SUCCEEDED: { + commit: function commit(_ref8) { + var connectionHolder = _ref8.connectionHolder, + onError = _ref8.onError; + _ref8.onComplete; + return { + result: newCompletedResult(new streamObservers.FailedObserver({ + error: (0, error.newError)('Cannot commit this transaction, because it has already been committed.'), + onError: onError + }), 'COMMIT', {}), + state: _states.SUCCEEDED, + connectionHolder: connectionHolder + }; + }, + rollback: function rollback(_ref9) { + var connectionHolder = _ref9.connectionHolder, + onError = _ref9.onError; + _ref9.onComplete; + return { + result: newCompletedResult(new streamObservers.FailedObserver({ + error: (0, error.newError)('Cannot rollback this transaction, because it has already been committed.'), + onError: onError + }), 'ROLLBACK', {}), + state: _states.SUCCEEDED, + connectionHolder: connectionHolder + }; + }, + run: function run(query, parameters, _ref10) { + var connectionHolder = _ref10.connectionHolder, + onError = _ref10.onError; + _ref10.onComplete; + return newCompletedResult(new streamObservers.FailedObserver({ + error: (0, error.newError)('Cannot run query in this transaction, because it has already been committed.'), + onError: onError + }), query, parameters, connectionHolder); + } + }, + // This transaction has been rolled back + ROLLED_BACK: { + commit: function commit(_ref11) { + var connectionHolder = _ref11.connectionHolder, + onError = _ref11.onError; + _ref11.onComplete; + return { + result: newCompletedResult(new streamObservers.FailedObserver({ + error: (0, error.newError)('Cannot commit this transaction, because it has already been rolled back.'), + onError: onError + }), 'COMMIT', {}, connectionHolder), + state: _states.ROLLED_BACK + }; + }, + rollback: function rollback(_ref12) { + var connectionHolder = _ref12.connectionHolder; + _ref12.onError; + _ref12.onComplete; + return { + result: newCompletedResult(new streamObservers.FailedObserver({ + error: (0, error.newError)('Cannot rollback this transaction, because it has already been rolled back.') + }), 'ROLLBACK', {}, connectionHolder), + state: _states.ROLLED_BACK + }; + }, + run: function run(query, parameters, _ref13) { + var connectionHolder = _ref13.connectionHolder, + onError = _ref13.onError; + _ref13.onComplete; + return newCompletedResult(new streamObservers.FailedObserver({ + error: (0, error.newError)('Cannot run query in this transaction, because it has already been rolled back.'), + onError: onError + }), query, parameters, connectionHolder); + } + } + /** + * + * @param {boolean} commit + * @param {ConnectionHolder} connectionHolder + * @param {function(err:Error): any} onError + * @param {function(metadata:object): any} onComplete + * @param {function() : any} onConnection + * @param {list>}pendingResults all run results in this transaction + */ + +}; + +function finishTransaction(commit, connectionHolder, onError, onComplete, onConnection, pendingResults) { + var observerPromise = connectionHolder.getConnection().then(function (connection) { + onConnection(); + pendingResults.forEach(function (r) { + return r._cancel(); + }); + return Promise.all(pendingResults).then(function (results) { + if (commit) { + return connection.protocol().commitTransaction({ + beforeError: onError, + afterComplete: onComplete + }); + } else { + return connection.protocol().rollbackTransaction({ + beforeError: onError, + afterComplete: onComplete + }); + } + }); + })["catch"](function (error) { + return new streamObservers.FailedObserver({ + error: error, + onError: onError + }); + }); // for commit & rollback we need result that uses real connection holder and notifies it when + // connection is not needed and can be safely released to the pool + + return new _result["default"](observerPromise, commit ? 'COMMIT' : 'ROLLBACK', {}, connectionHolder); +} +/** + * Creates a {@link Result} with empty connection holder. + * For cases when result represents an intermediate or failed action, does not require any metadata and does not + * need to influence real connection holder to release connections. + * @param {ResultStreamObserver} observer - an observer for the created result. + * @param {string} query - the cypher query that produced the result. + * @param {Object} parameters - the parameters for cypher query that produced the result. + * @param {ConnectionHolder} connectionHolder - the connection holder used to get the result + * @return {Result} new result. + * @private + */ + + +function newCompletedResult(observerPromise, query, parameters) { + var connectionHolder = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _connectionHolder.EMPTY_CONNECTION_HOLDER; + return new _result["default"](Promise.resolve(observerPromise), query, parameters, new _connectionHolderReadonly["default"](connectionHolder || _connectionHolder.EMPTY_CONNECTION_HOLDER)); +} + +var _default = Transaction; +exports["default"] = _default; +}); + +var transactionExecutor = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var DEFAULT_MAX_RETRY_TIME_MS = 30 * 1000; // 30 seconds + +var DEFAULT_INITIAL_RETRY_DELAY_MS = 1000; // 1 seconds + +var DEFAULT_RETRY_DELAY_MULTIPLIER = 2.0; +var DEFAULT_RETRY_DELAY_JITTER_FACTOR = 0.2; + +var TransactionExecutor = +/*#__PURE__*/ +function () { + function TransactionExecutor(maxRetryTimeMs, initialRetryDelayMs, multiplier, jitterFactor) { + (0, _classCallCheck2["default"])(this, TransactionExecutor); + this._maxRetryTimeMs = _valueOrDefault(maxRetryTimeMs, DEFAULT_MAX_RETRY_TIME_MS); + this._initialRetryDelayMs = _valueOrDefault(initialRetryDelayMs, DEFAULT_INITIAL_RETRY_DELAY_MS); + this._multiplier = _valueOrDefault(multiplier, DEFAULT_RETRY_DELAY_MULTIPLIER); + this._jitterFactor = _valueOrDefault(jitterFactor, DEFAULT_RETRY_DELAY_JITTER_FACTOR); + this._inFlightTimeoutIds = []; + + this._verifyAfterConstruction(); + } + + (0, _createClass2["default"])(TransactionExecutor, [{ + key: "execute", + value: function execute(transactionCreator, transactionWork) { + var _this = this; + + return new Promise(function (resolve, reject) { + _this._executeTransactionInsidePromise(transactionCreator, transactionWork, resolve, reject); + })["catch"](function (error) { + var retryStartTimeMs = Date.now(); + var retryDelayMs = _this._initialRetryDelayMs; + return _this._retryTransactionPromise(transactionCreator, transactionWork, error, retryStartTimeMs, retryDelayMs); + }); + } + }, { + key: "close", + value: function close() { + // cancel all existing timeouts to prevent further retries + this._inFlightTimeoutIds.forEach(function (timeoutId) { + return clearTimeout(timeoutId); + }); + + this._inFlightTimeoutIds = []; + } + }, { + key: "_retryTransactionPromise", + value: function _retryTransactionPromise(transactionCreator, transactionWork, error, retryStartTime, retryDelayMs) { + var _this2 = this; + + var elapsedTimeMs = Date.now() - retryStartTime; + + if (elapsedTimeMs > this._maxRetryTimeMs || !TransactionExecutor._canRetryOn(error)) { + return Promise.reject(error); + } + + return new Promise(function (resolve, reject) { + var nextRetryTime = _this2._computeDelayWithJitter(retryDelayMs); + + var timeoutId = setTimeout(function () { + // filter out this timeoutId when time has come and function is being executed + _this2._inFlightTimeoutIds = _this2._inFlightTimeoutIds.filter(function (id) { + return id !== timeoutId; + }); + + _this2._executeTransactionInsidePromise(transactionCreator, transactionWork, resolve, reject); + }, nextRetryTime); // add newly created timeoutId to the list of all in-flight timeouts + + _this2._inFlightTimeoutIds.push(timeoutId); + })["catch"](function (error) { + var nextRetryDelayMs = retryDelayMs * _this2._multiplier; + return _this2._retryTransactionPromise(transactionCreator, transactionWork, error, retryStartTime, nextRetryDelayMs); + }); + } + }, { + key: "_executeTransactionInsidePromise", + value: function _executeTransactionInsidePromise(transactionCreator, transactionWork, resolve, reject) { + var _this3 = this; + + var tx; + + try { + tx = transactionCreator(); + } catch (error) { + // failed to create a transaction + reject(error); + return; + } + + var resultPromise = this._safeExecuteTransactionWork(tx, transactionWork); + + resultPromise.then(function (result) { + return _this3._handleTransactionWorkSuccess(result, tx, resolve, reject); + })["catch"](function (error) { + return _this3._handleTransactionWorkFailure(error, tx, reject); + }); + } + }, { + key: "_safeExecuteTransactionWork", + value: function _safeExecuteTransactionWork(tx, transactionWork) { + try { + var result = transactionWork(tx); // user defined callback is supposed to return a promise, but it might not; so to protect against an + // incorrect API usage we wrap the returned value with a resolved promise; this is effectively a + // validation step without type checks + + return Promise.resolve(result); + } catch (error) { + return Promise.reject(error); + } + } + }, { + key: "_handleTransactionWorkSuccess", + value: function _handleTransactionWorkSuccess(result, tx, resolve, reject) { + if (tx.isOpen()) { + // transaction work returned resolved promise and transaction has not been committed/rolled back + // try to commit the transaction + tx.commit().then(function () { + // transaction was committed, return result to the user + resolve(result); + })["catch"](function (error) { + // transaction failed to commit, propagate the failure + reject(error); + }); + } else { + // transaction work returned resolved promise and transaction is already committed/rolled back + // return the result returned by given transaction work + resolve(result); + } + } + }, { + key: "_handleTransactionWorkFailure", + value: function _handleTransactionWorkFailure(error, tx, reject) { + if (tx.isOpen()) { + // transaction work failed and the transaction is still open, roll it back and propagate the failure + tx.rollback()["catch"](function (ignore) {// ignore the rollback error + }).then(function () { + return reject(error); + }); // propagate the original error we got from the transaction work + } else { + // transaction is already rolled back, propagate the error + reject(error); + } + } + }, { + key: "_computeDelayWithJitter", + value: function _computeDelayWithJitter(delayMs) { + var jitter = delayMs * this._jitterFactor; + var min = delayMs - jitter; + var max = delayMs + jitter; + return Math.random() * (max - min) + min; + } + }, { + key: "_verifyAfterConstruction", + value: function _verifyAfterConstruction() { + if (this._maxRetryTimeMs < 0) { + throw (0, error.newError)('Max retry time should be >= 0: ' + this._maxRetryTimeMs); + } + + if (this._initialRetryDelayMs < 0) { + throw (0, error.newError)('Initial retry delay should >= 0: ' + this._initialRetryDelayMs); + } + + if (this._multiplier < 1.0) { + throw (0, error.newError)('Multiplier should be >= 1.0: ' + this._multiplier); + } + + if (this._jitterFactor < 0 || this._jitterFactor > 1) { + throw (0, error.newError)('Jitter factor should be in [0.0, 1.0]: ' + this._jitterFactor); + } + } + }], [{ + key: "_canRetryOn", + value: function _canRetryOn(error$1) { + return error$1 && error$1 instanceof error.Neo4jError && error$1.code && (error$1.code === error.SERVICE_UNAVAILABLE || error$1.code === error.SESSION_EXPIRED || this._isTransientError(error$1)); + } + }, { + key: "_isTransientError", + value: function _isTransientError(error) { + // Retries should not happen when transaction was explicitly terminated by the user. + // Termination of transaction might result in two different error codes depending on where it was + // terminated. These are really client errors but classification on the server is not entirely correct and + // they are classified as transient. + var code = error.code; + + if (code.indexOf('TransientError') >= 0) { + if (code === 'Neo.TransientError.Transaction.Terminated' || code === 'Neo.TransientError.Transaction.LockClientStopped') { + return false; + } + + return true; + } + + return false; + } + }]); + return TransactionExecutor; +}(); + +exports["default"] = TransactionExecutor; + +function _valueOrDefault(value, defaultValue) { + if (value || value === 0) { + return value; + } + + return defaultValue; +} +}); + +var session = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _regenerator = interopRequireDefault(regenerator); + +var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +var _result = interopRequireDefault(result); + +var _transaction = interopRequireDefault(transaction); + + + + + +var _connectionHolder = interopRequireDefault(connectionHolder); + +var _driver = interopRequireDefault(driver); + + + +var _transactionExecutor = interopRequireDefault(transactionExecutor); + +var _bookmark = interopRequireDefault(bookmark); + +var _txConfig = interopRequireDefault(txConfig); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A Session instance is used for handling the connection and + * sending queries through the connection. + * In a single session, multiple queries will be executed serially. + * In order to execute parallel queries, multiple sessions are required. + * @access public + */ +var Session = +/*#__PURE__*/ +function () { + /** + * @constructor + * @protected + * @param {Object} args + * @param {string} args.mode the default access mode for this session. + * @param {ConnectionProvider} args.connectionProvider - The connection provider to acquire connections from. + * @param {Bookmark} args.bookmark - The initial bookmark for this session. + * @param {string} args.database the database name + * @param {Object} args.config={} - This driver configuration. + * @param {boolean} args.reactive - Whether this session should create reactive streams + * @param {number} args.fetchSize - Defines how many records is pulled in each pulling batch + */ + function Session(_ref) { + var mode = _ref.mode, + connectionProvider = _ref.connectionProvider, + bookmark = _ref.bookmark, + database = _ref.database, + config = _ref.config, + reactive = _ref.reactive, + fetchSize = _ref.fetchSize; + (0, _classCallCheck2["default"])(this, Session); + this._mode = mode; + this._database = database; + this._reactive = reactive; + this._fetchSize = fetchSize; + this._readConnectionHolder = new _connectionHolder["default"]({ + mode: constants.ACCESS_MODE_READ, + database: database, + bookmark: bookmark, + connectionProvider: connectionProvider + }); + this._writeConnectionHolder = new _connectionHolder["default"]({ + mode: constants.ACCESS_MODE_WRITE, + database: database, + bookmark: bookmark, + connectionProvider: connectionProvider + }); + this._open = true; + this._hasTx = false; + this._lastBookmark = bookmark; + this._transactionExecutor = _createTransactionExecutor(config); + this._onComplete = this._onCompleteCallback.bind(this); + } + /** + * Run Cypher query + * Could be called with a query object i.e.: `{text: "MATCH ...", prameters: {param: 1}}` + * or with the query and parameters as separate arguments. + * + * @public + * @param {mixed} query - Cypher query to execute + * @param {Object} parameters - Map with parameters to use in query + * @param {TransactionConfig} [transactionConfig] - Configuration for the new auto-commit transaction. + * @return {Result} New Result. + */ + + + (0, _createClass2["default"])(Session, [{ + key: "run", + value: function run(query, parameters, transactionConfig) { + var _this = this; + + var _validateQueryAndPara = (0, util.validateQueryAndParameters)(query, parameters), + validatedQuery = _validateQueryAndPara.validatedQuery, + params = _validateQueryAndPara.params; + + var autoCommitTxConfig = transactionConfig ? new _txConfig["default"](transactionConfig) : _txConfig["default"].empty(); + return this._run(validatedQuery, params, function (connection) { + _this._assertSessionIsOpen(); + + return connection.protocol().run(validatedQuery, params, { + bookmark: _this._lastBookmark, + txConfig: autoCommitTxConfig, + mode: _this._mode, + database: _this._database, + afterComplete: _this._onComplete, + reactive: _this._reactive, + fetchSize: _this._fetchSize + }); + }); + } + }, { + key: "_run", + value: function _run(query, parameters, customRunner) { + var connectionHolder = this._connectionHolderWithMode(this._mode); + + var observerPromise; + + if (!this._open) { + observerPromise = Promise.resolve(new streamObservers.FailedObserver({ + error: (0, error.newError)('Cannot run query in a closed session.') + })); + } else if (!this._hasTx && connectionHolder.initializeConnection()) { + observerPromise = connectionHolder.getConnection().then(function (connection) { + return customRunner(connection); + })["catch"](function (error) { + return Promise.resolve(new streamObservers.FailedObserver({ + error: error + })); + }); + } else { + observerPromise = Promise.resolve(new streamObservers.FailedObserver({ + error: (0, error.newError)('Queries cannot be run directly on a ' + 'session with an open transaction; either run from within the ' + 'transaction or use a different session.') + })); + } + + return new _result["default"](observerPromise, query, parameters, connectionHolder); + } + /** + * Begin a new transaction in this session. A session can have at most one transaction running at a time, if you + * want to run multiple concurrent transactions, you should use multiple concurrent sessions. + * + * While a transaction is open the session cannot be used to run queries outside the transaction. + * + * @param {TransactionConfig} [transactionConfig] - Configuration for the new auto-commit transaction. + * @returns {Transaction} New Transaction. + */ + + }, { + key: "beginTransaction", + value: function beginTransaction(transactionConfig) { + // this function needs to support bookmarks parameter for backwards compatibility + // parameter was of type {string|string[]} and represented either a single or multiple bookmarks + // that's why we need to check parameter type and decide how to interpret the value + var arg = transactionConfig; + + var txConfig = _txConfig["default"].empty(); + + if (arg) { + txConfig = new _txConfig["default"](arg); + } + + return this._beginTransaction(this._mode, txConfig); + } + }, { + key: "_beginTransaction", + value: function _beginTransaction(accessMode, txConfig) { + if (!this._open) { + throw (0, error.newError)('Cannot begin a transaction on a closed session.'); + } + + if (this._hasTx) { + throw (0, error.newError)('You cannot begin a transaction on a session with an open transaction; ' + 'either run from within the transaction or use a different session.'); + } + + var mode = _driver["default"]._validateSessionMode(accessMode); + + var connectionHolder = this._connectionHolderWithMode(mode); + + connectionHolder.initializeConnection(); + this._hasTx = true; + var tx = new _transaction["default"]({ + connectionHolder: connectionHolder, + onClose: this._transactionClosed.bind(this), + onBookmark: this._updateBookmark.bind(this), + onConnection: this._assertSessionIsOpen.bind(this), + reactive: this._reactive, + fetchSize: this._fetchSize + }); + + tx._begin(this._lastBookmark, txConfig); + + return tx; + } + }, { + key: "_assertSessionIsOpen", + value: function _assertSessionIsOpen() { + if (!this._open) { + throw (0, error.newError)('You cannot run more transactions on a closed session.'); + } + } + }, { + key: "_transactionClosed", + value: function _transactionClosed() { + this._hasTx = false; + } + /** + * Return the bookmark received following the last completed {@link Transaction}. + * + * @return {string[]} A reference to a previous transaction. + */ + + }, { + key: "lastBookmark", + value: function lastBookmark() { + return this._lastBookmark.values(); + } + /** + * Execute given unit of work in a {@link READ} transaction. + * + * Transaction will automatically be committed unless the given function throws or returns a rejected promise. + * Some failures of the given function or the commit itself will be retried with exponential backoff with initial + * delay of 1 second and maximum retry time of 30 seconds. Maximum retry time is configurable via driver config's + * `maxTransactionRetryTime` property in milliseconds. + * + * @param {function(tx: Transaction): Promise} transactionWork - Callback that executes operations against + * a given {@link Transaction}. + * @param {TransactionConfig} [transactionConfig] - Configuration for all transactions started to execute the unit of work. + * @return {Promise} Resolved promise as returned by the given function or rejected promise when given + * function or commit fails. + */ + + }, { + key: "readTransaction", + value: function readTransaction(transactionWork, transactionConfig) { + var config = new _txConfig["default"](transactionConfig); + return this._runTransaction(constants.ACCESS_MODE_READ, config, transactionWork); + } + /** + * Execute given unit of work in a {@link WRITE} transaction. + * + * Transaction will automatically be committed unless the given function throws or returns a rejected promise. + * Some failures of the given function or the commit itself will be retried with exponential backoff with initial + * delay of 1 second and maximum retry time of 30 seconds. Maximum retry time is configurable via driver config's + * `maxTransactionRetryTime` property in milliseconds. + * + * @param {function(tx: Transaction): Promise} transactionWork - Callback that executes operations against + * a given {@link Transaction}. + * @param {TransactionConfig} [transactionConfig] - Configuration for all transactions started to execute the unit of work. + * @return {Promise} Resolved promise as returned by the given function or rejected promise when given + * function or commit fails. + */ + + }, { + key: "writeTransaction", + value: function writeTransaction(transactionWork, transactionConfig) { + var config = new _txConfig["default"](transactionConfig); + return this._runTransaction(constants.ACCESS_MODE_WRITE, config, transactionWork); + } + }, { + key: "_runTransaction", + value: function _runTransaction(accessMode, transactionConfig, transactionWork) { + var _this2 = this; + + return this._transactionExecutor.execute(function () { + return _this2._beginTransaction(accessMode, transactionConfig); + }, transactionWork); + } + /** + * Update value of the last bookmark. + * @param {Bookmark} newBookmark - The new bookmark. + */ + + }, { + key: "_updateBookmark", + value: function _updateBookmark(newBookmark) { + if (newBookmark && !newBookmark.isEmpty()) { + this._lastBookmark = newBookmark; + } + } + /** + * Close this session. + * @return {Promise} + */ + + }, { + key: "close", + value: function () { + var _close = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee() { + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + if (!this._open) { + _context.next = 7; + break; + } + + this._open = false; + + this._transactionExecutor.close(); + + _context.next = 5; + return this._readConnectionHolder.close(); + + case 5: + _context.next = 7; + return this._writeConnectionHolder.close(); + + case 7: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function close() { + return _close.apply(this, arguments); + } + + return close; + }() + }, { + key: "_connectionHolderWithMode", + value: function _connectionHolderWithMode(mode) { + if (mode === constants.ACCESS_MODE_READ) { + return this._readConnectionHolder; + } else if (mode === constants.ACCESS_MODE_WRITE) { + return this._writeConnectionHolder; + } else { + throw (0, error.newError)('Unknown access mode: ' + mode); + } + } + }, { + key: "_onCompleteCallback", + value: function _onCompleteCallback(meta) { + this._updateBookmark(new _bookmark["default"](meta.bookmark)); + } + }]); + return Session; +}(); + +function _createTransactionExecutor(config) { + var maxRetryTimeMs = config && config.maxTransactionRetryTime ? config.maxTransactionRetryTime : null; + return new _transactionExecutor["default"](maxRetryTimeMs); +} + +var _default = Session; +exports["default"] = _default; +}); + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function isFunction$1(x) { + return typeof x === 'function'; +} + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var _enable_super_gross_mode_that_will_cause_bad_things = false; +var config = { + Promise: undefined, + set useDeprecatedSynchronousErrorHandling(value) { + if (value) { + var error = /*@__PURE__*/ new Error(); + /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); + } + _enable_super_gross_mode_that_will_cause_bad_things = value; + }, + get useDeprecatedSynchronousErrorHandling() { + return _enable_super_gross_mode_that_will_cause_bad_things; + }, +}; + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function hostReportError(err) { + setTimeout(function () { throw err; }, 0); +} + +/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ +var empty = { + closed: true, + next: function (value) { }, + error: function (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + hostReportError(err); + } + }, + complete: function () { } +}; + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var isArray$1 = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function isObject$1(x) { + return x !== null && typeof x === 'object'; +} + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { + function UnsubscriptionErrorImpl(errors) { + Error.call(this); + this.message = errors ? + errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; + this.name = 'UnsubscriptionError'; + this.errors = errors; + return this; + } + UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return UnsubscriptionErrorImpl; +})(); +var UnsubscriptionError = UnsubscriptionErrorImpl; + +/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ +var Subscription = /*@__PURE__*/ (function () { + function Subscription(unsubscribe) { + this.closed = false; + this._parentOrParents = null; + this._subscriptions = null; + if (unsubscribe) { + this._ctorUnsubscribe = true; + this._unsubscribe = unsubscribe; + } + } + Subscription.prototype.unsubscribe = function () { + var errors; + if (this.closed) { + return; + } + var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; + this.closed = true; + this._parentOrParents = null; + this._subscriptions = null; + if (_parentOrParents instanceof Subscription) { + _parentOrParents.remove(this); + } + else if (_parentOrParents !== null) { + for (var index = 0; index < _parentOrParents.length; ++index) { + var parent_1 = _parentOrParents[index]; + parent_1.remove(this); + } + } + if (isFunction$1(_unsubscribe)) { + if (_ctorUnsubscribe) { + this._unsubscribe = undefined; + } + try { + _unsubscribe.call(this); + } + catch (e) { + errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; + } + } + if (isArray$1(_subscriptions)) { + var index = -1; + var len = _subscriptions.length; + while (++index < len) { + var sub = _subscriptions[index]; + if (isObject$1(sub)) { + try { + sub.unsubscribe(); + } + catch (e) { + errors = errors || []; + if (e instanceof UnsubscriptionError) { + errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); + } + else { + errors.push(e); + } + } + } + } + } + if (errors) { + throw new UnsubscriptionError(errors); + } + }; + Subscription.prototype.add = function (teardown) { + var subscription = teardown; + if (!teardown) { + return Subscription.EMPTY; + } + switch (typeof teardown) { + case 'function': + subscription = new Subscription(teardown); + case 'object': + if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { + return subscription; + } + else if (this.closed) { + subscription.unsubscribe(); + return subscription; + } + else if (!(subscription instanceof Subscription)) { + var tmp = subscription; + subscription = new Subscription(); + subscription._subscriptions = [tmp]; + } + break; + default: { + throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); + } + } + var _parentOrParents = subscription._parentOrParents; + if (_parentOrParents === null) { + subscription._parentOrParents = this; + } + else if (_parentOrParents instanceof Subscription) { + if (_parentOrParents === this) { + return subscription; + } + subscription._parentOrParents = [_parentOrParents, this]; + } + else if (_parentOrParents.indexOf(this) === -1) { + _parentOrParents.push(this); + } + else { + return subscription; + } + var subscriptions = this._subscriptions; + if (subscriptions === null) { + this._subscriptions = [subscription]; + } + else { + subscriptions.push(subscription); + } + return subscription; + }; + Subscription.prototype.remove = function (subscription) { + var subscriptions = this._subscriptions; + if (subscriptions) { + var subscriptionIndex = subscriptions.indexOf(subscription); + if (subscriptionIndex !== -1) { + subscriptions.splice(subscriptionIndex, 1); + } + } + }; + Subscription.EMPTY = (function (empty) { + empty.closed = true; + return empty; + }(new Subscription())); + return Subscription; +}()); +function flattenUnsubscriptionErrors(errors) { + return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []); +} + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var rxSubscriber = /*@__PURE__*/ (function () { + return typeof Symbol === 'function' + ? /*@__PURE__*/ Symbol('rxSubscriber') + : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); +})(); + +/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ +var Subscriber = /*@__PURE__*/ (function (_super) { + __extends(Subscriber, _super); + function Subscriber(destinationOrNext, error, complete) { + var _this = _super.call(this) || this; + _this.syncErrorValue = null; + _this.syncErrorThrown = false; + _this.syncErrorThrowable = false; + _this.isStopped = false; + switch (arguments.length) { + case 0: + _this.destination = empty; + break; + case 1: + if (!destinationOrNext) { + _this.destination = empty; + break; + } + if (typeof destinationOrNext === 'object') { + if (destinationOrNext instanceof Subscriber) { + _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; + _this.destination = destinationOrNext; + destinationOrNext.add(_this); + } + else { + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext); + } + break; + } + default: + _this.syncErrorThrowable = true; + _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); + break; + } + return _this; + } + Subscriber.prototype[rxSubscriber] = function () { return this; }; + Subscriber.create = function (next, error, complete) { + var subscriber = new Subscriber(next, error, complete); + subscriber.syncErrorThrowable = false; + return subscriber; + }; + Subscriber.prototype.next = function (value) { + if (!this.isStopped) { + this._next(value); + } + }; + Subscriber.prototype.error = function (err) { + if (!this.isStopped) { + this.isStopped = true; + this._error(err); + } + }; + Subscriber.prototype.complete = function () { + if (!this.isStopped) { + this.isStopped = true; + this._complete(); + } + }; + Subscriber.prototype.unsubscribe = function () { + if (this.closed) { + return; + } + this.isStopped = true; + _super.prototype.unsubscribe.call(this); + }; + Subscriber.prototype._next = function (value) { + this.destination.next(value); + }; + Subscriber.prototype._error = function (err) { + this.destination.error(err); + this.unsubscribe(); + }; + Subscriber.prototype._complete = function () { + this.destination.complete(); + this.unsubscribe(); + }; + Subscriber.prototype._unsubscribeAndRecycle = function () { + var _parentOrParents = this._parentOrParents; + this._parentOrParents = null; + this.unsubscribe(); + this.closed = false; + this.isStopped = false; + this._parentOrParents = _parentOrParents; + return this; + }; + return Subscriber; +}(Subscription)); +var SafeSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SafeSubscriber, _super); + function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { + var _this = _super.call(this) || this; + _this._parentSubscriber = _parentSubscriber; + var next; + var context = _this; + if (isFunction$1(observerOrNext)) { + next = observerOrNext; + } + else if (observerOrNext) { + next = observerOrNext.next; + error = observerOrNext.error; + complete = observerOrNext.complete; + if (observerOrNext !== empty) { + context = Object.create(observerOrNext); + if (isFunction$1(context.unsubscribe)) { + _this.add(context.unsubscribe.bind(context)); + } + context.unsubscribe = _this.unsubscribe.bind(_this); + } + } + _this._context = context; + _this._next = next; + _this._error = error; + _this._complete = complete; + return _this; + } + SafeSubscriber.prototype.next = function (value) { + if (!this.isStopped && this._next) { + var _parentSubscriber = this._parentSubscriber; + if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._next, value); + } + else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling; + if (this._error) { + if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(this._error, err); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, this._error, err); + this.unsubscribe(); + } + } + else if (!_parentSubscriber.syncErrorThrowable) { + this.unsubscribe(); + if (useDeprecatedSynchronousErrorHandling) { + throw err; + } + hostReportError(err); + } + else { + if (useDeprecatedSynchronousErrorHandling) { + _parentSubscriber.syncErrorValue = err; + _parentSubscriber.syncErrorThrown = true; + } + else { + hostReportError(err); + } + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.complete = function () { + var _this = this; + if (!this.isStopped) { + var _parentSubscriber = this._parentSubscriber; + if (this._complete) { + var wrappedComplete = function () { return _this._complete.call(_this._context); }; + if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { + this.__tryOrUnsub(wrappedComplete); + this.unsubscribe(); + } + else { + this.__tryOrSetError(_parentSubscriber, wrappedComplete); + this.unsubscribe(); + } + } + else { + this.unsubscribe(); + } + } + }; + SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { + try { + fn.call(this._context, value); + } + catch (err) { + this.unsubscribe(); + if (config.useDeprecatedSynchronousErrorHandling) { + throw err; + } + else { + hostReportError(err); + } + } + }; + SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { + if (!config.useDeprecatedSynchronousErrorHandling) { + throw new Error('bad call'); + } + try { + fn.call(this._context, value); + } + catch (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + parent.syncErrorValue = err; + parent.syncErrorThrown = true; + return true; + } + else { + hostReportError(err); + return true; + } + } + return false; + }; + SafeSubscriber.prototype._unsubscribe = function () { + var _parentSubscriber = this._parentSubscriber; + this._context = null; + this._parentSubscriber = null; + _parentSubscriber.unsubscribe(); + }; + return SafeSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ +function canReportError(observer) { + while (observer) { + var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; + if (closed_1 || isStopped) { + return false; + } + else if (destination && destination instanceof Subscriber) { + observer = destination; + } + else { + observer = null; + } + } + return true; +} + +/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ +function toSubscriber(nextOrObserver, error, complete) { + if (nextOrObserver) { + if (nextOrObserver instanceof Subscriber) { + return nextOrObserver; + } + if (nextOrObserver[rxSubscriber]) { + return nextOrObserver[rxSubscriber](); + } + } + if (!nextOrObserver && !error && !complete) { + return new Subscriber(empty); + } + return new Subscriber(nextOrObserver, error, complete); +} + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function identity$1(x) { + return x; +} + +/** PURE_IMPORTS_START _identity PURE_IMPORTS_END */ +function pipe() { + var fns = []; + for (var _i = 0; _i < arguments.length; _i++) { + fns[_i] = arguments[_i]; + } + return pipeFromArray(fns); +} +function pipeFromArray(fns) { + if (fns.length === 0) { + return identity$1; + } + if (fns.length === 1) { + return fns[0]; + } + return function piped(input) { + return fns.reduce(function (prev, fn) { return fn(prev); }, input); + }; +} + +/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ +var Observable = /*@__PURE__*/ (function () { + function Observable(subscribe) { + this._isScalar = false; + if (subscribe) { + this._subscribe = subscribe; + } + } + Observable.prototype.lift = function (operator) { + var observable = new Observable(); + observable.source = this; + observable.operator = operator; + return observable; + }; + Observable.prototype.subscribe = function (observerOrNext, error, complete) { + var operator = this.operator; + var sink = toSubscriber(observerOrNext, error, complete); + if (operator) { + sink.add(operator.call(sink, this.source)); + } + else { + sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? + this._subscribe(sink) : + this._trySubscribe(sink)); + } + if (config.useDeprecatedSynchronousErrorHandling) { + if (sink.syncErrorThrowable) { + sink.syncErrorThrowable = false; + if (sink.syncErrorThrown) { + throw sink.syncErrorValue; + } + } + } + return sink; + }; + Observable.prototype._trySubscribe = function (sink) { + try { + return this._subscribe(sink); + } + catch (err) { + if (config.useDeprecatedSynchronousErrorHandling) { + sink.syncErrorThrown = true; + sink.syncErrorValue = err; + } + if (canReportError(sink)) { + sink.error(err); + } + else { + console.warn(err); + } + } + }; + Observable.prototype.forEach = function (next, promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var subscription; + subscription = _this.subscribe(function (value) { + try { + next(value); + } + catch (err) { + reject(err); + if (subscription) { + subscription.unsubscribe(); + } + } + }, reject, resolve); + }); + }; + Observable.prototype._subscribe = function (subscriber) { + var source = this.source; + return source && source.subscribe(subscriber); + }; + Observable.prototype[observable] = function () { + return this; + }; + Observable.prototype.pipe = function () { + var operations = []; + for (var _i = 0; _i < arguments.length; _i++) { + operations[_i] = arguments[_i]; + } + if (operations.length === 0) { + return this; + } + return pipeFromArray(operations)(this); + }; + Observable.prototype.toPromise = function (promiseCtor) { + var _this = this; + promiseCtor = getPromiseCtor(promiseCtor); + return new promiseCtor(function (resolve, reject) { + var value; + _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); + }); + }; + Observable.create = function (subscribe) { + return new Observable(subscribe); + }; + return Observable; +}()); +function getPromiseCtor(promiseCtor) { + if (!promiseCtor) { + promiseCtor = config.Promise || Promise; + } + if (!promiseCtor) { + throw new Error('no Promise impl found'); + } + return promiseCtor; +} + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () { + function ObjectUnsubscribedErrorImpl() { + Error.call(this); + this.message = 'object unsubscribed'; + this.name = 'ObjectUnsubscribedError'; + return this; + } + ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return ObjectUnsubscribedErrorImpl; +})(); +var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl; + +/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ +var SubjectSubscription = /*@__PURE__*/ (function (_super) { + __extends(SubjectSubscription, _super); + function SubjectSubscription(subject, subscriber) { + var _this = _super.call(this) || this; + _this.subject = subject; + _this.subscriber = subscriber; + _this.closed = false; + return _this; + } + SubjectSubscription.prototype.unsubscribe = function () { + if (this.closed) { + return; + } + this.closed = true; + var subject = this.subject; + var observers = subject.observers; + this.subject = null; + if (!observers || observers.length === 0 || subject.isStopped || subject.closed) { + return; + } + var subscriberIndex = observers.indexOf(this.subscriber); + if (subscriberIndex !== -1) { + observers.splice(subscriberIndex, 1); + } + }; + return SubjectSubscription; +}(Subscription)); + +/** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ +var SubjectSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SubjectSubscriber, _super); + function SubjectSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + return _this; + } + return SubjectSubscriber; +}(Subscriber)); +var Subject = /*@__PURE__*/ (function (_super) { + __extends(Subject, _super); + function Subject() { + var _this = _super.call(this) || this; + _this.observers = []; + _this.closed = false; + _this.isStopped = false; + _this.hasError = false; + _this.thrownError = null; + return _this; + } + Subject.prototype[rxSubscriber] = function () { + return new SubjectSubscriber(this); + }; + Subject.prototype.lift = function (operator) { + var subject = new AnonymousSubject(this, this); + subject.operator = operator; + return subject; + }; + Subject.prototype.next = function (value) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + if (!this.isStopped) { + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].next(value); + } + } + }; + Subject.prototype.error = function (err) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + this.hasError = true; + this.thrownError = err; + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].error(err); + } + this.observers.length = 0; + }; + Subject.prototype.complete = function () { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + this.isStopped = true; + var observers = this.observers; + var len = observers.length; + var copy = observers.slice(); + for (var i = 0; i < len; i++) { + copy[i].complete(); + } + this.observers.length = 0; + }; + Subject.prototype.unsubscribe = function () { + this.isStopped = true; + this.closed = true; + this.observers = null; + }; + Subject.prototype._trySubscribe = function (subscriber) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + else { + return _super.prototype._trySubscribe.call(this, subscriber); + } + }; + Subject.prototype._subscribe = function (subscriber) { + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + else if (this.hasError) { + subscriber.error(this.thrownError); + return Subscription.EMPTY; + } + else if (this.isStopped) { + subscriber.complete(); + return Subscription.EMPTY; + } + else { + this.observers.push(subscriber); + return new SubjectSubscription(this, subscriber); + } + }; + Subject.prototype.asObservable = function () { + var observable = new Observable(); + observable.source = this; + return observable; + }; + Subject.create = function (destination, source) { + return new AnonymousSubject(destination, source); + }; + return Subject; +}(Observable)); +var AnonymousSubject = /*@__PURE__*/ (function (_super) { + __extends(AnonymousSubject, _super); + function AnonymousSubject(destination, source) { + var _this = _super.call(this) || this; + _this.destination = destination; + _this.source = source; + return _this; + } + AnonymousSubject.prototype.next = function (value) { + var destination = this.destination; + if (destination && destination.next) { + destination.next(value); + } + }; + AnonymousSubject.prototype.error = function (err) { + var destination = this.destination; + if (destination && destination.error) { + this.destination.error(err); + } + }; + AnonymousSubject.prototype.complete = function () { + var destination = this.destination; + if (destination && destination.complete) { + this.destination.complete(); + } + }; + AnonymousSubject.prototype._subscribe = function (subscriber) { + var source = this.source; + if (source) { + return this.source.subscribe(subscriber); + } + else { + return Subscription.EMPTY; + } + }; + return AnonymousSubject; +}(Subject)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function refCount() { + return function refCountOperatorFunction(source) { + return source.lift(new RefCountOperator(source)); + }; +} +var RefCountOperator = /*@__PURE__*/ (function () { + function RefCountOperator(connectable) { + this.connectable = connectable; + } + RefCountOperator.prototype.call = function (subscriber, source) { + var connectable = this.connectable; + connectable._refCount++; + var refCounter = new RefCountSubscriber(subscriber, connectable); + var subscription = source.subscribe(refCounter); + if (!refCounter.closed) { + refCounter.connection = connectable.connect(); + } + return subscription; + }; + return RefCountOperator; +}()); +var RefCountSubscriber = /*@__PURE__*/ (function (_super) { + __extends(RefCountSubscriber, _super); + function RefCountSubscriber(destination, connectable) { + var _this = _super.call(this, destination) || this; + _this.connectable = connectable; + return _this; + } + RefCountSubscriber.prototype._unsubscribe = function () { + var connectable = this.connectable; + if (!connectable) { + this.connection = null; + return; + } + this.connectable = null; + var refCount = connectable._refCount; + if (refCount <= 0) { + this.connection = null; + return; + } + connectable._refCount = refCount - 1; + if (refCount > 1) { + this.connection = null; + return; + } + var connection = this.connection; + var sharedConnection = connectable._connection; + this.connection = null; + if (sharedConnection && (!connection || sharedConnection === connection)) { + sharedConnection.unsubscribe(); + } + }; + return RefCountSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subject,_Observable,_Subscriber,_Subscription,_operators_refCount PURE_IMPORTS_END */ +var ConnectableObservable = /*@__PURE__*/ (function (_super) { + __extends(ConnectableObservable, _super); + function ConnectableObservable(source, subjectFactory) { + var _this = _super.call(this) || this; + _this.source = source; + _this.subjectFactory = subjectFactory; + _this._refCount = 0; + _this._isComplete = false; + return _this; + } + ConnectableObservable.prototype._subscribe = function (subscriber) { + return this.getSubject().subscribe(subscriber); + }; + ConnectableObservable.prototype.getSubject = function () { + var subject = this._subject; + if (!subject || subject.isStopped) { + this._subject = this.subjectFactory(); + } + return this._subject; + }; + ConnectableObservable.prototype.connect = function () { + var connection = this._connection; + if (!connection) { + this._isComplete = false; + connection = this._connection = new Subscription(); + connection.add(this.source + .subscribe(new ConnectableSubscriber(this.getSubject(), this))); + if (connection.closed) { + this._connection = null; + connection = Subscription.EMPTY; + } + } + return connection; + }; + ConnectableObservable.prototype.refCount = function () { + return refCount()(this); + }; + return ConnectableObservable; +}(Observable)); +var connectableObservableDescriptor = /*@__PURE__*/ (function () { + var connectableProto = ConnectableObservable.prototype; + return { + operator: { value: null }, + _refCount: { value: 0, writable: true }, + _subject: { value: null, writable: true }, + _connection: { value: null, writable: true }, + _subscribe: { value: connectableProto._subscribe }, + _isComplete: { value: connectableProto._isComplete, writable: true }, + getSubject: { value: connectableProto.getSubject }, + connect: { value: connectableProto.connect }, + refCount: { value: connectableProto.refCount } + }; +})(); +var ConnectableSubscriber = /*@__PURE__*/ (function (_super) { + __extends(ConnectableSubscriber, _super); + function ConnectableSubscriber(destination, connectable) { + var _this = _super.call(this, destination) || this; + _this.connectable = connectable; + return _this; + } + ConnectableSubscriber.prototype._error = function (err) { + this._unsubscribe(); + _super.prototype._error.call(this, err); + }; + ConnectableSubscriber.prototype._complete = function () { + this.connectable._isComplete = true; + this._unsubscribe(); + _super.prototype._complete.call(this); + }; + ConnectableSubscriber.prototype._unsubscribe = function () { + var connectable = this.connectable; + if (connectable) { + this.connectable = null; + var connection = connectable._connection; + connectable._refCount = 0; + connectable._subject = null; + connectable._connection = null; + if (connection) { + connection.unsubscribe(); + } + } + }; + return ConnectableSubscriber; +}(SubjectSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber,_Subscription,_Observable,_Subject PURE_IMPORTS_END */ +function groupBy(keySelector, elementSelector, durationSelector, subjectSelector) { + return function (source) { + return source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector)); + }; +} +var GroupByOperator = /*@__PURE__*/ (function () { + function GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector) { + this.keySelector = keySelector; + this.elementSelector = elementSelector; + this.durationSelector = durationSelector; + this.subjectSelector = subjectSelector; + } + GroupByOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector)); + }; + return GroupByOperator; +}()); +var GroupBySubscriber = /*@__PURE__*/ (function (_super) { + __extends(GroupBySubscriber, _super); + function GroupBySubscriber(destination, keySelector, elementSelector, durationSelector, subjectSelector) { + var _this = _super.call(this, destination) || this; + _this.keySelector = keySelector; + _this.elementSelector = elementSelector; + _this.durationSelector = durationSelector; + _this.subjectSelector = subjectSelector; + _this.groups = null; + _this.attemptedToUnsubscribe = false; + _this.count = 0; + return _this; + } + GroupBySubscriber.prototype._next = function (value) { + var key; + try { + key = this.keySelector(value); + } + catch (err) { + this.error(err); + return; + } + this._group(value, key); + }; + GroupBySubscriber.prototype._group = function (value, key) { + var groups = this.groups; + if (!groups) { + groups = this.groups = new Map(); + } + var group = groups.get(key); + var element; + if (this.elementSelector) { + try { + element = this.elementSelector(value); + } + catch (err) { + this.error(err); + } + } + else { + element = value; + } + if (!group) { + group = (this.subjectSelector ? this.subjectSelector() : new Subject()); + groups.set(key, group); + var groupedObservable = new GroupedObservable(key, group, this); + this.destination.next(groupedObservable); + if (this.durationSelector) { + var duration = void 0; + try { + duration = this.durationSelector(new GroupedObservable(key, group)); + } + catch (err) { + this.error(err); + return; + } + this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this))); + } + } + if (!group.closed) { + group.next(element); + } + }; + GroupBySubscriber.prototype._error = function (err) { + var groups = this.groups; + if (groups) { + groups.forEach(function (group, key) { + group.error(err); + }); + groups.clear(); + } + this.destination.error(err); + }; + GroupBySubscriber.prototype._complete = function () { + var groups = this.groups; + if (groups) { + groups.forEach(function (group, key) { + group.complete(); + }); + groups.clear(); + } + this.destination.complete(); + }; + GroupBySubscriber.prototype.removeGroup = function (key) { + this.groups.delete(key); + }; + GroupBySubscriber.prototype.unsubscribe = function () { + if (!this.closed) { + this.attemptedToUnsubscribe = true; + if (this.count === 0) { + _super.prototype.unsubscribe.call(this); + } + } + }; + return GroupBySubscriber; +}(Subscriber)); +var GroupDurationSubscriber = /*@__PURE__*/ (function (_super) { + __extends(GroupDurationSubscriber, _super); + function GroupDurationSubscriber(key, group, parent) { + var _this = _super.call(this, group) || this; + _this.key = key; + _this.group = group; + _this.parent = parent; + return _this; + } + GroupDurationSubscriber.prototype._next = function (value) { + this.complete(); + }; + GroupDurationSubscriber.prototype._unsubscribe = function () { + var _a = this, parent = _a.parent, key = _a.key; + this.key = this.parent = null; + if (parent) { + parent.removeGroup(key); + } + }; + return GroupDurationSubscriber; +}(Subscriber)); +var GroupedObservable = /*@__PURE__*/ (function (_super) { + __extends(GroupedObservable, _super); + function GroupedObservable(key, groupSubject, refCountSubscription) { + var _this = _super.call(this) || this; + _this.key = key; + _this.groupSubject = groupSubject; + _this.refCountSubscription = refCountSubscription; + return _this; + } + GroupedObservable.prototype._subscribe = function (subscriber) { + var subscription = new Subscription(); + var _a = this, refCountSubscription = _a.refCountSubscription, groupSubject = _a.groupSubject; + if (refCountSubscription && !refCountSubscription.closed) { + subscription.add(new InnerRefCountSubscription(refCountSubscription)); + } + subscription.add(groupSubject.subscribe(subscriber)); + return subscription; + }; + return GroupedObservable; +}(Observable)); +var InnerRefCountSubscription = /*@__PURE__*/ (function (_super) { + __extends(InnerRefCountSubscription, _super); + function InnerRefCountSubscription(parent) { + var _this = _super.call(this) || this; + _this.parent = parent; + parent.count++; + return _this; + } + InnerRefCountSubscription.prototype.unsubscribe = function () { + var parent = this.parent; + if (!parent.closed && !this.closed) { + _super.prototype.unsubscribe.call(this); + parent.count -= 1; + if (parent.count === 0 && parent.attemptedToUnsubscribe) { + parent.unsubscribe(); + } + } + }; + return InnerRefCountSubscription; +}(Subscription)); + +/** PURE_IMPORTS_START tslib,_Subject,_util_ObjectUnsubscribedError PURE_IMPORTS_END */ +var BehaviorSubject = /*@__PURE__*/ (function (_super) { + __extends(BehaviorSubject, _super); + function BehaviorSubject(_value) { + var _this = _super.call(this) || this; + _this._value = _value; + return _this; + } + Object.defineProperty(BehaviorSubject.prototype, "value", { + get: function () { + return this.getValue(); + }, + enumerable: true, + configurable: true + }); + BehaviorSubject.prototype._subscribe = function (subscriber) { + var subscription = _super.prototype._subscribe.call(this, subscriber); + if (subscription && !subscription.closed) { + subscriber.next(this._value); + } + return subscription; + }; + BehaviorSubject.prototype.getValue = function () { + if (this.hasError) { + throw this.thrownError; + } + else if (this.closed) { + throw new ObjectUnsubscribedError(); + } + else { + return this._value; + } + }; + BehaviorSubject.prototype.next = function (value) { + _super.prototype.next.call(this, this._value = value); + }; + return BehaviorSubject; +}(Subject)); + +/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ +var Action = /*@__PURE__*/ (function (_super) { + __extends(Action, _super); + function Action(scheduler, work) { + return _super.call(this) || this; + } + Action.prototype.schedule = function (state, delay) { + return this; + }; + return Action; +}(Subscription)); + +/** PURE_IMPORTS_START tslib,_Action PURE_IMPORTS_END */ +var AsyncAction = /*@__PURE__*/ (function (_super) { + __extends(AsyncAction, _super); + function AsyncAction(scheduler, work) { + var _this = _super.call(this, scheduler, work) || this; + _this.scheduler = scheduler; + _this.work = work; + _this.pending = false; + return _this; + } + AsyncAction.prototype.schedule = function (state, delay) { + if (delay === void 0) { + delay = 0; + } + if (this.closed) { + return this; + } + this.state = state; + var id = this.id; + var scheduler = this.scheduler; + if (id != null) { + this.id = this.recycleAsyncId(scheduler, id, delay); + } + this.pending = true; + this.delay = delay; + this.id = this.id || this.requestAsyncId(scheduler, this.id, delay); + return this; + }; + AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + return setInterval(scheduler.flush.bind(scheduler, this), delay); + }; + AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + if (delay !== null && this.delay === delay && this.pending === false) { + return id; + } + clearInterval(id); + return undefined; + }; + AsyncAction.prototype.execute = function (state, delay) { + if (this.closed) { + return new Error('executing a cancelled action'); + } + this.pending = false; + var error = this._execute(state, delay); + if (error) { + return error; + } + else if (this.pending === false && this.id != null) { + this.id = this.recycleAsyncId(this.scheduler, this.id, null); + } + }; + AsyncAction.prototype._execute = function (state, delay) { + var errored = false; + var errorValue = undefined; + try { + this.work(state); + } + catch (e) { + errored = true; + errorValue = !!e && e || new Error(e); + } + if (errored) { + this.unsubscribe(); + return errorValue; + } + }; + AsyncAction.prototype._unsubscribe = function () { + var id = this.id; + var scheduler = this.scheduler; + var actions = scheduler.actions; + var index = actions.indexOf(this); + this.work = null; + this.state = null; + this.pending = false; + this.scheduler = null; + if (index !== -1) { + actions.splice(index, 1); + } + if (id != null) { + this.id = this.recycleAsyncId(scheduler, id, null); + } + this.delay = null; + }; + return AsyncAction; +}(Action)); + +/** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */ +var QueueAction = /*@__PURE__*/ (function (_super) { + __extends(QueueAction, _super); + function QueueAction(scheduler, work) { + var _this = _super.call(this, scheduler, work) || this; + _this.scheduler = scheduler; + _this.work = work; + return _this; + } + QueueAction.prototype.schedule = function (state, delay) { + if (delay === void 0) { + delay = 0; + } + if (delay > 0) { + return _super.prototype.schedule.call(this, state, delay); + } + this.delay = delay; + this.state = state; + this.scheduler.flush(this); + return this; + }; + QueueAction.prototype.execute = function (state, delay) { + return (delay > 0 || this.closed) ? + _super.prototype.execute.call(this, state, delay) : + this._execute(state, delay); + }; + QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { + return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); + } + return scheduler.flush(this); + }; + return QueueAction; +}(AsyncAction)); + +var Scheduler = /*@__PURE__*/ (function () { + function Scheduler(SchedulerAction, now) { + if (now === void 0) { + now = Scheduler.now; + } + this.SchedulerAction = SchedulerAction; + this.now = now; + } + Scheduler.prototype.schedule = function (work, delay, state) { + if (delay === void 0) { + delay = 0; + } + return new this.SchedulerAction(this, work).schedule(state, delay); + }; + Scheduler.now = function () { return Date.now(); }; + return Scheduler; +}()); + +/** PURE_IMPORTS_START tslib,_Scheduler PURE_IMPORTS_END */ +var AsyncScheduler = /*@__PURE__*/ (function (_super) { + __extends(AsyncScheduler, _super); + function AsyncScheduler(SchedulerAction, now) { + if (now === void 0) { + now = Scheduler.now; + } + var _this = _super.call(this, SchedulerAction, function () { + if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) { + return AsyncScheduler.delegate.now(); + } + else { + return now(); + } + }) || this; + _this.actions = []; + _this.active = false; + _this.scheduled = undefined; + return _this; + } + AsyncScheduler.prototype.schedule = function (work, delay, state) { + if (delay === void 0) { + delay = 0; + } + if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) { + return AsyncScheduler.delegate.schedule(work, delay, state); + } + else { + return _super.prototype.schedule.call(this, work, delay, state); + } + }; + AsyncScheduler.prototype.flush = function (action) { + var actions = this.actions; + if (this.active) { + actions.push(action); + return; + } + var error; + this.active = true; + do { + if (error = action.execute(action.state, action.delay)) { + break; + } + } while (action = actions.shift()); + this.active = false; + if (error) { + while (action = actions.shift()) { + action.unsubscribe(); + } + throw error; + } + }; + return AsyncScheduler; +}(Scheduler)); + +/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ +var QueueScheduler = /*@__PURE__*/ (function (_super) { + __extends(QueueScheduler, _super); + function QueueScheduler() { + return _super !== null && _super.apply(this, arguments) || this; + } + return QueueScheduler; +}(AsyncScheduler)); + +/** PURE_IMPORTS_START _QueueAction,_QueueScheduler PURE_IMPORTS_END */ +var queueScheduler = /*@__PURE__*/ new QueueScheduler(QueueAction); +var queue = queueScheduler; + +/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ +var EMPTY = /*@__PURE__*/ new Observable(function (subscriber) { return subscriber.complete(); }); +function empty$1(scheduler) { + return scheduler ? emptyScheduled(scheduler) : EMPTY; +} +function emptyScheduled(scheduler) { + return new Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); }); +} + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function isScheduler(value) { + return value && typeof value.schedule === 'function'; +} + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var subscribeToArray = function (array) { + return function (subscriber) { + for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) { + subscriber.next(array[i]); + } + subscriber.complete(); + }; +}; + +/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ +function scheduleArray(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + var i = 0; + sub.add(scheduler.schedule(function () { + if (i === input.length) { + subscriber.complete(); + return; + } + subscriber.next(input[i++]); + if (!subscriber.closed) { + sub.add(this.schedule()); + } + })); + return sub; + }); +} + +/** PURE_IMPORTS_START _Observable,_util_subscribeToArray,_scheduled_scheduleArray PURE_IMPORTS_END */ +function fromArray(input, scheduler) { + if (!scheduler) { + return new Observable(subscribeToArray(input)); + } + else { + return scheduleArray(input, scheduler); + } +} + +/** PURE_IMPORTS_START _util_isScheduler,_fromArray,_scheduled_scheduleArray PURE_IMPORTS_END */ +function of() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var scheduler = args[args.length - 1]; + if (isScheduler(scheduler)) { + args.pop(); + return scheduleArray(args, scheduler); + } + else { + return fromArray(args); + } +} + +/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ +function throwError(error, scheduler) { + if (!scheduler) { + return new Observable(function (subscriber) { return subscriber.error(error); }); + } + else { + return new Observable(function (subscriber) { return scheduler.schedule(dispatch, 0, { error: error, subscriber: subscriber }); }); + } +} +function dispatch(_a) { + var error = _a.error, subscriber = _a.subscriber; + subscriber.error(error); +} + +/** PURE_IMPORTS_START _observable_empty,_observable_of,_observable_throwError PURE_IMPORTS_END */ +var NotificationKind; +/*@__PURE__*/ (function (NotificationKind) { + NotificationKind["NEXT"] = "N"; + NotificationKind["ERROR"] = "E"; + NotificationKind["COMPLETE"] = "C"; +})(NotificationKind || (NotificationKind = {})); +var Notification = /*@__PURE__*/ (function () { + function Notification(kind, value, error) { + this.kind = kind; + this.value = value; + this.error = error; + this.hasValue = kind === 'N'; + } + Notification.prototype.observe = function (observer) { + switch (this.kind) { + case 'N': + return observer.next && observer.next(this.value); + case 'E': + return observer.error && observer.error(this.error); + case 'C': + return observer.complete && observer.complete(); + } + }; + Notification.prototype.do = function (next, error, complete) { + var kind = this.kind; + switch (kind) { + case 'N': + return next && next(this.value); + case 'E': + return error && error(this.error); + case 'C': + return complete && complete(); + } + }; + Notification.prototype.accept = function (nextOrObserver, error, complete) { + if (nextOrObserver && typeof nextOrObserver.next === 'function') { + return this.observe(nextOrObserver); + } + else { + return this.do(nextOrObserver, error, complete); + } + }; + Notification.prototype.toObservable = function () { + var kind = this.kind; + switch (kind) { + case 'N': + return of(this.value); + case 'E': + return throwError(this.error); + case 'C': + return empty$1(); + } + throw new Error('unexpected notification kind value'); + }; + Notification.createNext = function (value) { + if (typeof value !== 'undefined') { + return new Notification('N', value); + } + return Notification.undefinedValueNotification; + }; + Notification.createError = function (err) { + return new Notification('E', undefined, err); + }; + Notification.createComplete = function () { + return Notification.completeNotification; + }; + Notification.completeNotification = new Notification('C'); + Notification.undefinedValueNotification = new Notification('N', undefined); + return Notification; +}()); + +/** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */ +function observeOn(scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + return function observeOnOperatorFunction(source) { + return source.lift(new ObserveOnOperator(scheduler, delay)); + }; +} +var ObserveOnOperator = /*@__PURE__*/ (function () { + function ObserveOnOperator(scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + this.scheduler = scheduler; + this.delay = delay; + } + ObserveOnOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay)); + }; + return ObserveOnOperator; +}()); +var ObserveOnSubscriber = /*@__PURE__*/ (function (_super) { + __extends(ObserveOnSubscriber, _super); + function ObserveOnSubscriber(destination, scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + var _this = _super.call(this, destination) || this; + _this.scheduler = scheduler; + _this.delay = delay; + return _this; + } + ObserveOnSubscriber.dispatch = function (arg) { + var notification = arg.notification, destination = arg.destination; + notification.observe(destination); + this.unsubscribe(); + }; + ObserveOnSubscriber.prototype.scheduleMessage = function (notification) { + var destination = this.destination; + destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination))); + }; + ObserveOnSubscriber.prototype._next = function (value) { + this.scheduleMessage(Notification.createNext(value)); + }; + ObserveOnSubscriber.prototype._error = function (err) { + this.scheduleMessage(Notification.createError(err)); + this.unsubscribe(); + }; + ObserveOnSubscriber.prototype._complete = function () { + this.scheduleMessage(Notification.createComplete()); + this.unsubscribe(); + }; + return ObserveOnSubscriber; +}(Subscriber)); +var ObserveOnMessage = /*@__PURE__*/ (function () { + function ObserveOnMessage(notification, destination) { + this.notification = notification; + this.destination = destination; + } + return ObserveOnMessage; +}()); + +/** PURE_IMPORTS_START tslib,_Subject,_scheduler_queue,_Subscription,_operators_observeOn,_util_ObjectUnsubscribedError,_SubjectSubscription PURE_IMPORTS_END */ +var ReplaySubject = /*@__PURE__*/ (function (_super) { + __extends(ReplaySubject, _super); + function ReplaySubject(bufferSize, windowTime, scheduler) { + if (bufferSize === void 0) { + bufferSize = Number.POSITIVE_INFINITY; + } + if (windowTime === void 0) { + windowTime = Number.POSITIVE_INFINITY; + } + var _this = _super.call(this) || this; + _this.scheduler = scheduler; + _this._events = []; + _this._infiniteTimeWindow = false; + _this._bufferSize = bufferSize < 1 ? 1 : bufferSize; + _this._windowTime = windowTime < 1 ? 1 : windowTime; + if (windowTime === Number.POSITIVE_INFINITY) { + _this._infiniteTimeWindow = true; + _this.next = _this.nextInfiniteTimeWindow; + } + else { + _this.next = _this.nextTimeWindow; + } + return _this; + } + ReplaySubject.prototype.nextInfiniteTimeWindow = function (value) { + if (!this.isStopped) { + var _events = this._events; + _events.push(value); + if (_events.length > this._bufferSize) { + _events.shift(); + } + } + _super.prototype.next.call(this, value); + }; + ReplaySubject.prototype.nextTimeWindow = function (value) { + if (!this.isStopped) { + this._events.push(new ReplayEvent(this._getNow(), value)); + this._trimBufferThenGetEvents(); + } + _super.prototype.next.call(this, value); + }; + ReplaySubject.prototype._subscribe = function (subscriber) { + var _infiniteTimeWindow = this._infiniteTimeWindow; + var _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents(); + var scheduler = this.scheduler; + var len = _events.length; + var subscription; + if (this.closed) { + throw new ObjectUnsubscribedError(); + } + else if (this.isStopped || this.hasError) { + subscription = Subscription.EMPTY; + } + else { + this.observers.push(subscriber); + subscription = new SubjectSubscription(this, subscriber); + } + if (scheduler) { + subscriber.add(subscriber = new ObserveOnSubscriber(subscriber, scheduler)); + } + if (_infiniteTimeWindow) { + for (var i = 0; i < len && !subscriber.closed; i++) { + subscriber.next(_events[i]); + } + } + else { + for (var i = 0; i < len && !subscriber.closed; i++) { + subscriber.next(_events[i].value); + } + } + if (this.hasError) { + subscriber.error(this.thrownError); + } + else if (this.isStopped) { + subscriber.complete(); + } + return subscription; + }; + ReplaySubject.prototype._getNow = function () { + return (this.scheduler || queue).now(); + }; + ReplaySubject.prototype._trimBufferThenGetEvents = function () { + var now = this._getNow(); + var _bufferSize = this._bufferSize; + var _windowTime = this._windowTime; + var _events = this._events; + var eventsCount = _events.length; + var spliceCount = 0; + while (spliceCount < eventsCount) { + if ((now - _events[spliceCount].time) < _windowTime) { + break; + } + spliceCount++; + } + if (eventsCount > _bufferSize) { + spliceCount = Math.max(spliceCount, eventsCount - _bufferSize); + } + if (spliceCount > 0) { + _events.splice(0, spliceCount); + } + return _events; + }; + return ReplaySubject; +}(Subject)); +var ReplayEvent = /*@__PURE__*/ (function () { + function ReplayEvent(time, value) { + this.time = time; + this.value = value; + } + return ReplayEvent; +}()); + +/** PURE_IMPORTS_START tslib,_Subject,_Subscription PURE_IMPORTS_END */ +var AsyncSubject = /*@__PURE__*/ (function (_super) { + __extends(AsyncSubject, _super); + function AsyncSubject() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.value = null; + _this.hasNext = false; + _this.hasCompleted = false; + return _this; + } + AsyncSubject.prototype._subscribe = function (subscriber) { + if (this.hasError) { + subscriber.error(this.thrownError); + return Subscription.EMPTY; + } + else if (this.hasCompleted && this.hasNext) { + subscriber.next(this.value); + subscriber.complete(); + return Subscription.EMPTY; + } + return _super.prototype._subscribe.call(this, subscriber); + }; + AsyncSubject.prototype.next = function (value) { + if (!this.hasCompleted) { + this.value = value; + this.hasNext = true; + } + }; + AsyncSubject.prototype.error = function (error) { + if (!this.hasCompleted) { + _super.prototype.error.call(this, error); + } + }; + AsyncSubject.prototype.complete = function () { + this.hasCompleted = true; + if (this.hasNext) { + _super.prototype.next.call(this, this.value); + } + _super.prototype.complete.call(this); + }; + return AsyncSubject; +}(Subject)); + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var nextHandle = 1; +var RESOLVED = /*@__PURE__*/ (function () { return /*@__PURE__*/ Promise.resolve(); })(); +var activeHandles = {}; +function findAndClearHandle(handle) { + if (handle in activeHandles) { + delete activeHandles[handle]; + return true; + } + return false; +} +var Immediate = { + setImmediate: function (cb) { + var handle = nextHandle++; + activeHandles[handle] = true; + RESOLVED.then(function () { return findAndClearHandle(handle) && cb(); }); + return handle; + }, + clearImmediate: function (handle) { + findAndClearHandle(handle); + }, +}; + +/** PURE_IMPORTS_START tslib,_util_Immediate,_AsyncAction PURE_IMPORTS_END */ +var AsapAction = /*@__PURE__*/ (function (_super) { + __extends(AsapAction, _super); + function AsapAction(scheduler, work) { + var _this = _super.call(this, scheduler, work) || this; + _this.scheduler = scheduler; + _this.work = work; + return _this; + } + AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + if (delay !== null && delay > 0) { + return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); + } + scheduler.actions.push(this); + return scheduler.scheduled || (scheduler.scheduled = Immediate.setImmediate(scheduler.flush.bind(scheduler, null))); + }; + AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { + return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay); + } + if (scheduler.actions.length === 0) { + Immediate.clearImmediate(id); + scheduler.scheduled = undefined; + } + return undefined; + }; + return AsapAction; +}(AsyncAction)); + +/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ +var AsapScheduler = /*@__PURE__*/ (function (_super) { + __extends(AsapScheduler, _super); + function AsapScheduler() { + return _super !== null && _super.apply(this, arguments) || this; + } + AsapScheduler.prototype.flush = function (action) { + this.active = true; + this.scheduled = undefined; + var actions = this.actions; + var error; + var index = -1; + var count = actions.length; + action = action || actions.shift(); + do { + if (error = action.execute(action.state, action.delay)) { + break; + } + } while (++index < count && (action = actions.shift())); + this.active = false; + if (error) { + while (++index < count && (action = actions.shift())) { + action.unsubscribe(); + } + throw error; + } + }; + return AsapScheduler; +}(AsyncScheduler)); + +/** PURE_IMPORTS_START _AsapAction,_AsapScheduler PURE_IMPORTS_END */ +var asapScheduler = /*@__PURE__*/ new AsapScheduler(AsapAction); +var asap = asapScheduler; + +/** PURE_IMPORTS_START _AsyncAction,_AsyncScheduler PURE_IMPORTS_END */ +var asyncScheduler = /*@__PURE__*/ new AsyncScheduler(AsyncAction); +var async = asyncScheduler; + +/** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */ +var AnimationFrameAction = /*@__PURE__*/ (function (_super) { + __extends(AnimationFrameAction, _super); + function AnimationFrameAction(scheduler, work) { + var _this = _super.call(this, scheduler, work) || this; + _this.scheduler = scheduler; + _this.work = work; + return _this; + } + AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + if (delay !== null && delay > 0) { + return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); + } + scheduler.actions.push(this); + return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(function () { return scheduler.flush(null); })); + }; + AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { + return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay); + } + if (scheduler.actions.length === 0) { + cancelAnimationFrame(id); + scheduler.scheduled = undefined; + } + return undefined; + }; + return AnimationFrameAction; +}(AsyncAction)); + +/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ +var AnimationFrameScheduler = /*@__PURE__*/ (function (_super) { + __extends(AnimationFrameScheduler, _super); + function AnimationFrameScheduler() { + return _super !== null && _super.apply(this, arguments) || this; + } + AnimationFrameScheduler.prototype.flush = function (action) { + this.active = true; + this.scheduled = undefined; + var actions = this.actions; + var error; + var index = -1; + var count = actions.length; + action = action || actions.shift(); + do { + if (error = action.execute(action.state, action.delay)) { + break; + } + } while (++index < count && (action = actions.shift())); + this.active = false; + if (error) { + while (++index < count && (action = actions.shift())) { + action.unsubscribe(); + } + throw error; + } + }; + return AnimationFrameScheduler; +}(AsyncScheduler)); + +/** PURE_IMPORTS_START _AnimationFrameAction,_AnimationFrameScheduler PURE_IMPORTS_END */ +var animationFrameScheduler = /*@__PURE__*/ new AnimationFrameScheduler(AnimationFrameAction); +var animationFrame = animationFrameScheduler; + +/** PURE_IMPORTS_START tslib,_AsyncAction,_AsyncScheduler PURE_IMPORTS_END */ +var VirtualTimeScheduler = /*@__PURE__*/ (function (_super) { + __extends(VirtualTimeScheduler, _super); + function VirtualTimeScheduler(SchedulerAction, maxFrames) { + if (SchedulerAction === void 0) { + SchedulerAction = VirtualAction; + } + if (maxFrames === void 0) { + maxFrames = Number.POSITIVE_INFINITY; + } + var _this = _super.call(this, SchedulerAction, function () { return _this.frame; }) || this; + _this.maxFrames = maxFrames; + _this.frame = 0; + _this.index = -1; + return _this; + } + VirtualTimeScheduler.prototype.flush = function () { + var _a = this, actions = _a.actions, maxFrames = _a.maxFrames; + var error, action; + while ((action = actions[0]) && action.delay <= maxFrames) { + actions.shift(); + this.frame = action.delay; + if (error = action.execute(action.state, action.delay)) { + break; + } + } + if (error) { + while (action = actions.shift()) { + action.unsubscribe(); + } + throw error; + } + }; + VirtualTimeScheduler.frameTimeFactor = 10; + return VirtualTimeScheduler; +}(AsyncScheduler)); +var VirtualAction = /*@__PURE__*/ (function (_super) { + __extends(VirtualAction, _super); + function VirtualAction(scheduler, work, index) { + if (index === void 0) { + index = scheduler.index += 1; + } + var _this = _super.call(this, scheduler, work) || this; + _this.scheduler = scheduler; + _this.work = work; + _this.index = index; + _this.active = true; + _this.index = scheduler.index = index; + return _this; + } + VirtualAction.prototype.schedule = function (state, delay) { + if (delay === void 0) { + delay = 0; + } + if (!this.id) { + return _super.prototype.schedule.call(this, state, delay); + } + this.active = false; + var action = new VirtualAction(this.scheduler, this.work); + this.add(action); + return action.schedule(state, delay); + }; + VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) { + if (delay === void 0) { + delay = 0; + } + this.delay = scheduler.frame + delay; + var actions = scheduler.actions; + actions.push(this); + actions.sort(VirtualAction.sortActions); + return true; + }; + VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) { + return undefined; + }; + VirtualAction.prototype._execute = function (state, delay) { + if (this.active === true) { + return _super.prototype._execute.call(this, state, delay); + } + }; + VirtualAction.sortActions = function (a, b) { + if (a.delay === b.delay) { + if (a.index === b.index) { + return 0; + } + else if (a.index > b.index) { + return 1; + } + else { + return -1; + } + } + else if (a.delay > b.delay) { + return 1; + } + else { + return -1; + } + }; + return VirtualAction; +}(AsyncAction)); + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function noop() { } + +/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ +function isObservable(obj) { + return !!obj && (obj instanceof Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function')); +} + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var ArgumentOutOfRangeErrorImpl = /*@__PURE__*/ (function () { + function ArgumentOutOfRangeErrorImpl() { + Error.call(this); + this.message = 'argument out of range'; + this.name = 'ArgumentOutOfRangeError'; + return this; + } + ArgumentOutOfRangeErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return ArgumentOutOfRangeErrorImpl; +})(); +var ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl; + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var EmptyErrorImpl = /*@__PURE__*/ (function () { + function EmptyErrorImpl() { + Error.call(this); + this.message = 'no elements in sequence'; + this.name = 'EmptyError'; + return this; + } + EmptyErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return EmptyErrorImpl; +})(); +var EmptyError = EmptyErrorImpl; + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var TimeoutErrorImpl = /*@__PURE__*/ (function () { + function TimeoutErrorImpl() { + Error.call(this); + this.message = 'Timeout has occurred'; + this.name = 'TimeoutError'; + return this; + } + TimeoutErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); + return TimeoutErrorImpl; +})(); +var TimeoutError = TimeoutErrorImpl; + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function map$1(project, thisArg) { + return function mapOperation(source) { + if (typeof project !== 'function') { + throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); + } + return source.lift(new MapOperator(project, thisArg)); + }; +} +var MapOperator = /*@__PURE__*/ (function () { + function MapOperator(project, thisArg) { + this.project = project; + this.thisArg = thisArg; + } + MapOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg)); + }; + return MapOperator; +}()); +var MapSubscriber = /*@__PURE__*/ (function (_super) { + __extends(MapSubscriber, _super); + function MapSubscriber(destination, project, thisArg) { + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.count = 0; + _this.thisArg = thisArg || _this; + return _this; + } + MapSubscriber.prototype._next = function (value) { + var result; + try { + result = this.project.call(this.thisArg, value, this.count++); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return MapSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _Observable,_AsyncSubject,_operators_map,_util_canReportError,_util_isArray,_util_isScheduler PURE_IMPORTS_END */ +function bindCallback(callbackFunc, resultSelector, scheduler) { + if (resultSelector) { + if (isScheduler(resultSelector)) { + scheduler = resultSelector; + } + else { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return bindCallback(callbackFunc, scheduler).apply(void 0, args).pipe(map$1(function (args) { return isArray$1(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); + }; + } + } + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var context = this; + var subject; + var params = { + context: context, + subject: subject, + callbackFunc: callbackFunc, + scheduler: scheduler, + }; + return new Observable(function (subscriber) { + if (!scheduler) { + if (!subject) { + subject = new AsyncSubject(); + var handler = function () { + var innerArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + innerArgs[_i] = arguments[_i]; + } + subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs); + subject.complete(); + }; + try { + callbackFunc.apply(context, args.concat([handler])); + } + catch (err) { + if (canReportError(subject)) { + subject.error(err); + } + else { + console.warn(err); + } + } + } + return subject.subscribe(subscriber); + } + else { + var state = { + args: args, subscriber: subscriber, params: params, + }; + return scheduler.schedule(dispatch$1, 0, state); + } + }); + }; +} +function dispatch$1(state) { + var _this = this; + var args = state.args, subscriber = state.subscriber, params = state.params; + var callbackFunc = params.callbackFunc, context = params.context, scheduler = params.scheduler; + var subject = params.subject; + if (!subject) { + subject = params.subject = new AsyncSubject(); + var handler = function () { + var innerArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + innerArgs[_i] = arguments[_i]; + } + var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs; + _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject })); + }; + try { + callbackFunc.apply(context, args.concat([handler])); + } + catch (err) { + subject.error(err); + } + } + this.add(subject.subscribe(subscriber)); +} +function dispatchNext(state) { + var value = state.value, subject = state.subject; + subject.next(value); + subject.complete(); +} + +/** PURE_IMPORTS_START _Observable,_AsyncSubject,_operators_map,_util_canReportError,_util_isScheduler,_util_isArray PURE_IMPORTS_END */ +function bindNodeCallback(callbackFunc, resultSelector, scheduler) { + if (resultSelector) { + if (isScheduler(resultSelector)) { + scheduler = resultSelector; + } + else { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return bindNodeCallback(callbackFunc, scheduler).apply(void 0, args).pipe(map$1(function (args) { return isArray$1(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); + }; + } + } + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var params = { + subject: undefined, + args: args, + callbackFunc: callbackFunc, + scheduler: scheduler, + context: this, + }; + return new Observable(function (subscriber) { + var context = params.context; + var subject = params.subject; + if (!scheduler) { + if (!subject) { + subject = params.subject = new AsyncSubject(); + var handler = function () { + var innerArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + innerArgs[_i] = arguments[_i]; + } + var err = innerArgs.shift(); + if (err) { + subject.error(err); + return; + } + subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs); + subject.complete(); + }; + try { + callbackFunc.apply(context, args.concat([handler])); + } + catch (err) { + if (canReportError(subject)) { + subject.error(err); + } + else { + console.warn(err); + } + } + } + return subject.subscribe(subscriber); + } + else { + return scheduler.schedule(dispatch$2, 0, { params: params, subscriber: subscriber, context: context }); + } + }); + }; +} +function dispatch$2(state) { + var _this = this; + var params = state.params, subscriber = state.subscriber, context = state.context; + var callbackFunc = params.callbackFunc, args = params.args, scheduler = params.scheduler; + var subject = params.subject; + if (!subject) { + subject = params.subject = new AsyncSubject(); + var handler = function () { + var innerArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + innerArgs[_i] = arguments[_i]; + } + var err = innerArgs.shift(); + if (err) { + _this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject })); + } + else { + var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs; + _this.add(scheduler.schedule(dispatchNext$1, 0, { value: value, subject: subject })); + } + }; + try { + callbackFunc.apply(context, args.concat([handler])); + } + catch (err) { + this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject })); + } + } + this.add(subject.subscribe(subscriber)); +} +function dispatchNext$1(arg) { + var value = arg.value, subject = arg.subject; + subject.next(value); + subject.complete(); +} +function dispatchError(arg) { + var err = arg.err, subject = arg.subject; + subject.error(err); +} + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +var OuterSubscriber = /*@__PURE__*/ (function (_super) { + __extends(OuterSubscriber, _super); + function OuterSubscriber() { + return _super !== null && _super.apply(this, arguments) || this; + } + OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + this.destination.next(innerValue); + }; + OuterSubscriber.prototype.notifyError = function (error, innerSub) { + this.destination.error(error); + }; + OuterSubscriber.prototype.notifyComplete = function (innerSub) { + this.destination.complete(); + }; + return OuterSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +var InnerSubscriber = /*@__PURE__*/ (function (_super) { + __extends(InnerSubscriber, _super); + function InnerSubscriber(parent, outerValue, outerIndex) { + var _this = _super.call(this) || this; + _this.parent = parent; + _this.outerValue = outerValue; + _this.outerIndex = outerIndex; + _this.index = 0; + return _this; + } + InnerSubscriber.prototype._next = function (value) { + this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this); + }; + InnerSubscriber.prototype._error = function (error) { + this.parent.notifyError(error, this); + this.unsubscribe(); + }; + InnerSubscriber.prototype._complete = function () { + this.parent.notifyComplete(this); + this.unsubscribe(); + }; + return InnerSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */ +var subscribeToPromise = function (promise) { + return function (subscriber) { + promise.then(function (value) { + if (!subscriber.closed) { + subscriber.next(value); + subscriber.complete(); + } + }, function (err) { return subscriber.error(err); }) + .then(null, hostReportError); + return subscriber; + }; +}; + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function getSymbolIterator() { + if (typeof Symbol !== 'function' || !Symbol.iterator) { + return '@@iterator'; + } + return Symbol.iterator; +} +var iterator = /*@__PURE__*/ getSymbolIterator(); + +/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ +var subscribeToIterable = function (iterable) { + return function (subscriber) { + var iterator$1 = iterable[iterator](); + do { + var item = void 0; + try { + item = iterator$1.next(); + } + catch (err) { + subscriber.error(err); + return subscriber; + } + if (item.done) { + subscriber.complete(); + break; + } + subscriber.next(item.value); + if (subscriber.closed) { + break; + } + } while (true); + if (typeof iterator$1.return === 'function') { + subscriber.add(function () { + if (iterator$1.return) { + iterator$1.return(); + } + }); + } + return subscriber; + }; +}; + +/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ +var subscribeToObservable = function (obj) { + return function (subscriber) { + var obs = obj[observable](); + if (typeof obs.subscribe !== 'function') { + throw new TypeError('Provided object does not correctly implement Symbol.observable'); + } + else { + return obs.subscribe(subscriber); + } + }; +}; + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +var isArrayLike$1 = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; }); + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function isPromise(value) { + return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function'; +} + +/** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */ +var subscribeTo = function (result) { + if (!!result && typeof result[observable] === 'function') { + return subscribeToObservable(result); + } + else if (isArrayLike$1(result)) { + return subscribeToArray(result); + } + else if (isPromise(result)) { + return subscribeToPromise(result); + } + else if (!!result && typeof result[iterator] === 'function') { + return subscribeToIterable(result); + } + else { + var value = isObject$1(result) ? 'an invalid object' : "'" + result + "'"; + var msg = "You provided " + value + " where a stream was expected." + + ' You can provide an Observable, Promise, Array, or Iterable.'; + throw new TypeError(msg); + } +}; + +/** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo,_Observable PURE_IMPORTS_END */ +function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, innerSubscriber) { + if (innerSubscriber === void 0) { + innerSubscriber = new InnerSubscriber(outerSubscriber, outerValue, outerIndex); + } + if (innerSubscriber.closed) { + return undefined; + } + if (result instanceof Observable) { + return result.subscribe(innerSubscriber); + } + return subscribeTo(result)(innerSubscriber); +} + +/** PURE_IMPORTS_START tslib,_util_isScheduler,_util_isArray,_OuterSubscriber,_util_subscribeToResult,_fromArray PURE_IMPORTS_END */ +var NONE = {}; +function combineLatest() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + var resultSelector = undefined; + var scheduler = undefined; + if (isScheduler(observables[observables.length - 1])) { + scheduler = observables.pop(); + } + if (typeof observables[observables.length - 1] === 'function') { + resultSelector = observables.pop(); + } + if (observables.length === 1 && isArray$1(observables[0])) { + observables = observables[0]; + } + return fromArray(observables, scheduler).lift(new CombineLatestOperator(resultSelector)); +} +var CombineLatestOperator = /*@__PURE__*/ (function () { + function CombineLatestOperator(resultSelector) { + this.resultSelector = resultSelector; + } + CombineLatestOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector)); + }; + return CombineLatestOperator; +}()); +var CombineLatestSubscriber = /*@__PURE__*/ (function (_super) { + __extends(CombineLatestSubscriber, _super); + function CombineLatestSubscriber(destination, resultSelector) { + var _this = _super.call(this, destination) || this; + _this.resultSelector = resultSelector; + _this.active = 0; + _this.values = []; + _this.observables = []; + return _this; + } + CombineLatestSubscriber.prototype._next = function (observable) { + this.values.push(NONE); + this.observables.push(observable); + }; + CombineLatestSubscriber.prototype._complete = function () { + var observables = this.observables; + var len = observables.length; + if (len === 0) { + this.destination.complete(); + } + else { + this.active = len; + this.toRespond = len; + for (var i = 0; i < len; i++) { + var observable = observables[i]; + this.add(subscribeToResult(this, observable, undefined, i)); + } + } + }; + CombineLatestSubscriber.prototype.notifyComplete = function (unused) { + if ((this.active -= 1) === 0) { + this.destination.complete(); + } + }; + CombineLatestSubscriber.prototype.notifyNext = function (_outerValue, innerValue, outerIndex) { + var values = this.values; + var oldVal = values[outerIndex]; + var toRespond = !this.toRespond + ? 0 + : oldVal === NONE ? --this.toRespond : this.toRespond; + values[outerIndex] = innerValue; + if (toRespond === 0) { + if (this.resultSelector) { + this._tryResultSelector(values); + } + else { + this.destination.next(values.slice()); + } + } + }; + CombineLatestSubscriber.prototype._tryResultSelector = function (values) { + var result; + try { + result = this.resultSelector.apply(this, values); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return CombineLatestSubscriber; +}(OuterSubscriber)); + +/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */ +function scheduleObservable(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + sub.add(scheduler.schedule(function () { + var observable$1 = input[observable](); + sub.add(observable$1.subscribe({ + next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, + error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, + complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, + })); + })); + return sub; + }); +} + +/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ +function schedulePromise(input, scheduler) { + return new Observable(function (subscriber) { + var sub = new Subscription(); + sub.add(scheduler.schedule(function () { + return input.then(function (value) { + sub.add(scheduler.schedule(function () { + subscriber.next(value); + sub.add(scheduler.schedule(function () { return subscriber.complete(); })); + })); + }, function (err) { + sub.add(scheduler.schedule(function () { return subscriber.error(err); })); + }); + })); + return sub; + }); +} + +/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */ +function scheduleIterable(input, scheduler) { + if (!input) { + throw new Error('Iterable cannot be null'); + } + return new Observable(function (subscriber) { + var sub = new Subscription(); + var iterator$1; + sub.add(function () { + if (iterator$1 && typeof iterator$1.return === 'function') { + iterator$1.return(); + } + }); + sub.add(scheduler.schedule(function () { + iterator$1 = input[iterator](); + sub.add(scheduler.schedule(function () { + if (subscriber.closed) { + return; + } + var value; + var done; + try { + var result = iterator$1.next(); + value = result.value; + done = result.done; + } + catch (err) { + subscriber.error(err); + return; + } + if (done) { + subscriber.complete(); + } + else { + subscriber.next(value); + this.schedule(); + } + })); + })); + return sub; + }); +} + +/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ +function isInteropObservable(input) { + return input && typeof input[observable] === 'function'; +} + +/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ +function isIterable(input) { + return input && typeof input[iterator] === 'function'; +} + +/** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */ +function scheduled(input, scheduler) { + if (input != null) { + if (isInteropObservable(input)) { + return scheduleObservable(input, scheduler); + } + else if (isPromise(input)) { + return schedulePromise(input, scheduler); + } + else if (isArrayLike$1(input)) { + return scheduleArray(input, scheduler); + } + else if (isIterable(input) || typeof input === 'string') { + return scheduleIterable(input, scheduler); + } + } + throw new TypeError((input !== null && typeof input || input) + ' is not observable'); +} + +/** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */ +function from(input, scheduler) { + if (!scheduler) { + if (input instanceof Observable) { + return input; + } + return new Observable(subscribeTo(input)); + } + else { + return scheduled(input, scheduler); + } +} + +/** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_util_subscribeTo PURE_IMPORTS_END */ +var SimpleInnerSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SimpleInnerSubscriber, _super); + function SimpleInnerSubscriber(parent) { + var _this = _super.call(this) || this; + _this.parent = parent; + return _this; + } + SimpleInnerSubscriber.prototype._next = function (value) { + this.parent.notifyNext(value); + }; + SimpleInnerSubscriber.prototype._error = function (error) { + this.parent.notifyError(error); + this.unsubscribe(); + }; + SimpleInnerSubscriber.prototype._complete = function () { + this.parent.notifyComplete(); + this.unsubscribe(); + }; + return SimpleInnerSubscriber; +}(Subscriber)); +var SimpleOuterSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SimpleOuterSubscriber, _super); + function SimpleOuterSubscriber() { + return _super !== null && _super.apply(this, arguments) || this; + } + SimpleOuterSubscriber.prototype.notifyNext = function (innerValue) { + this.destination.next(innerValue); + }; + SimpleOuterSubscriber.prototype.notifyError = function (err) { + this.destination.error(err); + }; + SimpleOuterSubscriber.prototype.notifyComplete = function () { + this.destination.complete(); + }; + return SimpleOuterSubscriber; +}(Subscriber)); +function innerSubscribe(result, innerSubscriber) { + if (innerSubscriber.closed) { + return undefined; + } + if (result instanceof Observable) { + return result.subscribe(innerSubscriber); + } + var subscription; + try { + subscription = subscribeTo(result)(innerSubscriber); + } + catch (error) { + innerSubscriber.error(error); + } + return subscription; +} + +/** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */ +function mergeMap(project, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + if (typeof resultSelector === 'function') { + return function (source) { return source.pipe(mergeMap(function (a, i) { return from(project(a, i)).pipe(map$1(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); }; + } + else if (typeof resultSelector === 'number') { + concurrent = resultSelector; + } + return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); }; +} +var MergeMapOperator = /*@__PURE__*/ (function () { + function MergeMapOperator(project, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + this.project = project; + this.concurrent = concurrent; + } + MergeMapOperator.prototype.call = function (observer, source) { + return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent)); + }; + return MergeMapOperator; +}()); +var MergeMapSubscriber = /*@__PURE__*/ (function (_super) { + __extends(MergeMapSubscriber, _super); + function MergeMapSubscriber(destination, project, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.concurrent = concurrent; + _this.hasCompleted = false; + _this.buffer = []; + _this.active = 0; + _this.index = 0; + return _this; + } + MergeMapSubscriber.prototype._next = function (value) { + if (this.active < this.concurrent) { + this._tryNext(value); + } + else { + this.buffer.push(value); + } + }; + MergeMapSubscriber.prototype._tryNext = function (value) { + var result; + var index = this.index++; + try { + result = this.project(value, index); + } + catch (err) { + this.destination.error(err); + return; + } + this.active++; + this._innerSub(result); + }; + MergeMapSubscriber.prototype._innerSub = function (ish) { + var innerSubscriber = new SimpleInnerSubscriber(this); + var destination = this.destination; + destination.add(innerSubscriber); + var innerSubscription = innerSubscribe(ish, innerSubscriber); + if (innerSubscription !== innerSubscriber) { + destination.add(innerSubscription); + } + }; + MergeMapSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (this.active === 0 && this.buffer.length === 0) { + this.destination.complete(); + } + this.unsubscribe(); + }; + MergeMapSubscriber.prototype.notifyNext = function (innerValue) { + this.destination.next(innerValue); + }; + MergeMapSubscriber.prototype.notifyComplete = function () { + var buffer = this.buffer; + this.active--; + if (buffer.length > 0) { + this._next(buffer.shift()); + } + else if (this.active === 0 && this.hasCompleted) { + this.destination.complete(); + } + }; + return MergeMapSubscriber; +}(SimpleOuterSubscriber)); +var flatMap$1 = mergeMap; + +/** PURE_IMPORTS_START _mergeMap,_util_identity PURE_IMPORTS_END */ +function mergeAll(concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + return mergeMap(identity$1, concurrent); +} + +/** PURE_IMPORTS_START _mergeAll PURE_IMPORTS_END */ +function concatAll() { + return mergeAll(1); +} + +/** PURE_IMPORTS_START _of,_operators_concatAll PURE_IMPORTS_END */ +function concat$1() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + return concatAll()(of.apply(void 0, observables)); +} + +/** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */ +function defer(observableFactory) { + return new Observable(function (subscriber) { + var input; + try { + input = observableFactory(); + } + catch (err) { + subscriber.error(err); + return undefined; + } + var source = input ? from(input) : empty$1(); + return source.subscribe(subscriber); + }); +} + +/** PURE_IMPORTS_START _Observable,_util_isArray,_operators_map,_util_isObject,_from PURE_IMPORTS_END */ +function forkJoin() { + var sources = []; + for (var _i = 0; _i < arguments.length; _i++) { + sources[_i] = arguments[_i]; + } + if (sources.length === 1) { + var first_1 = sources[0]; + if (isArray$1(first_1)) { + return forkJoinInternal(first_1, null); + } + if (isObject$1(first_1) && Object.getPrototypeOf(first_1) === Object.prototype) { + var keys = Object.keys(first_1); + return forkJoinInternal(keys.map(function (key) { return first_1[key]; }), keys); + } + } + if (typeof sources[sources.length - 1] === 'function') { + var resultSelector_1 = sources.pop(); + sources = (sources.length === 1 && isArray$1(sources[0])) ? sources[0] : sources; + return forkJoinInternal(sources, null).pipe(map$1(function (args) { return resultSelector_1.apply(void 0, args); })); + } + return forkJoinInternal(sources, null); +} +function forkJoinInternal(sources, keys) { + return new Observable(function (subscriber) { + var len = sources.length; + if (len === 0) { + subscriber.complete(); + return; + } + var values = new Array(len); + var completed = 0; + var emitted = 0; + var _loop_1 = function (i) { + var source = from(sources[i]); + var hasValue = false; + subscriber.add(source.subscribe({ + next: function (value) { + if (!hasValue) { + hasValue = true; + emitted++; + } + values[i] = value; + }, + error: function (err) { return subscriber.error(err); }, + complete: function () { + completed++; + if (completed === len || !hasValue) { + if (emitted === len) { + subscriber.next(keys ? + keys.reduce(function (result, key, i) { return (result[key] = values[i], result); }, {}) : + values); + } + subscriber.complete(); + } + } + })); + }; + for (var i = 0; i < len; i++) { + _loop_1(i); + } + }); +} + +/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */ +function fromEvent(target, eventName, options, resultSelector) { + if (isFunction$1(options)) { + resultSelector = options; + options = undefined; + } + if (resultSelector) { + return fromEvent(target, eventName, options).pipe(map$1(function (args) { return isArray$1(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); + } + return new Observable(function (subscriber) { + function handler(e) { + if (arguments.length > 1) { + subscriber.next(Array.prototype.slice.call(arguments)); + } + else { + subscriber.next(e); + } + } + setupSubscription(target, eventName, handler, subscriber, options); + }); +} +function setupSubscription(sourceObj, eventName, handler, subscriber, options) { + var unsubscribe; + if (isEventTarget(sourceObj)) { + var source_1 = sourceObj; + sourceObj.addEventListener(eventName, handler, options); + unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); }; + } + else if (isJQueryStyleEventEmitter(sourceObj)) { + var source_2 = sourceObj; + sourceObj.on(eventName, handler); + unsubscribe = function () { return source_2.off(eventName, handler); }; + } + else if (isNodeStyleEventEmitter(sourceObj)) { + var source_3 = sourceObj; + sourceObj.addListener(eventName, handler); + unsubscribe = function () { return source_3.removeListener(eventName, handler); }; + } + else if (sourceObj && sourceObj.length) { + for (var i = 0, len = sourceObj.length; i < len; i++) { + setupSubscription(sourceObj[i], eventName, handler, subscriber, options); + } + } + else { + throw new TypeError('Invalid event target'); + } + subscriber.add(unsubscribe); +} +function isNodeStyleEventEmitter(sourceObj) { + return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function'; +} +function isJQueryStyleEventEmitter(sourceObj) { + return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function'; +} +function isEventTarget(sourceObj) { + return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function'; +} + +/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */ +function fromEventPattern(addHandler, removeHandler, resultSelector) { + if (resultSelector) { + return fromEventPattern(addHandler, removeHandler).pipe(map$1(function (args) { return isArray$1(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); + } + return new Observable(function (subscriber) { + var handler = function () { + var e = []; + for (var _i = 0; _i < arguments.length; _i++) { + e[_i] = arguments[_i]; + } + return subscriber.next(e.length === 1 ? e[0] : e); + }; + var retValue; + try { + retValue = addHandler(handler); + } + catch (err) { + subscriber.error(err); + return undefined; + } + if (!isFunction$1(removeHandler)) { + return undefined; + } + return function () { return removeHandler(handler, retValue); }; + }); +} + +/** PURE_IMPORTS_START _Observable,_util_identity,_util_isScheduler PURE_IMPORTS_END */ +function generate(initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler) { + var resultSelector; + var initialState; + if (arguments.length == 1) { + var options = initialStateOrOptions; + initialState = options.initialState; + condition = options.condition; + iterate = options.iterate; + resultSelector = options.resultSelector || identity$1; + scheduler = options.scheduler; + } + else if (resultSelectorOrObservable === undefined || isScheduler(resultSelectorOrObservable)) { + initialState = initialStateOrOptions; + resultSelector = identity$1; + scheduler = resultSelectorOrObservable; + } + else { + initialState = initialStateOrOptions; + resultSelector = resultSelectorOrObservable; + } + return new Observable(function (subscriber) { + var state = initialState; + if (scheduler) { + return scheduler.schedule(dispatch$3, 0, { + subscriber: subscriber, + iterate: iterate, + condition: condition, + resultSelector: resultSelector, + state: state + }); + } + do { + if (condition) { + var conditionResult = void 0; + try { + conditionResult = condition(state); + } + catch (err) { + subscriber.error(err); + return undefined; + } + if (!conditionResult) { + subscriber.complete(); + break; + } + } + var value = void 0; + try { + value = resultSelector(state); + } + catch (err) { + subscriber.error(err); + return undefined; + } + subscriber.next(value); + if (subscriber.closed) { + break; + } + try { + state = iterate(state); + } + catch (err) { + subscriber.error(err); + return undefined; + } + } while (true); + return undefined; + }); +} +function dispatch$3(state) { + var subscriber = state.subscriber, condition = state.condition; + if (subscriber.closed) { + return undefined; + } + if (state.needIterate) { + try { + state.state = state.iterate(state.state); + } + catch (err) { + subscriber.error(err); + return undefined; + } + } + else { + state.needIterate = true; + } + if (condition) { + var conditionResult = void 0; + try { + conditionResult = condition(state.state); + } + catch (err) { + subscriber.error(err); + return undefined; + } + if (!conditionResult) { + subscriber.complete(); + return undefined; + } + if (subscriber.closed) { + return undefined; + } + } + var value; + try { + value = state.resultSelector(state.state); + } + catch (err) { + subscriber.error(err); + return undefined; + } + if (subscriber.closed) { + return undefined; + } + subscriber.next(value); + if (subscriber.closed) { + return undefined; + } + return this.schedule(state); +} + +/** PURE_IMPORTS_START _defer,_empty PURE_IMPORTS_END */ +function iif(condition, trueResult, falseResult) { + if (trueResult === void 0) { + trueResult = EMPTY; + } + if (falseResult === void 0) { + falseResult = EMPTY; + } + return defer(function () { return condition() ? trueResult : falseResult; }); +} + +/** PURE_IMPORTS_START _isArray PURE_IMPORTS_END */ +function isNumeric(val) { + return !isArray$1(val) && (val - parseFloat(val) + 1) >= 0; +} + +/** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric PURE_IMPORTS_END */ +function interval(period, scheduler) { + if (period === void 0) { + period = 0; + } + if (scheduler === void 0) { + scheduler = async; + } + if (!isNumeric(period) || period < 0) { + period = 0; + } + if (!scheduler || typeof scheduler.schedule !== 'function') { + scheduler = async; + } + return new Observable(function (subscriber) { + subscriber.add(scheduler.schedule(dispatch$4, period, { subscriber: subscriber, counter: 0, period: period })); + return subscriber; + }); +} +function dispatch$4(state) { + var subscriber = state.subscriber, counter = state.counter, period = state.period; + subscriber.next(counter); + this.schedule({ subscriber: subscriber, counter: counter + 1, period: period }, period); +} + +/** PURE_IMPORTS_START _Observable,_util_isScheduler,_operators_mergeAll,_fromArray PURE_IMPORTS_END */ +function merge() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + var concurrent = Number.POSITIVE_INFINITY; + var scheduler = null; + var last = observables[observables.length - 1]; + if (isScheduler(last)) { + scheduler = observables.pop(); + if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') { + concurrent = observables.pop(); + } + } + else if (typeof last === 'number') { + concurrent = observables.pop(); + } + if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) { + return observables[0]; + } + return mergeAll(concurrent)(fromArray(observables, scheduler)); +} + +/** PURE_IMPORTS_START _Observable,_util_noop PURE_IMPORTS_END */ +var NEVER = /*@__PURE__*/ new Observable(noop); +function never() { + return NEVER; +} + +/** PURE_IMPORTS_START _Observable,_from,_util_isArray,_empty PURE_IMPORTS_END */ +function onErrorResumeNext() { + var sources = []; + for (var _i = 0; _i < arguments.length; _i++) { + sources[_i] = arguments[_i]; + } + if (sources.length === 0) { + return EMPTY; + } + var first = sources[0], remainder = sources.slice(1); + if (sources.length === 1 && isArray$1(first)) { + return onErrorResumeNext.apply(void 0, first); + } + return new Observable(function (subscriber) { + var subNext = function () { return subscriber.add(onErrorResumeNext.apply(void 0, remainder).subscribe(subscriber)); }; + return from(first).subscribe({ + next: function (value) { subscriber.next(value); }, + error: subNext, + complete: subNext, + }); + }); +} + +/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ +function pairs(obj, scheduler) { + if (!scheduler) { + return new Observable(function (subscriber) { + var keys = Object.keys(obj); + for (var i = 0; i < keys.length && !subscriber.closed; i++) { + var key = keys[i]; + if (obj.hasOwnProperty(key)) { + subscriber.next([key, obj[key]]); + } + } + subscriber.complete(); + }); + } + else { + return new Observable(function (subscriber) { + var keys = Object.keys(obj); + var subscription = new Subscription(); + subscription.add(scheduler.schedule(dispatch$5, 0, { keys: keys, index: 0, subscriber: subscriber, subscription: subscription, obj: obj })); + return subscription; + }); + } +} +function dispatch$5(state) { + var keys = state.keys, index = state.index, subscriber = state.subscriber, subscription = state.subscription, obj = state.obj; + if (!subscriber.closed) { + if (index < keys.length) { + var key = keys[index]; + subscriber.next([key, obj[key]]); + subscription.add(this.schedule({ keys: keys, index: index + 1, subscriber: subscriber, subscription: subscription, obj: obj })); + } + else { + subscriber.complete(); + } + } +} + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function not(pred, thisArg) { + function notPred() { + return !(notPred.pred.apply(notPred.thisArg, arguments)); + } + notPred.pred = pred; + notPred.thisArg = thisArg; + return notPred; +} + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function filter(predicate, thisArg) { + return function filterOperatorFunction(source) { + return source.lift(new FilterOperator(predicate, thisArg)); + }; +} +var FilterOperator = /*@__PURE__*/ (function () { + function FilterOperator(predicate, thisArg) { + this.predicate = predicate; + this.thisArg = thisArg; + } + FilterOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg)); + }; + return FilterOperator; +}()); +var FilterSubscriber = /*@__PURE__*/ (function (_super) { + __extends(FilterSubscriber, _super); + function FilterSubscriber(destination, predicate, thisArg) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.thisArg = thisArg; + _this.count = 0; + return _this; + } + FilterSubscriber.prototype._next = function (value) { + var result; + try { + result = this.predicate.call(this.thisArg, value, this.count++); + } + catch (err) { + this.destination.error(err); + return; + } + if (result) { + this.destination.next(value); + } + }; + return FilterSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _util_not,_util_subscribeTo,_operators_filter,_Observable PURE_IMPORTS_END */ +function partition(source, predicate, thisArg) { + return [ + filter(predicate, thisArg)(new Observable(subscribeTo(source))), + filter(not(predicate, thisArg))(new Observable(subscribeTo(source))) + ]; +} + +/** PURE_IMPORTS_START tslib,_util_isArray,_fromArray,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +function race() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + if (observables.length === 1) { + if (isArray$1(observables[0])) { + observables = observables[0]; + } + else { + return observables[0]; + } + } + return fromArray(observables, undefined).lift(new RaceOperator()); +} +var RaceOperator = /*@__PURE__*/ (function () { + function RaceOperator() { + } + RaceOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new RaceSubscriber(subscriber)); + }; + return RaceOperator; +}()); +var RaceSubscriber = /*@__PURE__*/ (function (_super) { + __extends(RaceSubscriber, _super); + function RaceSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.hasFirst = false; + _this.observables = []; + _this.subscriptions = []; + return _this; + } + RaceSubscriber.prototype._next = function (observable) { + this.observables.push(observable); + }; + RaceSubscriber.prototype._complete = function () { + var observables = this.observables; + var len = observables.length; + if (len === 0) { + this.destination.complete(); + } + else { + for (var i = 0; i < len && !this.hasFirst; i++) { + var observable = observables[i]; + var subscription = subscribeToResult(this, observable, undefined, i); + if (this.subscriptions) { + this.subscriptions.push(subscription); + } + this.add(subscription); + } + this.observables = null; + } + }; + RaceSubscriber.prototype.notifyNext = function (_outerValue, innerValue, outerIndex) { + if (!this.hasFirst) { + this.hasFirst = true; + for (var i = 0; i < this.subscriptions.length; i++) { + if (i !== outerIndex) { + var subscription = this.subscriptions[i]; + subscription.unsubscribe(); + this.remove(subscription); + } + } + this.subscriptions = null; + } + this.destination.next(innerValue); + }; + return RaceSubscriber; +}(OuterSubscriber)); + +/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ +function range(start, count, scheduler) { + if (start === void 0) { + start = 0; + } + return new Observable(function (subscriber) { + if (count === undefined) { + count = start; + start = 0; + } + var index = 0; + var current = start; + if (scheduler) { + return scheduler.schedule(dispatch$6, 0, { + index: index, count: count, start: start, subscriber: subscriber + }); + } + else { + do { + if (index++ >= count) { + subscriber.complete(); + break; + } + subscriber.next(current++); + if (subscriber.closed) { + break; + } + } while (true); + } + return undefined; + }); +} +function dispatch$6(state) { + var start = state.start, index = state.index, count = state.count, subscriber = state.subscriber; + if (index >= count) { + subscriber.complete(); + return; + } + subscriber.next(start); + if (subscriber.closed) { + return; + } + state.index = index + 1; + state.start = start + 1; + this.schedule(state); +} + +/** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */ +function timer(dueTime, periodOrScheduler, scheduler) { + if (dueTime === void 0) { + dueTime = 0; + } + var period = -1; + if (isNumeric(periodOrScheduler)) { + period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler); + } + else if (isScheduler(periodOrScheduler)) { + scheduler = periodOrScheduler; + } + if (!isScheduler(scheduler)) { + scheduler = async; + } + return new Observable(function (subscriber) { + var due = isNumeric(dueTime) + ? dueTime + : (+dueTime - scheduler.now()); + return scheduler.schedule(dispatch$7, due, { + index: 0, period: period, subscriber: subscriber + }); + }); +} +function dispatch$7(state) { + var index = state.index, period = state.period, subscriber = state.subscriber; + subscriber.next(index); + if (subscriber.closed) { + return; + } + else if (period === -1) { + return subscriber.complete(); + } + state.index = index + 1; + this.schedule(state, period); +} + +/** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */ +function using(resourceFactory, observableFactory) { + return new Observable(function (subscriber) { + var resource; + try { + resource = resourceFactory(); + } + catch (err) { + subscriber.error(err); + return undefined; + } + var result; + try { + result = observableFactory(resource); + } + catch (err) { + subscriber.error(err); + return undefined; + } + var source = result ? from(result) : EMPTY; + var subscription = source.subscribe(subscriber); + return function () { + subscription.unsubscribe(); + if (resource) { + resource.unsubscribe(); + } + }; + }); +} + +/** PURE_IMPORTS_START tslib,_fromArray,_util_isArray,_Subscriber,_.._internal_symbol_iterator,_innerSubscribe PURE_IMPORTS_END */ +function zip() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + var resultSelector = observables[observables.length - 1]; + if (typeof resultSelector === 'function') { + observables.pop(); + } + return fromArray(observables, undefined).lift(new ZipOperator(resultSelector)); +} +var ZipOperator = /*@__PURE__*/ (function () { + function ZipOperator(resultSelector) { + this.resultSelector = resultSelector; + } + ZipOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector)); + }; + return ZipOperator; +}()); +var ZipSubscriber = /*@__PURE__*/ (function (_super) { + __extends(ZipSubscriber, _super); + function ZipSubscriber(destination, resultSelector, values) { + var _this = _super.call(this, destination) || this; + _this.resultSelector = resultSelector; + _this.iterators = []; + _this.active = 0; + _this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : undefined; + return _this; + } + ZipSubscriber.prototype._next = function (value) { + var iterators = this.iterators; + if (isArray$1(value)) { + iterators.push(new StaticArrayIterator(value)); + } + else if (typeof value[iterator] === 'function') { + iterators.push(new StaticIterator(value[iterator]())); + } + else { + iterators.push(new ZipBufferIterator(this.destination, this, value)); + } + }; + ZipSubscriber.prototype._complete = function () { + var iterators = this.iterators; + var len = iterators.length; + this.unsubscribe(); + if (len === 0) { + this.destination.complete(); + return; + } + this.active = len; + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + if (iterator.stillUnsubscribed) { + var destination = this.destination; + destination.add(iterator.subscribe()); + } + else { + this.active--; + } + } + }; + ZipSubscriber.prototype.notifyInactive = function () { + this.active--; + if (this.active === 0) { + this.destination.complete(); + } + }; + ZipSubscriber.prototype.checkIterators = function () { + var iterators = this.iterators; + var len = iterators.length; + var destination = this.destination; + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) { + return; + } + } + var shouldComplete = false; + var args = []; + for (var i = 0; i < len; i++) { + var iterator = iterators[i]; + var result = iterator.next(); + if (iterator.hasCompleted()) { + shouldComplete = true; + } + if (result.done) { + destination.complete(); + return; + } + args.push(result.value); + } + if (this.resultSelector) { + this._tryresultSelector(args); + } + else { + destination.next(args); + } + if (shouldComplete) { + destination.complete(); + } + }; + ZipSubscriber.prototype._tryresultSelector = function (args) { + var result; + try { + result = this.resultSelector.apply(this, args); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return ZipSubscriber; +}(Subscriber)); +var StaticIterator = /*@__PURE__*/ (function () { + function StaticIterator(iterator) { + this.iterator = iterator; + this.nextResult = iterator.next(); + } + StaticIterator.prototype.hasValue = function () { + return true; + }; + StaticIterator.prototype.next = function () { + var result = this.nextResult; + this.nextResult = this.iterator.next(); + return result; + }; + StaticIterator.prototype.hasCompleted = function () { + var nextResult = this.nextResult; + return Boolean(nextResult && nextResult.done); + }; + return StaticIterator; +}()); +var StaticArrayIterator = /*@__PURE__*/ (function () { + function StaticArrayIterator(array) { + this.array = array; + this.index = 0; + this.length = 0; + this.length = array.length; + } + StaticArrayIterator.prototype[iterator] = function () { + return this; + }; + StaticArrayIterator.prototype.next = function (value) { + var i = this.index++; + var array = this.array; + return i < this.length ? { value: array[i], done: false } : { value: null, done: true }; + }; + StaticArrayIterator.prototype.hasValue = function () { + return this.array.length > this.index; + }; + StaticArrayIterator.prototype.hasCompleted = function () { + return this.array.length === this.index; + }; + return StaticArrayIterator; +}()); +var ZipBufferIterator = /*@__PURE__*/ (function (_super) { + __extends(ZipBufferIterator, _super); + function ZipBufferIterator(destination, parent, observable) { + var _this = _super.call(this, destination) || this; + _this.parent = parent; + _this.observable = observable; + _this.stillUnsubscribed = true; + _this.buffer = []; + _this.isComplete = false; + return _this; + } + ZipBufferIterator.prototype[iterator] = function () { + return this; + }; + ZipBufferIterator.prototype.next = function () { + var buffer = this.buffer; + if (buffer.length === 0 && this.isComplete) { + return { value: null, done: true }; + } + else { + return { value: buffer.shift(), done: false }; + } + }; + ZipBufferIterator.prototype.hasValue = function () { + return this.buffer.length > 0; + }; + ZipBufferIterator.prototype.hasCompleted = function () { + return this.buffer.length === 0 && this.isComplete; + }; + ZipBufferIterator.prototype.notifyComplete = function () { + if (this.buffer.length > 0) { + this.isComplete = true; + this.parent.notifyInactive(); + } + else { + this.destination.complete(); + } + }; + ZipBufferIterator.prototype.notifyNext = function (innerValue) { + this.buffer.push(innerValue); + this.parent.checkIterators(); + }; + ZipBufferIterator.prototype.subscribe = function () { + return innerSubscribe(this.observable, new SimpleInnerSubscriber(this)); + }; + return ZipBufferIterator; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ + +var _esm5 = /*#__PURE__*/Object.freeze({ + __proto__: null, + Observable: Observable, + ConnectableObservable: ConnectableObservable, + GroupedObservable: GroupedObservable, + observable: observable, + Subject: Subject, + BehaviorSubject: BehaviorSubject, + ReplaySubject: ReplaySubject, + AsyncSubject: AsyncSubject, + asap: asap, + asapScheduler: asapScheduler, + async: async, + asyncScheduler: asyncScheduler, + queue: queue, + queueScheduler: queueScheduler, + animationFrame: animationFrame, + animationFrameScheduler: animationFrameScheduler, + VirtualTimeScheduler: VirtualTimeScheduler, + VirtualAction: VirtualAction, + Scheduler: Scheduler, + Subscription: Subscription, + Subscriber: Subscriber, + Notification: Notification, + get NotificationKind () { return NotificationKind; }, + pipe: pipe, + noop: noop, + identity: identity$1, + isObservable: isObservable, + ArgumentOutOfRangeError: ArgumentOutOfRangeError, + EmptyError: EmptyError, + ObjectUnsubscribedError: ObjectUnsubscribedError, + UnsubscriptionError: UnsubscriptionError, + TimeoutError: TimeoutError, + bindCallback: bindCallback, + bindNodeCallback: bindNodeCallback, + combineLatest: combineLatest, + concat: concat$1, + defer: defer, + empty: empty$1, + forkJoin: forkJoin, + from: from, + fromEvent: fromEvent, + fromEventPattern: fromEventPattern, + generate: generate, + iif: iif, + interval: interval, + merge: merge, + never: never, + of: of, + onErrorResumeNext: onErrorResumeNext, + pairs: pairs, + partition: partition, + race: race, + range: range, + throwError: throwError, + timer: timer, + using: using, + zip: zip, + scheduled: scheduled, + EMPTY: EMPTY, + NEVER: NEVER, + config: config +}); + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +function audit(durationSelector) { + return function auditOperatorFunction(source) { + return source.lift(new AuditOperator(durationSelector)); + }; +} +var AuditOperator = /*@__PURE__*/ (function () { + function AuditOperator(durationSelector) { + this.durationSelector = durationSelector; + } + AuditOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector)); + }; + return AuditOperator; +}()); +var AuditSubscriber = /*@__PURE__*/ (function (_super) { + __extends(AuditSubscriber, _super); + function AuditSubscriber(destination, durationSelector) { + var _this = _super.call(this, destination) || this; + _this.durationSelector = durationSelector; + _this.hasValue = false; + return _this; + } + AuditSubscriber.prototype._next = function (value) { + this.value = value; + this.hasValue = true; + if (!this.throttled) { + var duration = void 0; + try { + var durationSelector = this.durationSelector; + duration = durationSelector(value); + } + catch (err) { + return this.destination.error(err); + } + var innerSubscription = innerSubscribe(duration, new SimpleInnerSubscriber(this)); + if (!innerSubscription || innerSubscription.closed) { + this.clearThrottle(); + } + else { + this.add(this.throttled = innerSubscription); + } + } + }; + AuditSubscriber.prototype.clearThrottle = function () { + var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled; + if (throttled) { + this.remove(throttled); + this.throttled = undefined; + throttled.unsubscribe(); + } + if (hasValue) { + this.value = undefined; + this.hasValue = false; + this.destination.next(value); + } + }; + AuditSubscriber.prototype.notifyNext = function () { + this.clearThrottle(); + }; + AuditSubscriber.prototype.notifyComplete = function () { + this.clearThrottle(); + }; + return AuditSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START _scheduler_async,_audit,_observable_timer PURE_IMPORTS_END */ +function auditTime(duration, scheduler) { + if (scheduler === void 0) { + scheduler = async; + } + return audit(function () { return timer(duration, scheduler); }); +} + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +function buffer(closingNotifier) { + return function bufferOperatorFunction(source) { + return source.lift(new BufferOperator(closingNotifier)); + }; +} +var BufferOperator = /*@__PURE__*/ (function () { + function BufferOperator(closingNotifier) { + this.closingNotifier = closingNotifier; + } + BufferOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier)); + }; + return BufferOperator; +}()); +var BufferSubscriber = /*@__PURE__*/ (function (_super) { + __extends(BufferSubscriber, _super); + function BufferSubscriber(destination, closingNotifier) { + var _this = _super.call(this, destination) || this; + _this.buffer = []; + _this.add(innerSubscribe(closingNotifier, new SimpleInnerSubscriber(_this))); + return _this; + } + BufferSubscriber.prototype._next = function (value) { + this.buffer.push(value); + }; + BufferSubscriber.prototype.notifyNext = function () { + var buffer = this.buffer; + this.buffer = []; + this.destination.next(buffer); + }; + return BufferSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function bufferCount(bufferSize, startBufferEvery) { + if (startBufferEvery === void 0) { + startBufferEvery = null; + } + return function bufferCountOperatorFunction(source) { + return source.lift(new BufferCountOperator(bufferSize, startBufferEvery)); + }; +} +var BufferCountOperator = /*@__PURE__*/ (function () { + function BufferCountOperator(bufferSize, startBufferEvery) { + this.bufferSize = bufferSize; + this.startBufferEvery = startBufferEvery; + if (!startBufferEvery || bufferSize === startBufferEvery) { + this.subscriberClass = BufferCountSubscriber; + } + else { + this.subscriberClass = BufferSkipCountSubscriber; + } + } + BufferCountOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery)); + }; + return BufferCountOperator; +}()); +var BufferCountSubscriber = /*@__PURE__*/ (function (_super) { + __extends(BufferCountSubscriber, _super); + function BufferCountSubscriber(destination, bufferSize) { + var _this = _super.call(this, destination) || this; + _this.bufferSize = bufferSize; + _this.buffer = []; + return _this; + } + BufferCountSubscriber.prototype._next = function (value) { + var buffer = this.buffer; + buffer.push(value); + if (buffer.length == this.bufferSize) { + this.destination.next(buffer); + this.buffer = []; + } + }; + BufferCountSubscriber.prototype._complete = function () { + var buffer = this.buffer; + if (buffer.length > 0) { + this.destination.next(buffer); + } + _super.prototype._complete.call(this); + }; + return BufferCountSubscriber; +}(Subscriber)); +var BufferSkipCountSubscriber = /*@__PURE__*/ (function (_super) { + __extends(BufferSkipCountSubscriber, _super); + function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) { + var _this = _super.call(this, destination) || this; + _this.bufferSize = bufferSize; + _this.startBufferEvery = startBufferEvery; + _this.buffers = []; + _this.count = 0; + return _this; + } + BufferSkipCountSubscriber.prototype._next = function (value) { + var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count; + this.count++; + if (count % startBufferEvery === 0) { + buffers.push([]); + } + for (var i = buffers.length; i--;) { + var buffer = buffers[i]; + buffer.push(value); + if (buffer.length === bufferSize) { + buffers.splice(i, 1); + this.destination.next(buffer); + } + } + }; + BufferSkipCountSubscriber.prototype._complete = function () { + var _a = this, buffers = _a.buffers, destination = _a.destination; + while (buffers.length > 0) { + var buffer = buffers.shift(); + if (buffer.length > 0) { + destination.next(buffer); + } + } + _super.prototype._complete.call(this); + }; + return BufferSkipCountSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_scheduler_async,_Subscriber,_util_isScheduler PURE_IMPORTS_END */ +function bufferTime(bufferTimeSpan) { + var length = arguments.length; + var scheduler = async; + if (isScheduler(arguments[arguments.length - 1])) { + scheduler = arguments[arguments.length - 1]; + length--; + } + var bufferCreationInterval = null; + if (length >= 2) { + bufferCreationInterval = arguments[1]; + } + var maxBufferSize = Number.POSITIVE_INFINITY; + if (length >= 3) { + maxBufferSize = arguments[2]; + } + return function bufferTimeOperatorFunction(source) { + return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler)); + }; +} +var BufferTimeOperator = /*@__PURE__*/ (function () { + function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { + this.bufferTimeSpan = bufferTimeSpan; + this.bufferCreationInterval = bufferCreationInterval; + this.maxBufferSize = maxBufferSize; + this.scheduler = scheduler; + } + BufferTimeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler)); + }; + return BufferTimeOperator; +}()); +var Context = /*@__PURE__*/ (function () { + function Context() { + this.buffer = []; + } + return Context; +}()); +var BufferTimeSubscriber = /*@__PURE__*/ (function (_super) { + __extends(BufferTimeSubscriber, _super); + function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { + var _this = _super.call(this, destination) || this; + _this.bufferTimeSpan = bufferTimeSpan; + _this.bufferCreationInterval = bufferCreationInterval; + _this.maxBufferSize = maxBufferSize; + _this.scheduler = scheduler; + _this.contexts = []; + var context = _this.openContext(); + _this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0; + if (_this.timespanOnly) { + var timeSpanOnlyState = { subscriber: _this, context: context, bufferTimeSpan: bufferTimeSpan }; + _this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); + } + else { + var closeState = { subscriber: _this, context: context }; + var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: _this, scheduler: scheduler }; + _this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState)); + _this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState)); + } + return _this; + } + BufferTimeSubscriber.prototype._next = function (value) { + var contexts = this.contexts; + var len = contexts.length; + var filledBufferContext; + for (var i = 0; i < len; i++) { + var context_1 = contexts[i]; + var buffer = context_1.buffer; + buffer.push(value); + if (buffer.length == this.maxBufferSize) { + filledBufferContext = context_1; + } + } + if (filledBufferContext) { + this.onBufferFull(filledBufferContext); + } + }; + BufferTimeSubscriber.prototype._error = function (err) { + this.contexts.length = 0; + _super.prototype._error.call(this, err); + }; + BufferTimeSubscriber.prototype._complete = function () { + var _a = this, contexts = _a.contexts, destination = _a.destination; + while (contexts.length > 0) { + var context_2 = contexts.shift(); + destination.next(context_2.buffer); + } + _super.prototype._complete.call(this); + }; + BufferTimeSubscriber.prototype._unsubscribe = function () { + this.contexts = null; + }; + BufferTimeSubscriber.prototype.onBufferFull = function (context) { + this.closeContext(context); + var closeAction = context.closeAction; + closeAction.unsubscribe(); + this.remove(closeAction); + if (!this.closed && this.timespanOnly) { + context = this.openContext(); + var bufferTimeSpan = this.bufferTimeSpan; + var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan }; + this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); + } + }; + BufferTimeSubscriber.prototype.openContext = function () { + var context = new Context(); + this.contexts.push(context); + return context; + }; + BufferTimeSubscriber.prototype.closeContext = function (context) { + this.destination.next(context.buffer); + var contexts = this.contexts; + var spliceIndex = contexts ? contexts.indexOf(context) : -1; + if (spliceIndex >= 0) { + contexts.splice(contexts.indexOf(context), 1); + } + }; + return BufferTimeSubscriber; +}(Subscriber)); +function dispatchBufferTimeSpanOnly(state) { + var subscriber = state.subscriber; + var prevContext = state.context; + if (prevContext) { + subscriber.closeContext(prevContext); + } + if (!subscriber.closed) { + state.context = subscriber.openContext(); + state.context.closeAction = this.schedule(state, state.bufferTimeSpan); + } +} +function dispatchBufferCreation(state) { + var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler; + var context = subscriber.openContext(); + var action = this; + if (!subscriber.closed) { + subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context })); + action.schedule(state, bufferCreationInterval); + } +} +function dispatchBufferClose(arg) { + var subscriber = arg.subscriber, context = arg.context; + subscriber.closeContext(context); +} + +/** PURE_IMPORTS_START tslib,_Subscription,_util_subscribeToResult,_OuterSubscriber PURE_IMPORTS_END */ +function bufferToggle(openings, closingSelector) { + return function bufferToggleOperatorFunction(source) { + return source.lift(new BufferToggleOperator(openings, closingSelector)); + }; +} +var BufferToggleOperator = /*@__PURE__*/ (function () { + function BufferToggleOperator(openings, closingSelector) { + this.openings = openings; + this.closingSelector = closingSelector; + } + BufferToggleOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector)); + }; + return BufferToggleOperator; +}()); +var BufferToggleSubscriber = /*@__PURE__*/ (function (_super) { + __extends(BufferToggleSubscriber, _super); + function BufferToggleSubscriber(destination, openings, closingSelector) { + var _this = _super.call(this, destination) || this; + _this.closingSelector = closingSelector; + _this.contexts = []; + _this.add(subscribeToResult(_this, openings)); + return _this; + } + BufferToggleSubscriber.prototype._next = function (value) { + var contexts = this.contexts; + var len = contexts.length; + for (var i = 0; i < len; i++) { + contexts[i].buffer.push(value); + } + }; + BufferToggleSubscriber.prototype._error = function (err) { + var contexts = this.contexts; + while (contexts.length > 0) { + var context_1 = contexts.shift(); + context_1.subscription.unsubscribe(); + context_1.buffer = null; + context_1.subscription = null; + } + this.contexts = null; + _super.prototype._error.call(this, err); + }; + BufferToggleSubscriber.prototype._complete = function () { + var contexts = this.contexts; + while (contexts.length > 0) { + var context_2 = contexts.shift(); + this.destination.next(context_2.buffer); + context_2.subscription.unsubscribe(); + context_2.buffer = null; + context_2.subscription = null; + } + this.contexts = null; + _super.prototype._complete.call(this); + }; + BufferToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue) { + outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue); + }; + BufferToggleSubscriber.prototype.notifyComplete = function (innerSub) { + this.closeBuffer(innerSub.context); + }; + BufferToggleSubscriber.prototype.openBuffer = function (value) { + try { + var closingSelector = this.closingSelector; + var closingNotifier = closingSelector.call(this, value); + if (closingNotifier) { + this.trySubscribe(closingNotifier); + } + } + catch (err) { + this._error(err); + } + }; + BufferToggleSubscriber.prototype.closeBuffer = function (context) { + var contexts = this.contexts; + if (contexts && context) { + var buffer = context.buffer, subscription = context.subscription; + this.destination.next(buffer); + contexts.splice(contexts.indexOf(context), 1); + this.remove(subscription); + subscription.unsubscribe(); + } + }; + BufferToggleSubscriber.prototype.trySubscribe = function (closingNotifier) { + var contexts = this.contexts; + var buffer = []; + var subscription = new Subscription(); + var context = { buffer: buffer, subscription: subscription }; + contexts.push(context); + var innerSubscription = subscribeToResult(this, closingNotifier, context); + if (!innerSubscription || innerSubscription.closed) { + this.closeBuffer(context); + } + else { + innerSubscription.context = context; + this.add(innerSubscription); + subscription.add(innerSubscription); + } + }; + return BufferToggleSubscriber; +}(OuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscription,_innerSubscribe PURE_IMPORTS_END */ +function bufferWhen(closingSelector) { + return function (source) { + return source.lift(new BufferWhenOperator(closingSelector)); + }; +} +var BufferWhenOperator = /*@__PURE__*/ (function () { + function BufferWhenOperator(closingSelector) { + this.closingSelector = closingSelector; + } + BufferWhenOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector)); + }; + return BufferWhenOperator; +}()); +var BufferWhenSubscriber = /*@__PURE__*/ (function (_super) { + __extends(BufferWhenSubscriber, _super); + function BufferWhenSubscriber(destination, closingSelector) { + var _this = _super.call(this, destination) || this; + _this.closingSelector = closingSelector; + _this.subscribing = false; + _this.openBuffer(); + return _this; + } + BufferWhenSubscriber.prototype._next = function (value) { + this.buffer.push(value); + }; + BufferWhenSubscriber.prototype._complete = function () { + var buffer = this.buffer; + if (buffer) { + this.destination.next(buffer); + } + _super.prototype._complete.call(this); + }; + BufferWhenSubscriber.prototype._unsubscribe = function () { + this.buffer = undefined; + this.subscribing = false; + }; + BufferWhenSubscriber.prototype.notifyNext = function () { + this.openBuffer(); + }; + BufferWhenSubscriber.prototype.notifyComplete = function () { + if (this.subscribing) { + this.complete(); + } + else { + this.openBuffer(); + } + }; + BufferWhenSubscriber.prototype.openBuffer = function () { + var closingSubscription = this.closingSubscription; + if (closingSubscription) { + this.remove(closingSubscription); + closingSubscription.unsubscribe(); + } + var buffer = this.buffer; + if (this.buffer) { + this.destination.next(buffer); + } + this.buffer = []; + var closingNotifier; + try { + var closingSelector = this.closingSelector; + closingNotifier = closingSelector(); + } + catch (err) { + return this.error(err); + } + closingSubscription = new Subscription(); + this.closingSubscription = closingSubscription; + this.add(closingSubscription); + this.subscribing = true; + closingSubscription.add(innerSubscribe(closingNotifier, new SimpleInnerSubscriber(this))); + this.subscribing = false; + }; + return BufferWhenSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +function catchError(selector) { + return function catchErrorOperatorFunction(source) { + var operator = new CatchOperator(selector); + var caught = source.lift(operator); + return (operator.caught = caught); + }; +} +var CatchOperator = /*@__PURE__*/ (function () { + function CatchOperator(selector) { + this.selector = selector; + } + CatchOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught)); + }; + return CatchOperator; +}()); +var CatchSubscriber = /*@__PURE__*/ (function (_super) { + __extends(CatchSubscriber, _super); + function CatchSubscriber(destination, selector, caught) { + var _this = _super.call(this, destination) || this; + _this.selector = selector; + _this.caught = caught; + return _this; + } + CatchSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var result = void 0; + try { + result = this.selector(err, this.caught); + } + catch (err2) { + _super.prototype.error.call(this, err2); + return; + } + this._unsubscribeAndRecycle(); + var innerSubscriber = new SimpleInnerSubscriber(this); + this.add(innerSubscriber); + var innerSubscription = innerSubscribe(result, innerSubscriber); + if (innerSubscription !== innerSubscriber) { + this.add(innerSubscription); + } + } + }; + return CatchSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START _observable_combineLatest PURE_IMPORTS_END */ +function combineAll(project) { + return function (source) { return source.lift(new CombineLatestOperator(project)); }; +} + +/** PURE_IMPORTS_START _util_isArray,_observable_combineLatest,_observable_from PURE_IMPORTS_END */ +function combineLatest$1() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + var project = null; + if (typeof observables[observables.length - 1] === 'function') { + project = observables.pop(); + } + if (observables.length === 1 && isArray$1(observables[0])) { + observables = observables[0].slice(); + } + return function (source) { return source.lift.call(from([source].concat(observables)), new CombineLatestOperator(project)); }; +} + +/** PURE_IMPORTS_START _observable_concat PURE_IMPORTS_END */ +function concat$2() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + return function (source) { return source.lift.call(concat$1.apply(void 0, [source].concat(observables))); }; +} + +/** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ +function concatMap(project, resultSelector) { + return mergeMap(project, resultSelector, 1); +} + +/** PURE_IMPORTS_START _concatMap PURE_IMPORTS_END */ +function concatMapTo(innerObservable, resultSelector) { + return concatMap(function () { return innerObservable; }, resultSelector); +} + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function count(predicate) { + return function (source) { return source.lift(new CountOperator(predicate, source)); }; +} +var CountOperator = /*@__PURE__*/ (function () { + function CountOperator(predicate, source) { + this.predicate = predicate; + this.source = source; + } + CountOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source)); + }; + return CountOperator; +}()); +var CountSubscriber = /*@__PURE__*/ (function (_super) { + __extends(CountSubscriber, _super); + function CountSubscriber(destination, predicate, source) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.source = source; + _this.count = 0; + _this.index = 0; + return _this; + } + CountSubscriber.prototype._next = function (value) { + if (this.predicate) { + this._tryPredicate(value); + } + else { + this.count++; + } + }; + CountSubscriber.prototype._tryPredicate = function (value) { + var result; + try { + result = this.predicate(value, this.index++, this.source); + } + catch (err) { + this.destination.error(err); + return; + } + if (result) { + this.count++; + } + }; + CountSubscriber.prototype._complete = function () { + this.destination.next(this.count); + this.destination.complete(); + }; + return CountSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +function debounce(durationSelector) { + return function (source) { return source.lift(new DebounceOperator(durationSelector)); }; +} +var DebounceOperator = /*@__PURE__*/ (function () { + function DebounceOperator(durationSelector) { + this.durationSelector = durationSelector; + } + DebounceOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector)); + }; + return DebounceOperator; +}()); +var DebounceSubscriber = /*@__PURE__*/ (function (_super) { + __extends(DebounceSubscriber, _super); + function DebounceSubscriber(destination, durationSelector) { + var _this = _super.call(this, destination) || this; + _this.durationSelector = durationSelector; + _this.hasValue = false; + return _this; + } + DebounceSubscriber.prototype._next = function (value) { + try { + var result = this.durationSelector.call(this, value); + if (result) { + this._tryNext(value, result); + } + } + catch (err) { + this.destination.error(err); + } + }; + DebounceSubscriber.prototype._complete = function () { + this.emitValue(); + this.destination.complete(); + }; + DebounceSubscriber.prototype._tryNext = function (value, duration) { + var subscription = this.durationSubscription; + this.value = value; + this.hasValue = true; + if (subscription) { + subscription.unsubscribe(); + this.remove(subscription); + } + subscription = innerSubscribe(duration, new SimpleInnerSubscriber(this)); + if (subscription && !subscription.closed) { + this.add(this.durationSubscription = subscription); + } + }; + DebounceSubscriber.prototype.notifyNext = function () { + this.emitValue(); + }; + DebounceSubscriber.prototype.notifyComplete = function () { + this.emitValue(); + }; + DebounceSubscriber.prototype.emitValue = function () { + if (this.hasValue) { + var value = this.value; + var subscription = this.durationSubscription; + if (subscription) { + this.durationSubscription = undefined; + subscription.unsubscribe(); + this.remove(subscription); + } + this.value = undefined; + this.hasValue = false; + _super.prototype._next.call(this, value); + } + }; + return DebounceSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async PURE_IMPORTS_END */ +function debounceTime(dueTime, scheduler) { + if (scheduler === void 0) { + scheduler = async; + } + return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); }; +} +var DebounceTimeOperator = /*@__PURE__*/ (function () { + function DebounceTimeOperator(dueTime, scheduler) { + this.dueTime = dueTime; + this.scheduler = scheduler; + } + DebounceTimeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler)); + }; + return DebounceTimeOperator; +}()); +var DebounceTimeSubscriber = /*@__PURE__*/ (function (_super) { + __extends(DebounceTimeSubscriber, _super); + function DebounceTimeSubscriber(destination, dueTime, scheduler) { + var _this = _super.call(this, destination) || this; + _this.dueTime = dueTime; + _this.scheduler = scheduler; + _this.debouncedSubscription = null; + _this.lastValue = null; + _this.hasValue = false; + return _this; + } + DebounceTimeSubscriber.prototype._next = function (value) { + this.clearDebounce(); + this.lastValue = value; + this.hasValue = true; + this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext$2, this.dueTime, this)); + }; + DebounceTimeSubscriber.prototype._complete = function () { + this.debouncedNext(); + this.destination.complete(); + }; + DebounceTimeSubscriber.prototype.debouncedNext = function () { + this.clearDebounce(); + if (this.hasValue) { + var lastValue = this.lastValue; + this.lastValue = null; + this.hasValue = false; + this.destination.next(lastValue); + } + }; + DebounceTimeSubscriber.prototype.clearDebounce = function () { + var debouncedSubscription = this.debouncedSubscription; + if (debouncedSubscription !== null) { + this.remove(debouncedSubscription); + debouncedSubscription.unsubscribe(); + this.debouncedSubscription = null; + } + }; + return DebounceTimeSubscriber; +}(Subscriber)); +function dispatchNext$2(subscriber) { + subscriber.debouncedNext(); +} + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function defaultIfEmpty(defaultValue) { + if (defaultValue === void 0) { + defaultValue = null; + } + return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); }; +} +var DefaultIfEmptyOperator = /*@__PURE__*/ (function () { + function DefaultIfEmptyOperator(defaultValue) { + this.defaultValue = defaultValue; + } + DefaultIfEmptyOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue)); + }; + return DefaultIfEmptyOperator; +}()); +var DefaultIfEmptySubscriber = /*@__PURE__*/ (function (_super) { + __extends(DefaultIfEmptySubscriber, _super); + function DefaultIfEmptySubscriber(destination, defaultValue) { + var _this = _super.call(this, destination) || this; + _this.defaultValue = defaultValue; + _this.isEmpty = true; + return _this; + } + DefaultIfEmptySubscriber.prototype._next = function (value) { + this.isEmpty = false; + this.destination.next(value); + }; + DefaultIfEmptySubscriber.prototype._complete = function () { + if (this.isEmpty) { + this.destination.next(this.defaultValue); + } + this.destination.complete(); + }; + return DefaultIfEmptySubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ +function isDate(value) { + return value instanceof Date && !isNaN(+value); +} + +/** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_Subscriber,_Notification PURE_IMPORTS_END */ +function delay(delay, scheduler) { + if (scheduler === void 0) { + scheduler = async; + } + var absoluteDelay = isDate(delay); + var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay); + return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); }; +} +var DelayOperator = /*@__PURE__*/ (function () { + function DelayOperator(delay, scheduler) { + this.delay = delay; + this.scheduler = scheduler; + } + DelayOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler)); + }; + return DelayOperator; +}()); +var DelaySubscriber = /*@__PURE__*/ (function (_super) { + __extends(DelaySubscriber, _super); + function DelaySubscriber(destination, delay, scheduler) { + var _this = _super.call(this, destination) || this; + _this.delay = delay; + _this.scheduler = scheduler; + _this.queue = []; + _this.active = false; + _this.errored = false; + return _this; + } + DelaySubscriber.dispatch = function (state) { + var source = state.source; + var queue = source.queue; + var scheduler = state.scheduler; + var destination = state.destination; + while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) { + queue.shift().notification.observe(destination); + } + if (queue.length > 0) { + var delay_1 = Math.max(0, queue[0].time - scheduler.now()); + this.schedule(state, delay_1); + } + else { + this.unsubscribe(); + source.active = false; + } + }; + DelaySubscriber.prototype._schedule = function (scheduler) { + this.active = true; + var destination = this.destination; + destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, { + source: this, destination: this.destination, scheduler: scheduler + })); + }; + DelaySubscriber.prototype.scheduleNotification = function (notification) { + if (this.errored === true) { + return; + } + var scheduler = this.scheduler; + var message = new DelayMessage(scheduler.now() + this.delay, notification); + this.queue.push(message); + if (this.active === false) { + this._schedule(scheduler); + } + }; + DelaySubscriber.prototype._next = function (value) { + this.scheduleNotification(Notification.createNext(value)); + }; + DelaySubscriber.prototype._error = function (err) { + this.errored = true; + this.queue = []; + this.destination.error(err); + this.unsubscribe(); + }; + DelaySubscriber.prototype._complete = function () { + this.scheduleNotification(Notification.createComplete()); + this.unsubscribe(); + }; + return DelaySubscriber; +}(Subscriber)); +var DelayMessage = /*@__PURE__*/ (function () { + function DelayMessage(time, notification) { + this.time = time; + this.notification = notification; + } + return DelayMessage; +}()); + +/** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +function delayWhen(delayDurationSelector, subscriptionDelay) { + if (subscriptionDelay) { + return function (source) { + return new SubscriptionDelayObservable(source, subscriptionDelay) + .lift(new DelayWhenOperator(delayDurationSelector)); + }; + } + return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); }; +} +var DelayWhenOperator = /*@__PURE__*/ (function () { + function DelayWhenOperator(delayDurationSelector) { + this.delayDurationSelector = delayDurationSelector; + } + DelayWhenOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector)); + }; + return DelayWhenOperator; +}()); +var DelayWhenSubscriber = /*@__PURE__*/ (function (_super) { + __extends(DelayWhenSubscriber, _super); + function DelayWhenSubscriber(destination, delayDurationSelector) { + var _this = _super.call(this, destination) || this; + _this.delayDurationSelector = delayDurationSelector; + _this.completed = false; + _this.delayNotifierSubscriptions = []; + _this.index = 0; + return _this; + } + DelayWhenSubscriber.prototype.notifyNext = function (outerValue, _innerValue, _outerIndex, _innerIndex, innerSub) { + this.destination.next(outerValue); + this.removeSubscription(innerSub); + this.tryComplete(); + }; + DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) { + this._error(error); + }; + DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) { + var value = this.removeSubscription(innerSub); + if (value) { + this.destination.next(value); + } + this.tryComplete(); + }; + DelayWhenSubscriber.prototype._next = function (value) { + var index = this.index++; + try { + var delayNotifier = this.delayDurationSelector(value, index); + if (delayNotifier) { + this.tryDelay(delayNotifier, value); + } + } + catch (err) { + this.destination.error(err); + } + }; + DelayWhenSubscriber.prototype._complete = function () { + this.completed = true; + this.tryComplete(); + this.unsubscribe(); + }; + DelayWhenSubscriber.prototype.removeSubscription = function (subscription) { + subscription.unsubscribe(); + var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription); + if (subscriptionIdx !== -1) { + this.delayNotifierSubscriptions.splice(subscriptionIdx, 1); + } + return subscription.outerValue; + }; + DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) { + var notifierSubscription = subscribeToResult(this, delayNotifier, value); + if (notifierSubscription && !notifierSubscription.closed) { + var destination = this.destination; + destination.add(notifierSubscription); + this.delayNotifierSubscriptions.push(notifierSubscription); + } + }; + DelayWhenSubscriber.prototype.tryComplete = function () { + if (this.completed && this.delayNotifierSubscriptions.length === 0) { + this.destination.complete(); + } + }; + return DelayWhenSubscriber; +}(OuterSubscriber)); +var SubscriptionDelayObservable = /*@__PURE__*/ (function (_super) { + __extends(SubscriptionDelayObservable, _super); + function SubscriptionDelayObservable(source, subscriptionDelay) { + var _this = _super.call(this) || this; + _this.source = source; + _this.subscriptionDelay = subscriptionDelay; + return _this; + } + SubscriptionDelayObservable.prototype._subscribe = function (subscriber) { + this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source)); + }; + return SubscriptionDelayObservable; +}(Observable)); +var SubscriptionDelaySubscriber = /*@__PURE__*/ (function (_super) { + __extends(SubscriptionDelaySubscriber, _super); + function SubscriptionDelaySubscriber(parent, source) { + var _this = _super.call(this) || this; + _this.parent = parent; + _this.source = source; + _this.sourceSubscribed = false; + return _this; + } + SubscriptionDelaySubscriber.prototype._next = function (unused) { + this.subscribeToSource(); + }; + SubscriptionDelaySubscriber.prototype._error = function (err) { + this.unsubscribe(); + this.parent.error(err); + }; + SubscriptionDelaySubscriber.prototype._complete = function () { + this.unsubscribe(); + this.subscribeToSource(); + }; + SubscriptionDelaySubscriber.prototype.subscribeToSource = function () { + if (!this.sourceSubscribed) { + this.sourceSubscribed = true; + this.unsubscribe(); + this.source.subscribe(this.parent); + } + }; + return SubscriptionDelaySubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function dematerialize() { + return function dematerializeOperatorFunction(source) { + return source.lift(new DeMaterializeOperator()); + }; +} +var DeMaterializeOperator = /*@__PURE__*/ (function () { + function DeMaterializeOperator() { + } + DeMaterializeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DeMaterializeSubscriber(subscriber)); + }; + return DeMaterializeOperator; +}()); +var DeMaterializeSubscriber = /*@__PURE__*/ (function (_super) { + __extends(DeMaterializeSubscriber, _super); + function DeMaterializeSubscriber(destination) { + return _super.call(this, destination) || this; + } + DeMaterializeSubscriber.prototype._next = function (value) { + value.observe(this.destination); + }; + return DeMaterializeSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +function distinct(keySelector, flushes) { + return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); }; +} +var DistinctOperator = /*@__PURE__*/ (function () { + function DistinctOperator(keySelector, flushes) { + this.keySelector = keySelector; + this.flushes = flushes; + } + DistinctOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes)); + }; + return DistinctOperator; +}()); +var DistinctSubscriber = /*@__PURE__*/ (function (_super) { + __extends(DistinctSubscriber, _super); + function DistinctSubscriber(destination, keySelector, flushes) { + var _this = _super.call(this, destination) || this; + _this.keySelector = keySelector; + _this.values = new Set(); + if (flushes) { + _this.add(innerSubscribe(flushes, new SimpleInnerSubscriber(_this))); + } + return _this; + } + DistinctSubscriber.prototype.notifyNext = function () { + this.values.clear(); + }; + DistinctSubscriber.prototype.notifyError = function (error) { + this._error(error); + }; + DistinctSubscriber.prototype._next = function (value) { + if (this.keySelector) { + this._useKeySelector(value); + } + else { + this._finalizeNext(value, value); + } + }; + DistinctSubscriber.prototype._useKeySelector = function (value) { + var key; + var destination = this.destination; + try { + key = this.keySelector(value); + } + catch (err) { + destination.error(err); + return; + } + this._finalizeNext(key, value); + }; + DistinctSubscriber.prototype._finalizeNext = function (key, value) { + var values = this.values; + if (!values.has(key)) { + values.add(key); + this.destination.next(value); + } + }; + return DistinctSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function distinctUntilChanged(compare, keySelector) { + return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); }; +} +var DistinctUntilChangedOperator = /*@__PURE__*/ (function () { + function DistinctUntilChangedOperator(compare, keySelector) { + this.compare = compare; + this.keySelector = keySelector; + } + DistinctUntilChangedOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector)); + }; + return DistinctUntilChangedOperator; +}()); +var DistinctUntilChangedSubscriber = /*@__PURE__*/ (function (_super) { + __extends(DistinctUntilChangedSubscriber, _super); + function DistinctUntilChangedSubscriber(destination, compare, keySelector) { + var _this = _super.call(this, destination) || this; + _this.keySelector = keySelector; + _this.hasKey = false; + if (typeof compare === 'function') { + _this.compare = compare; + } + return _this; + } + DistinctUntilChangedSubscriber.prototype.compare = function (x, y) { + return x === y; + }; + DistinctUntilChangedSubscriber.prototype._next = function (value) { + var key; + try { + var keySelector = this.keySelector; + key = keySelector ? keySelector(value) : value; + } + catch (err) { + return this.destination.error(err); + } + var result = false; + if (this.hasKey) { + try { + var compare = this.compare; + result = compare(this.key, key); + } + catch (err) { + return this.destination.error(err); + } + } + else { + this.hasKey = true; + } + if (!result) { + this.key = key; + this.destination.next(value); + } + }; + return DistinctUntilChangedSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _distinctUntilChanged PURE_IMPORTS_END */ +function distinctUntilKeyChanged(key, compare) { + return distinctUntilChanged(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; }); +} + +/** PURE_IMPORTS_START tslib,_util_EmptyError,_Subscriber PURE_IMPORTS_END */ +function throwIfEmpty(errorFactory) { + if (errorFactory === void 0) { + errorFactory = defaultErrorFactory; + } + return function (source) { + return source.lift(new ThrowIfEmptyOperator(errorFactory)); + }; +} +var ThrowIfEmptyOperator = /*@__PURE__*/ (function () { + function ThrowIfEmptyOperator(errorFactory) { + this.errorFactory = errorFactory; + } + ThrowIfEmptyOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory)); + }; + return ThrowIfEmptyOperator; +}()); +var ThrowIfEmptySubscriber = /*@__PURE__*/ (function (_super) { + __extends(ThrowIfEmptySubscriber, _super); + function ThrowIfEmptySubscriber(destination, errorFactory) { + var _this = _super.call(this, destination) || this; + _this.errorFactory = errorFactory; + _this.hasValue = false; + return _this; + } + ThrowIfEmptySubscriber.prototype._next = function (value) { + this.hasValue = true; + this.destination.next(value); + }; + ThrowIfEmptySubscriber.prototype._complete = function () { + if (!this.hasValue) { + var err = void 0; + try { + err = this.errorFactory(); + } + catch (e) { + err = e; + } + this.destination.error(err); + } + else { + return this.destination.complete(); + } + }; + return ThrowIfEmptySubscriber; +}(Subscriber)); +function defaultErrorFactory() { + return new EmptyError(); +} + +/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */ +function take(count) { + return function (source) { + if (count === 0) { + return empty$1(); + } + else { + return source.lift(new TakeOperator(count)); + } + }; +} +var TakeOperator = /*@__PURE__*/ (function () { + function TakeOperator(total) { + this.total = total; + if (this.total < 0) { + throw new ArgumentOutOfRangeError; + } + } + TakeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TakeSubscriber(subscriber, this.total)); + }; + return TakeOperator; +}()); +var TakeSubscriber = /*@__PURE__*/ (function (_super) { + __extends(TakeSubscriber, _super); + function TakeSubscriber(destination, total) { + var _this = _super.call(this, destination) || this; + _this.total = total; + _this.count = 0; + return _this; + } + TakeSubscriber.prototype._next = function (value) { + var total = this.total; + var count = ++this.count; + if (count <= total) { + this.destination.next(value); + if (count === total) { + this.destination.complete(); + this.unsubscribe(); + } + } + }; + return TakeSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _util_ArgumentOutOfRangeError,_filter,_throwIfEmpty,_defaultIfEmpty,_take PURE_IMPORTS_END */ +function elementAt(index, defaultValue) { + if (index < 0) { + throw new ArgumentOutOfRangeError(); + } + var hasDefaultValue = arguments.length >= 2; + return function (source) { + return source.pipe(filter(function (v, i) { return i === index; }), take(1), hasDefaultValue + ? defaultIfEmpty(defaultValue) + : throwIfEmpty(function () { return new ArgumentOutOfRangeError(); })); + }; +} + +/** PURE_IMPORTS_START _observable_concat,_observable_of PURE_IMPORTS_END */ +function endWith() { + var array = []; + for (var _i = 0; _i < arguments.length; _i++) { + array[_i] = arguments[_i]; + } + return function (source) { return concat$1(source, of.apply(void 0, array)); }; +} + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function every$1(predicate, thisArg) { + return function (source) { return source.lift(new EveryOperator(predicate, thisArg, source)); }; +} +var EveryOperator = /*@__PURE__*/ (function () { + function EveryOperator(predicate, thisArg, source) { + this.predicate = predicate; + this.thisArg = thisArg; + this.source = source; + } + EveryOperator.prototype.call = function (observer, source) { + return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source)); + }; + return EveryOperator; +}()); +var EverySubscriber = /*@__PURE__*/ (function (_super) { + __extends(EverySubscriber, _super); + function EverySubscriber(destination, predicate, thisArg, source) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.thisArg = thisArg; + _this.source = source; + _this.index = 0; + _this.thisArg = thisArg || _this; + return _this; + } + EverySubscriber.prototype.notifyComplete = function (everyValueMatch) { + this.destination.next(everyValueMatch); + this.destination.complete(); + }; + EverySubscriber.prototype._next = function (value) { + var result = false; + try { + result = this.predicate.call(this.thisArg, value, this.index++, this.source); + } + catch (err) { + this.destination.error(err); + return; + } + if (!result) { + this.notifyComplete(false); + } + }; + EverySubscriber.prototype._complete = function () { + this.notifyComplete(true); + }; + return EverySubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +function exhaust() { + return function (source) { return source.lift(new SwitchFirstOperator()); }; +} +var SwitchFirstOperator = /*@__PURE__*/ (function () { + function SwitchFirstOperator() { + } + SwitchFirstOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SwitchFirstSubscriber(subscriber)); + }; + return SwitchFirstOperator; +}()); +var SwitchFirstSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SwitchFirstSubscriber, _super); + function SwitchFirstSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.hasCompleted = false; + _this.hasSubscription = false; + return _this; + } + SwitchFirstSubscriber.prototype._next = function (value) { + if (!this.hasSubscription) { + this.hasSubscription = true; + this.add(innerSubscribe(value, new SimpleInnerSubscriber(this))); + } + }; + SwitchFirstSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (!this.hasSubscription) { + this.destination.complete(); + } + }; + SwitchFirstSubscriber.prototype.notifyComplete = function () { + this.hasSubscription = false; + if (this.hasCompleted) { + this.destination.complete(); + } + }; + return SwitchFirstSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */ +function exhaustMap(project, resultSelector) { + if (resultSelector) { + return function (source) { return source.pipe(exhaustMap(function (a, i) { return from(project(a, i)).pipe(map$1(function (b, ii) { return resultSelector(a, b, i, ii); })); })); }; + } + return function (source) { + return source.lift(new ExhaustMapOperator(project)); + }; +} +var ExhaustMapOperator = /*@__PURE__*/ (function () { + function ExhaustMapOperator(project) { + this.project = project; + } + ExhaustMapOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project)); + }; + return ExhaustMapOperator; +}()); +var ExhaustMapSubscriber = /*@__PURE__*/ (function (_super) { + __extends(ExhaustMapSubscriber, _super); + function ExhaustMapSubscriber(destination, project) { + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.hasSubscription = false; + _this.hasCompleted = false; + _this.index = 0; + return _this; + } + ExhaustMapSubscriber.prototype._next = function (value) { + if (!this.hasSubscription) { + this.tryNext(value); + } + }; + ExhaustMapSubscriber.prototype.tryNext = function (value) { + var result; + var index = this.index++; + try { + result = this.project(value, index); + } + catch (err) { + this.destination.error(err); + return; + } + this.hasSubscription = true; + this._innerSub(result); + }; + ExhaustMapSubscriber.prototype._innerSub = function (result) { + var innerSubscriber = new SimpleInnerSubscriber(this); + var destination = this.destination; + destination.add(innerSubscriber); + var innerSubscription = innerSubscribe(result, innerSubscriber); + if (innerSubscription !== innerSubscriber) { + destination.add(innerSubscription); + } + }; + ExhaustMapSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (!this.hasSubscription) { + this.destination.complete(); + } + this.unsubscribe(); + }; + ExhaustMapSubscriber.prototype.notifyNext = function (innerValue) { + this.destination.next(innerValue); + }; + ExhaustMapSubscriber.prototype.notifyError = function (err) { + this.destination.error(err); + }; + ExhaustMapSubscriber.prototype.notifyComplete = function () { + this.hasSubscription = false; + if (this.hasCompleted) { + this.destination.complete(); + } + }; + return ExhaustMapSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +function expand(project, concurrent, scheduler) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent; + return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); }; +} +var ExpandOperator = /*@__PURE__*/ (function () { + function ExpandOperator(project, concurrent, scheduler) { + this.project = project; + this.concurrent = concurrent; + this.scheduler = scheduler; + } + ExpandOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler)); + }; + return ExpandOperator; +}()); +var ExpandSubscriber = /*@__PURE__*/ (function (_super) { + __extends(ExpandSubscriber, _super); + function ExpandSubscriber(destination, project, concurrent, scheduler) { + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.concurrent = concurrent; + _this.scheduler = scheduler; + _this.index = 0; + _this.active = 0; + _this.hasCompleted = false; + if (concurrent < Number.POSITIVE_INFINITY) { + _this.buffer = []; + } + return _this; + } + ExpandSubscriber.dispatch = function (arg) { + var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index; + subscriber.subscribeToProjection(result, value, index); + }; + ExpandSubscriber.prototype._next = function (value) { + var destination = this.destination; + if (destination.closed) { + this._complete(); + return; + } + var index = this.index++; + if (this.active < this.concurrent) { + destination.next(value); + try { + var project = this.project; + var result = project(value, index); + if (!this.scheduler) { + this.subscribeToProjection(result, value, index); + } + else { + var state = { subscriber: this, result: result, value: value, index: index }; + var destination_1 = this.destination; + destination_1.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state)); + } + } + catch (e) { + destination.error(e); + } + } + else { + this.buffer.push(value); + } + }; + ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) { + this.active++; + var destination = this.destination; + destination.add(innerSubscribe(result, new SimpleInnerSubscriber(this))); + }; + ExpandSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (this.hasCompleted && this.active === 0) { + this.destination.complete(); + } + this.unsubscribe(); + }; + ExpandSubscriber.prototype.notifyNext = function (innerValue) { + this._next(innerValue); + }; + ExpandSubscriber.prototype.notifyComplete = function () { + var buffer = this.buffer; + this.active--; + if (buffer && buffer.length > 0) { + this._next(buffer.shift()); + } + if (this.hasCompleted && this.active === 0) { + this.destination.complete(); + } + }; + return ExpandSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber,_Subscription PURE_IMPORTS_END */ +function finalize(callback) { + return function (source) { return source.lift(new FinallyOperator(callback)); }; +} +var FinallyOperator = /*@__PURE__*/ (function () { + function FinallyOperator(callback) { + this.callback = callback; + } + FinallyOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new FinallySubscriber(subscriber, this.callback)); + }; + return FinallyOperator; +}()); +var FinallySubscriber = /*@__PURE__*/ (function (_super) { + __extends(FinallySubscriber, _super); + function FinallySubscriber(destination, callback) { + var _this = _super.call(this, destination) || this; + _this.add(new Subscription(callback)); + return _this; + } + return FinallySubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function find(predicate, thisArg) { + if (typeof predicate !== 'function') { + throw new TypeError('predicate is not a function'); + } + return function (source) { return source.lift(new FindValueOperator(predicate, source, false, thisArg)); }; +} +var FindValueOperator = /*@__PURE__*/ (function () { + function FindValueOperator(predicate, source, yieldIndex, thisArg) { + this.predicate = predicate; + this.source = source; + this.yieldIndex = yieldIndex; + this.thisArg = thisArg; + } + FindValueOperator.prototype.call = function (observer, source) { + return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg)); + }; + return FindValueOperator; +}()); +var FindValueSubscriber = /*@__PURE__*/ (function (_super) { + __extends(FindValueSubscriber, _super); + function FindValueSubscriber(destination, predicate, source, yieldIndex, thisArg) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.source = source; + _this.yieldIndex = yieldIndex; + _this.thisArg = thisArg; + _this.index = 0; + return _this; + } + FindValueSubscriber.prototype.notifyComplete = function (value) { + var destination = this.destination; + destination.next(value); + destination.complete(); + this.unsubscribe(); + }; + FindValueSubscriber.prototype._next = function (value) { + var _a = this, predicate = _a.predicate, thisArg = _a.thisArg; + var index = this.index++; + try { + var result = predicate.call(thisArg || this, value, index, this.source); + if (result) { + this.notifyComplete(this.yieldIndex ? index : value); + } + } + catch (err) { + this.destination.error(err); + } + }; + FindValueSubscriber.prototype._complete = function () { + this.notifyComplete(this.yieldIndex ? -1 : undefined); + }; + return FindValueSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _operators_find PURE_IMPORTS_END */ +function findIndex(predicate, thisArg) { + return function (source) { return source.lift(new FindValueOperator(predicate, source, true, thisArg)); }; +} + +/** PURE_IMPORTS_START _util_EmptyError,_filter,_take,_defaultIfEmpty,_throwIfEmpty,_util_identity PURE_IMPORTS_END */ +function first(predicate, defaultValue) { + var hasDefaultValue = arguments.length >= 2; + return function (source) { return source.pipe(predicate ? filter(function (v, i) { return predicate(v, i, source); }) : identity$1, take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError(); })); }; +} + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function ignoreElements() { + return function ignoreElementsOperatorFunction(source) { + return source.lift(new IgnoreElementsOperator()); + }; +} +var IgnoreElementsOperator = /*@__PURE__*/ (function () { + function IgnoreElementsOperator() { + } + IgnoreElementsOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new IgnoreElementsSubscriber(subscriber)); + }; + return IgnoreElementsOperator; +}()); +var IgnoreElementsSubscriber = /*@__PURE__*/ (function (_super) { + __extends(IgnoreElementsSubscriber, _super); + function IgnoreElementsSubscriber() { + return _super !== null && _super.apply(this, arguments) || this; + } + IgnoreElementsSubscriber.prototype._next = function (unused) { + }; + return IgnoreElementsSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function isEmpty$1() { + return function (source) { return source.lift(new IsEmptyOperator()); }; +} +var IsEmptyOperator = /*@__PURE__*/ (function () { + function IsEmptyOperator() { + } + IsEmptyOperator.prototype.call = function (observer, source) { + return source.subscribe(new IsEmptySubscriber(observer)); + }; + return IsEmptyOperator; +}()); +var IsEmptySubscriber = /*@__PURE__*/ (function (_super) { + __extends(IsEmptySubscriber, _super); + function IsEmptySubscriber(destination) { + return _super.call(this, destination) || this; + } + IsEmptySubscriber.prototype.notifyComplete = function (isEmpty) { + var destination = this.destination; + destination.next(isEmpty); + destination.complete(); + }; + IsEmptySubscriber.prototype._next = function (value) { + this.notifyComplete(false); + }; + IsEmptySubscriber.prototype._complete = function () { + this.notifyComplete(true); + }; + return IsEmptySubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */ +function takeLast(count) { + return function takeLastOperatorFunction(source) { + if (count === 0) { + return empty$1(); + } + else { + return source.lift(new TakeLastOperator(count)); + } + }; +} +var TakeLastOperator = /*@__PURE__*/ (function () { + function TakeLastOperator(total) { + this.total = total; + if (this.total < 0) { + throw new ArgumentOutOfRangeError; + } + } + TakeLastOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TakeLastSubscriber(subscriber, this.total)); + }; + return TakeLastOperator; +}()); +var TakeLastSubscriber = /*@__PURE__*/ (function (_super) { + __extends(TakeLastSubscriber, _super); + function TakeLastSubscriber(destination, total) { + var _this = _super.call(this, destination) || this; + _this.total = total; + _this.ring = new Array(); + _this.count = 0; + return _this; + } + TakeLastSubscriber.prototype._next = function (value) { + var ring = this.ring; + var total = this.total; + var count = this.count++; + if (ring.length < total) { + ring.push(value); + } + else { + var index = count % total; + ring[index] = value; + } + }; + TakeLastSubscriber.prototype._complete = function () { + var destination = this.destination; + var count = this.count; + if (count > 0) { + var total = this.count >= this.total ? this.total : this.count; + var ring = this.ring; + for (var i = 0; i < total; i++) { + var idx = (count++) % total; + destination.next(ring[idx]); + } + } + destination.complete(); + }; + return TakeLastSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _util_EmptyError,_filter,_takeLast,_throwIfEmpty,_defaultIfEmpty,_util_identity PURE_IMPORTS_END */ +function last(predicate, defaultValue) { + var hasDefaultValue = arguments.length >= 2; + return function (source) { return source.pipe(predicate ? filter(function (v, i) { return predicate(v, i, source); }) : identity$1, takeLast(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError(); })); }; +} + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function mapTo(value) { + return function (source) { return source.lift(new MapToOperator(value)); }; +} +var MapToOperator = /*@__PURE__*/ (function () { + function MapToOperator(value) { + this.value = value; + } + MapToOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new MapToSubscriber(subscriber, this.value)); + }; + return MapToOperator; +}()); +var MapToSubscriber = /*@__PURE__*/ (function (_super) { + __extends(MapToSubscriber, _super); + function MapToSubscriber(destination, value) { + var _this = _super.call(this, destination) || this; + _this.value = value; + return _this; + } + MapToSubscriber.prototype._next = function (x) { + this.destination.next(this.value); + }; + return MapToSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */ +function materialize() { + return function materializeOperatorFunction(source) { + return source.lift(new MaterializeOperator()); + }; +} +var MaterializeOperator = /*@__PURE__*/ (function () { + function MaterializeOperator() { + } + MaterializeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new MaterializeSubscriber(subscriber)); + }; + return MaterializeOperator; +}()); +var MaterializeSubscriber = /*@__PURE__*/ (function (_super) { + __extends(MaterializeSubscriber, _super); + function MaterializeSubscriber(destination) { + return _super.call(this, destination) || this; + } + MaterializeSubscriber.prototype._next = function (value) { + this.destination.next(Notification.createNext(value)); + }; + MaterializeSubscriber.prototype._error = function (err) { + var destination = this.destination; + destination.next(Notification.createError(err)); + destination.complete(); + }; + MaterializeSubscriber.prototype._complete = function () { + var destination = this.destination; + destination.next(Notification.createComplete()); + destination.complete(); + }; + return MaterializeSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function scan(accumulator, seed) { + var hasSeed = false; + if (arguments.length >= 2) { + hasSeed = true; + } + return function scanOperatorFunction(source) { + return source.lift(new ScanOperator(accumulator, seed, hasSeed)); + }; +} +var ScanOperator = /*@__PURE__*/ (function () { + function ScanOperator(accumulator, seed, hasSeed) { + if (hasSeed === void 0) { + hasSeed = false; + } + this.accumulator = accumulator; + this.seed = seed; + this.hasSeed = hasSeed; + } + ScanOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed)); + }; + return ScanOperator; +}()); +var ScanSubscriber = /*@__PURE__*/ (function (_super) { + __extends(ScanSubscriber, _super); + function ScanSubscriber(destination, accumulator, _seed, hasSeed) { + var _this = _super.call(this, destination) || this; + _this.accumulator = accumulator; + _this._seed = _seed; + _this.hasSeed = hasSeed; + _this.index = 0; + return _this; + } + Object.defineProperty(ScanSubscriber.prototype, "seed", { + get: function () { + return this._seed; + }, + set: function (value) { + this.hasSeed = true; + this._seed = value; + }, + enumerable: true, + configurable: true + }); + ScanSubscriber.prototype._next = function (value) { + if (!this.hasSeed) { + this.seed = value; + this.destination.next(value); + } + else { + return this._tryNext(value); + } + }; + ScanSubscriber.prototype._tryNext = function (value) { + var index = this.index++; + var result; + try { + result = this.accumulator(this.seed, value, index); + } + catch (err) { + this.destination.error(err); + } + this.seed = result; + this.destination.next(result); + }; + return ScanSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _scan,_takeLast,_defaultIfEmpty,_util_pipe PURE_IMPORTS_END */ +function reduce$1(accumulator, seed) { + if (arguments.length >= 2) { + return function reduceOperatorFunctionWithSeed(source) { + return pipe(scan(accumulator, seed), takeLast(1), defaultIfEmpty(seed))(source); + }; + } + return function reduceOperatorFunction(source) { + return pipe(scan(function (acc, value, index) { return accumulator(acc, value, index + 1); }), takeLast(1))(source); + }; +} + +/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ +function max(comparer) { + var max = (typeof comparer === 'function') + ? function (x, y) { return comparer(x, y) > 0 ? x : y; } + : function (x, y) { return x > y ? x : y; }; + return reduce$1(max); +} + +/** PURE_IMPORTS_START _observable_merge PURE_IMPORTS_END */ +function merge$1() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + return function (source) { return source.lift.call(merge.apply(void 0, [source].concat(observables))); }; +} + +/** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ +function mergeMapTo(innerObservable, resultSelector, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + if (typeof resultSelector === 'function') { + return mergeMap(function () { return innerObservable; }, resultSelector, concurrent); + } + if (typeof resultSelector === 'number') { + concurrent = resultSelector; + } + return mergeMap(function () { return innerObservable; }, concurrent); +} + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +function mergeScan(accumulator, seed, concurrent) { + if (concurrent === void 0) { + concurrent = Number.POSITIVE_INFINITY; + } + return function (source) { return source.lift(new MergeScanOperator(accumulator, seed, concurrent)); }; +} +var MergeScanOperator = /*@__PURE__*/ (function () { + function MergeScanOperator(accumulator, seed, concurrent) { + this.accumulator = accumulator; + this.seed = seed; + this.concurrent = concurrent; + } + MergeScanOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new MergeScanSubscriber(subscriber, this.accumulator, this.seed, this.concurrent)); + }; + return MergeScanOperator; +}()); +var MergeScanSubscriber = /*@__PURE__*/ (function (_super) { + __extends(MergeScanSubscriber, _super); + function MergeScanSubscriber(destination, accumulator, acc, concurrent) { + var _this = _super.call(this, destination) || this; + _this.accumulator = accumulator; + _this.acc = acc; + _this.concurrent = concurrent; + _this.hasValue = false; + _this.hasCompleted = false; + _this.buffer = []; + _this.active = 0; + _this.index = 0; + return _this; + } + MergeScanSubscriber.prototype._next = function (value) { + if (this.active < this.concurrent) { + var index = this.index++; + var destination = this.destination; + var ish = void 0; + try { + var accumulator = this.accumulator; + ish = accumulator(this.acc, value, index); + } + catch (e) { + return destination.error(e); + } + this.active++; + this._innerSub(ish); + } + else { + this.buffer.push(value); + } + }; + MergeScanSubscriber.prototype._innerSub = function (ish) { + var innerSubscriber = new SimpleInnerSubscriber(this); + var destination = this.destination; + destination.add(innerSubscriber); + var innerSubscription = innerSubscribe(ish, innerSubscriber); + if (innerSubscription !== innerSubscriber) { + destination.add(innerSubscription); + } + }; + MergeScanSubscriber.prototype._complete = function () { + this.hasCompleted = true; + if (this.active === 0 && this.buffer.length === 0) { + if (this.hasValue === false) { + this.destination.next(this.acc); + } + this.destination.complete(); + } + this.unsubscribe(); + }; + MergeScanSubscriber.prototype.notifyNext = function (innerValue) { + var destination = this.destination; + this.acc = innerValue; + this.hasValue = true; + destination.next(innerValue); + }; + MergeScanSubscriber.prototype.notifyComplete = function () { + var buffer = this.buffer; + this.active--; + if (buffer.length > 0) { + this._next(buffer.shift()); + } + else if (this.active === 0 && this.hasCompleted) { + if (this.hasValue === false) { + this.destination.next(this.acc); + } + this.destination.complete(); + } + }; + return MergeScanSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ +function min(comparer) { + var min = (typeof comparer === 'function') + ? function (x, y) { return comparer(x, y) < 0 ? x : y; } + : function (x, y) { return x < y ? x : y; }; + return reduce$1(min); +} + +/** PURE_IMPORTS_START _observable_ConnectableObservable PURE_IMPORTS_END */ +function multicast(subjectOrSubjectFactory, selector) { + return function multicastOperatorFunction(source) { + var subjectFactory; + if (typeof subjectOrSubjectFactory === 'function') { + subjectFactory = subjectOrSubjectFactory; + } + else { + subjectFactory = function subjectFactory() { + return subjectOrSubjectFactory; + }; + } + if (typeof selector === 'function') { + return source.lift(new MulticastOperator(subjectFactory, selector)); + } + var connectable = Object.create(source, connectableObservableDescriptor); + connectable.source = source; + connectable.subjectFactory = subjectFactory; + return connectable; + }; +} +var MulticastOperator = /*@__PURE__*/ (function () { + function MulticastOperator(subjectFactory, selector) { + this.subjectFactory = subjectFactory; + this.selector = selector; + } + MulticastOperator.prototype.call = function (subscriber, source) { + var selector = this.selector; + var subject = this.subjectFactory(); + var subscription = selector(subject).subscribe(subscriber); + subscription.add(source.subscribe(subject)); + return subscription; + }; + return MulticastOperator; +}()); + +/** PURE_IMPORTS_START tslib,_observable_from,_util_isArray,_innerSubscribe PURE_IMPORTS_END */ +function onErrorResumeNext$1() { + var nextSources = []; + for (var _i = 0; _i < arguments.length; _i++) { + nextSources[_i] = arguments[_i]; + } + if (nextSources.length === 1 && isArray$1(nextSources[0])) { + nextSources = nextSources[0]; + } + return function (source) { return source.lift(new OnErrorResumeNextOperator(nextSources)); }; +} +var OnErrorResumeNextOperator = /*@__PURE__*/ (function () { + function OnErrorResumeNextOperator(nextSources) { + this.nextSources = nextSources; + } + OnErrorResumeNextOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources)); + }; + return OnErrorResumeNextOperator; +}()); +var OnErrorResumeNextSubscriber = /*@__PURE__*/ (function (_super) { + __extends(OnErrorResumeNextSubscriber, _super); + function OnErrorResumeNextSubscriber(destination, nextSources) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + _this.nextSources = nextSources; + return _this; + } + OnErrorResumeNextSubscriber.prototype.notifyError = function () { + this.subscribeToNextSource(); + }; + OnErrorResumeNextSubscriber.prototype.notifyComplete = function () { + this.subscribeToNextSource(); + }; + OnErrorResumeNextSubscriber.prototype._error = function (err) { + this.subscribeToNextSource(); + this.unsubscribe(); + }; + OnErrorResumeNextSubscriber.prototype._complete = function () { + this.subscribeToNextSource(); + this.unsubscribe(); + }; + OnErrorResumeNextSubscriber.prototype.subscribeToNextSource = function () { + var next = this.nextSources.shift(); + if (!!next) { + var innerSubscriber = new SimpleInnerSubscriber(this); + var destination = this.destination; + destination.add(innerSubscriber); + var innerSubscription = innerSubscribe(next, innerSubscriber); + if (innerSubscription !== innerSubscriber) { + destination.add(innerSubscription); + } + } + else { + this.destination.complete(); + } + }; + return OnErrorResumeNextSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function pairwise() { + return function (source) { return source.lift(new PairwiseOperator()); }; +} +var PairwiseOperator = /*@__PURE__*/ (function () { + function PairwiseOperator() { + } + PairwiseOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new PairwiseSubscriber(subscriber)); + }; + return PairwiseOperator; +}()); +var PairwiseSubscriber = /*@__PURE__*/ (function (_super) { + __extends(PairwiseSubscriber, _super); + function PairwiseSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.hasPrev = false; + return _this; + } + PairwiseSubscriber.prototype._next = function (value) { + var pair; + if (this.hasPrev) { + pair = [this.prev, value]; + } + else { + this.hasPrev = true; + } + this.prev = value; + if (pair) { + this.destination.next(pair); + } + }; + return PairwiseSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _util_not,_filter PURE_IMPORTS_END */ +function partition$1(predicate, thisArg) { + return function (source) { + return [ + filter(predicate, thisArg)(source), + filter(not(predicate, thisArg))(source) + ]; + }; +} + +/** PURE_IMPORTS_START _map PURE_IMPORTS_END */ +function pluck() { + var properties = []; + for (var _i = 0; _i < arguments.length; _i++) { + properties[_i] = arguments[_i]; + } + var length = properties.length; + if (length === 0) { + throw new Error('list of properties cannot be empty.'); + } + return function (source) { return map$1(plucker(properties, length))(source); }; +} +function plucker(props, length) { + var mapper = function (x) { + var currentProp = x; + for (var i = 0; i < length; i++) { + var p = currentProp != null ? currentProp[props[i]] : undefined; + if (p !== void 0) { + currentProp = p; + } + else { + return undefined; + } + } + return currentProp; + }; + return mapper; +} + +/** PURE_IMPORTS_START _Subject,_multicast PURE_IMPORTS_END */ +function publish(selector) { + return selector ? + multicast(function () { return new Subject(); }, selector) : + multicast(new Subject()); +} + +/** PURE_IMPORTS_START _BehaviorSubject,_multicast PURE_IMPORTS_END */ +function publishBehavior(value) { + return function (source) { return multicast(new BehaviorSubject(value))(source); }; +} + +/** PURE_IMPORTS_START _AsyncSubject,_multicast PURE_IMPORTS_END */ +function publishLast() { + return function (source) { return multicast(new AsyncSubject())(source); }; +} + +/** PURE_IMPORTS_START _ReplaySubject,_multicast PURE_IMPORTS_END */ +function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) { + if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') { + scheduler = selectorOrScheduler; + } + var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined; + var subject = new ReplaySubject(bufferSize, windowTime, scheduler); + return function (source) { return multicast(function () { return subject; }, selector)(source); }; +} + +/** PURE_IMPORTS_START _util_isArray,_observable_race PURE_IMPORTS_END */ +function race$1() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + return function raceOperatorFunction(source) { + if (observables.length === 1 && isArray$1(observables[0])) { + observables = observables[0]; + } + return source.lift.call(race.apply(void 0, [source].concat(observables))); + }; +} + +/** PURE_IMPORTS_START tslib,_Subscriber,_observable_empty PURE_IMPORTS_END */ +function repeat(count) { + if (count === void 0) { + count = -1; + } + return function (source) { + if (count === 0) { + return empty$1(); + } + else if (count < 0) { + return source.lift(new RepeatOperator(-1, source)); + } + else { + return source.lift(new RepeatOperator(count - 1, source)); + } + }; +} +var RepeatOperator = /*@__PURE__*/ (function () { + function RepeatOperator(count, source) { + this.count = count; + this.source = source; + } + RepeatOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source)); + }; + return RepeatOperator; +}()); +var RepeatSubscriber = /*@__PURE__*/ (function (_super) { + __extends(RepeatSubscriber, _super); + function RepeatSubscriber(destination, count, source) { + var _this = _super.call(this, destination) || this; + _this.count = count; + _this.source = source; + return _this; + } + RepeatSubscriber.prototype.complete = function () { + if (!this.isStopped) { + var _a = this, source = _a.source, count = _a.count; + if (count === 0) { + return _super.prototype.complete.call(this); + } + else if (count > -1) { + this.count = count - 1; + } + source.subscribe(this._unsubscribeAndRecycle()); + } + }; + return RepeatSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subject,_innerSubscribe PURE_IMPORTS_END */ +function repeatWhen(notifier) { + return function (source) { return source.lift(new RepeatWhenOperator(notifier)); }; +} +var RepeatWhenOperator = /*@__PURE__*/ (function () { + function RepeatWhenOperator(notifier) { + this.notifier = notifier; + } + RepeatWhenOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source)); + }; + return RepeatWhenOperator; +}()); +var RepeatWhenSubscriber = /*@__PURE__*/ (function (_super) { + __extends(RepeatWhenSubscriber, _super); + function RepeatWhenSubscriber(destination, notifier, source) { + var _this = _super.call(this, destination) || this; + _this.notifier = notifier; + _this.source = source; + _this.sourceIsBeingSubscribedTo = true; + return _this; + } + RepeatWhenSubscriber.prototype.notifyNext = function () { + this.sourceIsBeingSubscribedTo = true; + this.source.subscribe(this); + }; + RepeatWhenSubscriber.prototype.notifyComplete = function () { + if (this.sourceIsBeingSubscribedTo === false) { + return _super.prototype.complete.call(this); + } + }; + RepeatWhenSubscriber.prototype.complete = function () { + this.sourceIsBeingSubscribedTo = false; + if (!this.isStopped) { + if (!this.retries) { + this.subscribeToRetries(); + } + if (!this.retriesSubscription || this.retriesSubscription.closed) { + return _super.prototype.complete.call(this); + } + this._unsubscribeAndRecycle(); + this.notifications.next(undefined); + } + }; + RepeatWhenSubscriber.prototype._unsubscribe = function () { + var _a = this, notifications = _a.notifications, retriesSubscription = _a.retriesSubscription; + if (notifications) { + notifications.unsubscribe(); + this.notifications = undefined; + } + if (retriesSubscription) { + retriesSubscription.unsubscribe(); + this.retriesSubscription = undefined; + } + this.retries = undefined; + }; + RepeatWhenSubscriber.prototype._unsubscribeAndRecycle = function () { + var _unsubscribe = this._unsubscribe; + this._unsubscribe = null; + _super.prototype._unsubscribeAndRecycle.call(this); + this._unsubscribe = _unsubscribe; + return this; + }; + RepeatWhenSubscriber.prototype.subscribeToRetries = function () { + this.notifications = new Subject(); + var retries; + try { + var notifier = this.notifier; + retries = notifier(this.notifications); + } + catch (e) { + return _super.prototype.complete.call(this); + } + this.retries = retries; + this.retriesSubscription = innerSubscribe(retries, new SimpleInnerSubscriber(this)); + }; + return RepeatWhenSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function retry(count) { + if (count === void 0) { + count = -1; + } + return function (source) { return source.lift(new RetryOperator(count, source)); }; +} +var RetryOperator = /*@__PURE__*/ (function () { + function RetryOperator(count, source) { + this.count = count; + this.source = source; + } + RetryOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source)); + }; + return RetryOperator; +}()); +var RetrySubscriber = /*@__PURE__*/ (function (_super) { + __extends(RetrySubscriber, _super); + function RetrySubscriber(destination, count, source) { + var _this = _super.call(this, destination) || this; + _this.count = count; + _this.source = source; + return _this; + } + RetrySubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var _a = this, source = _a.source, count = _a.count; + if (count === 0) { + return _super.prototype.error.call(this, err); + } + else if (count > -1) { + this.count = count - 1; + } + source.subscribe(this._unsubscribeAndRecycle()); + } + }; + return RetrySubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subject,_innerSubscribe PURE_IMPORTS_END */ +function retryWhen(notifier) { + return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); }; +} +var RetryWhenOperator = /*@__PURE__*/ (function () { + function RetryWhenOperator(notifier, source) { + this.notifier = notifier; + this.source = source; + } + RetryWhenOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source)); + }; + return RetryWhenOperator; +}()); +var RetryWhenSubscriber = /*@__PURE__*/ (function (_super) { + __extends(RetryWhenSubscriber, _super); + function RetryWhenSubscriber(destination, notifier, source) { + var _this = _super.call(this, destination) || this; + _this.notifier = notifier; + _this.source = source; + return _this; + } + RetryWhenSubscriber.prototype.error = function (err) { + if (!this.isStopped) { + var errors = this.errors; + var retries = this.retries; + var retriesSubscription = this.retriesSubscription; + if (!retries) { + errors = new Subject(); + try { + var notifier = this.notifier; + retries = notifier(errors); + } + catch (e) { + return _super.prototype.error.call(this, e); + } + retriesSubscription = innerSubscribe(retries, new SimpleInnerSubscriber(this)); + } + else { + this.errors = undefined; + this.retriesSubscription = undefined; + } + this._unsubscribeAndRecycle(); + this.errors = errors; + this.retries = retries; + this.retriesSubscription = retriesSubscription; + errors.next(err); + } + }; + RetryWhenSubscriber.prototype._unsubscribe = function () { + var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription; + if (errors) { + errors.unsubscribe(); + this.errors = undefined; + } + if (retriesSubscription) { + retriesSubscription.unsubscribe(); + this.retriesSubscription = undefined; + } + this.retries = undefined; + }; + RetryWhenSubscriber.prototype.notifyNext = function () { + var _unsubscribe = this._unsubscribe; + this._unsubscribe = null; + this._unsubscribeAndRecycle(); + this._unsubscribe = _unsubscribe; + this.source.subscribe(this); + }; + return RetryWhenSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +function sample(notifier) { + return function (source) { return source.lift(new SampleOperator(notifier)); }; +} +var SampleOperator = /*@__PURE__*/ (function () { + function SampleOperator(notifier) { + this.notifier = notifier; + } + SampleOperator.prototype.call = function (subscriber, source) { + var sampleSubscriber = new SampleSubscriber(subscriber); + var subscription = source.subscribe(sampleSubscriber); + subscription.add(innerSubscribe(this.notifier, new SimpleInnerSubscriber(sampleSubscriber))); + return subscription; + }; + return SampleOperator; +}()); +var SampleSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SampleSubscriber, _super); + function SampleSubscriber() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this.hasValue = false; + return _this; + } + SampleSubscriber.prototype._next = function (value) { + this.value = value; + this.hasValue = true; + }; + SampleSubscriber.prototype.notifyNext = function () { + this.emitValue(); + }; + SampleSubscriber.prototype.notifyComplete = function () { + this.emitValue(); + }; + SampleSubscriber.prototype.emitValue = function () { + if (this.hasValue) { + this.hasValue = false; + this.destination.next(this.value); + } + }; + return SampleSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async PURE_IMPORTS_END */ +function sampleTime(period, scheduler) { + if (scheduler === void 0) { + scheduler = async; + } + return function (source) { return source.lift(new SampleTimeOperator(period, scheduler)); }; +} +var SampleTimeOperator = /*@__PURE__*/ (function () { + function SampleTimeOperator(period, scheduler) { + this.period = period; + this.scheduler = scheduler; + } + SampleTimeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler)); + }; + return SampleTimeOperator; +}()); +var SampleTimeSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SampleTimeSubscriber, _super); + function SampleTimeSubscriber(destination, period, scheduler) { + var _this = _super.call(this, destination) || this; + _this.period = period; + _this.scheduler = scheduler; + _this.hasValue = false; + _this.add(scheduler.schedule(dispatchNotification, period, { subscriber: _this, period: period })); + return _this; + } + SampleTimeSubscriber.prototype._next = function (value) { + this.lastValue = value; + this.hasValue = true; + }; + SampleTimeSubscriber.prototype.notifyNext = function () { + if (this.hasValue) { + this.hasValue = false; + this.destination.next(this.lastValue); + } + }; + return SampleTimeSubscriber; +}(Subscriber)); +function dispatchNotification(state) { + var subscriber = state.subscriber, period = state.period; + subscriber.notifyNext(); + this.schedule(state, period); +} + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function sequenceEqual(compareTo, comparator) { + return function (source) { return source.lift(new SequenceEqualOperator(compareTo, comparator)); }; +} +var SequenceEqualOperator = /*@__PURE__*/ (function () { + function SequenceEqualOperator(compareTo, comparator) { + this.compareTo = compareTo; + this.comparator = comparator; + } + SequenceEqualOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparator)); + }; + return SequenceEqualOperator; +}()); +var SequenceEqualSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SequenceEqualSubscriber, _super); + function SequenceEqualSubscriber(destination, compareTo, comparator) { + var _this = _super.call(this, destination) || this; + _this.compareTo = compareTo; + _this.comparator = comparator; + _this._a = []; + _this._b = []; + _this._oneComplete = false; + _this.destination.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, _this))); + return _this; + } + SequenceEqualSubscriber.prototype._next = function (value) { + if (this._oneComplete && this._b.length === 0) { + this.emit(false); + } + else { + this._a.push(value); + this.checkValues(); + } + }; + SequenceEqualSubscriber.prototype._complete = function () { + if (this._oneComplete) { + this.emit(this._a.length === 0 && this._b.length === 0); + } + else { + this._oneComplete = true; + } + this.unsubscribe(); + }; + SequenceEqualSubscriber.prototype.checkValues = function () { + var _c = this, _a = _c._a, _b = _c._b, comparator = _c.comparator; + while (_a.length > 0 && _b.length > 0) { + var a = _a.shift(); + var b = _b.shift(); + var areEqual = false; + try { + areEqual = comparator ? comparator(a, b) : a === b; + } + catch (e) { + this.destination.error(e); + } + if (!areEqual) { + this.emit(false); + } + } + }; + SequenceEqualSubscriber.prototype.emit = function (value) { + var destination = this.destination; + destination.next(value); + destination.complete(); + }; + SequenceEqualSubscriber.prototype.nextB = function (value) { + if (this._oneComplete && this._a.length === 0) { + this.emit(false); + } + else { + this._b.push(value); + this.checkValues(); + } + }; + SequenceEqualSubscriber.prototype.completeB = function () { + if (this._oneComplete) { + this.emit(this._a.length === 0 && this._b.length === 0); + } + else { + this._oneComplete = true; + } + }; + return SequenceEqualSubscriber; +}(Subscriber)); +var SequenceEqualCompareToSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SequenceEqualCompareToSubscriber, _super); + function SequenceEqualCompareToSubscriber(destination, parent) { + var _this = _super.call(this, destination) || this; + _this.parent = parent; + return _this; + } + SequenceEqualCompareToSubscriber.prototype._next = function (value) { + this.parent.nextB(value); + }; + SequenceEqualCompareToSubscriber.prototype._error = function (err) { + this.parent.error(err); + this.unsubscribe(); + }; + SequenceEqualCompareToSubscriber.prototype._complete = function () { + this.parent.completeB(); + this.unsubscribe(); + }; + return SequenceEqualCompareToSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _multicast,_refCount,_Subject PURE_IMPORTS_END */ +function shareSubjectFactory() { + return new Subject(); +} +function share() { + return function (source) { return refCount()(multicast(shareSubjectFactory)(source)); }; +} + +/** PURE_IMPORTS_START _ReplaySubject PURE_IMPORTS_END */ +function shareReplay(configOrBufferSize, windowTime, scheduler) { + var config; + if (configOrBufferSize && typeof configOrBufferSize === 'object') { + config = configOrBufferSize; + } + else { + config = { + bufferSize: configOrBufferSize, + windowTime: windowTime, + refCount: false, + scheduler: scheduler, + }; + } + return function (source) { return source.lift(shareReplayOperator(config)); }; +} +function shareReplayOperator(_a) { + var _b = _a.bufferSize, bufferSize = _b === void 0 ? Number.POSITIVE_INFINITY : _b, _c = _a.windowTime, windowTime = _c === void 0 ? Number.POSITIVE_INFINITY : _c, useRefCount = _a.refCount, scheduler = _a.scheduler; + var subject; + var refCount = 0; + var subscription; + var hasError = false; + var isComplete = false; + return function shareReplayOperation(source) { + refCount++; + var innerSub; + if (!subject || hasError) { + hasError = false; + subject = new ReplaySubject(bufferSize, windowTime, scheduler); + innerSub = subject.subscribe(this); + subscription = source.subscribe({ + next: function (value) { + subject.next(value); + }, + error: function (err) { + hasError = true; + subject.error(err); + }, + complete: function () { + isComplete = true; + subscription = undefined; + subject.complete(); + }, + }); + if (isComplete) { + subscription = undefined; + } + } + else { + innerSub = subject.subscribe(this); + } + this.add(function () { + refCount--; + innerSub.unsubscribe(); + innerSub = undefined; + if (subscription && !isComplete && useRefCount && refCount === 0) { + subscription.unsubscribe(); + subscription = undefined; + subject = undefined; + } + }); + }; +} + +/** PURE_IMPORTS_START tslib,_Subscriber,_util_EmptyError PURE_IMPORTS_END */ +function single(predicate) { + return function (source) { return source.lift(new SingleOperator(predicate, source)); }; +} +var SingleOperator = /*@__PURE__*/ (function () { + function SingleOperator(predicate, source) { + this.predicate = predicate; + this.source = source; + } + SingleOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source)); + }; + return SingleOperator; +}()); +var SingleSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SingleSubscriber, _super); + function SingleSubscriber(destination, predicate, source) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.source = source; + _this.seenValue = false; + _this.index = 0; + return _this; + } + SingleSubscriber.prototype.applySingleValue = function (value) { + if (this.seenValue) { + this.destination.error('Sequence contains more than one element'); + } + else { + this.seenValue = true; + this.singleValue = value; + } + }; + SingleSubscriber.prototype._next = function (value) { + var index = this.index++; + if (this.predicate) { + this.tryNext(value, index); + } + else { + this.applySingleValue(value); + } + }; + SingleSubscriber.prototype.tryNext = function (value, index) { + try { + if (this.predicate(value, index, this.source)) { + this.applySingleValue(value); + } + } + catch (err) { + this.destination.error(err); + } + }; + SingleSubscriber.prototype._complete = function () { + var destination = this.destination; + if (this.index > 0) { + destination.next(this.seenValue ? this.singleValue : undefined); + destination.complete(); + } + else { + destination.error(new EmptyError); + } + }; + return SingleSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function skip(count) { + return function (source) { return source.lift(new SkipOperator(count)); }; +} +var SkipOperator = /*@__PURE__*/ (function () { + function SkipOperator(total) { + this.total = total; + } + SkipOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SkipSubscriber(subscriber, this.total)); + }; + return SkipOperator; +}()); +var SkipSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SkipSubscriber, _super); + function SkipSubscriber(destination, total) { + var _this = _super.call(this, destination) || this; + _this.total = total; + _this.count = 0; + return _this; + } + SkipSubscriber.prototype._next = function (x) { + if (++this.count > this.total) { + this.destination.next(x); + } + }; + return SkipSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError PURE_IMPORTS_END */ +function skipLast(count) { + return function (source) { return source.lift(new SkipLastOperator(count)); }; +} +var SkipLastOperator = /*@__PURE__*/ (function () { + function SkipLastOperator(_skipCount) { + this._skipCount = _skipCount; + if (this._skipCount < 0) { + throw new ArgumentOutOfRangeError; + } + } + SkipLastOperator.prototype.call = function (subscriber, source) { + if (this._skipCount === 0) { + return source.subscribe(new Subscriber(subscriber)); + } + else { + return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount)); + } + }; + return SkipLastOperator; +}()); +var SkipLastSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SkipLastSubscriber, _super); + function SkipLastSubscriber(destination, _skipCount) { + var _this = _super.call(this, destination) || this; + _this._skipCount = _skipCount; + _this._count = 0; + _this._ring = new Array(_skipCount); + return _this; + } + SkipLastSubscriber.prototype._next = function (value) { + var skipCount = this._skipCount; + var count = this._count++; + if (count < skipCount) { + this._ring[count] = value; + } + else { + var currentIndex = count % skipCount; + var ring = this._ring; + var oldValue = ring[currentIndex]; + ring[currentIndex] = value; + this.destination.next(oldValue); + } + }; + return SkipLastSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +function skipUntil(notifier) { + return function (source) { return source.lift(new SkipUntilOperator(notifier)); }; +} +var SkipUntilOperator = /*@__PURE__*/ (function () { + function SkipUntilOperator(notifier) { + this.notifier = notifier; + } + SkipUntilOperator.prototype.call = function (destination, source) { + return source.subscribe(new SkipUntilSubscriber(destination, this.notifier)); + }; + return SkipUntilOperator; +}()); +var SkipUntilSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SkipUntilSubscriber, _super); + function SkipUntilSubscriber(destination, notifier) { + var _this = _super.call(this, destination) || this; + _this.hasValue = false; + var innerSubscriber = new SimpleInnerSubscriber(_this); + _this.add(innerSubscriber); + _this.innerSubscription = innerSubscriber; + var innerSubscription = innerSubscribe(notifier, innerSubscriber); + if (innerSubscription !== innerSubscriber) { + _this.add(innerSubscription); + _this.innerSubscription = innerSubscription; + } + return _this; + } + SkipUntilSubscriber.prototype._next = function (value) { + if (this.hasValue) { + _super.prototype._next.call(this, value); + } + }; + SkipUntilSubscriber.prototype.notifyNext = function () { + this.hasValue = true; + if (this.innerSubscription) { + this.innerSubscription.unsubscribe(); + } + }; + SkipUntilSubscriber.prototype.notifyComplete = function () { + }; + return SkipUntilSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function skipWhile(predicate) { + return function (source) { return source.lift(new SkipWhileOperator(predicate)); }; +} +var SkipWhileOperator = /*@__PURE__*/ (function () { + function SkipWhileOperator(predicate) { + this.predicate = predicate; + } + SkipWhileOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate)); + }; + return SkipWhileOperator; +}()); +var SkipWhileSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SkipWhileSubscriber, _super); + function SkipWhileSubscriber(destination, predicate) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.skipping = true; + _this.index = 0; + return _this; + } + SkipWhileSubscriber.prototype._next = function (value) { + var destination = this.destination; + if (this.skipping) { + this.tryCallPredicate(value); + } + if (!this.skipping) { + destination.next(value); + } + }; + SkipWhileSubscriber.prototype.tryCallPredicate = function (value) { + try { + var result = this.predicate(value, this.index++); + this.skipping = Boolean(result); + } + catch (err) { + this.destination.error(err); + } + }; + return SkipWhileSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START _observable_concat,_util_isScheduler PURE_IMPORTS_END */ +function startWith() { + var array = []; + for (var _i = 0; _i < arguments.length; _i++) { + array[_i] = arguments[_i]; + } + var scheduler = array[array.length - 1]; + if (isScheduler(scheduler)) { + array.pop(); + return function (source) { return concat$1(array, source, scheduler); }; + } + else { + return function (source) { return concat$1(array, source); }; + } +} + +/** PURE_IMPORTS_START tslib,_Observable,_scheduler_asap,_util_isNumeric PURE_IMPORTS_END */ +var SubscribeOnObservable = /*@__PURE__*/ (function (_super) { + __extends(SubscribeOnObservable, _super); + function SubscribeOnObservable(source, delayTime, scheduler) { + if (delayTime === void 0) { + delayTime = 0; + } + if (scheduler === void 0) { + scheduler = asap; + } + var _this = _super.call(this) || this; + _this.source = source; + _this.delayTime = delayTime; + _this.scheduler = scheduler; + if (!isNumeric(delayTime) || delayTime < 0) { + _this.delayTime = 0; + } + if (!scheduler || typeof scheduler.schedule !== 'function') { + _this.scheduler = asap; + } + return _this; + } + SubscribeOnObservable.create = function (source, delay, scheduler) { + if (delay === void 0) { + delay = 0; + } + if (scheduler === void 0) { + scheduler = asap; + } + return new SubscribeOnObservable(source, delay, scheduler); + }; + SubscribeOnObservable.dispatch = function (arg) { + var source = arg.source, subscriber = arg.subscriber; + return this.add(source.subscribe(subscriber)); + }; + SubscribeOnObservable.prototype._subscribe = function (subscriber) { + var delay = this.delayTime; + var source = this.source; + var scheduler = this.scheduler; + return scheduler.schedule(SubscribeOnObservable.dispatch, delay, { + source: source, subscriber: subscriber + }); + }; + return SubscribeOnObservable; +}(Observable)); + +/** PURE_IMPORTS_START _observable_SubscribeOnObservable PURE_IMPORTS_END */ +function subscribeOn(scheduler, delay) { + if (delay === void 0) { + delay = 0; + } + return function subscribeOnOperatorFunction(source) { + return source.lift(new SubscribeOnOperator(scheduler, delay)); + }; +} +var SubscribeOnOperator = /*@__PURE__*/ (function () { + function SubscribeOnOperator(scheduler, delay) { + this.scheduler = scheduler; + this.delay = delay; + } + SubscribeOnOperator.prototype.call = function (subscriber, source) { + return new SubscribeOnObservable(source, this.delay, this.scheduler).subscribe(subscriber); + }; + return SubscribeOnOperator; +}()); + +/** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */ +function switchMap(project, resultSelector) { + if (typeof resultSelector === 'function') { + return function (source) { return source.pipe(switchMap(function (a, i) { return from(project(a, i)).pipe(map$1(function (b, ii) { return resultSelector(a, b, i, ii); })); })); }; + } + return function (source) { return source.lift(new SwitchMapOperator(project)); }; +} +var SwitchMapOperator = /*@__PURE__*/ (function () { + function SwitchMapOperator(project) { + this.project = project; + } + SwitchMapOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new SwitchMapSubscriber(subscriber, this.project)); + }; + return SwitchMapOperator; +}()); +var SwitchMapSubscriber = /*@__PURE__*/ (function (_super) { + __extends(SwitchMapSubscriber, _super); + function SwitchMapSubscriber(destination, project) { + var _this = _super.call(this, destination) || this; + _this.project = project; + _this.index = 0; + return _this; + } + SwitchMapSubscriber.prototype._next = function (value) { + var result; + var index = this.index++; + try { + result = this.project(value, index); + } + catch (error) { + this.destination.error(error); + return; + } + this._innerSub(result); + }; + SwitchMapSubscriber.prototype._innerSub = function (result) { + var innerSubscription = this.innerSubscription; + if (innerSubscription) { + innerSubscription.unsubscribe(); + } + var innerSubscriber = new SimpleInnerSubscriber(this); + var destination = this.destination; + destination.add(innerSubscriber); + this.innerSubscription = innerSubscribe(result, innerSubscriber); + if (this.innerSubscription !== innerSubscriber) { + destination.add(this.innerSubscription); + } + }; + SwitchMapSubscriber.prototype._complete = function () { + var innerSubscription = this.innerSubscription; + if (!innerSubscription || innerSubscription.closed) { + _super.prototype._complete.call(this); + } + this.unsubscribe(); + }; + SwitchMapSubscriber.prototype._unsubscribe = function () { + this.innerSubscription = undefined; + }; + SwitchMapSubscriber.prototype.notifyComplete = function () { + this.innerSubscription = undefined; + if (this.isStopped) { + _super.prototype._complete.call(this); + } + }; + SwitchMapSubscriber.prototype.notifyNext = function (innerValue) { + this.destination.next(innerValue); + }; + return SwitchMapSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START _switchMap,_util_identity PURE_IMPORTS_END */ +function switchAll() { + return switchMap(identity$1); +} + +/** PURE_IMPORTS_START _switchMap PURE_IMPORTS_END */ +function switchMapTo(innerObservable, resultSelector) { + return resultSelector ? switchMap(function () { return innerObservable; }, resultSelector) : switchMap(function () { return innerObservable; }); +} + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +function takeUntil(notifier) { + return function (source) { return source.lift(new TakeUntilOperator(notifier)); }; +} +var TakeUntilOperator = /*@__PURE__*/ (function () { + function TakeUntilOperator(notifier) { + this.notifier = notifier; + } + TakeUntilOperator.prototype.call = function (subscriber, source) { + var takeUntilSubscriber = new TakeUntilSubscriber(subscriber); + var notifierSubscription = innerSubscribe(this.notifier, new SimpleInnerSubscriber(takeUntilSubscriber)); + if (notifierSubscription && !takeUntilSubscriber.seenValue) { + takeUntilSubscriber.add(notifierSubscription); + return source.subscribe(takeUntilSubscriber); + } + return takeUntilSubscriber; + }; + return TakeUntilOperator; +}()); +var TakeUntilSubscriber = /*@__PURE__*/ (function (_super) { + __extends(TakeUntilSubscriber, _super); + function TakeUntilSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.seenValue = false; + return _this; + } + TakeUntilSubscriber.prototype.notifyNext = function () { + this.seenValue = true; + this.complete(); + }; + TakeUntilSubscriber.prototype.notifyComplete = function () { + }; + return TakeUntilSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ +function takeWhile(predicate, inclusive) { + if (inclusive === void 0) { + inclusive = false; + } + return function (source) { + return source.lift(new TakeWhileOperator(predicate, inclusive)); + }; +} +var TakeWhileOperator = /*@__PURE__*/ (function () { + function TakeWhileOperator(predicate, inclusive) { + this.predicate = predicate; + this.inclusive = inclusive; + } + TakeWhileOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate, this.inclusive)); + }; + return TakeWhileOperator; +}()); +var TakeWhileSubscriber = /*@__PURE__*/ (function (_super) { + __extends(TakeWhileSubscriber, _super); + function TakeWhileSubscriber(destination, predicate, inclusive) { + var _this = _super.call(this, destination) || this; + _this.predicate = predicate; + _this.inclusive = inclusive; + _this.index = 0; + return _this; + } + TakeWhileSubscriber.prototype._next = function (value) { + var destination = this.destination; + var result; + try { + result = this.predicate(value, this.index++); + } + catch (err) { + destination.error(err); + return; + } + this.nextOrComplete(value, result); + }; + TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) { + var destination = this.destination; + if (Boolean(predicateResult)) { + destination.next(value); + } + else { + if (this.inclusive) { + destination.next(value); + } + destination.complete(); + } + }; + return TakeWhileSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber,_util_noop,_util_isFunction PURE_IMPORTS_END */ +function tap(nextOrObserver, error, complete) { + return function tapOperatorFunction(source) { + return source.lift(new DoOperator(nextOrObserver, error, complete)); + }; +} +var DoOperator = /*@__PURE__*/ (function () { + function DoOperator(nextOrObserver, error, complete) { + this.nextOrObserver = nextOrObserver; + this.error = error; + this.complete = complete; + } + DoOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete)); + }; + return DoOperator; +}()); +var TapSubscriber = /*@__PURE__*/ (function (_super) { + __extends(TapSubscriber, _super); + function TapSubscriber(destination, observerOrNext, error, complete) { + var _this = _super.call(this, destination) || this; + _this._tapNext = noop; + _this._tapError = noop; + _this._tapComplete = noop; + _this._tapError = error || noop; + _this._tapComplete = complete || noop; + if (isFunction$1(observerOrNext)) { + _this._context = _this; + _this._tapNext = observerOrNext; + } + else if (observerOrNext) { + _this._context = observerOrNext; + _this._tapNext = observerOrNext.next || noop; + _this._tapError = observerOrNext.error || noop; + _this._tapComplete = observerOrNext.complete || noop; + } + return _this; + } + TapSubscriber.prototype._next = function (value) { + try { + this._tapNext.call(this._context, value); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(value); + }; + TapSubscriber.prototype._error = function (err) { + try { + this._tapError.call(this._context, err); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.error(err); + }; + TapSubscriber.prototype._complete = function () { + try { + this._tapComplete.call(this._context); + } + catch (err) { + this.destination.error(err); + return; + } + return this.destination.complete(); + }; + return TapSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ +var defaultThrottleConfig = { + leading: true, + trailing: false +}; +function throttle(durationSelector, config) { + if (config === void 0) { + config = defaultThrottleConfig; + } + return function (source) { return source.lift(new ThrottleOperator(durationSelector, !!config.leading, !!config.trailing)); }; +} +var ThrottleOperator = /*@__PURE__*/ (function () { + function ThrottleOperator(durationSelector, leading, trailing) { + this.durationSelector = durationSelector; + this.leading = leading; + this.trailing = trailing; + } + ThrottleOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing)); + }; + return ThrottleOperator; +}()); +var ThrottleSubscriber = /*@__PURE__*/ (function (_super) { + __extends(ThrottleSubscriber, _super); + function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + _this.durationSelector = durationSelector; + _this._leading = _leading; + _this._trailing = _trailing; + _this._hasValue = false; + return _this; + } + ThrottleSubscriber.prototype._next = function (value) { + this._hasValue = true; + this._sendValue = value; + if (!this._throttled) { + if (this._leading) { + this.send(); + } + else { + this.throttle(value); + } + } + }; + ThrottleSubscriber.prototype.send = function () { + var _a = this, _hasValue = _a._hasValue, _sendValue = _a._sendValue; + if (_hasValue) { + this.destination.next(_sendValue); + this.throttle(_sendValue); + } + this._hasValue = false; + this._sendValue = undefined; + }; + ThrottleSubscriber.prototype.throttle = function (value) { + var duration = this.tryDurationSelector(value); + if (!!duration) { + this.add(this._throttled = innerSubscribe(duration, new SimpleInnerSubscriber(this))); + } + }; + ThrottleSubscriber.prototype.tryDurationSelector = function (value) { + try { + return this.durationSelector(value); + } + catch (err) { + this.destination.error(err); + return null; + } + }; + ThrottleSubscriber.prototype.throttlingDone = function () { + var _a = this, _throttled = _a._throttled, _trailing = _a._trailing; + if (_throttled) { + _throttled.unsubscribe(); + } + this._throttled = undefined; + if (_trailing) { + this.send(); + } + }; + ThrottleSubscriber.prototype.notifyNext = function () { + this.throttlingDone(); + }; + ThrottleSubscriber.prototype.notifyComplete = function () { + this.throttlingDone(); + }; + return ThrottleSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async,_throttle PURE_IMPORTS_END */ +function throttleTime(duration, scheduler, config) { + if (scheduler === void 0) { + scheduler = async; + } + if (config === void 0) { + config = defaultThrottleConfig; + } + return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); }; +} +var ThrottleTimeOperator = /*@__PURE__*/ (function () { + function ThrottleTimeOperator(duration, scheduler, leading, trailing) { + this.duration = duration; + this.scheduler = scheduler; + this.leading = leading; + this.trailing = trailing; + } + ThrottleTimeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing)); + }; + return ThrottleTimeOperator; +}()); +var ThrottleTimeSubscriber = /*@__PURE__*/ (function (_super) { + __extends(ThrottleTimeSubscriber, _super); + function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) { + var _this = _super.call(this, destination) || this; + _this.duration = duration; + _this.scheduler = scheduler; + _this.leading = leading; + _this.trailing = trailing; + _this._hasTrailingValue = false; + _this._trailingValue = null; + return _this; + } + ThrottleTimeSubscriber.prototype._next = function (value) { + if (this.throttled) { + if (this.trailing) { + this._trailingValue = value; + this._hasTrailingValue = true; + } + } + else { + this.add(this.throttled = this.scheduler.schedule(dispatchNext$3, this.duration, { subscriber: this })); + if (this.leading) { + this.destination.next(value); + } + else if (this.trailing) { + this._trailingValue = value; + this._hasTrailingValue = true; + } + } + }; + ThrottleTimeSubscriber.prototype._complete = function () { + if (this._hasTrailingValue) { + this.destination.next(this._trailingValue); + this.destination.complete(); + } + else { + this.destination.complete(); + } + }; + ThrottleTimeSubscriber.prototype.clearThrottle = function () { + var throttled = this.throttled; + if (throttled) { + if (this.trailing && this._hasTrailingValue) { + this.destination.next(this._trailingValue); + this._trailingValue = null; + this._hasTrailingValue = false; + } + throttled.unsubscribe(); + this.remove(throttled); + this.throttled = null; + } + }; + return ThrottleTimeSubscriber; +}(Subscriber)); +function dispatchNext$3(arg) { + var subscriber = arg.subscriber; + subscriber.clearThrottle(); +} + +/** PURE_IMPORTS_START _scheduler_async,_scan,_observable_defer,_map PURE_IMPORTS_END */ +function timeInterval(scheduler) { + if (scheduler === void 0) { + scheduler = async; + } + return function (source) { + return defer(function () { + return source.pipe(scan(function (_a, value) { + var current = _a.current; + return ({ value: value, current: scheduler.now(), last: current }); + }, { current: scheduler.now(), value: undefined, last: undefined }), map$1(function (_a) { + var current = _a.current, last = _a.last, value = _a.value; + return new TimeInterval(value, current - last); + })); + }); + }; +} +var TimeInterval = /*@__PURE__*/ (function () { + function TimeInterval(value, interval) { + this.value = value; + this.interval = interval; + } + return TimeInterval; +}()); + +/** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_innerSubscribe PURE_IMPORTS_END */ +function timeoutWith(due, withObservable, scheduler) { + if (scheduler === void 0) { + scheduler = async; + } + return function (source) { + var absoluteTimeout = isDate(due); + var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due); + return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler)); + }; +} +var TimeoutWithOperator = /*@__PURE__*/ (function () { + function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) { + this.waitFor = waitFor; + this.absoluteTimeout = absoluteTimeout; + this.withObservable = withObservable; + this.scheduler = scheduler; + } + TimeoutWithOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler)); + }; + return TimeoutWithOperator; +}()); +var TimeoutWithSubscriber = /*@__PURE__*/ (function (_super) { + __extends(TimeoutWithSubscriber, _super); + function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) { + var _this = _super.call(this, destination) || this; + _this.absoluteTimeout = absoluteTimeout; + _this.waitFor = waitFor; + _this.withObservable = withObservable; + _this.scheduler = scheduler; + _this.scheduleTimeout(); + return _this; + } + TimeoutWithSubscriber.dispatchTimeout = function (subscriber) { + var withObservable = subscriber.withObservable; + subscriber._unsubscribeAndRecycle(); + subscriber.add(innerSubscribe(withObservable, new SimpleInnerSubscriber(subscriber))); + }; + TimeoutWithSubscriber.prototype.scheduleTimeout = function () { + var action = this.action; + if (action) { + this.action = action.schedule(this, this.waitFor); + } + else { + this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this)); + } + }; + TimeoutWithSubscriber.prototype._next = function (value) { + if (!this.absoluteTimeout) { + this.scheduleTimeout(); + } + _super.prototype._next.call(this, value); + }; + TimeoutWithSubscriber.prototype._unsubscribe = function () { + this.action = undefined; + this.scheduler = null; + this.withObservable = null; + }; + return TimeoutWithSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START _scheduler_async,_util_TimeoutError,_timeoutWith,_observable_throwError PURE_IMPORTS_END */ +function timeout(due, scheduler) { + if (scheduler === void 0) { + scheduler = async; + } + return timeoutWith(due, throwError(new TimeoutError()), scheduler); +} + +/** PURE_IMPORTS_START _scheduler_async,_map PURE_IMPORTS_END */ +function timestamp(scheduler) { + if (scheduler === void 0) { + scheduler = async; + } + return map$1(function (value) { return new Timestamp(value, scheduler.now()); }); +} +var Timestamp = /*@__PURE__*/ (function () { + function Timestamp(value, timestamp) { + this.value = value; + this.timestamp = timestamp; + } + return Timestamp; +}()); + +/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ +function toArrayReducer(arr, item, index) { + if (index === 0) { + return [item]; + } + arr.push(item); + return arr; +} +function toArray() { + return reduce$1(toArrayReducer, []); +} + +/** PURE_IMPORTS_START tslib,_Subject,_innerSubscribe PURE_IMPORTS_END */ +function window$1(windowBoundaries) { + return function windowOperatorFunction(source) { + return source.lift(new WindowOperator(windowBoundaries)); + }; +} +var WindowOperator = /*@__PURE__*/ (function () { + function WindowOperator(windowBoundaries) { + this.windowBoundaries = windowBoundaries; + } + WindowOperator.prototype.call = function (subscriber, source) { + var windowSubscriber = new WindowSubscriber(subscriber); + var sourceSubscription = source.subscribe(windowSubscriber); + if (!sourceSubscription.closed) { + windowSubscriber.add(innerSubscribe(this.windowBoundaries, new SimpleInnerSubscriber(windowSubscriber))); + } + return sourceSubscription; + }; + return WindowOperator; +}()); +var WindowSubscriber = /*@__PURE__*/ (function (_super) { + __extends(WindowSubscriber, _super); + function WindowSubscriber(destination) { + var _this = _super.call(this, destination) || this; + _this.window = new Subject(); + destination.next(_this.window); + return _this; + } + WindowSubscriber.prototype.notifyNext = function () { + this.openWindow(); + }; + WindowSubscriber.prototype.notifyError = function (error) { + this._error(error); + }; + WindowSubscriber.prototype.notifyComplete = function () { + this._complete(); + }; + WindowSubscriber.prototype._next = function (value) { + this.window.next(value); + }; + WindowSubscriber.prototype._error = function (err) { + this.window.error(err); + this.destination.error(err); + }; + WindowSubscriber.prototype._complete = function () { + this.window.complete(); + this.destination.complete(); + }; + WindowSubscriber.prototype._unsubscribe = function () { + this.window = null; + }; + WindowSubscriber.prototype.openWindow = function () { + var prevWindow = this.window; + if (prevWindow) { + prevWindow.complete(); + } + var destination = this.destination; + var newWindow = this.window = new Subject(); + destination.next(newWindow); + }; + return WindowSubscriber; +}(SimpleOuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subscriber,_Subject PURE_IMPORTS_END */ +function windowCount(windowSize, startWindowEvery) { + if (startWindowEvery === void 0) { + startWindowEvery = 0; + } + return function windowCountOperatorFunction(source) { + return source.lift(new WindowCountOperator(windowSize, startWindowEvery)); + }; +} +var WindowCountOperator = /*@__PURE__*/ (function () { + function WindowCountOperator(windowSize, startWindowEvery) { + this.windowSize = windowSize; + this.startWindowEvery = startWindowEvery; + } + WindowCountOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery)); + }; + return WindowCountOperator; +}()); +var WindowCountSubscriber = /*@__PURE__*/ (function (_super) { + __extends(WindowCountSubscriber, _super); + function WindowCountSubscriber(destination, windowSize, startWindowEvery) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + _this.windowSize = windowSize; + _this.startWindowEvery = startWindowEvery; + _this.windows = [new Subject()]; + _this.count = 0; + destination.next(_this.windows[0]); + return _this; + } + WindowCountSubscriber.prototype._next = function (value) { + var startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize; + var destination = this.destination; + var windowSize = this.windowSize; + var windows = this.windows; + var len = windows.length; + for (var i = 0; i < len && !this.closed; i++) { + windows[i].next(value); + } + var c = this.count - windowSize + 1; + if (c >= 0 && c % startWindowEvery === 0 && !this.closed) { + windows.shift().complete(); + } + if (++this.count % startWindowEvery === 0 && !this.closed) { + var window_1 = new Subject(); + windows.push(window_1); + destination.next(window_1); + } + }; + WindowCountSubscriber.prototype._error = function (err) { + var windows = this.windows; + if (windows) { + while (windows.length > 0 && !this.closed) { + windows.shift().error(err); + } + } + this.destination.error(err); + }; + WindowCountSubscriber.prototype._complete = function () { + var windows = this.windows; + if (windows) { + while (windows.length > 0 && !this.closed) { + windows.shift().complete(); + } + } + this.destination.complete(); + }; + WindowCountSubscriber.prototype._unsubscribe = function () { + this.count = 0; + this.windows = null; + }; + return WindowCountSubscriber; +}(Subscriber)); + +/** PURE_IMPORTS_START tslib,_Subject,_scheduler_async,_Subscriber,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */ +function windowTime(windowTimeSpan) { + var scheduler = async; + var windowCreationInterval = null; + var maxWindowSize = Number.POSITIVE_INFINITY; + if (isScheduler(arguments[3])) { + scheduler = arguments[3]; + } + if (isScheduler(arguments[2])) { + scheduler = arguments[2]; + } + else if (isNumeric(arguments[2])) { + maxWindowSize = Number(arguments[2]); + } + if (isScheduler(arguments[1])) { + scheduler = arguments[1]; + } + else if (isNumeric(arguments[1])) { + windowCreationInterval = Number(arguments[1]); + } + return function windowTimeOperatorFunction(source) { + return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler)); + }; +} +var WindowTimeOperator = /*@__PURE__*/ (function () { + function WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) { + this.windowTimeSpan = windowTimeSpan; + this.windowCreationInterval = windowCreationInterval; + this.maxWindowSize = maxWindowSize; + this.scheduler = scheduler; + } + WindowTimeOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler)); + }; + return WindowTimeOperator; +}()); +var CountedSubject = /*@__PURE__*/ (function (_super) { + __extends(CountedSubject, _super); + function CountedSubject() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this._numberOfNextedValues = 0; + return _this; + } + CountedSubject.prototype.next = function (value) { + this._numberOfNextedValues++; + _super.prototype.next.call(this, value); + }; + Object.defineProperty(CountedSubject.prototype, "numberOfNextedValues", { + get: function () { + return this._numberOfNextedValues; + }, + enumerable: true, + configurable: true + }); + return CountedSubject; +}(Subject)); +var WindowTimeSubscriber = /*@__PURE__*/ (function (_super) { + __extends(WindowTimeSubscriber, _super); + function WindowTimeSubscriber(destination, windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + _this.windowTimeSpan = windowTimeSpan; + _this.windowCreationInterval = windowCreationInterval; + _this.maxWindowSize = maxWindowSize; + _this.scheduler = scheduler; + _this.windows = []; + var window = _this.openWindow(); + if (windowCreationInterval !== null && windowCreationInterval >= 0) { + var closeState = { subscriber: _this, window: window, context: null }; + var creationState = { windowTimeSpan: windowTimeSpan, windowCreationInterval: windowCreationInterval, subscriber: _this, scheduler: scheduler }; + _this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState)); + _this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState)); + } + else { + var timeSpanOnlyState = { subscriber: _this, window: window, windowTimeSpan: windowTimeSpan }; + _this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState)); + } + return _this; + } + WindowTimeSubscriber.prototype._next = function (value) { + var windows = this.windows; + var len = windows.length; + for (var i = 0; i < len; i++) { + var window_1 = windows[i]; + if (!window_1.closed) { + window_1.next(value); + if (window_1.numberOfNextedValues >= this.maxWindowSize) { + this.closeWindow(window_1); + } + } + } + }; + WindowTimeSubscriber.prototype._error = function (err) { + var windows = this.windows; + while (windows.length > 0) { + windows.shift().error(err); + } + this.destination.error(err); + }; + WindowTimeSubscriber.prototype._complete = function () { + var windows = this.windows; + while (windows.length > 0) { + var window_2 = windows.shift(); + if (!window_2.closed) { + window_2.complete(); + } + } + this.destination.complete(); + }; + WindowTimeSubscriber.prototype.openWindow = function () { + var window = new CountedSubject(); + this.windows.push(window); + var destination = this.destination; + destination.next(window); + return window; + }; + WindowTimeSubscriber.prototype.closeWindow = function (window) { + window.complete(); + var windows = this.windows; + windows.splice(windows.indexOf(window), 1); + }; + return WindowTimeSubscriber; +}(Subscriber)); +function dispatchWindowTimeSpanOnly(state) { + var subscriber = state.subscriber, windowTimeSpan = state.windowTimeSpan, window = state.window; + if (window) { + subscriber.closeWindow(window); + } + state.window = subscriber.openWindow(); + this.schedule(state, windowTimeSpan); +} +function dispatchWindowCreation(state) { + var windowTimeSpan = state.windowTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler, windowCreationInterval = state.windowCreationInterval; + var window = subscriber.openWindow(); + var action = this; + var context = { action: action, subscription: null }; + var timeSpanState = { subscriber: subscriber, window: window, context: context }; + context.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState); + action.add(context.subscription); + action.schedule(state, windowCreationInterval); +} +function dispatchWindowClose(state) { + var subscriber = state.subscriber, window = state.window, context = state.context; + if (context && context.action && context.subscription) { + context.action.remove(context.subscription); + } + subscriber.closeWindow(window); +} + +/** PURE_IMPORTS_START tslib,_Subject,_Subscription,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +function windowToggle(openings, closingSelector) { + return function (source) { return source.lift(new WindowToggleOperator(openings, closingSelector)); }; +} +var WindowToggleOperator = /*@__PURE__*/ (function () { + function WindowToggleOperator(openings, closingSelector) { + this.openings = openings; + this.closingSelector = closingSelector; + } + WindowToggleOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new WindowToggleSubscriber(subscriber, this.openings, this.closingSelector)); + }; + return WindowToggleOperator; +}()); +var WindowToggleSubscriber = /*@__PURE__*/ (function (_super) { + __extends(WindowToggleSubscriber, _super); + function WindowToggleSubscriber(destination, openings, closingSelector) { + var _this = _super.call(this, destination) || this; + _this.openings = openings; + _this.closingSelector = closingSelector; + _this.contexts = []; + _this.add(_this.openSubscription = subscribeToResult(_this, openings, openings)); + return _this; + } + WindowToggleSubscriber.prototype._next = function (value) { + var contexts = this.contexts; + if (contexts) { + var len = contexts.length; + for (var i = 0; i < len; i++) { + contexts[i].window.next(value); + } + } + }; + WindowToggleSubscriber.prototype._error = function (err) { + var contexts = this.contexts; + this.contexts = null; + if (contexts) { + var len = contexts.length; + var index = -1; + while (++index < len) { + var context_1 = contexts[index]; + context_1.window.error(err); + context_1.subscription.unsubscribe(); + } + } + _super.prototype._error.call(this, err); + }; + WindowToggleSubscriber.prototype._complete = function () { + var contexts = this.contexts; + this.contexts = null; + if (contexts) { + var len = contexts.length; + var index = -1; + while (++index < len) { + var context_2 = contexts[index]; + context_2.window.complete(); + context_2.subscription.unsubscribe(); + } + } + _super.prototype._complete.call(this); + }; + WindowToggleSubscriber.prototype._unsubscribe = function () { + var contexts = this.contexts; + this.contexts = null; + if (contexts) { + var len = contexts.length; + var index = -1; + while (++index < len) { + var context_3 = contexts[index]; + context_3.window.unsubscribe(); + context_3.subscription.unsubscribe(); + } + } + }; + WindowToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { + if (outerValue === this.openings) { + var closingNotifier = void 0; + try { + var closingSelector = this.closingSelector; + closingNotifier = closingSelector(innerValue); + } + catch (e) { + return this.error(e); + } + var window_1 = new Subject(); + var subscription = new Subscription(); + var context_4 = { window: window_1, subscription: subscription }; + this.contexts.push(context_4); + var innerSubscription = subscribeToResult(this, closingNotifier, context_4); + if (innerSubscription.closed) { + this.closeWindow(this.contexts.length - 1); + } + else { + innerSubscription.context = context_4; + subscription.add(innerSubscription); + } + this.destination.next(window_1); + } + else { + this.closeWindow(this.contexts.indexOf(outerValue)); + } + }; + WindowToggleSubscriber.prototype.notifyError = function (err) { + this.error(err); + }; + WindowToggleSubscriber.prototype.notifyComplete = function (inner) { + if (inner !== this.openSubscription) { + this.closeWindow(this.contexts.indexOf(inner.context)); + } + }; + WindowToggleSubscriber.prototype.closeWindow = function (index) { + if (index === -1) { + return; + } + var contexts = this.contexts; + var context = contexts[index]; + var window = context.window, subscription = context.subscription; + contexts.splice(index, 1); + window.complete(); + subscription.unsubscribe(); + }; + return WindowToggleSubscriber; +}(OuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +function windowWhen(closingSelector) { + return function windowWhenOperatorFunction(source) { + return source.lift(new WindowOperator$1(closingSelector)); + }; +} +var WindowOperator$1 = /*@__PURE__*/ (function () { + function WindowOperator(closingSelector) { + this.closingSelector = closingSelector; + } + WindowOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new WindowSubscriber$1(subscriber, this.closingSelector)); + }; + return WindowOperator; +}()); +var WindowSubscriber$1 = /*@__PURE__*/ (function (_super) { + __extends(WindowSubscriber, _super); + function WindowSubscriber(destination, closingSelector) { + var _this = _super.call(this, destination) || this; + _this.destination = destination; + _this.closingSelector = closingSelector; + _this.openWindow(); + return _this; + } + WindowSubscriber.prototype.notifyNext = function (_outerValue, _innerValue, _outerIndex, _innerIndex, innerSub) { + this.openWindow(innerSub); + }; + WindowSubscriber.prototype.notifyError = function (error) { + this._error(error); + }; + WindowSubscriber.prototype.notifyComplete = function (innerSub) { + this.openWindow(innerSub); + }; + WindowSubscriber.prototype._next = function (value) { + this.window.next(value); + }; + WindowSubscriber.prototype._error = function (err) { + this.window.error(err); + this.destination.error(err); + this.unsubscribeClosingNotification(); + }; + WindowSubscriber.prototype._complete = function () { + this.window.complete(); + this.destination.complete(); + this.unsubscribeClosingNotification(); + }; + WindowSubscriber.prototype.unsubscribeClosingNotification = function () { + if (this.closingNotification) { + this.closingNotification.unsubscribe(); + } + }; + WindowSubscriber.prototype.openWindow = function (innerSub) { + if (innerSub === void 0) { + innerSub = null; + } + if (innerSub) { + this.remove(innerSub); + innerSub.unsubscribe(); + } + var prevWindow = this.window; + if (prevWindow) { + prevWindow.complete(); + } + var window = this.window = new Subject(); + this.destination.next(window); + var closingNotifier; + try { + var closingSelector = this.closingSelector; + closingNotifier = closingSelector(); + } + catch (e) { + this.destination.error(e); + this.window.error(e); + return; + } + this.add(this.closingNotification = subscribeToResult(this, closingNotifier)); + }; + return WindowSubscriber; +}(OuterSubscriber)); + +/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ +function withLatestFrom() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return function (source) { + var project; + if (typeof args[args.length - 1] === 'function') { + project = args.pop(); + } + var observables = args; + return source.lift(new WithLatestFromOperator(observables, project)); + }; +} +var WithLatestFromOperator = /*@__PURE__*/ (function () { + function WithLatestFromOperator(observables, project) { + this.observables = observables; + this.project = project; + } + WithLatestFromOperator.prototype.call = function (subscriber, source) { + return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project)); + }; + return WithLatestFromOperator; +}()); +var WithLatestFromSubscriber = /*@__PURE__*/ (function (_super) { + __extends(WithLatestFromSubscriber, _super); + function WithLatestFromSubscriber(destination, observables, project) { + var _this = _super.call(this, destination) || this; + _this.observables = observables; + _this.project = project; + _this.toRespond = []; + var len = observables.length; + _this.values = new Array(len); + for (var i = 0; i < len; i++) { + _this.toRespond.push(i); + } + for (var i = 0; i < len; i++) { + var observable = observables[i]; + _this.add(subscribeToResult(_this, observable, undefined, i)); + } + return _this; + } + WithLatestFromSubscriber.prototype.notifyNext = function (_outerValue, innerValue, outerIndex) { + this.values[outerIndex] = innerValue; + var toRespond = this.toRespond; + if (toRespond.length > 0) { + var found = toRespond.indexOf(outerIndex); + if (found !== -1) { + toRespond.splice(found, 1); + } + } + }; + WithLatestFromSubscriber.prototype.notifyComplete = function () { + }; + WithLatestFromSubscriber.prototype._next = function (value) { + if (this.toRespond.length === 0) { + var args = [value].concat(this.values); + if (this.project) { + this._tryProject(args); + } + else { + this.destination.next(args); + } + } + }; + WithLatestFromSubscriber.prototype._tryProject = function (args) { + var result; + try { + result = this.project.apply(this, args); + } + catch (err) { + this.destination.error(err); + return; + } + this.destination.next(result); + }; + return WithLatestFromSubscriber; +}(OuterSubscriber)); + +/** PURE_IMPORTS_START _observable_zip PURE_IMPORTS_END */ +function zip$1() { + var observables = []; + for (var _i = 0; _i < arguments.length; _i++) { + observables[_i] = arguments[_i]; + } + return function zipOperatorFunction(source) { + return source.lift.call(zip.apply(void 0, [source].concat(observables))); + }; +} + +/** PURE_IMPORTS_START _observable_zip PURE_IMPORTS_END */ +function zipAll(project) { + return function (source) { return source.lift(new ZipOperator(project)); }; +} + +/** PURE_IMPORTS_START PURE_IMPORTS_END */ + +var operators = /*#__PURE__*/Object.freeze({ + __proto__: null, + audit: audit, + auditTime: auditTime, + buffer: buffer, + bufferCount: bufferCount, + bufferTime: bufferTime, + bufferToggle: bufferToggle, + bufferWhen: bufferWhen, + catchError: catchError, + combineAll: combineAll, + combineLatest: combineLatest$1, + concat: concat$2, + concatAll: concatAll, + concatMap: concatMap, + concatMapTo: concatMapTo, + count: count, + debounce: debounce, + debounceTime: debounceTime, + defaultIfEmpty: defaultIfEmpty, + delay: delay, + delayWhen: delayWhen, + dematerialize: dematerialize, + distinct: distinct, + distinctUntilChanged: distinctUntilChanged, + distinctUntilKeyChanged: distinctUntilKeyChanged, + elementAt: elementAt, + endWith: endWith, + every: every$1, + exhaust: exhaust, + exhaustMap: exhaustMap, + expand: expand, + filter: filter, + finalize: finalize, + find: find, + findIndex: findIndex, + first: first, + groupBy: groupBy, + ignoreElements: ignoreElements, + isEmpty: isEmpty$1, + last: last, + map: map$1, + mapTo: mapTo, + materialize: materialize, + max: max, + merge: merge$1, + mergeAll: mergeAll, + mergeMap: mergeMap, + flatMap: flatMap$1, + mergeMapTo: mergeMapTo, + mergeScan: mergeScan, + min: min, + multicast: multicast, + observeOn: observeOn, + onErrorResumeNext: onErrorResumeNext$1, + pairwise: pairwise, + partition: partition$1, + pluck: pluck, + publish: publish, + publishBehavior: publishBehavior, + publishLast: publishLast, + publishReplay: publishReplay, + race: race$1, + reduce: reduce$1, + repeat: repeat, + repeatWhen: repeatWhen, + retry: retry, + retryWhen: retryWhen, + refCount: refCount, + sample: sample, + sampleTime: sampleTime, + scan: scan, + sequenceEqual: sequenceEqual, + share: share, + shareReplay: shareReplay, + single: single, + skip: skip, + skipLast: skipLast, + skipUntil: skipUntil, + skipWhile: skipWhile, + startWith: startWith, + subscribeOn: subscribeOn, + switchAll: switchAll, + switchMap: switchMap, + switchMapTo: switchMapTo, + take: take, + takeLast: takeLast, + takeUntil: takeUntil, + takeWhile: takeWhile, + tap: tap, + throttle: throttle, + throttleTime: throttleTime, + throwIfEmpty: throwIfEmpty, + timeInterval: timeInterval, + timeout: timeout, + timeoutWith: timeoutWith, + timestamp: timestamp, + toArray: toArray, + window: window$1, + windowCount: windowCount, + windowTime: windowTime, + windowToggle: windowToggle, + windowWhen: windowWhen, + withLatestFrom: withLatestFrom, + zip: zip$1, + zipAll: zipAll +}); + +var _rxjs = /*@__PURE__*/getAugmentedNamespace(_esm5); + +var _operators = /*@__PURE__*/getAugmentedNamespace(operators); + +var resultRx = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +interopRequireDefault(resultSummary); + + + + + +interopRequireDefault(record); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var States = { + READY: 0, + STREAMING: 1, + COMPLETED: 2 + /** + * The reactive result interface. + */ + +}; + +var RxResult = +/*#__PURE__*/ +function () { + /** + * @constructor + * @protected + * @param {Observable} result - An observable of single Result instance to relay requests. + */ + function RxResult(result) { + (0, _classCallCheck2["default"])(this, RxResult); + var replayedResult = result.pipe((0, _operators.publishReplay)(1), (0, _operators.refCount)()); + this._result = replayedResult; + this._keys = replayedResult.pipe((0, _operators.flatMap)(function (r) { + return (0, _rxjs.from)(r.keys()); + }), (0, _operators.publishReplay)(1), (0, _operators.refCount)()); + this._records = new _rxjs.Subject(); + this._summary = new _rxjs.ReplaySubject(); + this._state = States.READY; + } + /** + * Returns an observable that exposes a single item containing field names + * returned by the executing query. + * + * Errors raised by actual query execution can surface on the returned + * observable stream. + * + * @public + * @returns {Observable} - An observable stream (with exactly one element) of field names. + */ + + + (0, _createClass2["default"])(RxResult, [{ + key: "keys", + value: function keys() { + return this._keys; + } + /** + * Returns an observable that exposes each record returned by the executing query. + * + * Errors raised during the streaming phase can surface on the returned observable stream. + * + * @public + * @returns {Observable} - An observable stream of records. + */ + + }, { + key: "records", + value: function records() { + var _this = this; + + return this._result.pipe((0, _operators.flatMap)(function (result) { + return new _rxjs.Observable(function (recordsObserver) { + return _this._startStreaming({ + result: result, + recordsObserver: recordsObserver + }); + }); + })); + } + /** + * Returns an observable that exposes a single item of {@link ResultSummary} that is generated by + * the server after the streaming of the executing query is completed. + * + * *Subscribing to this stream before subscribing to records() stream causes the results to be discarded on the server.* + * + * @public + * @returns {Observable} - An observable stream (with exactly one element) of result summary. + */ + + }, { + key: "consume", + value: function consume() { + var _this2 = this; + + return this._result.pipe((0, _operators.flatMap)(function (result) { + return new _rxjs.Observable(function (summaryObserver) { + return _this2._startStreaming({ + result: result, + summaryObserver: summaryObserver + }); + }); + })); + } + }, { + key: "_startStreaming", + value: function _startStreaming() { + var _this3 = this; + + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + result = _ref.result, + _ref$recordsObserver = _ref.recordsObserver, + recordsObserver = _ref$recordsObserver === void 0 ? null : _ref$recordsObserver, + _ref$summaryObserver = _ref.summaryObserver, + summaryObserver = _ref$summaryObserver === void 0 ? null : _ref$summaryObserver; + + var subscriptions = []; + + if (summaryObserver) { + subscriptions.push(this._summary.subscribe(summaryObserver)); + } + + if (this._state < States.STREAMING) { + this._state = States.STREAMING; + + if (recordsObserver) { + subscriptions.push(this._records.subscribe(recordsObserver)); + } + + subscriptions.push({ + unsubscribe: function unsubscribe() { + if (result._cancel) { + result._cancel(); + } + } + }); + + if (this._records.observers.length === 0) { + result._cancel(); + } + + result.subscribe({ + onNext: function onNext(record) { + _this3._records.next(record); + }, + onCompleted: function onCompleted(summary) { + _this3._records.complete(); + + _this3._summary.next(summary); + + _this3._summary.complete(); + + _this3._state = States.COMPLETED; + }, + onError: function onError(err) { + _this3._records.error(err); + + _this3._summary.error(err); + + _this3._state = States.COMPLETED; + } + }); + } else if (recordsObserver) { + recordsObserver.error((0, error.newError)('Streaming has already started/consumed with a previous records or summary subscription.')); + } + + return function () { + subscriptions.forEach(function (s) { + return s.unsubscribe(); + }); + }; + } + }]); + return RxResult; +}(); + +exports["default"] = RxResult; +}); + +var transactionRx = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +var _resultRx = interopRequireDefault(resultRx); + +interopRequireDefault(transaction); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A reactive transaction, which provides the same functionality as {@link Transaction} but through a Reactive API. + */ +var RxTransaction = +/*#__PURE__*/ +function () { + /** + * @constructor + * @protected + * @param {Transaction} txc - The underlying transaction instance to relay requests + */ + function RxTransaction(txc) { + (0, _classCallCheck2["default"])(this, RxTransaction); + this._txc = txc; + } + /** + * Creates a reactive result that will execute the query in this transaction, with the provided parameters. + * + * @public + * @param {string} query - Query to be executed. + * @param {Object} parameters - Parameter values to use in query execution. + * @returns {RxResult} - A reactive result + */ + + + (0, _createClass2["default"])(RxTransaction, [{ + key: "run", + value: function run(query, parameters) { + var _this = this; + + return new _resultRx["default"](new _rxjs.Observable(function (observer) { + try { + observer.next(_this._txc.run(query, parameters)); + observer.complete(); + } catch (err) { + observer.error(err); + } + + return function () {}; + })); + } + /** + * Commits the transaction. + * + * @public + * @returns {Observable} - An empty observable + */ + + }, { + key: "commit", + value: function commit() { + var _this2 = this; + + return new _rxjs.Observable(function (observer) { + _this2._txc.commit().then(function () { + observer.complete(); + })["catch"](function (err) { + return observer.error(err); + }); + }); + } + /** + * Rolls back the transaction. + * + * @public + * @returns {Observable} - An empty observable + */ + + }, { + key: "rollback", + value: function rollback() { + var _this3 = this; + + return new _rxjs.Observable(function (observer) { + _this3._txc.rollback().then(function () { + observer.complete(); + })["catch"](function (err) { + return observer.error(err); + }); + }); + } + }]); + return RxTransaction; +}(); + +exports["default"] = RxTransaction; +}); + +var retryLogicRx = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + + + + + +interopRequireDefault(logger); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var DEFAULT_MAX_RETRY_TIME_MS = 30 * 1000; // 30 seconds + +var DEFAULT_INITIAL_RETRY_DELAY_MS = 1000; // 1 seconds + +var DEFAULT_RETRY_DELAY_MULTIPLIER = 2.0; +var DEFAULT_RETRY_DELAY_JITTER_FACTOR = 0.2; + +var RxRetryLogic = +/*#__PURE__*/ +function () { + /** + * + * @param {Object} args + * @param {Logger} args.logger + */ + function RxRetryLogic() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$maxRetryTimeout = _ref.maxRetryTimeout, + maxRetryTimeout = _ref$maxRetryTimeout === void 0 ? DEFAULT_MAX_RETRY_TIME_MS : _ref$maxRetryTimeout, + _ref$initialDelay = _ref.initialDelay, + initialDelay = _ref$initialDelay === void 0 ? DEFAULT_INITIAL_RETRY_DELAY_MS : _ref$initialDelay, + _ref$delayMultiplier = _ref.delayMultiplier, + delayMultiplier = _ref$delayMultiplier === void 0 ? DEFAULT_RETRY_DELAY_MULTIPLIER : _ref$delayMultiplier, + _ref$delayJitter = _ref.delayJitter, + delayJitter = _ref$delayJitter === void 0 ? DEFAULT_RETRY_DELAY_JITTER_FACTOR : _ref$delayJitter, + _ref$logger = _ref.logger, + logger = _ref$logger === void 0 ? null : _ref$logger; + + (0, _classCallCheck2["default"])(this, RxRetryLogic); + this._maxRetryTimeout = valueOrDefault(maxRetryTimeout, DEFAULT_MAX_RETRY_TIME_MS); + this._initialDelay = valueOrDefault(initialDelay, DEFAULT_INITIAL_RETRY_DELAY_MS); + this._delayMultiplier = valueOrDefault(delayMultiplier, DEFAULT_RETRY_DELAY_MULTIPLIER); + this._delayJitter = valueOrDefault(delayJitter, DEFAULT_RETRY_DELAY_JITTER_FACTOR); + this._logger = logger; + } + /** + * + * @param {Observable} work + */ + + + (0, _createClass2["default"])(RxRetryLogic, [{ + key: "retry", + value: function retry(work) { + var _this = this; + + return work.pipe((0, _operators.retryWhen)(function (failedWork) { + var handledExceptions = []; + var startTime = Date.now(); + var retryCount = 1; + var delayDuration = _this._initialDelay; + return failedWork.pipe((0, _operators.flatMap)(function (err) { + if (!RxRetryLogic._canRetryOn(err)) { + return (0, _rxjs.throwError)(err); + } + + handledExceptions.push(err); + + if (retryCount >= 2 && Date.now() - startTime >= _this._maxRetryTimeout) { + var error$1 = (0, error.newError)("Failed after retried for ".concat(retryCount, " times in ").concat(_this._maxRetryTimeout, " ms. Make sure that your database is online and retry again."), error.SERVICE_UNAVAILABLE); + error$1.seenErrors = handledExceptions; + return (0, _rxjs.throwError)(error$1); + } + + var nextDelayDuration = _this._computeNextDelay(delayDuration); + + delayDuration = delayDuration * _this._delayMultiplier; + retryCount++; + + if (_this._logger) { + _this._logger.warn("Transaction failed and will be retried in ".concat(nextDelayDuration)); + } + + return (0, _rxjs.of)(1).pipe((0, _operators.delay)(nextDelayDuration)); + })); + })); + } + }, { + key: "_computeNextDelay", + value: function _computeNextDelay(delay) { + var jitter = delay * this._delayJitter; + return delay - jitter + 2 * jitter * Math.random(); + } + }], [{ + key: "_canRetryOn", + value: function _canRetryOn(error$1) { + return error$1 && error$1.code && (error$1.code === error.SERVICE_UNAVAILABLE || error$1.code === error.SESSION_EXPIRED || this._isTransientError(error$1)); + } + }, { + key: "_isTransientError", + value: function _isTransientError(error) { + // Retries should not happen when transaction was explicitly terminated by the user. + // Termination of transaction might result in two different error codes depending on where it was + // terminated. These are really client errors but classification on the server is not entirely correct and + // they are classified as transient. + var code = error.code; + + if (code.indexOf('TransientError') >= 0) { + if (code === 'Neo.TransientError.Transaction.Terminated' || code === 'Neo.TransientError.Transaction.LockClientStopped') { + return false; + } + + return true; + } + + return false; + } + }]); + return RxRetryLogic; +}(); + +exports["default"] = RxRetryLogic; + +function valueOrDefault(value, defaultValue) { + if (value || value === 0) { + return value; + } + + return defaultValue; +} +}); + +var sessionRx = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + + + +var _resultRx = interopRequireDefault(resultRx); + +interopRequireDefault(session); + +var _transactionRx = interopRequireDefault(transactionRx); + + + +var _txConfig = interopRequireDefault(txConfig); + +var _retryLogicRx = interopRequireDefault(retryLogicRx); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A Reactive session, which provides the same functionality as {@link Session} but through a Reactive API. + */ +var RxSession = +/*#__PURE__*/ +function () { + /** + * Constructs a reactive session with given default session instance and provided driver configuration. + * + * @protected + * @param {Object} param - Object parameter + * @param {Session} param.session - The underlying session instance to relay requests + */ + function RxSession() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + session = _ref.session, + config = _ref.config; + + (0, _classCallCheck2["default"])(this, RxSession); + this._session = session; + this._retryLogic = _createRetryLogic(config); + } + /** + * Creates a reactive result that will execute the query with the provided parameters and the provided + * transaction configuration that applies to the underlying auto-commit transaction. + * + * @public + * @param {string} query - Query to be executed. + * @param {Object} parameters - Parameter values to use in query execution. + * @param {TransactionConfig} transactionConfig - Configuration for the new auto-commit transaction. + * @returns {RxResult} - A reactive result + */ + + + (0, _createClass2["default"])(RxSession, [{ + key: "run", + value: function run(query, parameters, transactionConfig) { + var _this = this; + + return new _resultRx["default"](new _rxjs.Observable(function (observer) { + try { + observer.next(_this._session.run(query, parameters, transactionConfig)); + observer.complete(); + } catch (err) { + observer.error(err); + } + + return function () {}; + })); + } + /** + * Starts a new explicit transaction with the provided transaction configuration. + * + * @public + * @param {TransactionConfig} transactionConfig - Configuration for the new transaction. + * @returns {Observable} - A reactive stream that will generate at most **one** RxTransaction instance. + */ + + }, { + key: "beginTransaction", + value: function beginTransaction(transactionConfig) { + return this._beginTransaction(this._session._mode, transactionConfig); + } + /** + * Executes the provided unit of work in a {@link READ} reactive transaction which is created with the provided + * transaction configuration. + * @public + * @param {function(txc: RxTransaction): Observable} work - A unit of work to be executed. + * @param {TransactionConfig} transactionConfig - Configuration for the enclosing transaction created by the driver. + * @returns {Observable} - A reactive stream returned by the unit of work. + */ + + }, { + key: "readTransaction", + value: function readTransaction(work, transactionConfig) { + return this._runTransaction(constants.ACCESS_MODE_READ, work, transactionConfig); + } + /** + * Executes the provided unit of work in a {@link WRITE} reactive transaction which is created with the provided + * transaction configuration. + * @public + * @param {function(txc: RxTransaction): Observable} work - A unit of work to be executed. + * @param {TransactionConfig} transactionConfig - Configuration for the enclosing transaction created by the driver. + * @returns {Observable} - A reactive stream returned by the unit of work. + */ + + }, { + key: "writeTransaction", + value: function writeTransaction(work, transactionConfig) { + return this._runTransaction(constants.ACCESS_MODE_WRITE, work, transactionConfig); + } + /** + * Closes this reactive session. + * + * @public + * @returns {Observable} - An empty reactive stream + */ + + }, { + key: "close", + value: function close() { + var _this2 = this; + + return new _rxjs.Observable(function (observer) { + _this2._session.close().then(function () { + observer.complete(); + })["catch"](function (err) { + return observer.error(err); + }); + }); + } + /** + * Returns the bookmark received following the last successfully completed query, which is executed + * either in an {@link RxTransaction} obtained from this session instance or directly through one of + * the {@link RxSession#run} method of this session instance. + * + * If no bookmark was received or if this transaction was rolled back, the bookmark value will not be + * changed. + * + * @public + * @returns {string} + */ + + }, { + key: "lastBookmark", + value: function lastBookmark() { + return this._session.lastBookmark(); + } + /** + * @private + */ + + }, { + key: "_beginTransaction", + value: function _beginTransaction(accessMode, transactionConfig) { + var _this3 = this; + + var txConfig = _txConfig["default"].empty(); + + if (transactionConfig) { + txConfig = new _txConfig["default"](transactionConfig); + } + + return new _rxjs.Observable(function (observer) { + try { + observer.next(new _transactionRx["default"](_this3._session._beginTransaction(accessMode, txConfig))); + observer.complete(); + } catch (err) { + observer.error(err); + } + + return function () {}; + }); + } + /** + * @private + */ + + }, { + key: "_runTransaction", + value: function _runTransaction(accessMode, work, transactionConfig) { + _txConfig["default"].empty(); + + if (transactionConfig) { + new _txConfig["default"](transactionConfig); + } + + return this._retryLogic.retry(this._beginTransaction(accessMode, transactionConfig).pipe((0, _operators.flatMap)(function (txc) { + return (0, _rxjs.defer)(function () { + try { + return work(txc); + } catch (err) { + return (0, _rxjs.throwError)(err); + } + }).pipe((0, _operators.catchError)(function (err) { + return txc.rollback().pipe((0, _operators.concat)((0, _rxjs.throwError)(err))); + }), (0, _operators.concat)(txc.commit())); + }))); + } + }]); + return RxSession; +}(); + +exports["default"] = RxSession; + +function _createRetryLogic(config) { + var maxRetryTimeout = config && config.maxTransactionRetryTime ? config.maxTransactionRetryTime : null; + return new _retryLogicRx["default"]({ + maxRetryTimeout: maxRetryTimeout + }); +} +}); + +var driver = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = exports.WRITE = exports.READ = exports.Driver = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +interopRequireDefault(connectionProvider); + +var _bookmark = interopRequireDefault(bookmark); + +var _connectionProviderDirect = interopRequireDefault(connectionProviderDirect); + +var _connectivityVerifier = interopRequireDefault(connectivityVerifier); + + + +var _logger = interopRequireDefault(logger); + + + +var _session = interopRequireDefault(session); + +var _sessionRx = interopRequireDefault(sessionRx); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var DEFAULT_MAX_CONNECTION_LIFETIME = 60 * 60 * 1000; // 1 hour + +/** + * The default record fetch size. This is used in Bolt V4 protocol to pull query execution result in batches. + * @type {number} + */ + +var DEFAULT_FETCH_SIZE = 1000; +/** + * Constant that represents read session access mode. + * Should be used like this: `driver.session({ defaultAccessMode: neo4j.session.READ })`. + * @type {string} + */ + +var READ = constants.ACCESS_MODE_READ; +/** + * Constant that represents write session access mode. + * Should be used like this: `driver.session({ defaultAccessMode: neo4j.session.WRITE })`. + * @type {string} + */ + +exports.READ = READ; +var WRITE = constants.ACCESS_MODE_WRITE; +exports.WRITE = WRITE; +var idGenerator = 0; +/** + * A driver maintains one or more {@link Session}s with a remote + * Neo4j instance. Through the {@link Session}s you can send queries + * and retrieve results from the database. + * + * Drivers are reasonably expensive to create - you should strive to keep one + * driver instance around per Neo4j Instance you connect to. + * + * @access public + */ + +var Driver = +/*#__PURE__*/ +function () { + /** + * You should not be calling this directly, instead use {@link driver}. + * @constructor + * @protected + * @param {ServerAddress} address + * @param {string} userAgent + * @param {Object} authToken + * @param {Object} config + */ + function Driver(address, userAgent) { + var authToken = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + (0, _classCallCheck2["default"])(this, Driver); + sanitizeConfig(config); + this._id = idGenerator++; + this._address = address; + this._userAgent = userAgent; + this._authToken = authToken; + this._config = config; + this._log = _logger["default"].create(config); + /** + * Reference to the connection provider. Initialized lazily by {@link _getOrCreateConnectionProvider}. + * @type {ConnectionProvider} + * @protected + */ + + this._connectionProvider = null; + + this._afterConstruction(); + } + /** + * Verifies connectivity of this driver by trying to open a connection with the provided driver options. + * + * @public + * @param {Object} param - The object parameter + * @param {string} param.database - The target database to verify connectivity for. + * @returns {Promise} promise resolved with server info or rejected with error. + */ + + + (0, _createClass2["default"])(Driver, [{ + key: "verifyConnectivity", + value: function verifyConnectivity() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref$database = _ref.database, + database = _ref$database === void 0 ? '' : _ref$database; + + var connectionProvider = this._getOrCreateConnectionProvider(); + + var connectivityVerifier = new _connectivityVerifier["default"](connectionProvider); + return connectivityVerifier.verify({ + database: database + }); + } + /** + * Returns whether the server supports multi database capabilities based on the protocol + * version negotiated via handshake. + * + * Note that this function call _always_ causes a round-trip to the server. + * + * @returns {Promise} promise resolved with a boolean or rejected with error. + */ + + }, { + key: "supportsMultiDb", + value: function supportsMultiDb() { + var connectionProvider = this._getOrCreateConnectionProvider(); + + return connectionProvider.supportsMultiDb(); + } + /** + * Returns whether the server supports transaction config capabilities based on the protocol + * version negotiated via handshake. + * + * Note that this function call _always_ causes a round-trip to the server. + * + * @returns {Promise} promise resolved with a boolean or rejected with error. + */ + + }, { + key: "supportsTransactionConfig", + value: function supportsTransactionConfig() { + var connectionProvider = this._getOrCreateConnectionProvider(); + + return connectionProvider.supportsTransactionConfig(); + } + /** + * @protected + * @returns {boolean} + */ + + }, { + key: "_supportsRouting", + value: function _supportsRouting() { + return false; + } + /** + * Returns boolean to indicate if driver has been configured with encryption enabled. + * + * @protected + * @returns {boolean} + */ + + }, { + key: "_isEncrypted", + value: function _isEncrypted() { + return this._config.encrypted === util.ENCRYPTION_ON; + } + /** + * Returns the configured trust strategy that the driver has been configured with. + * + * @protected + * @returns {TrustStrategy} + */ + + }, { + key: "_getTrust", + value: function _getTrust() { + return this._config.trust; + } + /** + * Acquire a session to communicate with the database. The session will + * borrow connections from the underlying connection pool as required and + * should be considered lightweight and disposable. + * + * This comes with some responsibility - make sure you always call + * {@link close} when you are done using a session, and likewise, + * make sure you don't close your session before you are done using it. Once + * it is closed, the underlying connection will be released to the connection + * pool and made available for others to use. + * + * @public + * @param {Object} param - The object parameter + * @param {string} param.defaultAccessMode=WRITE - The access mode of this session, allowed values are {@link READ} and {@link WRITE}. + * @param {string|string[]} param.bookmarks - The initial reference or references to some previous + * transactions. Value is optional and absence indicates that that the bookmarks do not exist or are unknown. + * @param {number} param.fetchSize - The record fetch size of each batch of this session. + * Use {@link ALL} to always pull all records in one batch. This will override the config value set on driver config. + * @param {string} param.database - The database this session will operate on. + * @return {Session} new session. + */ + + }, { + key: "session", + value: function session() { + var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref2$defaultAccessMo = _ref2.defaultAccessMode, + defaultAccessMode = _ref2$defaultAccessMo === void 0 ? WRITE : _ref2$defaultAccessMo, + bookmarkOrBookmarks = _ref2.bookmarks, + _ref2$database = _ref2.database, + database = _ref2$database === void 0 ? '' : _ref2$database, + fetchSize = _ref2.fetchSize; + + return this._newSession({ + defaultAccessMode: defaultAccessMode, + bookmarkOrBookmarks: bookmarkOrBookmarks, + database: database, + reactive: false, + fetchSize: validateFetchSizeValue(fetchSize, this._config.fetchSize) + }); + } + /** + * Acquire a reactive session to communicate with the database. The session will + * borrow connections from the underlying connection pool as required and + * should be considered lightweight and disposable. + * + * This comes with some responsibility - make sure you always call + * {@link close} when you are done using a session, and likewise, + * make sure you don't close your session before you are done using it. Once + * it is closed, the underlying connection will be released to the connection + * pool and made available for others to use. + * + * @public + * @param {Object} param + * @param {string} param.defaultAccessMode=WRITE - The access mode of this session, allowed values are {@link READ} and {@link WRITE}. + * @param {string|string[]} param.bookmarks - The initial reference or references to some previous transactions. Value is optional and + * absence indicates that the bookmarks do not exist or are unknown. + * @param {string} param.database - The database this session will operate on. + * @returns {RxSession} new reactive session. + */ + + }, { + key: "rxSession", + value: function rxSession() { + var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + _ref3$defaultAccessMo = _ref3.defaultAccessMode, + defaultAccessMode = _ref3$defaultAccessMo === void 0 ? WRITE : _ref3$defaultAccessMo, + bookmarks = _ref3.bookmarks, + _ref3$database = _ref3.database, + database = _ref3$database === void 0 ? '' : _ref3$database, + fetchSize = _ref3.fetchSize; + + return new _sessionRx["default"]({ + session: this._newSession({ + defaultAccessMode: defaultAccessMode, + bookmarks: bookmarks, + database: database, + reactive: true, + fetchSize: validateFetchSizeValue(fetchSize, this._config.fetchSize) + }), + config: this._config + }); + } + /** + * Close all open sessions and other associated resources. You should + * make sure to use this when you are done with this driver instance. + * @public + * @return {Promise} promise resolved when the driver is closed. + */ + + }, { + key: "close", + value: function close() { + this._log.info("Driver ".concat(this._id, " closing")); + + if (this._connectionProvider) { + return this._connectionProvider.close(); + } + + return Promise.resolve(); + } + /** + * @protected + */ + + }, { + key: "_afterConstruction", + value: function _afterConstruction() { + this._log.info("Direct driver ".concat(this._id, " created for server address ").concat(this._address)); + } + /** + * @protected + */ + + }, { + key: "_createConnectionProvider", + value: function _createConnectionProvider(address, userAgent, authToken) { + return new _connectionProviderDirect["default"]({ + id: this._id, + config: this._config, + log: this._log, + address: address, + userAgent: userAgent, + authToken: authToken + }); + } + /** + * @protected + */ + + }, { + key: "_newSession", + + /** + * @private + */ + value: function _newSession(_ref4) { + var defaultAccessMode = _ref4.defaultAccessMode, + bookmarkOrBookmarks = _ref4.bookmarkOrBookmarks, + database = _ref4.database, + reactive = _ref4.reactive, + fetchSize = _ref4.fetchSize; + + var sessionMode = Driver._validateSessionMode(defaultAccessMode); + + var connectionProvider = this._getOrCreateConnectionProvider(); + + var bookmark = bookmarkOrBookmarks ? new _bookmark["default"](bookmarkOrBookmarks) : _bookmark["default"].empty(); + return new _session["default"]({ + mode: sessionMode, + database: database, + connectionProvider: connectionProvider, + bookmark: bookmark, + config: this._config, + reactive: reactive, + fetchSize: fetchSize + }); + } + /** + * @private + */ + + }, { + key: "_getOrCreateConnectionProvider", + value: function _getOrCreateConnectionProvider() { + if (!this._connectionProvider) { + this._connectionProvider = this._createConnectionProvider(this._address, this._userAgent, this._authToken); + } + + return this._connectionProvider; + } + }], [{ + key: "_validateSessionMode", + value: function _validateSessionMode(rawMode) { + var mode = rawMode || WRITE; + + if (mode !== constants.ACCESS_MODE_READ && mode !== constants.ACCESS_MODE_WRITE) { + throw (0, error.newError)('Illegal session mode ' + mode); + } + + return mode; + } + }]); + return Driver; +}(); +/** + * @private + */ + + +exports.Driver = Driver; + +function sanitizeConfig(config) { + config.maxConnectionLifetime = sanitizeIntValue(config.maxConnectionLifetime, DEFAULT_MAX_CONNECTION_LIFETIME); + config.maxConnectionPoolSize = sanitizeIntValue(config.maxConnectionPoolSize, poolConfig.DEFAULT_MAX_SIZE); + config.connectionAcquisitionTimeout = sanitizeIntValue(config.connectionAcquisitionTimeout, poolConfig.DEFAULT_ACQUISITION_TIMEOUT); + config.fetchSize = validateFetchSizeValue(config.fetchSize, DEFAULT_FETCH_SIZE); +} +/** + * @private + */ + + +function sanitizeIntValue(rawValue, defaultWhenAbsent) { + var sanitizedValue = parseInt(rawValue, 10); + + if (sanitizedValue > 0 || sanitizedValue === 0) { + return sanitizedValue; + } else if (sanitizedValue < 0) { + return Number.MAX_SAFE_INTEGER; + } else { + return defaultWhenAbsent; + } +} +/** + * @private + */ + + +function validateFetchSizeValue(rawValue, defaultWhenAbsent) { + var fetchSize = parseInt(rawValue, 10); + + if (fetchSize > 0 || fetchSize === requestMessage.ALL) { + return fetchSize; + } else if (fetchSize === 0 || fetchSize < 0) { + throw new Error('The fetch size can only be a positive value or -1 for ALL. However fetchSize = ' + fetchSize); + } else { + return defaultWhenAbsent; + } +} + +var _default = Driver; +exports["default"] = _default; +}); + +var arrayWithoutHoles = createCommonjsModule(function (module) { +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return arrayLikeToArray(arr); +} + +module.exports = _arrayWithoutHoles; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var iterableToArray = createCommonjsModule(function (module) { +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); +} + +module.exports = _iterableToArray; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var nonIterableSpread = createCommonjsModule(function (module) { +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +module.exports = _nonIterableSpread; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var toConsumableArray = createCommonjsModule(function (module) { +function _toConsumableArray(arr) { + return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); +} + +module.exports = _toConsumableArray; +module.exports["default"] = module.exports, module.exports.__esModule = true; +}); + +var routingTable = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _toConsumableArray2 = interopRequireDefault(toConsumableArray); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var MIN_ROUTERS = 1; + +var RoutingTable = +/*#__PURE__*/ +function () { + function RoutingTable() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + database = _ref.database, + routers = _ref.routers, + readers = _ref.readers, + writers = _ref.writers, + expirationTime = _ref.expirationTime; + + (0, _classCallCheck2["default"])(this, RoutingTable); + this.database = database; + this.databaseName = database || 'default database'; + this.routers = routers || []; + this.readers = readers || []; + this.writers = writers || []; + this.expirationTime = expirationTime || (0, integer["int"])(0); + } + + (0, _createClass2["default"])(RoutingTable, [{ + key: "forget", + value: function forget(address) { + // Don't remove it from the set of routers, since that might mean we lose our ability to re-discover, + // just remove it from the set of readers and writers, so that we don't use it for actual work without + // performing discovery first. + this.readers = removeFromArray(this.readers, address); + this.writers = removeFromArray(this.writers, address); + } + }, { + key: "forgetRouter", + value: function forgetRouter(address) { + this.routers = removeFromArray(this.routers, address); + } + }, { + key: "forgetWriter", + value: function forgetWriter(address) { + this.writers = removeFromArray(this.writers, address); + } + /** + * Check if this routing table is fresh to perform the required operation. + * @param {string} accessMode the type of operation. Allowed values are {@link READ} and {@link WRITE}. + * @return {boolean} `true` when this table contains servers to serve the required operation, `false` otherwise. + */ + + }, { + key: "isStaleFor", + value: function isStaleFor(accessMode) { + return this.expirationTime.lessThan(Date.now()) || this.routers.length < MIN_ROUTERS || accessMode === driver.READ && this.readers.length === 0 || accessMode === driver.WRITE && this.writers.length === 0; + } + /** + * Check if this routing table is expired for specified amount of duration + * + * @param {Integer} duration amount of duration in milliseconds to check for expiration + * @returns {boolean} + */ + + }, { + key: "isExpiredFor", + value: function isExpiredFor(duration) { + return this.expirationTime.add(duration).lessThan(Date.now()); + } + }, { + key: "allServers", + value: function allServers() { + return [].concat((0, _toConsumableArray2["default"])(this.routers), (0, _toConsumableArray2["default"])(this.readers), (0, _toConsumableArray2["default"])(this.writers)); + } + }, { + key: "toString", + value: function toString() { + return 'RoutingTable[' + "database=".concat(this.databaseName, ", ") + "expirationTime=".concat(this.expirationTime, ", ") + "currentTime=".concat(Date.now(), ", ") + "routers=[".concat(this.routers, "], ") + "readers=[".concat(this.readers, "], ") + "writers=[".concat(this.writers, "]]"); + } + }]); + return RoutingTable; +}(); +/** + * Remove all occurrences of the element in the array. + * @param {Array} array the array to filter. + * @param {Object} element the element to remove. + * @return {Array} new filtered array. + */ + + +exports["default"] = RoutingTable; + +function removeFromArray(array, element) { + return array.filter(function (item) { + return item.asKey() !== element.asKey(); + }); +} +}); + +createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.VERSION_IN_DEV = exports.VERSION_4_0_0 = exports.VERSION_3_5_0 = exports.VERSION_3_4_0 = exports.VERSION_3_2_0 = exports.ServerVersion = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var SERVER_VERSION_REGEX = new RegExp('^(Neo4j/)?(\\d+)\\.(\\d+)(?:\\.)?(\\d*)(\\.|-|\\+)?([0-9A-Za-z-.]*)?$'); +var NEO4J_IN_DEV_VERSION_STRING = 'Neo4j/dev'; + +var ServerVersion = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {number} major the major version number. + * @param {number} minor the minor version number. + * @param {number} patch the patch version number. + * @param {string} the original version string + */ + function ServerVersion(major, minor, patch, originalVersionString) { + (0, _classCallCheck2["default"])(this, ServerVersion); + this.major = major; + this.minor = minor; + this.patch = patch; + this._originalVersionString = originalVersionString; + } + /** + * Fetch server version using the given driver. + * @param {Driver} driver the driver to use. + * @return {Promise} promise resolved with a {@link ServerVersion} object or rejected with error. + */ + + + (0, _createClass2["default"])(ServerVersion, [{ + key: "compareTo", + + /** + * Compare this version to the given one. + * @param {ServerVersion} other the version to compare with. + * @return {number} value 0 if this version is the same as the given one, value less then 0 when this version + * was released earlier than the given one and value greater then 0 when this version was released after + * than the given one. + */ + value: function compareTo(other) { + var result = compareInts(this.major, other.major); + + if (result === 0) { + result = compareInts(this.minor, other.minor); + + if (result === 0) { + result = compareInts(this.patch, other.patch); + } + } + + return result; + } + }, { + key: "toString", + value: function toString() { + if (this._originalVersionString) { + return this._originalVersionString; + } + + return "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); + } + }], [{ + key: "fromDriver", + value: function fromDriver(driver) { + var session = driver.session(); + return session.run('RETURN 1').then(function (result) { + return session.close().then(function () { + return ServerVersion.fromString(result.summary.server.version); + }); + }); + } + /** + * Parse given string to a {@link ServerVersion} object. + * @param {string} versionStr the string to parse. + * @return {ServerVersion} version for the given string. + * @throws Error if given string can't be parsed. + */ + + }, { + key: "fromString", + value: function fromString(versionStr) { + if (!versionStr) { + return new ServerVersion(3, 0, 0); + } + + (0, util.assertString)(versionStr, 'Neo4j version string'); + + if (versionStr.toLowerCase() === NEO4J_IN_DEV_VERSION_STRING.toLowerCase()) { + return VERSION_IN_DEV; + } + + var version = versionStr.match(SERVER_VERSION_REGEX); + + if (!version) { + throw new Error("Unparsable Neo4j version: ".concat(versionStr)); + } + + var major = parseIntStrict(version[2]); + var minor = parseIntStrict(version[3]); + var patch = parseIntStrict(version[4] || 0); + return new ServerVersion(major, minor, patch, versionStr); + } + }]); + return ServerVersion; +}(); + +exports.ServerVersion = ServerVersion; + +function parseIntStrict(str, name) { + var value = parseInt(str, 10); + + if (!value && value !== 0) { + throw new Error("Unparsable number ".concat(name, ": '").concat(str, "'")); + } + + return value; +} + +function compareInts(x, y) { + return x < y ? -1 : x === y ? 0 : 1; +} + +var VERSION_3_2_0 = ServerVersion.fromString('Neo4j/3.2.0'); +exports.VERSION_3_2_0 = VERSION_3_2_0; +var VERSION_3_4_0 = ServerVersion.fromString('Neo4j/3.4.0'); +exports.VERSION_3_4_0 = VERSION_3_4_0; +var VERSION_3_5_0 = ServerVersion.fromString('Neo4j/3.5.0'); +exports.VERSION_3_5_0 = VERSION_3_5_0; +var VERSION_4_0_0 = ServerVersion.fromString('Neo4j/4.0.0'); +exports.VERSION_4_0_0 = VERSION_4_0_0; +var maxVer = Number.MAX_SAFE_INTEGER; +var VERSION_IN_DEV = new ServerVersion(maxVer, maxVer, maxVer, NEO4J_IN_DEV_VERSION_STRING); +exports.VERSION_IN_DEV = VERSION_IN_DEV; +}); + +/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ + +var uri_all = createCommonjsModule(function (module, exports) { +(function (global, factory) { + factory(exports) ; +}(commonjsGlobal, (function (exports) { +function merge() { + for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { + sets[_key] = arguments[_key]; + } + + if (sets.length > 1) { + sets[0] = sets[0].slice(0, -1); + var xl = sets.length - 1; + for (var x = 1; x < xl; ++x) { + sets[x] = sets[x].slice(1, -1); + } + sets[xl] = sets[xl].slice(1); + return sets.join(''); + } else { + return sets[0]; + } +} +function subexp(str) { + return "(?:" + str + ")"; +} +function typeOf(o) { + return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); +} +function toUpperCase(str) { + return str.toUpperCase(); +} +function toArray(obj) { + return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; +} +function assign(target, source) { + var obj = target; + if (source) { + for (var key in source) { + obj[key] = source[key]; + } + } + return obj; +} + +function buildExps(isIRI) { + var ALPHA$$ = "[A-Za-z]", + DIGIT$$ = "[0-9]", + HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), + PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), + //expanded + GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", + SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", + RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), + UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", + //subset, excludes bidi control characters + IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", + //subset + UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$); + subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"); + subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"); + var DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), + //relaxed parsing rules + IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), + H16$ = subexp(HEXDIG$$ + "{1,4}"), + LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), + IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), + // 6( h16 ":" ) ls32 + IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), + // "::" 5( h16 ":" ) ls32 + IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), + //[ h16 ] "::" 4( h16 ":" ) ls32 + IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), + //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 + IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), + //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 + IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), + //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 + IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), + //[ *4( h16 ":" ) h16 ] "::" ls32 + IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), + //[ *5( h16 ":" ) h16 ] "::" h16 + IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), + //[ *6( h16 ":" ) h16 ] "::" + IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), + ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"); + //RFC 6874, with relaxed parsing rules + subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"); + //RFC 6874 + subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"); + var PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")); + subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"); + subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"); + return { + NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), + NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), + NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), + NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), + ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), + UNRESERVED: new RegExp(UNRESERVED$$, "g"), + OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), + PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), + IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), + IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules + }; +} +var URI_PROTOCOL = buildExps(false); + +var IRI_PROTOCOL = buildExps(true); + +var slicedToArray = function () { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = undefined; + + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; + } + + return function (arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if (Symbol.iterator in Object(arr)) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); + + + + + + + + + + + + + +var toConsumableArray = function (arr) { + if (Array.isArray(arr)) { + for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; + + return arr2; + } else { + return Array.from(arr); + } +}; + +/** Highest positive signed 32-bit float value */ + +var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + +/** Bootstring parameters */ +var base = 36; +var tMin = 1; +var tMax = 26; +var skew = 38; +var damp = 700; +var initialBias = 72; +var initialN = 128; // 0x80 +var delimiter = '-'; // '\x2D' + +/** Regular expressions */ +var regexPunycode = /^xn--/; +var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars +var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + +/** Error messages */ +var errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' +}; + +/** Convenience shortcuts */ +var baseMinusTMin = base - tMin; +var floor = Math.floor; +var stringFromCharCode = String.fromCharCode; + +/*--------------------------------------------------------------------------*/ + +/** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ +function error$1(type) { + throw new RangeError(errors[type]); +} + +/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ +function map(array, fn) { + var result = []; + var length = array.length; + while (length--) { + result[length] = fn(array[length]); + } + return result; +} + +/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ +function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; +} + +/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ +function ucs2decode(string) { + var output = []; + var counter = 0; + var length = string.length; + while (counter < length) { + var value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // It's a high surrogate, and there is a next character. + var extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { + // Low surrogate. + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // It's an unmatched surrogate; only append this code unit, in case the + // next code unit is the high surrogate of a surrogate pair. + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; +} + +/** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ +var ucs2encode = function ucs2encode(array) { + return String.fromCodePoint.apply(String, toConsumableArray(array)); +}; + +/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ +var basicToDigit = function basicToDigit(codePoint) { + if (codePoint - 0x30 < 0x0A) { + return codePoint - 0x16; + } + if (codePoint - 0x41 < 0x1A) { + return codePoint - 0x41; + } + if (codePoint - 0x61 < 0x1A) { + return codePoint - 0x61; + } + return base; +}; + +/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ +var digitToBasic = function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); +}; + +/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ +var adapt = function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); +}; + +/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ +var decode = function decode(input) { + // Don't use UCS-2. + var output = []; + var inputLength = input.length; + var i = 0; + var n = initialN; + var bias = initialBias; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + var basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (var j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error$1('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + var oldi = i; + for (var w = 1, k = base;; /* no condition */k += base) { + + if (index >= inputLength) { + error$1('invalid-input'); + } + + var digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error$1('overflow'); + } + + i += digit * w; + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + + if (digit < t) { + break; + } + + var baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error$1('overflow'); + } + + w *= baseMinusT; + } + + var out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error$1('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output. + output.splice(i++, 0, n); + } + + return String.fromCodePoint.apply(String, output); +}; + +/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ +var encode = function encode(input) { + var output = []; + + // Convert the input in UCS-2 to an array of Unicode code points. + input = ucs2decode(input); + + // Cache the length. + var inputLength = input.length; + + // Initialize the state. + var n = initialN; + var delta = 0; + var bias = initialBias; + + // Handle the basic code points. + var _iteratorNormalCompletion = true; + var _didIteratorError = false; + var _iteratorError = undefined; + + try { + for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { + var _currentValue2 = _step.value; + + if (_currentValue2 < 0x80) { + output.push(stringFromCharCode(_currentValue2)); + } + } + } catch (err) { + _didIteratorError = true; + _iteratorError = err; + } finally { + try { + if (!_iteratorNormalCompletion && _iterator.return) { + _iterator.return(); + } + } finally { + if (_didIteratorError) { + throw _iteratorError; + } + } + } + + var basicLength = output.length; + var handledCPCount = basicLength; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string with a delimiter unless it's empty. + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + var m = maxInt; + var _iteratorNormalCompletion2 = true; + var _didIteratorError2 = false; + var _iteratorError2 = undefined; + + try { + for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { + var currentValue = _step2.value; + + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow. + } catch (err) { + _didIteratorError2 = true; + _iteratorError2 = err; + } finally { + try { + if (!_iteratorNormalCompletion2 && _iterator2.return) { + _iterator2.return(); + } + } finally { + if (_didIteratorError2) { + throw _iteratorError2; + } + } + } + + var handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error$1('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + var _iteratorNormalCompletion3 = true; + var _didIteratorError3 = false; + var _iteratorError3 = undefined; + + try { + for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { + var _currentValue = _step3.value; + + if (_currentValue < n && ++delta > maxInt) { + error$1('overflow'); + } + if (_currentValue == n) { + // Represent delta as a generalized variable-length integer. + var q = delta; + for (var k = base;; /* no condition */k += base) { + var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; + if (q < t) { + break; + } + var qMinusT = q - t; + var baseMinusT = base - t; + output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + } catch (err) { + _didIteratorError3 = true; + _iteratorError3 = err; + } finally { + try { + if (!_iteratorNormalCompletion3 && _iterator3.return) { + _iterator3.return(); + } + } finally { + if (_didIteratorError3) { + throw _iteratorError3; + } + } + } + + ++delta; + ++n; + } + return output.join(''); +}; + +/** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ +var toUnicode = function toUnicode(input) { + return mapDomain(input, function (string) { + return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; + }); +}; + +/** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ +var toASCII = function toASCII(input) { + return mapDomain(input, function (string) { + return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; + }); +}; + +/*--------------------------------------------------------------------------*/ + +/** Define the public API */ +var punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '2.1.0', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode +}; + +/** + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author Gary Court + * @see http://github.com/garycourt/uri-js + */ +/** + * Copyright 2011 Gary Court. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list + * of conditions and the following disclaimer in the documentation and/or other materials + * provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED + * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND + * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + * + * The views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. + */ +var SCHEMES = {}; +function pctEncChar(chr) { + var c = chr.charCodeAt(0); + var e = void 0; + if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); + return e; +} +function pctDecChars(str) { + var newStr = ""; + var i = 0; + var il = str.length; + while (i < il) { + var c = parseInt(str.substr(i + 1, 2), 16); + if (c < 128) { + newStr += String.fromCharCode(c); + i += 3; + } else if (c >= 194 && c < 224) { + if (il - i >= 6) { + var c2 = parseInt(str.substr(i + 4, 2), 16); + newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); + } else { + newStr += str.substr(i, 6); + } + i += 6; + } else if (c >= 224) { + if (il - i >= 9) { + var _c = parseInt(str.substr(i + 4, 2), 16); + var c3 = parseInt(str.substr(i + 7, 2), 16); + newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); + } else { + newStr += str.substr(i, 9); + } + i += 9; + } else { + newStr += str.substr(i, 3); + i += 3; + } + } + return newStr; +} +function _normalizeComponentEncoding(components, protocol) { + function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(protocol.UNRESERVED) ? str : decStr; + } + if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); + if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); + return components; +} + +function _stripLeadingZeros(str) { + return str.replace(/^0*(.*)/, "$1") || "0"; +} +function _normalizeIPv4(host, protocol) { + var matches = host.match(protocol.IPV4ADDRESS) || []; + + var _matches = slicedToArray(matches, 2), + address = _matches[1]; + + if (address) { + return address.split(".").map(_stripLeadingZeros).join("."); + } else { + return host; + } +} +function _normalizeIPv6(host, protocol) { + var matches = host.match(protocol.IPV6ADDRESS) || []; + + var _matches2 = slicedToArray(matches, 3), + address = _matches2[1], + zone = _matches2[2]; + + if (address) { + var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), + _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), + last = _address$toLowerCase$2[0], + first = _address$toLowerCase$2[1]; + + var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; + var lastFields = last.split(":").map(_stripLeadingZeros); + var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); + var fieldCount = isLastFieldIPv4Address ? 7 : 8; + var lastFieldsStart = lastFields.length - fieldCount; + var fields = Array(fieldCount); + for (var x = 0; x < fieldCount; ++x) { + fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; + } + if (isLastFieldIPv4Address) { + fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); + } + var allZeroFields = fields.reduce(function (acc, field, index) { + if (!field || field === "0") { + var lastLongest = acc[acc.length - 1]; + if (lastLongest && lastLongest.index + lastLongest.length === index) { + lastLongest.length++; + } else { + acc.push({ index: index, length: 1 }); + } + } + return acc; + }, []); + var longestZeroFields = allZeroFields.sort(function (a, b) { + return b.length - a.length; + })[0]; + var newHost = void 0; + if (longestZeroFields && longestZeroFields.length > 1) { + var newFirst = fields.slice(0, longestZeroFields.index); + var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); + newHost = newFirst.join(":") + "::" + newLast.join(":"); + } else { + newHost = fields.join(":"); + } + if (zone) { + newHost += "%" + zone; + } + return newHost; + } else { + return host; + } +} +var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; +var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; +function parse(uriString) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var components = {}; + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; + var matches = uriString.match(URI_PARSE); + if (matches) { + if (NO_MATCH_IS_UNDEFINED) { + //store each component + components.scheme = matches[1]; + components.userinfo = matches[3]; + components.host = matches[4]; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = matches[7]; + components.fragment = matches[8]; + //fix port number + if (isNaN(components.port)) { + components.port = matches[5]; + } + } else { + //IE FIX for improper RegExp matching + //store each component + components.scheme = matches[1] || undefined; + components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; + components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; + components.port = parseInt(matches[5], 10); + components.path = matches[6] || ""; + components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; + components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; + //fix port number + if (isNaN(components.port)) { + components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; + } + } + if (components.host) { + //normalize IP hosts + components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); + } + //determine reference type + if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { + components.reference = "same-document"; + } else if (components.scheme === undefined) { + components.reference = "relative"; + } else if (components.fragment === undefined) { + components.reference = "absolute"; + } else { + components.reference = "uri"; + } + //check for reference errors + if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { + components.error = components.error || "URI is not a " + options.reference + " reference."; + } + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //check if scheme can't handle IRIs + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + //if host component is a domain name + if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { + //convert Unicode IDN -> ASCII IDN + try { + components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; + } + } + //convert IRI -> URI + _normalizeComponentEncoding(components, URI_PROTOCOL); + } else { + //normalize encodings + _normalizeComponentEncoding(components, protocol); + } + //perform scheme specific parsing + if (schemeHandler && schemeHandler.parse) { + schemeHandler.parse(components, options); + } + } else { + components.error = components.error || "URI can not be parsed."; + } + return components; +} + +function _recomposeAuthority(components, options) { + var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + if (components.userinfo !== undefined) { + uriTokens.push(components.userinfo); + uriTokens.push("@"); + } + if (components.host !== undefined) { + //normalize IP hosts, add brackets and escape zone separator for IPv6 + uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { + return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; + })); + } + if (typeof components.port === "number" || typeof components.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(components.port)); + } + return uriTokens.length ? uriTokens.join("") : undefined; +} + +var RDS1 = /^\.\.?\//; +var RDS2 = /^\/\.(\/|$)/; +var RDS3 = /^\/\.\.(\/|$)/; +var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; +function removeDotSegments(input) { + var output = []; + while (input.length) { + if (input.match(RDS1)) { + input = input.replace(RDS1, ""); + } else if (input.match(RDS2)) { + input = input.replace(RDS2, "/"); + } else if (input.match(RDS3)) { + input = input.replace(RDS3, "/"); + output.pop(); + } else if (input === "." || input === "..") { + input = ""; + } else { + var im = input.match(RDS5); + if (im) { + var s = im[0]; + input = input.slice(s.length); + output.push(s); + } else { + throw new Error("Unexpected dot segment condition"); + } + } + } + return output.join(""); +} + +function serialize(components) { + var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; + + var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; + var uriTokens = []; + //find scheme handler + var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; + //perform scheme specific serialization + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); + if (components.host) { + //if host component is an IPv6 address + if (protocol.IPV6ADDRESS.test(components.host)) ; + //TODO: normalize IPv6 address as per RFC 5952 + + //if host component is a domain name + else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { + //convert IDN via punycode + try { + components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); + } catch (e) { + components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + } + } + //normalize encoding + _normalizeComponentEncoding(components, protocol); + if (options.reference !== "suffix" && components.scheme) { + uriTokens.push(components.scheme); + uriTokens.push(":"); + } + var authority = _recomposeAuthority(components, options); + if (authority !== undefined) { + if (options.reference !== "suffix") { + uriTokens.push("//"); + } + uriTokens.push(authority); + if (components.path && components.path.charAt(0) !== "/") { + uriTokens.push("/"); + } + } + if (components.path !== undefined) { + var s = components.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { + s = removeDotSegments(s); + } + if (authority === undefined) { + s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" + } + uriTokens.push(s); + } + if (components.query !== undefined) { + uriTokens.push("?"); + uriTokens.push(components.query); + } + if (components.fragment !== undefined) { + uriTokens.push("#"); + uriTokens.push(components.fragment); + } + return uriTokens.join(""); //merge tokens into a string +} + +function resolveComponents(base, relative) { + var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + var skipNormalization = arguments[3]; + + var target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); //normalize base components + relative = parse(serialize(relative, options), options); //normalize relative components + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { + //target.authority = relative.authority; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== undefined) { + target.query = relative.query; + } else { + target.query = base.query; + } + } else { + if (relative.path.charAt(0) === "/") { + target.path = removeDotSegments(relative.path); + } else { + if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { + target.path = "/" + relative.path; + } else if (!base.path) { + target.path = relative.path; + } else { + target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + } + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + //target.authority = base.authority; + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; +} + +function resolve(baseURI, relativeURI, options) { + var schemelessOptions = assign({ scheme: 'null' }, options); + return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); +} + +function normalize(uri, options) { + if (typeof uri === "string") { + uri = serialize(parse(uri, options), options); + } else if (typeOf(uri) === "object") { + uri = parse(serialize(uri, options), options); + } + return uri; +} + +function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = serialize(parse(uriA, options), options); + } else if (typeOf(uriA) === "object") { + uriA = serialize(uriA, options); + } + if (typeof uriB === "string") { + uriB = serialize(parse(uriB, options), options); + } else if (typeOf(uriB) === "object") { + uriB = serialize(uriB, options); + } + return uriA === uriB; +} + +function escapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); +} + +function unescapeComponent(str, options) { + return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); +} + +var handler = { + scheme: "http", + domainHost: true, + parse: function parse(components, options) { + //report missing host + if (!components.host) { + components.error = components.error || "HTTP URIs must have a host."; + } + return components; + }, + serialize: function serialize(components, options) { + var secure = String(components.scheme).toLowerCase() === "https"; + //normalize the default port + if (components.port === (secure ? 443 : 80) || components.port === "") { + components.port = undefined; + } + //normalize the empty path + if (!components.path) { + components.path = "/"; + } + //NOTE: We do not parse query strings for HTTP URIs + //as WWW Form Url Encoded query strings are part of the HTML4+ spec, + //and not the HTTP spec. + return components; + } +}; + +var handler$1 = { + scheme: "https", + domainHost: handler.domainHost, + parse: handler.parse, + serialize: handler.serialize +}; + +function isSecure(wsComponents) { + return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; +} +//RFC 6455 +var handler$2 = { + scheme: "ws", + domainHost: true, + parse: function parse(components, options) { + var wsComponents = components; + //indicate if the secure flag is set + wsComponents.secure = isSecure(wsComponents); + //construct resouce name + wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); + wsComponents.path = undefined; + wsComponents.query = undefined; + return wsComponents; + }, + serialize: function serialize(wsComponents, options) { + //normalize the default port + if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { + wsComponents.port = undefined; + } + //ensure scheme matches secure flag + if (typeof wsComponents.secure === 'boolean') { + wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws'; + wsComponents.secure = undefined; + } + //reconstruct path from resource name + if (wsComponents.resourceName) { + var _wsComponents$resourc = wsComponents.resourceName.split('?'), + _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), + path = _wsComponents$resourc2[0], + query = _wsComponents$resourc2[1]; + + wsComponents.path = path && path !== '/' ? path : undefined; + wsComponents.query = query; + wsComponents.resourceName = undefined; + } + //forbid fragment component + wsComponents.fragment = undefined; + return wsComponents; + } +}; + +var handler$3 = { + scheme: "wss", + domainHost: handler$2.domainHost, + parse: handler$2.parse, + serialize: handler$2.serialize +}; + +var O = {}; +//RFC 3986 +var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + ("\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" ) + "]"; +var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive +var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded +//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = +//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) +//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext +//const VCHAR$$ = "[\\x21-\\x7E]"; +//const WSP$$ = "[\\x20\\x09]"; +//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext +//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); +//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); +//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); +var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; +var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; +var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); +var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; +var UNRESERVED = new RegExp(UNRESERVED$$, "g"); +var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); +var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); +var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); +var NOT_HFVALUE = NOT_HFNAME; +function decodeUnreserved(str) { + var decStr = pctDecChars(str); + return !decStr.match(UNRESERVED) ? str : decStr; +} +var handler$4 = { + scheme: "mailto", + parse: function parse$$1(components, options) { + var mailtoComponents = components; + var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; + mailtoComponents.path = undefined; + if (mailtoComponents.query) { + var unknownHeaders = false; + var headers = {}; + var hfields = mailtoComponents.query.split("&"); + for (var x = 0, xl = hfields.length; x < xl; ++x) { + var hfield = hfields[x].split("="); + switch (hfield[0]) { + case "to": + var toAddrs = hfield[1].split(","); + for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { + to.push(toAddrs[_x]); + } + break; + case "subject": + mailtoComponents.subject = unescapeComponent(hfield[1], options); + break; + case "body": + mailtoComponents.body = unescapeComponent(hfield[1], options); + break; + default: + unknownHeaders = true; + headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); + break; + } + } + if (unknownHeaders) mailtoComponents.headers = headers; + } + mailtoComponents.query = undefined; + for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { + var addr = to[_x2].split("@"); + addr[0] = unescapeComponent(addr[0]); + if (!options.unicodeSupport) { + //convert Unicode IDN -> ASCII IDN + try { + addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); + } catch (e) { + mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; + } + } else { + addr[1] = unescapeComponent(addr[1], options).toLowerCase(); + } + to[_x2] = addr.join("@"); + } + return mailtoComponents; + }, + serialize: function serialize$$1(mailtoComponents, options) { + var components = mailtoComponents; + var to = toArray(mailtoComponents.to); + if (to) { + for (var x = 0, xl = to.length; x < xl; ++x) { + var toAddr = String(to[x]); + var atIdx = toAddr.lastIndexOf("@"); + var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); + var domain = toAddr.slice(atIdx + 1); + //convert IDN via punycode + try { + domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); + } catch (e) { + components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; + } + to[x] = localPart + "@" + domain; + } + components.path = to.join(","); + } + var headers = mailtoComponents.headers = mailtoComponents.headers || {}; + if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; + if (mailtoComponents.body) headers["body"] = mailtoComponents.body; + var fields = []; + for (var name in headers) { + if (headers[name] !== O[name]) { + fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); + } + } + if (fields.length) { + components.query = fields.join("&"); + } + return components; + } +}; + +var URN_PARSE = /^([^\:]+)\:(.*)/; +//RFC 2141 +var handler$5 = { + scheme: "urn", + parse: function parse$$1(components, options) { + var matches = components.path && components.path.match(URN_PARSE); + var urnComponents = components; + if (matches) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = matches[1].toLowerCase(); + var nss = matches[2]; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + urnComponents.nid = nid; + urnComponents.nss = nss; + urnComponents.path = undefined; + if (schemeHandler) { + urnComponents = schemeHandler.parse(urnComponents, options); + } + } else { + urnComponents.error = urnComponents.error || "URN can not be parsed."; + } + return urnComponents; + }, + serialize: function serialize$$1(urnComponents, options) { + var scheme = options.scheme || urnComponents.scheme || "urn"; + var nid = urnComponents.nid; + var urnScheme = scheme + ":" + (options.nid || nid); + var schemeHandler = SCHEMES[urnScheme]; + if (schemeHandler) { + urnComponents = schemeHandler.serialize(urnComponents, options); + } + var uriComponents = urnComponents; + var nss = urnComponents.nss; + uriComponents.path = (nid || options.nid) + ":" + nss; + return uriComponents; + } +}; + +var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; +//RFC 4122 +var handler$6 = { + scheme: "urn:uuid", + parse: function parse(urnComponents, options) { + var uuidComponents = urnComponents; + uuidComponents.uuid = uuidComponents.nss; + uuidComponents.nss = undefined; + if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { + uuidComponents.error = uuidComponents.error || "UUID is not valid."; + } + return uuidComponents; + }, + serialize: function serialize(uuidComponents, options) { + var urnComponents = uuidComponents; + //normalize UUID + urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); + return urnComponents; + } +}; + +SCHEMES[handler.scheme] = handler; +SCHEMES[handler$1.scheme] = handler$1; +SCHEMES[handler$2.scheme] = handler$2; +SCHEMES[handler$3.scheme] = handler$3; +SCHEMES[handler$4.scheme] = handler$4; +SCHEMES[handler$5.scheme] = handler$5; +SCHEMES[handler$6.scheme] = handler$6; + +exports.SCHEMES = SCHEMES; +exports.pctEncChar = pctEncChar; +exports.pctDecChars = pctDecChars; +exports.parse = parse; +exports.removeDotSegments = removeDotSegments; +exports.serialize = serialize; +exports.resolveComponents = resolveComponents; +exports.resolve = resolve; +exports.normalize = normalize; +exports.equal = equal; +exports.escapeComponent = escapeComponent; +exports.unescapeComponent = unescapeComponent; + +Object.defineProperty(exports, '__esModule', { value: true }); + +}))); + +}); + +var urlUtil = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _slicedToArray2 = interopRequireDefault(slicedToArray); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var DEFAULT_BOLT_PORT = 7687; +var DEFAULT_HTTP_PORT = 7474; +var DEFAULT_HTTPS_PORT = 7473; + +var Url = function Url(scheme, host, port, hostAndPort, query) { + (0, _classCallCheck2["default"])(this, Url); + + /** + * Nullable scheme (protocol) of the URL. + * Example: 'bolt', 'neo4j', 'http', 'https', etc. + * @type {string} + */ + this.scheme = scheme; + /** + * Nonnull host name or IP address. IPv6 not wrapped in square brackets. + * Example: 'neo4j.com', 'localhost', '127.0.0.1', '192.168.10.15', '::1', '2001:4860:4860::8844', etc. + * @type {string} + */ + + this.host = host; + /** + * Nonnull number representing port. Default port for the given scheme is used if given URL string + * does not contain port. Example: 7687 for bolt, 7474 for HTTP and 7473 for HTTPS. + * @type {number} + */ + + this.port = port; + /** + * Nonnull host name or IP address plus port, separated by ':'. IPv6 wrapped in square brackets. + * Example: 'neo4j.com', 'neo4j.com:7687', '127.0.0.1', '127.0.0.1:8080', '[2001:4860:4860::8844]', + * '[2001:4860:4860::8844]:9090', etc. + * @type {string} + */ + + this.hostAndPort = hostAndPort; + /** + * Nonnull object representing parsed query string key-value pairs. Duplicated keys not supported. + * Example: '{}', '{'key1': 'value1', 'key2': 'value2'}', etc. + * @type {Object} + */ + + this.query = query; +}; + +function parseDatabaseUrl(url) { + (0, util.assertString)(url, 'URL'); + var sanitized = sanitizeUrl(url); + var parsedUrl = (0, uri_all.parse)(sanitized.url); + var scheme = sanitized.schemeMissing ? null : extractScheme(parsedUrl.scheme); + var host = extractHost(parsedUrl.host); // no square brackets for IPv6 + + var formattedHost = formatHost(host); // has square brackets for IPv6 + + var port = extractPort(parsedUrl.port, scheme); + var hostAndPort = "".concat(formattedHost, ":").concat(port); + var query = extractQuery(parsedUrl.query || extractResourceQueryString(parsedUrl.resourceName), url); + return new Url(scheme, host, port, hostAndPort, query); +} + +function extractResourceQueryString(resource) { + if (typeof resource !== 'string') { + return null; + } + + var _resource$split = resource.split('?'), + _resource$split2 = (0, _slicedToArray2["default"])(_resource$split, 2); + _resource$split2[0]; + var query = _resource$split2[1]; + + return query; +} + +function sanitizeUrl(url) { + url = url.trim(); + + if (url.indexOf('://') === -1) { + // url does not contain scheme, add dummy 'none://' to make parser work correctly + return { + schemeMissing: true, + url: "none://".concat(url) + }; + } + + return { + schemeMissing: false, + url: url + }; +} + +function extractScheme(scheme) { + if (scheme) { + scheme = scheme.trim(); + + if (scheme.charAt(scheme.length - 1) === ':') { + scheme = scheme.substring(0, scheme.length - 1); + } + + return scheme; + } + + return null; +} + +function extractHost(host, url) { + if (!host) { + throw new Error("Unable to extract host from ".concat(url)); + } + + return host.trim(); +} + +function extractPort(portString, scheme) { + var port = parseInt(portString, 10); + return port === 0 || port ? port : defaultPortForScheme(scheme); +} + +function extractQuery(queryString, url) { + var query = trimAndSanitizeQuery(queryString); + var context = {}; + + if (query) { + query.split('&').forEach(function (pair) { + var keyValue = pair.split('='); + + if (keyValue.length !== 2) { + throw new Error("Invalid parameters: '".concat(keyValue, "' in URL '").concat(url, "'.")); + } + + var key = trimAndVerifyQueryElement(keyValue[0], 'key', url); + var value = trimAndVerifyQueryElement(keyValue[1], 'value', url); + + if (context[key]) { + throw new Error("Duplicated query parameters with key '".concat(key, "' in URL '").concat(url, "'")); + } + + context[key] = value; + }); + } + + return context; +} + +function trimAndSanitizeQuery(query) { + query = (query || '').trim(); + + if (query && query.charAt(0) === '?') { + query = query.substring(1, query.length); + } + + return query; +} + +function trimAndVerifyQueryElement(element, name, url) { + element = (element || '').trim(); + + if (!element) { + throw new Error("Illegal empty ".concat(name, " in URL query '").concat(url, "'")); + } + + return element; +} + +function escapeIPv6Address(address) { + var startsWithSquareBracket = address.charAt(0) === '['; + var endsWithSquareBracket = address.charAt(address.length - 1) === ']'; + + if (!startsWithSquareBracket && !endsWithSquareBracket) { + return "[".concat(address, "]"); + } else if (startsWithSquareBracket && endsWithSquareBracket) { + return address; + } else { + throw new Error("Illegal IPv6 address ".concat(address)); + } +} + +function formatHost(host) { + if (!host) { + throw new Error("Illegal host ".concat(host)); + } + + var isIPv6Address = host.indexOf(':') >= 0; + return isIPv6Address ? escapeIPv6Address(host) : host; +} + +function formatIPv4Address(address, port) { + return "".concat(address, ":").concat(port); +} + +function formatIPv6Address(address, port) { + var escapedAddress = escapeIPv6Address(address); + return "".concat(escapedAddress, ":").concat(port); +} + +function defaultPortForScheme(scheme) { + if (scheme === 'http') { + return DEFAULT_HTTP_PORT; + } else if (scheme === 'https') { + return DEFAULT_HTTPS_PORT; + } else { + return DEFAULT_BOLT_PORT; + } +} + +var _default = { + parseDatabaseUrl: parseDatabaseUrl, + defaultPortForScheme: defaultPortForScheme, + formatIPv4Address: formatIPv4Address, + formatIPv6Address: formatIPv6Address +}; +exports["default"] = _default; +}); + +var serverAddress = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +var _urlUtil = interopRequireDefault(urlUtil); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var ServerAddress = +/*#__PURE__*/ +function () { + function ServerAddress(host, resolved, port, hostPort) { + (0, _classCallCheck2["default"])(this, ServerAddress); + this._host = (0, util.assertString)(host, 'host'); + this._resolved = resolved ? (0, util.assertString)(resolved, 'resolved') : null; + this._port = (0, util.assertNumber)(port, 'port'); + this._hostPort = hostPort; + this._stringValue = resolved ? "".concat(hostPort, "(").concat(resolved, ")") : "".concat(hostPort); + } + + (0, _createClass2["default"])(ServerAddress, [{ + key: "host", + value: function host() { + return this._host; + } + }, { + key: "resolvedHost", + value: function resolvedHost() { + return this._resolved ? this._resolved : this._host; + } + }, { + key: "port", + value: function port() { + return this._port; + } + }, { + key: "resolveWith", + value: function resolveWith(resolved) { + return new ServerAddress(this._host, resolved, this._port, this._hostPort); + } + }, { + key: "asHostPort", + value: function asHostPort() { + return this._hostPort; + } + }, { + key: "asKey", + value: function asKey() { + return this._hostPort; + } + }, { + key: "toString", + value: function toString() { + return this._stringValue; + } + }], [{ + key: "fromUrl", + value: function fromUrl(url) { + var urlParsed = _urlUtil["default"].parseDatabaseUrl(url); + + return new ServerAddress(urlParsed.host, null, urlParsed.port, urlParsed.hostAndPort); + } + }]); + return ServerAddress; +}(); + +exports["default"] = ServerAddress; +}); + +var routingUtil = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _regenerator = interopRequireDefault(regenerator); + +var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + + + +var _integer = interopRequireWildcard(integer); + + + +interopRequireDefault(bookmark); + +interopRequireDefault(session); + +var _txConfig = interopRequireDefault(txConfig); + +var _serverAddress = interopRequireDefault(serverAddress); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var CONTEXT = 'context'; +var CALL_GET_ROUTING_TABLE = "CALL dbms.cluster.routing.getRoutingTable($".concat(CONTEXT, ")"); +var DATABASE = 'database'; +var CALL_GET_ROUTING_TABLE_MULTI_DB = "CALL dbms.routing.getRoutingTable($".concat(CONTEXT, ", $").concat(DATABASE, ")"); +var PROCEDURE_NOT_FOUND_CODE = 'Neo.ClientError.Procedure.ProcedureNotFound'; +var DATABASE_NOT_FOUND_CODE = 'Neo.ClientError.Database.DatabaseNotFound'; + +var RoutingUtil = +/*#__PURE__*/ +function () { + function RoutingUtil(routingContext, initialAddress) { + (0, _classCallCheck2["default"])(this, RoutingUtil); + this._routingContext = routingContext; // The address that the driver is connecting to, used by routing as a fallback when routing + // and clustering isn't configured. + + this._initialAddress = initialAddress; + } + /** + * Invoke routing procedure using the given session. + * @param {Session} session the session to use. + * @param {string} routerAddress the URL of the router. + * @return {Promise} promise resolved with records returned by the procedure call or null if + * connection error happened. + */ + + + (0, _createClass2["default"])(RoutingUtil, [{ + key: "callRoutingProcedure", + value: function () { + var _callRoutingProcedure = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee(session, database, routerAddress) { + var result; + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.prev = 0; + _context.next = 3; + return this._callAvailableRoutingProcedure(session, database); + + case 3: + result = _context.sent; + _context.next = 6; + return session.close(); + + case 6: + return _context.abrupt("return", result.records); + + case 9: + _context.prev = 9; + _context.t0 = _context["catch"](0); + + if (!(_context.t0.code === DATABASE_NOT_FOUND_CODE)) { + _context.next = 15; + break; + } + + throw _context.t0; + + case 15: + if (!(_context.t0.code === PROCEDURE_NOT_FOUND_CODE)) { + _context.next = 19; + break; + } + + throw (0, error.newError)("Server at ".concat(routerAddress.asHostPort(), " can't perform routing. Make sure you are connecting to a causal cluster"), error.SERVICE_UNAVAILABLE); + + case 19: + return _context.abrupt("return", null); + + case 20: + case "end": + return _context.stop(); + } + } + }, _callee, this, [[0, 9]]); + })); + + function callRoutingProcedure(_x, _x2, _x3) { + return _callRoutingProcedure.apply(this, arguments); + } + + return callRoutingProcedure; + }() + }, { + key: "parseTtl", + value: function parseTtl(record, routerAddress) { + try { + var now = (0, _integer["int"])(Date.now()); + var expires = (0, _integer["int"])(record.get('ttl')).multiply(1000).add(now); // if the server uses a really big expire time like Long.MAX_VALUE this may have overflowed + + if (expires.lessThan(now)) { + return _integer["default"].MAX_VALUE; + } + + return expires; + } catch (error$1) { + throw (0, error.newError)("Unable to parse TTL entry from router ".concat(routerAddress, " from record:\n").concat(JSON.stringify(record), "\nError message: ").concat(error$1.message), error.PROTOCOL_ERROR); + } + } + }, { + key: "parseServers", + value: function parseServers(record, routerAddress) { + try { + var servers = record.get('servers'); + var routers = []; + var readers = []; + var writers = []; + servers.forEach(function (server) { + var role = server.role; + var addresses = server.addresses; + + if (role === 'ROUTE') { + routers = parseArray(addresses).map(function (address) { + return _serverAddress["default"].fromUrl(address); + }); + } else if (role === 'WRITE') { + writers = parseArray(addresses).map(function (address) { + return _serverAddress["default"].fromUrl(address); + }); + } else if (role === 'READ') { + readers = parseArray(addresses).map(function (address) { + return _serverAddress["default"].fromUrl(address); + }); + } else { + throw (0, error.newError)('Unknown server role "' + role + '"', error.PROTOCOL_ERROR); + } + }); + return { + routers: routers, + readers: readers, + writers: writers + }; + } catch (error$1) { + throw (0, error.newError)("Unable to parse servers entry from router ".concat(routerAddress, " from record:\n").concat(JSON.stringify(record), "\nError message: ").concat(error$1.message), error.PROTOCOL_ERROR); + } + } + }, { + key: "_callAvailableRoutingProcedure", + value: function _callAvailableRoutingProcedure(session, database) { + var _this = this; + + return session._run(null, null, function (connection) { + var query; + var params; + var protocolVersion = connection.protocol().version; + + if (protocolVersion >= 4.0) { + query = CALL_GET_ROUTING_TABLE_MULTI_DB; + params = { + context: _this._routingContext || {}, + database: database || null + }; + params.context.address = _this._initialAddress; + } else { + query = CALL_GET_ROUTING_TABLE; + params = { + context: _this._routingContext + }; + } + + return connection.protocol().run(query, params, { + bookmark: session._lastBookmark, + txConfig: _txConfig["default"].empty(), + mode: session._mode, + database: session._database, + afterComplete: session._onComplete + }); + }); + } + }]); + return RoutingUtil; +}(); + +exports["default"] = RoutingUtil; + +function parseArray(addresses) { + if (!Array.isArray(addresses)) { + throw new TypeError('Array expected but got: ' + addresses); + } + + return Array.from(addresses); +} +}); + +var rediscovery = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _regenerator = interopRequireDefault(regenerator); + +var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _routingTable = interopRequireDefault(routingTable); + +interopRequireDefault(routingUtil); + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var Rediscovery = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {RoutingUtil} routingUtil the util to use. + */ + function Rediscovery(routingUtil) { + (0, _classCallCheck2["default"])(this, Rediscovery); + this._routingUtil = routingUtil; + } + /** + * Try to fetch new routing table from the given router. + * @param {Session} session the session to use. + * @param {string} database the database for which to lookup routing table. + * @param {string} routerAddress the URL of the router. + * @return {Promise} promise resolved with new routing table or null when connection error happened. + */ + + + (0, _createClass2["default"])(Rediscovery, [{ + key: "lookupRoutingTableOnRouter", + value: function () { + var _lookupRoutingTableOnRouter = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee(session, database, routerAddress) { + var records, record, expirationTime, _this$_routingUtil$pa, routers, readers, writers; + + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _context.next = 2; + return this._routingUtil.callRoutingProcedure(session, database, routerAddress); + + case 2: + records = _context.sent; + + if (!(records === null)) { + _context.next = 5; + break; + } + + return _context.abrupt("return", null); + + case 5: + if (!(records.length !== 1)) { + _context.next = 7; + break; + } + + throw (0, error.newError)('Illegal response from router "' + routerAddress + '". ' + 'Received ' + records.length + ' records but expected only one.\n' + JSON.stringify(records), error.PROTOCOL_ERROR); + + case 7: + record = records[0]; + expirationTime = this._routingUtil.parseTtl(record, routerAddress); + _this$_routingUtil$pa = this._routingUtil.parseServers(record, routerAddress), routers = _this$_routingUtil$pa.routers, readers = _this$_routingUtil$pa.readers, writers = _this$_routingUtil$pa.writers; + + Rediscovery._assertNonEmpty(routers, 'routers', routerAddress); + + Rediscovery._assertNonEmpty(readers, 'readers', routerAddress); // case with no writers is processed higher in the promise chain because only RoutingDriver knows + // how to deal with such table and how to treat router that returned such table + + + return _context.abrupt("return", new _routingTable["default"]({ + database: database, + routers: routers, + readers: readers, + writers: writers, + expirationTime: expirationTime + })); + + case 13: + case "end": + return _context.stop(); + } + } + }, _callee, this); + })); + + function lookupRoutingTableOnRouter(_x, _x2, _x3) { + return _lookupRoutingTableOnRouter.apply(this, arguments); + } + + return lookupRoutingTableOnRouter; + }() + }], [{ + key: "_assertNonEmpty", + value: function _assertNonEmpty(serverAddressesArray, serversName, routerAddress) { + if (serverAddressesArray.length === 0) { + throw (0, error.newError)('Received no ' + serversName + ' from router ' + routerAddress, error.PROTOCOL_ERROR); + } + } + }]); + return Rediscovery; +}(); + +exports["default"] = Rediscovery; +}); + +var connectionProviderSingle = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _connectionProvider = interopRequireDefault(connectionProvider); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var SingleConnectionProvider = +/*#__PURE__*/ +function (_ConnectionProvider) { + (0, _inherits2["default"])(SingleConnectionProvider, _ConnectionProvider); + + function SingleConnectionProvider(connection) { + var _this; + + (0, _classCallCheck2["default"])(this, SingleConnectionProvider); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(SingleConnectionProvider).call(this)); + _this._connection = connection; + return _this; + } + /** + * See {@link ConnectionProvider} for more information about this method and + * its arguments. + */ + + + (0, _createClass2["default"])(SingleConnectionProvider, [{ + key: "acquireConnection", + value: function acquireConnection() { + var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + _ref.accessMode; + _ref.database; + _ref.bookmarks; + + var connection = this._connection; + this._connection = null; + return Promise.resolve(connection); + } + }]); + return SingleConnectionProvider; +}(_connectionProvider["default"]); + +exports["default"] = SingleConnectionProvider; +}); + +var roundRobinArrayIndex = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var RoundRobinArrayIndex = +/*#__PURE__*/ +function () { + /** + * @constructor + * @param {number} [initialOffset=0] the initial offset for round robin. + */ + function RoundRobinArrayIndex(initialOffset) { + (0, _classCallCheck2["default"])(this, RoundRobinArrayIndex); + this._offset = initialOffset || 0; + } + /** + * Get next index for an array with given length. + * @param {number} arrayLength the array length. + * @return {number} index in the array. + */ + + + (0, _createClass2["default"])(RoundRobinArrayIndex, [{ + key: "next", + value: function next(arrayLength) { + if (arrayLength === 0) { + return -1; + } + + var nextOffset = this._offset; + this._offset += 1; + + if (this._offset === Number.MAX_SAFE_INTEGER) { + this._offset = 0; + } + + return nextOffset % arrayLength; + } + }]); + return RoundRobinArrayIndex; +}(); + +exports["default"] = RoundRobinArrayIndex; +}); + +var loadBalancingStrategy = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A facility to select most appropriate reader or writer among the given addresses for request processing. + */ +var LoadBalancingStrategy = +/*#__PURE__*/ +function () { + function LoadBalancingStrategy() { + (0, _classCallCheck2["default"])(this, LoadBalancingStrategy); + } + + (0, _createClass2["default"])(LoadBalancingStrategy, [{ + key: "selectReader", + + /** + * Select next most appropriate reader from the list of given readers. + * @param {string[]} knownReaders an array of currently known readers to select from. + * @return {string} most appropriate reader or `null` if given array is empty. + */ + value: function selectReader(knownReaders) { + throw new Error('Abstract function'); + } + /** + * Select next most appropriate writer from the list of given writers. + * @param {string[]} knownWriters an array of currently known writers to select from. + * @return {string} most appropriate writer or `null` if given array is empty. + */ + + }, { + key: "selectWriter", + value: function selectWriter(knownWriters) { + throw new Error('Abstract function'); + } + }]); + return LoadBalancingStrategy; +}(); + +exports["default"] = LoadBalancingStrategy; +}); + +var leastConnectedLoadBalancingStrategy = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + +var _roundRobinArrayIndex = interopRequireDefault(roundRobinArrayIndex); + +var _loadBalancingStrategy = interopRequireDefault(loadBalancingStrategy); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var LeastConnectedLoadBalancingStrategy = +/*#__PURE__*/ +function (_LoadBalancingStrateg) { + (0, _inherits2["default"])(LeastConnectedLoadBalancingStrategy, _LoadBalancingStrateg); + + /** + * @constructor + * @param {Pool} connectionPool the connection pool of this driver. + */ + function LeastConnectedLoadBalancingStrategy(connectionPool) { + var _this; + + (0, _classCallCheck2["default"])(this, LeastConnectedLoadBalancingStrategy); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(LeastConnectedLoadBalancingStrategy).call(this)); + _this._readersIndex = new _roundRobinArrayIndex["default"](); + _this._writersIndex = new _roundRobinArrayIndex["default"](); + _this._connectionPool = connectionPool; + return _this; + } + /** + * @inheritDoc + */ + + + (0, _createClass2["default"])(LeastConnectedLoadBalancingStrategy, [{ + key: "selectReader", + value: function selectReader(knownReaders) { + return this._select(knownReaders, this._readersIndex); + } + /** + * @inheritDoc + */ + + }, { + key: "selectWriter", + value: function selectWriter(knownWriters) { + return this._select(knownWriters, this._writersIndex); + } + }, { + key: "_select", + value: function _select(addresses, roundRobinIndex) { + var length = addresses.length; + + if (length === 0) { + return null; + } // choose start index for iteration in round-robin fashion + + + var startIndex = roundRobinIndex.next(length); + var index = startIndex; + var leastConnectedAddress = null; + var leastActiveConnections = Number.MAX_SAFE_INTEGER; // iterate over the array to find least connected address + + do { + var address = addresses[index]; + + var activeConnections = this._connectionPool.activeResourceCount(address); + + if (activeConnections < leastActiveConnections) { + leastConnectedAddress = address; + leastActiveConnections = activeConnections; + } // loop over to the start of the array when end is reached + + + if (index === length - 1) { + index = 0; + } else { + index++; + } + } while (index !== startIndex); + + return leastConnectedAddress; + } + }]); + return LeastConnectedLoadBalancingStrategy; +}(_loadBalancingStrategy["default"]); + +exports["default"] = LeastConnectedLoadBalancingStrategy; +}); + +var connectionProviderRouting = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _regenerator = interopRequireDefault(regenerator); + +var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + + + + + +var _session = interopRequireDefault(session); + +var _routingTable = interopRequireDefault(routingTable); + +var _rediscovery = interopRequireDefault(rediscovery); + +var _routingUtil = interopRequireDefault(routingUtil); + + + +var _connectionProviderSingle = interopRequireDefault(connectionProviderSingle); + +var _connectionProviderPooled = interopRequireDefault(connectionProviderPooled); + +var _connectionErrorHandler = interopRequireDefault(connectionErrorHandler); + +var _connectionDelegate = interopRequireDefault(connectionDelegate); + +var _leastConnectedLoadBalancingStrategy = interopRequireDefault(leastConnectedLoadBalancingStrategy); + +var _bookmark = interopRequireDefault(bookmark); + +var _connectionChannel = interopRequireDefault(connectionChannel); + + + + + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +var UNAUTHORIZED_ERROR_CODE = 'Neo.ClientError.Security.Unauthorized'; +var DATABASE_NOT_FOUND_ERROR_CODE = 'Neo.ClientError.Database.DatabaseNotFound'; +var SYSTEM_DB_NAME = 'system'; +var DEFAULT_DB_NAME = ''; +var DEFAULT_ROUTING_TABLE_PURGE_DELAY = (0, integer["int"])(30000); + +var RoutingConnectionProvider = +/*#__PURE__*/ +function (_PooledConnectionProv) { + (0, _inherits2["default"])(RoutingConnectionProvider, _PooledConnectionProv); + + function RoutingConnectionProvider(_ref) { + var _this; + + var id = _ref.id, + address = _ref.address, + routingContext = _ref.routingContext, + hostNameResolver = _ref.hostNameResolver, + config = _ref.config, + log = _ref.log, + userAgent = _ref.userAgent, + authToken = _ref.authToken, + routingTablePurgeDelay = _ref.routingTablePurgeDelay; + (0, _classCallCheck2["default"])(this, RoutingConnectionProvider); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(RoutingConnectionProvider).call(this, { + id: id, + config: config, + log: log, + userAgent: userAgent, + authToken: authToken + }, function (address) { + return _connectionChannel["default"].create(address, _this._config, _this._createConnectionErrorHandler(), _this._log, routingContext || {}); + })); + _this._seedRouter = address; + _this._routingTables = {}; + _this._rediscovery = new _rediscovery["default"](new _routingUtil["default"](routingContext, address.toString())); + _this._loadBalancingStrategy = new _leastConnectedLoadBalancingStrategy["default"](_this._connectionPool); + _this._hostNameResolver = hostNameResolver; + _this._dnsResolver = new node.HostNameResolver(); + _this._log = log; + _this._useSeedRouter = true; + _this._routingTablePurgeDelay = routingTablePurgeDelay ? (0, integer["int"])(routingTablePurgeDelay) : DEFAULT_ROUTING_TABLE_PURGE_DELAY; + return _this; + } + + (0, _createClass2["default"])(RoutingConnectionProvider, [{ + key: "_createConnectionErrorHandler", + value: function _createConnectionErrorHandler() { + // connection errors mean SERVICE_UNAVAILABLE for direct driver but for routing driver they should only + // result in SESSION_EXPIRED because there might still exist other servers capable of serving the request + return new _connectionErrorHandler["default"](error.SESSION_EXPIRED); + } + }, { + key: "_handleUnavailability", + value: function _handleUnavailability(error, address, database) { + this._log.warn("Routing driver ".concat(this._id, " will forget ").concat(address, " for database '").concat(database, "' because of an error ").concat(error.code, " '").concat(error.message, "'")); + + this.forget(address, database || ''); + return error; + } + }, { + key: "_handleWriteFailure", + value: function _handleWriteFailure(error$1, address, database) { + this._log.warn("Routing driver ".concat(this._id, " will forget writer ").concat(address, " for database '").concat(database, "' because of an error ").concat(error$1.code, " '").concat(error$1.message, "'")); + + this.forgetWriter(address, database || ''); + return (0, error.newError)('No longer possible to write to server at ' + address, error.SESSION_EXPIRED); + } + /** + * See {@link ConnectionProvider} for more information about this method and + * its arguments. + */ + + }, { + key: "acquireConnection", + value: function () { + var _acquireConnection = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee() { + var _this2 = this; + + var _ref2, + accessMode, + database, + bookmark, + name, + address, + databaseSpecificErrorHandler, + routingTable, + connection, + transformed, + _args = arguments; + + return _regenerator["default"].wrap(function _callee$(_context) { + while (1) { + switch (_context.prev = _context.next) { + case 0: + _ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, accessMode = _ref2.accessMode, database = _ref2.database, bookmark = _ref2.bookmark; + databaseSpecificErrorHandler = new _connectionErrorHandler["default"](error.SESSION_EXPIRED, function (error, address) { + return _this2._handleUnavailability(error, address, database); + }, function (error, address) { + return _this2._handleWriteFailure(error, address, database); + }); + _context.next = 4; + return this._freshRoutingTable({ + accessMode: accessMode, + database: database || DEFAULT_DB_NAME, + bookmark: bookmark + }); + + case 4: + routingTable = _context.sent; + + if (!(accessMode === driver.READ)) { + _context.next = 10; + break; + } + + address = this._loadBalancingStrategy.selectReader(routingTable.readers); + name = 'read'; + _context.next = 16; + break; + + case 10: + if (!(accessMode === driver.WRITE)) { + _context.next = 15; + break; + } + + address = this._loadBalancingStrategy.selectWriter(routingTable.writers); + name = 'write'; + _context.next = 16; + break; + + case 15: + throw (0, error.newError)('Illegal mode ' + accessMode); + + case 16: + if (address) { + _context.next = 18; + break; + } + + throw (0, error.newError)("Failed to obtain connection towards ".concat(name, " server. Known routing table is: ").concat(routingTable), error.SESSION_EXPIRED); + + case 18: + _context.prev = 18; + _context.next = 21; + return this._acquireConnectionToServer(address, name, routingTable); + + case 21: + connection = _context.sent; + return _context.abrupt("return", new _connectionDelegate["default"](connection, databaseSpecificErrorHandler)); + + case 25: + _context.prev = 25; + _context.t0 = _context["catch"](18); + transformed = databaseSpecificErrorHandler.handleAndTransformError(_context.t0, address); + throw transformed; + + case 29: + case "end": + return _context.stop(); + } + } + }, _callee, this, [[18, 25]]); + })); + + function acquireConnection() { + return _acquireConnection.apply(this, arguments); + } + + return acquireConnection; + }() + }, { + key: "_hasProtocolVersion", + value: function () { + var _hasProtocolVersion2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee2(versionPredicate) { + var addresses, lastError, i, connection, protocol; + return _regenerator["default"].wrap(function _callee2$(_context2) { + while (1) { + switch (_context2.prev = _context2.next) { + case 0: + _context2.next = 2; + return this._resolveSeedRouter(this._seedRouter); + + case 2: + addresses = _context2.sent; + i = 0; + + case 4: + if (!(i < addresses.length)) { + _context2.next = 25; + break; + } + + connection = _connectionChannel["default"].create(addresses[i], this._config, this._createConnectionErrorHandler(), this._log); + _context2.prev = 6; + _context2.next = 9; + return connection._negotiateProtocol(); + + case 9: + protocol = connection.protocol(); + + if (!protocol) { + _context2.next = 12; + break; + } + + return _context2.abrupt("return", versionPredicate(protocol.version)); + + case 12: + return _context2.abrupt("return", false); + + case 15: + _context2.prev = 15; + _context2.t0 = _context2["catch"](6); + lastError = _context2.t0; + + case 18: + _context2.prev = 18; + _context2.next = 21; + return connection.close(); + + case 21: + return _context2.finish(18); + + case 22: + i++; + _context2.next = 4; + break; + + case 25: + if (!lastError) { + _context2.next = 27; + break; + } + + throw lastError; + + case 27: + return _context2.abrupt("return", false); + + case 28: + case "end": + return _context2.stop(); + } + } + }, _callee2, this, [[6, 15, 18, 22]]); + })); + + function _hasProtocolVersion(_x) { + return _hasProtocolVersion2.apply(this, arguments); + } + + return _hasProtocolVersion; + }() + }, { + key: "supportsMultiDb", + value: function () { + var _supportsMultiDb = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee3() { + return _regenerator["default"].wrap(function _callee3$(_context3) { + while (1) { + switch (_context3.prev = _context3.next) { + case 0: + _context3.next = 2; + return this._hasProtocolVersion(function (version) { + return version >= constants.BOLT_PROTOCOL_V4_0; + }); + + case 2: + return _context3.abrupt("return", _context3.sent); + + case 3: + case "end": + return _context3.stop(); + } + } + }, _callee3, this); + })); + + function supportsMultiDb() { + return _supportsMultiDb.apply(this, arguments); + } + + return supportsMultiDb; + }() + }, { + key: "supportsTransactionConfig", + value: function () { + var _supportsTransactionConfig = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee4() { + return _regenerator["default"].wrap(function _callee4$(_context4) { + while (1) { + switch (_context4.prev = _context4.next) { + case 0: + _context4.next = 2; + return this._hasProtocolVersion(function (version) { + return version >= constants.BOLT_PROTOCOL_V3; + }); + + case 2: + return _context4.abrupt("return", _context4.sent); + + case 3: + case "end": + return _context4.stop(); + } + } + }, _callee4, this); + })); + + function supportsTransactionConfig() { + return _supportsTransactionConfig.apply(this, arguments); + } + + return supportsTransactionConfig; + }() + }, { + key: "forget", + value: function forget(address, database) { + if (database || database === '') { + this._routingTables[database].forget(address); + } else { + Object.values(this._routingTables).forEach(function (routingTable) { + return routingTable.forget(address); + }); + } // We're firing and forgetting this operation explicitly and listening for any + // errors to avoid unhandled promise rejection + + + this._connectionPool.purge(address)["catch"](function () {}); + } + }, { + key: "forgetWriter", + value: function forgetWriter(address, database) { + if (database || database === '') { + this._routingTables[database].forgetWriter(address); + } else { + Object.values(this._routingTables).forEach(function (routingTable) { + return routingTable.forgetWriter(address); + }); + } + } + }, { + key: "_acquireConnectionToServer", + value: function _acquireConnectionToServer(address, serverName, routingTable) { + return this._connectionPool.acquire(address); + } + }, { + key: "_freshRoutingTable", + value: function _freshRoutingTable() { + var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, + accessMode = _ref3.accessMode, + database = _ref3.database, + bookmark = _ref3.bookmark; + + var currentRoutingTable = this._routingTables[database] || new _routingTable["default"]({ + database: database + }); + + if (!currentRoutingTable.isStaleFor(accessMode)) { + return currentRoutingTable; + } + + this._log.info("Routing table is stale for database: \"".concat(database, "\" and access mode: \"").concat(accessMode, "\": ").concat(currentRoutingTable)); + + return this._refreshRoutingTable(currentRoutingTable, bookmark); + } + }, { + key: "_refreshRoutingTable", + value: function _refreshRoutingTable(currentRoutingTable, bookmark) { + var knownRouters = currentRoutingTable.routers; + + if (this._useSeedRouter) { + return this._fetchRoutingTableFromSeedRouterFallbackToKnownRouters(knownRouters, currentRoutingTable, bookmark); + } + + return this._fetchRoutingTableFromKnownRoutersFallbackToSeedRouter(knownRouters, currentRoutingTable, bookmark); + } + }, { + key: "_fetchRoutingTableFromSeedRouterFallbackToKnownRouters", + value: function () { + var _fetchRoutingTableFromSeedRouterFallbackToKnownRouters2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee5(knownRouters, currentRoutingTable, bookmark) { + var seenRouters, newRoutingTable; + return _regenerator["default"].wrap(function _callee5$(_context5) { + while (1) { + switch (_context5.prev = _context5.next) { + case 0: + // we start with seed router, no routers were probed before + seenRouters = []; + _context5.next = 3; + return this._fetchRoutingTableUsingSeedRouter(seenRouters, this._seedRouter, currentRoutingTable, bookmark); + + case 3: + newRoutingTable = _context5.sent; + + if (!newRoutingTable) { + _context5.next = 8; + break; + } + + this._useSeedRouter = false; + _context5.next = 11; + break; + + case 8: + _context5.next = 10; + return this._fetchRoutingTableUsingKnownRouters(knownRouters, currentRoutingTable, bookmark); + + case 10: + newRoutingTable = _context5.sent; + + case 11: + _context5.next = 13; + return this._applyRoutingTableIfPossible(currentRoutingTable, newRoutingTable); + + case 13: + return _context5.abrupt("return", _context5.sent); + + case 14: + case "end": + return _context5.stop(); + } + } + }, _callee5, this); + })); + + function _fetchRoutingTableFromSeedRouterFallbackToKnownRouters(_x2, _x3, _x4) { + return _fetchRoutingTableFromSeedRouterFallbackToKnownRouters2.apply(this, arguments); + } + + return _fetchRoutingTableFromSeedRouterFallbackToKnownRouters; + }() + }, { + key: "_fetchRoutingTableFromKnownRoutersFallbackToSeedRouter", + value: function () { + var _fetchRoutingTableFromKnownRoutersFallbackToSeedRouter2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee6(knownRouters, currentRoutingTable, bookmark) { + var newRoutingTable; + return _regenerator["default"].wrap(function _callee6$(_context6) { + while (1) { + switch (_context6.prev = _context6.next) { + case 0: + _context6.next = 2; + return this._fetchRoutingTableUsingKnownRouters(knownRouters, currentRoutingTable, bookmark); + + case 2: + newRoutingTable = _context6.sent; + + if (newRoutingTable) { + _context6.next = 7; + break; + } + + _context6.next = 6; + return this._fetchRoutingTableUsingSeedRouter(knownRouters, this._seedRouter, currentRoutingTable, bookmark); + + case 6: + newRoutingTable = _context6.sent; + + case 7: + _context6.next = 9; + return this._applyRoutingTableIfPossible(currentRoutingTable, newRoutingTable); + + case 9: + return _context6.abrupt("return", _context6.sent); + + case 10: + case "end": + return _context6.stop(); + } + } + }, _callee6, this); + })); + + function _fetchRoutingTableFromKnownRoutersFallbackToSeedRouter(_x5, _x6, _x7) { + return _fetchRoutingTableFromKnownRoutersFallbackToSeedRouter2.apply(this, arguments); + } + + return _fetchRoutingTableFromKnownRoutersFallbackToSeedRouter; + }() + }, { + key: "_fetchRoutingTableUsingKnownRouters", + value: function () { + var _fetchRoutingTableUsingKnownRouters2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee7(knownRouters, currentRoutingTable, bookmark) { + var newRoutingTable, lastRouterIndex; + return _regenerator["default"].wrap(function _callee7$(_context7) { + while (1) { + switch (_context7.prev = _context7.next) { + case 0: + _context7.next = 2; + return this._fetchRoutingTable(knownRouters, currentRoutingTable, bookmark); + + case 2: + newRoutingTable = _context7.sent; + + if (!newRoutingTable) { + _context7.next = 5; + break; + } + + return _context7.abrupt("return", newRoutingTable); + + case 5: + // returned routing table was undefined, this means a connection error happened and the last known + // router did not return a valid routing table, so we need to forget it + lastRouterIndex = knownRouters.length - 1; + + RoutingConnectionProvider._forgetRouter(currentRoutingTable, knownRouters, lastRouterIndex); + + return _context7.abrupt("return", null); + + case 8: + case "end": + return _context7.stop(); + } + } + }, _callee7, this); + })); + + function _fetchRoutingTableUsingKnownRouters(_x8, _x9, _x10) { + return _fetchRoutingTableUsingKnownRouters2.apply(this, arguments); + } + + return _fetchRoutingTableUsingKnownRouters; + }() + }, { + key: "_fetchRoutingTableUsingSeedRouter", + value: function () { + var _fetchRoutingTableUsingSeedRouter2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee8(seenRouters, seedRouter, routingTable, bookmark) { + var resolvedAddresses, newAddresses; + return _regenerator["default"].wrap(function _callee8$(_context8) { + while (1) { + switch (_context8.prev = _context8.next) { + case 0: + _context8.next = 2; + return this._resolveSeedRouter(seedRouter); + + case 2: + resolvedAddresses = _context8.sent; + // filter out all addresses that we've already tried + newAddresses = resolvedAddresses.filter(function (address) { + return seenRouters.indexOf(address) < 0; + }); + _context8.next = 6; + return this._fetchRoutingTable(newAddresses, routingTable, bookmark); + + case 6: + return _context8.abrupt("return", _context8.sent); + + case 7: + case "end": + return _context8.stop(); + } + } + }, _callee8, this); + })); + + function _fetchRoutingTableUsingSeedRouter(_x11, _x12, _x13, _x14) { + return _fetchRoutingTableUsingSeedRouter2.apply(this, arguments); + } + + return _fetchRoutingTableUsingSeedRouter; + }() + }, { + key: "_resolveSeedRouter", + value: function () { + var _resolveSeedRouter2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee9(seedRouter) { + var _this3 = this; + + var resolvedAddresses, dnsResolvedAddresses; + return _regenerator["default"].wrap(function _callee9$(_context9) { + while (1) { + switch (_context9.prev = _context9.next) { + case 0: + _context9.next = 2; + return this._hostNameResolver.resolve(seedRouter); + + case 2: + resolvedAddresses = _context9.sent; + _context9.next = 5; + return Promise.all(resolvedAddresses.map(function (address) { + return _this3._dnsResolver.resolve(address); + })); + + case 5: + dnsResolvedAddresses = _context9.sent; + return _context9.abrupt("return", [].concat.apply([], dnsResolvedAddresses)); + + case 7: + case "end": + return _context9.stop(); + } + } + }, _callee9, this); + })); + + function _resolveSeedRouter(_x15) { + return _resolveSeedRouter2.apply(this, arguments); + } + + return _resolveSeedRouter; + }() + }, { + key: "_fetchRoutingTable", + value: function _fetchRoutingTable(routerAddresses, routingTable, bookmark) { + var _this4 = this; + + return routerAddresses.reduce( + /*#__PURE__*/ + function () { + var _ref4 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee10(refreshedTablePromise, currentRouter, currentIndex) { + var newRoutingTable, previousRouterIndex, session; + return _regenerator["default"].wrap(function _callee10$(_context10) { + while (1) { + switch (_context10.prev = _context10.next) { + case 0: + _context10.next = 2; + return refreshedTablePromise; + + case 2: + newRoutingTable = _context10.sent; + + if (!newRoutingTable) { + _context10.next = 7; + break; + } + + return _context10.abrupt("return", newRoutingTable); + + case 7: + // returned routing table was undefined, this means a connection error happened and we need to forget the + // previous router and try the next one + previousRouterIndex = currentIndex - 1; + + RoutingConnectionProvider._forgetRouter(routingTable, routerAddresses, previousRouterIndex); + + case 9: + _context10.next = 11; + return _this4._createSessionForRediscovery(currentRouter, bookmark); + + case 11: + session = _context10.sent; + + if (!session) { + _context10.next = 27; + break; + } + + _context10.prev = 13; + _context10.next = 16; + return _this4._rediscovery.lookupRoutingTableOnRouter(session, routingTable.database, currentRouter); + + case 16: + return _context10.abrupt("return", _context10.sent); + + case 19: + _context10.prev = 19; + _context10.t0 = _context10["catch"](13); + + if (!(_context10.t0 && _context10.t0.code === DATABASE_NOT_FOUND_ERROR_CODE)) { + _context10.next = 23; + break; + } + + throw _context10.t0; + + case 23: + _this4._log.warn("unable to fetch routing table because of an error ".concat(_context10.t0)); + + return _context10.abrupt("return", null); + + case 25: + _context10.next = 28; + break; + + case 27: + return _context10.abrupt("return", null); + + case 28: + case "end": + return _context10.stop(); + } + } + }, _callee10, null, [[13, 19]]); + })); + + return function (_x16, _x17, _x18) { + return _ref4.apply(this, arguments); + }; + }(), Promise.resolve(null)); + } + }, { + key: "_createSessionForRediscovery", + value: function () { + var _createSessionForRediscovery2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee11(routerAddress, bookmark) { + var connection, connectionProvider, protocolVersion; + return _regenerator["default"].wrap(function _callee11$(_context11) { + while (1) { + switch (_context11.prev = _context11.next) { + case 0: + _context11.prev = 0; + _context11.next = 3; + return this._connectionPool.acquire(routerAddress); + + case 3: + connection = _context11.sent; + connectionProvider = new _connectionProviderSingle["default"](connection); + protocolVersion = connection.protocol().version; + + if (!(protocolVersion < 4.0)) { + _context11.next = 8; + break; + } + + return _context11.abrupt("return", new _session["default"]({ + mode: driver.WRITE, + bookmark: _bookmark["default"].empty(), + connectionProvider: connectionProvider + })); + + case 8: + return _context11.abrupt("return", new _session["default"]({ + mode: driver.READ, + database: SYSTEM_DB_NAME, + bookmark: bookmark, + connectionProvider: connectionProvider + })); + + case 11: + _context11.prev = 11; + _context11.t0 = _context11["catch"](0); + + if (!(_context11.t0 && _context11.t0.code === UNAUTHORIZED_ERROR_CODE)) { + _context11.next = 15; + break; + } + + throw _context11.t0; + + case 15: + return _context11.abrupt("return", null); + + case 16: + case "end": + return _context11.stop(); + } + } + }, _callee11, this, [[0, 11]]); + })); + + function _createSessionForRediscovery(_x19, _x20) { + return _createSessionForRediscovery2.apply(this, arguments); + } + + return _createSessionForRediscovery; + }() + }, { + key: "_applyRoutingTableIfPossible", + value: function () { + var _applyRoutingTableIfPossible2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee12(currentRoutingTable, newRoutingTable) { + return _regenerator["default"].wrap(function _callee12$(_context12) { + while (1) { + switch (_context12.prev = _context12.next) { + case 0: + if (newRoutingTable) { + _context12.next = 2; + break; + } + + throw (0, error.newError)("Could not perform discovery. No routing servers available. Known routing table: ".concat(currentRoutingTable), error.SERVICE_UNAVAILABLE); + + case 2: + if (newRoutingTable.writers.length === 0) { + // use seed router next time. this is important when cluster is partitioned. it tries to make sure driver + // does not always get routing table without writers because it talks exclusively to a minority partition + this._useSeedRouter = true; + } + + _context12.next = 5; + return this._updateRoutingTable(newRoutingTable); + + case 5: + return _context12.abrupt("return", newRoutingTable); + + case 6: + case "end": + return _context12.stop(); + } + } + }, _callee12, this); + })); + + function _applyRoutingTableIfPossible(_x21, _x22) { + return _applyRoutingTableIfPossible2.apply(this, arguments); + } + + return _applyRoutingTableIfPossible; + }() + }, { + key: "_updateRoutingTable", + value: function () { + var _updateRoutingTable2 = (0, _asyncToGenerator2["default"])( + /*#__PURE__*/ + _regenerator["default"].mark(function _callee13(newRoutingTable) { + var _this5 = this; + + return _regenerator["default"].wrap(function _callee13$(_context13) { + while (1) { + switch (_context13.prev = _context13.next) { + case 0: + _context13.next = 2; + return this._connectionPool.keepAll(newRoutingTable.allServers()); + + case 2: + // filter out expired to purge (expired for a pre-configured amount of time) routing table entries + Object.values(this._routingTables).forEach(function (value) { + if (value.isExpiredFor(_this5._routingTablePurgeDelay)) { + delete _this5._routingTables[value.database]; + } + }); // make this driver instance aware of the new table + + this._routingTables[newRoutingTable.database] = newRoutingTable; + + this._log.info("Updated routing table ".concat(newRoutingTable)); + + case 5: + case "end": + return _context13.stop(); + } + } + }, _callee13, this); + })); + + function _updateRoutingTable(_x23) { + return _updateRoutingTable2.apply(this, arguments); + } + + return _updateRoutingTable; + }() + }], [{ + key: "_forgetRouter", + value: function _forgetRouter(routingTable, routersArray, routerIndex) { + var address = routersArray[routerIndex]; + + if (routingTable && address) { + routingTable.forgetRouter(address); + } + } + }]); + return RoutingConnectionProvider; +}(_connectionProviderPooled["default"]); + +exports["default"] = RoutingConnectionProvider; +}); + +var configuredCustomResolver = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _serverAddress = interopRequireDefault(serverAddress); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function resolveToSelf(address) { + return Promise.resolve([address]); +} + +var ConfiguredCustomResolver = +/*#__PURE__*/ +function () { + function ConfiguredCustomResolver(resolverFunction) { + (0, _classCallCheck2["default"])(this, ConfiguredCustomResolver); + this._resolverFunction = resolverFunction || resolveToSelf; + } + + (0, _createClass2["default"])(ConfiguredCustomResolver, [{ + key: "resolve", + value: function resolve(seedRouter) { + var _this = this; + + return new Promise(function (resolve) { + return resolve(_this._resolverFunction(seedRouter.asHostPort())); + }).then(function (resolved) { + if (!Array.isArray(resolved)) { + throw new TypeError('Configured resolver function should either return an array of addresses or a Promise resolved with an array of addresses.' + "Each address is ':'. Got: ".concat(resolved)); + } + + return resolved.map(function (r) { + return _serverAddress["default"].fromUrl(r); + }); + }); + } + }]); + return ConfiguredCustomResolver; +}(); + +exports["default"] = ConfiguredCustomResolver; +}); + +var routingDriver = createCommonjsModule(function (module, exports) { + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +var _classCallCheck2 = interopRequireDefault(classCallCheck); + +var _createClass2 = interopRequireDefault(createClass); + +var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); + +var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); + +var _inherits2 = interopRequireDefault(inherits); + + + + + +var _connectionProviderRouting = interopRequireDefault(connectionProviderRouting); + +interopRequireDefault(leastConnectedLoadBalancingStrategy); + +interopRequireDefault(connectionErrorHandler); + +var _configuredCustomResolver = interopRequireDefault(configuredCustomResolver); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * A driver that supports routing in a causal cluster. + * @private + */ +var RoutingDriver = +/*#__PURE__*/ +function (_Driver) { + (0, _inherits2["default"])(RoutingDriver, _Driver); + + function RoutingDriver(address, routingContext, userAgent) { + var _this; + + var token = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; + var config = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; + (0, _classCallCheck2["default"])(this, RoutingDriver); + _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(RoutingDriver).call(this, address, userAgent, token, validateConfig(config))); + _this._routingContext = routingContext; + return _this; + } + + (0, _createClass2["default"])(RoutingDriver, [{ + key: "_afterConstruction", + value: function _afterConstruction() { + this._log.info("Routing driver ".concat(this._id, " created for server address ").concat(this._address)); + } + }, { + key: "_createConnectionProvider", + value: function _createConnectionProvider(address, userAgent, authToken) { + return new _connectionProviderRouting["default"]({ + id: this._id, + address: address, + routingContext: this._routingContext, + hostNameResolver: createHostNameResolver(this._config), + config: this._config, + log: this._log, + userAgent: userAgent, + authToken: authToken + }); + } + }, { + key: "_supportsRouting", + value: function _supportsRouting() { + return true; + } + }]); + return RoutingDriver; +}(driver.Driver); +/** + * @private + * @returns {ConfiguredCustomResolver} new custom resolver that wraps the passed-in resolver function. + * If resolved function is not specified, it defaults to an identity resolver. + */ + + +function createHostNameResolver(config) { + return new _configuredCustomResolver["default"](config.resolver); +} +/** + * @private + * @returns {Object} the given config. + */ + + +function validateConfig(config) { + var resolver = config.resolver; + + if (resolver && typeof resolver !== 'function') { + throw new TypeError("Configured resolver should be a function. Got: ".concat(resolver)); + } + + return config; +} + +var _default = RoutingDriver; +exports["default"] = _default; +}); + +var version = createCommonjsModule(function (module, exports) { + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports["default"] = void 0; + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// DO NOT CHANGE THE VERSION BELOW HERE +// This is set by the build system at release time, using +// +// gulp set --x +// +// This is set up this way to keep the version in the code in +// sync with the npm package version, and to allow the build +// system to control version names at packaging time. +var _default = '4.2.3'; +exports["default"] = _default; +}); + +var lib = createCommonjsModule(function (module, exports) { + + + + + +Object.defineProperty(exports, "__esModule", { + value: true +}); +exports.driver = driver$1; +Object.defineProperty(exports, "int", { + enumerable: true, + get: function get() { + return _integer["int"]; + } +}); +Object.defineProperty(exports, "isInt", { + enumerable: true, + get: function get() { + return _integer.isInt; + } +}); +Object.defineProperty(exports, "Neo4jError", { + enumerable: true, + get: function get() { + return error.Neo4jError; + } +}); +Object.defineProperty(exports, "isPoint", { + enumerable: true, + get: function get() { + return spatialTypes.isPoint; + } +}); +Object.defineProperty(exports, "isDate", { + enumerable: true, + get: function get() { + return temporalTypes.isDate; + } +}); +Object.defineProperty(exports, "isDateTime", { + enumerable: true, + get: function get() { + return temporalTypes.isDateTime; + } +}); +Object.defineProperty(exports, "isDuration", { + enumerable: true, + get: function get() { + return temporalTypes.isDuration; + } +}); +Object.defineProperty(exports, "isLocalDateTime", { + enumerable: true, + get: function get() { + return temporalTypes.isLocalDateTime; + } +}); +Object.defineProperty(exports, "isLocalTime", { + enumerable: true, + get: function get() { + return temporalTypes.isLocalTime; + } +}); +Object.defineProperty(exports, "isTime", { + enumerable: true, + get: function get() { + return temporalTypes.isTime; + } +}); +exports["default"] = exports.temporal = exports.spatial = exports.error = exports.session = exports.types = exports.logging = exports.auth = exports.integer = void 0; + +var _integer = interopRequireWildcard(integer); + + + + + +var _result = interopRequireDefault(result); + +var _resultSummary = interopRequireDefault(resultSummary); + +var _record = interopRequireDefault(record); + + + +var _routingDriver = interopRequireDefault(routingDriver); + +var _version = interopRequireDefault(version); + + + +var _urlUtil = interopRequireDefault(urlUtil); + + + + + +var _serverAddress = interopRequireDefault(serverAddress); + +/** + * Copyright (c) "Neo4j" + * Neo4j Sweden AB [http://neo4j.com] + * + * This file is part of Neo4j. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Construct a new Neo4j Driver. This is your main entry point for this + * library. + * + * ## Configuration + * + * This function optionally takes a configuration argument. Available configuration + * options are as follows: + * + * { + * // Encryption level: ENCRYPTION_ON or ENCRYPTION_OFF. + * encrypted: ENCRYPTION_ON|ENCRYPTION_OFF + * + * // Trust strategy to use if encryption is enabled. There is no mode to disable + * // trust other than disabling encryption altogether. The reason for + * // this is that if you don't know who you are talking to, it is easy for an + * // attacker to hijack your encrypted connection, rendering encryption pointless. + * // + * // TRUST_SYSTEM_CA_SIGNED_CERTIFICATES is the default choice. For NodeJS environments, this + * // means that you trust whatever certificates are in the default trusted certificate + * // store of the underlying system. For Browser environments, the trusted certificate + * // store is usually managed by the browser. Refer to your system or browser documentation + * // if you want to explicitly add a certificate as trusted. + * // + * // TRUST_CUSTOM_CA_SIGNED_CERTIFICATES is another option for trust verification - + * // whenever we establish an encrypted connection, we ensure the host is using + * // an encryption certificate that is in, or is signed by, a certificate given + * // as trusted through configuration. This option is only available for NodeJS environments. + * // + * // TRUST_ALL_CERTIFICATES means that you trust everything without any verifications + * // steps carried out. This option is only available for NodeJS environments and should not + * // be used on production systems. + * trust: "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES" | "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES" | + * "TRUST_ALL_CERTIFICATES", + * + * // List of one or more paths to trusted encryption certificates. This only + * // works in the NodeJS bundle, and only matters if you use "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES". + * // The certificate files should be in regular X.509 PEM format. + * // For instance, ['./trusted.pem'] + * trustedCertificates: [], + * + * // The maximum total number of connections allowed to be managed by the connection pool, per host. + * // This includes both in-use and idle connections. No maximum connection pool size is imposed + * // by default. + * maxConnectionPoolSize: 100, + * + * // The maximum allowed lifetime for a pooled connection in milliseconds. Pooled connections older than this + * // threshold will be closed and removed from the pool. Such discarding happens during connection acquisition + * // so that new session is never backed by an old connection. Setting this option to a low value will cause + * // a high connection churn and might result in a performance hit. It is recommended to set maximum lifetime + * // to a slightly smaller value than the one configured in network equipment (load balancer, proxy, firewall, + * // etc. can also limit maximum connection lifetime). No maximum lifetime limit is imposed by default. Zero + * // and negative values result in lifetime not being checked. + * maxConnectionLifetime: 60 * 60 * 1000, // 1 hour + * + * // The maximum amount of time to wait to acquire a connection from the pool (to either create a new + * // connection or borrow an existing one. + * connectionAcquisitionTimeout: 60000, // 1 minute + * + * // Specify the maximum time in milliseconds transactions are allowed to retry via + * // `Session#readTransaction()` and `Session#writeTransaction()` functions. + * // These functions will retry the given unit of work on `ServiceUnavailable`, `SessionExpired` and transient + * // errors with exponential backoff using initial delay of 1 second. + * // Default value is 30000 which is 30 seconds. + * maxTransactionRetryTime: 30000, // 30 seconds + * + * // Specify socket connection timeout in milliseconds. Numeric values are expected. Negative and zero values + * // result in no timeout being applied. Connection establishment will be then bound by the timeout configured + * // on the operating system level. Default value is 30000, which is 30 seconds. + * connectionTimeout: 30000, // 30 seconds + * + * // Make this driver always return native JavaScript numbers for integer values, instead of the + * // dedicated {@link Integer} class. Values that do not fit in native number bit range will be represented as + * // `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`. + * // **Warning:** ResultSummary It is not always safe to enable this setting when JavaScript applications are not the only ones + * // interacting with the database. Stored numbers might in such case be not representable by native + * // {@link Number} type and thus driver will return lossy values. This might also happen when data was + * // initially imported using neo4j import tool and contained numbers larger than + * // `Number.MAX_SAFE_INTEGER`. Driver will then return positive infinity, which is lossy. + * // Default value for this option is `false` because native JavaScript numbers might result + * // in loss of precision in the general case. + * disableLosslessIntegers: false, + * + * // Specify the logging configuration for the driver. Object should have two properties `level` and `logger`. + * // + * // Property `level` represents the logging level which should be one of: 'error', 'warn', 'info' or 'debug'. This property is optional and + * // its default value is 'info'. Levels have priorities: 'error': 0, 'warn': 1, 'info': 2, 'debug': 3. Enabling a certain level also enables all + * // levels with lower priority. For example: 'error', 'warn' and 'info' will be logged when 'info' level is configured. + * // + * // Property `logger` represents the logging function which will be invoked for every log call with an acceptable level. The function should + * // take two string arguments `level` and `message`. The function should not execute any blocking or long-running operations + * // because it is often executed on a hot path. + * // + * // No logging is done by default. See `neo4j.logging` object that contains predefined logging implementations. + * logging: { + * level: 'info', + * logger: (level, message) => console.log(level + ' ' + message) + * }, + * + * // Specify a custom server address resolver function used by the routing driver to resolve the initial address used to create the driver. + * // Such resolution happens: + * // * during the very first rediscovery when driver is created + * // * when all the known routers from the current routing table have failed and driver needs to fallback to the initial address + * // + * // In NodeJS environment driver defaults to performing a DNS resolution of the initial address using 'dns' module. + * // In browser environment driver uses the initial address as-is. + * // Value should be a function that takes a single string argument - the initial address. It should return an array of new addresses. + * // Address is a string of shape ':'. Provided function can return either a Promise resolved with an array of addresses + * // or array of addresses directly. + * resolver: function(address) { + * return ['127.0.0.1:8888', 'fallback.db.com:7687']; + * }, + * + * // Optionally override the default user agent name. + * userAgent: USER_AGENT + * } + * + * @param {string} url The URL for the Neo4j database, for instance "neo4j://localhost" and/or "bolt://localhost" + * @param {Map} authToken Authentication credentials. See {@link auth} for helpers. + * @param {Object} config Configuration object. See the configuration section above for details. + * @returns {Driver} + */ +function driver$1(url, authToken) { + var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; + (0, util.assertString)(url, 'Bolt URL'); + + var parsedUrl = _urlUtil["default"].parseDatabaseUrl(url); // Determine entryption/trust options from the URL. + + + var routing = false; + var encrypted = false; + var trust; + + switch (parsedUrl.scheme) { + case 'bolt': + break; + + case 'bolt+s': + encrypted = true; + trust = 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'; + break; + + case 'bolt+ssc': + encrypted = true; + trust = 'TRUST_ALL_CERTIFICATES'; + break; + + case 'neo4j': + routing = true; + break; + + case 'neo4j+s': + encrypted = true; + trust = 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'; + routing = true; + break; + + case 'neo4j+ssc': + encrypted = true; + trust = 'TRUST_ALL_CERTIFICATES'; + routing = true; + break; + + default: + throw new Error("Unknown scheme: ".concat(parsedUrl.scheme)); + } // Encryption enabled on URL, propagate trust to the config. + + + if (encrypted) { + // Check for configuration conflict between URL and config. + if ('encrypted' in config || 'trust' in config) { + throw new Error('Encryption/trust can only be configured either through URL or config, not both'); + } + + config.encrypted = util.ENCRYPTION_ON; + config.trust = trust; + } // Sanitize authority token. Nicer error from server when a scheme is set. + + + authToken = authToken || {}; + authToken.scheme = authToken.scheme || 'none'; // Use default user agent or user agent specified by user. + + config.userAgent = config.userAgent || USER_AGENT; + + if (routing) { + return new _routingDriver["default"](_serverAddress["default"].fromUrl(parsedUrl.hostAndPort), parsedUrl.query, config.userAgent, authToken, config); + } else { + if (!(0, util.isEmptyObjectOrNull)(parsedUrl.query)) { + throw new Error("Parameters are not supported with none routed scheme. Given URL: '".concat(url, "'")); + } + + return new driver.Driver(_serverAddress["default"].fromUrl(parsedUrl.hostAndPort), config.userAgent, authToken, config); + } +} +/** + * @property {function(username: string, password: string, realm: ?string)} basic the function to create a + * basic authentication token. + * @property {function(base64EncodedTicket: string)} kerberos the function to create a Kerberos authentication token. + * Accepts a single string argument - base64 encoded Kerberos ticket. + * @property {function(principal: string, credentials: string, realm: string, scheme: string, parameters: ?object)} custom + * the function to create a custom authentication token. + */ + + +var auth = { + basic: function basic(username, password) { + var realm = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; + + if (realm) { + return { + scheme: 'basic', + principal: username, + credentials: password, + realm: realm + }; + } else { + return { + scheme: 'basic', + principal: username, + credentials: password + }; + } + }, + kerberos: function kerberos(base64EncodedTicket) { + return { + scheme: 'kerberos', + principal: '', + // This empty string is required for backwards compatibility. + credentials: base64EncodedTicket + }; + }, + custom: function custom(principal, credentials, realm, scheme) { + var parameters = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined; + + if (parameters) { + return { + scheme: scheme, + principal: principal, + credentials: credentials, + realm: realm, + parameters: parameters + }; + } else { + return { + scheme: scheme, + principal: principal, + credentials: credentials, + realm: realm + }; + } + } +}; +exports.auth = auth; +var USER_AGENT = 'neo4j-javascript/' + _version["default"]; +/** + * Object containing predefined logging configurations. These are expected to be used as values of the driver config's `logging` property. + * @property {function(level: ?string): object} console the function to create a logging config that prints all messages to `console.log` with + * timestamp, level and message. It takes an optional `level` parameter which represents the maximum log level to be logged. Default value is 'info'. + */ + +var logging = { + console: function (_console) { + function console(_x) { + return _console.apply(this, arguments); + } + + console.toString = function () { + return _console.toString(); + }; + + return console; + }(function (level) { + return { + level: level, + logger: function logger(level, message) { + return console.log("".concat(commonjsGlobal.Date.now(), " ").concat(level.toUpperCase(), " ").concat(message)); + } + }; + }) + /** + * Object containing constructors for all neo4j types. + */ + +}; +exports.logging = logging; +var types = { + Node: graphTypes.Node, + Relationship: graphTypes.Relationship, + UnboundRelationship: graphTypes.UnboundRelationship, + PathSegment: graphTypes.PathSegment, + Path: graphTypes.Path, + Result: _result["default"], + ResultSummary: _resultSummary["default"], + Record: _record["default"], + Point: spatialTypes.Point, + Date: temporalTypes.Date, + DateTime: temporalTypes.DateTime, + Duration: temporalTypes.Duration, + LocalDateTime: temporalTypes.LocalDateTime, + LocalTime: temporalTypes.LocalTime, + Time: temporalTypes.Time, + Integer: _integer["default"] + /** + * Object containing string constants representing session access modes. + */ + +}; +exports.types = types; +var session = { + READ: driver.READ, + WRITE: driver.WRITE + /** + * Object containing string constants representing predefined {@link Neo4jError} codes. + */ + +}; +exports.session = session; +var error$1 = { + SERVICE_UNAVAILABLE: error.SERVICE_UNAVAILABLE, + SESSION_EXPIRED: error.SESSION_EXPIRED, + PROTOCOL_ERROR: error.PROTOCOL_ERROR + /** + * Object containing functions to work with {@link Integer} objects. + */ + +}; +exports.error = error$1; +var integer$1 = { + toNumber: _integer.toNumber, + toString: _integer.toString, + inSafeRange: _integer.inSafeRange + /** + * Object containing functions to work with spatial types, like {@link Point}. + */ + +}; +exports.integer = integer$1; +var spatial = { + isPoint: spatialTypes.isPoint + /** + * Object containing functions to work with temporal types, like {@link Time} or {@link Duration}. + */ + +}; +exports.spatial = spatial; +var temporal = { + isDuration: temporalTypes.isDuration, + isLocalTime: temporalTypes.isLocalTime, + isTime: temporalTypes.isTime, + isDate: temporalTypes.isDate, + isLocalDateTime: temporalTypes.isLocalDateTime, + isDateTime: temporalTypes.isDateTime + /** + * @private + */ + +}; +exports.temporal = temporal; +var forExport = { + driver: driver$1, + "int": _integer["int"], + isInt: _integer.isInt, + isPoint: spatialTypes.isPoint, + isDuration: temporalTypes.isDuration, + isLocalTime: temporalTypes.isLocalTime, + isTime: temporalTypes.isTime, + isDate: temporalTypes.isDate, + isLocalDateTime: temporalTypes.isLocalDateTime, + isDateTime: temporalTypes.isDateTime, + integer: integer$1, + Neo4jError: error.Neo4jError, + auth: auth, + logging: logging, + types: types, + session: session, + error: error$1, + spatial: spatial, + temporal: temporal +}; +var _default = forExport; +exports["default"] = _default; +}); + +var neo4j = /*@__PURE__*/getDefaultExportFromCjs(lib); + +/** `Object#toString` result references. */ +var regexpTag$2 = '[object RegExp]'; + +/** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ +function baseIsRegExp(value) { + return isObjectLike_1(value) && _baseGetTag(value) == regexpTag$2; +} + +var _baseIsRegExp = baseIsRegExp; + +/* Node.js helper references. */ +var nodeIsRegExp = _nodeUtil && _nodeUtil.isRegExp; + +/** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ +var isRegExp = nodeIsRegExp ? _baseUnary(nodeIsRegExp) : _baseIsRegExp; + +var isRegExp_1 = isRegExp; + +/** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ +function last$1(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; +} + +var last_1 = last$1; + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike_1(value) && isArrayLike_1(value); +} + +var isArrayLikeObject_1 = isArrayLikeObject; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$1 = Math.max; + +/** + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. + * + * @static + * @memberOf _ + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. + * @example + * + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + * + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] + */ +function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = _arrayFilter(array, function(group) { + if (isArrayLikeObject_1(group)) { + length = nativeMax$1(group.length, length); + return true; + } + }); + return _baseTimes(length, function(index) { + return _arrayMap(array, _baseProperty(index)); + }); +} + +var unzip_1 = unzip; + +/** + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. + * @example + * + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] + */ +var zip$2 = _baseRest(unzip_1); + +var zip_1 = zip$2; + +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ +function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? _baseFlatten(array, 1) : []; +} + +var flatten_1 = flatten; + +/****************************************************************************** +nodeCleanup() installs functions -- cleanup handlers -- that perform cleanup activities just before the node process exits, except on SIGKILL, which can't be intercepted. nodeCleanup() can also install messages to be written to stderr on either SIGINT or an uncaught exception. + +Each cleanup handler has the following (FlowType) signature: + + cleanupHandler(exitCode: number|null, signal: string|null): boolean? + +If the process is terminating for a reason other than a signal, exitCode is an integer that provides the reason for termination, and signal is null. If the process received a POSIX signal, signal is the signal's string name, and exitCode is null. These are also the arguments passed to a process' `exit` event handler, mirrored in node-cleanup for consistency. + +The process terminates after cleanup, except possibly on signals. If any cleanup handler returns a boolean false for a signal, the process will not exit; otherwise the process exits. SIGKILL cannot be intercepted. + +Install a cleanup handler as follows: + + var nodeCleanup = require('node-cleanup'); + nodeCleanup(cleanupHandler, stderrMessages); + +Or to only install stderr messages: + + nodeCleanup(stderrMessages); + +Or to install the default stderr messages: + + nodeCleanup(); + +nodeCleanup() may be called multiple times to install multiple cleanup handlers. However, only the most recently installed stderr messages get used. The messages available are ctrl_C and uncaughtException. + +The following uninstalls all cleanup handlers and may be called multiple times in succession: + + nodeCleanup.uninstall(); + +This module has its origin in code by @CanyonCasa at http://stackoverflow.com/a/21947851/650894, but the module was significantly rewritten to resolve issues raised by @Banjocat at http://stackoverflow.com/questions/14031763/doing-a-cleanup-action-just-before-node-js-exits#comment68567869_21947851. It has also been extended for greater configurability. +******************************************************************************/ +//// CONSTANTS //////////////////////////////////////////////////////////////// + +var DEFAULT_MESSAGES = { + ctrl_C: '[ctrl-C]', + uncaughtException: 'Uncaught exception...' +}; + +//// CONFIGURATION //////////////////////////////////////////////////////////// + +var cleanupHandlers = null; // array of cleanup handlers to call +var messages = null; // messages to write to stderr + +var sigintHandler; // POSIX signal handlers +var sighupHandler; +var sigquitHandler; +var sigtermHandler; + +//// HANDLERS ///////////////////////////////////////////////////////////////// + +function signalHandler(signal) +{ + var exit = true; + cleanupHandlers.forEach(function (cleanup) { + if (cleanup(null, signal) === false) + exit = false; + }); + if (exit) { + if (signal === 'SIGINT' && messages && messages.ctrl_C !== '') + process.stderr.write(messages.ctrl_C + "\n"); + uninstall(); // don't cleanup again + // necessary to communicate the signal to the parent process + process.kill(process.pid, signal); + } +} + +function exceptionHandler(e) +{ + if (messages && messages.uncaughtException !== '') + process.stderr.write(messages.uncaughtException + "\n"); + process.stderr.write(e.stack + "\n"); + process.exit(1); // will call exitHandler() for cleanup +} + +function exitHandler(exitCode, signal) +{ + cleanupHandlers.forEach(function (cleanup) { + cleanup(exitCode, signal); + }); +} + +//// MAIN ///////////////////////////////////////////////////////////////////// + +function install(cleanupHandler, stderrMessages) +{ + if (cleanupHandler) { + if (typeof cleanupHandler === 'object') { + stderrMessages = cleanupHandler; + cleanupHandler = null; + } + } + else if (!stderrMessages) + stderrMessages = DEFAULT_MESSAGES; + + if (stderrMessages) { + if (messages === null) + messages = { ctrl_C: '', uncaughtException: '' }; + if (typeof stderrMessages.ctrl_C === 'string') + messages.ctrl_C = stderrMessages.ctrl_C; + if (typeof stderrMessages.uncaughtException === 'string') + messages.uncaughtException = stderrMessages.uncaughtException; + } + + if (cleanupHandlers === null) { + cleanupHandlers = []; // establish before installing handlers + + sigintHandler = signalHandler.bind(this, 'SIGINT'); + sighupHandler = signalHandler.bind(this, 'SIGHUP'); + sigquitHandler = signalHandler.bind(this, 'SIGQUIT'); + sigtermHandler = signalHandler.bind(this, 'SIGTERM'); + + process.on('SIGINT', sigintHandler); + process.on('SIGHUP', sighupHandler); + process.on('SIGQUIT', sigquitHandler); + process.on('SIGTERM', sigtermHandler); + process.on('uncaughtException', exceptionHandler); + process.on('exit', exitHandler); + + cleanupHandlers.push(cleanupHandler || noCleanup); + } + else if (cleanupHandler) + cleanupHandlers.push(cleanupHandler); +} + +function uninstall() +{ + if (cleanupHandlers !== null) { + process.removeListener('SIGINT', sigintHandler); + process.removeListener('SIGHUP', sighupHandler); + process.removeListener('SIGQUIT', sigquitHandler); + process.removeListener('SIGTERM', sigtermHandler); + process.removeListener('uncaughtException', exceptionHandler); + process.removeListener('exit', exitHandler); + cleanupHandlers = null; // null only after uninstalling + } +} + +function noCleanup() +{ + return true; // signals will always terminate process +} + +//// EXPORTS ////////////////////////////////////////////////////////////////// + +var nodeCleanup = install; +install.uninstall = uninstall; + +/** + * Converts a string to camel case and ensures it is unique in the provided + * list. + * @param {string} str + * @param {Array} existing + * @return {string} + */ +function uniqueString(str, existing) { + var camelString = camelCase_1(str); // Check if the string already has a number extension + + + var number = null; + var matches = camelString.match(/[0-9]+$/); + + if (matches) { + number = +matches[0]; + camelString = camelString.substr(0, camelString.length - matches[0].length); + } // Compute all taken suffixes that are similar to the given string + + + var regex = new RegExp("^" + camelString + "([0-9]*)$"); + + var takenSuffixes = reduce_1(existing, function (suffixes, existingString) { + var matches = existingString.match(regex); + + if (matches) { + var suffix = matches[1]; + suffixes.push(suffix ? +suffix : 1); + } + + return suffixes; + }, []); // If there was no suffix on the given string or it was already taken, + // compute the new suffix. + + + if (!number || takenSuffixes.indexOf(number) !== -1) { + number = Math.max.apply(Math, __spreadArrays([0], takenSuffixes)) + 1; + } // Append the suffix if it is not 1 + + + return camelString + (number === 1 ? '' : number); +} +/** + * Converts a Javascript value into a string suitable for a cypher query. + * @param {object|Array|string|boolean|number} value + * @return {string} + */ + +function stringifyValue(value) { + if (isNumber_1(value) || isBoolean_1(value)) { + return "" + value; + } + + if (isString_1(value)) { + return "'" + value + "'"; + } + + if (isArray_1(value)) { + var str = map_1(value, stringifyValue).join(', '); + + return "[ " + str + " ]"; + } + + if (isObject_1(value)) { + var pairs = map_1(value, function (el, key) { + return key + ": " + stringifyValue(el); + }); + + var str = pairs.join(', '); + return "{ " + str + " }"; + } + + return ''; +} +/** + * Converts labels into a string that can be put into a pattern. + * + * @param {string|array} labels + * @param relation When true, joins labels by a | instead of : + * @return {string} + */ + +function stringifyLabels(labels, relation) { + if (relation === void 0) { + relation = false; + } + + if (labels.length === 0) { + return ''; + } + + return ":" + castArray_1(labels).join(relation ? '|' : ':'); +} +/** + * Converts a path length bounds into a string to put into a relationship. + * @param {Array|int} bounds An array of bounds + * @return {string} + */ + +function stringifyPathLength(bounds) { + if (isNil_1(bounds)) { + return ''; + } + + if (bounds === '*') { + return '*'; + } + + if (isNumber_1(bounds)) { + return "*" + bounds; + } + + var lower = isNil_1(bounds[0]) ? '' : "" + bounds[0]; + var upper = isNil_1(bounds[1]) ? '' : "" + bounds[1]; + return lower || upper ? "*" + lower + ".." + upper : '*'; +} + +var Parameter = +/** @class */ +function () { + function Parameter(name, value) { + this.name = name; + this.value = value; + } + + Parameter.prototype.toString = function () { + return "$" + this.name; + }; + + return Parameter; +}(); + +var ParameterBag = +/** @class */ +function () { + function ParameterBag() { + this.parameterMap = {}; + } + /** + * Constructs a unique name for this parameter bag. + * @return {string} + */ + + + ParameterBag.prototype.getName = function (name) { + if (name === void 0) { + name = 'p'; + } + + return uniqueString(name, keys_1(this.parameterMap)); + }; + /** + * Adds a new parameter to this bag. + * @param {*} value + * @param {string|undefined} name + * @return {Parameter} Newly created parameter object. + */ + + + ParameterBag.prototype.addParam = function (value, name) { + var actualName = this.getName(name); + var param = new Parameter(actualName, value); + this.parameterMap[actualName] = param; + return param; + }; + /** + * Adds an existing parameter to this bag. The name may be changed if + * it is already taken, however, the Parameter object will not be recreated. + * @param {Parameter} param + * @return {Parameter} + */ + + + ParameterBag.prototype.addExistingParam = function (param) { + param.name = this.getName(param.name); + this.parameterMap[param.name] = param; + return param; + }; + /** + * Returns the params in a name: value object suitable for putting into a + * query object. + * @return {object} + */ + + + ParameterBag.prototype.getParams = function () { + return mapValues_1(this.parameterMap, 'value'); + }; + /** + * Removes a parameter from the internal map. + * @param {string} name + */ + + + ParameterBag.prototype.deleteParam = function (name) { + delete this.parameterMap[name]; + }; + /** + * Copies all parameters from another bag into this bag. + */ + + + ParameterBag.prototype.importParams = function (other) { + for (var key in other.parameterMap) { + this.addExistingParam(other.parameterMap[key]); + } + }; + /** + * Returns a parameter with the given name. + */ + + + ParameterBag.prototype.getParam = function (name) { + return this.parameterMap[name]; + }; + + return ParameterBag; +}(); + +var ParameterContainer = +/** @class */ +function () { + function ParameterContainer() { + this.parameterBag = new ParameterBag(); + } + + ParameterContainer.prototype.useParameterBag = function (newBag) { + newBag.importParams(this.parameterBag); + this.parameterBag = newBag; + }; + + ParameterContainer.prototype.getParams = function () { + return this.parameterBag.getParams(); + }; + /** + * Adds a new parameter to the bag. + * @param {*} value + * @param {string|undefined} name + * @return {Parameter} Newly created parameter object. + */ + + + ParameterContainer.prototype.addParam = function (value, name) { + return this.parameterBag.addParam(value, name); + }; + + ParameterContainer.prototype.getParameterBag = function () { + return this.parameterBag; + }; + + return ParameterContainer; +}(); + +var Clause = +/** @class */ +function (_super) { + __extends(Clause, _super); + + function Clause() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * Turns the clause into a query string. + * @return {string} Partial query string. + */ + + + Clause.prototype.toString = function () { + return this.build(); + }; + /** + * Turns the clause into a query object. + * @return {object} Query object with two parameters: query and params. + */ + + + Clause.prototype.buildQueryObject = function () { + return { + query: this.build(), + params: this.getParams() + }; + }; + /** + * Turns the clause into a query string with parameters + * interpolated into the string. For debugging purposes only. + * @return {string} + */ + + + Clause.prototype.interpolate = function () { + var query = this.build(); + var params = this.getParams(); + + for (var name in params) { + var pattern = new RegExp("\\$" + name + "(?![a-zA-Z0-9_])", 'g'); + query = query.replace(pattern, stringifyValue(params[name])); + } + + return query; + }; + + return Clause; +}(ParameterContainer); + +var Pattern = +/** @class */ +function (_super) { + __extends(Pattern, _super); + + function Pattern(name, labels, conditions, options) { + if (options === void 0) { + options = { + expanded: true + }; + } + + var _this = _super.call(this) || this; + + _this.options = options; + _this.conditionParams = {}; + + var isConditions = function (a) { + return isObjectLike_1(a) && !isArray_1(a); + }; + + var tempName = name; + var tempLabels = labels; + var tempConditions = conditions; + + if (isNil_1(tempConditions)) { + if (isConditions(tempLabels)) { + tempConditions = tempLabels; + tempLabels = undefined; + } else if (isNil_1(tempLabels) && isConditions(tempName)) { + tempConditions = tempName; + tempName = undefined; + } else { + tempConditions = {}; + } + } + + if (isNil_1(tempLabels)) { + if (isArray_1(tempName)) { + tempLabels = tempName; + tempName = undefined; + } else { + tempLabels = []; + } + } + + if (isNil_1(tempName)) { + tempName = ''; + } + + if (!isString_1(tempName)) { + throw new TypeError('Name must be a string.'); + } + + if (!isString_1(tempLabels) && !isArray_1(tempLabels)) { + throw new TypeError('Labels must be a string or an array'); + } + + if (!isConditions(tempConditions)) { + throw new TypeError('Conditions must be an object.'); + } + + _this.labels = castArray_1(tempLabels); + _this.name = tempName; + _this.conditions = tempConditions; + + _this.setExpandedConditions(options.expanded); + + return _this; + } + + Pattern.prototype.setExpandedConditions = function (expanded) { + if (this.useExpandedConditions !== expanded) { + this.useExpandedConditions = expanded; + this.rebindConditionParams(); + } + }; + + Pattern.prototype.rebindConditionParams = function () { + var _this = this; // Delete old bindings + + + if (this.conditionParams instanceof Parameter) { + this.parameterBag.deleteParam(this.conditionParams.name); + } else { + for (var key in this.conditionParams) { + this.parameterBag.deleteParam(this.conditionParams[key].name); + } + } // Rebind params + + + if (!isEmpty_1(this.conditions)) { + if (this.useExpandedConditions) { + this.conditionParams = mapValues_1(this.conditions, function (value, name) { + return _this.parameterBag.addParam(value, name); + }); + } else { + this.conditionParams = this.parameterBag.addParam(this.conditions, 'conditions'); + } + } else { + this.conditionParams = {}; + } + }; + + Pattern.prototype.getNameString = function () { + return this.name ? this.name : ''; + }; + + Pattern.prototype.getLabelsString = function (relation) { + if (relation === void 0) { + relation = false; + } + + return stringifyLabels(this.labels, relation); + }; + + Pattern.prototype.getConditionsParamString = function () { + if (isEmpty_1(this.conditions)) { + return ''; + } + + if (this.useExpandedConditions) { + var strings = map_1(this.conditionParams, function (param, name) { + return name + ": " + param; + }); + + return "{ " + strings.join(', ') + " }"; + } + + return this.conditionParams.toString(); + }; + + return Pattern; +}(Clause); + +var NodePattern = +/** @class */ +function (_super) { + __extends(NodePattern, _super); + + function NodePattern(name, labels, conditions) { + return _super.call(this, name, labels, conditions) || this; + } + + NodePattern.prototype.build = function () { + var query = this.getNameString(); + query += this.getLabelsString(); + query += " " + this.getConditionsParamString(); + return "(" + trim_1(query) + ")"; + }; + + return NodePattern; +}(Pattern); + +var isPathLengthArray = function (value) { + return isArray_1(value) && every_1(value, function (item) { + return isNumber_1(item) || isNil_1(item); + }) && value.length > 0; +}; + +var isPathLength = function (value) { + return value === '*' || isNumber_1(value) || isPathLengthArray(value); +}; + +var RelationPattern = +/** @class */ +function (_super) { + __extends(RelationPattern, _super); + + function RelationPattern(dir, name, labels, conditions, length) { + var _this = this; + + var tempName = name; + var tempLabels = labels; + var tempConditions = conditions; + var tempLength = length; + + if (isNil_1(tempLength)) { + if (isPathLength(tempConditions)) { + tempLength = tempConditions; + tempConditions = undefined; + } else if (isNil_1(tempConditions) && isPathLength(tempLabels)) { + tempLength = tempLabels; + tempLabels = undefined; + } else if (isNil_1(tempConditions) && isNil_1(tempLabels) && isPathLength(tempName)) { + tempLength = tempName; + tempName = undefined; + } + } + + if (isPathLength(tempName) || isPathLength(tempLabels) || isPathLength(tempConditions)) { + throw new TypeError('Invalid argument combination.'); + } + + _this = _super.call(this, tempName, tempLabels, tempConditions) || this; + _this.dir = dir; + _this.length = tempLength; + return _this; + } + + RelationPattern.prototype.build = function () { + var name = this.getNameString(); + var labels = this.getLabelsString(true); + var length = stringifyPathLength(this.length); + var conditions = this.getConditionsParamString(); + + var query = trim_1("" + name + labels + length + " " + conditions); + + var arrows = { + in: ['<-', '-'], + out: ['-', '->'], + either: ['-', '-'] + }; + return arrows[this.dir].join(query.length > 0 ? "[" + query + "]" : ''); + }; + + return RelationPattern; +}(Pattern); + +var PatternClause = +/** @class */ +function (_super) { + __extends(PatternClause, _super); + + function PatternClause(patterns, options) { + if (options === void 0) { + options = { + useExpandedConditions: false + }; + } + + var _this = _super.call(this) || this; + + var defaultOptions = { + useExpandedConditions: true + }; + + var useExpandedConditions = assign_1(defaultOptions, options).useExpandedConditions; // Ensure patterns is a two dimensional array. + + + var arr = castArray_1(patterns); + + _this.patterns = isArray_1(arr[0]) ? arr : [arr]; // Add child patterns as clauses + + _this.patterns.forEach(function (arr) { + return arr.forEach(function (pat) { + pat.setExpandedConditions(useExpandedConditions); + pat.useParameterBag(_this.parameterBag); + }); + }); + + return _this; + } + + PatternClause.prototype.build = function () { + var patternStrings = map_1(this.patterns, function (pattern) { + return reduce_1(pattern, function (str, clause) { + return str + clause.build(); + }, ''); + }); + + return patternStrings.join(', '); + }; + + return PatternClause; +}(Clause); + +var Create = +/** @class */ +function (_super) { + __extends(Create, _super); + + function Create(patterns, options) { + if (options === void 0) { + options = {}; + } + + var _this = _super.call(this, patterns, { + useExpandedConditions: false + }) || this; + + _this.options = options; + return _this; + } + + Create.prototype.build = function () { + var unique = this.options.unique ? ' UNIQUE' : ''; + return "CREATE" + unique + " " + _super.prototype.build.call(this); + }; + + return Create; +}(PatternClause); + +var TermListClause = +/** @class */ +function (_super) { + __extends(TermListClause, _super); + /** + * Accepts: + * node -> string + * many nodes -> string[] + * nodes with aliases -> Dictionary + * node properties -> Dictionary + * node properties with aliases -> Dictionary[]> + * or an array of any combination + */ + + + function TermListClause(terms) { + var _this = _super.call(this) || this; + + _this.terms = castArray_1(terms); + return _this; + } + + TermListClause.prototype.build = function () { + return this.toString(); + }; + + TermListClause.prototype.toString = function () { + var _this = this; + + return flatMapDeep_1(this.terms, function (term) { + return _this.stringifyTerm(term); + }).join(', '); + }; + + TermListClause.prototype.stringifyTerm = function (term) { + // Just a node + if (isString_1(term)) { + return [this.stringifyProperty(term)]; + } // Node properties or aliases + + + if (isPlainObject_1(term)) { + return this.stringifyDictionary(term); + } + + return []; + }; + + TermListClause.prototype.stringifyProperty = function (prop, alias, node) { + var prefixString = node ? node + "." : ''; + var aliasString = alias ? alias + " AS " : ''; + return prefixString + aliasString + prop; + }; + + TermListClause.prototype.stringifyProperties = function (props, alias, node) { + var _this = this; + + var convertToString = function (list, prop) { + if (isString_1(prop)) { + // Single node property + list.push(_this.stringifyProperty(prop, alias, node)); + } else { + // Node properties with aliases + list.push.apply(list, map_1(prop, function (name, alias) { + return _this.stringifyProperty(name, alias, node); + })); + } + + return list; + }; + + return reduce_1(castArray_1(props), convertToString, []); + }; + + TermListClause.prototype.stringifyDictionary = function (node) { + var _this = this; + + return reduce_1(node, function (list, prop, key) { + if (isString_1(prop)) { + // Alias + list.push(_this.stringifyProperty(prop, key)); + } else { + // Node with properties + list.push.apply(list, _this.stringifyProperties(prop, undefined, key)); + } + + return list; + }, []); + }; + + return TermListClause; +}(Clause); + +var With = +/** @class */ +function (_super) { + __extends(With, _super); + /** + * Creates a with clause + * @param {string|object|array} terms + */ + + + function With(terms) { + return _super.call(this, terms) || this; + } + + With.prototype.build = function () { + return "WITH " + _super.prototype.build.call(this); + }; + + return With; +}(TermListClause); + +var Unwind = +/** @class */ +function (_super) { + __extends(Unwind, _super); + + function Unwind(list, name) { + var _this = _super.call(this) || this; + + _this.list = list; + _this.name = name; + _this.listParam = _this.parameterBag.addParam(_this.list, 'list'); + return _this; + } + + Unwind.prototype.build = function () { + return "UNWIND " + this.listParam + " AS " + this.name; + }; + + return Unwind; +}(Clause); + +var Delete = +/** @class */ +function (_super) { + __extends(Delete, _super); + + function Delete(variables, options) { + if (options === void 0) { + options = {}; + } + + var _this = _super.call(this) || this; + + _this.options = options; + _this.variables = castArray_1(variables); + return _this; + } + + Delete.prototype.build = function () { + var detach = this.options.detach ? 'DETACH ' : ''; + return detach + "DELETE " + this.variables.join(', '); + }; + + return Delete; +}(Clause); + +var Set$2 = +/** @class */ +function (_super) { + __extends(Set, _super); + + function Set(_a, options) { + var labels = _a.labels, + values = _a.values, + variables = _a.variables; + + if (options === void 0) { + options = {}; + } + + var _this = _super.call(this) || this; + + _this.makeLabelStatement = function (labels, key) { + return key + stringifyLabels(labels); + }; + + _this.makeValueStatement = function (value, key) { + var valueIsObject = value instanceof Parameter ? isObject_1(value.value) : isObject_1(value); + var op = _this.merge && valueIsObject ? ' += ' : ' = '; + return key + op + value; + }; + + _this.makeVariableStatement = function (value, key) { + var op = _this.merge ? ' += ' : ' = '; + + if (isString_1(value)) { + return key + op + value; + } + + var operationStrings = map_1(value, function (value, prop) { + return key + "." + prop + op + value; + }); + + return operationStrings.join(', '); + }; + + _this.labels = mapValues_1(labels, castArray_1); + _this.values = mapValues_1(values, function (value, name) { + return _this.parameterBag.addParam(value, name); + }); + _this.variables = variables || {}; + _this.merge = !!options.merge; + return _this; + } + + Set.prototype.build = function () { + var labels = map_1(this.labels, this.makeLabelStatement); + + var values = map_1(this.values, this.makeValueStatement); + + var variables = map_1(this.variables, this.makeVariableStatement); + + return "SET " + concat_1(labels, values, variables).join(', '); + }; + + return Set; +}(Clause); + +var Match = +/** @class */ +function (_super) { + __extends(Match, _super); + + function Match(patterns, options) { + if (options === void 0) { + options = { + optional: false + }; + } + + var _this = _super.call(this, patterns, { + useExpandedConditions: true + }) || this; + + _this.options = options; + return _this; + } + + Match.prototype.build = function () { + var str = 'MATCH '; + + if (this.options.optional) { + str = "OPTIONAL " + str; + } + + return str + _super.prototype.build.call(this); + }; + + return Match; +}(PatternClause); + +var Remove = +/** @class */ +function (_super) { + __extends(Remove, _super); + + function Remove(_a) { + var _b = _a.labels, + labels = _b === void 0 ? {} : _b, + _c = _a.properties, + properties = _c === void 0 ? {} : _c; + + var _this = _super.call(this) || this; + + _this.labels = mapValues_1(labels, castArray_1); + _this.properties = mapValues_1(properties, castArray_1); + return _this; + } + + Remove.prototype.build = function () { + var labels = map_1(this.labels, function (labels, key) { + return key + stringifyLabels(labels); + }); + + var properties = flatMap_1(this.properties, function (properties, key) { + return map_1(properties, function (property) { + return key + "." + property; + }); + }); + + return "REMOVE " + __spreadArrays(labels, properties).join(', '); + }; + + return Remove; +}(Clause); + +var Return = +/** @class */ +function (_super) { + __extends(Return, _super); + + function Return(terms, options) { + if (options === void 0) { + options = {}; + } + + var _this = _super.call(this, terms) || this; + + _this.options = options; + return _this; + } + + Return.prototype.build = function () { + var distinct = this.options.distinct ? ' DISTINCT' : ''; + return "RETURN" + distinct + " " + _super.prototype.build.call(this); + }; + + return Return; +}(TermListClause); + +var Skip = +/** @class */ +function (_super) { + __extends(Skip, _super); + + function Skip(amount) { + var _this = _super.call(this) || this; + + _this.amount = amount; + _this.amountParam = _this.addParam(neo4j.int(amount), 'skipCount'); + return _this; + } + + Skip.prototype.build = function () { + return "SKIP " + this.amountParam; + }; + + return Skip; +}(Clause); + +var Limit = +/** @class */ +function (_super) { + __extends(Limit, _super); + + function Limit(amount) { + var _this = _super.call(this) || this; + + _this.amount = amount; + _this.amountParam = _this.addParam(neo4j.int(amount), 'limitCount'); + return _this; + } + + Limit.prototype.build = function () { + return "LIMIT " + this.amountParam; + }; + + return Limit; +}(Clause); + +function compare(operator, value, variable, paramName) { + return function (params, name) { + var baseParamName = paramName || last_1(name.split('.')); + + var parts = [name, operator, variable ? value : params.addParam(value, baseParamName)]; + return parts.join(' '); + }; +} +/** + * Regexp comparator for use in where clauses. Also accepts a case insensitive + * to make it easier to add the `'(?i)'` flag to the start of your regexp. + * If you are already using flags in your regexp, you should not set insensitive + * to true because it will prepend `'(?i)'` which will make your regexp + * malformed. + * + * For convenience you can also pass a Javascript RegExp object into this + * comparator, which will then be converted into a string before it is + * passed to cypher. *However*, beware that the cypher regexp syntax is + * inherited from [java]{@link + * https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html}, + * and may have slight differences to the Javascript syntax. For example, + * Javascript RegExp flags will not be preserved when sent to cypher. + * + * If you want to compare against a Neo4j variable you can set `variable` to + * true and the value will be inserted literally into the query. + * + * ``` + * query.where({ name: regexp('s.*e') }) + * // WHERE name =~ 's.*e' + * + * query.where({ name: regexp('s.*e', true) }) + * // WHERE name =~ '(?i)s.*e' + * + * query.where({ name: regexp('clientPattern', false, true) }) + * // WHERE name =~ clientPattern + * ``` + * @param exp + * @param insensitive + * @param {boolean} variable + * @returns {Comparator} + */ + +function regexp(exp, insensitive, variable) { + var stringExp = exp; + + if (exp instanceof RegExp) { + // Convert regular expression to string and strip slashes and trailing flags. + // This regular expression will always match something so we can use the ! operator to ignore + // type errors. + stringExp = exp.toString().match(/\/(.*)\/[a-z]*/)[1]; + } + + return compare('=~', insensitive ? "(?i)" + stringExp : stringExp, variable); +} + +var Precedence; + +(function (Precedence) { + Precedence[Precedence["None"] = 0] = "None"; + Precedence[Precedence["Or"] = 1] = "Or"; + Precedence[Precedence["Xor"] = 2] = "Xor"; + Precedence[Precedence["And"] = 3] = "And"; + Precedence[Precedence["Not"] = 4] = "Not"; +})(Precedence || (Precedence = {})); + +var WhereOp = +/** @class */ +function () { + function WhereOp() {} + + return WhereOp; +}(); +function stringifyCondition(params, condition, name) { + if (name === void 0) { + name = ''; + } + + if (isFunction_1(condition)) { + return condition(params, name); + } + + var conditionName = last_1(name.split('.')); + + return name + " = " + params.addParam(condition, conditionName); +} +function stringCons(params, conditions, precedence, name) { + if (precedence === void 0) { + precedence = Precedence.None; + } + + if (name === void 0) { + name = ''; + } + + if (isArray_1(conditions)) { + return combineOr(params, conditions, precedence, name); + } + + if (isPlainObject_1(conditions)) { + return combineAnd(params, conditions, precedence, name); + } + + if (conditions instanceof WhereOp) { + return conditions.evaluate(params, precedence, name); + } + + if (isRegExp_1(conditions)) { + return stringifyCondition(params, regexp(conditions), name); + } + + return stringifyCondition(params, conditions, name); +} +function combineNot(params, conditions, precedence, name) { + if (precedence === void 0) { + precedence = Precedence.None; + } + + if (name === void 0) { + name = ''; + } + + var string = "NOT " + stringCons(params, conditions, Precedence.Not, name); + var braces = precedence !== Precedence.None && precedence > Precedence.Not; + return braces ? "(" + string + ")" : string; +} +function combineOr(params, conditions, precedence, name) { + if (precedence === void 0) { + precedence = Precedence.None; + } + + if (name === void 0) { + name = ''; + } // If this operator will not be used, precedence should not be altered + + + var newPrecedence = conditions.length < 2 ? precedence : Precedence.Or; + + var strings = map_1(conditions, function (condition) { + return stringCons(params, condition, newPrecedence, name); + }); + + var string = strings.join(' OR '); + var braces = precedence !== Precedence.None && precedence > newPrecedence; + return braces ? "(" + string + ")" : string; +} +function combineXor(params, conditions, precedence, name) { + if (precedence === void 0) { + precedence = Precedence.None; + } + + if (name === void 0) { + name = ''; + } // If this operator will not be used, precedence should not be altered + + + var newPrecedence = conditions.length < 2 ? precedence : Precedence.Xor; + + var strings = map_1(conditions, function (condition) { + return stringCons(params, condition, newPrecedence, name); + }); + + var string = strings.join(' XOR '); + var braces = precedence !== Precedence.None && precedence > newPrecedence; + return braces ? "(" + string + ")" : string; +} +function combineAnd(params, conditions, precedence, name) { + if (precedence === void 0) { + precedence = Precedence.None; + } + + if (name === void 0) { + name = ''; + } // Prepare name to be joined with the key of the object + + + var namePrefix = name.length > 0 ? name + "." : ''; // If this operator will not be used, precedence should not be altered + + var newPrecedence = keys_1(conditions).length < 2 ? precedence : Precedence.And; + + var strings = map_1(conditions, function (condition, key) { + return stringCons(params, condition, newPrecedence, namePrefix + key); + }); + + var string = strings.join(' AND '); + var braces = precedence !== Precedence.None && precedence > newPrecedence; + return braces ? "(" + string + ")" : string; +} + +var Where = +/** @class */ +function (_super) { + __extends(Where, _super); + + function Where(conditions) { + var _this = _super.call(this) || this; + + _this.conditions = conditions; + return _this; + } + + Where.prototype.build = function () { + return "WHERE " + stringCons(this.parameterBag, this.conditions); + }; + + return Where; +}(Clause); + +var Raw = +/** @class */ +function (_super) { + __extends(Raw, _super); + + function Raw(clause) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + var _this = _super.call(this) || this; + + if (isString_1(clause)) { + _this.clause = clause; + var params = args[0]; + + if (isObjectLike_1(params)) { + for (var key in params) { + if (Object.hasOwnProperty.call(params, key)) { + _this.addParam(params[key], key); + } + } + } else if (!isNil_1(params)) { + throw new TypeError('When passing a string clause to Raw, params should be an object'); + } + } else if (isArray_1(clause)) { + var queryParams = map_1(args, function (param) { + return _this.addParam(param); + }); + + _this.clause = flatten_1(zip_1(clause, queryParams)).join(''); + } else { + throw new TypeError('Clause should be a string or an array'); + } + + return _this; + } + + Raw.prototype.build = function () { + return this.clause; + }; + + return Raw; +}(Clause); + +var OrderBy = +/** @class */ +function (_super) { + __extends(OrderBy, _super); + + function OrderBy(fields, dir) { + var _this = _super.call(this) || this; + + var direction = OrderBy.normalizeDirection(dir); + + if (isString_1(fields)) { + _this.constraints = [{ + direction: direction, + field: fields + }]; + } else if (isArray_1(fields)) { + _this.constraints = map_1(fields, function (field) { + if (!isArray_1(field)) { + return { + field: field, + direction: direction + }; + } + + var fieldDirection = field[1] ? OrderBy.normalizeDirection(field[1]) : direction; + return { + field: field[0], + direction: fieldDirection + }; + }); + } else { + _this.constraints = map_1(fields, function (fieldDirection, field) { + return { + field: field, + direction: OrderBy.normalizeDirection(fieldDirection) + }; + }); + } + + return _this; + } + + OrderBy.prototype.build = function () { + var constraints = map_1(this.constraints, function (_a) { + var field = _a.field, + direction = _a.direction; + return trim_1(field + " " + direction); + }); + + return "ORDER BY " + constraints.join(', '); + }; + + OrderBy.normalizeDirection = function (dir) { + var upperDir = typeof dir === 'string' ? dir.toUpperCase() : dir; + var isDescending = upperDir === 'DESC' || upperDir === 'DESCENDING' || upperDir === true; + return isDescending ? 'DESC' : ''; + }; + + return OrderBy; +}(Clause); + +var Merge = +/** @class */ +function (_super) { + __extends(Merge, _super); + + function Merge(patterns) { + return _super.call(this, patterns, { + useExpandedConditions: true + }) || this; + } + + Merge.prototype.build = function () { + return "MERGE " + _super.prototype.build.call(this); + }; + + return Merge; +}(PatternClause); + +var OnMatch = +/** @class */ +function (_super) { + __extends(OnMatch, _super); + + function OnMatch(clause) { + var _this = _super.call(this) || this; + + _this.clause = clause; + clause.useParameterBag(_this.parameterBag); + return _this; + } + + OnMatch.prototype.build = function () { + return "ON MATCH " + this.clause.build(); + }; + + return OnMatch; +}(Clause); + +var OnCreate = +/** @class */ +function (_super) { + __extends(OnCreate, _super); + + function OnCreate(clause) { + var _this = _super.call(this) || this; + + _this.clause = clause; + clause.useParameterBag(_this.parameterBag); + return _this; + } + + OnCreate.prototype.build = function () { + return "ON CREATE " + this.clause.build(); + }; + + return OnCreate; +}(Clause); + +/** @class */ +(function (_super) { + __extends(WhereAnd, _super); + + function WhereAnd(conditions) { + var _this = _super.call(this) || this; + + _this.conditions = conditions; + return _this; + } + + WhereAnd.prototype.evaluate = function (params, precedence, name) { + if (precedence === void 0) { + precedence = Precedence.None; + } + + if (name === void 0) { + name = ''; + } + + return combineAnd(params, this.conditions, precedence, name); + }; + + return WhereAnd; +})(WhereOp); + +/** @class */ +(function (_super) { + __extends(WhereOr, _super); + + function WhereOr(conditions) { + var _this = _super.call(this) || this; + + _this.conditions = conditions; + return _this; + } + + WhereOr.prototype.evaluate = function (params, precedence, name) { + if (precedence === void 0) { + precedence = Precedence.None; + } + + if (name === void 0) { + name = ''; + } + + return combineOr(params, this.conditions, precedence, name); + }; + + return WhereOr; +})(WhereOp); + +/** @class */ +(function (_super) { + __extends(WhereXor, _super); + + function WhereXor(conditions) { + var _this = _super.call(this) || this; + + _this.conditions = conditions; + return _this; + } + + WhereXor.prototype.evaluate = function (params, precedence, name) { + if (precedence === void 0) { + precedence = Precedence.None; + } + + if (name === void 0) { + name = ''; + } + + return combineXor(params, this.conditions, precedence, name); + }; + + return WhereXor; +})(WhereOp); + +/** @class */ +(function (_super) { + __extends(WhereNot, _super); + + function WhereNot(conditions) { + var _this = _super.call(this) || this; + + _this.conditions = conditions; + return _this; + } + + WhereNot.prototype.evaluate = function (params, precedence, name) { + if (precedence === void 0) { + precedence = Precedence.None; + } + + if (name === void 0) { + name = ''; + } + + return combineNot(params, this.conditions, precedence, name); + }; + + return WhereNot; +})(WhereOp); + +/** + * Creates a node pattern like `(parent:Person { name: 'Gwenn' })`. + * + * All of the arguments are optional and most of the time you can supply only + * the ones you want, assuming you keep the order the same of course. + * + * Use the following signatures as a reference: + * + * ```typescript + * node(conditions: Dictionary) + * node(labels: string[], conditions?: Dictionary) + * node(name: string, conditions?: Dictionary) + * node(name: string, labels?: string | string[], conditions?: Dictionary) + * ``` + * *Note that labels must be an array when it is the first argument.* + * + * + * + * Some examples + * + * ```typescript + * node() + * // () + * + * node('parent') + * // (parent) + * + * node('parent', 'Person') + * // (parent:Person) + * + * node([ 'Person' ]) + * // (:Person) + * + * node('parent', [ 'Person', 'Adult' ]) + * // (parent:Person:Adult) + * + * node({ name: 'Gwenn' }) + * // ({ name: 'Gwenn' }) + * + * node('parent', { name: 'Gwenn' }) + * // (parent { name: 'Gwenn' }) + * + * node([ 'Person' ], { name: 'Gwenn' }) + * // (:Person { name: 'Gwenn' }) + * + * node('parent', 'Person', { name: 'Gwenn' }) + * // (parent:Person { name: 'Gwenn' }) + * ``` + * + * For more details on node patterns see the cypher + * [docs]{@link + * https://neo4j.com/docs/developer-manual/current/cypher/syntax/patterns/#cypher-pattern-node} + * + * @param {_.Many | _.Dictionary} name + * @param {_.Many | _.Dictionary} labels + * @param {_.Dictionary} conditions A dictionary of conditions to attach + * to the node. These are stored as parameters so there is no need to worry + * about escaping. + * @returns {NodePattern} An object representing the node pattern. + */ + +function node$1(name, labels, conditions) { + return new NodePattern(name, labels, conditions); +} // Need to disable line length because there is a long link in the documentation + +/* tslint:disable:max-line-length */ + +/** + * Creates a relation pattern like `-[rel:FriendsWith { active: true }]->`. + * + * The only required argument is direction. All other arguments are optional and all combinations of + * them are valid. The only exception is that when labels is the first argument after direction, it + * must be an array, otherwise it will be interpreted as the relation name. + * + * Some examples + * + * ```typescript + * relation('either') + * // -- + * + * relation('out', 'rel') + * // -[rel]-> + * + * relation('out', 'rel', 'FriendsWith') + * // -[rel:FriendsWith]-> + * + * relation('in', [ 'FriendsWith', 'RelatedTo' ]) + * // <-[:FriendsWith|RelatedTo]- + * // Note that this will match a relation with either the FriendsWith label or + * // the RelatedTo label. You cannot use this syntax when creating relations. + * + * relation('in', [4, 10]) + * // <-[*4..10]- + * + * relation('in', { active: true }) + * // <-[{ active: true }] + * + * relation('in', 'rel', { active: true }) + * // <-[rel { active: true }]- + * + * relation('either', [ 'FriendsWith' ], { active: true }) + * // -[:FriendsWith { active: true }]- + * + * relation('either', 'rel', 'FriendsWith', { active: true }, 3) + * // -[rel:FriendsWith*3 { active: true }]- + * + * relation('either', 'rel', 'FriendsWith', { active: true }, [ 3 ]) + * // -[rel:FriendsWith*3.. { active: true }]- + * + * relation('either', 'rel', 'FriendsWith', { active: true }, [ 3, 5 ]) + * // -[rel:FriendsWith*3..5 { active: true }]- + * + * relation('either', 'rel', 'FriendsWith', { active: true }, '*') + * // -[rel:FriendsWith* { active: true }]- + * ``` + * + * For more details on relation patterns see the cypher + * [docs]{@link + * https://neo4j.com/docs/developer-manual/current/cypher/syntax/patterns/#cypher-pattern-relationship}. + * + * @param dir Direction of the relation. `in` means to the left, `out` means to + * the right and `either` means no direction. + * @param {_.Many | _.Dictionary} name + * @param {_.Many | _.Dictionary} labels + * @param {_.Dictionary} conditions + * @param length Length of the relation for flexible length paths. Can be the + * string `'*'` to represent any length, a single number `3` to represent the + * maximum length of the path, or an array of two numbers which represent the + * minimum and maximum length of the path. When passing an array, the second + * number is optional, see the examples above. + * @returns {RelationPattern} An object representing the relation pattern. + */ + +/* tslint:disable:max-line-length */ + +function relation(dir, name, labels, conditions, length) { + return new RelationPattern(dir, name, labels, conditions, length); +} + +var Union = +/** @class */ +function (_super) { + __extends(Union, _super); + + function Union(all) { + if (all === void 0) { + all = false; + } + + var _this = _super.call(this) || this; + + _this.all = all; + return _this; + } + + Union.prototype.build = function () { + return "UNION" + (this.all ? ' ALL' : ''); + }; + + return Union; +}(Clause); + +/** + * @internal + */ + +var SetBlock = +/** @class */ +function () { + function SetBlock(chain, wrapper) { + this.chain = chain; + this.wrapper = wrapper; + } + /** + * Adds a [set]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/set} + * clause to the query. + * + * `set` lets you updates a nodes labels and properties in one clause. Most of + * the time it will be easier to use one of the variants such as `setLabels`, + * `setValues` or `setVariables`. + * + * This function accepts three different kind of properties, each of which is + * described in more detail in the variants. + * + * ``` + * query.set({ + * labels: { + * sale: 'Active', + * }, + * variables: { + * sale: { + * activatedAt: 'timestamp()', + * }, + * }, + * values: { + * sale: { + * activatedBy: user.id, + * }, + * }, + * }) + * // SET sale:Active, sale.activatedAt = timestamp(), sale.activatedBy = $userId + * ``` + * + * `set` also accepts an options object which currently only contains a + * single setting: `override`. Override controls whether the `=` or `+=` + * operator is used in the set clause. `true` causes the existing object to be + * cleared and replaced by the new object. `false` on the other hand will + * merge the existing and new objects together, with new properties replacing + * the ones on the existing object. + * The default value of override is a little inconsistent and it will be + * improved in the next major version. If you don't pass any settings object, + * override will default to `true`. If you pass an options object without an + * `override` key, override will be `false`. In future versions, override will + * always default to `false` to be more consistent with `setVariables` and + * `setValues`. + * + * @param {SetProperties} properties + * @param {SetOptions} options + * @returns {Q} + */ + + + SetBlock.prototype.set = function (properties, options) { + return this.chain(this.wrap(new Set$2(properties, options))); + }; + /** + * Adds labels to a node using a [set]{@link + * https://neo4j.com/docs/developer-manual/current/cypher/clauses/set} + * clause. + * + * ``` + * query.setLabels({ + * sale: 'Active', + * }) + * // SET sale:Active + * ``` + * + * `setLabels` accepts a dictionary where the keys are nodes to be updated + * and the value is a single label or an array of labels to add to the node. + * + * @param {_.Dictionary<_.Many>} labels + * @returns {Q} + */ + + + SetBlock.prototype.setLabels = function (labels) { + return this.chain(this.wrap(new Set$2({ + labels: labels + }))); + }; + /** + * Updates a node from parameters using a [set]{@link + * https://neo4j.com/docs/developer-manual/current/cypher/clauses/set} + * clause. This function treats all values as parameters which is different to + * `setVariables` which assumes values are cypher variables. + * + * ``` + * query.setValues({ + * 'sale.activatedBy': user.id, + * }) + * // SET sale.activatedBy += $userId + * ``` + * + * `setValues` accepts a dictionary where the keys are nodes or property names + * to be updated. + * + * To use the `+=` operator to merge properties of a node, you can pass + * `true` to the merge option. + * ``` + * query.setValues({ + * 'sale': { active: true }, + * }, true) + * // SET sale += $sale + * ``` + */ + + + SetBlock.prototype.setValues = function (values, merge) { + return this.chain(this.wrap(new Set$2({ + values: values + }, { + merge: merge + }))); + }; + /** + * Updates a node from a variable that was previously declared in the query + * using a [set]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/set} + * clause. This function only accepts strings as its values which are not + * escaped in any way so beware. If you want to store some user supplied + * information in the database, `setValues` is the function you want. + * + * ``` + * query.setVariables({ + * 'sale.activatedAt': 'timestamp()', + * }) + * // SET sale.activatedAt = timestamp() + * ``` + * Note how values are inserted into the query, as is. + * + * To use the `+=` operator to merge properties of a node, you can pass + * `true` to the merge option. + * ``` + * query.setVariables({ + * 'sale': 'newSaleDetails' + * }, true) + * // SET sale += newSaleDetails + * ``` + */ + + + SetBlock.prototype.setVariables = function (variables, merge) { + return this.chain(this.wrap(new Set$2({ + variables: variables + }, { + merge: merge + }))); + }; + + SetBlock.prototype.wrap = function (clause) { + return this.wrapper ? new this.wrapper(clause) : clause; + }; + + return SetBlock; +}(); +/** + * Root class for all query chains, namely the {@link Connection} and + * {@link Query} classes. + * @internal + */ + +var Builder = +/** @class */ +function (_super) { + __extends(Builder, _super); + + function Builder() { + var _this = _super.call(this, function (c) { + return _this.continueChainClause(c); + }) || this; + /** + * Used to add an `ON CREATE` clause to the query. Any following query will be prefixed with + * `ON CREATE`. + * + * Example: + * ```javascript + * query.onCreate.setLabels({ node: 'Active' }); + * // ON CREATE SET node:Active + * query.onCreate.setVariables({ 'node.createdAt': 'timestamp()' }); + * // ON CREATE SET node.createdAt = timestamp() + * ```` + * + * The only methods that are available after `onCreate` are the set family of clauses. + */ + + + _this.onCreate = new SetBlock(_this.continueChainClause.bind(_this), OnCreate); + /** + * Used to add an `ON MATCH` clause to the query. Any following query will be prefixed with + * `ON MATCH`. + * + * Example: + * ```javascript + * query.onMatch.setLabels({ node: 'Active' }); + * // ON MATCH SET node:Active + * query.onMatch.setVariables({ 'node.updatedAt': 'timestamp()' }); + * // ON MATCH SET node.createdAt = timestamp() + * ```` + * + * The only methods that are available after `onMatch` are the set family of clauses. + */ + + _this.onMatch = new SetBlock(_this.continueChainClause.bind(_this), OnMatch); + return _this; + } + /** + * Adds a [create]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/create} + * clause to the query. + * + * Create accepts a single pattern, a list of patterns or a list of a list of + * patterns. Each pattern represents a single part of a cypher pattern. For + * example: `(people:Person { age: 30 })` would be a node pattern and + * `-[:FriendsWith]->` would be a relationship pattern. + * + * If an array of patterns is provided, they are joined together to form a + * composite pattern. For example: + * ```javascript + * query.create([ + * node('people', 'Person', { age: 30 }), + * relation('out', '', 'FriendsWith'), + * node('friend', 'Friend'), + * ]) + * ``` + * + * Would equate to the cypher pattern + * ``` + * CREATE (people:Person { age: 30 })-[:FriendsWith]->(friend:Friend) + * ``` + * + * The create method also accepts a `unique` option which will cause a `CREATE UNIQUE` clause to + * be emitted instead. + * ```javascript + * query.create([node('people', 'Person', { age: 30 })], { unique: true }); + * // CREATE UNIQUE (people:Person { age: 30 }) + * ``` + */ + + + Builder.prototype.create = function (patterns, options) { + return this.continueChainClause(new Create(patterns, options)); + }; + /** + * Shorthand for `create(patterns, { unique: true })` + */ + + + Builder.prototype.createUnique = function (patterns) { + return this.create(patterns, { + unique: true + }); + }; + /** + * Shorthand for `create(node(name, labels, conditions), options)`. For more details + * the arguments see @{link node}. + */ + + + Builder.prototype.createNode = function (name, labels, conditions, options) { + var clause = new Create(new NodePattern(name, labels, conditions), options); + return this.continueChainClause(clause); + }; + /** + * Shorthand for `createNode(name, labels, conditions, { unique: true })` + */ + + + Builder.prototype.createUniqueNode = function (name, labels, conditions) { + return this.createNode(name, labels, conditions, { + unique: true + }); + }; + /** + * Adds a [delete]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/delete} + * clause to the query. + * + * Delete accepts a single string or an array of them and all of them are + * joined together with commas. *Note that these strings are not escaped or + * passed to Neo4j using parameters, therefore you should not pass user + * input into this clause without escaping it first*. + * + * You can set `detach: true` in the options to make it a `DETACH DELETE` + * clause. + * + * @param {_.Many} terms + * @param {DeleteOptions} options + * @returns {Q} + */ + + + Builder.prototype.delete = function (terms, options) { + return this.continueChainClause(new Delete(terms, options)); + }; + /** + * Shorthand for `delete(terms, { detach: true })`. + * + * @param {_.Many} terms + * @param {DeleteOptions} options + * @returns {Q} + */ + + + Builder.prototype.detachDelete = function (terms, options) { + if (options === void 0) { + options = {}; + } + + return this.continueChainClause(new Delete(terms, assign_1(options, { + detach: true + }))); + }; + /** + * Adds a [limit]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/limit} + * clause to the query. + * + * @param {string | number} amount + * @returns {Q} + */ + + + Builder.prototype.limit = function (amount) { + return this.continueChainClause(new Limit(amount)); + }; + /** + * Adds a [match]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/match} + * clause to the query. + * + * Match accepts a single pattern, a list of patterns or a list of a list of + * patterns. Each pattern represents a single part of a cypher pattern. For + * example: `(people:Person { age: 30 })` would be a node pattern and + * `-[:FriendsWith]->` would be a relationship pattern. + * + * If an array of patterns is provided, they are joined together to form a + * composite pattern. For example: + * ```javascript + * query.match([ + * node('people', 'Person', { age: 30 }), + * relation('out', '', 'FriendsWith'), + * node('friends'), + * ]) + * ``` + * + * Would equate to the cypher pattern + * ``` + * MATCH (people:Person { age: 30 })-[:FriendsWith]->(friends) + * ``` + * + * If an array of an array of patterns is provided each array is joined + * together like above, and then each composite pattern is joined with a comma + * to allow matching of multiple distinct patterns. Note: matching many + * distinct patterns will produce a cross product of the results as noted in + * the [cypher docs]{@link + * https://neo4j.com/developer/kb/cross-product-cypher-queries-will-not-perform-well/}. + * + * You can also provide `optional: true` in the options to create and + * `OPTIONAL MATCH` clause. + * + * @param {PatternCollection} patterns List of patterns to be matched. + * @param {MatchOptions} options + * @returns {Q} + */ + + + Builder.prototype.match = function (patterns, options) { + return this.continueChainClause(new Match(patterns, options)); + }; + /** + * Shorthand for `match(node(name, labels, conditions))`. For more details on + * the arguments see {@link node}. + * + * @param {_.Many | _.Dictionary} name + * @param {_.Many | _.Dictionary} labels + * @param {_.Dictionary} conditions + * @returns {Q} + */ + + + Builder.prototype.matchNode = function (name, labels, conditions) { + var clause = new Match(new NodePattern(name, labels, conditions)); + return this.continueChainClause(clause); + }; + /** + * Shorthand for `match(patterns, { optional: true })`. + * + * @param {PatternCollection} patterns + * @param {MatchOptions} options + * @returns {Q} + */ + + + Builder.prototype.optionalMatch = function (patterns, options) { + if (options === void 0) { + options = {}; + } + + return this.continueChainClause(new Match(patterns, assign_1(options, { + optional: true + }))); + }; + /** + * Adds a [merge]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/merge/} + * clause to the query. It accepts the same parameters as `match` and `create` so refer to them + * for more information. + * + * ```javascript + * query.merge([ + * node('user', 'User', { id: 1 }), + * relation('out', 'rel', 'OwnsProject'), + * node('project', 'Project', { id: 20 }), + * ]) + * .onMatch.setVariables({ 'rel.updatedAt': `timestamp` }); + * // MERGE (user:User { id: 1 })-[rel:OwnsProject]->(project:Project { id: 20 }) + * // ON MATCH SET rel.updatedAt = timestamp() + * ``` + */ + + + Builder.prototype.merge = function (patterns) { + return this.continueChainClause(new Merge(patterns)); + }; + /** + * Adds an [order by]{@link + * https://neo4j.com/docs/developer-manual/current/cypher/clauses/order-by} + * to the query. + * + * Pass a single string or an array of strings to order by. + * ```javascript + * query.orderBy([ + * 'name', + * 'occupation', + * ]) + * // ORDER BY name, occupation + * ``` + * + * You can control the sort direction by adding a direction to each property. + * ```javascript + * query.orderBy([ + * ['name', 'DESC'], + * 'occupation', // Same as ['occupation', 'ASC'] + * ]) + * // ORDER BY name DESC, occupation + * ``` + * + * The second parameter is the default search direction for all properties that + * don't have a direction specified. So the above query could instead be + * written as: + * ```javascript + * query.orderBy([ + * 'name', + * ['occupation', 'ASC'] + * ], 'DESC') + * // ORDER BY name DESC, occupation + * ``` + * + * It is also acceptable to pass an object where each key is the + * property and the value is a direction. Eg: + * ```javascript + * query.orderBy({ + * name: 'DESC', + * occupation: 'ASC', + * }) + * ``` + * However, the underlying iteration order is not always guaranteed and + * it may cause subtle bugs in your code. It is still accepted but it + * is recommended that you use the array syntax above. + * + * Valid values for directions are `DESC`, `DESCENDING`, `ASC`, `ASCENDING`. + * `true` and `false` are also accepted (`true` being the same as `DESC` and + * `false` the same as `ASC`), however they should be avoided as they are + * quite ambiguous. Directions always default to `ASC` as it does in cypher. + * + * @param {_.Many | OrderConstraints} fields + * @param {Direction} dir + * @returns {Q} + */ + + + Builder.prototype.orderBy = function (fields, dir) { + return this.continueChainClause(new OrderBy(fields, dir)); + }; + /** + * Adds a clause to the query as is. You can also provide an object of params + * as well. + * + * ```javascript + * query.raw('MATCH (:Event { date: $date }', { date: '2017-01-01' }) + * ``` + * + * `raw` can also be used as a template tag + * + * ```javascript + * query.matchNode('event', 'Event', { id: 1 }) + * .raw`SET event.finishedAt = ${Date.now()}` + * ``` + * + * But note that using template parameters where they are not supported in a query will produce + * an malformed query. + * + * ```javascript + * query.raw`SET node.${property} = 'value'` + * // Invalid query: + * // SET node.$param1 = 'value' + * ``` + * + * @param {string} clause + * @param args + * @returns {Q} + */ + + + Builder.prototype.raw = function (clause) { + var args = []; + + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + + return this.continueChainClause(new (Raw.bind.apply(Raw, __spreadArrays([void 0, clause], args)))()); + }; + /** + * Adds a [remove]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/remove/} + * clause to the query. + * + * Pass objects containing the list of properties and labels to remove from a node. Each key in an + * object is the name of a node and the values are the names of the labels and properties to + * remove. The values of each object can be either a single string, or an array of strings. + * ```javascript + * query.remove({ + * labels: { + * coupon: 'Active', + * }, + * properties: { + * customer: ['inactive', 'new'], + * }, + * }); + * // REMOVE coupon:Active, customer.inactive, customer.new + * ``` + * + * Both labels and properties objects are optional, but you must provide at least one of them for + * the query to be syntatically valid. + * ``` + * query.remove({ + * + * }); + * // Invalid query: + * // REMOVE + * ``` + * + * If you only need to remove labels *or* properties, you may find `removeProperties` or + * `removeLabels` more convenient. + */ + + + Builder.prototype.remove = function (properties) { + return this.continueChainClause(new Remove(properties)); + }; + /** + * Adds a [remove]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/remove/} + * clause to the query. + * + * Pass an object containing the list of properties to remove from a node. Each key in the + * object is the name of a node and the values are the names of the properties to remove. The + * values can be either a single string, or an array of strings. + * ```javascript + * query.remove({ + * customer: ['inactive', 'new'], + * coupon: 'available', + * }); + * // REMOVE customer.inactive, customer.new, coupon.available + * ``` + */ + + + Builder.prototype.removeProperties = function (properties) { + return this.continueChainClause(new Remove({ + properties: properties + })); + }; + /** + * Adds a [remove]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/remove/} + * clause to the query. + * + * Pass an object containing the list of labels to remove from a node. Each key in the + * object is the name of a node and the values are the names of the labels to remove. The + * values can be either a single string, or an array of strings. + * ```javascript + * query.remove({ + * customer: ['Inactive', 'New'], + * coupon: 'Available', + * }); + * // REMOVE customer:Inactive, customer:New, coupon:Available + * ``` + */ + + + Builder.prototype.removeLabels = function (labels) { + return this.continueChainClause(new Remove({ + labels: labels + })); + }; + /** + * Adds a [return]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/return} + * clause to the query. + * + * There are many different ways to pass arguments to `return` so each is + * documented in turn below. + * + * A single string: + * ```javascript + * query.return('people') + * // RETURN people + * ``` + * + * An array of strings to return multiple variables: + * ```javascript + * query.return([ 'people', 'pets' ]) + * // RETURN people, pets + * ``` + * + * A single object to rename variables: + * ```javascript + * query.return({ people: 'employees' }) + * // RETURN people AS employees + * ``` + * + * A single object with an array for each value: + * ```javascript + * query.return({ + * people: [ 'name', 'age' ], + * pets: [ 'name', 'breed' ], + * }) + * // RETURN people.name, people.age, pets.name, pets.breed + * ``` + * This gives you a shortcut to specifying many node properties. You can also + * rename each property by adding an object inside the array or by providing + * an object as the value: + * ```javascript + * query.return({ + * people: [{ name: 'personName' }, 'age' ], + * }) + * // RETURN people.name AS personName, people.age + * ``` + * or + * ```javascript + * query.return({ + * people: { + * name: 'personName', + * age: 'personAge', + * }, + * }) + * // RETURN people.name AS personName, people.age AS personAge + * ``` + * + * You can also pass an array of any of the above methods. + * + * The return method also accepts a `distinct` option which will cause a `RETURN DISTINCT` clause + * to be emitted instead. + * ```javascript + * query.return('people', { distinct: true }) + * // RETURN DISTINCT people + * ``` + */ + + + Builder.prototype.return = function (terms, options) { + return this.continueChainClause(new Return(terms, options)); + }; + /** + * Shorthand for `return(terms, { distinct: true }); + */ + + + Builder.prototype.returnDistinct = function (terms) { + return this.return(terms, { + distinct: true + }); + }; + /** + * Adds a [skip]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/skip} + * clause to the query. + * + * @param {string | number} amount + * @returns {Q} + */ + + + Builder.prototype.skip = function (amount) { + return this.continueChainClause(new Skip(amount)); + }; + /** + * Add a [union]{@link https://neo4j.com/docs/cypher-manual/current/clauses/union/} clause to the + * query. + * + * ```javascript + * query.matchNode('people', 'People') + * .return({ 'people.name': 'name' }) + * .union() + * .matchNode('departments', 'Department') + * .return({ 'departments.name': 'name' }); + * // MATCH (people:People) + * // RETURN people.name AS name + * // UNION + * // MATCH (departments:Department) + * // RETURN departments.name AS name + * ``` + */ + + + Builder.prototype.union = function (all) { + return this.continueChainClause(new Union(all)); + }; + /** + * Add a [union all]{@link https://neo4j.com/docs/cypher-manual/current/clauses/union/} clause to + * the query. Just shorthand for `union(true)`. + * + * ```javascript + * query.matchNode('people', 'People') + * .return({ 'people.name': 'name' }) + * .unionAll() + * .matchNode('departments', 'Department') + * .return({ 'departments.name': 'name' }); + * // MATCH (people:People) + * // RETURN people.name AS name + * // UNION ALL + * // MATCH (departments:Department) + * // RETURN departments.name AS name + * ``` + */ + + + Builder.prototype.unionAll = function () { + return this.continueChainClause(new Union(true)); + }; + /** + * Adds an [unwind]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/unwind} + * clause to the query. + * + * @param {any[]} list Any kind of array to unwind in the query + * @param {string} name Name of the variable to use in the unwinding + * @returns {Q} + */ + + + Builder.prototype.unwind = function (list, name) { + return this.continueChainClause(new Unwind(list, name)); + }; + /** + * Adds a [where]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/where} + * clause to the query. + * + * `where` is probably the most complex clause in this package because of the flexible ways to + * combine conditions. A handy rule of thumb is when you see an array it becomes an `OR` and when + * you see a dictionary, it becomes an `AND`. The many different ways of specifying your + * constraints are listed below. + * + * As a simple object, the comparison of each property is just `AND`ed together. + * ```javascript + * query.where({ + * name: 'Alan', + * age: 54, + * }) + * // WHERE name = 'Alan' AND age = 54 + * ``` + * + * You can wrap your constraints in a top level dictionary in which case the key of the outer + * dictionary will be considered the name of the node. + * ```javascript + * query.where({ + * person: { + * name: 'Alan', + * age: 54, + * }, + * }) + * // WHERE person.name = 'Alan' AND person.age = 54 + * ``` + * + * Using an array, you can generate `OR`ed conditions. + * ```javascript + * query.where([ + * { name: 'Alan' }, + * { age: 54 }, + * ]) + * // WHERE name = 'Alan' OR age = 54 + * ``` + * + * Arrays can be placed at many levels in the conditions. + * ```javascript + * query.where({ + * name: [ 'Alan', 'Steve', 'Bob' ], + * }) + * // WHERE name = 'Alan' OR name = 'Steve' OR name = 'Bob' + * + * query.where({ + * person: [ + * { name: 'Alan' }, + * { age: 54 }, + * ], + * }) + * // WHERE person.name = 'Alan' OR person.age = 54 + * + * query.where([ + * { employee: { name: 'Alan' } }, + * { department: { code: 765 } }, + * }) + * // WHERE employee.name = 'Alan' OR department.code = 765 + * ``` + * + * For more complex comparisons, you can use the comparator functions such as: + * ```javascript + * query.where({ + * age: greaterThan(30), + * }) + * // WHERE age > 30 + * ``` + * + * The full list of comparators currently supported are: + * - [between]{@link http://jamesfer.me/cypher-query-builder/globals.html#between} + * - [contains]{@link http://jamesfer.me/cypher-query-builder/globals.html#contains} + * - [endsWith]{@link http://jamesfer.me/cypher-query-builder/globals.html#endswith} + * - [equals]{@link http://jamesfer.me/cypher-query-builder/globals.html#equals} + * - [exists]{@link http://jamesfer.me/cypher-query-builder/globals.html#exists} + * - [greaterEqualTo]{@link http://jamesfer.me/cypher-query-builder/globals.html#greaterequalto} + * - [greaterThan]{@link http://jamesfer.me/cypher-query-builder/globals.html#greaterthan} + * - [hasLabel]{@link http://jamesfer.me/cypher-query-builder/globals.html#haslabel} + * - [inArray]{@link http://jamesfer.me/cypher-query-builder/globals.html#inarray} + * - [isNull]{@link http://jamesfer.me/cypher-query-builder/globals.html#isnull} + * - [lessEqualTo]{@link http://jamesfer.me/cypher-query-builder/globals.html#lessequalto} + * - [lessThan]{@link http://jamesfer.me/cypher-query-builder/globals.html#lessthan} + * - [regexp]{@link http://jamesfer.me/cypher-query-builder/globals.html#regexp} + * - [startsWith]{@link http://jamesfer.me/cypher-query-builder/globals.html#startswith} + * + * You can import the comparisons one at a time or all at once. + * ```javascript + * import { greaterThan, regexp } from 'cypher-query-builder'; + * // or + * import { comparisons } form 'cypher-query-builder'; + * ``` + * + * For convenience you can also pass a Javascript RegExp object as a value, + * which will then be converted into a string before it is passed to cypher. + * *However*, beware that the cypher regexp syntax is inherited from + * [java]{@link + * https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html}, + * and may have slight differences to the Javascript syntax. If you would + * prefer, you can use the `regexp` comparator and use strings instead of + * RegExp objects. For example, Javascript RegExp flags will not be + * preserved when sent to cypher. + * ```javascript + * query.where({ + * name: /[A-Z].*son/, + * }) + * // WHERE age =~ '[A-Z].*son' + * ``` + * + * All the binary operators including `xor` and `not` are available as well and can also be + * imported individually or all at once. + * ```javascript + * import { xor, and } from 'cypher-query-builder'; + * // or + * import { operators } form 'cypher-query-builder'; + * ``` + * + * The operators can be placed at any level of the query. + * ```javascript + * query.where({ + * age: xor([lessThan(12), greaterThan(65)]) + * }) + * // WHERE age < 12 XOR age > 65 + * ``` + * + * @param {AnyConditions} conditions + * @returns {Q} + */ + + + Builder.prototype.where = function (conditions) { + return this.continueChainClause(new Where(conditions)); + }; + /** + * Adds a [with]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/with} + * clause to the query. + * + * There are many different ways to pass arguments to `with` so each is + * documented in turn below. + * + * A single string: + * ```javascript + * query.with('people') + * // WITH people + * ``` + * + * An array of strings to return multiple variables: + * ```javascript + * query.with([ 'people', 'pets' ]) + * // WITH people, pets + * ``` + * + * A single object to rename variables: + * ```javascript + * query.with({ people: 'employees' }) + * // WITH people AS employees + * ``` + * + * A single object with an array for each value: + * ```javascript + * query.with({ + * people: [ 'name', 'age' ], + * pets: [ 'name', 'breed' ], + * }) + * // WITH people.name, people.age, pets.name, pets.breed + * ``` + * This gives you a shortcut to specifying many node properties. You can also + * rename each property by adding an object inside the array or by providing + * an object as the value: + * ```javascript + * query.with({ + * people: [{ name: 'personName' }, 'age' ], + * }) + * // WITH people.name AS personName, people.age + * ``` + * or + * ```javascript + * query.with({ + * people: { + * name: 'personName', + * age: 'personAge', + * }, + * }) + * // WITH people.name AS personName, people.age AS personAge + * ``` + * + * You can also pass an array of any of the above methods. + * + * @param {_.Many} terms + * @returns {Q} + */ + + + Builder.prototype.with = function (terms) { + return this.continueChainClause(new With(terms)); + }; + + return Builder; +}(SetBlock); + +var Transformer = +/** @class */ +function () { + function Transformer() {} + + Transformer.prototype.transformRecords = function (records) { + var _this = this; + + return map_1(records, function (rec) { + return _this.transformRecord(rec); + }); + }; + + Transformer.prototype.transformRecord = function (record) { + var _this = this; + + return mapValues_1(record.toObject(), function (node) { + return _this.transformValue(node); + }); + }; + + Transformer.prototype.transformValue = function (value) { + var _this = this; + + if (this.isPlainValue(value)) { + return value; + } + + if (isArray_1(value)) { + return map_1(value, function (v) { + return _this.transformValue(v); + }); + } + + if (lib.isInt(value)) { + return this.convertInteger(value); + } + + if (this.isNode(value)) { + return this.transformNode(value); + } + + if (this.isRelation(value)) { + return this.transformRelation(value); + } + + if (typeof value === 'object') { + return mapValues_1(value, function (v) { + return _this.transformValue(v); + }); + } + + return null; + }; + + Transformer.prototype.isPlainValue = function (value) { + var type = typeof value; + return value == null || type === 'string' || type === 'boolean' || type === 'number'; + }; + + Transformer.prototype.isNode = function (node) { + return node !== null && typeof node === 'object' && !isArray_1(node) && node.identity && node.labels && node.properties; + }; + + Transformer.prototype.transformNode = function (node) { + return { + identity: lib.integer.toString(node.identity), + labels: node.labels, + properties: mapValues_1(node.properties, this.transformValue.bind(this)) + }; + }; + + Transformer.prototype.isRelation = function (rel) { + return rel.identity && rel.type && rel.properties && rel.start && rel.end; + }; + + Transformer.prototype.transformRelation = function (rel) { + return { + identity: lib.integer.toString(rel.identity), + start: lib.integer.toString(rel.start), + end: lib.integer.toString(rel.end), + label: rel.type, + properties: mapValues_1(rel.properties, this.transformValue.bind(this)) + }; + }; + + Transformer.prototype.convertInteger = function (num) { + if (lib.integer.inSafeRange(num)) { + return lib.integer.toNumber(num); + } + + return lib.integer.toString(num); + }; + + return Transformer; +}(); + +var ClauseCollection = +/** @class */ +function (_super) { + __extends(ClauseCollection, _super); + + function ClauseCollection() { + var _this = _super !== null && _super.apply(this, arguments) || this; + + _this.clauses = []; + return _this; + } + /** + * Returns all clauses in this collection. + * @returns {Clause[]} + */ + + + ClauseCollection.prototype.getClauses = function () { + return this.clauses; + }; + /** + * Adds a clause to the child list. + * @param {Clause} clause + */ + + + ClauseCollection.prototype.addClause = function (clause) { + clause.useParameterBag(this.parameterBag); + this.clauses.push(clause); + }; + /** + * @inheritDoc + */ + + + ClauseCollection.prototype.build = function () { + return map_1(this.clauses, function (s) { + return s.build(); + }).join('\n') + ";"; + }; + + return ClauseCollection; +}(Clause); + +var Query = +/** @class */ +function (_super) { + __extends(Query, _super); + /** + * Creates a new query with a given connection. + * + * @param {Connection} connection + */ + + + function Query(connection) { + if (connection === void 0) { + connection = null; + } + + var _this = _super.call(this) || this; + + _this.connection = connection; + _this.clauses = new ClauseCollection(); + return _this; + } + + Query.prototype.continueChainClause = function (clause) { + return this.addClause(clause); + }; + /** + * Runs this query on its connection. If this query was created by calling a + * chainable method of a connection, then its connection was automatically + * set. + * + * Returns a promise that resolves to an array of records. Each key of the + * record is the name of a variable that you specified in your `RETURN` + * clause. + * Eg: + * ```typescript + * connection.match([ + * node('steve', { name: 'Steve' }), + * relation('out', [ 'FriendsWith' ]), + * node('friends'), + * ]) + * .return([ 'steve', 'friends' ]) + * .run(); + * ``` + * + * Would result in the value: + * ``` + * [ + * { + * steve: { ... } // steve node, + * friends: { ... } // first friend, + * }, + * { + * steve: { ... } // steve node, + * friends: { ... } // second friend, + * }, + * { + * steve: { ... } // steve node, + * friends: { ... } // third friend, + * }, + * ] + * ``` + * + * Notice how the steve record is returned for each row, this is how cypher + * works. If you use lodash you can extract all of Steve's friends from the + * results like using `_.map(results, 'friends')`. If you don't, you can use + * ES2015/ES6: `results.map(record => record.friends)`. + * + * If you use typescript you can use the type parameter to hint at the type of + * the return value which is `Dictionary[]`. + * + * Throws an exception if this query does not have a connection or has no + * clauses. + * + * @returns {Promise[]>} + */ + + + Query.prototype.run = function () { + return __awaiter(this, void 0, Promise, function () { + return __generator(this, function (_a) { + if (!this.connection) { + throw new Error('Cannot run query; no connection object available.'); + } + + return [2 + /*return*/ + , this.connection.run(this)]; + }); + }); + }; + /** + * Runs this query on its connection. If this query was created by calling a + * chainable method of a connection, then its connection was automatically + * set. + * + * Returns an RxJS observable that emits each record as it is received from the + * database. This is the most efficient way of working with very large + * datasets. Each record is an object where each key is the name of a variable + * that you specified in your return clause. + * + * Eg: + * ```typescript + * const result$ = connection.match([ + * node('steve', { name: 'Steve' }), + * relation('out', [ 'FriendsWith' ]), + * node('friends'), + * ]) + * .return([ 'steve', 'friends' ]) + * .stream(); + * + * // Emits + * // { + * // steve: { ... } // steve node, + * // friends: { ... } // first friend, + * // }, + * // Then emits + * // { + * // steve: { ... } // steve node, + * // friends: { ... } // first friend, + * // }, + * // And so on + * ``` + * + * Notice how the steve record is returned for each row, this is how cypher + * works. You can extract all of steve's friends from the query by using RxJS + * operators: + * ``` + * const friends$ = results$.map(row => row.friends); + * ``` + * + * If you use typescript you can use the type parameter to hint at the type of + * the return value which is `Observable>`. + * + * Throws an exception if this query does not have a connection or has no + * clauses. + */ + + + Query.prototype.stream = function () { + if (!this.connection) { + return new Observable(function (subscriber) { + subscriber.error(new Error('Cannot run query; no connection object available.')); + }); + } + + return this.connection.stream(this); + }; + /** + * Runs the current query on its connection and returns the first result. + * If the query was created by calling a chainable method of a connection, + * the query's connection was automatically set. + * + * If 0 results were returned from the database, returns `undefined`. + * + * Returns a promise that resolves to a single record. Each key of the + * record is the name of a variable that you specified in your `RETURN` + * clause. + * + * If you use typescript you can use the type parameter to hint at the type of + * the return value which is `Dictionary`. Note that this function returns + * `undefined` if the result set was empty. + */ + + + Query.prototype.first = function () { + return this.run().then(function (results) { + return results && results.length > 0 ? results[0] : undefined; + }); + }; // Clause proxied methods + + /** + * Returns the query as a string with parameter variables. + * + * Eg: + * ```typescript + * connection.match([ + * node('steve', { name: 'Steve' }), + * relation('out', [ 'FriendsWith' ]), + * node('friends'), + * ]) + * .return([ 'steve', 'friends' ]) + * .build(); + * + * // MATCH (steve { name: $name })-[:FriendsWith]->(friends) + * // RETURN steve, friends + * ``` + * + * @returns {string} + */ + + + Query.prototype.build = function () { + return this.clauses.build(); + }; + /** + * Synonym for `build()`. + * @returns {string} + */ + + + Query.prototype.toString = function () { + return this.clauses.toString(); + }; + /** + * Returns an object that includes both the query and the params ready to be + * passed to the neo4j driver. + */ + + + Query.prototype.buildQueryObject = function () { + return this.clauses.buildQueryObject(); + }; + /** + * Like `build`, but will insert the values of the parameters into the string + * so queries are easier to debug. __Note: this should only ever be used for + * debugging__. + * + * ```typescript + * connection.match([ + * node('steve', { name: 'Steve' }), + * relation('out', [ 'FriendsWith' ]), + * node('friends'), + * ]) + * .return([ 'steve', 'friends' ]) + * .build(); + * + * // MATCH (steve { name: 'Steve' })-[:FriendsWith]->(friends) + * // RETURN steve, friends + * ``` + * + * @returns {string} + */ + + + Query.prototype.interpolate = function () { + return this.clauses.interpolate(); + }; + /** + * Returns an array of all the clauses in this query. + * @returns {Clause[]} + */ + + + Query.prototype.getClauses = function () { + return this.clauses.getClauses(); + }; + /** + * Adds a new clause to the query. You probably won't ever need to call this + * directly, but there is nothing stopping you. + * + * @param {Clause} clause + * @returns {this} + */ + + + Query.prototype.addClause = function (clause) { + this.clauses.addClause(clause); + return this; + }; + + return Query; +}(Builder); + +var connections = []; // Closes all open connections + +nodeCleanup(function () { + connections.forEach(function (con) { + return con.close(); + }); + connections = []; +}); + +function isCredentials(credentials) { + return 'username' in credentials && 'password' in credentials; +} // We have to correct the type of lodash's isFunction method because it doesn't correctly narrow +// union types such as the options parameter passed to the connection constructor. + + +var isTrueFunction = isFunction_1; // tslint:disable max-line-length + +/** + * The Connection class lets you access the Neo4j server and run queries against it. Under the hood, + * the Connection class uses the official Neo4j Nodejs driver which manages connection pooling on a + * [session basis]{@link https://neo4j.com/docs/api/javascript-driver/current/class/src/v1/driver.js~Driver.html#instance-method-session}. + * It should be enough to have a single Connection instance per database per application. + * + * To create the connection, simply call the + * [constructor]{@link https://jamesfer.me/cypher-query-builder/classes/connection.html#constructor} + * and pass in the database url, username and password. + * ``` + * const db = new Connection('bolt://localhost', { + * username: 'neo4j', + * password: 'password', + * }) + * ``` + * + * To use the connection, just start calling any of the clause methods such as `match`, `create` or + * `matchNode` etc. They automatically create a {@link Query} object that you can then chain other + * methods off of. + * ``` + * db.matchNode('people', 'Person') + * .where({ 'people.age': greaterThan(18) }) + * .return('people') + * .run() + * ``` + * + * You can also pass a query to the + * [run]{@link https://jamesfer.me/cypher-query-builder/classes/connection.html#run} method, + * however, this is probably much less convenient. + * ``` + * db.run( + * new Query().matchNode('people', 'Person') + * .where({ 'people.age': greaterThan(18) }) + * .return('people') + * .run() + * ); + * ``` + * + * Once you've finished with the connection you should close the connection. + * ``` + * db.close() + * ``` + * + * The library will attempt to clean up all connections when the process exits, but it is better to + * be explicit. + */ +// tslint:enable max-line-length + +/** @class */ +(function (_super) { + __extends(Connection, _super); + /** + * Creates a new connection to the database. + * + * @param url Url of the database such as `'bolt://localhost'` + * @param auth Auth can either be an object in the form `{ username: ..., password: ... }`, or a + * Neo4j AuthToken object which contains the `scheme`, `principal` and `credentials` properties + * for more advanced authentication scenarios. The AuthToken object is what is passed directly to + * the neo4j javascript driver so checkout their docs for more information on it. + * @param options Additional configuration options. If you provide a function instead of an + * object, it will be used as the driver constructor. While passing a driver constructor function + * here is not deprecated, it is the legacy way of setting it and you should prefer to pass an + * options object with the `driverConstructor` parameter. + * @param options.driverConstructor An optional driver constructor to use for + * this connection. Defaults to the official Neo4j driver. The constructor is + * given the url you pass to this constructor and an auth token that is + * generated from calling [`neo4j.auth.basic`]{@link + * https://neo4j.com/docs/api/javascript-driver/current#usage-examples}. + * @param options.driverConfig Neo4j options that are passed directly to the underlying driver. + */ + + + function Connection(url, auth$1, options) { + if (options === void 0) { + options = lib.driver; + } + + var _this = _super.call(this) || this; + + _this.url = url; + _this.transformer = new Transformer(); + _this.auth = isCredentials(auth$1) ? lib.auth.basic(auth$1.username, auth$1.password) : auth$1; + var driverConstructor = isTrueFunction(options) ? options : options.driverConstructor ? options.driverConstructor : lib.driver; + var driverConfig = isTrueFunction(options) || !options.driverConfig ? {} : options.driverConfig; + _this.options = { + driverConstructor: driverConstructor, + driverConfig: driverConfig + }; + _this.driver = driverConstructor(_this.url, _this.auth, _this.options.driverConfig); + _this.open = true; + connections.push(_this); + return _this; + } + /** + * Closes this connection if it is open. Closed connections cannot be + * reopened. + */ + + + Connection.prototype.close = function () { + return __awaiter(this, void 0, Promise, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + if (!this.open) return [3 + /*break*/ + , 2]; + return [4 + /*yield*/ + , this.driver.close()]; + + case 1: + _a.sent(); + + this.open = false; + _a.label = 2; + + case 2: + return [2 + /*return*/ + ]; + } + }); + }); + }; + /** + * Opens and returns a session. You should never need to use this directly. + * Your probably better off with `run` instead. + */ + + + Connection.prototype.session = function () { + if (this.open) { + return this.driver.session(); + } + + return null; + }; + /** + * Returns a new query that uses this connection. The methods such as `match` + * or `create` are probably more useful to you as they automatically create a + * new chainable query for you. + * @return {Query} + */ + + + Connection.prototype.query = function () { + return new Query(this); + }; + + Connection.prototype.continueChainClause = function (clause) { + return this.query().addClause(clause); + }; + /** + * Runs the provided query on this connection, regardless of which connection + * the query was created from. Each query is run on it's own session. + * + * Run returns a promise that resolves to an array of records. Each key of the + * record is the name of a variable that you specified in your `RETURN` + * clause. + * Eg: + * ```typescript + * connection.match([ + * node('steve', { name: 'Steve' }), + * relation('out', [ 'FriendsWith' ]), + * node('friends'), + * ]) + * .return([ 'steve', 'friends' ]) + * .run(); + * ``` + * + * Would result in the value: + * ``` + * [ + * { + * steve: { ... } // steve node, + * friends: { ... } // first friend, + * }, + * { + * steve: { ... } // steve node, + * friends: { ... } // second friend, + * }, + * { + * steve: { ... } // steve node, + * friends: { ... } // third friend, + * }, + * ] + * ``` + * + * Notice how the steve record is returned for each row, this is how cypher + * works. If you use lodash you can extract all of Steve's friends from the + * results like using `_.map(results, 'friends')`. If you don't, you can use + * ES2015/ES6: `results.map(record => record.friends)`. + * + * If you use typescript you can use the type parameter to hint at the type of + * the return value which is `Dictionary[]`. + * + * Throws an exception if this connection is not open or there are no clauses + * in the query. + * + * @param {Query} query + * @returns {Promise[]>} + */ + + + Connection.prototype.run = function (query) { + return __awaiter(this, void 0, Promise, function () { + var session, queryObj; + + var _this = this; + + return __generator(this, function (_a) { + if (!this.open) { + throw new Error('Cannot run query; connection is not open.'); + } + + if (query.getClauses().length === 0) { + throw new Error('Cannot run query: no clauses attached to the query.'); + } + + session = this.session(); + + if (!session) { + throw new Error('Cannot run query: connection is not open.'); + } + + queryObj = query.buildQueryObject(); + return [2 + /*return*/ + , session.run(queryObj.query, queryObj.params).then(function (_a) { + var records = _a.records; + return __awaiter(_this, void 0, void 0, function () { + return __generator(this, function (_b) { + switch (_b.label) { + case 0: + return [4 + /*yield*/ + , session.close()]; + + case 1: + _b.sent(); + + return [2 + /*return*/ + , this.transformer.transformRecords(records)]; + } + }); + }); + }, function (error) { + return __awaiter(_this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 + /*yield*/ + , session.close()]; + + case 1: + _a.sent(); + + throw error; + } + }); + }); + })]; + }); + }); + }; + /** + * Runs the provided query on this connection, regardless of which connection + * the query was created from. Each query is run on it's own session. + * + * Returns an RxJS observable that emits each record as it is received from the + * database. This is the most efficient way of working with very large + * datasets. Each record is an object where each key is the name of a variable + * that you specified in your return clause. + * + * Eg: + * ```typescript + * const results$ = connection.match([ + * node('steve', { name: 'Steve' }), + * relation('out', [ 'FriendsWith' ]), + * node('friends'), + * ]) + * .return([ 'steve', 'friends' ]) + * .stream(); + * + * // Emits + * // { + * // steve: { ... } // steve node, + * // friends: { ... } // first friend, + * // }, + * // Then emits + * // { + * // steve: { ... } // steve node, + * // friends: { ... } // first friend, + * // }, + * // And so on + * ``` + * + * Notice how the steve record is returned for each row, this is how cypher + * works. You can extract all of steve's friends from the query by using + * operators: + * ``` + * const friends$ = results$.map(row => row.friends); + * ``` + * + * If you use typescript you can use the type parameter to hint at the type of + * the return value which is `Dictionary`. + * + * Throws an exception if this connection is not open or there are no clauses + * in the query. + * + * The query is run when you call stream so you should subscribe to the results + * immediately to prevent missing any data. + * + * Due to the way the Neo4j javascript driver works, once you call stream there + * is no way to stop the query until it is complete. Even if you unsubscribe from + * the observable, all the remaining rows will still be parsed by the driver but + * then immediately discarded. + * ```typescript + * const results$ = connection.matchNode('records') + * .return('records') + * .limit(1000) // 1000 records will be loaded and parsed from the database + * .stream() + * .take(10) // even though you only take the first 10 + * .subscribe(record => {}); + * ``` + * In practice this should never happen unless you're doing some strange things. + */ + + + Connection.prototype.stream = function (query) { + var _this = this; + + return new Observable(function (subscriber) { + if (!_this.open) { + subscriber.error(new Error('Cannot run query: connection is not open.')); + return; + } + + if (query.getClauses().length === 0) { + subscriber.error(new Error('Cannot run query: no clauses attached to the query.')); + return; + } + + var session = _this.session(); + + if (!session) { + subscriber.error(new Error('Cannot run query: connection is not open.')); + return; + } // Run the query + + + var queryObj = query.buildQueryObject(); + var result = session.run(queryObj.query, queryObj.params); // Subscribe to the result and clean up the session + // Note: Neo4j observables use a different subscribe syntax to RxJS observables + + result.subscribe({ + onNext: function (record) { + if (!subscriber.closed) { + subscriber.next(_this.transformer.transformRecord(record)); + } + }, + onError: function (error) { + return __awaiter(_this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 + /*yield*/ + , session.close()]; + + case 1: + _a.sent(); + + if (!subscriber.closed) { + subscriber.error(error); + } + + return [2 + /*return*/ + ]; + } + }); + }); + }, + onCompleted: function () { + return __awaiter(_this, void 0, void 0, function () { + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + return [4 + /*yield*/ + , session.close()]; + + case 1: + _a.sent(); + + if (!subscriber.closed) { + subscriber.complete(); + } + + return [2 + /*return*/ + ]; + } + }); + }); + } + }); + }); + }; + + return Connection; +})(Builder); + +// Ensures synchronous execution of queries to prevent problems with race conditions on Neo4j. +// Problem: Is it thread-safe? Probably right, because js is single-threaded? +class SyncQueue { + constructor(toBind) { + this.callbackQueue = []; + this.activeCallback = null; + this.toBind = toBind; + } + async execute(callback, ...data) { + this.callbackQueue.push([callback, data]); + if (this.callbackQueue.length === 1 && this.activeCallback === null) { + // On empty queue, make active and assume responsibility of handling the queue. + while (this.callbackQueue.length > 0) { + const nextEvent = this.callbackQueue.shift(); + this.activeCallback = nextEvent[0]; + console.log('starting callback'); + await this.activeCallback.call(this.toBind, ...nextEvent[1]); + console.log('ending callback'); + } + this.activeCallback = null; + console.log('exiting execute'); + } + } +} + +const CAT_DANGLING = 'dangling'; +const CORE_STORE_ID = 'core'; +class VizId { + constructor(id, storeId) { + this.id = id; + this.storeId = storeId; + } + toString() { + return `${this.storeId}:${this.id}`; + } + toId() { + return this.toString(); + } + static fromId(id) { + const split = id.split(':'); + const storeId = split[0]; + const _id = split.slice(1).join(':'); + return new VizId(_id, storeId); + } + static fromNode(node) { + return VizId.fromId(node.id()); + } + static fromNodes(nodes) { + return nodes.map((n) => VizId.fromNode(n)); + } + static fromFile(file) { + return new VizId(file.name, 'core'); + } + static toId(id, storeId) { + return new VizId(id, storeId).toId(); + } +} +const _parseTags = function (tags) { + return [].concat(...tags + .map((tag) => { + tag = tag.slice(1); + const hSplit = tag.split('/'); + const tags = []; + for (const i in hSplit) { + const hTag = hSplit.slice(0, parseInt(i) + 1).join('-'); + tags.push(`tag-${hTag}`); + } + return tags; + })); +}; +const getClasses = function (file, metadataCache) { + if (file) { + const classes = []; + if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'svg', 'tiff'].contains(file.extension)) { + classes.push('image'); + } + else if (['mp3', 'webm', 'wav', 'm4a', 'ogg', '3gp', 'flac'].contains(file.extension)) { + classes.push('audio'); + } + else if (['mp4', 'webm', 'ogv'].contains(file.extension)) { + classes.push('video'); + } + else if (file.extension === 'pdf') { + classes.push('pdf'); + } + // This is replaced by the 'path' data attribute. + // if (!(file.parent.name === '/' || file.parent.name === '')) { + // classes.push(`folder-${file.parent.name + // .replace(' ', '_')}`); + // } else { + // classes.push('root'); + // } + if (file.extension === 'md') { + classes.push('note'); + const cache = metadataCache.getFileCache(file); + if (cache?.frontmatter) { + if ('image' in cache.frontmatter) { + classes.push('image'); + } + if ('tags' in cache.frontmatter) { + const tags = obsidian.parseFrontMatterTags(cache.frontmatter); + if (tags) { + classes.push(..._parseTags(tags)); + } + } + if ('cssclass' in cache.frontmatter) { + const clazzes = obsidian.parseFrontMatterStringArray(cache.frontmatter, 'cssclass'); + if (clazzes) { + classes.push(...clazzes); + } + } + } + if (cache?.tags) { + classes.push(..._parseTags(cache.tags.map((t) => t.tag))); + } + } + else { + classes.push('file'); + } + return classes; + } + return [CAT_DANGLING]; +}; +const nodeFromFile = async function (file, plugin) { + const cache = plugin.app.metadataCache.getFileCache(file); + const name = file.extension === 'md' ? file.basename : file.name; + const classes = getClasses(file, plugin.app.metadataCache).join(' '); + const data = { + id: VizId.toId(file.name, CORE_STORE_ID), + name: name, + path: file.path, + }; + if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'svg', 'tiff'].contains(file.extension)) { + try { + // @ts-ignore + data['resource_url'] = `http://localhost:${plugin.settings.imgServerPort}/${encodeURI(file.path)}`; + } + catch { } + } + if (file.extension == 'md') { + data['content'] = await plugin.app.vault.cachedRead(file); + } + const frontmatter = cache?.frontmatter; + if (frontmatter) { + Object.keys(frontmatter).forEach((k) => { + if (!(k === 'position')) { + if (k === 'image') { + const imageField = frontmatter[k]; + try { + // Check if url. throws error otherwise + new URL(imageField); + data[k] = imageField; + } + catch { + try { + // @ts-ignore + data[k] = `http://localhost:${plugin.settings.imgServerPort}/${encodeURI(imageField)}`; + } + catch { } + } + } + else { + data[k] = frontmatter[k]; + } + } + }); + } + return { + group: 'nodes', + data: data, + classes: classes, + }; +}; +const nodeDangling = function (path) { + return { + group: 'nodes', + data: { + id: VizId.toId(path, CORE_STORE_ID), + name: path, + }, + classes: 'dangling', + }; +}; + +const CAT_DANGLING$1 = 'SMD_dangling'; +const nameRegex = '[^\\W\\d]\\w*'; +// Match around [[ and ]], and ensure content isn't a wikilnk closure +// This doesn't explicitly parse aliases. +const wikilinkRegex = '\\[\\[([^\\]\\r\\n]+?)\\]\\]'; +class QueryMetadata { + constructor() { + this.nodeIndex = 0; + this.nodeVars = {}; + } + nextNodeVar(name, prefix = 'n') { + const varName = `${prefix}${this.nodeIndex.toString()}`; + this.nodeVars[name] = varName; + this.nodeIndex += 1; + return varName; + } + values() { + return Object.keys(this.nodeVars).map((k) => this.nodeVars[k]); + } +} +class Neo4jStream extends obsidian.Component { + constructor(plugin) { + super(); + this.plugin = plugin; + this.workspace = plugin.app.workspace; + this.vault = plugin.app.vault; + this.settings = plugin.settings; + this.metadataCache = plugin.app.metadataCache; + this.eventQueue = new SyncQueue(this); + } + async start() { + if (this.driver) { + await this.driver.close(); + } + this.driver = neo4j.driver('neo4j://localhost', neo4j.auth.basic('neo4j', this.settings.password), { + maxTransactionRetryTime: 30000, + }); + const connection = this.session(); + if (this.settings.debug) { + console.log('Removing existing data'); + } + // await this.connection.run("MATCH (n) RETURN n LIMIT 10").then(res => { + // console.log(res); + // }); + await this.executeQueries([new Query() + .matchNode('n', { SMD_vault: this.vault.getName() }) + .detachDelete('n')]); + console.log('Iterating md files'); + // let noteQueries: Query[] = []; + const markdownFiles = this.vault.getMarkdownFiles(); + let query = new Query(); + const queryMetadata = new QueryMetadata(); + for (const file of markdownFiles) { + queryMetadata.nextNodeVar(file.basename); + query = await this.queryCreateNote(file, query, queryMetadata); + } + for (const file of markdownFiles) { + await this.queryCreateRels(file, query, queryMetadata); + } + console.log('Pushing to Neo4j'); + await this.executeQueries([query], connection); + // TODO: Define schema/indexes + new obsidian.Notice('Neo4j stream online!'); + this.plugin.statusBar.setText('Neo4j stream online'); + await connection.close(); + } + session() { + return this.driver.session(); + } + async createNode(file, name) { + let nodeDef = null; + if (file) { + nodeDef = await nodeFromFile(file, this.plugin); + } + else { + nodeDef = nodeDangling(name); + } + nodeDef.data.vault = this.vault.getName(); + nodeDef.data.obsidian_url = `obsidian://open?vault=${encodeURIComponent(this.vault.getName())}&file=${encodeURIComponent(nodeDef.data.name)}`; + // @ts-ignore + const labels = nodeDef.classes.replaceAll('-', '_').split(' '); + return { + labels: labels, + properties: nodeDef.data, + }; + } + runQuery(query, session = null) { + let newSess = false; + if (session === null) { + newSess = true; + session = this.driver.session(); + } + const queryO = query.buildQueryObject(); + if (this.settings.debug) { + console.log(queryO); + } + const q = session.run(queryO.query, queryO.params); + if (newSess) { + q.subscribe({ + async onCompleted(summary) { + await session.close(); + }, + }); + } + return q; + } + async executeQueries(queries, session = null) { + for (const query of queries) { + // Note: The await here is important, as a connection cannot run multiple transactions simultaneously. + await this.runQuery(query, session).then((value) => { + if (this.settings.debug) { + console.log(value); + } + }).catch((reason) => { + console.log('Query failed'); + console.log(query.buildQueryObject()); + console.log(reason); + }); + } + } + node(varName, name) { + return node$1(varName, { name: name, vault: this.vault.getName() }); + } + async queryUpdateNote(file, query, queryMetadata) { + return this.queryCreateOrUpdateNote(file, query, queryMetadata, true); + } + async queryCreateNote(file, query, queryMetadata) { + return this.queryCreateOrUpdateNote(file, query, queryMetadata, false); + } + async queryCreateOrUpdateNote(file, query, queryMetadata, update) { + const nodeDef = await this.createNode(file, file.name); + if (nodeDef) { + const nodeVar = queryMetadata.nodeVars[file.basename]; + if (update) { + return query.set({ + labels: { + [nodeVar]: nodeDef.labels, + }, + values: { + [nodeVar]: nodeDef.properties, + }, + }, { + merge: false, + }); + } + else { + return query.createNode(nodeVar, nodeDef.labels, nodeDef.properties); + } + } + console.log('File without metadata'); + console.log(file); + return null; + } + regexEscape(str) { + return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); + } + parseTypedLink(link, line) { + // TODO: This is something specific I use, but shouldn't keep being in this repo. + const regexPublishedIn = new RegExp(`^${this.regexEscape(this.settings.typedLinkPrefix)} (publishedIn) (\\d\\d\\d\\d) (${wikilinkRegex},? *)+$`); + const matchPI = regexPublishedIn.exec(line); + if (!(matchPI === null)) { + return { + type: 'publishedIn', + isInline: false, + properties: { + year: matchPI[2], + context: '', + type: 'publishedIn', + }, + class: 'publishedIn', + }; + } + // Intuition: Start with the typed link prefix. Then a neo4j name (nameRegex). + // Then one or more of the wikilink group: wikilink regex separated by optional comma and multiple spaces + const regex = new RegExp(`^${this.regexEscape(this.settings.typedLinkPrefix)} (${nameRegex}) (${wikilinkRegex},? *)+$`); + const match = regex.exec(line); + if (!(match === null)) { + return { + type: match[1], + isInline: false, + properties: { + context: '', + type: match[1], + }, + class: match[1], + }; + } + return null; + } + async queryCreateRels(file, query, queryMetadata, merge = false) { + const metadata = this.metadataCache.getFileCache(file); + const content = (await this.vault.cachedRead(file)).split('\n'); + const srcVar = queryMetadata.nodeVars[file.basename]; + if (metadata) { + const links = metadata.links; + if (links === undefined) { + return query; + } + for (const link of links) { + let baseName = obsidian.getLinkpath(link.link); // + // Returns NULL for dangling notes! + const trgtFile = this.metadataCache.getFirstLinkpathDest(baseName, file.path); + if (trgtFile) { + // This is an existing object. + baseName = trgtFile.basename; + } + let trgtVar; + if (baseName in queryMetadata.nodeVars) { + trgtVar = queryMetadata.nodeVars[baseName]; + } + else if (trgtFile && merge) { + // When merging, there's likely no var created for this note yet. + trgtVar = queryMetadata.nextNodeVar(baseName); + query = query.match(this.node(trgtVar, baseName)); + } + else { + // This node hasn't been seen before, so we need to create it. + // Creates dangling nodes if untyped, otherwise creates attachment nodes + trgtVar = queryMetadata.nextNodeVar(baseName); + const nodeDef = await this.createNode(trgtFile, baseName); + if (merge) { + query = query.merge(node$1(trgtVar, nodeDef.labels, nodeDef.properties)); + } + else { + query = query.createNode(trgtVar, nodeDef.labels, nodeDef.properties); + } + } + const line = content[link.position.start.line]; + let typedLink = this.parseTypedLink(link, line); + if (typedLink === null) { + typedLink = { + class: 'inline', + isInline: true, + properties: { + context: line, + type: '', + }, + }; + } + query = query.create([ + node$1(srcVar), + relation('out', [typedLink.class], typedLink.properties), + node$1(trgtVar) + ]); + if (merge) { + query.with(queryMetadata.values()); + } + } + return query; + } + console.log('File without metadata'); + console.log(file); + return null; + } + async metadataCacheOnChanged(file) { + // It's always called after the respective other events. + // Note: This is NOT called on rename, unless there's a reflexive link to itself. + // When a file is created, this is fired with an empty filecache. We synchronize the event firing, + // so we let the create callback handle the creation of the node. + console.log('changed metadata'); + console.log(file); + const session = this.session(); + if (file instanceof obsidian.TFile) { + const name = file.basename; + const queryMetadata = new QueryMetadata(); + const nodeVar = 'n0'; + // Find all labels on node + const result = await this.runQuery(new Query().match(this.node(nodeVar, name)).return(nodeVar), session); + const oldLabels = result.records[0].get(0).labels; + if (oldLabels.length > 0) { + console.log(oldLabels); + // Remove all labels on node + await this.runQuery(new Query().match(this.node(nodeVar, name)) + // @ts-ignore + .removeLabels({ n0: oldLabels }), session); + } + queryMetadata.nodeIndex = 1; + queryMetadata.nodeVars[name] = nodeVar; + let query = new Query().match(this.node(nodeVar, name)); + // Update node with new info + query = await this.queryUpdateNote(file, query, queryMetadata); + await this.executeQueries([query], session); + // Delete all outgoing edges: + const dRelQuery = new Query().match([ + this.node(nodeVar, name), + relation('out', 'r'), node$1('plc') + ]) + .delete('r'); + await this.executeQueries([dRelQuery]); + // Recreate relations, taking into account any changes + const relQuery = await this.queryCreateRels(file, new Query().match(this.node(nodeVar, name)), queryMetadata, true); + await this.executeQueries([relQuery.return(nodeVar)], session); + } + await session.close(); + } + async vaultOnRename(file, oldPath) { + // This is called BEFORE metadataCache vault change. + // So if we just rename the neo4j node, it should be fine when rebuilding relations. But rebuilding relations + // should happen before the rename event is resolved... Hopefully it works async + console.log('onRename'); + if (file instanceof obsidian.TFile) { + const oldName = path.basename(oldPath, '.md'); + console.log(oldName); + const query = new Query().match(this.node('n', oldName)) + .setValues({ n: { name: file.basename } }, true); + await this.executeQueries([query]); + } + this.lastFileEvent = 'rename'; + } + async vaultOnModify(file) { + // Called BEFORE metadataCache changed event. + // At this point, the metadataCache HASN'T been updated yet! + // It shouldn't be needed to do anything related with relation/tag updating here. + // At most, we could update the content property of the node. + this.lastFileEvent = 'modify'; + console.log('onModify'); + } + async vaultOnDelete(file) { + // After deleting, no metadatacache changed event is fired. + // Note: MetadataCache event isn't called either for incoming edges + this.lastFileEvent = 'delete'; + console.log('onDelete'); + const session = this.session(); + if (file instanceof obsidian.TFile) { + const name = file.basename; + const result = await this.runQuery(new Query().match([ + this.node('n', name), + relation('in'), + node$1('m') + ]).return('n'), session); + console.log(result); + if (result.records.length === 0) { + // If there are no incoming links, detach delete the node + await this.executeQueries([ + new Query().match(this.node('n', name)) + .detachDelete('n') + ], session); + } + else { + // If there are any incoming links, change labels to dangling and empty properties + const result = await this.runQuery(new Query() + .match(this.node('n', name)).return('n'), session); + // return query.setValues({}).removeLabels(dict); + let query = new Query().match(this.node('n', name)); + const oldLabels = result.records[0].get(0).labels; + if (oldLabels.length > 0) { + query = query.removeLabels({ n: oldLabels }); + } + query = query.setLabels({ n: CAT_DANGLING$1 }) + .setValues({ + SMD_vault: this.vault.getName(), + name: name, + }, false); + await this.executeQueries([query], session); + } + } + await session.close(); + } + async vaultOnCreate(file) { + // This is called BEFORE metadataCache vault change. + // Create the node as a blank state, then fill in later with on metadatacache changed etc. + // Note: it's possible the node already exists as a dangling node. In that case, just do nothing + // and let the metadatacache event handle it + this.lastFileEvent = 'create'; + console.log('onCreate'); + const session = this.session(); + console.log('sess created'); + if (file instanceof obsidian.TFile) { + const name = file.basename; + const result = await this.runQuery(new Query().match(this.node('n', name)) + .return('n'), session); + console.log(result); + if (result.records.length == 0) { + // if not exists: + await this.executeQueries([new Query().create(this.node('n', name))], session); + } + } + } + async stop() { + await this.driver.close(); + } +} + +const DefaultNeo4jStreamSettings = { + password: '', + typedLinkPrefix: '-', + neo4jServerPort: 7687, + server: 'localhost', + indexContent: true, + debug: false, +}; +class Neo4jStreamSettingsTab extends obsidian.PluginSettingTab { + constructor(app, plugin) { + super(app, plugin); + this.plugin = plugin; + } + display() { + const { containerEl } = this; + containerEl.empty(); + containerEl.createEl('h3'); + containerEl.createEl('h3', { text: 'Neo4j Stream' }); + const doc_link = document.createElement('a'); + doc_link.href = 'https://juggl.io'; + doc_link.target = '_blank'; + doc_link.innerHTML = 'the documentation'; + const discord_link = document.createElement('a'); + discord_link.href = 'https://discord.gg/sAmSGpaPgM'; + discord_link.target = '_blank'; + discord_link.innerHTML = 'the Discord server'; + const introPar = document.createElement('p'); + introPar.innerHTML = + 'Check out ' + doc_link.outerHTML + ' for documentation on how to use the plugin.
' + + 'Join ' + discord_link.outerHTML + ' for help, nice discussion and insight into development.'; + containerEl.appendChild(introPar); + new obsidian.Setting(containerEl) + .setName('Neo4j server') + .setDesc('Set the Neo4j server to use. Default localhost.') + .addText((text) => { + text.setValue(this.plugin.settings.server + '') + .setPlaceholder('localhost') + .onChange((new_value) => { + this.plugin.settings.server = new_value.trim(); + this.plugin.saveData(this.plugin.settings); + }); + }); + new obsidian.Setting(containerEl) + .setName('Neo4j server port') + .setDesc('Set the port of the Neo4j server. Default 7687.') + .addText((text) => { + text.setValue(this.plugin.settings.neo4jServerPort + '') + .setPlaceholder('7687') + .onChange((new_value) => { + this.plugin.settings.neo4jServerPort = parseInt(new_value.trim()); + this.plugin.saveData(this.plugin.settings); + }); + }); + new obsidian.Setting(containerEl) + .setName('Neo4j database password') + .setDesc('The password of your neo4j graph database. WARNING: This is stored in plaintext in your vault. ' + + 'Don\'t use sensitive passwords here!') + .addText((text) => { + text.setPlaceholder('') + .setValue(this.plugin.settings.password) + .onChange((newFolder) => { + this.plugin.settings.password = newFolder; + this.plugin.saveData(this.plugin.settings); + }).inputEl.setAttribute('type', 'password'); + }); + new obsidian.Setting(containerEl) + .setName('Index note content') + .setDesc('This will full-text index the content of notes. ' + + 'This allows searching within notes using the Neo4j Bloom search bar. However, it could decrease performance.') + .addToggle((toggle) => { + toggle.setValue(this.plugin.settings.indexContent) + .onChange((new_value) => { + this.plugin.settings.indexContent = new_value; + this.plugin.saveData(this.plugin.settings); + }); + }); + new obsidian.Setting(containerEl) + .setName('Typed links prefix') + .setDesc('Prefix to use for typed links. Default is \'-\'. Requires a server restart.') + .addText((text) => { + text.setPlaceholder('') + .setValue(this.plugin.settings.typedLinkPrefix) + .onChange((new_folder) => { + this.plugin.settings.typedLinkPrefix = new_folder; + this.plugin.saveData(this.plugin.settings); + }); + }); + new obsidian.Setting(containerEl) + .setName('Debug') + .setDesc('Enable debug mode, which prints a lot of stuff in the developers console.') + .addToggle((toggle) => { + toggle.setValue(this.plugin.settings.debug) + .onChange((new_value) => { + this.plugin.settings.debug = new_value; + this.plugin.saveData(this.plugin.settings); + }); + }); + } +} + +const STATUS_OFFLINE = 'Neo4j stream offline'; + +class Neo4jPlugin extends obsidian.Plugin { + async onload() { + super.onload(); + console.log('Loading Neo4j stream'); + this.settings = Object.assign({}, DefaultNeo4jStreamSettings, await this.loadData()); + this.vault = this.app.vault; + this.metadata = this.app.metadataCache; + this.statusBar = this.addStatusBarItem(); + this.statusBar.setText(STATUS_OFFLINE); + this.neo4jStream = new Neo4jStream(this); + this.addChild(this.neo4jStream); + this.addCommand({ + id: 'restart-stream', + name: 'Restart Neo4j stream', + callback: () => { + console.log('Restarting stream'); + this.neo4jStream.stop(); + this.neo4jStream.start(); + }, + }); + this.addCommand({ + id: 'stop-stream', + name: 'Stop Neo4j stream', + callback: () => { + this.neo4jStream.stop(); + }, + }); + // this.addCommand({ + // id: 'open-bloom-link', + // name: 'Open note in Neo4j Bloom', + // callback: () => { + // if (!this.stream_process) { + // new Notice("Cannot open in Neo4j Bloom as neo4j stream is not active.") + // } + // let active_view = this.app.workspace.getActiveViewOfType(MarkdownView); + // if (active_view == null) { + // return; + // } + // let name = active_view.getDisplayText(); + // // active_view.getState(). + // + // console.log(encodeURI("neo4j://graphapps/neo4j-bloom?search=SMD_no_tags with name " + name)); + // open(encodeURI("neo4j://graphapps/neo4j-bloom?search=SMD_no_tags with name " + name)); + // // require("electron").shell.openExternal("www.google.com"); + // }, + // }); + this.addSettingTab(new Neo4jStreamSettingsTab(this.app, this)); + this.app.workspace.onLayoutReady(() => { + this.neo4jStream.start(); + }); + } + // nodeCypher(label: string): string { + // return 'MATCH (n) WHERE n.name="' + label + + // '" AND n.' + PROP_VAULT + '="' + this.app.vault.getName() + + // '" RETURN n'; + // } + // + // localNeighborhoodCypher(label:string): string { + // return 'MATCH (n {name: "' + label + + // '", ' + PROP_VAULT + ':"' + this.app.vault.getName() + + // '"}) OPTIONAL MATCH (n)-[r]-(m) RETURN n,r,m'; + // } + // executeQuery() { + // // Code taken from https://github.com/mrjackphil/obsidian-text-expand/blob/0.6.4/main.ts + // const currentView = this.app.workspace.activeLeaf.view; + // + // if (!(currentView instanceof MarkdownView)) { + // return; + // } + // + // const cmDoc = currentView.sourceMode.cmEditor; + // const curNum = cmDoc.getCursor().line; + // const query = this.getContentBetweenLines(curNum, '```cypher', '```', cmDoc); + // if (query.length > 0) { + // const leaf = this.app.workspace.splitActiveLeaf(this.settings.splitDirection); + // try { + // // TODO: Pass query. + // // const neovisView = new NeoVisView((leaf, this, name, [new ObsidianStore(this)]); + // // leaf.open(neovisView); + // } catch (e) { + // if (e instanceof Neo4jError) { + // new Notice('Invalid cypher query. Check console for more info.'); + // } else { + // throw e; + // } + // } + // } + // } + async onunload() { + super.onunload(); + console.log('Unloading Neo4j stream'); + } +} + +module.exports = Neo4jPlugin; diff --git a/docs/Neo4j Stream/manifest.json b/docs/Neo4j Stream/manifest.json new file mode 100644 index 0000000..ec5dc0c --- /dev/null +++ b/docs/Neo4j Stream/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "neo4j-stream", + "name": "Neoj Stream", + "version": "0.0.1", + "minAppVersion": "0.11.5", + "description": "Adds a completely interactive, stylable and expandable graph view to Obsidian.", + "author": "Emile", + "authorUrl": "https://twitter.com/emilevankrieken", + "isDesktopOnly": true +} diff --git a/docs/Roadmap.md b/docs/Roadmap.md index c704553..c9bb183 100644 --- a/docs/Roadmap.md +++ b/docs/Roadmap.md @@ -6,9 +6,8 @@ aliases: [] # Juggl ## Planned ### [[Neo4j Stream]] -A new plugin that will upload your vault to [[Neo4j Desktop]]. This feature was present in [[Neo4j Graph View Plugin]], but not in [[Juggl]]. It'll be a separate plugin to ensure non-advanced users will not have to deal with installing Neo4j, and that this is completely optional for advanced users. +Allow for [[Cypher]] querying in [[Juggl]] ^2d1fd7 -This plugin will not require installing Python, and will allow for [[Cypher]] querying in [[Juggl]]. ### [[Link Types]] Add better support for creating and maintaining link types. Also provide new syntax for inline link types and properties on links. A discussion on syntax is in [[Link Types]]. @@ -19,6 +18,7 @@ Add better support for creating and maintaining link types. Also provide new syn ### [[Style Pane]] for edges Makes it easier to style typed links. + ### Outline in compound nodes The outline of a note is essentially a tree. As it is completely hierarchical wrt the node representing the note, it can be nicely rendered and collapsed using compound nodes, like in From fd85f14c69cac48bbb50d1e69bdd188f0c7d7358 Mon Sep 17 00:00:00 2001 From: Emile van Krieken Date: Thu, 30 Sep 2021 11:45:23 +0200 Subject: [PATCH 2/8] Delete main.js Do not host plugin directly --- docs/Neo4j Stream/main.js | 38536 ------------------------------------ 1 file changed, 38536 deletions(-) delete mode 100644 docs/Neo4j Stream/main.js diff --git a/docs/Neo4j Stream/main.js b/docs/Neo4j Stream/main.js deleted file mode 100644 index 8f15d3f..0000000 --- a/docs/Neo4j Stream/main.js +++ /dev/null @@ -1,38536 +0,0 @@ -'use strict'; - -var obsidian = require('obsidian'); -var require$$6 = require('buffer'); -var require$$2 = require('net'); -var require$$3 = require('tls'); -var require$$4 = require('fs'); -var require$$6$1 = require('dns'); -var _string_decoder = require('string_decoder'); -var path = require('path'); - -function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } - -var require$$6__default = /*#__PURE__*/_interopDefaultLegacy(require$$6); -var require$$2__default = /*#__PURE__*/_interopDefaultLegacy(require$$2); -var require$$3__default = /*#__PURE__*/_interopDefaultLegacy(require$$3); -var require$$4__default = /*#__PURE__*/_interopDefaultLegacy(require$$4); -var require$$6__default$1 = /*#__PURE__*/_interopDefaultLegacy(require$$6$1); -var _string_decoder__default = /*#__PURE__*/_interopDefaultLegacy(_string_decoder); - -var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - -function getDefaultExportFromCjs (x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; -} - -function getAugmentedNamespace(n) { - if (n.__esModule) return n; - var a = Object.defineProperty({}, '__esModule', {value: true}); - Object.keys(n).forEach(function (k) { - var d = Object.getOwnPropertyDescriptor(n, k); - Object.defineProperty(a, k, d.get ? d : { - enumerable: true, - get: function () { - return n[k]; - } - }); - }); - return a; -} - -function createCommonjsModule(fn) { - var module = { exports: {} }; - return fn(module, module.exports), module.exports; -} - -/** Detect free variable `global` from Node.js. */ - -var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; - -var _freeGlobal = freeGlobal; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = _freeGlobal || freeSelf || Function('return this')(); - -var _root = root; - -/** Built-in value references. */ -var Symbol$1 = _root.Symbol; - -var _Symbol = Symbol$1; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; - -/** Built-in value references. */ -var symToStringTag = _Symbol ? _Symbol.toStringTag : undefined; - -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; - - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; -} - -var _getRawTag = getRawTag; - -/** Used for built-in method references. */ -var objectProto$1 = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$1.toString; - -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString$1.call(value); -} - -var _objectToString = objectToString; - -/** `Object#toString` result references. */ -var nullTag = '[object Null]', - undefinedTag = '[object Undefined]'; - -/** Built-in value references. */ -var symToStringTag$1 = _Symbol ? _Symbol.toStringTag : undefined; - -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag$1 && symToStringTag$1 in Object(value)) - ? _getRawTag(value) - : _objectToString(value); -} - -var _baseGetTag = baseGetTag; - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} - -var isObject_1 = isObject; - -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - proxyTag = '[object Proxy]'; - -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - if (!isObject_1(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = _baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; -} - -var isFunction_1 = isFunction; - -/** Used to detect overreaching core-js shims. */ -var coreJsData = _root['__core-js_shared__']; - -var _coreJsData = coreJsData; - -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(_coreJsData && _coreJsData.keys && _coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); - -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); -} - -var _isMasked = isMasked; - -/** Used for built-in method references. */ -var funcProto = Function.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; - -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; -} - -var _toSource = toSource; - -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; - -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; - -/** Used for built-in method references. */ -var funcProto$1 = Function.prototype, - objectProto$2 = Object.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString$1 = funcProto$1.toString; - -/** Used to check objects for own properties. */ -var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString$1.call(hasOwnProperty$1).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); - -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative(value) { - if (!isObject_1(value) || _isMasked(value)) { - return false; - } - var pattern = isFunction_1(value) ? reIsNative : reIsHostCtor; - return pattern.test(_toSource(value)); -} - -var _baseIsNative = baseIsNative; - -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ -function getValue(object, key) { - return object == null ? undefined : object[key]; -} - -var _getValue = getValue; - -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = _getValue(object, key); - return _baseIsNative(value) ? value : undefined; -} - -var _getNative = getNative; - -var defineProperty = (function() { - try { - var func = _getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} -}()); - -var _defineProperty = defineProperty; - -/** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function baseAssignValue(object, key, value) { - if (key == '__proto__' && _defineProperty) { - _defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } -} - -var _baseAssignValue = baseAssignValue; - -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} - -var eq_1 = eq; - -/** Used for built-in method references. */ -var objectProto$3 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty$2.call(object, key) && eq_1(objValue, value)) || - (value === undefined && !(key in object))) { - _baseAssignValue(object, key, value); - } -} - -var _assignValue = assignValue; - -/** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ -function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; - - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - _baseAssignValue(object, key, newValue); - } else { - _assignValue(object, key, newValue); - } - } - return object; -} - -var _copyObject = copyObject; - -/** - * This method returns the first argument it receives. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Util - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'a': 1 }; - * - * console.log(_.identity(object) === object); - * // => true - */ -function identity(value) { - return value; -} - -var identity_1 = identity; - -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} - -var _apply = apply; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; - -/** - * A specialized version of `baseRest` which transforms the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. - */ -function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return _apply(func, this, otherArgs); - }; -} - -var _overRest = overRest; - -/** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ -function constant(value) { - return function() { - return value; - }; -} - -var constant_1 = constant; - -/** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ -var baseSetToString = !_defineProperty ? identity_1 : function(func, string) { - return _defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant_1(string), - 'writable': true - }); -}; - -var _baseSetToString = baseSetToString; - -/** Used to detect hot functions by number of calls within a span of milliseconds. */ -var HOT_COUNT = 800, - HOT_SPAN = 16; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeNow = Date.now; - -/** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. - * - * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. - */ -function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); - - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; -} - -var _shortOut = shortOut; - -/** - * Sets the `toString` method of `func` to return `string`. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ -var setToString = _shortOut(_baseSetToString); - -var _setToString = setToString; - -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - return _setToString(_overRest(func, start, identity_1), func + ''); -} - -var _baseRest = baseRest; - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} - -var isLength_1 = isLength; - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength_1(value.length) && !isFunction_1(value); -} - -var isArrayLike_1 = isArrayLike; - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER$1 = 9007199254740991; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER$1 : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); -} - -var _isIndex = isIndex; - -/** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ -function isIterateeCall(value, index, object) { - if (!isObject_1(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike_1(object) && _isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq_1(object[index], value); - } - return false; -} - -var _isIterateeCall = isIterateeCall; - -/** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ -function createAssigner(assigner) { - return _baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; - - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; - - if (guard && _isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); -} - -var _createAssigner = createAssigner; - -/** Used for built-in method references. */ -var objectProto$4 = Object.prototype; - -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$4; - - return value === proto; -} - -var _isPrototype = isPrototype; - -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} - -var _baseTimes = baseTimes; - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; -} - -var isObjectLike_1 = isObjectLike; - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]'; - -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments(value) { - return isObjectLike_1(value) && _baseGetTag(value) == argsTag; -} - -var _baseIsArguments = baseIsArguments; - -/** Used for built-in method references. */ -var objectProto$5 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$3 = objectProto$5.hasOwnProperty; - -/** Built-in value references. */ -var propertyIsEnumerable = objectProto$5.propertyIsEnumerable; - -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -var isArguments = _baseIsArguments(function() { return arguments; }()) ? _baseIsArguments : function(value) { - return isObjectLike_1(value) && hasOwnProperty$3.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); -}; - -var isArguments_1 = isArguments; - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -var isArray_1 = isArray; - -/** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ -function stubFalse() { - return false; -} - -var stubFalse_1 = stubFalse; - -var isBuffer_1 = createCommonjsModule(function (module, exports) { -/** Detect free variable `exports`. */ -var freeExports = exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; - -/** Built-in value references. */ -var Buffer = moduleExports ? _root.Buffer : undefined; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - -/** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ -var isBuffer = nativeIsBuffer || stubFalse_1; - -module.exports = isBuffer; -}); - -/** `Object#toString` result references. */ -var argsTag$1 = '[object Arguments]', - arrayTag = '[object Array]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - errorTag = '[object Error]', - funcTag$1 = '[object Function]', - mapTag = '[object Map]', - numberTag = '[object Number]', - objectTag = '[object Object]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - weakMapTag = '[object WeakMap]'; - -var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = -typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = -typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = -typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = -typedArrayTags[uint32Tag] = true; -typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = -typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = -typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = -typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = -typedArrayTags[mapTag] = typedArrayTags[numberTag] = -typedArrayTags[objectTag] = typedArrayTags[regexpTag] = -typedArrayTags[setTag] = typedArrayTags[stringTag] = -typedArrayTags[weakMapTag] = false; - -/** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ -function baseIsTypedArray(value) { - return isObjectLike_1(value) && - isLength_1(value.length) && !!typedArrayTags[_baseGetTag(value)]; -} - -var _baseIsTypedArray = baseIsTypedArray; - -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); - }; -} - -var _baseUnary = baseUnary; - -var _nodeUtil = createCommonjsModule(function (module, exports) { -/** Detect free variable `exports`. */ -var freeExports = exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule = freeExports && 'object' == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; - -/** Detect free variable `process` from Node.js. */ -var freeProcess = moduleExports && _freeGlobal.process; - -/** Used to access faster Node.js helpers. */ -var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; - - if (types) { - return types; - } - - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} -}()); - -module.exports = nodeUtil; -}); - -/* Node.js helper references. */ -var nodeIsTypedArray = _nodeUtil && _nodeUtil.isTypedArray; - -/** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ -var isTypedArray = nodeIsTypedArray ? _baseUnary(nodeIsTypedArray) : _baseIsTypedArray; - -var isTypedArray_1 = isTypedArray; - -/** Used for built-in method references. */ -var objectProto$6 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$4 = objectProto$6.hasOwnProperty; - -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - var isArr = isArray_1(value), - isArg = !isArr && isArguments_1(value), - isBuff = !isArr && !isArg && isBuffer_1(value), - isType = !isArr && !isArg && !isBuff && isTypedArray_1(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? _baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$4.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - _isIndex(key, length) - ))) { - result.push(key); - } - } - return result; -} - -var _arrayLikeKeys = arrayLikeKeys; - -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} - -var _overArg = overArg; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = _overArg(Object.keys, Object); - -var _nativeKeys = nativeKeys; - -/** Used for built-in method references. */ -var objectProto$7 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$5 = objectProto$7.hasOwnProperty; - -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys(object) { - if (!_isPrototype(object)) { - return _nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$5.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; -} - -var _baseKeys = baseKeys; - -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike_1(object) ? _arrayLikeKeys(object) : _baseKeys(object); -} - -var keys_1 = keys; - -/** Used for built-in method references. */ -var objectProto$8 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$6 = objectProto$8.hasOwnProperty; - -/** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } - */ -var assign = _createAssigner(function(object, source) { - if (_isPrototype(source) || isArrayLike_1(source)) { - _copyObject(source, keys_1(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty$6.call(source, key)) { - _assignValue(object, key, source[key]); - } - } -}); - -var assign_1 = assign; - -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise */ - -var extendStatics = function(d, b) { - extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; - return extendStatics(d, b); -}; - -function __extends(d, b) { - if (typeof b !== "function" && b !== null) - throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); -} - -function __awaiter(thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -} - -function __generator(thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } -} - -/** @deprecated */ -function __spreadArrays() { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; -} - -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} - -var _arrayMap = arrayMap; - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike_1(value) && _baseGetTag(value) == symbolTag); -} - -var isSymbol_1 = isSymbol; - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = _Symbol ? _Symbol.prototype : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; - -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray_1(value)) { - // Recursively convert values (susceptible to call stack limits). - return _arrayMap(value, baseToString) + ''; - } - if (isSymbol_1(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} - -var _baseToString = baseToString; - -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} - -var _baseSlice = baseSlice; - -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : _baseSlice(array, start, end); -} - -var _castSlice = castSlice; - -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} - -var _baseFindIndex = baseFindIndex; - -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} - -var _baseIsNaN = baseIsNaN; - -/** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} - -var _strictIndexOf = strictIndexOf; - -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - return value === value - ? _strictIndexOf(array, value, fromIndex) - : _baseFindIndex(array, _baseIsNaN, fromIndex); -} - -var _baseIndexOf = baseIndexOf; - -/** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ -function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} - -var _charsEndIndex = charsEndIndex; - -/** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ -function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && _baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} - -var _charsStartIndex = charsStartIndex; - -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function asciiToArray(string) { - return string.split(''); -} - -var _asciiToArray = asciiToArray; - -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsVarRange = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsZWJ = '\\u200d'; - -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode(string) { - return reHasUnicode.test(string); -} - -var _hasUnicode = hasUnicode; - -/** Used to compose unicode character classes. */ -var rsAstralRange$1 = '\\ud800-\\udfff', - rsComboMarksRange$1 = '\\u0300-\\u036f', - reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', - rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', - rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, - rsVarRange$1 = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsAstral = '[' + rsAstralRange$1 + ']', - rsCombo = '[' + rsComboRange$1 + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange$1 + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsZWJ$1 = '\\u200d'; - -/** Used to compose unicode regexes. */ -var reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange$1 + ']?', - rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; -} - -var _unicodeToArray = unicodeToArray; - -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return _hasUnicode(string) - ? _unicodeToArray(string) - : _asciiToArray(string); -} - -var _stringToArray = stringToArray; - -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : _baseToString(value); -} - -var toString_1 = toString; - -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; - -/** - * Removes leading and trailing whitespace or specified characters from `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. - * @example - * - * _.trim(' abc '); - * // => 'abc' - * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' - * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] - */ -function trim(string, chars, guard) { - string = toString_1(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); - } - if (!string || !(chars = _baseToString(chars))) { - return string; - } - var strSymbols = _stringToArray(string), - chrSymbols = _stringToArray(chars), - start = _charsStartIndex(strSymbols, chrSymbols), - end = _charsEndIndex(strSymbols, chrSymbols) + 1; - - return _castSlice(strSymbols, start, end).join(''); -} - -var trim_1 = trim; - -/** - * Checks if `value` is `null` or `undefined`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is nullish, else `false`. - * @example - * - * _.isNil(null); - * // => true - * - * _.isNil(void 0); - * // => true - * - * _.isNil(NaN); - * // => false - */ -function isNil(value) { - return value == null; -} - -var isNil_1 = isNil; - -/** - * Casts `value` as an array if it's not one. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Lang - * @param {*} value The value to inspect. - * @returns {Array} Returns the cast array. - * @example - * - * _.castArray(1); - * // => [1] - * - * _.castArray({ 'a': 1 }); - * // => [{ 'a': 1 }] - * - * _.castArray('abc'); - * // => ['abc'] - * - * _.castArray(null); - * // => [null] - * - * _.castArray(undefined); - * // => [undefined] - * - * _.castArray(); - * // => [] - * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true - */ -function castArray() { - if (!arguments.length) { - return []; - } - var value = arguments[0]; - return isArray_1(value) ? value : [value]; -} - -var castArray_1 = castArray; - -/** `Object#toString` result references. */ -var stringTag$1 = '[object String]'; - -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || - (!isArray_1(value) && isObjectLike_1(value) && _baseGetTag(value) == stringTag$1); -} - -var isString_1 = isString; - -/* Built-in method references that are verified to be native. */ -var DataView = _getNative(_root, 'DataView'); - -var _DataView = DataView; - -/* Built-in method references that are verified to be native. */ -var Map$1 = _getNative(_root, 'Map'); - -var _Map = Map$1; - -/* Built-in method references that are verified to be native. */ -var Promise$1 = _getNative(_root, 'Promise'); - -var _Promise = Promise$1; - -/* Built-in method references that are verified to be native. */ -var Set$1 = _getNative(_root, 'Set'); - -var _Set = Set$1; - -/* Built-in method references that are verified to be native. */ -var WeakMap$1 = _getNative(_root, 'WeakMap'); - -var _WeakMap = WeakMap$1; - -/** `Object#toString` result references. */ -var mapTag$1 = '[object Map]', - objectTag$1 = '[object Object]', - promiseTag = '[object Promise]', - setTag$1 = '[object Set]', - weakMapTag$1 = '[object WeakMap]'; - -var dataViewTag$1 = '[object DataView]'; - -/** Used to detect maps, sets, and weakmaps. */ -var dataViewCtorString = _toSource(_DataView), - mapCtorString = _toSource(_Map), - promiseCtorString = _toSource(_Promise), - setCtorString = _toSource(_Set), - weakMapCtorString = _toSource(_WeakMap); - -/** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -var getTag = _baseGetTag; - -// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. -if ((_DataView && getTag(new _DataView(new ArrayBuffer(1))) != dataViewTag$1) || - (_Map && getTag(new _Map) != mapTag$1) || - (_Promise && getTag(_Promise.resolve()) != promiseTag) || - (_Set && getTag(new _Set) != setTag$1) || - (_WeakMap && getTag(new _WeakMap) != weakMapTag$1)) { - getTag = function(value) { - var result = _baseGetTag(value), - Ctor = result == objectTag$1 ? value.constructor : undefined, - ctorString = Ctor ? _toSource(Ctor) : ''; - - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag$1; - case mapCtorString: return mapTag$1; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag$1; - case weakMapCtorString: return weakMapTag$1; - } - } - return result; - }; -} - -var _getTag = getTag; - -/** `Object#toString` result references. */ -var mapTag$2 = '[object Map]', - setTag$2 = '[object Set]'; - -/** Used for built-in method references. */ -var objectProto$9 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$7 = objectProto$9.hasOwnProperty; - -/** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({ 'a': 1 }); - * // => false - */ -function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike_1(value) && - (isArray_1(value) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer_1(value) || isTypedArray_1(value) || isArguments_1(value))) { - return !value.length; - } - var tag = _getTag(value); - if (tag == mapTag$2 || tag == setTag$2) { - return !value.size; - } - if (_isPrototype(value)) { - return !_baseKeys(value).length; - } - for (var key in value) { - if (hasOwnProperty$7.call(value, key)) { - return false; - } - } - return true; -} - -var isEmpty_1 = isEmpty; - -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; - this.size = 0; -} - -var _listCacheClear = listCacheClear; - -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq_1(array[length][0], key)) { - return length; - } - } - return -1; -} - -var _assocIndexOf = assocIndexOf; - -/** Used for built-in method references. */ -var arrayProto = Array.prototype; - -/** Built-in value references. */ -var splice = arrayProto.splice; - -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete(key) { - var data = this.__data__, - index = _assocIndexOf(data, key); - - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; -} - -var _listCacheDelete = listCacheDelete; - -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet(key) { - var data = this.__data__, - index = _assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; -} - -var _listCacheGet = listCacheGet; - -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas(key) { - return _assocIndexOf(this.__data__, key) > -1; -} - -var _listCacheHas = listCacheHas; - -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = _assocIndexOf(data, key); - - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; -} - -var _listCacheSet = listCacheSet; - -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `ListCache`. -ListCache.prototype.clear = _listCacheClear; -ListCache.prototype['delete'] = _listCacheDelete; -ListCache.prototype.get = _listCacheGet; -ListCache.prototype.has = _listCacheHas; -ListCache.prototype.set = _listCacheSet; - -var _ListCache = ListCache; - -/** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ -function stackClear() { - this.__data__ = new _ListCache; - this.size = 0; -} - -var _stackClear = stackClear; - -/** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); - - this.size = data.size; - return result; -} - -var _stackDelete = stackDelete; - -/** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function stackGet(key) { - return this.__data__.get(key); -} - -var _stackGet = stackGet; - -/** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function stackHas(key) { - return this.__data__.has(key); -} - -var _stackHas = stackHas; - -/* Built-in method references that are verified to be native. */ -var nativeCreate = _getNative(Object, 'create'); - -var _nativeCreate = nativeCreate; - -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = _nativeCreate ? _nativeCreate(null) : {}; - this.size = 0; -} - -var _hashClear = hashClear; - -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; -} - -var _hashDelete = hashDelete; - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; - -/** Used for built-in method references. */ -var objectProto$a = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$8 = objectProto$a.hasOwnProperty; - -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet(key) { - var data = this.__data__; - if (_nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty$8.call(data, key) ? data[key] : undefined; -} - -var _hashGet = hashGet; - -/** Used for built-in method references. */ -var objectProto$b = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$9 = objectProto$b.hasOwnProperty; - -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return _nativeCreate ? (data[key] !== undefined) : hasOwnProperty$9.call(data, key); -} - -var _hashHas = hashHas; - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; - -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (_nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; - return this; -} - -var _hashSet = hashSet; - -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `Hash`. -Hash.prototype.clear = _hashClear; -Hash.prototype['delete'] = _hashDelete; -Hash.prototype.get = _hashGet; -Hash.prototype.has = _hashHas; -Hash.prototype.set = _hashSet; - -var _Hash = Hash; - -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new _Hash, - 'map': new (_Map || _ListCache), - 'string': new _Hash - }; -} - -var _mapCacheClear = mapCacheClear; - -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); -} - -var _isKeyable = isKeyable; - -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return _isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; -} - -var _getMapData = getMapData; - -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - var result = _getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; -} - -var _mapCacheDelete = mapCacheDelete; - -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet(key) { - return _getMapData(this, key).get(key); -} - -var _mapCacheGet = mapCacheGet; - -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas(key) { - return _getMapData(this, key).has(key); -} - -var _mapCacheHas = mapCacheHas; - -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet(key, value) { - var data = _getMapData(this, key), - size = data.size; - - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; -} - -var _mapCacheSet = mapCacheSet; - -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; - - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} - -// Add methods to `MapCache`. -MapCache.prototype.clear = _mapCacheClear; -MapCache.prototype['delete'] = _mapCacheDelete; -MapCache.prototype.get = _mapCacheGet; -MapCache.prototype.has = _mapCacheHas; -MapCache.prototype.set = _mapCacheSet; - -var _MapCache = MapCache; - -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE = 200; - -/** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ -function stackSet(key, value) { - var data = this.__data__; - if (data instanceof _ListCache) { - var pairs = data.__data__; - if (!_Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new _MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; -} - -var _stackSet = stackSet; - -/** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Stack(entries) { - var data = this.__data__ = new _ListCache(entries); - this.size = data.size; -} - -// Add methods to `Stack`. -Stack.prototype.clear = _stackClear; -Stack.prototype['delete'] = _stackDelete; -Stack.prototype.get = _stackGet; -Stack.prototype.has = _stackHas; -Stack.prototype.set = _stackSet; - -var _Stack = Stack; - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; - -/** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ -function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED$2); - return this; -} - -var _setCacheAdd = setCacheAdd; - -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ -function setCacheHas(value) { - return this.__data__.has(value); -} - -var _setCacheHas = setCacheHas; - -/** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ -function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; - - this.__data__ = new _MapCache; - while (++index < length) { - this.add(values[index]); - } -} - -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = _setCacheAdd; -SetCache.prototype.has = _setCacheHas; - -var _SetCache = SetCache; - -/** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ -function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; -} - -var _arraySome = arraySome; - -/** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function cacheHas(cache, key) { - return cache.has(key); -} - -var _cacheHas = cacheHas; - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; - -/** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ -function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; - - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Check that cyclic values are equal. - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new _SetCache : undefined; - - stack.set(array, other); - stack.set(other, array); - - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!_arraySome(other, function(othValue, othIndex) { - if (!_cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } - } - stack['delete'](array); - stack['delete'](other); - return result; -} - -var _equalArrays = equalArrays; - -/** Built-in value references. */ -var Uint8Array = _root.Uint8Array; - -var _Uint8Array = Uint8Array; - -/** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ -function mapToArray(map) { - var index = -1, - result = Array(map.size); - - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; -} - -var _mapToArray = mapToArray; - -/** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ -function setToArray(set) { - var index = -1, - result = Array(set.size); - - set.forEach(function(value) { - result[++index] = value; - }); - return result; -} - -var _setToArray = setToArray; - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$1 = 1, - COMPARE_UNORDERED_FLAG$1 = 2; - -/** `Object#toString` result references. */ -var boolTag$1 = '[object Boolean]', - dateTag$1 = '[object Date]', - errorTag$1 = '[object Error]', - mapTag$3 = '[object Map]', - numberTag$1 = '[object Number]', - regexpTag$1 = '[object RegExp]', - setTag$3 = '[object Set]', - stringTag$2 = '[object String]', - symbolTag$1 = '[object Symbol]'; - -var arrayBufferTag$1 = '[object ArrayBuffer]', - dataViewTag$2 = '[object DataView]'; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto$1 = _Symbol ? _Symbol.prototype : undefined, - symbolValueOf = symbolProto$1 ? symbolProto$1.valueOf : undefined; - -/** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag$2: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; - - case arrayBufferTag$1: - if ((object.byteLength != other.byteLength) || - !equalFunc(new _Uint8Array(object), new _Uint8Array(other))) { - return false; - } - return true; - - case boolTag$1: - case dateTag$1: - case numberTag$1: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq_1(+object, +other); - - case errorTag$1: - return object.name == other.name && object.message == other.message; - - case regexpTag$1: - case stringTag$2: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); - - case mapTag$3: - var convert = _mapToArray; - - case setTag$3: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$1; - convert || (convert = _setToArray); - - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG$1; - - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = _equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; - - case symbolTag$1: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; -} - -var _equalByTag = equalByTag; - -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} - -var _arrayPush = arrayPush; - -/** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ -function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray_1(object) ? result : _arrayPush(result, symbolsFunc(object)); -} - -var _baseGetAllKeys = baseGetAllKeys; - -/** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ -function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; - } - } - return result; -} - -var _arrayFilter = arrayFilter; - -/** - * This method returns a new empty array. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {Array} Returns the new empty array. - * @example - * - * var arrays = _.times(2, _.stubArray); - * - * console.log(arrays); - * // => [[], []] - * - * console.log(arrays[0] === arrays[1]); - * // => false - */ -function stubArray() { - return []; -} - -var stubArray_1 = stubArray; - -/** Used for built-in method references. */ -var objectProto$c = Object.prototype; - -/** Built-in value references. */ -var propertyIsEnumerable$1 = objectProto$c.propertyIsEnumerable; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeGetSymbols = Object.getOwnPropertySymbols; - -/** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ -var getSymbols = !nativeGetSymbols ? stubArray_1 : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return _arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable$1.call(object, symbol); - }); -}; - -var _getSymbols = getSymbols; - -/** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ -function getAllKeys(object) { - return _baseGetAllKeys(object, keys_1, _getSymbols); -} - -var _getAllKeys = getAllKeys; - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$2 = 1; - -/** Used for built-in method references. */ -var objectProto$d = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$a = objectProto$d.hasOwnProperty; - -/** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG$2, - objProps = _getAllKeys(object), - objLength = objProps.length, - othProps = _getAllKeys(other), - othLength = othProps.length; - - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty$a.call(other, key))) { - return false; - } - } - // Check that cyclic values are equal. - var objStacked = stack.get(object); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object; - } - var result = true; - stack.set(object, other); - stack.set(other, object); - - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; - - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; - - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; -} - -var _equalObjects = equalObjects; - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$3 = 1; - -/** `Object#toString` result references. */ -var argsTag$2 = '[object Arguments]', - arrayTag$1 = '[object Array]', - objectTag$2 = '[object Object]'; - -/** Used for built-in method references. */ -var objectProto$e = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$b = objectProto$e.hasOwnProperty; - -/** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ -function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray_1(object), - othIsArr = isArray_1(other), - objTag = objIsArr ? arrayTag$1 : _getTag(object), - othTag = othIsArr ? arrayTag$1 : _getTag(other); - - objTag = objTag == argsTag$2 ? objectTag$2 : objTag; - othTag = othTag == argsTag$2 ? objectTag$2 : othTag; - - var objIsObj = objTag == objectTag$2, - othIsObj = othTag == objectTag$2, - isSameTag = objTag == othTag; - - if (isSameTag && isBuffer_1(object)) { - if (!isBuffer_1(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new _Stack); - return (objIsArr || isTypedArray_1(object)) - ? _equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : _equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG$3)) { - var objIsWrapped = objIsObj && hasOwnProperty$b.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty$b.call(other, '__wrapped__'); - - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; - - stack || (stack = new _Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new _Stack); - return _equalObjects(object, other, bitmask, customizer, equalFunc, stack); -} - -var _baseIsEqualDeep = baseIsEqualDeep; - -/** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ -function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike_1(value) && !isObjectLike_1(other))) { - return value !== value && other !== other; - } - return _baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); -} - -var _baseIsEqual = baseIsEqual; - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$4 = 1, - COMPARE_UNORDERED_FLAG$2 = 2; - -/** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ -function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; - - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; - - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new _Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$4 | COMPARE_UNORDERED_FLAG$2, customizer, stack) - : result - )) { - return false; - } - } - } - return true; -} - -var _baseIsMatch = baseIsMatch; - -/** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. - */ -function isStrictComparable(value) { - return value === value && !isObject_1(value); -} - -var _isStrictComparable = isStrictComparable; - -/** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ -function getMatchData(object) { - var result = keys_1(object), - length = result.length; - - while (length--) { - var key = result[length], - value = object[key]; - - result[length] = [key, value, _isStrictComparable(value)]; - } - return result; -} - -var _getMatchData = getMatchData; - -/** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. - * - * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ -function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; -} - -var _matchesStrictComparable = matchesStrictComparable; - -/** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ -function baseMatches(source) { - var matchData = _getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return _matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || _baseIsMatch(object, source, matchData); - }; -} - -var _baseMatches = baseMatches; - -/** Used to match property names within property paths. */ -var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/; - -/** - * Checks if `value` is a property name and not a property path. - * - * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. - */ -function isKey(value, object) { - if (isArray_1(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol_1(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); -} - -var _isKey = isKey; - -/** Error message constants. */ -var FUNC_ERROR_TEXT = 'Expected a function'; - -/** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] - * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; - */ -function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); - } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; - return result; - }; - memoized.cache = new (memoize.Cache || _MapCache); - return memoized; -} - -// Expose `MapCache`. -memoize.Cache = _MapCache; - -var memoize_1 = memoize; - -/** Used as the maximum memoize cache size. */ -var MAX_MEMOIZE_SIZE = 500; - -/** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. - * - * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. - */ -function memoizeCapped(func) { - var result = memoize_1(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - - var cache = result.cache; - return result; -} - -var _memoizeCapped = memoizeCapped; - -/** Used to match property names within property paths. */ -var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - -/** Used to match backslashes in property paths. */ -var reEscapeChar = /\\(\\)?/g; - -/** - * Converts `string` to a property path array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. - */ -var stringToPath = _memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; -}); - -var _stringToPath = stringToPath; - -/** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ -function castPath(value, object) { - if (isArray_1(value)) { - return value; - } - return _isKey(value, object) ? [value] : _stringToPath(toString_1(value)); -} - -var _castPath = castPath; - -/** Used as references for various `Number` constants. */ -var INFINITY$1 = 1 / 0; - -/** - * Converts `value` to a string key if it's not a string or symbol. - * - * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. - */ -function toKey(value) { - if (typeof value == 'string' || isSymbol_1(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY$1) ? '-0' : result; -} - -var _toKey = toKey; - -/** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ -function baseGet(object, path) { - path = _castPath(path, object); - - var index = 0, - length = path.length; - - while (object != null && index < length) { - object = object[_toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; -} - -var _baseGet = baseGet; - -/** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. - * - * @static - * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 - * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' - */ -function get(object, path, defaultValue) { - var result = object == null ? undefined : _baseGet(object, path); - return result === undefined ? defaultValue : result; -} - -var get_1 = get; - -/** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ -function baseHasIn(object, key) { - return object != null && key in Object(object); -} - -var _baseHasIn = baseHasIn; - -/** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ -function hasPath(object, path, hasFunc) { - path = _castPath(path, object); - - var index = -1, - length = path.length, - result = false; - - while (++index < length) { - var key = _toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength_1(length) && _isIndex(key, length) && - (isArray_1(object) || isArguments_1(object)); -} - -var _hasPath = hasPath; - -/** - * Checks if `path` is a direct or inherited property of `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - * @example - * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false - */ -function hasIn(object, path) { - return object != null && _hasPath(object, path, _baseHasIn); -} - -var hasIn_1 = hasIn; - -/** Used to compose bitmasks for value comparisons. */ -var COMPARE_PARTIAL_FLAG$5 = 1, - COMPARE_UNORDERED_FLAG$3 = 2; - -/** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ -function baseMatchesProperty(path, srcValue) { - if (_isKey(path) && _isStrictComparable(srcValue)) { - return _matchesStrictComparable(_toKey(path), srcValue); - } - return function(object) { - var objValue = get_1(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn_1(object, path) - : _baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$5 | COMPARE_UNORDERED_FLAG$3); - }; -} - -var _baseMatchesProperty = baseMatchesProperty; - -/** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; -} - -var _baseProperty = baseProperty; - -/** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function basePropertyDeep(path) { - return function(object) { - return _baseGet(object, path); - }; -} - -var _basePropertyDeep = basePropertyDeep; - -/** - * Creates a function that returns the value at `path` of a given object. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - * @example - * - * var objects = [ - * { 'a': { 'b': 2 } }, - * { 'a': { 'b': 1 } } - * ]; - * - * _.map(objects, _.property('a.b')); - * // => [2, 1] - * - * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); - * // => [1, 2] - */ -function property(path) { - return _isKey(path) ? _baseProperty(_toKey(path)) : _basePropertyDeep(path); -} - -var property_1 = property; - -/** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ -function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity_1; - } - if (typeof value == 'object') { - return isArray_1(value) - ? _baseMatchesProperty(value[0], value[1]) - : _baseMatches(value); - } - return property_1(value); -} - -var _baseIteratee = baseIteratee; - -/** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; -} - -var _createBaseFor = createBaseFor; - -/** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ -var baseFor = _createBaseFor(); - -var _baseFor = baseFor; - -/** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ -function baseForOwn(object, iteratee) { - return object && _baseFor(object, iteratee, keys_1); -} - -var _baseForOwn = baseForOwn; - -/** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - if (collection == null) { - return collection; - } - if (!isArrayLike_1(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); - - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; -} - -var _createBaseEach = createBaseEach; - -/** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ -var baseEach = _createBaseEach(_baseForOwn); - -var _baseEach = baseEach; - -/** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike_1(collection) ? Array(collection.length) : []; - - _baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; -} - -var _baseMap = baseMap; - -/** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] - * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; - * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] - */ -function map(collection, iteratee) { - var func = isArray_1(collection) ? _arrayMap : _baseMap; - return func(collection, _baseIteratee(iteratee)); -} - -var map_1 = map; - -/** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys - * @example - * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) - */ -function mapValues(object, iteratee) { - var result = {}; - iteratee = _baseIteratee(iteratee); - - _baseForOwn(object, function(value, key, object) { - _baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; -} - -var mapValues_1 = mapValues; - -/** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ -function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array == null ? 0 : array.length; - - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; -} - -var _arrayReduce = arrayReduce; - -/** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ -function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; -} - -var _baseReduce = baseReduce; - -/** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 - * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) - */ -function reduce(collection, iteratee, accumulator) { - var func = isArray_1(collection) ? _arrayReduce : _baseReduce, - initAccum = arguments.length < 3; - - return func(collection, _baseIteratee(iteratee), accumulator, initAccum, _baseEach); -} - -var reduce_1 = reduce; - -/** `Object#toString` result references. */ -var numberTag$2 = '[object Number]'; - -/** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ -function isNumber(value) { - return typeof value == 'number' || - (isObjectLike_1(value) && _baseGetTag(value) == numberTag$2); -} - -var isNumber_1 = isNumber; - -/** `Object#toString` result references. */ -var boolTag$2 = '[object Boolean]'; - -/** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ -function isBoolean(value) { - return value === true || value === false || - (isObjectLike_1(value) && _baseGetTag(value) == boolTag$2); -} - -var isBoolean_1 = isBoolean; - -/** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ -function createCaseFirst(methodName) { - return function(string) { - string = toString_1(string); - - var strSymbols = _hasUnicode(string) - ? _stringToArray(string) - : undefined; - - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); - - var trailing = strSymbols - ? _castSlice(strSymbols, 1).join('') - : string.slice(1); - - return chr[methodName]() + trailing; - }; -} - -var _createCaseFirst = createCaseFirst; - -/** - * Converts the first character of `string` to upper case. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.upperFirst('fred'); - * // => 'Fred' - * - * _.upperFirst('FRED'); - * // => 'FRED' - */ -var upperFirst = _createCaseFirst('toUpperCase'); - -var upperFirst_1 = upperFirst; - -/** - * Converts the first character of `string` to upper case and the remaining - * to lower case. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. - * @example - * - * _.capitalize('FRED'); - * // => 'Fred' - */ -function capitalize(string) { - return upperFirst_1(toString_1(string).toLowerCase()); -} - -var capitalize_1 = capitalize; - -/** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ -function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; -} - -var _basePropertyOf = basePropertyOf; - -/** Used to map Latin Unicode letters to basic Latin letters. */ -var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 's' -}; - -/** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ -var deburrLetter = _basePropertyOf(deburredLetters); - -var _deburrLetter = deburrLetter; - -/** Used to match Latin Unicode letters (excluding mathematical operators). */ -var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - -/** Used to compose unicode character classes. */ -var rsComboMarksRange$2 = '\\u0300-\\u036f', - reComboHalfMarksRange$2 = '\\ufe20-\\ufe2f', - rsComboSymbolsRange$2 = '\\u20d0-\\u20ff', - rsComboRange$2 = rsComboMarksRange$2 + reComboHalfMarksRange$2 + rsComboSymbolsRange$2; - -/** Used to compose unicode capture groups. */ -var rsCombo$1 = '[' + rsComboRange$2 + ']'; - -/** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ -var reComboMark = RegExp(rsCombo$1, 'g'); - -/** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. - * @example - * - * _.deburr('déjà vu'); - * // => 'deja vu' - */ -function deburr(string) { - string = toString_1(string); - return string && string.replace(reLatin, _deburrLetter).replace(reComboMark, ''); -} - -var deburr_1 = deburr; - -/** Used to match words composed of alphanumeric characters. */ -var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - -/** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ -function asciiWords(string) { - return string.match(reAsciiWord) || []; -} - -var _asciiWords = asciiWords; - -/** Used to detect strings that need a more robust regexp to match words. */ -var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - -/** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ -function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); -} - -var _hasUnicodeWord = hasUnicodeWord; - -/** Used to compose unicode character classes. */ -var rsAstralRange$2 = '\\ud800-\\udfff', - rsComboMarksRange$3 = '\\u0300-\\u036f', - reComboHalfMarksRange$3 = '\\ufe20-\\ufe2f', - rsComboSymbolsRange$3 = '\\u20d0-\\u20ff', - rsComboRange$3 = rsComboMarksRange$3 + reComboHalfMarksRange$3 + rsComboSymbolsRange$3, - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange$2 = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - -/** Used to compose unicode capture groups. */ -var rsApos = "['\u2019]", - rsBreak = '[' + rsBreakRange + ']', - rsCombo$2 = '[' + rsComboRange$3 + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange$2 + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz$1 = '\\ud83c[\\udffb-\\udfff]', - rsModifier$1 = '(?:' + rsCombo$2 + '|' + rsFitz$1 + ')', - rsNonAstral$1 = '[^' + rsAstralRange$2 + ']', - rsRegional$1 = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair$1 = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ$2 = '\\u200d'; - -/** Used to compose unicode regexes. */ -var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', - rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod$1 = rsModifier$1 + '?', - rsOptVar$1 = '[' + rsVarRange$2 + ']?', - rsOptJoin$1 = '(?:' + rsZWJ$2 + '(?:' + [rsNonAstral$1, rsRegional$1, rsSurrPair$1].join('|') + ')' + rsOptVar$1 + reOptMod$1 + ')*', - rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', - rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', - rsSeq$1 = rsOptVar$1 + reOptMod$1 + rsOptJoin$1, - rsEmoji = '(?:' + [rsDingbat, rsRegional$1, rsSurrPair$1].join('|') + ')' + rsSeq$1; - -/** Used to match complex or compound words. */ -var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', - rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, - rsUpper + '+' + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji -].join('|'), 'g'); - -/** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ -function unicodeWords(string) { - return string.match(reUnicodeWord) || []; -} - -var _unicodeWords = unicodeWords; - -/** - * Splits `string` into an array of its words. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {RegExp|string} [pattern] The pattern to match words. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the words of `string`. - * @example - * - * _.words('fred, barney, & pebbles'); - * // => ['fred', 'barney', 'pebbles'] - * - * _.words('fred, barney, & pebbles', /[^, ]+/g); - * // => ['fred', 'barney', '&', 'pebbles'] - */ -function words(string, pattern, guard) { - string = toString_1(string); - pattern = guard ? undefined : pattern; - - if (pattern === undefined) { - return _hasUnicodeWord(string) ? _unicodeWords(string) : _asciiWords(string); - } - return string.match(pattern) || []; -} - -var words_1 = words; - -/** Used to compose unicode capture groups. */ -var rsApos$1 = "['\u2019]"; - -/** Used to match apostrophes. */ -var reApos = RegExp(rsApos$1, 'g'); - -/** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ -function createCompounder(callback) { - return function(string) { - return _arrayReduce(words_1(deburr_1(string).replace(reApos, '')), callback, ''); - }; -} - -var _createCompounder = createCompounder; - -/** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. - * @example - * - * _.camelCase('Foo Bar'); - * // => 'fooBar' - * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' - * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' - */ -var camelCase = _createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize_1(word) : word); -}); - -var camelCase_1 = camelCase; - -/** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ -function arrayEvery(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; -} - -var _arrayEvery = arrayEvery; - -/** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ -function baseEvery(collection, predicate) { - var result = true; - _baseEach(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; -} - -var _baseEvery = baseEvery; - -/** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false - */ -function every(collection, predicate, guard) { - var func = isArray_1(collection) ? _arrayEvery : _baseEvery; - if (guard && _isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, _baseIteratee(predicate)); -} - -var every_1 = every; - -/** Built-in value references. */ -var getPrototype = _overArg(Object.getPrototypeOf, Object); - -var _getPrototype = getPrototype; - -/** `Object#toString` result references. */ -var objectTag$3 = '[object Object]'; - -/** Used for built-in method references. */ -var funcProto$2 = Function.prototype, - objectProto$f = Object.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString$2 = funcProto$2.toString; - -/** Used to check objects for own properties. */ -var hasOwnProperty$c = objectProto$f.hasOwnProperty; - -/** Used to infer the `Object` constructor. */ -var objectCtorString = funcToString$2.call(Object); - -/** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ -function isPlainObject(value) { - if (!isObjectLike_1(value) || _baseGetTag(value) != objectTag$3) { - return false; - } - var proto = _getPrototype(value); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty$c.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString$2.call(Ctor) == objectCtorString; -} - -var isPlainObject_1 = isPlainObject; - -/** Built-in value references. */ -var spreadableSymbol = _Symbol ? _Symbol.isConcatSpreadable : undefined; - -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable(value) { - return isArray_1(value) || isArguments_1(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); -} - -var _isFlattenable = isFlattenable; - -/** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ -function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = _isFlattenable); - result || (result = []); - - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - _arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; -} - -var _baseFlatten = baseFlatten; - -/** Used as references for various `Number` constants. */ -var INFINITY$2 = 1 / 0; - -/** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } - * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ -function flatMapDeep(collection, iteratee) { - return _baseFlatten(map_1(collection, iteratee), INFINITY$2); -} - -var flatMapDeep_1 = flatMapDeep; - -/** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ -function copyArray(source, array) { - var index = -1, - length = source.length; - - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; -} - -var _copyArray = copyArray; - -/** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to concatenate. - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. - * @example - * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); - * - * console.log(other); - * // => [1, 2, 3, [4]] - * - * console.log(array); - * // => [1] - */ -function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; - - while (index--) { - args[index - 1] = arguments[index]; - } - return _arrayPush(isArray_1(array) ? _copyArray(array) : [array], _baseFlatten(args, 1)); -} - -var concat_1 = concat; - -/** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [n, n]; - * } - * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] - */ -function flatMap(collection, iteratee) { - return _baseFlatten(map_1(collection, iteratee), 1); -} - -var flatMap_1 = flatMap; - -var interopRequireDefault = createCommonjsModule(function (module) { -function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { - "default": obj - }; -} - -module.exports = _interopRequireDefault; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var _typeof_1 = createCommonjsModule(function (module) { -function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - module.exports = _typeof = function _typeof(obj) { - return typeof obj; - }; - - module.exports["default"] = module.exports, module.exports.__esModule = true; - } else { - module.exports = _typeof = function _typeof(obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - - module.exports["default"] = module.exports, module.exports.__esModule = true; - } - - return _typeof(obj); -} - -module.exports = _typeof; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var interopRequireWildcard = createCommonjsModule(function (module) { -var _typeof = _typeof_1["default"]; - -function _getRequireWildcardCache() { - if (typeof WeakMap !== "function") return null; - var cache = new WeakMap(); - - _getRequireWildcardCache = function _getRequireWildcardCache() { - return cache; - }; - - return cache; -} - -function _interopRequireWildcard(obj) { - if (obj && obj.__esModule) { - return obj; - } - - if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { - return { - "default": obj - }; - } - - var cache = _getRequireWildcardCache(); - - if (cache && cache.has(obj)) { - return cache.get(obj); - } - - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - - newObj["default"] = obj; - - if (cache) { - cache.set(obj, newObj); - } - - return newObj; -} - -module.exports = _interopRequireWildcard; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var classCallCheck = createCommonjsModule(function (module) { -function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -} - -module.exports = _classCallCheck; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var createClass = createCommonjsModule(function (module) { -function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } -} - -function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; -} - -module.exports = _createClass; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var assertThisInitialized = createCommonjsModule(function (module) { -function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; -} - -module.exports = _assertThisInitialized; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var possibleConstructorReturn = createCommonjsModule(function (module) { -var _typeof = _typeof_1["default"]; - - - -function _possibleConstructorReturn(self, call) { - if (call && (_typeof(call) === "object" || typeof call === "function")) { - return call; - } - - return assertThisInitialized(self); -} - -module.exports = _possibleConstructorReturn; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var getPrototypeOf = createCommonjsModule(function (module) { -function _getPrototypeOf(o) { - module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - module.exports["default"] = module.exports, module.exports.__esModule = true; - return _getPrototypeOf(o); -} - -module.exports = _getPrototypeOf; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var setPrototypeOf = createCommonjsModule(function (module) { -function _setPrototypeOf(o, p) { - module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - module.exports["default"] = module.exports, module.exports.__esModule = true; - return _setPrototypeOf(o, p); -} - -module.exports = _setPrototypeOf; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var inherits = createCommonjsModule(function (module) { -function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) setPrototypeOf(subClass, superClass); -} - -module.exports = _inherits; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var isNativeFunction = createCommonjsModule(function (module) { -function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; -} - -module.exports = _isNativeFunction; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var isNativeReflectConstruct = createCommonjsModule(function (module) { -function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); - return true; - } catch (e) { - return false; - } -} - -module.exports = _isNativeReflectConstruct; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var construct = createCommonjsModule(function (module) { -function _construct(Parent, args, Class) { - if (isNativeReflectConstruct()) { - module.exports = _construct = Reflect.construct; - module.exports["default"] = module.exports, module.exports.__esModule = true; - } else { - module.exports = _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) setPrototypeOf(instance, Class.prototype); - return instance; - }; - - module.exports["default"] = module.exports, module.exports.__esModule = true; - } - - return _construct.apply(null, arguments); -} - -module.exports = _construct; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var wrapNativeSuper = createCommonjsModule(function (module) { -function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return construct(Class, arguments, getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return setPrototypeOf(Wrapper, Class); - }; - - module.exports["default"] = module.exports, module.exports.__esModule = true; - return _wrapNativeSuper(Class); -} - -module.exports = _wrapNativeSuper; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var error = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.newError = newError; -exports.PROTOCOL_ERROR = exports.SESSION_EXPIRED = exports.SERVICE_UNAVAILABLE = exports.Neo4jError = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _wrapNativeSuper2 = interopRequireDefault(wrapNativeSuper); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// A common place for constructing error objects, to keep them -// uniform across the driver surface. - -/** - * Error code representing complete loss of service. Used by {@link Neo4jError#code}. - * @type {string} - */ -var SERVICE_UNAVAILABLE = 'ServiceUnavailable'; -/** - * Error code representing transient loss of service. Used by {@link Neo4jError#code}. - * @type {string} - */ - -exports.SERVICE_UNAVAILABLE = SERVICE_UNAVAILABLE; -var SESSION_EXPIRED = 'SessionExpired'; -/** - * Error code representing serialization/deserialization issue in the Bolt protocol. Used by {@link Neo4jError#code}. - * @type {string} - */ - -exports.SESSION_EXPIRED = SESSION_EXPIRED; -var PROTOCOL_ERROR = 'ProtocolError'; -/** - * Create a new error from a message and error code - * @param message the error message - * @param code the error code - * @return {Neo4jError} an {@link Neo4jError} - * @private - */ - -exports.PROTOCOL_ERROR = PROTOCOL_ERROR; - -function newError(message) { - var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'N/A'; - // TODO: Idea is that we can check the code here and throw sub-classes - // of Neo4jError as appropriate - return new Neo4jError(message, code); -} -/** - * Class for all errors thrown/returned by the driver. - */ - - -var Neo4jError = -/*#__PURE__*/ -function (_Error) { - (0, _inherits2["default"])(Neo4jError, _Error); - - /** - * @constructor - * @param {string} message - The error message. - * @param {string} code - Optional error code. Will be populated when error originates in the database. - */ - function Neo4jError(message) { - var _this; - - var code = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'N/A'; - (0, _classCallCheck2["default"])(this, Neo4jError); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(Neo4jError).call(this, message)); - /** - * The error message - * @type {string} - */ - - _this.message = message; - /** - * Optional error code. Will be populated when error originates in the database. - * @type {string} - */ - - _this.code = code; - /** - * The name of the error. - * @type {string} - */ - - _this.name = 'Neo4jError'; - return _this; - } - - return Neo4jError; -}((0, _wrapNativeSuper2["default"])(Error)); - -exports.Neo4jError = Neo4jError; -}); - -var integer = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = exports.toString = exports.toNumber = exports.inSafeRange = exports.isInt = exports["int"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// 64-bit Integer library, originally from Long.js by dcodeIO -// https://github.com/dcodeIO/Long.js -// License Apache 2 - -/** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See exported functions for more convenient ways of operating integers. - * Use `int()` function to create new integers, `isInt()` to check if given object is integer, - * `inSafeRange()` to check if it is safe to convert given value to native number, - * `toNumber()` and `toString()` to convert given integer to number or string respectively. - * @access public - * @exports Integer - * @class A Integer class for representing a 64 bit two's-complement integer value. - * @param {number} low The low (signed) 32 bits of the long - * @param {number} high The high (signed) 32 bits of the long - * @constructor - */ -var Integer = -/*#__PURE__*/ -function () { - function Integer(low, high) { - (0, _classCallCheck2["default"])(this, Integer); - - /** - * The low 32 bits as a signed value. - * @type {number} - * @expose - */ - this.low = low | 0; - /** - * The high 32 bits as a signed value. - * @type {number} - * @expose - */ - - this.high = high | 0; - } // The internal representation of an Integer is the two given signed, 32-bit values. - // We use 32-bit pieces because these are the size of integers on which - // JavaScript performs bit-operations. For operations like addition and - // multiplication, we split each number into 16 bit pieces, which can easily be - // multiplied within JavaScript's floating-point representation without overflow - // or change in sign. - // - // In the algorithms below, we frequently reduce the negative case to the - // positive case by negating the input(s) and then post-processing the result. - // Note that we must ALWAYS check specially whether those values are MIN_VALUE - // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - // a positive number, it overflows back into a negative). Not handling this - // case would often result in infinite recursion. - // - // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from* - // methods on which they depend. - - - (0, _createClass2["default"])(Integer, [{ - key: "inSafeRange", - value: function inSafeRange() { - return this.greaterThanOrEqual(Integer.MIN_SAFE_VALUE) && this.lessThanOrEqual(Integer.MAX_SAFE_VALUE); - } - /** - * Converts the Integer to an exact javascript Number, assuming it is a 32 bit integer. - * @returns {number} - * @expose - */ - - }, { - key: "toInt", - value: function toInt() { - return this.low; - } - /** - * Converts the Integer to a the nearest floating-point representation of this value (double, 53 bit mantissa). - * @returns {number} - * @expose - */ - - }, { - key: "toNumber", - value: function toNumber() { - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - } - /** - * Converts the Integer to native number or -Infinity/+Infinity when it does not fit. - * @return {number} - * @package - */ - - }, { - key: "toNumberOrInfinity", - value: function toNumberOrInfinity() { - if (this.lessThan(Integer.MIN_SAFE_VALUE)) { - return Number.NEGATIVE_INFINITY; - } else if (this.greaterThan(Integer.MAX_SAFE_VALUE)) { - return Number.POSITIVE_INFINITY; - } else { - return this.toNumber(); - } - } - /** - * Converts the Integer to a string written in the specified radix. - * @param {number=} radix Radix (2-36), defaults to 10 - * @returns {string} - * @override - * @throws {RangeError} If `radix` is out of range - * @expose - */ - - }, { - key: "toString", - value: function toString(radix) { - radix = radix || 10; - - if (radix < 2 || radix > 36) { - throw RangeError('radix out of range: ' + radix); - } - - if (this.isZero()) { - return '0'; - } - - var rem; - - if (this.isNegative()) { - if (this.equals(Integer.MIN_VALUE)) { - // We need to change the Integer value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixInteger = Integer.fromNumber(radix); - var div = this.div(radixInteger); - rem = div.multiply(radixInteger).subtract(this); - return div.toString(radix) + rem.toInt().toString(radix); - } else { - return '-' + this.negate().toString(radix); - } - } // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - - - var radixToPower = Integer.fromNumber(Math.pow(radix, 6)); - rem = this; - var result = ''; - - while (true) { - var remDiv = rem.div(radixToPower); - var intval = rem.subtract(remDiv.multiply(radixToPower)).toInt() >>> 0; - var digits = intval.toString(radix); - rem = remDiv; - - if (rem.isZero()) { - return digits + result; - } else { - while (digits.length < 6) { - digits = '0' + digits; - } - - result = '' + digits + result; - } - } - } - /** - * Gets the high 32 bits as a signed integer. - * @returns {number} Signed high bits - * @expose - */ - - }, { - key: "getHighBits", - value: function getHighBits() { - return this.high; - } - /** - * Gets the low 32 bits as a signed integer. - * @returns {number} Signed low bits - * @expose - */ - - }, { - key: "getLowBits", - value: function getLowBits() { - return this.low; - } - /** - * Gets the number of bits needed to represent the absolute value of this Integer. - * @returns {number} - * @expose - */ - - }, { - key: "getNumBitsAbs", - value: function getNumBitsAbs() { - if (this.isNegative()) { - return this.equals(Integer.MIN_VALUE) ? 64 : this.negate().getNumBitsAbs(); - } - - var val = this.high !== 0 ? this.high : this.low; - - for (var bit = 31; bit > 0; bit--) { - if ((val & 1 << bit) !== 0) { - break; - } - } - - return this.high !== 0 ? bit + 33 : bit + 1; - } - /** - * Tests if this Integer's value equals zero. - * @returns {boolean} - * @expose - */ - - }, { - key: "isZero", - value: function isZero() { - return this.high === 0 && this.low === 0; - } - /** - * Tests if this Integer's value is negative. - * @returns {boolean} - * @expose - */ - - }, { - key: "isNegative", - value: function isNegative() { - return this.high < 0; - } - /** - * Tests if this Integer's value is positive. - * @returns {boolean} - * @expose - */ - - }, { - key: "isPositive", - value: function isPositive() { - return this.high >= 0; - } - /** - * Tests if this Integer's value is odd. - * @returns {boolean} - * @expose - */ - - }, { - key: "isOdd", - value: function isOdd() { - return (this.low & 1) === 1; - } - /** - * Tests if this Integer's value is even. - * @returns {boolean} - * @expose - */ - - }, { - key: "isEven", - value: function isEven() { - return (this.low & 1) === 0; - } - /** - * Tests if this Integer's value equals the specified's. - * @param {!Integer|number|string} other Other value - * @returns {boolean} - * @expose - */ - - }, { - key: "equals", - value: function equals(other) { - if (!Integer.isInteger(other)) { - other = Integer.fromValue(other); - } - - return this.high === other.high && this.low === other.low; - } - /** - * Tests if this Integer's value differs from the specified's. - * @param {!Integer|number|string} other Other value - * @returns {boolean} - * @expose - */ - - }, { - key: "notEquals", - value: function notEquals(other) { - return !this.equals( - /* validates */ - other); - } - /** - * Tests if this Integer's value is less than the specified's. - * @param {!Integer|number|string} other Other value - * @returns {boolean} - * @expose - */ - - }, { - key: "lessThan", - value: function lessThan(other) { - return this.compare( - /* validates */ - other) < 0; - } - /** - * Tests if this Integer's value is less than or equal the specified's. - * @param {!Integer|number|string} other Other value - * @returns {boolean} - * @expose - */ - - }, { - key: "lessThanOrEqual", - value: function lessThanOrEqual(other) { - return this.compare( - /* validates */ - other) <= 0; - } - /** - * Tests if this Integer's value is greater than the specified's. - * @param {!Integer|number|string} other Other value - * @returns {boolean} - * @expose - */ - - }, { - key: "greaterThan", - value: function greaterThan(other) { - return this.compare( - /* validates */ - other) > 0; - } - /** - * Tests if this Integer's value is greater than or equal the specified's. - * @param {!Integer|number|string} other Other value - * @returns {boolean} - * @expose - */ - - }, { - key: "greaterThanOrEqual", - value: function greaterThanOrEqual(other) { - return this.compare( - /* validates */ - other) >= 0; - } - /** - * Compares this Integer's value with the specified's. - * @param {!Integer|number|string} other Other value - * @returns {number} 0 if they are the same, 1 if the this is greater and -1 - * if the given one is greater - * @expose - */ - - }, { - key: "compare", - value: function compare(other) { - if (!Integer.isInteger(other)) { - other = Integer.fromValue(other); - } - - if (this.equals(other)) { - return 0; - } - - var thisNeg = this.isNegative(); - var otherNeg = other.isNegative(); - - if (thisNeg && !otherNeg) { - return -1; - } - - if (!thisNeg && otherNeg) { - return 1; - } // At this point the sign bits are the same - - - return this.subtract(other).isNegative() ? -1 : 1; - } - /** - * Negates this Integer's value. - * @returns {!Integer} Negated Integer - * @expose - */ - - }, { - key: "negate", - value: function negate() { - if (this.equals(Integer.MIN_VALUE)) { - return Integer.MIN_VALUE; - } - - return this.not().add(Integer.ONE); - } - /** - * Returns the sum of this and the specified Integer. - * @param {!Integer|number|string} addend Addend - * @returns {!Integer} Sum - * @expose - */ - - }, { - key: "add", - value: function add(addend) { - if (!Integer.isInteger(addend)) { - addend = Integer.fromValue(addend); - } // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = addend.high >>> 16; - var b32 = addend.high & 0xffff; - var b16 = addend.low >>> 16; - var b00 = addend.low & 0xffff; - var c48 = 0; - var c32 = 0; - var c16 = 0; - var c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return Integer.fromBits(c16 << 16 | c00, c48 << 16 | c32); - } - /** - * Returns the difference of this and the specified Integer. - * @param {!Integer|number|string} subtrahend Subtrahend - * @returns {!Integer} Difference - * @expose - */ - - }, { - key: "subtract", - value: function subtract(subtrahend) { - if (!Integer.isInteger(subtrahend)) { - subtrahend = Integer.fromValue(subtrahend); - } - - return this.add(subtrahend.negate()); - } - /** - * Returns the product of this and the specified Integer. - * @param {!Integer|number|string} multiplier Multiplier - * @returns {!Integer} Product - * @expose - */ - - }, { - key: "multiply", - value: function multiply(multiplier) { - if (this.isZero()) { - return Integer.ZERO; - } - - if (!Integer.isInteger(multiplier)) { - multiplier = Integer.fromValue(multiplier); - } - - if (multiplier.isZero()) { - return Integer.ZERO; - } - - if (this.equals(Integer.MIN_VALUE)) { - return multiplier.isOdd() ? Integer.MIN_VALUE : Integer.ZERO; - } - - if (multiplier.equals(Integer.MIN_VALUE)) { - return this.isOdd() ? Integer.MIN_VALUE : Integer.ZERO; - } - - if (this.isNegative()) { - if (multiplier.isNegative()) { - return this.negate().multiply(multiplier.negate()); - } else { - return this.negate().multiply(multiplier).negate(); - } - } else if (multiplier.isNegative()) { - return this.multiply(multiplier.negate()).negate(); - } // If both longs are small, use float multiplication - - - if (this.lessThan(TWO_PWR_24) && multiplier.lessThan(TWO_PWR_24)) { - return Integer.fromNumber(this.toNumber() * multiplier.toNumber()); - } // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 0xffff; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 0xffff; - var c48 = 0; - var c32 = 0; - var c16 = 0; - var c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return Integer.fromBits(c16 << 16 | c00, c48 << 16 | c32); - } - /** - * Returns this Integer divided by the specified. - * @param {!Integer|number|string} divisor Divisor - * @returns {!Integer} Quotient - * @expose - */ - - }, { - key: "div", - value: function div(divisor) { - if (!Integer.isInteger(divisor)) { - divisor = Integer.fromValue(divisor); - } - - if (divisor.isZero()) { - throw (0, error.newError)('division by zero'); - } - - if (this.isZero()) { - return Integer.ZERO; - } - - var approx, rem, res; - - if (this.equals(Integer.MIN_VALUE)) { - if (divisor.equals(Integer.ONE) || divisor.equals(Integer.NEG_ONE)) { - return Integer.MIN_VALUE; - } - - if (divisor.equals(Integer.MIN_VALUE)) { - return Integer.ONE; - } else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shiftRight(1); - approx = halfThis.div(divisor).shiftLeft(1); - - if (approx.equals(Integer.ZERO)) { - return divisor.isNegative() ? Integer.ONE : Integer.NEG_ONE; - } else { - rem = this.subtract(divisor.multiply(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } else if (divisor.equals(Integer.MIN_VALUE)) { - return Integer.ZERO; - } - - if (this.isNegative()) { - if (divisor.isNegative()) { - return this.negate().div(divisor.negate()); - } - - return this.negate().div(divisor).negate(); - } else if (divisor.isNegative()) { - return this.div(divisor.negate()).negate(); - } // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - - - res = Integer.ZERO; - rem = this; - - while (rem.greaterThanOrEqual(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - - var log2 = Math.ceil(Math.log(approx) / Math.LN2); - var delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48); // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - - var approxRes = Integer.fromNumber(approx); - var approxRem = approxRes.multiply(divisor); - - while (approxRem.isNegative() || approxRem.greaterThan(rem)) { - approx -= delta; - approxRes = Integer.fromNumber(approx); - approxRem = approxRes.multiply(divisor); - } // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - - - if (approxRes.isZero()) { - approxRes = Integer.ONE; - } - - res = res.add(approxRes); - rem = rem.subtract(approxRem); - } - - return res; - } - /** - * Returns this Integer modulo the specified. - * @param {!Integer|number|string} divisor Divisor - * @returns {!Integer} Remainder - * @expose - */ - - }, { - key: "modulo", - value: function modulo(divisor) { - if (!Integer.isInteger(divisor)) { - divisor = Integer.fromValue(divisor); - } - - return this.subtract(this.div(divisor).multiply(divisor)); - } - /** - * Returns the bitwise NOT of this Integer. - * @returns {!Integer} - * @expose - */ - - }, { - key: "not", - value: function not() { - return Integer.fromBits(~this.low, ~this.high); - } - /** - * Returns the bitwise AND of this Integer and the specified. - * @param {!Integer|number|string} other Other Integer - * @returns {!Integer} - * @expose - */ - - }, { - key: "and", - value: function and(other) { - if (!Integer.isInteger(other)) { - other = Integer.fromValue(other); - } - - return Integer.fromBits(this.low & other.low, this.high & other.high); - } - /** - * Returns the bitwise OR of this Integer and the specified. - * @param {!Integer|number|string} other Other Integer - * @returns {!Integer} - * @expose - */ - - }, { - key: "or", - value: function or(other) { - if (!Integer.isInteger(other)) { - other = Integer.fromValue(other); - } - - return Integer.fromBits(this.low | other.low, this.high | other.high); - } - /** - * Returns the bitwise XOR of this Integer and the given one. - * @param {!Integer|number|string} other Other Integer - * @returns {!Integer} - * @expose - */ - - }, { - key: "xor", - value: function xor(other) { - if (!Integer.isInteger(other)) { - other = Integer.fromValue(other); - } - - return Integer.fromBits(this.low ^ other.low, this.high ^ other.high); - } - /** - * Returns this Integer with bits shifted to the left by the given amount. - * @param {number|!Integer} numBits Number of bits - * @returns {!Integer} Shifted Integer - * @expose - */ - - }, { - key: "shiftLeft", - value: function shiftLeft(numBits) { - if (Integer.isInteger(numBits)) { - numBits = numBits.toInt(); - } - - if ((numBits &= 63) === 0) { - return this; - } else if (numBits < 32) { - return Integer.fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits); - } else { - return Integer.fromBits(0, this.low << numBits - 32); - } - } - /** - * Returns this Integer with bits arithmetically shifted to the right by the given amount. - * @param {number|!Integer} numBits Number of bits - * @returns {!Integer} Shifted Integer - * @expose - */ - - }, { - key: "shiftRight", - value: function shiftRight(numBits) { - if (Integer.isInteger(numBits)) { - numBits = numBits.toInt(); - } - - if ((numBits &= 63) === 0) { - return this; - } else if (numBits < 32) { - return Integer.fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits); - } else { - return Integer.fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1); - } - } - }]); - return Integer; -}(); -/** - * An indicator used to reliably determine if an object is a Integer or not. - * @type {boolean} - * @const - * @expose - * @private - */ - - -Integer.__isInteger__ = true; -Object.defineProperty(Integer.prototype, '__isInteger__', { - value: true, - enumerable: false, - configurable: false -}); -/** - * Tests if the specified object is a Integer. - * @access private - * @param {*} obj Object - * @returns {boolean} - * @expose - */ - -Integer.isInteger = function (obj) { - return (obj && obj.__isInteger__) === true; -}; -/** - * A cache of the Integer representations of small integer values. - * @type {!Object} - * @inner - * @private - */ - - -var INT_CACHE = {}; -/** - * Returns a Integer representing the given 32 bit integer value. - * @access private - * @param {number} value The 32 bit integer in question - * @returns {!Integer} The corresponding Integer value - * @expose - */ - -Integer.fromInt = function (value) { - var obj, cachedObj; - value = value | 0; - - if (value >= -128 && value < 128) { - cachedObj = INT_CACHE[value]; - - if (cachedObj) { - return cachedObj; - } - } - - obj = new Integer(value, value < 0 ? -1 : 0, false); - - if (value >= -128 && value < 128) { - INT_CACHE[value] = obj; - } - - return obj; -}; -/** - * Returns a Integer representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @access private - * @param {number} value The number in question - * @returns {!Integer} The corresponding Integer value - * @expose - */ - - -Integer.fromNumber = function (value) { - if (isNaN(value) || !isFinite(value)) { - return Integer.ZERO; - } - - if (value <= -TWO_PWR_63_DBL) { - return Integer.MIN_VALUE; - } - - if (value + 1 >= TWO_PWR_63_DBL) { - return Integer.MAX_VALUE; - } - - if (value < 0) { - return Integer.fromNumber(-value).negate(); - } - - return new Integer(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0); -}; -/** - * Returns a Integer representing the 64 bit integer that comes by concatenating the given low and high bits. Each is - * assumed to use 32 bits. - * @access private - * @param {number} lowBits The low 32 bits - * @param {number} highBits The high 32 bits - * @returns {!Integer} The corresponding Integer value - * @expose - */ - - -Integer.fromBits = function (lowBits, highBits) { - return new Integer(lowBits, highBits); -}; -/** - * Returns a Integer representation of the given string, written using the specified radix. - * @access private - * @param {string} str The textual representation of the Integer - * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 - * @returns {!Integer} The corresponding Integer value - * @expose - */ - - -Integer.fromString = function (str, radix) { - if (str.length === 0) { - throw (0, error.newError)('number format error: empty string'); - } - - if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity') { - return Integer.ZERO; - } - - radix = radix || 10; - - if (radix < 2 || radix > 36) { - throw (0, error.newError)('radix out of range: ' + radix); - } - - var p; - - if ((p = str.indexOf('-')) > 0) { - throw (0, error.newError)('number format error: interior "-" character: ' + str); - } else if (p === 0) { - return Integer.fromString(str.substring(1), radix).negate(); - } // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - - - var radixToPower = Integer.fromNumber(Math.pow(radix, 8)); - var result = Integer.ZERO; - - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i); - var value = parseInt(str.substring(i, i + size), radix); - - if (size < 8) { - var power = Integer.fromNumber(Math.pow(radix, size)); - result = result.multiply(power).add(Integer.fromNumber(value)); - } else { - result = result.multiply(radixToPower); - result = result.add(Integer.fromNumber(value)); - } - } - - return result; -}; -/** - * Converts the specified value to a Integer. - * @access private - * @param {!Integer|number|string|!{low: number, high: number}} val Value - * @returns {!Integer} - * @expose - */ - - -Integer.fromValue = function (val) { - if (val - /* is compatible */ - instanceof Integer) { - return val; - } - - if (typeof val === 'number') { - return Integer.fromNumber(val); - } - - if (typeof val === 'string') { - return Integer.fromString(val); - } // Throws for non-objects, converts non-instanceof Integer: - - - return new Integer(val.low, val.high); -}; -/** - * Converts the specified value to a number. - * @access private - * @param {!Integer|number|string|!{low: number, high: number}} val Value - * @returns {number} - * @expose - */ - - -Integer.toNumber = function (val) { - return Integer.fromValue(val).toNumber(); -}; -/** - * Converts the specified value to a string. - * @access private - * @param {!Integer|number|string|!{low: number, high: number}} val Value - * @param {number} radix optional radix for string conversion, defaults to 10 - * @returns {string} - * @expose - */ - - -Integer.toString = function (val, radix) { - return Integer.fromValue(val).toString(radix); -}; -/** - * Checks if the given value is in the safe range in order to be converted to a native number - * @access private - * @param {!Integer|number|string|!{low: number, high: number}} val Value - * @param {number} radix optional radix for string conversion, defaults to 10 - * @returns {boolean} - * @expose - */ - - -Integer.inSafeRange = function (val) { - return Integer.fromValue(val).inSafeRange(); -}; -/** - * @type {number} - * @const - * @inner - * @private - */ - - -var TWO_PWR_16_DBL = 1 << 16; -/** - * @type {number} - * @const - * @inner - * @private - */ - -var TWO_PWR_24_DBL = 1 << 24; -/** - * @type {number} - * @const - * @inner - * @private - */ - -var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; -/** - * @type {number} - * @const - * @inner - * @private - */ - -var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; -/** - * @type {number} - * @const - * @inner - * @private - */ - -var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; -/** - * @type {!Integer} - * @const - * @inner - * @private - */ - -var TWO_PWR_24 = Integer.fromInt(TWO_PWR_24_DBL); -/** - * Signed zero. - * @type {!Integer} - * @expose - */ - -Integer.ZERO = Integer.fromInt(0); -/** - * Signed one. - * @type {!Integer} - * @expose - */ - -Integer.ONE = Integer.fromInt(1); -/** - * Signed negative one. - * @type {!Integer} - * @expose - */ - -Integer.NEG_ONE = Integer.fromInt(-1); -/** - * Maximum signed value. - * @type {!Integer} - * @expose - */ - -Integer.MAX_VALUE = Integer.fromBits(0xffffffff | 0, 0x7fffffff | 0, false); -/** - * Minimum signed value. - * @type {!Integer} - * @expose - */ - -Integer.MIN_VALUE = Integer.fromBits(0, 0x80000000 | 0, false); -/** - * Minimum safe value. - * @type {!Integer} - * @expose - */ - -Integer.MIN_SAFE_VALUE = Integer.fromBits(0x1 | 0, 0xffffffffffe00000 | 0); -/** - * Maximum safe value. - * @type {!Integer} - * @expose - */ - -Integer.MAX_SAFE_VALUE = Integer.fromBits(0xffffffff | 0, 0x1fffff | 0); -/** - * Cast value to Integer type. - * @access public - * @param {Mixed} value - The value to use. - * @return {Integer} - An object of type Integer. - */ - -var _int = Integer.fromValue; -/** - * Check if a variable is of Integer type. - * @access public - * @param {Mixed} value - The variable to check. - * @return {Boolean} - Is it of the Integer type? - */ - -exports["int"] = _int; -var isInt = Integer.isInteger; -/** - * Check if a variable can be safely converted to a number - * @access public - * @param {Mixed} value - The variable to check - * @return {Boolean} - true if it is safe to call toNumber on variable otherwise false - */ - -exports.isInt = isInt; -var inSafeRange = Integer.inSafeRange; -/** - * Converts a variable to a number - * @access public - * @param {Mixed} value - The variable to convert - * @return {number} - the variable as a number - */ - -exports.inSafeRange = inSafeRange; -var toNumber = Integer.toNumber; -/** - * Converts the integer to a string representation - * @access public - * @param {Mixed} value - The variable to convert - * @param {number} radix - radix to use in string conversion, defaults to 10 - * @return {string} - returns a string representation of the integer - */ - -exports.toNumber = toNumber; -var toString = Integer.toString; -exports.toString = toString; -var _default = Integer; -exports["default"] = _default; -}); - -var graphTypes = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isNode = isNode; -exports.isRelationship = isRelationship; -exports.isUnboundRelationship = isUnboundRelationship; -exports.isPath = isPath; -exports.isPathSegment = isPathSegment; -exports.PathSegment = exports.Path = exports.UnboundRelationship = exports.Relationship = exports.Node = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var IDENTIFIER_PROPERTY_ATTRIBUTES = { - value: true, - enumerable: false, - configurable: false, - writable: false -}; -var NODE_IDENTIFIER_PROPERTY = '__isNode__'; -var RELATIONSHIP_IDENTIFIER_PROPERTY = '__isRelationship__'; -var UNBOUND_RELATIONSHIP_IDENTIFIER_PROPERTY = '__isUnboundRelationship__'; -var PATH_IDENTIFIER_PROPERTY = '__isPath__'; -var PATH_SEGMENT_IDENTIFIER_PROPERTY = '__isPathSegment__'; - -function hasIdentifierProperty(obj, property) { - return (obj && obj[property]) === true; -} -/** - * Class for Node Type. - */ - - -var Node = -/*#__PURE__*/ -function () { - /** - * @constructor - * @protected - * @param {Integer} identity - Unique identity - * @param {Array} labels - Array for all labels - * @param {Object} properties - Map with node properties - */ - function Node(identity, labels, properties) { - (0, _classCallCheck2["default"])(this, Node); - - /** - * Identity of the node. - * @type {Integer} - */ - this.identity = identity; - /** - * Labels of the node. - * @type {string[]} - */ - - this.labels = labels; - /** - * Properties of the node. - * @type {Object} - */ - - this.properties = properties; - } - /** - * @ignore - */ - - - (0, _createClass2["default"])(Node, [{ - key: "toString", - value: function toString() { - var s = '(' + this.identity; - - for (var i = 0; i < this.labels.length; i++) { - s += ':' + this.labels[i]; - } - - var keys = Object.keys(this.properties); - - if (keys.length > 0) { - s += ' {'; - - for (var _i = 0; _i < keys.length; _i++) { - if (_i > 0) s += ','; - s += keys[_i] + ':' + JSON.stringify(this.properties[keys[_i]]); - } - - s += '}'; - } - - s += ')'; - return s; - } - }]); - return Node; -}(); - -exports.Node = Node; -Object.defineProperty(Node.prototype, NODE_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); -/** - * Test if given object is an instance of {@link Node} class. - * @param {Object} obj the object to test. - * @return {boolean} `true` if given object is a {@link Node}, `false` otherwise. - */ - -function isNode(obj) { - return hasIdentifierProperty(obj, NODE_IDENTIFIER_PROPERTY); -} -/** - * Class for Relationship Type. - */ - - -var Relationship = -/*#__PURE__*/ -function () { - /** - * @constructor - * @protected - * @param {Integer} identity - Unique identity - * @param {Integer} start - Identity of start Node - * @param {Integer} end - Identity of end Node - * @param {string} type - Relationship type - * @param {Object} properties - Map with relationship properties - */ - function Relationship(identity, start, end, type, properties) { - (0, _classCallCheck2["default"])(this, Relationship); - - /** - * Identity of the relationship. - * @type {Integer} - */ - this.identity = identity; - /** - * Identity of the start node. - * @type {Integer} - */ - - this.start = start; - /** - * Identity of the end node. - * @type {Integer} - */ - - this.end = end; - /** - * Type of the relationship. - * @type {string} - */ - - this.type = type; - /** - * Properties of the relationship. - * @type {Object} - */ - - this.properties = properties; - } - /** - * @ignore - */ - - - (0, _createClass2["default"])(Relationship, [{ - key: "toString", - value: function toString() { - var s = '(' + this.start + ')-[:' + this.type; - var keys = Object.keys(this.properties); - - if (keys.length > 0) { - s += ' {'; - - for (var i = 0; i < keys.length; i++) { - if (i > 0) s += ','; - s += keys[i] + ':' + JSON.stringify(this.properties[keys[i]]); - } - - s += '}'; - } - - s += ']->(' + this.end + ')'; - return s; - } - }]); - return Relationship; -}(); - -exports.Relationship = Relationship; -Object.defineProperty(Relationship.prototype, RELATIONSHIP_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); -/** - * Test if given object is an instance of {@link Relationship} class. - * @param {Object} obj the object to test. - * @return {boolean} `true` if given object is a {@link Relationship}, `false` otherwise. - */ - -function isRelationship(obj) { - return hasIdentifierProperty(obj, RELATIONSHIP_IDENTIFIER_PROPERTY); -} -/** - * Class for UnboundRelationship Type. - * @access private - */ - - -var UnboundRelationship = -/*#__PURE__*/ -function () { - /** - * @constructor - * @protected - * @param {Integer} identity - Unique identity - * @param {string} type - Relationship type - * @param {Object} properties - Map with relationship properties - */ - function UnboundRelationship(identity, type, properties) { - (0, _classCallCheck2["default"])(this, UnboundRelationship); - - /** - * Identity of the relationship. - * @type {Integer} - */ - this.identity = identity; - /** - * Type of the relationship. - * @type {string} - */ - - this.type = type; - /** - * Properties of the relationship. - * @type {Object} - */ - - this.properties = properties; - } - /** - * Bind relationship - * - * @protected - * @param {Integer} start - Identity of start node - * @param {Integer} end - Identity of end node - * @return {Relationship} - Created relationship - */ - - - (0, _createClass2["default"])(UnboundRelationship, [{ - key: "bind", - value: function bind(start, end) { - return new Relationship(this.identity, start, end, this.type, this.properties); - } - /** - * @ignore - */ - - }, { - key: "toString", - value: function toString() { - var s = '-[:' + this.type; - var keys = Object.keys(this.properties); - - if (keys.length > 0) { - s += ' {'; - - for (var i = 0; i < keys.length; i++) { - if (i > 0) s += ','; - s += keys[i] + ':' + JSON.stringify(this.properties[keys[i]]); - } - - s += '}'; - } - - s += ']->'; - return s; - } - }]); - return UnboundRelationship; -}(); - -exports.UnboundRelationship = UnboundRelationship; -Object.defineProperty(UnboundRelationship.prototype, UNBOUND_RELATIONSHIP_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); -/** - * Test if given object is an instance of {@link UnboundRelationship} class. - * @param {Object} obj the object to test. - * @return {boolean} `true` if given object is a {@link UnboundRelationship}, `false` otherwise. - */ - -function isUnboundRelationship(obj) { - return hasIdentifierProperty(obj, UNBOUNT_RELATIONSHIP_IDENTIFIER_PROPERTY); -} -/** - * Class for PathSegment Type. - */ - - -var PathSegment = -/** - * @constructor - * @protected - * @param {Node} start - start node - * @param {Relationship} rel - relationship that connects start and end node - * @param {Node} end - end node - */ -function PathSegment(start, rel, end) { - (0, _classCallCheck2["default"])(this, PathSegment); - - /** - * Start node. - * @type {Node} - */ - this.start = start; - /** - * Relationship. - * @type {Relationship} - */ - - this.relationship = rel; - /** - * End node. - * @type {Node} - */ - - this.end = end; -}; - -exports.PathSegment = PathSegment; -Object.defineProperty(PathSegment.prototype, PATH_SEGMENT_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); -/** - * Test if given object is an instance of {@link PathSegment} class. - * @param {Object} obj the object to test. - * @return {boolean} `true` if given object is a {@link PathSegment}, `false` otherwise. - */ - -function isPathSegment(obj) { - return hasIdentifierProperty(obj, PATH_SEGMENT_IDENTIFIER_PROPERTY); -} -/** - * Class for Path Type. - */ - - -var Path = -/** - * @constructor - * @protected - * @param {Node} start - start node - * @param {Node} end - end node - * @param {Array} segments - Array of Segments - */ -function Path(start, end, segments) { - (0, _classCallCheck2["default"])(this, Path); - - /** - * Start node. - * @type {Node} - */ - this.start = start; - /** - * End node. - * @type {Node} - */ - - this.end = end; - /** - * Segments. - * @type {Array} - */ - - this.segments = segments; - /** - * Length of the segments. - * @type {Number} - */ - - this.length = segments.length; -}; - -exports.Path = Path; -Object.defineProperty(Path.prototype, PATH_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); -/** - * Test if given object is an instance of {@link Path} class. - * @param {Object} obj the object to test. - * @return {boolean} `true` if given object is a {@link Path}, `false` otherwise. - */ - -function isPath(obj) { - return hasIdentifierProperty(obj, PATH_IDENTIFIER_PROPERTY); -} -}); - -var resultSummary = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = exports.queryType = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * A ResultSummary instance contains structured metadata for a {@link Result}. - * @access public - */ -var ResultSummary = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {string} query - The query this summary is for - * @param {Object} parameters - Parameters for the query - * @param {Object} metadata - Query metadata - * @param {number} protocolVersion - Bolt protocol version - */ - function ResultSummary(query, parameters, metadata, protocolVersion) { - (0, _classCallCheck2["default"])(this, ResultSummary); - - /** - * The query and parameters this summary is for. - * @type {{text: string, parameters: Object}} - * @public - */ - this.query = { - text: query, - parameters: parameters - /** - * The type of query executed. Can be "r" for read-only query, "rw" for read-write query, - * "w" for write-only query and "s" for schema-write query. - * String constants are available in {@link queryType} object. - * @type {string} - * @public - */ - - }; - this.queryType = metadata.type; - /** - * Counters for operations the query triggered. - * @type {QueryStatistics} - * @public - */ - - this.counters = new QueryStatistics(metadata.stats || {}); // for backwards compatibility, remove in future version - - /** - * Use {@link ResultSummary.counters} instead. - * @type {QueryStatistics} - * @deprecated - */ - - this.updateStatistics = this.counters; - /** - * This describes how the database will execute the query. - * Query plan for the executed query if available, otherwise undefined. - * Will only be populated for queries that start with "EXPLAIN". - * @type {Plan} - * @public - */ - - this.plan = metadata.plan || metadata.profile ? new Plan(metadata.plan || metadata.profile) : false; - /** - * This describes how the database did execute your query. This will contain detailed information about what - * each step of the plan did. Profiled query plan for the executed query if available, otherwise undefined. - * Will only be populated for queries that start with "PROFILE". - * @type {ProfiledPlan} - * @public - */ - - this.profile = metadata.profile ? new ProfiledPlan(metadata.profile) : false; - /** - * An array of notifications that might arise when executing the query. Notifications can be warnings about - * problematic queries or other valuable information that can be presented in a client. Unlike failures - * or errors, notifications do not affect the execution of a query. - * @type {Array} - * @public - */ - - this.notifications = this._buildNotifications(metadata.notifications); - /** - * The basic information of the server where the result is obtained from. - * @type {ServerInfo} - * @public - */ - - this.server = new ServerInfo(metadata.server, protocolVersion); - /** - * The time it took the server to consume the result. - * @type {number} - * @public - */ - - this.resultConsumedAfter = metadata.result_consumed_after; - /** - * The time it took the server to make the result available for consumption in milliseconds. - * @type {number} - * @public - */ - - this.resultAvailableAfter = metadata.result_available_after; - /** - * The database name where this summary is obtained from. - * @type {{name: string}} - * @public - */ - - this.database = { - name: metadata.db || null - }; - } - - (0, _createClass2["default"])(ResultSummary, [{ - key: "_buildNotifications", - value: function _buildNotifications(notifications) { - if (!notifications) { - return []; - } - - return notifications.map(function (n) { - return new Notification(n); - }); - } - /** - * Check if the result summary has a plan - * @return {boolean} - */ - - }, { - key: "hasPlan", - value: function hasPlan() { - return this.plan instanceof Plan; - } - /** - * Check if the result summary has a profile - * @return {boolean} - */ - - }, { - key: "hasProfile", - value: function hasProfile() { - return this.profile instanceof ProfiledPlan; - } - }]); - return ResultSummary; -}(); -/** - * Class for execution plan received by prepending Cypher with EXPLAIN. - * @access public - */ - - -var Plan = -/** - * Create a Plan instance - * @constructor - * @param {Object} plan - Object with plan data - */ -function Plan(plan) { - (0, _classCallCheck2["default"])(this, Plan); - this.operatorType = plan.operatorType; - this.identifiers = plan.identifiers; - this.arguments = plan.args; - this.children = plan.children ? plan.children.map(function (child) { - return new Plan(child); - }) : []; -}; -/** - * Class for execution plan received by prepending Cypher with PROFILE. - * @access public - */ - - -var ProfiledPlan = -/*#__PURE__*/ -function () { - /** - * Create a ProfiledPlan instance - * @constructor - * @param {Object} profile - Object with profile data - */ - function ProfiledPlan(profile) { - (0, _classCallCheck2["default"])(this, ProfiledPlan); - this.operatorType = profile.operatorType; - this.identifiers = profile.identifiers; - this.arguments = profile.args; - this.dbHits = valueOrDefault('dbHits', profile); - this.rows = valueOrDefault('rows', profile); - this.pageCacheMisses = valueOrDefault('pageCacheMisses', profile); - this.pageCacheHits = valueOrDefault('pageCacheHits', profile); - this.pageCacheHitRatio = valueOrDefault('pageCacheHitRatio', profile); - this.time = valueOrDefault('time', profile); - this.children = profile.children ? profile.children.map(function (child) { - return new ProfiledPlan(child); - }) : []; - } - - (0, _createClass2["default"])(ProfiledPlan, [{ - key: "hasPageCacheStats", - value: function hasPageCacheStats() { - return this.pageCacheMisses > 0 || this.pageCacheHits > 0 || this.pageCacheHitRatio > 0; - } - }]); - return ProfiledPlan; -}(); -/** - * Get statistical information for a {@link Result}. - * @access public - */ - - -var QueryStatistics = -/*#__PURE__*/ -function () { - /** - * Structurize the statistics - * @constructor - * @param {Object} statistics - Result statistics - */ - function QueryStatistics(statistics) { - var _this = this; - - (0, _classCallCheck2["default"])(this, QueryStatistics); - this._stats = { - nodesCreated: 0, - nodesDeleted: 0, - relationshipsCreated: 0, - relationshipsDeleted: 0, - propertiesSet: 0, - labelsAdded: 0, - labelsRemoved: 0, - indexesAdded: 0, - indexesRemoved: 0, - constraintsAdded: 0, - constraintsRemoved: 0 - }; - this._systemUpdates = 0; - Object.keys(statistics).forEach(function (index) { - // To camelCase - var camelCaseIndex = index.replace(/(-\w)/g, function (m) { - return m[1].toUpperCase(); - }); - - if (camelCaseIndex in _this._stats) { - _this._stats[camelCaseIndex] = intValue(statistics[index]); - } else if (camelCaseIndex === 'systemUpdates') { - _this._systemUpdates = intValue(statistics[index]); - } - }); - this._stats = Object.freeze(this._stats); - } - /** - * Did the database get updated? - * @return {boolean} - */ - - - (0, _createClass2["default"])(QueryStatistics, [{ - key: "containsUpdates", - value: function containsUpdates() { - var _this2 = this; - - return Object.keys(this._stats).reduce(function (last, current) { - return last + _this2._stats[current]; - }, 0) > 0; - } - /** - * Returns the query statistics updates in a dictionary. - * @returns {*} - */ - - }, { - key: "updates", - value: function updates() { - return this._stats; - } - /** - * Return true if the system database get updated, otherwise false - * @returns {boolean} - If the system database get updated or not. - */ - - }, { - key: "containsSystemUpdates", - value: function containsSystemUpdates() { - return this._systemUpdates > 0; - } - /** - * @returns {number} - Number of system updates - */ - - }, { - key: "systemUpdates", - value: function systemUpdates() { - return this._systemUpdates; - } - }]); - return QueryStatistics; -}(); -/** - * Class for Cypher notifications - * @access public - */ - - -var Notification = -/*#__PURE__*/ -function () { - /** - * Create a Notification instance - * @constructor - * @param {Object} notification - Object with notification data - */ - function Notification(notification) { - (0, _classCallCheck2["default"])(this, Notification); - this.code = notification.code; - this.title = notification.title; - this.description = notification.description; - this.severity = notification.severity; - this.position = Notification._constructPosition(notification.position); - } - - (0, _createClass2["default"])(Notification, null, [{ - key: "_constructPosition", - value: function _constructPosition(pos) { - if (!pos) { - return {}; - } - - return { - offset: intValue(pos.offset), - line: intValue(pos.line), - column: intValue(pos.column) - }; - } - }]); - return Notification; -}(); -/** - * Class for exposing server info from a result. - * @access public - */ - - -var ServerInfo = -/** - * Create a ServerInfo instance - * @constructor - * @param {Object} serverMeta - Object with serverMeta data - * @param {number} protocolVersion - Bolt protocol version - */ -function ServerInfo(serverMeta, protocolVersion) { - (0, _classCallCheck2["default"])(this, ServerInfo); - - if (serverMeta) { - this.address = serverMeta.address; - this.version = serverMeta.version; - } - - this.protocolVersion = protocolVersion; -}; - -function intValue(value) { - return (0, integer.isInt)(value) ? value.toInt() : value; -} - -function valueOrDefault(key, values) { - var defaultValue = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; - - if (key in values) { - var value = values[key]; - return (0, integer.isInt)(value) ? value.toInt() : value; - } else { - return defaultValue; - } -} -/** - * The constants for query types - * @type {{SCHEMA_WRITE: string, WRITE_ONLY: string, READ_ONLY: string, READ_WRITE: string}} - */ - - -var queryType = { - READ_ONLY: 'r', - READ_WRITE: 'rw', - WRITE_ONLY: 'w', - SCHEMA_WRITE: 's' -}; -exports.queryType = queryType; -var _default = ResultSummary; -exports["default"] = _default; -}); - -var util = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isEmptyObjectOrNull = isEmptyObjectOrNull; -exports.isObject = isObject; -exports.isString = isString; -exports.assertObject = assertObject; -exports.assertString = assertString; -exports.assertNumber = assertNumber; -exports.assertNumberOrInteger = assertNumberOrInteger; -exports.assertValidDate = assertValidDate; -exports.validateQueryAndParameters = validateQueryAndParameters; -exports.ENCRYPTION_OFF = exports.ENCRYPTION_ON = void 0; - -var _typeof2 = interopRequireDefault(_typeof_1); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var ENCRYPTION_ON = 'ENCRYPTION_ON'; -exports.ENCRYPTION_ON = ENCRYPTION_ON; -var ENCRYPTION_OFF = 'ENCRYPTION_OFF'; -exports.ENCRYPTION_OFF = ENCRYPTION_OFF; - -function isEmptyObjectOrNull(obj) { - if (obj === null) { - return true; - } - - if (!isObject(obj)) { - return false; - } - - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { - return false; - } - } - - return true; -} - -function isObject(obj) { - return (0, _typeof2["default"])(obj) === 'object' && !Array.isArray(obj) && obj !== null; -} -/** - * Check and normalize given query and parameters. - * @param {string|{text: string, parameters: object}} query the query to check. - * @param {Object} parameters - * @return {{query: string, params: object}} the normalized query with parameters. - * @throws TypeError when either given query or parameters are invalid. - */ - - -function validateQueryAndParameters(query, parameters) { - var validatedQuery = query; - var params = parameters || {}; - - if ((0, _typeof2["default"])(query) === 'object' && query.text) { - validatedQuery = query.text; - params = query.parameters || {}; - } - - assertCypherQuery(validatedQuery); - assertQueryParameters(params); - return { - validatedQuery: validatedQuery, - params: params - }; -} - -function assertObject(obj, objName) { - if (!isObject(obj)) { - throw new TypeError(objName + ' expected to be an object but was: ' + JSON.stringify(obj)); - } - - return obj; -} - -function assertString(obj, objName) { - if (!isString(obj)) { - throw new TypeError(objName + ' expected to be string but was: ' + JSON.stringify(obj)); - } - - return obj; -} - -function assertNumber(obj, objName) { - if (typeof obj !== 'number') { - throw new TypeError(objName + ' expected to be a number but was: ' + JSON.stringify(obj)); - } - - return obj; -} - -function assertNumberOrInteger(obj, objName) { - if (typeof obj !== 'number' && !(0, integer.isInt)(obj)) { - throw new TypeError(objName + ' expected to be either a number or an Integer object but was: ' + JSON.stringify(obj)); - } - - return obj; -} - -function assertValidDate(obj, objName) { - if (Object.prototype.toString.call(obj) !== '[object Date]') { - throw new TypeError(objName + ' expected to be a standard JavaScript Date but was: ' + JSON.stringify(obj)); - } - - if (Number.isNaN(obj.getTime())) { - throw new TypeError(objName + ' expected to be valid JavaScript Date but its time was NaN: ' + JSON.stringify(obj)); - } - - return obj; -} - -function assertCypherQuery(obj) { - assertString(obj, 'Cypher query'); - - if (obj.trim().length === 0) { - throw new TypeError('Cypher query is expected to be a non-empty string.'); - } -} - -function assertQueryParameters(obj) { - if (!isObject(obj)) { - // objects created with `Object.create(null)` do not have a constructor property - var _constructor = obj.constructor ? ' ' + obj.constructor.name : ''; - - throw new TypeError("Query parameters are expected to either be undefined/null or an object, given:".concat(_constructor, " ").concat(obj)); - } -} - -function isString(str) { - return Object.prototype.toString.call(str) === '[object String]'; -} -}); - -var constants = createCommonjsModule(function (module, exports) { - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.BOLT_PROTOCOL_V4_2 = exports.BOLT_PROTOCOL_V4_1 = exports.BOLT_PROTOCOL_V4_0 = exports.BOLT_PROTOCOL_V3 = exports.BOLT_PROTOCOL_V2 = exports.BOLT_PROTOCOL_V1 = exports.ACCESS_MODE_WRITE = exports.ACCESS_MODE_READ = void 0; - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var ACCESS_MODE_READ = 'READ'; -exports.ACCESS_MODE_READ = ACCESS_MODE_READ; -var ACCESS_MODE_WRITE = 'WRITE'; -exports.ACCESS_MODE_WRITE = ACCESS_MODE_WRITE; -var BOLT_PROTOCOL_V1 = 1; -exports.BOLT_PROTOCOL_V1 = BOLT_PROTOCOL_V1; -var BOLT_PROTOCOL_V2 = 2; -exports.BOLT_PROTOCOL_V2 = BOLT_PROTOCOL_V2; -var BOLT_PROTOCOL_V3 = 3; -exports.BOLT_PROTOCOL_V3 = BOLT_PROTOCOL_V3; -var BOLT_PROTOCOL_V4_0 = 4.0; -exports.BOLT_PROTOCOL_V4_0 = BOLT_PROTOCOL_V4_0; -var BOLT_PROTOCOL_V4_1 = 4.1; -exports.BOLT_PROTOCOL_V4_1 = BOLT_PROTOCOL_V4_1; -var BOLT_PROTOCOL_V4_2 = 4.2; -exports.BOLT_PROTOCOL_V4_2 = BOLT_PROTOCOL_V4_2; -}); - -var defineProperty$1 = createCommonjsModule(function (module) { -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -module.exports = _defineProperty; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var bookmark = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _defineProperty2 = interopRequireDefault(defineProperty$1); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var util$1 = interopRequireWildcard(util); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var BOOKMARKS_KEY = 'bookmarks'; - -var Bookmark = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {string|string[]} values single bookmark as string or multiple bookmarks as a string array. - */ - function Bookmark(values) { - (0, _classCallCheck2["default"])(this, Bookmark); - this._values = asStringArray(values); - } - - (0, _createClass2["default"])(Bookmark, [{ - key: "isEmpty", - - /** - * Check if the given bookmark is meaningful and can be send to the database. - * @return {boolean} returns `true` bookmark has a value, `false` otherwise. - */ - value: function isEmpty() { - return this._values.length === 0; - } - /** - * Get all bookmark values as an array. - * @return {string[]} all values. - */ - - }, { - key: "values", - value: function values() { - return this._values; - } - /** - * Get this bookmark as an object for begin transaction call. - * @return {Object} the value of this bookmark as object. - */ - - }, { - key: "asBeginTransactionParameters", - value: function asBeginTransactionParameters() { - if (this.isEmpty()) { - return {}; - } // Driver sends {bookmark: "max", bookmarks: ["one", "two", "max"]} instead of simple - // {bookmarks: ["one", "two", "max"]} for backwards compatibility reasons. Old servers can only accept single - // bookmark that is why driver has to parse and compare given list of bookmarks. This functionality will - // eventually be removed. - - - return (0, _defineProperty2["default"])({}, BOOKMARKS_KEY, this._values); - } - }], [{ - key: "empty", - value: function empty() { - return EMPTY_BOOKMARK; - } - }]); - return Bookmark; -}(); - -exports["default"] = Bookmark; -var EMPTY_BOOKMARK = new Bookmark(null); -/** - * Converts given value to an array. - * @param {string|string[]|Array} [value=undefined] argument to convert. - * @return {string[]} value converted to an array. - */ - -function asStringArray(value) { - if (!value) { - return []; - } - - if (util$1.isString(value)) { - return [value]; - } - - if (Array.isArray(value)) { - var result = []; - var flattenedValue = flattenArray(value); - - for (var i = 0; i < flattenedValue.length; i++) { - var element = flattenedValue[i]; // if it is undefined or null, ignore it - - if (element !== undefined && element !== null) { - if (!util$1.isString(element)) { - throw new TypeError("Bookmark value should be a string, given: '".concat(element, "'")); - } - - result.push(element); - } - } - - return result; - } - - throw new TypeError("Bookmark should either be a string or a string array, given: '".concat(value, "'")); -} -/** - * Recursively flattens an array so that the result becomes a single array - * of values, which does not include any sub-arrays - * - * @param {Array} value - */ - - -function flattenArray(values) { - return values.reduce(function (dest, value) { - return Array.isArray(value) ? dest.concat(flattenArray(value)) : dest.concat(value); - }, []); -} -}); - -var connectionHolder = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.EMPTY_CONNECTION_HOLDER = exports["default"] = void 0; - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - - - - - -var _bookmark = interopRequireDefault(bookmark); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Utility to lazily initialize connections and return them back to the pool when unused. - */ -var ConnectionHolder = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {string} mode - the access mode for new connection holder. - * @param {string} database - the target database name. - * @param {ConnectionProvider} connectionProvider - the connection provider to acquire connections from. - */ - function ConnectionHolder() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref$mode = _ref.mode, - mode = _ref$mode === void 0 ? constants.ACCESS_MODE_WRITE : _ref$mode, - _ref$database = _ref.database, - database = _ref$database === void 0 ? '' : _ref$database, - bookmark = _ref.bookmark, - connectionProvider = _ref.connectionProvider; - - (0, _classCallCheck2["default"])(this, ConnectionHolder); - this._mode = mode; - this._database = database ? (0, util.assertString)(database, 'database') : ''; - this._bookmark = bookmark || _bookmark["default"].empty(); - this._connectionProvider = connectionProvider; - this._referenceCount = 0; - this._connectionPromise = Promise.resolve(null); - } - /** - * Returns the assigned access mode. - * @returns {string} access mode - */ - - - (0, _createClass2["default"])(ConnectionHolder, [{ - key: "mode", - value: function mode() { - return this._mode; - } - /** - * Returns the target database name - * @returns {string} the database name - */ - - }, { - key: "database", - value: function database() { - return this._database; - } - /** - * Make this holder initialize new connection if none exists already. - * @return {boolean} - */ - - }, { - key: "initializeConnection", - value: function initializeConnection() { - if (this._referenceCount === 0) { - this._connectionPromise = this._connectionProvider.acquireConnection({ - accessMode: this._mode, - database: this._database, - bookmark: this._bookmark - }); - } else { - this._referenceCount++; - return false; - } - - this._referenceCount++; - return true; - } - /** - * Get the current connection promise. - * @return {Promise} promise resolved with the current connection. - */ - - }, { - key: "getConnection", - value: function getConnection() { - return this._connectionPromise; - } - /** - * Notify this holder that single party does not require current connection any more. - * @return {Promise} promise resolved with the current connection, never a rejected promise. - */ - - }, { - key: "releaseConnection", - value: function releaseConnection() { - if (this._referenceCount === 0) { - return this._connectionPromise; - } - - this._referenceCount--; - - if (this._referenceCount === 0) { - return this._releaseConnection(); - } - - return this._connectionPromise; - } - /** - * Closes this holder and releases current connection (if any) despite any existing users. - * @return {Promise} promise resolved when current connection is released to the pool. - */ - - }, { - key: "close", - value: function close() { - if (this._referenceCount === 0) { - return this._connectionPromise; - } - - this._referenceCount = 0; - return this._releaseConnection(); - } - /** - * Return the current pooled connection instance to the connection pool. - * We don't pool Session instances, to avoid users using the Session after they've called close. - * The `Session` object is just a thin wrapper around Connection anyway, so it makes little difference. - * @return {Promise} - promise resolved then connection is returned to the pool. - * @private - */ - - }, { - key: "_releaseConnection", - value: function _releaseConnection() { - this._connectionPromise = this._connectionPromise.then(function (connection) { - if (connection) { - return connection.resetAndFlush()["catch"](ignoreError).then(function () { - return connection._release(); - }); - } else { - return Promise.resolve(); - } - })["catch"](ignoreError); - return this._connectionPromise; - } - }]); - return ConnectionHolder; -}(); - -exports["default"] = ConnectionHolder; - -var EmptyConnectionHolder = -/*#__PURE__*/ -function (_ConnectionHolder) { - (0, _inherits2["default"])(EmptyConnectionHolder, _ConnectionHolder); - - function EmptyConnectionHolder() { - (0, _classCallCheck2["default"])(this, EmptyConnectionHolder); - return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(EmptyConnectionHolder).apply(this, arguments)); - } - - (0, _createClass2["default"])(EmptyConnectionHolder, [{ - key: "initializeConnection", - value: function initializeConnection() { - // nothing to initialize - return true; - } - }, { - key: "getConnection", - value: function getConnection() { - return Promise.reject((0, error.newError)('This connection holder does not serve connections')); - } - }, { - key: "releaseConnection", - value: function releaseConnection() { - return Promise.resolve(); - } - }, { - key: "close", - value: function close() { - return Promise.resolve(); - } - }]); - return EmptyConnectionHolder; -}(ConnectionHolder); // eslint-disable-next-line handle-callback-err - - -function ignoreError(error) {} -/** - * Connection holder that does not manage any connections. - * @type {ConnectionHolder} - */ - - -var EMPTY_CONNECTION_HOLDER = new EmptyConnectionHolder(); -exports.EMPTY_CONNECTION_HOLDER = EMPTY_CONNECTION_HOLDER; -}); - -var superPropBase = createCommonjsModule(function (module) { -function _superPropBase(object, property) { - while (!Object.prototype.hasOwnProperty.call(object, property)) { - object = getPrototypeOf(object); - if (object === null) break; - } - - return object; -} - -module.exports = _superPropBase; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var get$1 = createCommonjsModule(function (module) { -function _get(target, property, receiver) { - if (typeof Reflect !== "undefined" && Reflect.get) { - module.exports = _get = Reflect.get; - module.exports["default"] = module.exports, module.exports.__esModule = true; - } else { - module.exports = _get = function _get(target, property, receiver) { - var base = superPropBase(target, property); - if (!base) return; - var desc = Object.getOwnPropertyDescriptor(base, property); - - if (desc.get) { - return desc.get.call(receiver); - } - - return desc.value; - }; - - module.exports["default"] = module.exports, module.exports.__esModule = true; - } - - return _get(target, property, receiver || target); -} - -module.exports = _get; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -/** - * Copyright (c) 2014-present, Facebook, Inc. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ - -var runtime_1 = createCommonjsModule(function (module) { -var runtime = (function (exports) { - - var Op = Object.prototype; - var hasOwn = Op.hasOwnProperty; - var undefined$1; // More compressible than void 0. - var $Symbol = typeof Symbol === "function" ? Symbol : {}; - var iteratorSymbol = $Symbol.iterator || "@@iterator"; - var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator"; - var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag"; - - function define(obj, key, value) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - return obj[key]; - } - try { - // IE 8 has a broken Object.defineProperty that only works on DOM objects. - define({}, ""); - } catch (err) { - define = function(obj, key, value) { - return obj[key] = value; - }; - } - - function wrap(innerFn, outerFn, self, tryLocsList) { - // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator. - var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator; - var generator = Object.create(protoGenerator.prototype); - var context = new Context(tryLocsList || []); - - // The ._invoke method unifies the implementations of the .next, - // .throw, and .return methods. - generator._invoke = makeInvokeMethod(innerFn, self, context); - - return generator; - } - exports.wrap = wrap; - - // Try/catch helper to minimize deoptimizations. Returns a completion - // record like context.tryEntries[i].completion. This interface could - // have been (and was previously) designed to take a closure to be - // invoked without arguments, but in all the cases we care about we - // already have an existing method we want to call, so there's no need - // to create a new function object. We can even get away with assuming - // the method takes exactly one argument, since that happens to be true - // in every case, so we don't have to touch the arguments object. The - // only additional allocation required is the completion record, which - // has a stable shape and so hopefully should be cheap to allocate. - function tryCatch(fn, obj, arg) { - try { - return { type: "normal", arg: fn.call(obj, arg) }; - } catch (err) { - return { type: "throw", arg: err }; - } - } - - var GenStateSuspendedStart = "suspendedStart"; - var GenStateSuspendedYield = "suspendedYield"; - var GenStateExecuting = "executing"; - var GenStateCompleted = "completed"; - - // Returning this object from the innerFn has the same effect as - // breaking out of the dispatch switch statement. - var ContinueSentinel = {}; - - // Dummy constructor functions that we use as the .constructor and - // .constructor.prototype properties for functions that return Generator - // objects. For full spec compliance, you may wish to configure your - // minifier not to mangle the names of these two functions. - function Generator() {} - function GeneratorFunction() {} - function GeneratorFunctionPrototype() {} - - // This is a polyfill for %IteratorPrototype% for environments that - // don't natively support it. - var IteratorPrototype = {}; - IteratorPrototype[iteratorSymbol] = function () { - return this; - }; - - var getProto = Object.getPrototypeOf; - var NativeIteratorPrototype = getProto && getProto(getProto(values([]))); - if (NativeIteratorPrototype && - NativeIteratorPrototype !== Op && - hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) { - // This environment has a native %IteratorPrototype%; use it instead - // of the polyfill. - IteratorPrototype = NativeIteratorPrototype; - } - - var Gp = GeneratorFunctionPrototype.prototype = - Generator.prototype = Object.create(IteratorPrototype); - GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype; - GeneratorFunctionPrototype.constructor = GeneratorFunction; - GeneratorFunction.displayName = define( - GeneratorFunctionPrototype, - toStringTagSymbol, - "GeneratorFunction" - ); - - // Helper for defining the .next, .throw, and .return methods of the - // Iterator interface in terms of a single ._invoke method. - function defineIteratorMethods(prototype) { - ["next", "throw", "return"].forEach(function(method) { - define(prototype, method, function(arg) { - return this._invoke(method, arg); - }); - }); - } - - exports.isGeneratorFunction = function(genFun) { - var ctor = typeof genFun === "function" && genFun.constructor; - return ctor - ? ctor === GeneratorFunction || - // For the native GeneratorFunction constructor, the best we can - // do is to check its .name property. - (ctor.displayName || ctor.name) === "GeneratorFunction" - : false; - }; - - exports.mark = function(genFun) { - if (Object.setPrototypeOf) { - Object.setPrototypeOf(genFun, GeneratorFunctionPrototype); - } else { - genFun.__proto__ = GeneratorFunctionPrototype; - define(genFun, toStringTagSymbol, "GeneratorFunction"); - } - genFun.prototype = Object.create(Gp); - return genFun; - }; - - // Within the body of any async function, `await x` is transformed to - // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test - // `hasOwn.call(value, "__await")` to determine if the yielded value is - // meant to be awaited. - exports.awrap = function(arg) { - return { __await: arg }; - }; - - function AsyncIterator(generator, PromiseImpl) { - function invoke(method, arg, resolve, reject) { - var record = tryCatch(generator[method], generator, arg); - if (record.type === "throw") { - reject(record.arg); - } else { - var result = record.arg; - var value = result.value; - if (value && - typeof value === "object" && - hasOwn.call(value, "__await")) { - return PromiseImpl.resolve(value.__await).then(function(value) { - invoke("next", value, resolve, reject); - }, function(err) { - invoke("throw", err, resolve, reject); - }); - } - - return PromiseImpl.resolve(value).then(function(unwrapped) { - // When a yielded Promise is resolved, its final value becomes - // the .value of the Promise<{value,done}> result for the - // current iteration. - result.value = unwrapped; - resolve(result); - }, function(error) { - // If a rejected Promise was yielded, throw the rejection back - // into the async generator function so it can be handled there. - return invoke("throw", error, resolve, reject); - }); - } - } - - var previousPromise; - - function enqueue(method, arg) { - function callInvokeWithMethodAndArg() { - return new PromiseImpl(function(resolve, reject) { - invoke(method, arg, resolve, reject); - }); - } - - return previousPromise = - // If enqueue has been called before, then we want to wait until - // all previous Promises have been resolved before calling invoke, - // so that results are always delivered in the correct order. If - // enqueue has not been called before, then it is important to - // call invoke immediately, without waiting on a callback to fire, - // so that the async generator function has the opportunity to do - // any necessary setup in a predictable way. This predictability - // is why the Promise constructor synchronously invokes its - // executor callback, and why async functions synchronously - // execute code before the first await. Since we implement simple - // async functions in terms of async generators, it is especially - // important to get this right, even though it requires care. - previousPromise ? previousPromise.then( - callInvokeWithMethodAndArg, - // Avoid propagating failures to Promises returned by later - // invocations of the iterator. - callInvokeWithMethodAndArg - ) : callInvokeWithMethodAndArg(); - } - - // Define the unified helper method that is used to implement .next, - // .throw, and .return (see defineIteratorMethods). - this._invoke = enqueue; - } - - defineIteratorMethods(AsyncIterator.prototype); - AsyncIterator.prototype[asyncIteratorSymbol] = function () { - return this; - }; - exports.AsyncIterator = AsyncIterator; - - // Note that simple async functions are implemented on top of - // AsyncIterator objects; they just return a Promise for the value of - // the final result produced by the iterator. - exports.async = function(innerFn, outerFn, self, tryLocsList, PromiseImpl) { - if (PromiseImpl === void 0) PromiseImpl = Promise; - - var iter = new AsyncIterator( - wrap(innerFn, outerFn, self, tryLocsList), - PromiseImpl - ); - - return exports.isGeneratorFunction(outerFn) - ? iter // If outerFn is a generator, return the full iterator. - : iter.next().then(function(result) { - return result.done ? result.value : iter.next(); - }); - }; - - function makeInvokeMethod(innerFn, self, context) { - var state = GenStateSuspendedStart; - - return function invoke(method, arg) { - if (state === GenStateExecuting) { - throw new Error("Generator is already running"); - } - - if (state === GenStateCompleted) { - if (method === "throw") { - throw arg; - } - - // Be forgiving, per 25.3.3.3.3 of the spec: - // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume - return doneResult(); - } - - context.method = method; - context.arg = arg; - - while (true) { - var delegate = context.delegate; - if (delegate) { - var delegateResult = maybeInvokeDelegate(delegate, context); - if (delegateResult) { - if (delegateResult === ContinueSentinel) continue; - return delegateResult; - } - } - - if (context.method === "next") { - // Setting context._sent for legacy support of Babel's - // function.sent implementation. - context.sent = context._sent = context.arg; - - } else if (context.method === "throw") { - if (state === GenStateSuspendedStart) { - state = GenStateCompleted; - throw context.arg; - } - - context.dispatchException(context.arg); - - } else if (context.method === "return") { - context.abrupt("return", context.arg); - } - - state = GenStateExecuting; - - var record = tryCatch(innerFn, self, context); - if (record.type === "normal") { - // If an exception is thrown from innerFn, we leave state === - // GenStateExecuting and loop back for another invocation. - state = context.done - ? GenStateCompleted - : GenStateSuspendedYield; - - if (record.arg === ContinueSentinel) { - continue; - } - - return { - value: record.arg, - done: context.done - }; - - } else if (record.type === "throw") { - state = GenStateCompleted; - // Dispatch the exception by looping back around to the - // context.dispatchException(context.arg) call above. - context.method = "throw"; - context.arg = record.arg; - } - } - }; - } - - // Call delegate.iterator[context.method](context.arg) and handle the - // result, either by returning a { value, done } result from the - // delegate iterator, or by modifying context.method and context.arg, - // setting context.delegate to null, and returning the ContinueSentinel. - function maybeInvokeDelegate(delegate, context) { - var method = delegate.iterator[context.method]; - if (method === undefined$1) { - // A .throw or .return when the delegate iterator has no .throw - // method always terminates the yield* loop. - context.delegate = null; - - if (context.method === "throw") { - // Note: ["return"] must be used for ES3 parsing compatibility. - if (delegate.iterator["return"]) { - // If the delegate iterator has a return method, give it a - // chance to clean up. - context.method = "return"; - context.arg = undefined$1; - maybeInvokeDelegate(delegate, context); - - if (context.method === "throw") { - // If maybeInvokeDelegate(context) changed context.method from - // "return" to "throw", let that override the TypeError below. - return ContinueSentinel; - } - } - - context.method = "throw"; - context.arg = new TypeError( - "The iterator does not provide a 'throw' method"); - } - - return ContinueSentinel; - } - - var record = tryCatch(method, delegate.iterator, context.arg); - - if (record.type === "throw") { - context.method = "throw"; - context.arg = record.arg; - context.delegate = null; - return ContinueSentinel; - } - - var info = record.arg; - - if (! info) { - context.method = "throw"; - context.arg = new TypeError("iterator result is not an object"); - context.delegate = null; - return ContinueSentinel; - } - - if (info.done) { - // Assign the result of the finished delegate to the temporary - // variable specified by delegate.resultName (see delegateYield). - context[delegate.resultName] = info.value; - - // Resume execution at the desired location (see delegateYield). - context.next = delegate.nextLoc; - - // If context.method was "throw" but the delegate handled the - // exception, let the outer generator proceed normally. If - // context.method was "next", forget context.arg since it has been - // "consumed" by the delegate iterator. If context.method was - // "return", allow the original .return call to continue in the - // outer generator. - if (context.method !== "return") { - context.method = "next"; - context.arg = undefined$1; - } - - } else { - // Re-yield the result returned by the delegate method. - return info; - } - - // The delegate iterator is finished, so forget it and continue with - // the outer generator. - context.delegate = null; - return ContinueSentinel; - } - - // Define Generator.prototype.{next,throw,return} in terms of the - // unified ._invoke helper method. - defineIteratorMethods(Gp); - - define(Gp, toStringTagSymbol, "Generator"); - - // A Generator should always return itself as the iterator object when the - // @@iterator function is called on it. Some browsers' implementations of the - // iterator prototype chain incorrectly implement this, causing the Generator - // object to not be returned from this call. This ensures that doesn't happen. - // See https://github.com/facebook/regenerator/issues/274 for more details. - Gp[iteratorSymbol] = function() { - return this; - }; - - Gp.toString = function() { - return "[object Generator]"; - }; - - function pushTryEntry(locs) { - var entry = { tryLoc: locs[0] }; - - if (1 in locs) { - entry.catchLoc = locs[1]; - } - - if (2 in locs) { - entry.finallyLoc = locs[2]; - entry.afterLoc = locs[3]; - } - - this.tryEntries.push(entry); - } - - function resetTryEntry(entry) { - var record = entry.completion || {}; - record.type = "normal"; - delete record.arg; - entry.completion = record; - } - - function Context(tryLocsList) { - // The root entry object (effectively a try statement without a catch - // or a finally block) gives us a place to store values thrown from - // locations where there is no enclosing try statement. - this.tryEntries = [{ tryLoc: "root" }]; - tryLocsList.forEach(pushTryEntry, this); - this.reset(true); - } - - exports.keys = function(object) { - var keys = []; - for (var key in object) { - keys.push(key); - } - keys.reverse(); - - // Rather than returning an object with a next method, we keep - // things simple and return the next function itself. - return function next() { - while (keys.length) { - var key = keys.pop(); - if (key in object) { - next.value = key; - next.done = false; - return next; - } - } - - // To avoid creating an additional object, we just hang the .value - // and .done properties off the next function object itself. This - // also ensures that the minifier will not anonymize the function. - next.done = true; - return next; - }; - }; - - function values(iterable) { - if (iterable) { - var iteratorMethod = iterable[iteratorSymbol]; - if (iteratorMethod) { - return iteratorMethod.call(iterable); - } - - if (typeof iterable.next === "function") { - return iterable; - } - - if (!isNaN(iterable.length)) { - var i = -1, next = function next() { - while (++i < iterable.length) { - if (hasOwn.call(iterable, i)) { - next.value = iterable[i]; - next.done = false; - return next; - } - } - - next.value = undefined$1; - next.done = true; - - return next; - }; - - return next.next = next; - } - } - - // Return an iterator with no values. - return { next: doneResult }; - } - exports.values = values; - - function doneResult() { - return { value: undefined$1, done: true }; - } - - Context.prototype = { - constructor: Context, - - reset: function(skipTempReset) { - this.prev = 0; - this.next = 0; - // Resetting context._sent for legacy support of Babel's - // function.sent implementation. - this.sent = this._sent = undefined$1; - this.done = false; - this.delegate = null; - - this.method = "next"; - this.arg = undefined$1; - - this.tryEntries.forEach(resetTryEntry); - - if (!skipTempReset) { - for (var name in this) { - // Not sure about the optimal order of these conditions: - if (name.charAt(0) === "t" && - hasOwn.call(this, name) && - !isNaN(+name.slice(1))) { - this[name] = undefined$1; - } - } - } - }, - - stop: function() { - this.done = true; - - var rootEntry = this.tryEntries[0]; - var rootRecord = rootEntry.completion; - if (rootRecord.type === "throw") { - throw rootRecord.arg; - } - - return this.rval; - }, - - dispatchException: function(exception) { - if (this.done) { - throw exception; - } - - var context = this; - function handle(loc, caught) { - record.type = "throw"; - record.arg = exception; - context.next = loc; - - if (caught) { - // If the dispatched exception was caught by a catch block, - // then let that catch block handle the exception normally. - context.method = "next"; - context.arg = undefined$1; - } - - return !! caught; - } - - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - var record = entry.completion; - - if (entry.tryLoc === "root") { - // Exception thrown outside of any try block that could handle - // it, so set the completion value of the entire function to - // throw the exception. - return handle("end"); - } - - if (entry.tryLoc <= this.prev) { - var hasCatch = hasOwn.call(entry, "catchLoc"); - var hasFinally = hasOwn.call(entry, "finallyLoc"); - - if (hasCatch && hasFinally) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } else if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else if (hasCatch) { - if (this.prev < entry.catchLoc) { - return handle(entry.catchLoc, true); - } - - } else if (hasFinally) { - if (this.prev < entry.finallyLoc) { - return handle(entry.finallyLoc); - } - - } else { - throw new Error("try statement without catch or finally"); - } - } - } - }, - - abrupt: function(type, arg) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc <= this.prev && - hasOwn.call(entry, "finallyLoc") && - this.prev < entry.finallyLoc) { - var finallyEntry = entry; - break; - } - } - - if (finallyEntry && - (type === "break" || - type === "continue") && - finallyEntry.tryLoc <= arg && - arg <= finallyEntry.finallyLoc) { - // Ignore the finally entry if control is not jumping to a - // location outside the try/catch block. - finallyEntry = null; - } - - var record = finallyEntry ? finallyEntry.completion : {}; - record.type = type; - record.arg = arg; - - if (finallyEntry) { - this.method = "next"; - this.next = finallyEntry.finallyLoc; - return ContinueSentinel; - } - - return this.complete(record); - }, - - complete: function(record, afterLoc) { - if (record.type === "throw") { - throw record.arg; - } - - if (record.type === "break" || - record.type === "continue") { - this.next = record.arg; - } else if (record.type === "return") { - this.rval = this.arg = record.arg; - this.method = "return"; - this.next = "end"; - } else if (record.type === "normal" && afterLoc) { - this.next = afterLoc; - } - - return ContinueSentinel; - }, - - finish: function(finallyLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.finallyLoc === finallyLoc) { - this.complete(entry.completion, entry.afterLoc); - resetTryEntry(entry); - return ContinueSentinel; - } - } - }, - - "catch": function(tryLoc) { - for (var i = this.tryEntries.length - 1; i >= 0; --i) { - var entry = this.tryEntries[i]; - if (entry.tryLoc === tryLoc) { - var record = entry.completion; - if (record.type === "throw") { - var thrown = record.arg; - resetTryEntry(entry); - } - return thrown; - } - } - - // The context.catch method must only be called with a location - // argument that corresponds to a known catch block. - throw new Error("illegal catch attempt"); - }, - - delegateYield: function(iterable, resultName, nextLoc) { - this.delegate = { - iterator: values(iterable), - resultName: resultName, - nextLoc: nextLoc - }; - - if (this.method === "next") { - // Deliberately forget the last sent value so that we don't - // accidentally pass it on to the delegate. - this.arg = undefined$1; - } - - return ContinueSentinel; - } - }; - - // Regardless of whether this script is executing as a CommonJS module - // or not, return the runtime object so that we can declare the variable - // regeneratorRuntime in the outer scope, which allows this module to be - // injected easily by `bin/regenerator --include-runtime script.js`. - return exports; - -}( - // If this script is executing as a CommonJS module, use module.exports - // as the regeneratorRuntime namespace. Otherwise create a new empty - // object. Either way, the resulting object will be used to initialize - // the regeneratorRuntime variable at the top of this file. - module.exports -)); - -try { - regeneratorRuntime = runtime; -} catch (accidentalStrictMode) { - // This module should not be running in strict mode, so the above - // assignment should always work unless something is misconfigured. Just - // in case runtime.js accidentally runs in strict mode, we can escape - // strict mode using a global Function call. This could conceivably fail - // if a Content Security Policy forbids using Function, but in that case - // the proper solution is to fix the accidental strict mode problem. If - // you've misconfigured your bundler to force strict mode and applied a - // CSP to forbid Function, and you're not willing to fix either of those - // problems, please detail your unique predicament in a GitHub issue. - Function("r", "regeneratorRuntime = r")(runtime); -} -}); - -var regenerator = runtime_1; - -var arrayWithHoles = createCommonjsModule(function (module) { -function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; -} - -module.exports = _arrayWithHoles; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var iterableToArrayLimit = createCommonjsModule(function (module) { -function _iterableToArrayLimit(arr, i) { - if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"] != null) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; -} - -module.exports = _iterableToArrayLimit; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var arrayLikeToArray = createCommonjsModule(function (module) { -function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) { - arr2[i] = arr[i]; - } - - return arr2; -} - -module.exports = _arrayLikeToArray; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var unsupportedIterableToArray = createCommonjsModule(function (module) { -function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); -} - -module.exports = _unsupportedIterableToArray; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var nonIterableRest = createCommonjsModule(function (module) { -function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); -} - -module.exports = _nonIterableRest; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var slicedToArray = createCommonjsModule(function (module) { -function _slicedToArray(arr, i) { - return arrayWithHoles(arr) || iterableToArrayLimit(arr, i) || unsupportedIterableToArray(arr, i) || nonIterableRest(); -} - -module.exports = _slicedToArray; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var record = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _regenerator = interopRequireDefault(regenerator); - -var _slicedToArray2 = interopRequireDefault(slicedToArray); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function generateFieldLookup(keys) { - var lookup = {}; - keys.forEach(function (name, idx) { - lookup[name] = idx; - }); - return lookup; -} -/** - * Records make up the contents of the {@link Result}, and is how you access - * the output of a query. A simple query might yield a result stream - * with a single record, for instance: - * - * MATCH (u:User) RETURN u.name, u.age - * - * This returns a stream of records with two fields, named `u.name` and `u.age`, - * each record represents one user found by the query above. You can access - * the values of each field either by name: - * - * record.get("u.name") - * - * Or by it's position: - * - * record.get(0) - * - * @access public - */ - - -var Record = -/*#__PURE__*/ -function () { - /** - * Create a new record object. - * @constructor - * @protected - * @param {string[]} keys An array of field keys, in the order the fields appear in the record - * @param {Array} fields An array of field values - * @param {Object} fieldLookup An object of fieldName -> value index, used to map - * field names to values. If this is null, one will be - * generated. - */ - function Record(keys, fields) { - var fieldLookup = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - (0, _classCallCheck2["default"])(this, Record); - - /** - * Field keys, in the order the fields appear in the record. - * @type {string[]} - */ - this.keys = keys; - /** - * Number of fields - * @type {Number} - */ - - this.length = keys.length; - this._fields = fields; - this._fieldLookup = fieldLookup || generateFieldLookup(keys); - } - /** - * Run the given function for each field in this record. The function - * will get three arguments - the value, the key and this record, in that - * order. - * - * @param {function(value: Object, key: string, record: Record)} visitor the function to apply to each field. - */ - - - (0, _createClass2["default"])(Record, [{ - key: "forEach", - value: function forEach(visitor) { - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = this.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var _step$value = (0, _slicedToArray2["default"])(_step.value, 2), - key = _step$value[0], - value = _step$value[1]; - - visitor(value, key, this); - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator["return"] != null) { - _iterator["return"](); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - } - /** - * Run the given function for each field in this record. The function - * will get three arguments - the value, the key and this record, in that - * order. - * - * @param {function(value: Object, key: string, record: Record)} visitor the function to apply on each field - * and return a value that is saved to the returned Array. - * - * @returns {Array} - */ - - }, { - key: "map", - value: function map(visitor) { - var resultArray = []; - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = this.entries()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var _step2$value = (0, _slicedToArray2["default"])(_step2.value, 2), - key = _step2$value[0], - value = _step2$value[1]; - - resultArray.push(visitor(value, key, this)); - } - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) { - _iterator2["return"](); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - - return resultArray; - } - /** - * Iterate over results. Each iteration will yield an array - * of exactly two items - the key, and the value (in order). - * - * @generator - * @returns {IterableIterator} - */ - - }, { - key: "entries", - value: - /*#__PURE__*/ - _regenerator["default"].mark(function entries() { - var i; - return _regenerator["default"].wrap(function entries$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - i = 0; - - case 1: - if (!(i < this.keys.length)) { - _context.next = 7; - break; - } - - _context.next = 4; - return [this.keys[i], this._fields[i]]; - - case 4: - i++; - _context.next = 1; - break; - - case 7: - case "end": - return _context.stop(); - } - } - }, entries, this); - }) - /** - * Iterate over values. - * - * @generator - * @returns {IterableIterator} - */ - - }, { - key: "values", - value: - /*#__PURE__*/ - _regenerator["default"].mark(function values() { - var i; - return _regenerator["default"].wrap(function values$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - i = 0; - - case 1: - if (!(i < this.keys.length)) { - _context2.next = 7; - break; - } - - _context2.next = 4; - return this._fields[i]; - - case 4: - i++; - _context2.next = 1; - break; - - case 7: - case "end": - return _context2.stop(); - } - } - }, values, this); - }) - /** - * Iterate over values. Delegates to {@link Record#values} - * - * @generator - * @returns {IterableIterator} - */ - - }, { - key: Symbol.iterator, - value: - /*#__PURE__*/ - _regenerator["default"].mark(function value() { - return _regenerator["default"].wrap(function value$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - return _context3.delegateYield(this.values(), "t0", 1); - - case 1: - case "end": - return _context3.stop(); - } - } - }, value, this); - }) - /** - * Generates an object out of the current Record - * - * @returns {Object} - */ - - }, { - key: "toObject", - value: function toObject() { - var object = {}; - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; - - try { - for (var _iterator3 = this.entries()[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var _step3$value = (0, _slicedToArray2["default"])(_step3.value, 2), - key = _step3$value[0], - _value = _step3$value[1]; - - object[key] = _value; - } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3["return"] != null) { - _iterator3["return"](); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } - } - } - - return object; - } - /** - * Get a value from this record, either by index or by field key. - * - * @param {string|Number} key Field key, or the index of the field. - * @returns {*} - */ - - }, { - key: "get", - value: function get(key) { - var index; - - if (!(typeof key === 'number')) { - index = this._fieldLookup[key]; - - if (index === undefined) { - throw (0, error.newError)("This record has no field with key '" + key + "', available key are: [" + this.keys + '].'); - } - } else { - index = key; - } - - if (index > this._fields.length - 1 || index < 0) { - throw (0, error.newError)("This record has no field with index '" + index + "'. Remember that indexes start at `0`, " + 'and make sure your query returns records in the shape you meant it to.'); - } - - return this._fields[index]; - } - /** - * Check if a value from this record, either by index or by field key, exists. - * - * @param {string|Number} key Field key, or the index of the field. - * @returns {boolean} - */ - - }, { - key: "has", - value: function has(key) { - // if key is a number, we check if it is in the _fields array - if (typeof key === 'number') { - return key >= 0 && key < this._fields.length; - } // if it's not a number, we check _fieldLookup dictionary directly - - - return this._fieldLookup[key] !== undefined; - } - }]); - return Record; -}(); - -var _default = Record; -exports["default"] = _default; -}); - -var assertDatabaseIsEmpty_1 = assertDatabaseIsEmpty; -var assertTxConfigIsEmpty_1 = assertTxConfigIsEmpty; - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * @param {TxConfig} txConfig the auto-commit transaction configuration. - * @param {Connection} connection the connection. - * @param {ResultStreamObserver} observer the response observer. - */ -function assertTxConfigIsEmpty(txConfig, connection, observer) { - if (txConfig && !txConfig.isEmpty()) { - var error$1 = (0, error.newError)('Driver is connected to the database that does not support transaction configuration. ' + 'Please upgrade to neo4j 3.5.0 or later in order to use this functionality'); // unsupported API was used, consider this a fatal error for the current connection - - connection._handleFatalError(error$1); - - observer.onError(error$1); - throw error$1; - } -} -/** - * Asserts that the passed-in database name is empty. - * @param {string} database - * @param {Connection} connection - */ - - -function assertDatabaseIsEmpty(database, connection, observer) { - if (database) { - var error$1 = (0, error.newError)('Driver is connected to the database that does not support multiple databases. ' + 'Please upgrade to neo4j 4.0.0 or later in order to use this functionality'); // unsupported API was used, consider this a fatal error for the current connection - - connection._handleFatalError(error$1); - - observer.onError(error$1); - throw error$1; - } -} - -var boltProtocolUtil = /*#__PURE__*/Object.defineProperty({ - assertDatabaseIsEmpty: assertDatabaseIsEmpty_1, - assertTxConfigIsEmpty: assertTxConfigIsEmpty_1 -}, '__esModule', {value: true}); - -var baseBuf = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Common base with default implementation for most buffer methods. - * Buffers are stateful - they track a current "position", this helps greatly - * when reading and writing from them incrementally. You can also ignore the - * stateful read/write methods. - * readXXX and writeXXX-methods move the inner position of the buffer. - * putXXX and getXXX-methods do not. - * @access private - */ -var BaseBuffer = -/*#__PURE__*/ -function () { - /** - * Create a instance with the injected size. - * @constructor - * @param {Integer} size - */ - function BaseBuffer(size) { - (0, _classCallCheck2["default"])(this, BaseBuffer); - this.position = 0; - this.length = size; - } - - (0, _createClass2["default"])(BaseBuffer, [{ - key: "getUInt8", - value: function getUInt8(position) { - throw new Error('Not implemented'); - } - }, { - key: "getInt8", - value: function getInt8(position) { - throw new Error('Not implemented'); - } - }, { - key: "getFloat64", - value: function getFloat64(position) { - throw new Error('Not implemented'); - } - }, { - key: "putUInt8", - value: function putUInt8(position, val) { - throw new Error('Not implemented'); - } - }, { - key: "putInt8", - value: function putInt8(position, val) { - throw new Error('Not implemented'); - } - }, { - key: "putFloat64", - value: function putFloat64(position, val) { - throw new Error('Not implemented'); - } - /** - * @param p - */ - - }, { - key: "getInt16", - value: function getInt16(p) { - return this.getInt8(p) << 8 | this.getUInt8(p + 1); - } - /** - * @param p - */ - - }, { - key: "getUInt16", - value: function getUInt16(p) { - return this.getUInt8(p) << 8 | this.getUInt8(p + 1); - } - /** - * @param p - */ - - }, { - key: "getInt32", - value: function getInt32(p) { - return this.getInt8(p) << 24 | this.getUInt8(p + 1) << 16 | this.getUInt8(p + 2) << 8 | this.getUInt8(p + 3); - } - /** - * @param p - */ - - }, { - key: "getUInt32", - value: function getUInt32(p) { - return this.getUInt8(p) << 24 | this.getUInt8(p + 1) << 16 | this.getUInt8(p + 2) << 8 | this.getUInt8(p + 3); - } - /** - * @param p - */ - - }, { - key: "getInt64", - value: function getInt64(p) { - return this.getInt8(p) << 56 | this.getUInt8(p + 1) << 48 | this.getUInt8(p + 2) << 40 | this.getUInt8(p + 3) << 32 | this.getUInt8(p + 4) << 24 | this.getUInt8(p + 5) << 16 | this.getUInt8(p + 6) << 8 | this.getUInt8(p + 7); - } - /** - * Get a slice of this buffer. This method does not copy any data, - * but simply provides a slice view of this buffer - * @param start - * @param length - */ - - }, { - key: "getSlice", - value: function getSlice(start, length) { - return new SliceBuffer(start, length, this); - } - /** - * @param p - * @param val - */ - - }, { - key: "putInt16", - value: function putInt16(p, val) { - this.putInt8(p, val >> 8); - this.putUInt8(p + 1, val & 0xff); - } - /** - * @param p - * @param val - */ - - }, { - key: "putUInt16", - value: function putUInt16(p, val) { - this.putUInt8(p, val >> 8 & 0xff); - this.putUInt8(p + 1, val & 0xff); - } - /** - * @param p - * @param val - */ - - }, { - key: "putInt32", - value: function putInt32(p, val) { - this.putInt8(p, val >> 24); - this.putUInt8(p + 1, val >> 16 & 0xff); - this.putUInt8(p + 2, val >> 8 & 0xff); - this.putUInt8(p + 3, val & 0xff); - } - /** - * @param p - * @param val - */ - - }, { - key: "putUInt32", - value: function putUInt32(p, val) { - this.putUInt8(p, val >> 24 & 0xff); - this.putUInt8(p + 1, val >> 16 & 0xff); - this.putUInt8(p + 2, val >> 8 & 0xff); - this.putUInt8(p + 3, val & 0xff); - } - /** - * @param p - * @param val - */ - - }, { - key: "putInt64", - value: function putInt64(p, val) { - this.putInt8(p, val >> 48); - this.putUInt8(p + 1, val >> 42 & 0xff); - this.putUInt8(p + 2, val >> 36 & 0xff); - this.putUInt8(p + 3, val >> 30 & 0xff); - this.putUInt8(p + 4, val >> 24 & 0xff); - this.putUInt8(p + 5, val >> 16 & 0xff); - this.putUInt8(p + 6, val >> 8 & 0xff); - this.putUInt8(p + 7, val & 0xff); - } - /** - * @param position - * @param other - */ - - }, { - key: "putBytes", - value: function putBytes(position, other) { - for (var i = 0, end = other.remaining(); i < end; i++) { - this.putUInt8(position + i, other.readUInt8()); - } - } - /** - * Read from state position. - */ - - }, { - key: "readUInt8", - value: function readUInt8() { - return this.getUInt8(this._updatePos(1)); - } - /** - * Read from state position. - */ - - }, { - key: "readInt8", - value: function readInt8() { - return this.getInt8(this._updatePos(1)); - } - /** - * Read from state position. - */ - - }, { - key: "readUInt16", - value: function readUInt16() { - return this.getUInt16(this._updatePos(2)); - } - /** - * Read from state position. - */ - - }, { - key: "readUInt32", - value: function readUInt32() { - return this.getUInt32(this._updatePos(4)); - } - /** - * Read from state position. - */ - - }, { - key: "readInt16", - value: function readInt16() { - return this.getInt16(this._updatePos(2)); - } - /** - * Read from state position. - */ - - }, { - key: "readInt32", - value: function readInt32() { - return this.getInt32(this._updatePos(4)); - } - /** - * Read from state position. - */ - - }, { - key: "readInt64", - value: function readInt64() { - return this.getInt32(this._updatePos(8)); - } - /** - * Read from state position. - */ - - }, { - key: "readFloat64", - value: function readFloat64() { - return this.getFloat64(this._updatePos(8)); - } - /** - * Write to state position. - * @param val - */ - - }, { - key: "writeUInt8", - value: function writeUInt8(val) { - this.putUInt8(this._updatePos(1), val); - } - /** - * Write to state position. - * @param val - */ - - }, { - key: "writeInt8", - value: function writeInt8(val) { - this.putInt8(this._updatePos(1), val); - } - /** - * Write to state position. - * @param val - */ - - }, { - key: "writeInt16", - value: function writeInt16(val) { - this.putInt16(this._updatePos(2), val); - } - /** - * Write to state position. - * @param val - */ - - }, { - key: "writeInt32", - value: function writeInt32(val) { - this.putInt32(this._updatePos(4), val); - } - /** - * Write to state position. - * @param val - */ - - }, { - key: "writeUInt32", - value: function writeUInt32(val) { - this.putUInt32(this._updatePos(4), val); - } - /** - * Write to state position. - * @param val - */ - - }, { - key: "writeInt64", - value: function writeInt64(val) { - this.putInt64(this._updatePos(8), val); - } - /** - * Write to state position. - * @param val - */ - - }, { - key: "writeFloat64", - value: function writeFloat64(val) { - this.putFloat64(this._updatePos(8), val); - } - /** - * Write to state position. - * @param val - */ - - }, { - key: "writeBytes", - value: function writeBytes(val) { - this.putBytes(this._updatePos(val.remaining()), val); - } - /** - * Get a slice of this buffer. This method does not copy any data, - * but simply provides a slice view of this buffer - * @param length - */ - - }, { - key: "readSlice", - value: function readSlice(length) { - return this.getSlice(this._updatePos(length), length); - } - }, { - key: "_updatePos", - value: function _updatePos(length) { - var p = this.position; - this.position += length; - return p; - } - /** - * Get remaining - */ - - }, { - key: "remaining", - value: function remaining() { - return this.length - this.position; - } - /** - * Has remaining - */ - - }, { - key: "hasRemaining", - value: function hasRemaining() { - return this.remaining() > 0; - } - /** - * Reset position state - */ - - }, { - key: "reset", - value: function reset() { - this.position = 0; - } - /** - * Get string representation of buffer and it's state. - * @return {string} Buffer as a string - */ - - }, { - key: "toString", - value: function toString() { - return this.constructor.name + '( position=' + this.position + ' )\n ' + this.toHex(); - } - /** - * Get string representation of buffer. - * @return {string} Buffer as a string - */ - - }, { - key: "toHex", - value: function toHex() { - var out = ''; - - for (var i = 0; i < this.length; i++) { - var hexByte = this.getUInt8(i).toString(16); - - if (hexByte.length === 1) { - hexByte = '0' + hexByte; - } - - out += hexByte; - - if (i !== this.length - 1) { - out += ' '; - } - } - - return out; - } - }]); - return BaseBuffer; -}(); -/** - * Represents a view as slice of another buffer. - * @access private - */ - - -exports["default"] = BaseBuffer; - -var SliceBuffer = -/*#__PURE__*/ -function (_BaseBuffer) { - (0, _inherits2["default"])(SliceBuffer, _BaseBuffer); - - function SliceBuffer(start, length, inner) { - var _this; - - (0, _classCallCheck2["default"])(this, SliceBuffer); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(SliceBuffer).call(this, length)); - _this._start = start; - _this._inner = inner; - return _this; - } - - (0, _createClass2["default"])(SliceBuffer, [{ - key: "putUInt8", - value: function putUInt8(position, val) { - this._inner.putUInt8(this._start + position, val); - } - }, { - key: "getUInt8", - value: function getUInt8(position) { - return this._inner.getUInt8(this._start + position); - } - }, { - key: "putInt8", - value: function putInt8(position, val) { - this._inner.putInt8(this._start + position, val); - } - }, { - key: "putFloat64", - value: function putFloat64(position, val) { - this._inner.putFloat64(this._start + position, val); - } - }, { - key: "getInt8", - value: function getInt8(position) { - return this._inner.getInt8(this._start + position); - } - }, { - key: "getFloat64", - value: function getFloat64(position) { - return this._inner.getFloat64(this._start + position); - } - }]); - return SliceBuffer; -}(BaseBuffer); -}); - -var nodeBuf = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _get2 = interopRequireDefault(get$1); - -var _inherits2 = interopRequireDefault(inherits); - -var _buffer = interopRequireDefault(require$$6__default['default']); - -var _baseBuf = interopRequireDefault(baseBuf); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var NodeBuffer = -/*#__PURE__*/ -function (_BaseBuffer) { - (0, _inherits2["default"])(NodeBuffer, _BaseBuffer); - - function NodeBuffer(arg) { - var _this; - - (0, _classCallCheck2["default"])(this, NodeBuffer); - var buffer = newNodeJSBuffer(arg); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(NodeBuffer).call(this, buffer.length)); - _this._buffer = buffer; - return _this; - } - - (0, _createClass2["default"])(NodeBuffer, [{ - key: "getUInt8", - value: function getUInt8(position) { - return this._buffer.readUInt8(position); - } - }, { - key: "getInt8", - value: function getInt8(position) { - return this._buffer.readInt8(position); - } - }, { - key: "getFloat64", - value: function getFloat64(position) { - return this._buffer.readDoubleBE(position); - } - }, { - key: "putUInt8", - value: function putUInt8(position, val) { - this._buffer.writeUInt8(val, position); - } - }, { - key: "putInt8", - value: function putInt8(position, val) { - this._buffer.writeInt8(val, position); - } - }, { - key: "putFloat64", - value: function putFloat64(position, val) { - this._buffer.writeDoubleBE(val, position); - } - }, { - key: "putBytes", - value: function putBytes(position, val) { - if (val instanceof NodeBuffer) { - var bytesToCopy = Math.min(val.length - val.position, this.length - position); - - val._buffer.copy(this._buffer, position, val.position, val.position + bytesToCopy); - - val.position += bytesToCopy; - } else { - (0, _get2["default"])((0, _getPrototypeOf2["default"])(NodeBuffer.prototype), "putBytes", this).call(this, position, val); - } - } - }, { - key: "getSlice", - value: function getSlice(start, length) { - return new NodeBuffer(this._buffer.slice(start, start + length)); - } - }]); - return NodeBuffer; -}(_baseBuf["default"]); - -exports["default"] = NodeBuffer; - -function newNodeJSBuffer(arg) { - if (arg instanceof _buffer["default"].Buffer) { - return arg; - } else if (typeof arg === 'number' && typeof _buffer["default"].Buffer.alloc === 'function') { - // use static factory function present in newer NodeJS versions to allocate new buffer with specified size - return _buffer["default"].Buffer.alloc(arg); - } else { - // fallback to the old, potentially deprecated constructor - // eslint-disable-next-line node/no-deprecated-api - return new _buffer["default"].Buffer(arg); - } -} -}); - -var nodeChannel = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _net = interopRequireDefault(require$$2__default['default']); - -var _tls = interopRequireDefault(require$$3__default['default']); - -var _fs = interopRequireDefault(require$$4__default['default']); - -var _nodeBuf = interopRequireDefault(nodeBuf); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var _CONNECTION_IDGEN = 0; -var TrustStrategy = { - TRUST_CUSTOM_CA_SIGNED_CERTIFICATES: function TRUST_CUSTOM_CA_SIGNED_CERTIFICATES(config, onSuccess, onFailure) { - if (!config.trustedCertificates || config.trustedCertificates.length === 0) { - onFailure((0, error.newError)('You are using TRUST_CUSTOM_CA_SIGNED_CERTIFICATES as the method ' + 'to verify trust for encrypted connections, but have not configured any ' + 'trustedCertificates. You must specify the path to at least one trusted ' + 'X.509 certificate for this to work. Two other alternatives is to use ' + 'TRUST_ALL_CERTIFICATES or to disable encryption by setting encrypted="' + util.ENCRYPTION_OFF + '"' + 'in your driver configuration.')); - return; - } - - var tlsOpts = newTlsOptions(config.address.host(), config.trustedCertificates.map(function (f) { - return _fs["default"].readFileSync(f); - })); - - var socket = _tls["default"].connect(config.address.port(), config.address.resolvedHost(), tlsOpts, function () { - if (!socket.authorized) { - onFailure((0, error.newError)('Server certificate is not trusted. If you trust the database you are connecting to, add' + ' the signing certificate, or the server certificate, to the list of certificates trusted by this driver' + " using `neo4j.driver(.., { trustedCertificates:['path/to/certificate.crt']}). This " + ' is a security measure to protect against man-in-the-middle attacks. If you are just trying ' + ' Neo4j out and are not concerned about encryption, simply disable it using `encrypted="' + util.ENCRYPTION_OFF + '"`' + ' in the driver options. Socket responded with: ' + socket.authorizationError)); - } else { - onSuccess(); - } - }); - - socket.on('error', onFailure); - return configureSocket(socket); - }, - TRUST_SYSTEM_CA_SIGNED_CERTIFICATES: function TRUST_SYSTEM_CA_SIGNED_CERTIFICATES(config, onSuccess, onFailure) { - var tlsOpts = newTlsOptions(config.address.host()); - - var socket = _tls["default"].connect(config.address.port(), config.address.resolvedHost(), tlsOpts, function () { - if (!socket.authorized) { - onFailure((0, error.newError)('Server certificate is not trusted. If you trust the database you are connecting to, use ' + 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES and add' + ' the signing certificate, or the server certificate, to the list of certificates trusted by this driver' + " using `neo4j.driver(.., { trustedCertificates:['path/to/certificate.crt']}). This " + ' is a security measure to protect against man-in-the-middle attacks. If you are just trying ' + ' Neo4j out and are not concerned about encryption, simply disable it using `encrypted="' + util.ENCRYPTION_OFF + '"`' + ' in the driver options. Socket responded with: ' + socket.authorizationError)); - } else { - onSuccess(); - } - }); - - socket.on('error', onFailure); - return configureSocket(socket); - }, - TRUST_ALL_CERTIFICATES: function TRUST_ALL_CERTIFICATES(config, onSuccess, onFailure) { - var tlsOpts = newTlsOptions(config.address.host()); - - var socket = _tls["default"].connect(config.address.port(), config.address.resolvedHost(), tlsOpts, function () { - var certificate = socket.getPeerCertificate(); - - if ((0, util.isEmptyObjectOrNull)(certificate)) { - onFailure((0, error.newError)('Secure connection was successful but server did not return any valid ' + 'certificates. Such connection can not be trusted. If you are just trying ' + ' Neo4j out and are not concerned about encryption, simply disable it using ' + '`encrypted="' + util.ENCRYPTION_OFF + '"` in the driver options. ' + 'Socket responded with: ' + socket.authorizationError)); - } else { - onSuccess(); - } - }); - - socket.on('error', onFailure); - return configureSocket(socket); - } - /** - * Connect using node socket. - * @param {ChannelConfig} config - configuration of this channel. - * @param {function} onSuccess - callback to execute on connection success. - * @param {function} onFailure - callback to execute on connection failure. - * @return {*} socket connection. - */ - -}; - -function connect(config, onSuccess) { - var onFailure = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () { - return null; - }; - var trustStrategy = trustStrategyName(config); - - if (!isEncrypted(config)) { - var socket = _net["default"].connect(config.address.port(), config.address.resolvedHost(), onSuccess); - - socket.on('error', onFailure); - return configureSocket(socket); - } else if (TrustStrategy[trustStrategy]) { - return TrustStrategy[trustStrategy](config, onSuccess, onFailure); - } else { - onFailure((0, error.newError)('Unknown trust strategy: ' + config.trust + '. Please use either ' + "trust:'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES' or trust:'TRUST_ALL_CERTIFICATES' in your driver " + 'configuration. Alternatively, you can disable encryption by setting ' + '`encrypted:"' + util.ENCRYPTION_OFF + '"`. There is no mechanism to use encryption without trust verification, ' + 'because this incurs the overhead of encryption without improving security. If ' + 'the driver does not verify that the peer it is connected to is really Neo4j, it ' + 'is very easy for an attacker to bypass the encryption by pretending to be Neo4j.')); - } -} - -function isEncrypted(config) { - var encryptionNotConfigured = config.encrypted == null || config.encrypted === undefined; - - if (encryptionNotConfigured) { - // default to using encryption if trust-all-certificates is available - return false; - } - - return config.encrypted === true || config.encrypted === util.ENCRYPTION_ON; -} - -function trustStrategyName(config) { - if (config.trust) { - return config.trust; - } - - return 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'; -} -/** - * Create a new configuration options object for the {@code tls.connect()} call. - * @param {string} hostname the target hostname. - * @param {string|undefined} ca an optional CA. - * @return {Object} a new options object. - */ - - -function newTlsOptions(hostname) { - var ca = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - return { - rejectUnauthorized: false, - // we manually check for this in the connect callback, to give a more helpful error to the user - servername: hostname, - // server name for the SNI (Server Name Indication) TLS extension - ca: ca // optional CA useful for TRUST_CUSTOM_CA_SIGNED_CERTIFICATES trust mode - - }; -} -/** - * Update socket options for the newly created socket. Accepts either `net.Socket` or its subclass `tls.TLSSocket`. - * @param {net.Socket} socket the socket to configure. - * @return {net.Socket} the given socket. - */ - - -function configureSocket(socket) { - socket.setKeepAlive(true); - return socket; -} -/** - * In a Node.js environment the 'net' module is used - * as transport. - * @access private - */ - - -var NodeChannel = -/*#__PURE__*/ -function () { - /** - * Create new instance - * @param {ChannelConfig} config - configuration for this channel. - */ - function NodeChannel(config) { - (0, _classCallCheck2["default"])(this, NodeChannel); - var self = this; - this.id = _CONNECTION_IDGEN++; - this._pending = []; - this._open = true; - this._error = null; - this._handleConnectionError = this._handleConnectionError.bind(this); - this._handleConnectionTerminated = this._handleConnectionTerminated.bind(this); - this._connectionErrorCode = config.connectionErrorCode; - this._conn = connect(config, function () { - if (!self._open) { - return; - } - - self._conn.on('data', function (buffer) { - if (self.onmessage) { - self.onmessage(new _nodeBuf["default"](buffer)); - } - }); - - self._conn.on('error', self._handleConnectionError); - - self._conn.on('end', self._handleConnectionTerminated); // Drain all pending messages - - - var pending = self._pending; - self._pending = null; - - for (var i = 0; i < pending.length; i++) { - self.write(pending[i]); - } - }, this._handleConnectionError); - - this._setupConnectionTimeout(config, this._conn); - } - - (0, _createClass2["default"])(NodeChannel, [{ - key: "_handleConnectionError", - value: function _handleConnectionError(err) { - var msg = 'Failed to connect to server. ' + 'Please ensure that your database is listening on the correct host and port ' + 'and that you have compatible encryption settings both on Neo4j server and driver. ' + 'Note that the default encryption setting has changed in Neo4j 4.0.'; - if (err.message) msg += ' Caused by: ' + err.message; - this._error = (0, error.newError)(msg, this._connectionErrorCode); - - if (this.onerror) { - this.onerror(this._error); - } - } - }, { - key: "_handleConnectionTerminated", - value: function _handleConnectionTerminated() { - this._open = false; - this._error = (0, error.newError)('Connection was closed by server', this._connectionErrorCode); - - if (this.onerror) { - this.onerror(this._error); - } - } - /** - * Setup connection timeout on the socket, if configured. - * @param {ChannelConfig} config - configuration of this channel. - * @param {Object} socket - `net.Socket` or `tls.TLSSocket` object. - * @private - */ - - }, { - key: "_setupConnectionTimeout", - value: function _setupConnectionTimeout(config, socket) { - var timeout = config.connectionTimeout; - - if (timeout) { - socket.on('connect', function () { - // connected - clear connection timeout - socket.setTimeout(0); - }); - socket.on('timeout', function () { - // timeout fired - not connected within configured time. cancel timeout and destroy socket - socket.setTimeout(0); - socket.destroy((0, error.newError)("Failed to establish connection in ".concat(timeout, "ms"), config.connectionErrorCode)); - }); - socket.setTimeout(timeout); - } - } - /** - * Write the passed in buffer to connection - * @param {NodeBuffer} buffer - Buffer to write - */ - - }, { - key: "write", - value: function write(buffer) { - // If there is a pending queue, push this on that queue. This means - // we are not yet connected, so we queue things locally. - if (this._pending !== null) { - this._pending.push(buffer); - } else if (buffer instanceof _nodeBuf["default"]) { - this._conn.write(buffer._buffer); - } else { - throw (0, error.newError)("Don't know how to write: " + buffer); - } - } - /** - * Close the connection - * @returns {Promise} A promise that will be resolved after channel is closed - */ - - }, { - key: "close", - value: function close() { - var _this = this; - - return new Promise(function (resolve, reject) { - var cleanup = function cleanup() { - if (!_this._conn.destroyed) { - _this._conn.destroy(); - } - - resolve(); - }; - - if (_this._open) { - _this._open = false; - - _this._conn.removeListener('end', _this._handleConnectionTerminated); - - _this._conn.on('end', function () { - return cleanup(); - }); - - _this._conn.on('close', function () { - return cleanup(); - }); - - _this._conn.end(); - - _this._conn.destroy(); - } else { - cleanup(); - } - }); - } - }]); - return NodeChannel; -}(); - -exports["default"] = NodeChannel; -}); - -var baseHostNameResolver = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var BaseHostNameResolver = -/*#__PURE__*/ -function () { - function BaseHostNameResolver() { - (0, _classCallCheck2["default"])(this, BaseHostNameResolver); - } - - (0, _createClass2["default"])(BaseHostNameResolver, [{ - key: "resolve", - value: function resolve() { - throw new Error('Abstract function'); - } - /** - * @protected - */ - - }, { - key: "_resolveToItself", - value: function _resolveToItself(address) { - return Promise.resolve([address]); - } - }]); - return BaseHostNameResolver; -}(); - -exports["default"] = BaseHostNameResolver; -}); - -var nodeHostNameResolver = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _baseHostNameResolver = interopRequireDefault(baseHostNameResolver); - -var _dns = interopRequireDefault(require$$6__default$1['default']); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var NodeHostNameResolver = -/*#__PURE__*/ -function (_BaseHostNameResolver) { - (0, _inherits2["default"])(NodeHostNameResolver, _BaseHostNameResolver); - - function NodeHostNameResolver() { - (0, _classCallCheck2["default"])(this, NodeHostNameResolver); - return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(NodeHostNameResolver).apply(this, arguments)); - } - - (0, _createClass2["default"])(NodeHostNameResolver, [{ - key: "resolve", - value: function resolve(address) { - return new Promise(function (resolve) { - _dns["default"].lookup(address.host(), { - all: true - }, function (error, resolvedTo) { - if (error) { - resolve([address]); - } else { - var resolvedAddresses = resolvedTo.map(function (a) { - return address.resolveWith(a.address); - }); - resolve(resolvedAddresses); - } - }); - }); - } - }]); - return NodeHostNameResolver; -}(_baseHostNameResolver["default"]); - -exports["default"] = NodeHostNameResolver; -}); - -var combinedBuf = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _baseBuf = interopRequireDefault(baseBuf); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Buffer that combines multiple buffers, exposing them as one single buffer. - */ -var CombinedBuffer = -/*#__PURE__*/ -function (_BaseBuffer) { - (0, _inherits2["default"])(CombinedBuffer, _BaseBuffer); - - function CombinedBuffer(buffers) { - var _this; - - (0, _classCallCheck2["default"])(this, CombinedBuffer); - var length = 0; - - for (var i = 0; i < buffers.length; i++) { - length += buffers[i].length; - } - - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(CombinedBuffer).call(this, length)); - _this._buffers = buffers; - return _this; - } - - (0, _createClass2["default"])(CombinedBuffer, [{ - key: "getUInt8", - value: function getUInt8(position) { - // Surely there's a faster way to do this.. some sort of lookup table thing? - for (var i = 0; i < this._buffers.length; i++) { - var buffer = this._buffers[i]; // If the position is not in the current buffer, skip the current buffer - - if (position >= buffer.length) { - position -= buffer.length; - } else { - return buffer.getUInt8(position); - } - } - } - }, { - key: "getInt8", - value: function getInt8(position) { - // Surely there's a faster way to do this.. some sort of lookup table thing? - for (var i = 0; i < this._buffers.length; i++) { - var buffer = this._buffers[i]; // If the position is not in the current buffer, skip the current buffer - - if (position >= buffer.length) { - position -= buffer.length; - } else { - return buffer.getInt8(position); - } - } - } - }, { - key: "getFloat64", - value: function getFloat64(position) { - // At some point, a more efficient impl. For now, we copy the 8 bytes - // we want to read and depend on the platform impl of IEEE 754. - var b = (0, node.alloc)(8); - - for (var i = 0; i < 8; i++) { - b.putUInt8(i, this.getUInt8(position + i)); - } - - return b.getFloat64(0); - } - }]); - return CombinedBuffer; -}(_baseBuf["default"]); - -exports["default"] = CombinedBuffer; -}); - -var nodeUtf8 = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _combinedBuf = interopRequireDefault(combinedBuf); - -var _nodeBuf = interopRequireDefault(nodeBuf); - - - -var _buffer = interopRequireDefault(require$$6__default['default']); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var decoder = new _string_decoder__default['default'].StringDecoder('utf8'); - -function encode(str) { - return new _nodeBuf["default"](newNodeJSBuffer(str)); -} - -function decode(buffer, length) { - if (buffer instanceof _nodeBuf["default"]) { - return decodeNodeBuffer(buffer, length); - } else if (buffer instanceof _combinedBuf["default"]) { - return decodeCombinedBuffer(buffer, length); - } else { - throw (0, error.newError)("Don't know how to decode strings from '".concat(buffer, "'")); - } -} - -function decodeNodeBuffer(buffer, length) { - var start = buffer.position; - var end = start + length; - buffer.position = Math.min(end, buffer.length); - return buffer._buffer.toString('utf8', start, end); -} - -function decodeCombinedBuffer(buffer, length) { - return streamDecodeCombinedBuffer(buffer, length, function (partBuffer) { - return decoder.write(partBuffer._buffer); - }, function () { - return decoder.end(); - }); -} - -function streamDecodeCombinedBuffer(combinedBuffers, length, decodeFn, endFn) { - var remainingBytesToRead = length; - var position = combinedBuffers.position; - - combinedBuffers._updatePos(Math.min(length, combinedBuffers.length - position)); // Reduce CombinedBuffers to a decoded string - - - var out = combinedBuffers._buffers.reduce(function (last, partBuffer) { - if (remainingBytesToRead <= 0) { - return last; - } else if (position >= partBuffer.length) { - position -= partBuffer.length; - return ''; - } else { - partBuffer._updatePos(position - partBuffer.position); - - var bytesToRead = Math.min(partBuffer.length - position, remainingBytesToRead); - var lastSlice = partBuffer.readSlice(bytesToRead); - - partBuffer._updatePos(bytesToRead); - - remainingBytesToRead = Math.max(remainingBytesToRead - lastSlice.length, 0); - position = 0; - return last + decodeFn(lastSlice); - } - }, ''); - - return out + endFn(); -} - -function newNodeJSBuffer(str) { - // use static factory function present in newer NodeJS versions to create a buffer containing the given string - // or fallback to the old, potentially deprecated constructor - if (typeof _buffer["default"].Buffer.from === 'function') { - return _buffer["default"].Buffer.from(str, 'utf8'); - } else { - // eslint-disable-next-line node/no-deprecated-api - return new _buffer["default"].Buffer(str, 'utf8'); - } -} - -var _default = { - encode: encode, - decode: decode -}; -exports["default"] = _default; -}); - -var node = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.utf8 = exports.HostNameResolver = exports.Channel = exports.alloc = void 0; - -var _nodeBuf = interopRequireDefault(nodeBuf); - -var _nodeChannel = interopRequireDefault(nodeChannel); - -var _nodeHostNameResolver = interopRequireDefault(nodeHostNameResolver); - -var _nodeUtf = interopRequireDefault(nodeUtf8); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - -This module exports a set of components to be used in NodeJS environment. -They are not compatible with browser environment. -All files that require environment-dependent APIs should import this file by default. -Imports/requires are replaced at build time with `browser/index.js` when building a browser bundle. - -NOTE: exports in this module should have exactly the same names/structure as exports in `browser/index.js`. - - */ -var alloc = function alloc(arg) { - return new _nodeBuf["default"](arg); -}; - -exports.alloc = alloc; -var Channel = _nodeChannel["default"]; -exports.Channel = Channel; -var HostNameResolver = _nodeHostNameResolver["default"]; -exports.HostNameResolver = HostNameResolver; -var utf8 = _nodeUtf["default"]; -exports.utf8 = utf8; -}); - -var chunking = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.Dechunker = exports.Chunker = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _baseBuf = interopRequireDefault(baseBuf); - - - -var _combinedBuf = interopRequireDefault(combinedBuf); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var _CHUNK_HEADER_SIZE = 2; -var _MESSAGE_BOUNDARY = 0x00; -var _DEFAULT_BUFFER_SIZE = 1400; // http://stackoverflow.com/questions/2613734/maximum-packet-size-for-a-tcp-connection - -/** - * Looks like a writable buffer, chunks output transparently into a channel below. - * @access private - */ - -var Chunker = -/*#__PURE__*/ -function (_BaseBuffer) { - (0, _inherits2["default"])(Chunker, _BaseBuffer); - - function Chunker(channel, bufferSize) { - var _this; - - (0, _classCallCheck2["default"])(this, Chunker); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(Chunker).call(this, 0)); - _this._bufferSize = bufferSize || _DEFAULT_BUFFER_SIZE; - _this._ch = channel; - _this._buffer = (0, node.alloc)(_this._bufferSize); - _this._currentChunkStart = 0; - _this._chunkOpen = false; - return _this; - } - - (0, _createClass2["default"])(Chunker, [{ - key: "putUInt8", - value: function putUInt8(position, val) { - this._ensure(1); - - this._buffer.writeUInt8(val); - } - }, { - key: "putInt8", - value: function putInt8(position, val) { - this._ensure(1); - - this._buffer.writeInt8(val); - } - }, { - key: "putFloat64", - value: function putFloat64(position, val) { - this._ensure(8); - - this._buffer.writeFloat64(val); - } - }, { - key: "putBytes", - value: function putBytes(position, data) { - // TODO: If data is larger than our chunk size or so, we're very likely better off just passing this buffer on - // rather than doing the copy here TODO: *however* note that we need some way to find out when the data has been - // written (and thus the buffer can be re-used) if we take that approach - while (data.remaining() > 0) { - // Ensure there is an open chunk, and that it has at least one byte of space left - this._ensure(1); - - if (this._buffer.remaining() > data.remaining()) { - this._buffer.writeBytes(data); - } else { - this._buffer.writeBytes(data.readSlice(this._buffer.remaining())); - } - } - - return this; - } - }, { - key: "flush", - value: function flush() { - if (this._buffer.position > 0) { - this._closeChunkIfOpen(); // Local copy and clear the buffer field. This ensures that the buffer is not re-released if the flush call fails - - - var out = this._buffer; - this._buffer = null; - - this._ch.write(out.getSlice(0, out.position)); // Alloc a new output buffer. We assume we're using NodeJS's buffer pooling under the hood here! - - - this._buffer = (0, node.alloc)(this._bufferSize); - this._chunkOpen = false; - } - - return this; - } - /** - * Bolt messages are encoded in one or more chunks, and the boundary between two messages - * is encoded as a 0-length chunk, `00 00`. This inserts such a message boundary, closing - * any currently open chunk as needed - */ - - }, { - key: "messageBoundary", - value: function messageBoundary() { - this._closeChunkIfOpen(); - - if (this._buffer.remaining() < _CHUNK_HEADER_SIZE) { - this.flush(); - } // Write message boundary - - - this._buffer.writeInt16(_MESSAGE_BOUNDARY); - } - /** Ensure at least the given size is available for writing */ - - }, { - key: "_ensure", - value: function _ensure(size) { - var toWriteSize = this._chunkOpen ? size : size + _CHUNK_HEADER_SIZE; - - if (this._buffer.remaining() < toWriteSize) { - this.flush(); - } - - if (!this._chunkOpen) { - this._currentChunkStart = this._buffer.position; - this._buffer.position = this._buffer.position + _CHUNK_HEADER_SIZE; - this._chunkOpen = true; - } - } - }, { - key: "_closeChunkIfOpen", - value: function _closeChunkIfOpen() { - if (this._chunkOpen) { - var chunkSize = this._buffer.position - (this._currentChunkStart + _CHUNK_HEADER_SIZE); - - this._buffer.putUInt16(this._currentChunkStart, chunkSize); - - this._chunkOpen = false; - } - } - }]); - return Chunker; -}(_baseBuf["default"]); -/** - * Combines chunks until a complete message is gathered up, and then forwards that - * message to an 'onmessage' listener. - * @access private - */ - - -exports.Chunker = Chunker; - -var Dechunker = -/*#__PURE__*/ -function () { - function Dechunker() { - (0, _classCallCheck2["default"])(this, Dechunker); - this._currentMessage = []; - this._partialChunkHeader = 0; - this._state = this.AWAITING_CHUNK; - } - - (0, _createClass2["default"])(Dechunker, [{ - key: "AWAITING_CHUNK", - value: function AWAITING_CHUNK(buf) { - if (buf.remaining() >= 2) { - // Whole header available, read that - return this._onHeader(buf.readUInt16()); - } else { - // Only one byte available, read that and wait for the second byte - this._partialChunkHeader = buf.readUInt8() << 8; - return this.IN_HEADER; - } - } - }, { - key: "IN_HEADER", - value: function IN_HEADER(buf) { - // First header byte read, now we read the next one - return this._onHeader((this._partialChunkHeader | buf.readUInt8()) & 0xffff); - } - }, { - key: "IN_CHUNK", - value: function IN_CHUNK(buf) { - if (this._chunkSize <= buf.remaining()) { - // Current packet is larger than current chunk, or same size: - this._currentMessage.push(buf.readSlice(this._chunkSize)); - - return this.AWAITING_CHUNK; - } else { - // Current packet is smaller than the chunk we're reading, split the current chunk itself up - this._chunkSize -= buf.remaining(); - - this._currentMessage.push(buf.readSlice(buf.remaining())); - - return this.IN_CHUNK; - } - } - }, { - key: "CLOSED", - value: function CLOSED(buf) {} // no-op - - /** Called when a complete chunk header has been received */ - - }, { - key: "_onHeader", - value: function _onHeader(header) { - if (header === 0) { - // Message boundary - var message; - - switch (this._currentMessage.length) { - case 0: - // Keep alive chunk, sent by server to keep network alive. - return this.AWAITING_CHUNK; - - case 1: - // All data in one chunk, this signals the end of that chunk. - message = this._currentMessage[0]; - break; - - default: - // A large chunk of data received, this signals that the last chunk has been received. - message = new _combinedBuf["default"](this._currentMessage); - break; - } - - this._currentMessage = []; - this.onmessage(message); - return this.AWAITING_CHUNK; - } else { - this._chunkSize = header; - return this.IN_CHUNK; - } - } - }, { - key: "write", - value: function write(buf) { - while (buf.hasRemaining()) { - this._state = this._state(buf); - } - } - }]); - return Dechunker; -}(); - -exports.Dechunker = Dechunker; -}); - -var packstreamV1 = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.Structure = exports.Unpacker = exports.Packer = void 0; - -var _typeof2 = interopRequireDefault(_typeof_1); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -var _integer = interopRequireWildcard(integer); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var TINY_STRING = 0x80; -var TINY_LIST = 0x90; -var TINY_MAP = 0xa0; -var TINY_STRUCT = 0xb0; -var NULL = 0xc0; -var FLOAT_64 = 0xc1; -var FALSE = 0xc2; -var TRUE = 0xc3; -var INT_8 = 0xc8; -var INT_16 = 0xc9; -var INT_32 = 0xca; -var INT_64 = 0xcb; -var STRING_8 = 0xd0; -var STRING_16 = 0xd1; -var STRING_32 = 0xd2; -var LIST_8 = 0xd4; -var LIST_16 = 0xd5; -var LIST_32 = 0xd6; -var BYTES_8 = 0xcc; -var BYTES_16 = 0xcd; -var BYTES_32 = 0xce; -var MAP_8 = 0xd8; -var MAP_16 = 0xd9; -var MAP_32 = 0xda; -var STRUCT_8 = 0xdc; -var STRUCT_16 = 0xdd; -var NODE = 0x4e; -var NODE_STRUCT_SIZE = 3; -var RELATIONSHIP = 0x52; -var RELATIONSHIP_STRUCT_SIZE = 5; -var UNBOUND_RELATIONSHIP = 0x72; -var UNBOUND_RELATIONSHIP_STRUCT_SIZE = 3; -var PATH = 0x50; -var PATH_STRUCT_SIZE = 3; -/** - * A Structure have a signature and fields. - * @access private - */ - -var Structure = -/*#__PURE__*/ -function () { - /** - * Create new instance - */ - function Structure(signature, fields) { - (0, _classCallCheck2["default"])(this, Structure); - this.signature = signature; - this.fields = fields; - } - - (0, _createClass2["default"])(Structure, [{ - key: "toString", - value: function toString() { - var fieldStr = ''; - - for (var i = 0; i < this.fields.length; i++) { - if (i > 0) { - fieldStr += ', '; - } - - fieldStr += this.fields[i]; - } - - return 'Structure(' + this.signature + ', [' + fieldStr + '])'; - } - }]); - return Structure; -}(); -/** - * Class to pack - * @access private - */ - - -exports.Structure = Structure; - -var Packer = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {Chunker} channel the chunker backed by a network channel. - */ - function Packer(channel) { - (0, _classCallCheck2["default"])(this, Packer); - this._ch = channel; - this._byteArraysSupported = true; - } - /** - * Creates a packable function out of the provided value - * @param x the value to pack - * @returns Function - */ - - - (0, _createClass2["default"])(Packer, [{ - key: "packable", - value: function packable(x) { - var _this = this; - - if (x === null) { - return function () { - return _this._ch.writeUInt8(NULL); - }; - } else if (x === true) { - return function () { - return _this._ch.writeUInt8(TRUE); - }; - } else if (x === false) { - return function () { - return _this._ch.writeUInt8(FALSE); - }; - } else if (typeof x === 'number') { - return function () { - return _this.packFloat(x); - }; - } else if (typeof x === 'string') { - return function () { - return _this.packString(x); - }; - } else if ((0, _integer.isInt)(x)) { - return function () { - return _this.packInteger(x); - }; - } else if (x instanceof Int8Array) { - return function () { - return _this.packBytes(x); - }; - } else if (x instanceof Array) { - return function () { - _this.packListHeader(x.length); - - for (var _i = 0; _i < x.length; _i++) { - _this.packable(x[_i] === undefined ? null : x[_i])(); - } - }; - } else if (isIterable(x)) { - return this.packableIterable(x); - } else if (x instanceof graphTypes.Node) { - return this._nonPackableValue("It is not allowed to pass nodes in query parameters, given: ".concat(x)); - } else if (x instanceof graphTypes.Relationship) { - return this._nonPackableValue("It is not allowed to pass relationships in query parameters, given: ".concat(x)); - } else if (x instanceof graphTypes.Path) { - return this._nonPackableValue("It is not allowed to pass paths in query parameters, given: ".concat(x)); - } else if (x instanceof Structure) { - var packableFields = []; - - for (var i = 0; i < x.fields.length; i++) { - packableFields[i] = this.packable(x.fields[i]); - } - - return function () { - return _this.packStruct(x.signature, packableFields); - }; - } else if ((0, _typeof2["default"])(x) === 'object') { - return function () { - var keys = Object.keys(x); - var count = 0; - - for (var _i2 = 0; _i2 < keys.length; _i2++) { - if (x[keys[_i2]] !== undefined) { - count++; - } - } - - _this.packMapHeader(count); - - for (var _i3 = 0; _i3 < keys.length; _i3++) { - var key = keys[_i3]; - - if (x[key] !== undefined) { - _this.packString(key); - - _this.packable(x[key])(); - } - } - }; - } else { - return this._nonPackableValue("Unable to pack the given value: ".concat(x)); - } - } - }, { - key: "packableIterable", - value: function packableIterable(iterable) { - try { - var array = Array.from(iterable); - return this.packable(array); - } catch (e) { - // handle errors from iterable to array conversion - throw (0, error.newError)("Cannot pack given iterable, ".concat(e.message, ": ").concat(iterable)); - } - } - /** - * Packs a struct - * @param signature the signature of the struct - * @param packableFields the fields of the struct, make sure you call `packable on all fields` - */ - - }, { - key: "packStruct", - value: function packStruct(signature, packableFields) { - packableFields = packableFields || []; - this.packStructHeader(packableFields.length, signature); - - for (var i = 0; i < packableFields.length; i++) { - packableFields[i](); - } - } - }, { - key: "packInteger", - value: function packInteger(x) { - var high = x.high; - var low = x.low; - - if (x.greaterThanOrEqual(-0x10) && x.lessThan(0x80)) { - this._ch.writeInt8(low); - } else if (x.greaterThanOrEqual(-0x80) && x.lessThan(-0x10)) { - this._ch.writeUInt8(INT_8); - - this._ch.writeInt8(low); - } else if (x.greaterThanOrEqual(-0x8000) && x.lessThan(0x8000)) { - this._ch.writeUInt8(INT_16); - - this._ch.writeInt16(low); - } else if (x.greaterThanOrEqual(-0x80000000) && x.lessThan(0x80000000)) { - this._ch.writeUInt8(INT_32); - - this._ch.writeInt32(low); - } else { - this._ch.writeUInt8(INT_64); - - this._ch.writeInt32(high); - - this._ch.writeInt32(low); - } - } - }, { - key: "packFloat", - value: function packFloat(x) { - this._ch.writeUInt8(FLOAT_64); - - this._ch.writeFloat64(x); - } - }, { - key: "packString", - value: function packString(x) { - var bytes = node.utf8.encode(x); - - var size = bytes.length; - - if (size < 0x10) { - this._ch.writeUInt8(TINY_STRING | size); - - this._ch.writeBytes(bytes); - } else if (size < 0x100) { - this._ch.writeUInt8(STRING_8); - - this._ch.writeUInt8(size); - - this._ch.writeBytes(bytes); - } else if (size < 0x10000) { - this._ch.writeUInt8(STRING_16); - - this._ch.writeUInt8(size / 256 >> 0); - - this._ch.writeUInt8(size % 256); - - this._ch.writeBytes(bytes); - } else if (size < 0x100000000) { - this._ch.writeUInt8(STRING_32); - - this._ch.writeUInt8((size / 16777216 >> 0) % 256); - - this._ch.writeUInt8((size / 65536 >> 0) % 256); - - this._ch.writeUInt8((size / 256 >> 0) % 256); - - this._ch.writeUInt8(size % 256); - - this._ch.writeBytes(bytes); - } else { - throw (0, error.newError)('UTF-8 strings of size ' + size + ' are not supported'); - } - } - }, { - key: "packListHeader", - value: function packListHeader(size) { - if (size < 0x10) { - this._ch.writeUInt8(TINY_LIST | size); - } else if (size < 0x100) { - this._ch.writeUInt8(LIST_8); - - this._ch.writeUInt8(size); - } else if (size < 0x10000) { - this._ch.writeUInt8(LIST_16); - - this._ch.writeUInt8((size / 256 >> 0) % 256); - - this._ch.writeUInt8(size % 256); - } else if (size < 0x100000000) { - this._ch.writeUInt8(LIST_32); - - this._ch.writeUInt8((size / 16777216 >> 0) % 256); - - this._ch.writeUInt8((size / 65536 >> 0) % 256); - - this._ch.writeUInt8((size / 256 >> 0) % 256); - - this._ch.writeUInt8(size % 256); - } else { - throw (0, error.newError)('Lists of size ' + size + ' are not supported'); - } - } - }, { - key: "packBytes", - value: function packBytes(array) { - if (this._byteArraysSupported) { - this.packBytesHeader(array.length); - - for (var i = 0; i < array.length; i++) { - this._ch.writeInt8(array[i]); - } - } else { - throw (0, error.newError)('Byte arrays are not supported by the database this driver is connected to'); - } - } - }, { - key: "packBytesHeader", - value: function packBytesHeader(size) { - if (size < 0x100) { - this._ch.writeUInt8(BYTES_8); - - this._ch.writeUInt8(size); - } else if (size < 0x10000) { - this._ch.writeUInt8(BYTES_16); - - this._ch.writeUInt8((size / 256 >> 0) % 256); - - this._ch.writeUInt8(size % 256); - } else if (size < 0x100000000) { - this._ch.writeUInt8(BYTES_32); - - this._ch.writeUInt8((size / 16777216 >> 0) % 256); - - this._ch.writeUInt8((size / 65536 >> 0) % 256); - - this._ch.writeUInt8((size / 256 >> 0) % 256); - - this._ch.writeUInt8(size % 256); - } else { - throw (0, error.newError)('Byte arrays of size ' + size + ' are not supported'); - } - } - }, { - key: "packMapHeader", - value: function packMapHeader(size) { - if (size < 0x10) { - this._ch.writeUInt8(TINY_MAP | size); - } else if (size < 0x100) { - this._ch.writeUInt8(MAP_8); - - this._ch.writeUInt8(size); - } else if (size < 0x10000) { - this._ch.writeUInt8(MAP_16); - - this._ch.writeUInt8(size / 256 >> 0); - - this._ch.writeUInt8(size % 256); - } else if (size < 0x100000000) { - this._ch.writeUInt8(MAP_32); - - this._ch.writeUInt8((size / 16777216 >> 0) % 256); - - this._ch.writeUInt8((size / 65536 >> 0) % 256); - - this._ch.writeUInt8((size / 256 >> 0) % 256); - - this._ch.writeUInt8(size % 256); - } else { - throw (0, error.newError)('Maps of size ' + size + ' are not supported'); - } - } - }, { - key: "packStructHeader", - value: function packStructHeader(size, signature) { - if (size < 0x10) { - this._ch.writeUInt8(TINY_STRUCT | size); - - this._ch.writeUInt8(signature); - } else if (size < 0x100) { - this._ch.writeUInt8(STRUCT_8); - - this._ch.writeUInt8(size); - - this._ch.writeUInt8(signature); - } else if (size < 0x10000) { - this._ch.writeUInt8(STRUCT_16); - - this._ch.writeUInt8(size / 256 >> 0); - - this._ch.writeUInt8(size % 256); - } else { - throw (0, error.newError)('Structures of size ' + size + ' are not supported'); - } - } - }, { - key: "disableByteArrays", - value: function disableByteArrays() { - this._byteArraysSupported = false; - } - }, { - key: "_nonPackableValue", - value: function _nonPackableValue(message) { - return function () { - throw (0, error.newError)(message, error.PROTOCOL_ERROR); - }; - } - }]); - return Packer; -}(); -/** - * Class to unpack - * @access private - */ - - -exports.Packer = Packer; - -var Unpacker = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {boolean} disableLosslessIntegers if this unpacker should convert all received integers to native JS numbers. - */ - function Unpacker() { - var disableLosslessIntegers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - (0, _classCallCheck2["default"])(this, Unpacker); - this._disableLosslessIntegers = disableLosslessIntegers; - } - - (0, _createClass2["default"])(Unpacker, [{ - key: "unpack", - value: function unpack(buffer) { - var marker = buffer.readUInt8(); - var markerHigh = marker & 0xf0; - var markerLow = marker & 0x0f; - - if (marker === NULL) { - return null; - } - - var _boolean = this._unpackBoolean(marker); - - if (_boolean !== null) { - return _boolean; - } - - var numberOrInteger = this._unpackNumberOrInteger(marker, buffer); - - if (numberOrInteger !== null) { - if (this._disableLosslessIntegers && (0, _integer.isInt)(numberOrInteger)) { - return numberOrInteger.toNumberOrInfinity(); - } - - return numberOrInteger; - } - - var string = this._unpackString(marker, markerHigh, markerLow, buffer); - - if (string !== null) { - return string; - } - - var list = this._unpackList(marker, markerHigh, markerLow, buffer); - - if (list !== null) { - return list; - } - - var byteArray = this._unpackByteArray(marker, buffer); - - if (byteArray !== null) { - return byteArray; - } - - var map = this._unpackMap(marker, markerHigh, markerLow, buffer); - - if (map !== null) { - return map; - } - - var struct = this._unpackStruct(marker, markerHigh, markerLow, buffer); - - if (struct !== null) { - return struct; - } - - throw (0, error.newError)('Unknown packed value with marker ' + marker.toString(16)); - } - }, { - key: "unpackInteger", - value: function unpackInteger(buffer) { - var marker = buffer.readUInt8(); - - var result = this._unpackInteger(marker, buffer); - - if (result == null) { - throw (0, error.newError)('Unable to unpack integer value with marker ' + marker.toString(16)); - } - - return result; - } - }, { - key: "_unpackBoolean", - value: function _unpackBoolean(marker) { - if (marker === TRUE) { - return true; - } else if (marker === FALSE) { - return false; - } else { - return null; - } - } - }, { - key: "_unpackNumberOrInteger", - value: function _unpackNumberOrInteger(marker, buffer) { - if (marker === FLOAT_64) { - return buffer.readFloat64(); - } else { - return this._unpackInteger(marker, buffer); - } - } - }, { - key: "_unpackInteger", - value: function _unpackInteger(marker, buffer) { - if (marker >= 0 && marker < 128) { - return (0, _integer["int"])(marker); - } else if (marker >= 240 && marker < 256) { - return (0, _integer["int"])(marker - 256); - } else if (marker === INT_8) { - return (0, _integer["int"])(buffer.readInt8()); - } else if (marker === INT_16) { - return (0, _integer["int"])(buffer.readInt16()); - } else if (marker === INT_32) { - var b = buffer.readInt32(); - return (0, _integer["int"])(b); - } else if (marker === INT_64) { - var high = buffer.readInt32(); - var low = buffer.readInt32(); - return new _integer["default"](low, high); - } else { - return null; - } - } - }, { - key: "_unpackString", - value: function _unpackString(marker, markerHigh, markerLow, buffer) { - if (markerHigh === TINY_STRING) { - return node.utf8.decode(buffer, markerLow); - } else if (marker === STRING_8) { - return node.utf8.decode(buffer, buffer.readUInt8()); - } else if (marker === STRING_16) { - return node.utf8.decode(buffer, buffer.readUInt16()); - } else if (marker === STRING_32) { - return node.utf8.decode(buffer, buffer.readUInt32()); - } else { - return null; - } - } - }, { - key: "_unpackList", - value: function _unpackList(marker, markerHigh, markerLow, buffer) { - if (markerHigh === TINY_LIST) { - return this._unpackListWithSize(markerLow, buffer); - } else if (marker === LIST_8) { - return this._unpackListWithSize(buffer.readUInt8(), buffer); - } else if (marker === LIST_16) { - return this._unpackListWithSize(buffer.readUInt16(), buffer); - } else if (marker === LIST_32) { - return this._unpackListWithSize(buffer.readUInt32(), buffer); - } else { - return null; - } - } - }, { - key: "_unpackListWithSize", - value: function _unpackListWithSize(size, buffer) { - var value = []; - - for (var i = 0; i < size; i++) { - value.push(this.unpack(buffer)); - } - - return value; - } - }, { - key: "_unpackByteArray", - value: function _unpackByteArray(marker, buffer) { - if (marker === BYTES_8) { - return this._unpackByteArrayWithSize(buffer.readUInt8(), buffer); - } else if (marker === BYTES_16) { - return this._unpackByteArrayWithSize(buffer.readUInt16(), buffer); - } else if (marker === BYTES_32) { - return this._unpackByteArrayWithSize(buffer.readUInt32(), buffer); - } else { - return null; - } - } - }, { - key: "_unpackByteArrayWithSize", - value: function _unpackByteArrayWithSize(size, buffer) { - var value = new Int8Array(size); - - for (var i = 0; i < size; i++) { - value[i] = buffer.readInt8(); - } - - return value; - } - }, { - key: "_unpackMap", - value: function _unpackMap(marker, markerHigh, markerLow, buffer) { - if (markerHigh === TINY_MAP) { - return this._unpackMapWithSize(markerLow, buffer); - } else if (marker === MAP_8) { - return this._unpackMapWithSize(buffer.readUInt8(), buffer); - } else if (marker === MAP_16) { - return this._unpackMapWithSize(buffer.readUInt16(), buffer); - } else if (marker === MAP_32) { - return this._unpackMapWithSize(buffer.readUInt32(), buffer); - } else { - return null; - } - } - }, { - key: "_unpackMapWithSize", - value: function _unpackMapWithSize(size, buffer) { - var value = {}; - - for (var i = 0; i < size; i++) { - var key = this.unpack(buffer); - value[key] = this.unpack(buffer); - } - - return value; - } - }, { - key: "_unpackStruct", - value: function _unpackStruct(marker, markerHigh, markerLow, buffer) { - if (markerHigh === TINY_STRUCT) { - return this._unpackStructWithSize(markerLow, buffer); - } else if (marker === STRUCT_8) { - return this._unpackStructWithSize(buffer.readUInt8(), buffer); - } else if (marker === STRUCT_16) { - return this._unpackStructWithSize(buffer.readUInt16(), buffer); - } else { - return null; - } - } - }, { - key: "_unpackStructWithSize", - value: function _unpackStructWithSize(structSize, buffer) { - var signature = buffer.readUInt8(); - - if (signature === NODE) { - return this._unpackNode(structSize, buffer); - } else if (signature === RELATIONSHIP) { - return this._unpackRelationship(structSize, buffer); - } else if (signature === UNBOUND_RELATIONSHIP) { - return this._unpackUnboundRelationship(structSize, buffer); - } else if (signature === PATH) { - return this._unpackPath(structSize, buffer); - } else { - return this._unpackUnknownStruct(signature, structSize, buffer); - } - } - }, { - key: "_unpackNode", - value: function _unpackNode(structSize, buffer) { - this._verifyStructSize('Node', NODE_STRUCT_SIZE, structSize); - - return new graphTypes.Node(this.unpack(buffer), // Identity - this.unpack(buffer), // Labels - this.unpack(buffer) // Properties - ); - } - }, { - key: "_unpackRelationship", - value: function _unpackRelationship(structSize, buffer) { - this._verifyStructSize('Relationship', RELATIONSHIP_STRUCT_SIZE, structSize); - - return new graphTypes.Relationship(this.unpack(buffer), // Identity - this.unpack(buffer), // Start Node Identity - this.unpack(buffer), // End Node Identity - this.unpack(buffer), // Type - this.unpack(buffer) // Properties - ); - } - }, { - key: "_unpackUnboundRelationship", - value: function _unpackUnboundRelationship(structSize, buffer) { - this._verifyStructSize('UnboundRelationship', UNBOUND_RELATIONSHIP_STRUCT_SIZE, structSize); - - return new graphTypes.UnboundRelationship(this.unpack(buffer), // Identity - this.unpack(buffer), // Type - this.unpack(buffer) // Properties - ); - } - }, { - key: "_unpackPath", - value: function _unpackPath(structSize, buffer) { - this._verifyStructSize('Path', PATH_STRUCT_SIZE, structSize); - - var nodes = this.unpack(buffer); - var rels = this.unpack(buffer); - var sequence = this.unpack(buffer); - var segments = []; - var prevNode = nodes[0]; - - for (var i = 0; i < sequence.length; i += 2) { - var nextNode = nodes[sequence[i + 1]]; - var relIndex = sequence[i]; - var rel = void 0; - - if (relIndex > 0) { - rel = rels[relIndex - 1]; - - if (rel instanceof graphTypes.UnboundRelationship) { - // To avoid duplication, relationships in a path do not contain - // information about their start and end nodes, that's instead - // inferred from the path sequence. This is us inferring (and, - // for performance reasons remembering) the start/end of a rel. - rels[relIndex - 1] = rel = rel.bind(prevNode.identity, nextNode.identity); - } - } else { - rel = rels[-relIndex - 1]; - - if (rel instanceof graphTypes.UnboundRelationship) { - // See above - rels[-relIndex - 1] = rel = rel.bind(nextNode.identity, prevNode.identity); - } - } // Done hydrating one path segment. - - - segments.push(new graphTypes.PathSegment(prevNode, rel, nextNode)); - prevNode = nextNode; - } - - return new graphTypes.Path(nodes[0], nodes[nodes.length - 1], segments); - } - }, { - key: "_unpackUnknownStruct", - value: function _unpackUnknownStruct(signature, structSize, buffer) { - var result = new Structure(signature, []); - - for (var i = 0; i < structSize; i++) { - result.fields.push(this.unpack(buffer)); - } - - return result; - } - }, { - key: "_verifyStructSize", - value: function _verifyStructSize(structName, expectedSize, actualSize) { - if (expectedSize !== actualSize) { - throw (0, error.newError)("Wrong struct size for ".concat(structName, ", expected ").concat(expectedSize, " but was ").concat(actualSize), error.PROTOCOL_ERROR); - } - } - }]); - return Unpacker; -}(); - -exports.Unpacker = Unpacker; - -function isIterable(obj) { - if (obj == null) { - return false; - } - - return typeof obj[Symbol.iterator] === 'function'; -} -}); - -var requestMessage = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = exports.ALL = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* eslint-disable no-unused-vars */ -// Signature bytes for each request message type -var INIT = 0x01; // 0000 0001 // INIT - -var RESET = 0x0f; // 0000 1111 // RESET - -var RUN = 0x10; // 0001 0000 // RUN - -var PULL_ALL = 0x3f; // 0011 1111 // PULL_ALL - -var HELLO = 0x01; // 0000 0001 // HELLO - -var GOODBYE = 0x02; // 0000 0010 // GOODBYE - -var BEGIN = 0x11; // 0001 0001 // BEGIN - -var COMMIT = 0x12; // 0001 0010 // COMMIT - -var ROLLBACK = 0x13; // 0001 0011 // ROLLBACK - -var DISCARD = 0x2f; // 0010 1111 // DISCARD - -var PULL = 0x3f; // 0011 1111 // PULL - -var READ_MODE = 'r'; -/* eslint-enable no-unused-vars */ - -var NO_STATEMENT_ID = -1; -var ALL = -1; -exports.ALL = ALL; - -var RequestMessage = -/*#__PURE__*/ -function () { - function RequestMessage(signature, fields, toString) { - (0, _classCallCheck2["default"])(this, RequestMessage); - this.signature = signature; - this.fields = fields; - this.toString = toString; - } - /** - * Create a new INIT message. - * @param {string} clientName the client name. - * @param {Object} authToken the authentication token. - * @return {RequestMessage} new INIT message. - */ - - - (0, _createClass2["default"])(RequestMessage, null, [{ - key: "init", - value: function init(clientName, authToken) { - return new RequestMessage(INIT, [clientName, authToken], function () { - return "INIT ".concat(clientName, " {...}"); - }); - } - /** - * Create a new RUN message. - * @param {string} query the cypher query. - * @param {Object} parameters the query parameters. - * @return {RequestMessage} new RUN message. - */ - - }, { - key: "run", - value: function run(query, parameters) { - return new RequestMessage(RUN, [query, parameters], function () { - return "RUN ".concat(query, " ").concat(JSON.stringify(parameters)); - }); - } - /** - * Get a PULL_ALL message. - * @return {RequestMessage} the PULL_ALL message. - */ - - }, { - key: "pullAll", - value: function pullAll() { - return PULL_ALL_MESSAGE; - } - /** - * Get a RESET message. - * @return {RequestMessage} the RESET message. - */ - - }, { - key: "reset", - value: function reset() { - return RESET_MESSAGE; - } - /** - * Create a new HELLO message. - * @param {string} userAgent the user agent. - * @param {Object} authToken the authentication token. - * @param {Object} optional server side routing, set to routing context to turn on server side routing (> 4.1) - * @return {RequestMessage} new HELLO message. - */ - - }, { - key: "hello", - value: function hello(userAgent, authToken) { - var routing = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; - var metadata = Object.assign({ - user_agent: userAgent - }, authToken); - - if (routing != null) { - metadata.routing = routing; - } - - return new RequestMessage(HELLO, [metadata], function () { - return "HELLO {user_agent: '".concat(userAgent, "', ...}"); - }); - } - /** - * Create a new BEGIN message. - * @param {Bookmark} bookmark the bookmark. - * @param {TxConfig} txConfig the configuration. - * @param {string} database the database name. - * @param {string} mode the access mode. - * @return {RequestMessage} new BEGIN message. - */ - - }, { - key: "begin", - value: function begin() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - bookmark = _ref.bookmark, - txConfig = _ref.txConfig, - database = _ref.database, - mode = _ref.mode; - - var metadata = buildTxMetadata(bookmark, txConfig, database, mode); - return new RequestMessage(BEGIN, [metadata], function () { - return "BEGIN ".concat(JSON.stringify(metadata)); - }); - } - /** - * Get a COMMIT message. - * @return {RequestMessage} the COMMIT message. - */ - - }, { - key: "commit", - value: function commit() { - return COMMIT_MESSAGE; - } - /** - * Get a ROLLBACK message. - * @return {RequestMessage} the ROLLBACK message. - */ - - }, { - key: "rollback", - value: function rollback() { - return ROLLBACK_MESSAGE; - } - /** - * Create a new RUN message with additional metadata. - * @param {string} query the cypher query. - * @param {Object} parameters the query parameters. - * @param {Bookmark} bookmark the bookmark. - * @param {TxConfig} txConfig the configuration. - * @param {string} database the database name. - * @param {string} mode the access mode. - * @return {RequestMessage} new RUN message with additional metadata. - */ - - }, { - key: "runWithMetadata", - value: function runWithMetadata(query, parameters) { - var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - bookmark = _ref2.bookmark, - txConfig = _ref2.txConfig, - database = _ref2.database, - mode = _ref2.mode; - - var metadata = buildTxMetadata(bookmark, txConfig, database, mode); - return new RequestMessage(RUN, [query, parameters, metadata], function () { - return "RUN ".concat(query, " ").concat(JSON.stringify(parameters), " ").concat(JSON.stringify(metadata)); - }); - } - /** - * Get a GOODBYE message. - * @return {RequestMessage} the GOODBYE message. - */ - - }, { - key: "goodbye", - value: function goodbye() { - return GOODBYE_MESSAGE; - } - /** - * Generates a new PULL message with additional metadata. - * @param {Integer|number} stmtId - * @param {Integer|number} n - * @return {RequestMessage} the PULL message. - */ - - }, { - key: "pull", - value: function pull() { - var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref3$stmtId = _ref3.stmtId, - stmtId = _ref3$stmtId === void 0 ? NO_STATEMENT_ID : _ref3$stmtId, - _ref3$n = _ref3.n, - n = _ref3$n === void 0 ? ALL : _ref3$n; - - var metadata = buildStreamMetadata(stmtId || NO_STATEMENT_ID, n || ALL); - return new RequestMessage(PULL, [metadata], function () { - return "PULL ".concat(JSON.stringify(metadata)); - }); - } - /** - * Generates a new DISCARD message with additional metadata. - * @param {Integer|number} stmtId - * @param {Integer|number} n - * @return {RequestMessage} the PULL message. - */ - - }, { - key: "discard", - value: function discard() { - var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref4$stmtId = _ref4.stmtId, - stmtId = _ref4$stmtId === void 0 ? NO_STATEMENT_ID : _ref4$stmtId, - _ref4$n = _ref4.n, - n = _ref4$n === void 0 ? ALL : _ref4$n; - - var metadata = buildStreamMetadata(stmtId || NO_STATEMENT_ID, n || ALL); - return new RequestMessage(DISCARD, [metadata], function () { - return "DISCARD ".concat(JSON.stringify(metadata)); - }); - } - }]); - return RequestMessage; -}(); -/** - * Create an object that represent transaction metadata. - * @param {Bookmark} bookmark the bookmark. - * @param {TxConfig} txConfig the configuration. - * @param {string} database the database name. - * @param {string} mode the access mode. - * @return {Object} a metadata object. - */ - - -exports["default"] = RequestMessage; - -function buildTxMetadata(bookmark, txConfig, database, mode) { - var metadata = {}; - - if (!bookmark.isEmpty()) { - metadata.bookmarks = bookmark.values(); - } - - if (txConfig.timeout) { - metadata.tx_timeout = txConfig.timeout; - } - - if (txConfig.metadata) { - metadata.tx_metadata = txConfig.metadata; - } - - if (database) { - metadata.db = (0, util.assertString)(database, 'database'); - } - - if (mode === constants.ACCESS_MODE_READ) { - metadata.mode = READ_MODE; - } - - return metadata; -} -/** - * Create an object that represents streaming metadata. - * @param {Integer|number} stmtId The query id to stream its results. - * @param {Integer|number} n The number of records to stream. - * @returns {Object} a metadata object. - */ - - -function buildStreamMetadata(stmtId, n) { - var metadata = { - n: (0, integer["int"])(n) - }; - - if (stmtId !== NO_STATEMENT_ID) { - metadata.qid = (0, integer["int"])(stmtId); - } - - return metadata; -} // constants for messages that never change - - -var PULL_ALL_MESSAGE = new RequestMessage(PULL_ALL, [], function () { - return 'PULL_ALL'; -}); -var RESET_MESSAGE = new RequestMessage(RESET, [], function () { - return 'RESET'; -}); -var COMMIT_MESSAGE = new RequestMessage(COMMIT, [], function () { - return 'COMMIT'; -}); -var ROLLBACK_MESSAGE = new RequestMessage(ROLLBACK, [], function () { - return 'ROLLBACK'; -}); -var GOODBYE_MESSAGE = new RequestMessage(GOODBYE, [], function () { - return 'GOODBYE'; -}); -}); - -var txConfig = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var util$1 = interopRequireWildcard(util); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Internal holder of the transaction configuration. - * It performs input validation and value conversion for further serialization by the Bolt protocol layer. - * Users of the driver provide transaction configuration as regular objects `{timeout: 10, metadata: {key: 'value'}}`. - * Driver converts such objects to {@link TxConfig} immediately and uses converted values everywhere. - */ -var TxConfig = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {Object} config the raw configuration object. - */ - function TxConfig(config) { - (0, _classCallCheck2["default"])(this, TxConfig); - assertValidConfig(config); - this.timeout = extractTimeout(config); - this.metadata = extractMetadata(config); - } - /** - * Get an empty config object. - * @return {TxConfig} an empty config. - */ - - - (0, _createClass2["default"])(TxConfig, [{ - key: "isEmpty", - - /** - * Check if this config object is empty. I.e. has no configuration values specified. - * @return {boolean} `true` if this object is empty, `false` otherwise. - */ - value: function isEmpty() { - return Object.values(this).every(function (value) { - return value == null; - }); - } - }], [{ - key: "empty", - value: function empty() { - return EMPTY_CONFIG; - } - }]); - return TxConfig; -}(); - -exports["default"] = TxConfig; -var EMPTY_CONFIG = new TxConfig({}); -/** - * @return {Integer|null} - */ - -function extractTimeout(config) { - if (util$1.isObject(config) && (config.timeout || config.timeout === 0)) { - util$1.assertNumberOrInteger(config.timeout, 'Transaction timeout'); - var timeout = (0, integer["int"])(config.timeout); - - if (timeout.isZero()) { - throw (0, error.newError)('Transaction timeout should not be zero'); - } - - if (timeout.isNegative()) { - throw (0, error.newError)('Transaction timeout should not be negative'); - } - - return timeout; - } - - return null; -} -/** - * @return {object|null} - */ - - -function extractMetadata(config) { - if (util$1.isObject(config) && config.metadata) { - var metadata = config.metadata; - util$1.assertObject(metadata); - - if (Object.keys(metadata).length !== 0) { - // not an empty object - return metadata; - } - } - - return null; -} - -function assertValidConfig(config) { - if (config) { - util$1.assertObject(config, 'Transaction config'); - } -} -}); - -var boltProtocolV1 = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -var _bookmark = interopRequireDefault(bookmark); - - - -interopRequireDefault(connection); - - - -var v1 = interopRequireWildcard(packstreamV1); - -var _requestMessage = interopRequireDefault(requestMessage); - - - -var _txConfig = interopRequireDefault(txConfig); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var BoltProtocol = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {Connection} connection the connection. - * @param {Chunker} chunker the chunker. - * @param {boolean} disableLosslessIntegers if this connection should convert all received integers to native JS numbers. - */ - function BoltProtocol(connection, chunker, disableLosslessIntegers) { - (0, _classCallCheck2["default"])(this, BoltProtocol); - this._connection = connection; - this._packer = this._createPacker(chunker); - this._unpacker = this._createUnpacker(disableLosslessIntegers); - } - /** - * Returns the numerical version identifier for this protocol - */ - - - (0, _createClass2["default"])(BoltProtocol, [{ - key: "packer", - - /** - * Get the packer. - * @return {Packer} the protocol's packer. - */ - value: function packer() { - return this._packer; - } - /** - * Get the unpacker. - * @return {Unpacker} the protocol's unpacker. - */ - - }, { - key: "unpacker", - value: function unpacker() { - return this._unpacker; - } - /** - * Transform metadata received in SUCCESS message before it is passed to the handler. - * @param {Object} metadata the received metadata. - * @return {Object} transformed metadata. - */ - - }, { - key: "transformMetadata", - value: function transformMetadata(metadata) { - return metadata; - } - /** - * Perform initialization and authentication of the underlying connection. - * @param {Object} param - * @param {string} param.userAgent the user agent. - * @param {Object} param.authToken the authentication token. - * @param {function(err: Error)} param.onError the callback to invoke on error. - * @param {function()} param.onComplete the callback to invoke on completion. - * @returns {StreamObserver} the stream observer that monitors the corresponding server response. - */ - - }, { - key: "initialize", - value: function initialize() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - userAgent = _ref.userAgent, - authToken = _ref.authToken, - onError = _ref.onError, - onComplete = _ref.onComplete; - - var observer = new streamObservers.LoginObserver({ - connection: this._connection, - afterError: onError, - afterComplete: onComplete - }); - - this._connection.write(_requestMessage["default"].init(userAgent, authToken), observer, true); - - return observer; - } - /** - * Perform protocol related operations for closing this connection - */ - - }, { - key: "prepareToClose", - value: function prepareToClose() {} // no need to notify the database in this protocol version - - /** - * Begin an explicit transaction. - * @param {Object} param - * @param {Bookmark} param.bookmark the bookmark. - * @param {TxConfig} param.txConfig the configuration. - * @param {string} param.database the target database name. - * @param {string} param.mode the access mode. - * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error. - * @param {function(err: Error)} param.afterError the callback to invoke after handling the error. - * @param {function()} param.beforeComplete the callback to invoke before handling the completion. - * @param {function()} param.afterComplete the callback to invoke after handling the completion. - * @returns {StreamObserver} the stream observer that monitors the corresponding server response. - */ - - }, { - key: "beginTransaction", - value: function beginTransaction() { - var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - bookmark = _ref2.bookmark, - txConfig = _ref2.txConfig, - database = _ref2.database, - mode = _ref2.mode, - beforeError = _ref2.beforeError, - afterError = _ref2.afterError, - beforeComplete = _ref2.beforeComplete, - afterComplete = _ref2.afterComplete; - - return this.run('BEGIN', bookmark ? bookmark.asBeginTransactionParameters() : {}, { - bookmark: bookmark, - txConfig: txConfig, - database: database, - mode: mode, - beforeError: beforeError, - afterError: afterError, - beforeComplete: beforeComplete, - afterComplete: afterComplete, - flush: false - }); - } - /** - * Commit the explicit transaction. - * @param {Object} param - * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error. - * @param {function(err: Error)} param.afterError the callback to invoke after handling the error. - * @param {function()} param.beforeComplete the callback to invoke before handling the completion. - * @param {function()} param.afterComplete the callback to invoke after handling the completion. - * @returns {StreamObserver} the stream observer that monitors the corresponding server response. - */ - - }, { - key: "commitTransaction", - value: function commitTransaction() { - var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - beforeError = _ref3.beforeError, - afterError = _ref3.afterError, - beforeComplete = _ref3.beforeComplete, - afterComplete = _ref3.afterComplete; - - // WRITE access mode is used as a place holder here, it has - // no effect on behaviour for Bolt V1 & V2 - return this.run('COMMIT', {}, { - bookmark: _bookmark["default"].empty(), - txConfig: _txConfig["default"].empty(), - mode: constants.ACCESS_MODE_WRITE, - beforeError: beforeError, - afterError: afterError, - beforeComplete: beforeComplete, - afterComplete: afterComplete - }); - } - /** - * Rollback the explicit transaction. - * @param {Object} param - * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error. - * @param {function(err: Error)} param.afterError the callback to invoke after handling the error. - * @param {function()} param.beforeComplete the callback to invoke before handling the completion. - * @param {function()} param.afterComplete the callback to invoke after handling the completion. - * @returns {StreamObserver} the stream observer that monitors the corresponding server response. - */ - - }, { - key: "rollbackTransaction", - value: function rollbackTransaction() { - var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - beforeError = _ref4.beforeError, - afterError = _ref4.afterError, - beforeComplete = _ref4.beforeComplete, - afterComplete = _ref4.afterComplete; - - // WRITE access mode is used as a place holder here, it has - // no effect on behaviour for Bolt V1 & V2 - return this.run('ROLLBACK', {}, { - bookmark: _bookmark["default"].empty(), - txConfig: _txConfig["default"].empty(), - mode: constants.ACCESS_MODE_WRITE, - beforeError: beforeError, - afterError: afterError, - beforeComplete: beforeComplete, - afterComplete: afterComplete - }); - } - /** - * Send a Cypher query through the underlying connection. - * @param {string} query the cypher query. - * @param {Object} parameters the query parameters. - * @param {Object} param - * @param {Bookmark} param.bookmark the bookmark. - * @param {TxConfig} param.txConfig the transaction configuration. - * @param {string} param.database the target database name. - * @param {string} param.mode the access mode. - * @param {function(keys: string[])} param.beforeKeys the callback to invoke before handling the keys. - * @param {function(keys: string[])} param.afterKeys the callback to invoke after handling the keys. - * @param {function(err: Error)} param.beforeError the callback to invoke before handling the error. - * @param {function(err: Error)} param.afterError the callback to invoke after handling the error. - * @param {function()} param.beforeComplete the callback to invoke before handling the completion. - * @param {function()} param.afterComplete the callback to invoke after handling the completion. - * @param {boolean} param.flush whether to flush the buffered messages. - * @returns {StreamObserver} the stream observer that monitors the corresponding server response. - */ - - }, { - key: "run", - value: function run(query, parameters) { - var _ref5 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - _ref5.bookmark; - var txConfig = _ref5.txConfig, - database = _ref5.database; - _ref5.mode; - var beforeKeys = _ref5.beforeKeys, - afterKeys = _ref5.afterKeys, - beforeError = _ref5.beforeError, - afterError = _ref5.afterError, - beforeComplete = _ref5.beforeComplete, - afterComplete = _ref5.afterComplete, - _ref5$flush = _ref5.flush, - flush = _ref5$flush === void 0 ? true : _ref5$flush; - - var observer = new streamObservers.ResultStreamObserver({ - connection: this._connection, - beforeKeys: beforeKeys, - afterKeys: afterKeys, - beforeError: beforeError, - afterError: afterError, - beforeComplete: beforeComplete, - afterComplete: afterComplete - }); // bookmark and mode are ignored in this version of the protocol - - (0, boltProtocolUtil.assertTxConfigIsEmpty)(txConfig, this._connection, observer); // passing in a database name on this protocol version throws an error - - (0, boltProtocolUtil.assertDatabaseIsEmpty)(database, this._connection, observer); - - this._connection.write(_requestMessage["default"].run(query, parameters), observer, false); - - this._connection.write(_requestMessage["default"].pullAll(), observer, flush); - - return observer; - } - /** - * Send a RESET through the underlying connection. - * @param {Object} param - * @param {function(err: Error)} param.onError the callback to invoke on error. - * @param {function()} param.onComplete the callback to invoke on completion. - * @returns {StreamObserver} the stream observer that monitors the corresponding server response. - */ - - }, { - key: "reset", - value: function reset() { - var _ref6 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - onError = _ref6.onError, - onComplete = _ref6.onComplete; - - var observer = new streamObservers.ResetObserver({ - connection: this._connection, - onError: onError, - onComplete: onComplete - }); - - this._connection.write(_requestMessage["default"].reset(), observer, true); - - return observer; - } - }, { - key: "_createPacker", - value: function _createPacker(chunker) { - return new v1.Packer(chunker); - } - }, { - key: "_createUnpacker", - value: function _createUnpacker(disableLosslessIntegers) { - return new v1.Unpacker(disableLosslessIntegers); - } - }, { - key: "version", - get: function get() { - return constants.BOLT_PROTOCOL_V1; - } - }]); - return BoltProtocol; -}(); - -exports["default"] = BoltProtocol; -}); - -var connection = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -interopRequireDefault(boltProtocolV1); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Connection = -/*#__PURE__*/ -function () { - /** - * @param {ConnectionErrorHandler} errorHandler the error handler - */ - function Connection(errorHandler) { - (0, _classCallCheck2["default"])(this, Connection); - this._errorHandler = errorHandler; - } - - (0, _createClass2["default"])(Connection, [{ - key: "isOpen", - - /** - * @returns {boolean} whether this connection is in a working condition - */ - value: function isOpen() { - throw new Error('not implemented'); - } - /** - * @returns {BoltProtocol} the underlying bolt protocol assigned to this connection - */ - - }, { - key: "protocol", - value: function protocol() { - throw new Error('not implemented'); - } - /** - * @returns {ServerAddress} the server address this connection is opened against - */ - - }, { - key: "connect", - - /** - * Connect to the target address, negotiate Bolt protocol and send initialization message. - * @param {string} userAgent the user agent for this driver. - * @param {Object} authToken the object containing auth information. - * @return {Promise} promise resolved with the current connection if connection is successful. Rejected promise otherwise. - */ - value: function connect(userAgent, authToken) { - throw new Error('not implemented'); - } - /** - * Write a message to the network channel. - * @param {RequestMessage} message the message to write. - * @param {ResultStreamObserver} observer the response observer. - * @param {boolean} flush `true` if flush should happen after the message is written to the buffer. - */ - - }, { - key: "write", - value: function write(message, observer, flush) { - throw new Error('not implemented'); - } - /** - * Send a RESET-message to the database. Message is immediately flushed to the network. - * @return {Promise} promise resolved when SUCCESS-message response arrives, or failed when other response messages arrives. - */ - - }, { - key: "resetAndFlush", - value: function resetAndFlush() { - throw new Error('not implemented'); - } - /** - * Call close on the channel. - * @returns {Promise} - A promise that will be resolved when the connection is closed. - * - */ - - }, { - key: "close", - value: function close() { - throw new Error('not implemented'); - } - /** - * - * @param error - * @param address - * @returns {Neo4jError|*} - */ - - }, { - key: "handleAndTransformError", - value: function handleAndTransformError(error, address) { - if (this._errorHandler) { - return this._errorHandler.handleAndTransformError(error, address); - } - - return error; - } - }, { - key: "id", - get: function get() { - throw new Error('not implemented'); - } - }, { - key: "databaseId", - get: function get() { - throw new Error('not implemented'); - }, - set: function set(value) { - throw new Error('not implemented'); - } - }, { - key: "address", - get: function get() { - throw new Error('not implemented'); - } - /** - * @returns {ServerVersion} the version of the server this connection is connected to - */ - - }, { - key: "version", - get: function get() { - throw new Error('not implemented'); - }, - set: function set(value) { - throw new Error('not implemented'); - } - }, { - key: "server", - get: function get() { - throw new Error('not implemented'); - } - }]); - return Connection; -}(); - -exports["default"] = Connection; -}); - -var streamObservers = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.CompletedObserver = exports.FailedObserver = exports.ResetObserver = exports.LoginObserver = exports.ResultStreamObserver = exports.StreamObserver = void 0; - -var _assertThisInitialized2 = interopRequireDefault(assertThisInitialized); - -var _get2 = interopRequireDefault(get$1); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _record = interopRequireDefault(record); - -interopRequireDefault(connection); - - - -interopRequireDefault(integer); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var StreamObserver = -/*#__PURE__*/ -function () { - function StreamObserver() { - (0, _classCallCheck2["default"])(this, StreamObserver); - } - - (0, _createClass2["default"])(StreamObserver, [{ - key: "onNext", - value: function onNext(rawRecord) {} - }, { - key: "onError", - value: function onError(error) {} - }, { - key: "onCompleted", - value: function onCompleted(meta) {} - }]); - return StreamObserver; -}(); -/** - * Handles a RUN/PULL_ALL, or RUN/DISCARD_ALL requests, maps the responses - * in a way that a user-provided observer can see these as a clean Stream - * of records. - * This class will queue up incoming messages until a user-provided observer - * for the incoming stream is registered. Thus, we keep fields around - * for tracking head/records/tail. These are only used if there is no - * observer registered. - * @access private - */ - - -exports.StreamObserver = StreamObserver; - -var ResultStreamObserver = -/*#__PURE__*/ -function (_StreamObserver) { - (0, _inherits2["default"])(ResultStreamObserver, _StreamObserver); - - /** - * - * @param {Object} param - * @param {Connection} param.connection - * @param {boolean} param.reactive - * @param {function(connection: Connection, stmtId: number|Integer, n: number|Integer, observer: StreamObserver)} param.moreFunction - - * @param {function(connection: Connection, stmtId: number|Integer, observer: StreamObserver)} param.discardFunction - - * @param {number|Integer} param.fetchSize - - * @param {function(err: Error): Promise|void} param.beforeError - - * @param {function(err: Error): Promise|void} param.afterError - - * @param {function(keys: string[]): Promise|void} param.beforeKeys - - * @param {function(keys: string[]): Promise|void} param.afterKeys - - * @param {function(metadata: Object): Promise|void} param.beforeComplete - - * @param {function(metadata: Object): Promise|void} param.afterComplete - - */ - function ResultStreamObserver() { - var _this; - - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - connection = _ref.connection, - _ref$reactive = _ref.reactive, - reactive = _ref$reactive === void 0 ? false : _ref$reactive, - moreFunction = _ref.moreFunction, - discardFunction = _ref.discardFunction, - _ref$fetchSize = _ref.fetchSize, - fetchSize = _ref$fetchSize === void 0 ? requestMessage.ALL : _ref$fetchSize, - beforeError = _ref.beforeError, - afterError = _ref.afterError, - beforeKeys = _ref.beforeKeys, - afterKeys = _ref.afterKeys, - beforeComplete = _ref.beforeComplete, - afterComplete = _ref.afterComplete; - - (0, _classCallCheck2["default"])(this, ResultStreamObserver); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ResultStreamObserver).call(this)); - _this._connection = connection; - _this._fieldKeys = null; - _this._fieldLookup = null; - _this._head = null; - _this._queuedRecords = []; - _this._tail = null; - _this._error = null; - _this._observers = []; - _this._meta = {}; - _this._beforeError = beforeError; - _this._afterError = afterError; - _this._beforeKeys = beforeKeys; - _this._afterKeys = afterKeys; - _this._beforeComplete = beforeComplete; - _this._afterComplete = afterComplete; - _this._queryId = null; - _this._moreFunction = moreFunction; - _this._discardFunction = discardFunction; - _this._discard = false; - _this._fetchSize = fetchSize; - - _this._setState(reactive ? _states.READY : _states.READY_STREAMING); - - _this._setupAuoPull(fetchSize); - - return _this; - } - /** - * Will be called on every record that comes in and transform a raw record - * to a Object. If user-provided observer is present, pass transformed record - * to it's onNext method, otherwise, push to record que. - * @param {Array} rawRecord - An array with the raw record - */ - - - (0, _createClass2["default"])(ResultStreamObserver, [{ - key: "onNext", - value: function onNext(rawRecord) { - var record = new _record["default"](this._fieldKeys, rawRecord, this._fieldLookup); - - if (this._observers.some(function (o) { - return o.onNext; - })) { - this._observers.forEach(function (o) { - if (o.onNext) { - o.onNext(record); - } - }); - } else { - this._queuedRecords.push(record); - - if (this._queuedRecords.length > this._highRecordWatermark) { - this._autoPull = false; - } - } - } - }, { - key: "onCompleted", - value: function onCompleted(meta) { - this._state.onSuccess(this, meta); - } - /** - * Will be called on errors. - * If user-provided observer is present, pass the error - * to it's onError method, otherwise set instance variable _error. - * @param {Object} error - An error object - */ - - }, { - key: "onError", - value: function onError(error) { - this._state.onError(this, error); - } - /** - * Cancel pending record stream - */ - - }, { - key: "cancel", - value: function cancel() { - this._discard = true; - } - /** - * Stream observer defaults to handling responses for two messages: RUN + PULL_ALL or RUN + DISCARD_ALL. - * Response for RUN initializes query keys. Response for PULL_ALL / DISCARD_ALL exposes the result stream. - * - * However, some operations can be represented as a single message which receives full metadata in a single response. - * For example, operations to begin, commit and rollback an explicit transaction use two messages in Bolt V1 but a single message in Bolt V3. - * Messages are `RUN "BEGIN" {}` + `PULL_ALL` in Bolt V1 and `BEGIN` in Bolt V3. - * - * This function prepares the observer to only handle a single response message. - */ - - }, { - key: "prepareToHandleSingleResponse", - value: function prepareToHandleSingleResponse() { - this._head = []; - this._fieldKeys = []; - - this._setState(_states.STREAMING); - } - /** - * Mark this observer as if it has completed with no metadata. - */ - - }, { - key: "markCompleted", - value: function markCompleted() { - this._head = []; - this._fieldKeys = []; - this._tail = {}; - - this._setState(_states.SUCCEEDED); - } - /** - * Subscribe to events with provided observer. - * @param {Object} observer - Observer object - * @param {function(keys: String[])} observer.onKeys - Handle stream header, field keys. - * @param {function(record: Object)} observer.onNext - Handle records, one by one. - * @param {function(metadata: Object)} observer.onCompleted - Handle stream tail, the metadata. - * @param {function(error: Object)} observer.onError - Handle errors, should always be provided. - */ - - }, { - key: "subscribe", - value: function subscribe(observer) { - if (this._error) { - observer.onError(this._error); - return; - } - - if (this._head && observer.onKeys) { - observer.onKeys(this._head); - } - - if (this._queuedRecords.length > 0 && observer.onNext) { - for (var i = 0; i < this._queuedRecords.length; i++) { - observer.onNext(this._queuedRecords[i]); - - if (this._queuedRecords.length - i - 1 <= this._lowRecordWatermark) { - this._autoPull = true; - - if (this._state === _states.READY) { - this._handleStreaming(); - } - } - } - } - - if (this._tail && observer.onCompleted) { - observer.onCompleted(this._tail); - } - - this._observers.push(observer); - - if (this._state === _states.READY) { - this._handleStreaming(); - } - } - }, { - key: "_handleHasMore", - value: function _handleHasMore(meta) { - // We've consumed current batch and server notified us that there're more - // records to stream. Let's invoke more or discard function based on whether - // the user wants to discard streaming or not - this._setState(_states.READY); // we've done streaming - - - this._handleStreaming(); - - delete meta.has_more; - } - }, { - key: "_handlePullSuccess", - value: function _handlePullSuccess(meta) { - var _this2 = this; - - this._setState(_states.SUCCEEDED); - - var completionMetadata = Object.assign(this._connection ? { - server: this._connection.server - } : {}, this._meta, meta); - var beforeHandlerResult = null; - - if (this._beforeComplete) { - beforeHandlerResult = this._beforeComplete(completionMetadata); - } - - var continuation = function continuation() { - // End of stream - _this2._tail = completionMetadata; - - if (_this2._observers.some(function (o) { - return o.onCompleted; - })) { - _this2._observers.forEach(function (o) { - if (o.onCompleted) { - o.onCompleted(completionMetadata); - } - }); - } - - if (_this2._afterComplete) { - _this2._afterComplete(completionMetadata); - } - }; - - if (beforeHandlerResult) { - Promise.resolve(beforeHandlerResult).then(function () { - return continuation(); - }); - } else { - continuation(); - } - } - }, { - key: "_handleRunSuccess", - value: function _handleRunSuccess(meta, afterSuccess) { - var _this3 = this; - - if (this._fieldKeys === null) { - // Stream header, build a name->index field lookup table - // to be used by records. This is an optimization to make it - // faster to look up fields in a record by name, rather than by index. - // Since the records we get back via Bolt are just arrays of values. - this._fieldKeys = []; - this._fieldLookup = {}; - - if (meta.fields && meta.fields.length > 0) { - this._fieldKeys = meta.fields; - - for (var i = 0; i < meta.fields.length; i++) { - this._fieldLookup[meta.fields[i]] = i; - } // remove fields key from metadata object - - - delete meta.fields; - } // Extract server generated query id for use in requestMore and discard - // functions - - - if (meta.qid) { - this._queryId = meta.qid; // remove qid from metadata object - - delete meta.qid; - } - - this._storeMetadataForCompletion(meta); - - var beforeHandlerResult = null; - - if (this._beforeKeys) { - beforeHandlerResult = this._beforeKeys(this._fieldKeys); - } - - var continuation = function continuation() { - _this3._head = _this3._fieldKeys; - - if (_this3._observers.some(function (o) { - return o.onKeys; - })) { - _this3._observers.forEach(function (o) { - if (o.onKeys) { - o.onKeys(_this3._fieldKeys); - } - }); - } - - if (_this3._afterKeys) { - _this3._afterKeys(_this3._fieldKeys); - } - - afterSuccess(); - }; - - if (beforeHandlerResult) { - Promise.resolve(beforeHandlerResult).then(function () { - return continuation(); - }); - } else { - continuation(); - } - } - } - }, { - key: "_handleError", - value: function _handleError(error) { - var _this4 = this; - - this._setState(_states.FAILED); - - this._error = error; - var beforeHandlerResult = null; - - if (this._beforeError) { - beforeHandlerResult = this._beforeError(error); - } - - var continuation = function continuation() { - if (_this4._observers.some(function (o) { - return o.onError; - })) { - _this4._observers.forEach(function (o) { - if (o.onError) { - o.onError(error); - } - }); - } - - if (_this4._afterError) { - _this4._afterError(error); - } - }; - - if (beforeHandlerResult) { - Promise.resolve(beforeHandlerResult).then(function () { - return continuation(); - }); - } else { - continuation(); - } - } - }, { - key: "_handleStreaming", - value: function _handleStreaming() { - if (this._head && this._observers.some(function (o) { - return o.onNext || o.onCompleted; - })) { - if (this._discard) { - this._discardFunction(this._connection, this._queryId, this); - - this._setState(_states.STREAMING); - } else if (this._autoPull) { - this._moreFunction(this._connection, this._queryId, this._fetchSize, this); - - this._setState(_states.STREAMING); - } - } - } - }, { - key: "_storeMetadataForCompletion", - value: function _storeMetadataForCompletion(meta) { - var keys = Object.keys(meta); - var index = keys.length; - var key = ''; - - while (index--) { - key = keys[index]; - this._meta[key] = meta[key]; - } - } - }, { - key: "_setState", - value: function _setState(state) { - this._state = state; - } - }, { - key: "_setupAuoPull", - value: function _setupAuoPull(fetchSize) { - this._autoPull = true; - - if (fetchSize === requestMessage.ALL) { - this._lowRecordWatermark = Number.MAX_VALUE; // we shall always lower than this number to enable auto pull - - this._highRecordWatermark = Number.MAX_VALUE; // we shall never reach this number to disable auto pull - } else { - this._lowRecordWatermark = 0.3 * fetchSize; - this._highRecordWatermark = 0.7 * fetchSize; - } - } - }]); - return ResultStreamObserver; -}(StreamObserver); - -exports.ResultStreamObserver = ResultStreamObserver; - -var LoginObserver = -/*#__PURE__*/ -function (_StreamObserver2) { - (0, _inherits2["default"])(LoginObserver, _StreamObserver2); - - /** - * - * @param {Object} param - - * @param {Connection} param.connection - * @param {function(err: Error)} param.beforeError - * @param {function(err: Error)} param.afterError - * @param {function(metadata)} param.beforeComplete - * @param {function(metadata)} param.afterComplete - */ - function LoginObserver() { - var _this5; - - var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - connection = _ref2.connection, - beforeError = _ref2.beforeError, - afterError = _ref2.afterError, - beforeComplete = _ref2.beforeComplete, - afterComplete = _ref2.afterComplete; - - (0, _classCallCheck2["default"])(this, LoginObserver); - _this5 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(LoginObserver).call(this)); - _this5._connection = connection; - _this5._beforeError = beforeError; - _this5._afterError = afterError; - _this5._beforeComplete = beforeComplete; - _this5._afterComplete = afterComplete; - return _this5; - } - - (0, _createClass2["default"])(LoginObserver, [{ - key: "onNext", - value: function onNext(record) { - this.onError((0, error.newError)('Received RECORD when initializing ' + JSON.stringify(record))); - } - }, { - key: "onError", - value: function onError(error) { - if (this._beforeError) { - this._beforeError(error); - } - - this._connection._updateCurrentObserver(); // make sure this exact observer will not be called again - - - this._connection._handleFatalError(error); // initialization errors are fatal - - - if (this._afterError) { - this._afterError(error); - } - } - }, { - key: "onCompleted", - value: function onCompleted(metadata) { - if (this._beforeComplete) { - this._beforeComplete(metadata); - } - - if (metadata) { - // read server version from the response metadata, if it is available - var serverVersion = metadata.server; - - if (!this._connection.version) { - this._connection.version = serverVersion; - } // read database connection id from the response metadata, if it is available - - - var dbConnectionId = metadata.connection_id; - - if (!this._connection.databaseId) { - this._connection.databaseId = dbConnectionId; - } - } - - if (this._afterComplete) { - this._afterComplete(metadata); - } - } - }]); - return LoginObserver; -}(StreamObserver); - -exports.LoginObserver = LoginObserver; - -var ResetObserver = -/*#__PURE__*/ -function (_StreamObserver3) { - (0, _inherits2["default"])(ResetObserver, _StreamObserver3); - - /** - * - * @param {Object} param - - * @param {Connection} param.connection - * @param {function(err: Error)} param.onError - * @param {function(metadata)} param.onComplete - */ - function ResetObserver() { - var _this6; - - var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - connection = _ref3.connection, - onError = _ref3.onError, - onComplete = _ref3.onComplete; - - (0, _classCallCheck2["default"])(this, ResetObserver); - _this6 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ResetObserver).call(this)); - _this6._connection = connection; - _this6._onError = onError; - _this6._onComplete = onComplete; - return _this6; - } - - (0, _createClass2["default"])(ResetObserver, [{ - key: "onNext", - value: function onNext(record) { - this.onError((0, error.newError)('Received RECORD when resetting: received record is: ' + JSON.stringify(record), error.PROTOCOL_ERROR)); - } - }, { - key: "onError", - value: function onError(error$1) { - if (error$1.code === error.PROTOCOL_ERROR) { - this._connection._handleProtocolError(error$1.message); - } - - if (this._onError) { - this._onError(error$1); - } - } - }, { - key: "onCompleted", - value: function onCompleted(metadata) { - if (this._onComplete) { - this._onComplete(metadata); - } - } - }]); - return ResetObserver; -}(StreamObserver); - -exports.ResetObserver = ResetObserver; - -var FailedObserver = -/*#__PURE__*/ -function (_ResultStreamObserver) { - (0, _inherits2["default"])(FailedObserver, _ResultStreamObserver); - - function FailedObserver(_ref4) { - var _this7; - - var error = _ref4.error, - onError = _ref4.onError; - (0, _classCallCheck2["default"])(this, FailedObserver); - _this7 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(FailedObserver).call(this, { - beforeError: onError - })); - - _this7.onError(error); - - return _this7; - } - - return FailedObserver; -}(ResultStreamObserver); - -exports.FailedObserver = FailedObserver; - -var CompletedObserver = -/*#__PURE__*/ -function (_ResultStreamObserver2) { - (0, _inherits2["default"])(CompletedObserver, _ResultStreamObserver2); - - function CompletedObserver() { - var _this8; - - (0, _classCallCheck2["default"])(this, CompletedObserver); - _this8 = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(CompletedObserver).call(this)); - (0, _get2["default"])((0, _getPrototypeOf2["default"])(CompletedObserver.prototype), "markCompleted", (0, _assertThisInitialized2["default"])(_this8)).call((0, _assertThisInitialized2["default"])(_this8)); - return _this8; - } - - return CompletedObserver; -}(ResultStreamObserver); - -exports.CompletedObserver = CompletedObserver; -var _states = { - READY_STREAMING: { - // async start state - onSuccess: function onSuccess(streamObserver, meta) { - streamObserver._handleRunSuccess(meta, function () { - streamObserver._setState(_states.STREAMING); - } // after run succeeded, async directly move to streaming - // state - ); - }, - onError: function onError(streamObserver, error) { - streamObserver._handleError(error); - }, - name: function name() { - return 'READY_STREAMING'; - } - }, - READY: { - // reactive start state - onSuccess: function onSuccess(streamObserver, meta) { - streamObserver._handleRunSuccess(meta, function () { - return streamObserver._handleStreaming(); - } // after run succeeded received, reactive shall start pulling - ); - }, - onError: function onError(streamObserver, error) { - streamObserver._handleError(error); - }, - name: function name() { - return 'READY'; - } - }, - STREAMING: { - onSuccess: function onSuccess(streamObserver, meta) { - if (meta.has_more) { - streamObserver._handleHasMore(meta); - } else { - streamObserver._handlePullSuccess(meta); - } - }, - onError: function onError(streamObserver, error) { - streamObserver._handleError(error); - }, - name: function name() { - return 'STREAMING'; - } - }, - FAILED: { - onError: function onError(error) {// more errors are ignored - }, - name: function name() { - return 'FAILED'; - } - }, - SUCCEEDED: { - name: function name() { - return 'SUCCEEDED'; - } - } -}; -}); - -var result = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _resultSummary = interopRequireDefault(resultSummary); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DEFAULT_ON_ERROR = function DEFAULT_ON_ERROR(error) { - console.log('Uncaught error when processing result: ' + error); -}; - -var DEFAULT_ON_COMPLETED = function DEFAULT_ON_COMPLETED(summary) {}; -/** - * A stream of {@link Record} representing the result of a query. - * Can be consumed eagerly as {@link Promise} resolved with array of records and {@link ResultSummary} - * summary, or rejected with error that contains {@link string} code and {@link string} message. - * Alternatively can be consumed lazily using {@link Result#subscribe} function. - * @access public - */ - - -var Result = -/*#__PURE__*/ -function () { - /** - * Inject the observer to be used. - * @constructor - * @access private - * @param {Promise} streamObserverPromise - * @param {mixed} query - Cypher query to execute - * @param {Object} parameters - Map with parameters to use in query - * @param {ConnectionHolder} connectionHolder - to be notified when result is either fully consumed or error happened. - */ - function Result(streamObserverPromise, query, parameters, connectionHolder$1) { - (0, _classCallCheck2["default"])(this, Result); - this._stack = captureStacktrace(); - this._streamObserverPromise = streamObserverPromise; - this._p = null; - this._query = query; - this._parameters = parameters || {}; - this._connectionHolder = connectionHolder$1 || connectionHolder.EMPTY_CONNECTION_HOLDER; - } - /** - * Returns a promise for the field keys. - * - * *Should not be combined with {@link Result#subscribe} function.* - * - * @public - * @returns {Promise} - Field keys, in the order they will appear in records. - } - */ - - - (0, _createClass2["default"])(Result, [{ - key: "keys", - value: function keys() { - var _this = this; - - return new Promise(function (resolve, reject) { - _this._streamObserverPromise.then(function (observer) { - return observer.subscribe({ - onKeys: function onKeys(keys) { - return resolve(keys); - }, - onError: function onError(err) { - return reject(err); - } - }); - }); - }); - } - /** - * Returns a promise for the result summary. - * - * *Should not be combined with {@link Result#subscribe} function.* - * - * @public - * @returns {Promise} - Result summary. - * - */ - - }, { - key: "summary", - value: function summary() { - var _this2 = this; - - return new Promise(function (resolve, reject) { - _this2._streamObserverPromise.then(function (o) { - o.cancel(); - o.subscribe({ - onCompleted: function onCompleted(metadata) { - return resolve(metadata); - }, - onError: function onError(err) { - return reject(err); - } - }); - }); - }); - } - /** - * Create and return new Promise - * - * @private - * @return {Promise} new Promise. - */ - - }, { - key: "_getOrCreatePromise", - value: function _getOrCreatePromise() { - var _this3 = this; - - if (!this._p) { - this._p = new Promise(function (resolve, reject) { - var records = []; - var observer = { - onNext: function onNext(record) { - records.push(record); - }, - onCompleted: function onCompleted(summary) { - resolve({ - records: records, - summary: summary - }); - }, - onError: function onError(error) { - reject(error); - } - }; - - _this3.subscribe(observer); - }); - } - - return this._p; - } - /** - * Waits for all results and calls the passed in function with the results. - * - * *Should not be combined with {@link Result#subscribe} function.* - * - * @param {function(result: {records:Array, summary: ResultSummary})} onFulfilled - function to be called - * when finished. - * @param {function(error: {message:string, code:string})} onRejected - function to be called upon errors. - * @return {Promise} promise. - */ - - }, { - key: "then", - value: function then(onFulfilled, onRejected) { - return this._getOrCreatePromise().then(onFulfilled, onRejected); - } - /** - * Catch errors when using promises. - * - * *Should not be combined with {@link Result#subscribe} function.* - * - * @param {function(error: Neo4jError)} onRejected - Function to be called upon errors. - * @return {Promise} promise. - */ - - }, { - key: "catch", - value: function _catch(onRejected) { - return this._getOrCreatePromise()["catch"](onRejected); - } - /** - * Stream records to observer as they come in, this is a more efficient method - * of handling the results, and allows you to handle arbitrarily large results. - * - * @param {Object} observer - Observer object - * @param {function(keys: string[])} observer.onKeys - handle stream head, the field keys. - * @param {function(record: Record)} observer.onNext - handle records, one by one. - * @param {function(summary: ResultSummary)} observer.onCompleted - handle stream tail, the result summary. - * @param {function(error: {message:string, code:string})} observer.onError - handle errors. - * @return - */ - - }, { - key: "subscribe", - value: function subscribe(observer) { - var _this4 = this; - - var onCompletedOriginal = observer.onCompleted || DEFAULT_ON_COMPLETED; - - var onCompletedWrapper = function onCompletedWrapper(metadata) { - var connectionHolder = _this4._connectionHolder; - var query = _this4._query; - var parameters = _this4._parameters; - - function complete(protocolVersion) { - onCompletedOriginal.call(observer, new _resultSummary["default"](query, parameters, metadata, protocolVersion)); - } - - function release() { - // notify connection holder that the used connection is not needed any more because result has - // been fully consumed; call the original onCompleted callback after that - return connectionHolder.releaseConnection(); - } - - connectionHolder.getConnection().then( // onFulfilled: - function (connection) { - release().then(function () { - return complete(connection !== undefined ? connection.protocol().version : undefined); - }); - }, // onRejected: - function (_) { - complete(); - }); - }; - - observer.onCompleted = onCompletedWrapper; - var onErrorOriginal = observer.onError || DEFAULT_ON_ERROR; - - var onErrorWrapper = function onErrorWrapper(error) { - // notify connection holder that the used connection is not needed any more because error happened - // and result can't bee consumed any further; call the original onError callback after that - _this4._connectionHolder.releaseConnection().then(function () { - replaceStacktrace(error, _this4._stack); - onErrorOriginal.call(observer, error); - }); - }; - - observer.onError = onErrorWrapper; - - this._streamObserverPromise.then(function (o) { - return o.subscribe(observer); - }); - } - /** - * Signals the stream observer that the future records should be discarded on the server. - * - * @protected - * @since 4.0.0 - */ - - }, { - key: "_cancel", - value: function _cancel() { - this._streamObserverPromise.then(function (o) { - return o.cancel(); - }); - } - }]); - return Result; -}(); - -function captureStacktrace() { - var error = new Error(''); - - if (error.stack) { - return error.stack.replace(/^Error(\n\r)*/, ''); // we don't need the 'Error\n' part, if only it exists - } - - return null; -} - -function replaceStacktrace(error, newStack) { - if (newStack) { - // Error.prototype.toString() concatenates error.name and error.message nicely - // then we add the rest of the stack trace - error.stack = error.toString() + '\n' + newStack; - } -} - -var _default = Result; -exports["default"] = _default; -}); - -var connectionProvider = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -interopRequireDefault(bookmark); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var ConnectionProvider = -/*#__PURE__*/ -function () { - function ConnectionProvider() { - (0, _classCallCheck2["default"])(this, ConnectionProvider); - } - - (0, _createClass2["default"])(ConnectionProvider, [{ - key: "acquireConnection", - - /** - * This method acquires a connection against the specified database. - * - * Access mode and Bookmarks only applies to routing driver. Access mode only - * differentiates the target server for the connection, where WRITE selects a - * WRITER server, whereas READ selects a READ server. Bookmarks, when specified, - * is only passed to the routing discovery procedure, for the system database to - * synchronize on creation of databases and is never used in direct drivers. - * - * @param {object} param - object parameter - * @param {string} param.accessMode - the access mode for the to-be-acquired connection - * @param {string} param.database - the target database for the to-be-acquired connection - * @param {Bookmark} param.bookmarks - the bookmarks to send to routing discovery - */ - value: function acquireConnection() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - _ref.accessMode; - _ref.database; - _ref.bookmarks; - - throw new Error('not implemented'); - } - /** - * This method checks whether the backend database supports multi database functionality - * by checking protocol handshake result. - * - * @returns {Promise} - */ - - }, { - key: "supportsMultiDb", - value: function supportsMultiDb() { - throw new Error('not implemented'); - } - /** - * This method checks whether the backend database supports transaction config functionality - * by checking protocol handshake result. - * - * @returns {Promise} - */ - - }, { - key: "supportsTransactionConfig", - value: function supportsTransactionConfig() { - throw new Error('not implemented'); - } - /** - * Closes this connection provider along with its internals (connections, pools, etc.) - * - * @returns {Promise} - */ - - }, { - key: "close", - value: function close() { - throw new Error('not implemented'); - } - }]); - return ConnectionProvider; -}(); - -exports["default"] = ConnectionProvider; -}); - -var asyncToGenerator = createCommonjsModule(function (module) { -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - Promise.resolve(value).then(_next, _throw); - } -} - -function _asyncToGenerator(fn) { - return function () { - var self = this, - args = arguments; - return new Promise(function (resolve, reject) { - var gen = fn.apply(self, args); - - function _next(value) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); - } - - function _throw(err) { - asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); - } - - _next(undefined); - }); - }; -} - -module.exports = _asyncToGenerator; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var channelConfig = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DEFAULT_CONNECTION_TIMEOUT_MILLIS = 30000; // 30 seconds by default - -var ALLOWED_VALUES_ENCRYPTED = [null, undefined, true, false, util.ENCRYPTION_ON, util.ENCRYPTION_OFF]; -var ALLOWED_VALUES_TRUST = [null, undefined, 'TRUST_ALL_CERTIFICATES', 'TRUST_CUSTOM_CA_SIGNED_CERTIFICATES', 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES']; - -var ChannelConfig = -/** - * @constructor - * @param {ServerAddress} address the address for the channel to connect to. - * @param {Object} driverConfig the driver config provided by the user when driver is created. - * @param {string} connectionErrorCode the default error code to use on connection errors. - */ -function ChannelConfig(address, driverConfig, connectionErrorCode) { - (0, _classCallCheck2["default"])(this, ChannelConfig); - this.address = address; - this.encrypted = extractEncrypted(driverConfig); - this.trust = extractTrust(driverConfig); - this.trustedCertificates = extractTrustedCertificates(driverConfig); - this.knownHostsPath = extractKnownHostsPath(driverConfig); - this.connectionErrorCode = connectionErrorCode || error.SERVICE_UNAVAILABLE; - this.connectionTimeout = extractConnectionTimeout(driverConfig); -}; - -exports["default"] = ChannelConfig; - -function extractEncrypted(driverConfig) { - var value = driverConfig.encrypted; - - if (ALLOWED_VALUES_ENCRYPTED.indexOf(value) === -1) { - throw (0, error.newError)("Illegal value of the encrypted setting ".concat(value, ". Expected one of ").concat(ALLOWED_VALUES_ENCRYPTED)); - } - - return value; -} - -function extractTrust(driverConfig) { - var value = driverConfig.trust; - - if (ALLOWED_VALUES_TRUST.indexOf(value) === -1) { - throw (0, error.newError)("Illegal value of the trust setting ".concat(value, ". Expected one of ").concat(ALLOWED_VALUES_TRUST)); - } - - return value; -} - -function extractTrustedCertificates(driverConfig) { - return driverConfig.trustedCertificates || []; -} - -function extractKnownHostsPath(driverConfig) { - return driverConfig.knownHosts || null; -} - -function extractConnectionTimeout(driverConfig) { - var configuredTimeout = parseInt(driverConfig.connectionTimeout, 10); - - if (configuredTimeout === 0) { - // timeout explicitly configured to 0 - return null; - } else if (configuredTimeout && configuredTimeout < 0) { - // timeout explicitly configured to a negative value - return null; - } else if (!configuredTimeout) { - // timeout not configured, use default value - return DEFAULT_CONNECTION_TIMEOUT_MILLIS; - } else { - // timeout configured, use the provided value - return configuredTimeout; - } -} -}); - -var spatialTypes = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isPoint = isPoint; -exports.Point = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var POINT_IDENTIFIER_PROPERTY = '__isPoint__'; -/** - * Represents a single two or three-dimensional point in a particular coordinate reference system. - * Created `Point` objects are frozen with `Object.freeze()` in constructor and thus immutable. - */ - -var Point = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {Integer|number} srid - The coordinate reference system identifier. - * @param {number} x - The `x` coordinate of the point. - * @param {number} y - The `y` coordinate of the point. - * @param {number} [z=undefined] - The `z` coordinate of the point or `undefined` if point has 2 dimensions. - */ - function Point(srid, x, y, z) { - (0, _classCallCheck2["default"])(this, Point); - - /** - * The coordinate reference system identifier. - * @type {Integer|number} - */ - this.srid = (0, util.assertNumberOrInteger)(srid, 'SRID'); - /** - * The `x` coordinate of the point. - * @type {number} - */ - - this.x = (0, util.assertNumber)(x, 'X coordinate'); - /** - * The `y` coordinate of the point. - * @type {number} - */ - - this.y = (0, util.assertNumber)(y, 'Y coordinate'); - /** - * The `z` coordinate of the point or `undefined` if point is 2-dimensional. - * @type {number} - */ - - this.z = z === null || z === undefined ? z : (0, util.assertNumber)(z, 'Z coordinate'); - Object.freeze(this); - } - /** - * @ignore - */ - - - (0, _createClass2["default"])(Point, [{ - key: "toString", - value: function toString() { - return this.z || this.z === 0 ? "Point{srid=".concat(formatAsFloat(this.srid), ", x=").concat(formatAsFloat(this.x), ", y=").concat(formatAsFloat(this.y), ", z=").concat(formatAsFloat(this.z), "}") : "Point{srid=".concat(formatAsFloat(this.srid), ", x=").concat(formatAsFloat(this.x), ", y=").concat(formatAsFloat(this.y), "}"); - } - }]); - return Point; -}(); - -exports.Point = Point; - -function formatAsFloat(number) { - return Number.isInteger(number) ? number + '.0' : number.toString(); -} - -Object.defineProperty(Point.prototype, POINT_IDENTIFIER_PROPERTY, { - value: true, - enumerable: false, - configurable: false, - writable: false -}); -/** - * Test if given object is an instance of {@link Point} class. - * @param {Object} obj the object to test. - * @return {boolean} `true` if given object is a {@link Point}, `false` otherwise. - */ - -function isPoint(obj) { - return (obj && obj[POINT_IDENTIFIER_PROPERTY]) === true; -} -}); - -var normalizeSecondsForDuration_1 = normalizeSecondsForDuration; -var normalizeNanosecondsForDuration_1 = normalizeNanosecondsForDuration; -var localTimeToNanoOfDay_1 = localTimeToNanoOfDay; -var nanoOfDayToLocalTime_1 = nanoOfDayToLocalTime; -var localDateTimeToEpochSecond_1 = localDateTimeToEpochSecond; -var epochSecondAndNanoToLocalDateTime_1 = epochSecondAndNanoToLocalDateTime; -var dateToEpochDay_1 = dateToEpochDay; -var epochDayToDate_1 = epochDayToDate; -var durationToIsoString_1 = durationToIsoString; -var timeToIsoString_1 = timeToIsoString; -var timeZoneOffsetToIsoString_1 = timeZoneOffsetToIsoString; -var dateToIsoString_1 = dateToIsoString; -var totalNanoseconds_1 = totalNanoseconds; -var timeZoneOffsetInSeconds_1 = timeZoneOffsetInSeconds; -var assertValidYear_1 = assertValidYear; -var assertValidMonth_1 = assertValidMonth; -var assertValidDay_1 = assertValidDay; -var assertValidHour_1 = assertValidHour; -var assertValidMinute_1 = assertValidMinute; -var assertValidSecond_1 = assertValidSecond; -var assertValidNanosecond_1 = assertValidNanosecond; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - - - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/* - Code in this util should be compatible with code in the database that uses JSR-310 java.time APIs. - - It is based on a library called ThreeTen (https://github.com/ThreeTen/threetenbp) which was derived - from JSR-310 reference implementation previously hosted on GitHub. Code uses `Integer` type everywhere - to correctly handle large integer values that are greater than `Number.MAX_SAFE_INTEGER`. - - Please consult either ThreeTen or js-joda (https://github.com/js-joda/js-joda) when working with the - conversion functions. - */ -var ValueRange = -/*#__PURE__*/ -function () { - function ValueRange(min, max) { - (0, _classCallCheck2["default"])(this, ValueRange); - this._minNumber = min; - this._maxNumber = max; - this._minInteger = (0, integer["int"])(min); - this._maxInteger = (0, integer["int"])(max); - } - - (0, _createClass2["default"])(ValueRange, [{ - key: "contains", - value: function contains(value) { - if ((0, integer.isInt)(value)) { - return value.greaterThanOrEqual(this._minInteger) && value.lessThanOrEqual(this._maxInteger); - } else { - return value >= this._minNumber && value <= this._maxNumber; - } - } - }, { - key: "toString", - value: function toString() { - return "[".concat(this._minNumber, ", ").concat(this._maxNumber, "]"); - } - }]); - return ValueRange; -}(); - -var YEAR_RANGE = new ValueRange(-999999999, 999999999); -var MONTH_OF_YEAR_RANGE = new ValueRange(1, 12); -var DAY_OF_MONTH_RANGE = new ValueRange(1, 31); -var HOUR_OF_DAY_RANGE = new ValueRange(0, 23); -var MINUTE_OF_HOUR_RANGE = new ValueRange(0, 59); -var SECOND_OF_MINUTE_RANGE = new ValueRange(0, 59); -var NANOSECOND_OF_SECOND_RANGE = new ValueRange(0, 999999999); -var MINUTES_PER_HOUR = 60; -var SECONDS_PER_MINUTE = 60; -var SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR; -var NANOS_PER_SECOND = 1000000000; -var NANOS_PER_MILLISECOND = 1000000; -var NANOS_PER_MINUTE = NANOS_PER_SECOND * SECONDS_PER_MINUTE; -var NANOS_PER_HOUR = NANOS_PER_MINUTE * MINUTES_PER_HOUR; -var DAYS_0000_TO_1970 = 719528; -var DAYS_PER_400_YEAR_CYCLE = 146097; -var SECONDS_PER_DAY = 86400; - -function normalizeSecondsForDuration(seconds, nanoseconds) { - return (0, integer["int"])(seconds).add(floorDiv(nanoseconds, NANOS_PER_SECOND)); -} - -function normalizeNanosecondsForDuration(nanoseconds) { - return floorMod(nanoseconds, NANOS_PER_SECOND); -} -/** - * Converts given local time into a single integer representing this same time in nanoseconds of the day. - * @param {Integer|number|string} hour the hour of the local time to convert. - * @param {Integer|number|string} minute the minute of the local time to convert. - * @param {Integer|number|string} second the second of the local time to convert. - * @param {Integer|number|string} nanosecond the nanosecond of the local time to convert. - * @return {Integer} nanoseconds representing the given local time. - */ - - -function localTimeToNanoOfDay(hour, minute, second, nanosecond) { - hour = (0, integer["int"])(hour); - minute = (0, integer["int"])(minute); - second = (0, integer["int"])(second); - nanosecond = (0, integer["int"])(nanosecond); - var totalNanos = hour.multiply(NANOS_PER_HOUR); - totalNanos = totalNanos.add(minute.multiply(NANOS_PER_MINUTE)); - totalNanos = totalNanos.add(second.multiply(NANOS_PER_SECOND)); - return totalNanos.add(nanosecond); -} -/** - * Converts nanoseconds of the day into local time. - * @param {Integer|number|string} nanoOfDay the nanoseconds of the day to convert. - * @return {LocalTime} the local time representing given nanoseconds of the day. - */ - - -function nanoOfDayToLocalTime(nanoOfDay) { - nanoOfDay = (0, integer["int"])(nanoOfDay); - var hour = nanoOfDay.div(NANOS_PER_HOUR); - nanoOfDay = nanoOfDay.subtract(hour.multiply(NANOS_PER_HOUR)); - var minute = nanoOfDay.div(NANOS_PER_MINUTE); - nanoOfDay = nanoOfDay.subtract(minute.multiply(NANOS_PER_MINUTE)); - var second = nanoOfDay.div(NANOS_PER_SECOND); - var nanosecond = nanoOfDay.subtract(second.multiply(NANOS_PER_SECOND)); - return new temporalTypes.LocalTime(hour, minute, second, nanosecond); -} -/** - * Converts given local date time into a single integer representing this same time in epoch seconds UTC. - * @param {Integer|number|string} year the year of the local date-time to convert. - * @param {Integer|number|string} month the month of the local date-time to convert. - * @param {Integer|number|string} day the day of the local date-time to convert. - * @param {Integer|number|string} hour the hour of the local date-time to convert. - * @param {Integer|number|string} minute the minute of the local date-time to convert. - * @param {Integer|number|string} second the second of the local date-time to convert. - * @param {Integer|number|string} nanosecond the nanosecond of the local date-time to convert. - * @return {Integer} epoch second in UTC representing the given local date time. - */ - - -function localDateTimeToEpochSecond(year, month, day, hour, minute, second, nanosecond) { - var epochDay = dateToEpochDay(year, month, day); - var localTimeSeconds = localTimeToSecondOfDay(hour, minute, second); - return epochDay.multiply(SECONDS_PER_DAY).add(localTimeSeconds); -} -/** - * Converts given epoch second and nanosecond adjustment into a local date time object. - * @param {Integer|number|string} epochSecond the epoch second to use. - * @param {Integer|number|string} nano the nanosecond to use. - * @return {LocalDateTime} the local date time representing given epoch second and nano. - */ - - -function epochSecondAndNanoToLocalDateTime(epochSecond, nano) { - var epochDay = floorDiv(epochSecond, SECONDS_PER_DAY); - var secondsOfDay = floorMod(epochSecond, SECONDS_PER_DAY); - var nanoOfDay = secondsOfDay.multiply(NANOS_PER_SECOND).add(nano); - var localDate = epochDayToDate(epochDay); - var localTime = nanoOfDayToLocalTime(nanoOfDay); - return new temporalTypes.LocalDateTime(localDate.year, localDate.month, localDate.day, localTime.hour, localTime.minute, localTime.second, localTime.nanosecond); -} -/** - * Converts given local date into a single integer representing it's epoch day. - * @param {Integer|number|string} year the year of the local date to convert. - * @param {Integer|number|string} month the month of the local date to convert. - * @param {Integer|number|string} day the day of the local date to convert. - * @return {Integer} epoch day representing the given date. - */ - - -function dateToEpochDay(year, month, day) { - year = (0, integer["int"])(year); - month = (0, integer["int"])(month); - day = (0, integer["int"])(day); - var epochDay = year.multiply(365); - - if (year.greaterThanOrEqual(0)) { - epochDay = epochDay.add(year.add(3).div(4).subtract(year.add(99).div(100)).add(year.add(399).div(400))); - } else { - epochDay = epochDay.subtract(year.div(-4).subtract(year.div(-100)).add(year.div(-400))); - } - - epochDay = epochDay.add(month.multiply(367).subtract(362).div(12)); - epochDay = epochDay.add(day.subtract(1)); - - if (month.greaterThan(2)) { - epochDay = epochDay.subtract(1); - - if (!isLeapYear(year)) { - epochDay = epochDay.subtract(1); - } - } - - return epochDay.subtract(DAYS_0000_TO_1970); -} -/** - * Converts given epoch day to a local date. - * @param {Integer|number|string} epochDay the epoch day to convert. - * @return {Date} the date representing the epoch day in years, months and days. - */ - - -function epochDayToDate(epochDay) { - epochDay = (0, integer["int"])(epochDay); - var zeroDay = epochDay.add(DAYS_0000_TO_1970).subtract(60); - var adjust = (0, integer["int"])(0); - - if (zeroDay.lessThan(0)) { - var adjustCycles = zeroDay.add(1).div(DAYS_PER_400_YEAR_CYCLE).subtract(1); - adjust = adjustCycles.multiply(400); - zeroDay = zeroDay.add(adjustCycles.multiply(-DAYS_PER_400_YEAR_CYCLE)); - } - - var year = zeroDay.multiply(400).add(591).div(DAYS_PER_400_YEAR_CYCLE); - var dayOfYearEst = zeroDay.subtract(year.multiply(365).add(year.div(4)).subtract(year.div(100)).add(year.div(400))); - - if (dayOfYearEst.lessThan(0)) { - year = year.subtract(1); - dayOfYearEst = zeroDay.subtract(year.multiply(365).add(year.div(4)).subtract(year.div(100)).add(year.div(400))); - } - - year = year.add(adjust); - var marchDayOfYear = dayOfYearEst; - var marchMonth = marchDayOfYear.multiply(5).add(2).div(153); - var month = marchMonth.add(2).modulo(12).add(1); - var day = marchDayOfYear.subtract(marchMonth.multiply(306).add(5).div(10)).add(1); - year = year.add(marchMonth.div(10)); - return new temporalTypes.Date(year, month, day); -} -/** - * Format given duration to an ISO 8601 string. - * @param {Integer|number|string} months the number of months. - * @param {Integer|number|string} days the number of days. - * @param {Integer|number|string} seconds the number of seconds. - * @param {Integer|number|string} nanoseconds the number of nanoseconds. - * @return {string} ISO string that represents given duration. - */ - - -function durationToIsoString(months, days, seconds, nanoseconds) { - var monthsString = formatNumber(months); - var daysString = formatNumber(days); - var secondsAndNanosecondsString = formatSecondsAndNanosecondsForDuration(seconds, nanoseconds); - return "P".concat(monthsString, "M").concat(daysString, "DT").concat(secondsAndNanosecondsString, "S"); -} -/** - * Formats given time to an ISO 8601 string. - * @param {Integer|number|string} hour the hour value. - * @param {Integer|number|string} minute the minute value. - * @param {Integer|number|string} second the second value. - * @param {Integer|number|string} nanosecond the nanosecond value. - * @return {string} ISO string that represents given time. - */ - - -function timeToIsoString(hour, minute, second, nanosecond) { - var hourString = formatNumber(hour, 2); - var minuteString = formatNumber(minute, 2); - var secondString = formatNumber(second, 2); - var nanosecondString = formatNanosecond(nanosecond); - return "".concat(hourString, ":").concat(minuteString, ":").concat(secondString).concat(nanosecondString); -} -/** - * Formats given time zone offset in seconds to string representation like '±HH:MM', '±HH:MM:SS' or 'Z' for UTC. - * @param {Integer|number|string} offsetSeconds the offset in seconds. - * @return {string} ISO string that represents given offset. - */ - - -function timeZoneOffsetToIsoString(offsetSeconds) { - offsetSeconds = (0, integer["int"])(offsetSeconds); - - if (offsetSeconds.equals(0)) { - return 'Z'; - } - - var isNegative = offsetSeconds.isNegative(); - - if (isNegative) { - offsetSeconds = offsetSeconds.multiply(-1); - } - - var signPrefix = isNegative ? '-' : '+'; - var hours = formatNumber(offsetSeconds.div(SECONDS_PER_HOUR), 2); - var minutes = formatNumber(offsetSeconds.div(SECONDS_PER_MINUTE).modulo(MINUTES_PER_HOUR), 2); - var secondsValue = offsetSeconds.modulo(SECONDS_PER_MINUTE); - var seconds = secondsValue.equals(0) ? null : formatNumber(secondsValue, 2); - return seconds ? "".concat(signPrefix).concat(hours, ":").concat(minutes, ":").concat(seconds) : "".concat(signPrefix).concat(hours, ":").concat(minutes); -} -/** - * Formats given date to an ISO 8601 string. - * @param {Integer|number|string} year the date year. - * @param {Integer|number|string} month the date month. - * @param {Integer|number|string} day the date day. - * @return {string} ISO string that represents given date. - */ - - -function dateToIsoString(year, month, day) { - year = (0, integer["int"])(year); - var isNegative = year.isNegative(); - - if (isNegative) { - year = year.multiply(-1); - } - - var yearString = formatNumber(year, 4); - - if (isNegative) { - yearString = '-' + yearString; - } - - var monthString = formatNumber(month, 2); - var dayString = formatNumber(day, 2); - return "".concat(yearString, "-").concat(monthString, "-").concat(dayString); -} -/** - * Get the total number of nanoseconds from the milliseconds of the given standard JavaScript date and optional nanosecond part. - * @param {global.Date} standardDate the standard JavaScript date. - * @param {Integer|number|undefined} nanoseconds the optional number of nanoseconds. - * @return {Integer|number} the total amount of nanoseconds. - */ - - -function totalNanoseconds(standardDate, nanoseconds) { - nanoseconds = nanoseconds || 0; - var nanosFromMillis = standardDate.getMilliseconds() * NANOS_PER_MILLISECOND; - return (0, integer.isInt)(nanoseconds) ? nanoseconds.add(nanosFromMillis) : nanoseconds + nanosFromMillis; -} -/** - * Get the time zone offset in seconds from the given standard JavaScript date. - * - * Implementation note: - * Time zone offset returned by the standard JavaScript date is the difference, in minutes, from local time to UTC. - * So positive value means offset is behind UTC and negative value means it is ahead. - * For Neo4j temporal types, like `Time` or `DateTime` offset is in seconds and represents difference from UTC to local time. - * This is different from standard JavaScript dates and that's why implementation negates the returned value. - * - * @param {global.Date} standardDate the standard JavaScript date. - * @return {number} the time zone offset in seconds. - */ - - -function timeZoneOffsetInSeconds(standardDate) { - var offsetInMinutes = standardDate.getTimezoneOffset(); - - if (offsetInMinutes === 0) { - return 0; - } - - return -1 * offsetInMinutes * SECONDS_PER_MINUTE; -} -/** - * Assert that the year value is valid. - * @param {Integer|number} year the value to check. - * @return {Integer|number} the value of the year if it is valid. Exception is thrown otherwise. - */ - - -function assertValidYear(year) { - return assertValidTemporalValue(year, YEAR_RANGE, 'Year'); -} -/** - * Assert that the month value is valid. - * @param {Integer|number} month the value to check. - * @return {Integer|number} the value of the month if it is valid. Exception is thrown otherwise. - */ - - -function assertValidMonth(month) { - return assertValidTemporalValue(month, MONTH_OF_YEAR_RANGE, 'Month'); -} -/** - * Assert that the day value is valid. - * @param {Integer|number} day the value to check. - * @return {Integer|number} the value of the day if it is valid. Exception is thrown otherwise. - */ - - -function assertValidDay(day) { - return assertValidTemporalValue(day, DAY_OF_MONTH_RANGE, 'Day'); -} -/** - * Assert that the hour value is valid. - * @param {Integer|number} hour the value to check. - * @return {Integer|number} the value of the hour if it is valid. Exception is thrown otherwise. - */ - - -function assertValidHour(hour) { - return assertValidTemporalValue(hour, HOUR_OF_DAY_RANGE, 'Hour'); -} -/** - * Assert that the minute value is valid. - * @param {Integer|number} minute the value to check. - * @return {Integer|number} the value of the minute if it is valid. Exception is thrown otherwise. - */ - - -function assertValidMinute(minute) { - return assertValidTemporalValue(minute, MINUTE_OF_HOUR_RANGE, 'Minute'); -} -/** - * Assert that the second value is valid. - * @param {Integer|number} second the value to check. - * @return {Integer|number} the value of the second if it is valid. Exception is thrown otherwise. - */ - - -function assertValidSecond(second) { - return assertValidTemporalValue(second, SECOND_OF_MINUTE_RANGE, 'Second'); -} -/** - * Assert that the nanosecond value is valid. - * @param {Integer|number} nanosecond the value to check. - * @return {Integer|number} the value of the nanosecond if it is valid. Exception is thrown otherwise. - */ - - -function assertValidNanosecond(nanosecond) { - return assertValidTemporalValue(nanosecond, NANOSECOND_OF_SECOND_RANGE, 'Nanosecond'); -} -/** - * Check if the given value is of expected type and is in the expected range. - * @param {Integer|number} value the value to check. - * @param {ValueRange} range the range. - * @param {string} name the name of the value. - * @return {Integer|number} the value if valid. Exception is thrown otherwise. - */ - - -function assertValidTemporalValue(value, range, name) { - (0, util.assertNumberOrInteger)(value, name); - - if (!range.contains(value)) { - throw (0, error.newError)("".concat(name, " is expected to be in range ").concat(range, " but was: ").concat(value)); - } - - return value; -} -/** - * Converts given local time into a single integer representing this same time in seconds of the day. Nanoseconds are skipped. - * @param {Integer|number|string} hour the hour of the local time. - * @param {Integer|number|string} minute the minute of the local time. - * @param {Integer|number|string} second the second of the local time. - * @return {Integer} seconds representing the given local time. - */ - - -function localTimeToSecondOfDay(hour, minute, second) { - hour = (0, integer["int"])(hour); - minute = (0, integer["int"])(minute); - second = (0, integer["int"])(second); - var totalSeconds = hour.multiply(SECONDS_PER_HOUR); - totalSeconds = totalSeconds.add(minute.multiply(SECONDS_PER_MINUTE)); - return totalSeconds.add(second); -} -/** - * Check if given year is a leap year. Uses algorithm described here {@link https://en.wikipedia.org/wiki/Leap_year#Algorithm}. - * @param {Integer|number|string} year the year to check. Will be converted to {@link Integer} for all calculations. - * @return {boolean} `true` if given year is a leap year, `false` otherwise. - */ - - -function isLeapYear(year) { - year = (0, integer["int"])(year); - - if (!year.modulo(4).equals(0)) { - return false; - } else if (!year.modulo(100).equals(0)) { - return true; - } else if (!year.modulo(400).equals(0)) { - return false; - } else { - return true; - } -} -/** - * @param {Integer|number|string} x the divident. - * @param {Integer|number|string} y the divisor. - * @return {Integer} the result. - */ - - -function floorDiv(x, y) { - x = (0, integer["int"])(x); - y = (0, integer["int"])(y); - var result = x.div(y); - - if (x.isPositive() !== y.isPositive() && result.multiply(y).notEquals(x)) { - result = result.subtract(1); - } - - return result; -} -/** - * @param {Integer|number|string} x the divident. - * @param {Integer|number|string} y the divisor. - * @return {Integer} the result. - */ - - -function floorMod(x, y) { - x = (0, integer["int"])(x); - y = (0, integer["int"])(y); - return x.subtract(floorDiv(x, y).multiply(y)); -} -/** - * @param {Integer|number|string} seconds the number of seconds to format. - * @param {Integer|number|string} nanoseconds the number of nanoseconds to format. - * @return {string} formatted value. - */ - - -function formatSecondsAndNanosecondsForDuration(seconds, nanoseconds) { - seconds = (0, integer["int"])(seconds); - nanoseconds = (0, integer["int"])(nanoseconds); - var secondsString; - var nanosecondsString; - var secondsNegative = seconds.isNegative(); - var nanosecondsGreaterThanZero = nanoseconds.greaterThan(0); - - if (secondsNegative && nanosecondsGreaterThanZero) { - if (seconds.equals(-1)) { - secondsString = '-0'; - } else { - secondsString = seconds.add(1).toString(); - } - } else { - secondsString = seconds.toString(); - } - - if (nanosecondsGreaterThanZero) { - if (secondsNegative) { - nanosecondsString = formatNanosecond(nanoseconds.negate().add(2 * NANOS_PER_SECOND).modulo(NANOS_PER_SECOND)); - } else { - nanosecondsString = formatNanosecond(nanoseconds.add(NANOS_PER_SECOND).modulo(NANOS_PER_SECOND)); - } - } - - return nanosecondsString ? secondsString + nanosecondsString : secondsString; -} -/** - * @param {Integer|number|string} value the number of nanoseconds to format. - * @return {string} formatted and possibly left-padded nanoseconds part as string. - */ - - -function formatNanosecond(value) { - value = (0, integer["int"])(value); - return value.equals(0) ? '' : '.' + formatNumber(value, 9); -} -/** - * @param {Integer|number|string} num the number to format. - * @param {number} [stringLength=undefined] the string length to left-pad to. - * @return {string} formatted and possibly left-padded number as string. - */ - - -function formatNumber(num) { - var stringLength = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - num = (0, integer["int"])(num); - var isNegative = num.isNegative(); - - if (isNegative) { - num = num.negate(); - } - - var numString = num.toString(); - - if (stringLength) { - // left pad the string with zeroes - while (numString.length < stringLength) { - numString = '0' + numString; - } - } - - return isNegative ? '-' + numString : numString; -} - -var temporalUtil = /*#__PURE__*/Object.defineProperty({ - normalizeSecondsForDuration: normalizeSecondsForDuration_1, - normalizeNanosecondsForDuration: normalizeNanosecondsForDuration_1, - localTimeToNanoOfDay: localTimeToNanoOfDay_1, - nanoOfDayToLocalTime: nanoOfDayToLocalTime_1, - localDateTimeToEpochSecond: localDateTimeToEpochSecond_1, - epochSecondAndNanoToLocalDateTime: epochSecondAndNanoToLocalDateTime_1, - dateToEpochDay: dateToEpochDay_1, - epochDayToDate: epochDayToDate_1, - durationToIsoString: durationToIsoString_1, - timeToIsoString: timeToIsoString_1, - timeZoneOffsetToIsoString: timeZoneOffsetToIsoString_1, - dateToIsoString: dateToIsoString_1, - totalNanoseconds: totalNanoseconds_1, - timeZoneOffsetInSeconds: timeZoneOffsetInSeconds_1, - assertValidYear: assertValidYear_1, - assertValidMonth: assertValidMonth_1, - assertValidDay: assertValidDay_1, - assertValidHour: assertValidHour_1, - assertValidMinute: assertValidMinute_1, - assertValidSecond: assertValidSecond_1, - assertValidNanosecond: assertValidNanosecond_1 -}, '__esModule', {value: true}); - -var temporalTypes = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isDuration = isDuration; -exports.isLocalTime = isLocalTime; -exports.isTime = isTime; -exports.isDate = isDate; -exports.isLocalDateTime = isLocalDateTime; -exports.isDateTime = isDateTime; -exports.DateTime = exports.LocalDateTime = exports.Date = exports.Time = exports.LocalTime = exports.Duration = void 0; - -var _slicedToArray2 = interopRequireDefault(slicedToArray); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var util$1 = interopRequireWildcard(temporalUtil); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var IDENTIFIER_PROPERTY_ATTRIBUTES = { - value: true, - enumerable: false, - configurable: false, - writable: false -}; -var DURATION_IDENTIFIER_PROPERTY = '__isDuration__'; -var LOCAL_TIME_IDENTIFIER_PROPERTY = '__isLocalTime__'; -var TIME_IDENTIFIER_PROPERTY = '__isTime__'; -var DATE_IDENTIFIER_PROPERTY = '__isDate__'; -var LOCAL_DATE_TIME_IDENTIFIER_PROPERTY = '__isLocalDateTime__'; -var DATE_TIME_IDENTIFIER_PROPERTY = '__isDateTime__'; -/** - * Represents an ISO 8601 duration. Contains both date-based values (years, months, days) and time-based values (seconds, nanoseconds). - * Created `Duration` objects are frozen with `Object.freeze()` in constructor and thus immutable. - */ - -var Duration = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {Integer|number} months - The number of months for the new duration. - * @param {Integer|number} days - The number of days for the new duration. - * @param {Integer|number} seconds - The number of seconds for the new duration. - * @param {Integer|number} nanoseconds - The number of nanoseconds for the new duration. - */ - function Duration(months, days, seconds, nanoseconds) { - (0, _classCallCheck2["default"])(this, Duration); - - /** - * The number of months. - * @type {Integer|number} - */ - this.months = (0, util.assertNumberOrInteger)(months, 'Months'); - /** - * The number of days. - * @type {Integer|number} - */ - - this.days = (0, util.assertNumberOrInteger)(days, 'Days'); - (0, util.assertNumberOrInteger)(seconds, 'Seconds'); - (0, util.assertNumberOrInteger)(nanoseconds, 'Nanoseconds'); - /** - * The number of seconds. - * @type {Integer|number} - */ - - this.seconds = util$1.normalizeSecondsForDuration(seconds, nanoseconds); - /** - * The number of nanoseconds. - * @type {Integer|number} - */ - - this.nanoseconds = util$1.normalizeNanosecondsForDuration(nanoseconds); - Object.freeze(this); - } - /** - * @ignore - */ - - - (0, _createClass2["default"])(Duration, [{ - key: "toString", - value: function toString() { - return util$1.durationToIsoString(this.months, this.days, this.seconds, this.nanoseconds); - } - }]); - return Duration; -}(); - -exports.Duration = Duration; -Object.defineProperty(Duration.prototype, DURATION_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); -/** - * Test if given object is an instance of {@link Duration} class. - * @param {Object} obj the object to test. - * @return {boolean} `true` if given object is a {@link Duration}, `false` otherwise. - */ - -function isDuration(obj) { - return hasIdentifierProperty(obj, DURATION_IDENTIFIER_PROPERTY); -} -/** - * Represents an instant capturing the time of day, but not the date, nor the timezone. - * Created {@link LocalTime} objects are frozen with `Object.freeze()` in constructor and thus immutable. - */ - - -var LocalTime = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {Integer|number} hour - The hour for the new local time. - * @param {Integer|number} minute - The minute for the new local time. - * @param {Integer|number} second - The second for the new local time. - * @param {Integer|number} nanosecond - The nanosecond for the new local time. - */ - function LocalTime(hour, minute, second, nanosecond) { - (0, _classCallCheck2["default"])(this, LocalTime); - - /** - * The hour. - * @type {Integer|number} - */ - this.hour = util$1.assertValidHour(hour); - /** - * The minute. - * @type {Integer|number} - */ - - this.minute = util$1.assertValidMinute(minute); - /** - * The second. - * @type {Integer|number} - */ - - this.second = util$1.assertValidSecond(second); - /** - * The nanosecond. - * @type {Integer|number} - */ - - this.nanosecond = util$1.assertValidNanosecond(nanosecond); - Object.freeze(this); - } - /** - * Create a {@link LocalTime} object from the given standard JavaScript `Date` and optional nanoseconds. - * Year, month, day and time zone offset components of the given date are ignored. - * @param {global.Date} standardDate - The standard JavaScript date to convert. - * @param {Integer|number|undefined} nanosecond - The optional amount of nanoseconds. - * @return {LocalTime} New LocalTime. - */ - - - (0, _createClass2["default"])(LocalTime, [{ - key: "toString", - - /** - * @ignore - */ - value: function toString() { - return util$1.timeToIsoString(this.hour, this.minute, this.second, this.nanosecond); - } - }], [{ - key: "fromStandardDate", - value: function fromStandardDate(standardDate, nanosecond) { - verifyStandardDateAndNanos(standardDate, nanosecond); - return new LocalTime(standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util$1.totalNanoseconds(standardDate, nanosecond)); - } - }]); - return LocalTime; -}(); - -exports.LocalTime = LocalTime; -Object.defineProperty(LocalTime.prototype, LOCAL_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); -/** - * Test if given object is an instance of {@link LocalTime} class. - * @param {Object} obj the object to test. - * @return {boolean} `true` if given object is a {@link LocalTime}, `false` otherwise. - */ - -function isLocalTime(obj) { - return hasIdentifierProperty(obj, LOCAL_TIME_IDENTIFIER_PROPERTY); -} -/** - * Represents an instant capturing the time of day, and the timezone offset in seconds, but not the date. - * Created {@link Time} objects are frozen with `Object.freeze()` in constructor and thus immutable. - */ - - -var Time = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {Integer|number} hour - The hour for the new local time. - * @param {Integer|number} minute - The minute for the new local time. - * @param {Integer|number} second - The second for the new local time. - * @param {Integer|number} nanosecond - The nanosecond for the new local time. - * @param {Integer|number} timeZoneOffsetSeconds - The time zone offset in seconds. Value represents the difference, in seconds, from UTC to local time. - * This is different from standard JavaScript `Date.getTimezoneOffset()` which is the difference, in minutes, from local time to UTC. - */ - function Time(hour, minute, second, nanosecond, timeZoneOffsetSeconds) { - (0, _classCallCheck2["default"])(this, Time); - - /** - * The hour. - * @type {Integer|number} - */ - this.hour = util$1.assertValidHour(hour); - /** - * The minute. - * @type {Integer|number} - */ - - this.minute = util$1.assertValidMinute(minute); - /** - * The second. - * @type {Integer|number} - */ - - this.second = util$1.assertValidSecond(second); - /** - * The nanosecond. - * @type {Integer|number} - */ - - this.nanosecond = util$1.assertValidNanosecond(nanosecond); - /** - * The time zone offset in seconds. - * @type {Integer|number} - */ - - this.timeZoneOffsetSeconds = (0, util.assertNumberOrInteger)(timeZoneOffsetSeconds, 'Time zone offset in seconds'); - Object.freeze(this); - } - /** - * Create a {@link Time} object from the given standard JavaScript `Date` and optional nanoseconds. - * Year, month and day components of the given date are ignored. - * @param {global.Date} standardDate - The standard JavaScript date to convert. - * @param {Integer|number|undefined} nanosecond - The optional amount of nanoseconds. - * @return {Time} New Time. - */ - - - (0, _createClass2["default"])(Time, [{ - key: "toString", - - /** - * @ignore - */ - value: function toString() { - return util$1.timeToIsoString(this.hour, this.minute, this.second, this.nanosecond) + util$1.timeZoneOffsetToIsoString(this.timeZoneOffsetSeconds); - } - }], [{ - key: "fromStandardDate", - value: function fromStandardDate(standardDate, nanosecond) { - verifyStandardDateAndNanos(standardDate, nanosecond); - return new Time(standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util$1.totalNanoseconds(standardDate, nanosecond), util$1.timeZoneOffsetInSeconds(standardDate)); - } - }]); - return Time; -}(); - -exports.Time = Time; -Object.defineProperty(Time.prototype, TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); -/** - * Test if given object is an instance of {@link Time} class. - * @param {Object} obj the object to test. - * @return {boolean} `true` if given object is a {@link Time}, `false` otherwise. - */ - -function isTime(obj) { - return hasIdentifierProperty(obj, TIME_IDENTIFIER_PROPERTY); -} -/** - * Represents an instant capturing the date, but not the time, nor the timezone. - * Created {@link Date} objects are frozen with `Object.freeze()` in constructor and thus immutable. - */ - - -var Date = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {Integer|number} year - The year for the new local date. - * @param {Integer|number} month - The month for the new local date. - * @param {Integer|number} day - The day for the new local date. - */ - function Date(year, month, day) { - (0, _classCallCheck2["default"])(this, Date); - - /** - * The year. - * @type {Integer|number} - */ - this.year = util$1.assertValidYear(year); - /** - * The month. - * @type {Integer|number} - */ - - this.month = util$1.assertValidMonth(month); - /** - * The day. - * @type {Integer|number} - */ - - this.day = util$1.assertValidDay(day); - Object.freeze(this); - } - /** - * Create a {@link Date} object from the given standard JavaScript `Date`. - * Hour, minute, second, millisecond and time zone offset components of the given date are ignored. - * @param {global.Date} standardDate - The standard JavaScript date to convert. - * @return {Date} New Date. - */ - - - (0, _createClass2["default"])(Date, [{ - key: "toString", - - /** - * @ignore - */ - value: function toString() { - return util$1.dateToIsoString(this.year, this.month, this.day); - } - }], [{ - key: "fromStandardDate", - value: function fromStandardDate(standardDate) { - verifyStandardDateAndNanos(standardDate, null); - return new Date(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate()); - } - }]); - return Date; -}(); - -exports.Date = Date; -Object.defineProperty(Date.prototype, DATE_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); -/** - * Test if given object is an instance of {@link Date} class. - * @param {Object} obj - The object to test. - * @return {boolean} `true` if given object is a {@link Date}, `false` otherwise. - */ - -function isDate(obj) { - return hasIdentifierProperty(obj, DATE_IDENTIFIER_PROPERTY); -} -/** - * Represents an instant capturing the date and the time, but not the timezone. - * Created {@link LocalDateTime} objects are frozen with `Object.freeze()` in constructor and thus immutable. - */ - - -var LocalDateTime = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {Integer|number} year - The year for the new local date. - * @param {Integer|number} month - The month for the new local date. - * @param {Integer|number} day - The day for the new local date. - * @param {Integer|number} hour - The hour for the new local time. - * @param {Integer|number} minute - The minute for the new local time. - * @param {Integer|number} second - The second for the new local time. - * @param {Integer|number} nanosecond - The nanosecond for the new local time. - */ - function LocalDateTime(year, month, day, hour, minute, second, nanosecond) { - (0, _classCallCheck2["default"])(this, LocalDateTime); - - /** - * The year. - * @type {Integer|number} - */ - this.year = util$1.assertValidYear(year); - /** - * The month. - * @type {Integer|number} - */ - - this.month = util$1.assertValidMonth(month); - /** - * The day. - * @type {Integer|number} - */ - - this.day = util$1.assertValidDay(day); - /** - * The hour. - * @type {Integer|number} - */ - - this.hour = util$1.assertValidHour(hour); - /** - * The minute. - * @type {Integer|number} - */ - - this.minute = util$1.assertValidMinute(minute); - /** - * The second. - * @type {Integer|number} - */ - - this.second = util$1.assertValidSecond(second); - /** - * The nanosecond. - * @type {Integer|number} - */ - - this.nanosecond = util$1.assertValidNanosecond(nanosecond); - Object.freeze(this); - } - /** - * Create a {@link LocalDateTime} object from the given standard JavaScript `Date` and optional nanoseconds. - * Time zone offset component of the given date is ignored. - * @param {global.Date} standardDate - The standard JavaScript date to convert. - * @param {Integer|number|undefined} nanosecond - The optional amount of nanoseconds. - * @return {LocalDateTime} New LocalDateTime. - */ - - - (0, _createClass2["default"])(LocalDateTime, [{ - key: "toString", - - /** - * @ignore - */ - value: function toString() { - return localDateTimeToString(this.year, this.month, this.day, this.hour, this.minute, this.second, this.nanosecond); - } - }], [{ - key: "fromStandardDate", - value: function fromStandardDate(standardDate, nanosecond) { - verifyStandardDateAndNanos(standardDate, nanosecond); - return new LocalDateTime(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate(), standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util$1.totalNanoseconds(standardDate, nanosecond)); - } - }]); - return LocalDateTime; -}(); - -exports.LocalDateTime = LocalDateTime; -Object.defineProperty(LocalDateTime.prototype, LOCAL_DATE_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); -/** - * Test if given object is an instance of {@link LocalDateTime} class. - * @param {Object} obj - The object to test. - * @return {boolean} `true` if given object is a {@link LocalDateTime}, `false` otherwise. - */ - -function isLocalDateTime(obj) { - return hasIdentifierProperty(obj, LOCAL_DATE_TIME_IDENTIFIER_PROPERTY); -} -/** - * Represents an instant capturing the date, the time and the timezone identifier. - * Created {@ DateTime} objects are frozen with `Object.freeze()` in constructor and thus immutable. - */ - - -var DateTime = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {Integer|number} year - The year for the new date-time. - * @param {Integer|number} month - The month for the new date-time. - * @param {Integer|number} day - The day for the new date-time. - * @param {Integer|number} hour - The hour for the new date-time. - * @param {Integer|number} minute - The minute for the new date-time. - * @param {Integer|number} second - The second for the new date-time. - * @param {Integer|number} nanosecond - The nanosecond for the new date-time. - * @param {Integer|number} timeZoneOffsetSeconds - The time zone offset in seconds. Either this argument or `timeZoneId` should be defined. - * Value represents the difference, in seconds, from UTC to local time. - * This is different from standard JavaScript `Date.getTimezoneOffset()` which is the difference, in minutes, from local time to UTC. - * @param {string|null} timeZoneId - The time zone id for the new date-time. Either this argument or `timeZoneOffsetSeconds` should be defined. - */ - function DateTime(year, month, day, hour, minute, second, nanosecond, timeZoneOffsetSeconds, timeZoneId) { - (0, _classCallCheck2["default"])(this, DateTime); - - /** - * The year. - * @type {Integer|number} - */ - this.year = util$1.assertValidYear(year); - /** - * The month. - * @type {Integer|number} - */ - - this.month = util$1.assertValidMonth(month); - /** - * The day. - * @type {Integer|number} - */ - - this.day = util$1.assertValidDay(day); - /** - * The hour. - * @type {Integer|number} - */ - - this.hour = util$1.assertValidHour(hour); - /** - * The minute. - * @type {Integer|number} - */ - - this.minute = util$1.assertValidMinute(minute); - /** - * The second. - * @type {Integer|number} - */ - - this.second = util$1.assertValidSecond(second); - /** - * The nanosecond. - * @type {Integer|number} - */ - - this.nanosecond = util$1.assertValidNanosecond(nanosecond); - - var _verifyTimeZoneArgume = verifyTimeZoneArguments(timeZoneOffsetSeconds, timeZoneId), - _verifyTimeZoneArgume2 = (0, _slicedToArray2["default"])(_verifyTimeZoneArgume, 2), - offset = _verifyTimeZoneArgume2[0], - id = _verifyTimeZoneArgume2[1]; - /** - * The time zone offset in seconds. - * - * *Either this or {@link timeZoneId} is defined.* - * - * @type {Integer|number} - */ - - - this.timeZoneOffsetSeconds = offset; - /** - * The time zone id. - * - * *Either this or {@link timeZoneOffsetSeconds} is defined.* - * - * @type {string} - */ - - this.timeZoneId = id; - Object.freeze(this); - } - /** - * Create a {@link DateTime} object from the given standard JavaScript `Date` and optional nanoseconds. - * @param {global.Date} standardDate - The standard JavaScript date to convert. - * @param {Integer|number|undefined} nanosecond - The optional amount of nanoseconds. - * @return {DateTime} New DateTime. - */ - - - (0, _createClass2["default"])(DateTime, [{ - key: "toString", - - /** - * @ignore - */ - value: function toString() { - var localDateTimeStr = localDateTimeToString(this.year, this.month, this.day, this.hour, this.minute, this.second, this.nanosecond); - var timeZoneStr = this.timeZoneId ? "[".concat(this.timeZoneId, "]") : util$1.timeZoneOffsetToIsoString(this.timeZoneOffsetSeconds); - return localDateTimeStr + timeZoneStr; - } - }], [{ - key: "fromStandardDate", - value: function fromStandardDate(standardDate, nanosecond) { - verifyStandardDateAndNanos(standardDate, nanosecond); - return new DateTime(standardDate.getFullYear(), standardDate.getMonth() + 1, standardDate.getDate(), standardDate.getHours(), standardDate.getMinutes(), standardDate.getSeconds(), util$1.totalNanoseconds(standardDate, nanosecond), util$1.timeZoneOffsetInSeconds(standardDate), null - /* no time zone id */ - ); - } - }]); - return DateTime; -}(); - -exports.DateTime = DateTime; -Object.defineProperty(DateTime.prototype, DATE_TIME_IDENTIFIER_PROPERTY, IDENTIFIER_PROPERTY_ATTRIBUTES); -/** - * Test if given object is an instance of {@link DateTime} class. - * @param {Object} obj - The object to test. - * @return {boolean} `true` if given object is a {@link DateTime}, `false` otherwise. - */ - -function isDateTime(obj) { - return hasIdentifierProperty(obj, DATE_TIME_IDENTIFIER_PROPERTY); -} - -function hasIdentifierProperty(obj, property) { - return (obj && obj[property]) === true; -} - -function localDateTimeToString(year, month, day, hour, minute, second, nanosecond) { - return util$1.dateToIsoString(year, month, day) + 'T' + util$1.timeToIsoString(hour, minute, second, nanosecond); -} - -function verifyTimeZoneArguments(timeZoneOffsetSeconds, timeZoneId) { - var offsetDefined = timeZoneOffsetSeconds || timeZoneOffsetSeconds === 0; - var idDefined = timeZoneId && timeZoneId !== ''; - - if (offsetDefined && !idDefined) { - (0, util.assertNumberOrInteger)(timeZoneOffsetSeconds, 'Time zone offset in seconds'); - return [timeZoneOffsetSeconds, null]; - } else if (!offsetDefined && idDefined) { - (0, util.assertString)(timeZoneId, 'Time zone ID'); - return [null, timeZoneId]; - } else if (offsetDefined && idDefined) { - throw (0, error.newError)("Unable to create DateTime with both time zone offset and id. Please specify either of them. Given offset: ".concat(timeZoneOffsetSeconds, " and id: ").concat(timeZoneId)); - } else { - throw (0, error.newError)("Unable to create DateTime without either time zone offset or id. Please specify either of them. Given offset: ".concat(timeZoneOffsetSeconds, " and id: ").concat(timeZoneId)); - } -} - -function verifyStandardDateAndNanos(standardDate, nanosecond) { - (0, util.assertValidDate)(standardDate, 'Standard date'); - - if (nanosecond !== null && nanosecond !== undefined) { - (0, util.assertNumberOrInteger)(nanosecond, 'Nanosecond'); - } -} -}); - -var packstreamV2 = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.Unpacker = exports.Packer = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _get2 = interopRequireDefault(get$1); - -var _inherits2 = interopRequireDefault(inherits); - -var v1 = interopRequireWildcard(packstreamV1); - - - - - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var POINT_2D = 0x58; -var POINT_2D_STRUCT_SIZE = 3; -var POINT_3D = 0x59; -var POINT_3D_STRUCT_SIZE = 4; -var DURATION = 0x45; -var DURATION_STRUCT_SIZE = 4; -var LOCAL_TIME = 0x74; -var LOCAL_TIME_STRUCT_SIZE = 1; -var TIME = 0x54; -var TIME_STRUCT_SIZE = 2; -var DATE = 0x44; -var DATE_STRUCT_SIZE = 1; -var LOCAL_DATE_TIME = 0x64; -var LOCAL_DATE_TIME_STRUCT_SIZE = 2; -var DATE_TIME_WITH_ZONE_OFFSET = 0x46; -var DATE_TIME_WITH_ZONE_OFFSET_STRUCT_SIZE = 3; -var DATE_TIME_WITH_ZONE_ID = 0x66; -var DATE_TIME_WITH_ZONE_ID_STRUCT_SIZE = 3; - -var Packer = -/*#__PURE__*/ -function (_v1$Packer) { - (0, _inherits2["default"])(Packer, _v1$Packer); - - function Packer() { - (0, _classCallCheck2["default"])(this, Packer); - return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(Packer).apply(this, arguments)); - } - - (0, _createClass2["default"])(Packer, [{ - key: "disableByteArrays", - value: function disableByteArrays() { - throw new Error('Bolt V2 should always support byte arrays'); - } - }, { - key: "packable", - value: function packable(obj) { - var _this = this; - - if ((0, spatialTypes.isPoint)(obj)) { - return function () { - return packPoint(obj, _this); - }; - } else if ((0, temporalTypes.isDuration)(obj)) { - return function () { - return packDuration(obj, _this); - }; - } else if ((0, temporalTypes.isLocalTime)(obj)) { - return function () { - return packLocalTime(obj, _this); - }; - } else if ((0, temporalTypes.isTime)(obj)) { - return function () { - return packTime(obj, _this); - }; - } else if ((0, temporalTypes.isDate)(obj)) { - return function () { - return packDate(obj, _this); - }; - } else if ((0, temporalTypes.isLocalDateTime)(obj)) { - return function () { - return packLocalDateTime(obj, _this); - }; - } else if ((0, temporalTypes.isDateTime)(obj)) { - return function () { - return packDateTime(obj, _this); - }; - } else { - return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Packer.prototype), "packable", this).call(this, obj); - } - } - }]); - return Packer; -}(v1.Packer); - -exports.Packer = Packer; - -var Unpacker = -/*#__PURE__*/ -function (_v1$Unpacker) { - (0, _inherits2["default"])(Unpacker, _v1$Unpacker); - - /** - * @constructor - * @param {boolean} disableLosslessIntegers if this unpacker should convert all received integers to native JS numbers. - */ - function Unpacker() { - var disableLosslessIntegers = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; - (0, _classCallCheck2["default"])(this, Unpacker); - return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(Unpacker).call(this, disableLosslessIntegers)); - } - - (0, _createClass2["default"])(Unpacker, [{ - key: "_unpackUnknownStruct", - value: function _unpackUnknownStruct(signature, structSize, buffer) { - if (signature === POINT_2D) { - return unpackPoint2D(this, structSize, buffer); - } else if (signature === POINT_3D) { - return unpackPoint3D(this, structSize, buffer); - } else if (signature === DURATION) { - return unpackDuration(this, structSize, buffer); - } else if (signature === LOCAL_TIME) { - return unpackLocalTime(this, structSize, buffer, this._disableLosslessIntegers); - } else if (signature === TIME) { - return unpackTime(this, structSize, buffer, this._disableLosslessIntegers); - } else if (signature === DATE) { - return unpackDate(this, structSize, buffer, this._disableLosslessIntegers); - } else if (signature === LOCAL_DATE_TIME) { - return unpackLocalDateTime(this, structSize, buffer, this._disableLosslessIntegers); - } else if (signature === DATE_TIME_WITH_ZONE_OFFSET) { - return unpackDateTimeWithZoneOffset(this, structSize, buffer, this._disableLosslessIntegers); - } else if (signature === DATE_TIME_WITH_ZONE_ID) { - return unpackDateTimeWithZoneId(this, structSize, buffer, this._disableLosslessIntegers); - } else { - return (0, _get2["default"])((0, _getPrototypeOf2["default"])(Unpacker.prototype), "_unpackUnknownStruct", this).call(this, signature, structSize, buffer, this._disableLosslessIntegers); - } - } - }]); - return Unpacker; -}(v1.Unpacker); -/** - * Pack given 2D or 3D point. - * @param {Point} point the point value to pack. - * @param {Packer} packer the packer to use. - */ - - -exports.Unpacker = Unpacker; - -function packPoint(point, packer) { - var is2DPoint = point.z === null || point.z === undefined; - - if (is2DPoint) { - packPoint2D(point, packer); - } else { - packPoint3D(point, packer); - } -} -/** - * Pack given 2D point. - * @param {Point} point the point value to pack. - * @param {Packer} packer the packer to use. - */ - - -function packPoint2D(point, packer) { - var packableStructFields = [packer.packable((0, integer["int"])(point.srid)), packer.packable(point.x), packer.packable(point.y)]; - packer.packStruct(POINT_2D, packableStructFields); -} -/** - * Pack given 3D point. - * @param {Point} point the point value to pack. - * @param {Packer} packer the packer to use. - */ - - -function packPoint3D(point, packer) { - var packableStructFields = [packer.packable((0, integer["int"])(point.srid)), packer.packable(point.x), packer.packable(point.y), packer.packable(point.z)]; - packer.packStruct(POINT_3D, packableStructFields); -} -/** - * Unpack 2D point value using the given unpacker. - * @param {Unpacker} unpacker the unpacker to use. - * @param {number} structSize the retrieved struct size. - * @param {BaseBuffer} buffer the buffer to unpack from. - * @return {Point} the unpacked 2D point value. - */ - - -function unpackPoint2D(unpacker, structSize, buffer) { - unpacker._verifyStructSize('Point2D', POINT_2D_STRUCT_SIZE, structSize); - - return new spatialTypes.Point(unpacker.unpack(buffer), // srid - unpacker.unpack(buffer), // x - unpacker.unpack(buffer), // y - undefined // z - ); -} -/** - * Unpack 3D point value using the given unpacker. - * @param {Unpacker} unpacker the unpacker to use. - * @param {number} structSize the retrieved struct size. - * @param {BaseBuffer} buffer the buffer to unpack from. - * @return {Point} the unpacked 3D point value. - */ - - -function unpackPoint3D(unpacker, structSize, buffer) { - unpacker._verifyStructSize('Point3D', POINT_3D_STRUCT_SIZE, structSize); - - return new spatialTypes.Point(unpacker.unpack(buffer), // srid - unpacker.unpack(buffer), // x - unpacker.unpack(buffer), // y - unpacker.unpack(buffer) // z - ); -} -/** - * Pack given duration. - * @param {Duration} value the duration value to pack. - * @param {Packer} packer the packer to use. - */ - - -function packDuration(value, packer) { - var months = (0, integer["int"])(value.months); - var days = (0, integer["int"])(value.days); - var seconds = (0, integer["int"])(value.seconds); - var nanoseconds = (0, integer["int"])(value.nanoseconds); - var packableStructFields = [packer.packable(months), packer.packable(days), packer.packable(seconds), packer.packable(nanoseconds)]; - packer.packStruct(DURATION, packableStructFields); -} -/** - * Unpack duration value using the given unpacker. - * @param {Unpacker} unpacker the unpacker to use. - * @param {number} structSize the retrieved struct size. - * @param {BaseBuffer} buffer the buffer to unpack from. - * @return {Duration} the unpacked duration value. - */ - - -function unpackDuration(unpacker, structSize, buffer) { - unpacker._verifyStructSize('Duration', DURATION_STRUCT_SIZE, structSize); - - var months = unpacker.unpack(buffer); - var days = unpacker.unpack(buffer); - var seconds = unpacker.unpack(buffer); - var nanoseconds = unpacker.unpack(buffer); - return new temporalTypes.Duration(months, days, seconds, nanoseconds); -} -/** - * Pack given local time. - * @param {LocalTime} value the local time value to pack. - * @param {Packer} packer the packer to use. - */ - - -function packLocalTime(value, packer) { - var nanoOfDay = (0, temporalUtil.localTimeToNanoOfDay)(value.hour, value.minute, value.second, value.nanosecond); - var packableStructFields = [packer.packable(nanoOfDay)]; - packer.packStruct(LOCAL_TIME, packableStructFields); -} -/** - * Unpack local time value using the given unpacker. - * @param {Unpacker} unpacker the unpacker to use. - * @param {number} structSize the retrieved struct size. - * @param {BaseBuffer} buffer the buffer to unpack from. - * @param {boolean} disableLosslessIntegers if integer properties in the result local time should be native JS numbers. - * @return {LocalTime} the unpacked local time value. - */ - - -function unpackLocalTime(unpacker, structSize, buffer, disableLosslessIntegers) { - unpacker._verifyStructSize('LocalTime', LOCAL_TIME_STRUCT_SIZE, structSize); - - var nanoOfDay = unpacker.unpackInteger(buffer); - var result = (0, temporalUtil.nanoOfDayToLocalTime)(nanoOfDay); - return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); -} -/** - * Pack given time. - * @param {Time} value the time value to pack. - * @param {Packer} packer the packer to use. - */ - - -function packTime(value, packer) { - var nanoOfDay = (0, temporalUtil.localTimeToNanoOfDay)(value.hour, value.minute, value.second, value.nanosecond); - var offsetSeconds = (0, integer["int"])(value.timeZoneOffsetSeconds); - var packableStructFields = [packer.packable(nanoOfDay), packer.packable(offsetSeconds)]; - packer.packStruct(TIME, packableStructFields); -} -/** - * Unpack time value using the given unpacker. - * @param {Unpacker} unpacker the unpacker to use. - * @param {number} structSize the retrieved struct size. - * @param {BaseBuffer} buffer the buffer to unpack from. - * @param {boolean} disableLosslessIntegers if integer properties in the result time should be native JS numbers. - * @return {Time} the unpacked time value. - */ - - -function unpackTime(unpacker, structSize, buffer, disableLosslessIntegers) { - unpacker._verifyStructSize('Time', TIME_STRUCT_SIZE, structSize); - - var nanoOfDay = unpacker.unpackInteger(buffer); - var offsetSeconds = unpacker.unpackInteger(buffer); - var localTime = (0, temporalUtil.nanoOfDayToLocalTime)(nanoOfDay); - var result = new temporalTypes.Time(localTime.hour, localTime.minute, localTime.second, localTime.nanosecond, offsetSeconds); - return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); -} -/** - * Pack given neo4j date. - * @param {Date} value the date value to pack. - * @param {Packer} packer the packer to use. - */ - - -function packDate(value, packer) { - var epochDay = (0, temporalUtil.dateToEpochDay)(value.year, value.month, value.day); - var packableStructFields = [packer.packable(epochDay)]; - packer.packStruct(DATE, packableStructFields); -} -/** - * Unpack neo4j date value using the given unpacker. - * @param {Unpacker} unpacker the unpacker to use. - * @param {number} structSize the retrieved struct size. - * @param {BaseBuffer} buffer the buffer to unpack from. - * @param {boolean} disableLosslessIntegers if integer properties in the result date should be native JS numbers. - * @return {Date} the unpacked neo4j date value. - */ - - -function unpackDate(unpacker, structSize, buffer, disableLosslessIntegers) { - unpacker._verifyStructSize('Date', DATE_STRUCT_SIZE, structSize); - - var epochDay = unpacker.unpackInteger(buffer); - var result = (0, temporalUtil.epochDayToDate)(epochDay); - return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); -} -/** - * Pack given local date time. - * @param {LocalDateTime} value the local date time value to pack. - * @param {Packer} packer the packer to use. - */ - - -function packLocalDateTime(value, packer) { - var epochSecond = (0, temporalUtil.localDateTimeToEpochSecond)(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond); - var nano = (0, integer["int"])(value.nanosecond); - var packableStructFields = [packer.packable(epochSecond), packer.packable(nano)]; - packer.packStruct(LOCAL_DATE_TIME, packableStructFields); -} -/** - * Unpack local date time value using the given unpacker. - * @param {Unpacker} unpacker the unpacker to use. - * @param {number} structSize the retrieved struct size. - * @param {BaseBuffer} buffer the buffer to unpack from. - * @param {boolean} disableLosslessIntegers if integer properties in the result local date-time should be native JS numbers. - * @return {LocalDateTime} the unpacked local date time value. - */ - - -function unpackLocalDateTime(unpacker, structSize, buffer, disableLosslessIntegers) { - unpacker._verifyStructSize('LocalDateTime', LOCAL_DATE_TIME_STRUCT_SIZE, structSize); - - var epochSecond = unpacker.unpackInteger(buffer); - var nano = unpacker.unpackInteger(buffer); - var result = (0, temporalUtil.epochSecondAndNanoToLocalDateTime)(epochSecond, nano); - return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); -} -/** - * Pack given date time. - * @param {DateTime} value the date time value to pack. - * @param {Packer} packer the packer to use. - */ - - -function packDateTime(value, packer) { - if (value.timeZoneId) { - packDateTimeWithZoneId(value, packer); - } else { - packDateTimeWithZoneOffset(value, packer); - } -} -/** - * Pack given date time with zone offset. - * @param {DateTime} value the date time value to pack. - * @param {Packer} packer the packer to use. - */ - - -function packDateTimeWithZoneOffset(value, packer) { - var epochSecond = (0, temporalUtil.localDateTimeToEpochSecond)(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond); - var nano = (0, integer["int"])(value.nanosecond); - var timeZoneOffsetSeconds = (0, integer["int"])(value.timeZoneOffsetSeconds); - var packableStructFields = [packer.packable(epochSecond), packer.packable(nano), packer.packable(timeZoneOffsetSeconds)]; - packer.packStruct(DATE_TIME_WITH_ZONE_OFFSET, packableStructFields); -} -/** - * Unpack date time with zone offset value using the given unpacker. - * @param {Unpacker} unpacker the unpacker to use. - * @param {number} structSize the retrieved struct size. - * @param {BaseBuffer} buffer the buffer to unpack from. - * @param {boolean} disableLosslessIntegers if integer properties in the result date-time should be native JS numbers. - * @return {DateTime} the unpacked date time with zone offset value. - */ - - -function unpackDateTimeWithZoneOffset(unpacker, structSize, buffer, disableLosslessIntegers) { - unpacker._verifyStructSize('DateTimeWithZoneOffset', DATE_TIME_WITH_ZONE_OFFSET_STRUCT_SIZE, structSize); - - var epochSecond = unpacker.unpackInteger(buffer); - var nano = unpacker.unpackInteger(buffer); - var timeZoneOffsetSeconds = unpacker.unpackInteger(buffer); - var localDateTime = (0, temporalUtil.epochSecondAndNanoToLocalDateTime)(epochSecond, nano); - var result = new temporalTypes.DateTime(localDateTime.year, localDateTime.month, localDateTime.day, localDateTime.hour, localDateTime.minute, localDateTime.second, localDateTime.nanosecond, timeZoneOffsetSeconds, null); - return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); -} -/** - * Pack given date time with zone id. - * @param {DateTime} value the date time value to pack. - * @param {Packer} packer the packer to use. - */ - - -function packDateTimeWithZoneId(value, packer) { - var epochSecond = (0, temporalUtil.localDateTimeToEpochSecond)(value.year, value.month, value.day, value.hour, value.minute, value.second, value.nanosecond); - var nano = (0, integer["int"])(value.nanosecond); - var timeZoneId = value.timeZoneId; - var packableStructFields = [packer.packable(epochSecond), packer.packable(nano), packer.packable(timeZoneId)]; - packer.packStruct(DATE_TIME_WITH_ZONE_ID, packableStructFields); -} -/** - * Unpack date time with zone id value using the given unpacker. - * @param {Unpacker} unpacker the unpacker to use. - * @param {number} structSize the retrieved struct size. - * @param {BaseBuffer} buffer the buffer to unpack from. - * @param {boolean} disableLosslessIntegers if integer properties in the result date-time should be native JS numbers. - * @return {DateTime} the unpacked date time with zone id value. - */ - - -function unpackDateTimeWithZoneId(unpacker, structSize, buffer, disableLosslessIntegers) { - unpacker._verifyStructSize('DateTimeWithZoneId', DATE_TIME_WITH_ZONE_ID_STRUCT_SIZE, structSize); - - var epochSecond = unpacker.unpackInteger(buffer); - var nano = unpacker.unpackInteger(buffer); - var timeZoneId = unpacker.unpack(buffer); - var localDateTime = (0, temporalUtil.epochSecondAndNanoToLocalDateTime)(epochSecond, nano); - var result = new temporalTypes.DateTime(localDateTime.year, localDateTime.month, localDateTime.day, localDateTime.hour, localDateTime.minute, localDateTime.second, localDateTime.nanosecond, null, timeZoneId); - return convertIntegerPropsIfNeeded(result, disableLosslessIntegers); -} - -function convertIntegerPropsIfNeeded(obj, disableLosslessIntegers) { - if (!disableLosslessIntegers) { - return obj; - } - - var clone = Object.create(Object.getPrototypeOf(obj)); - - for (var prop in obj) { - if (obj.hasOwnProperty(prop)) { - var value = obj[prop]; - clone[prop] = (0, integer.isInt)(value) ? value.toNumberOrInfinity() : value; - } - } - - Object.freeze(clone); - return clone; -} -}); - -var boltProtocolV2 = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _boltProtocolV = interopRequireDefault(boltProtocolV1); - -var v2 = interopRequireWildcard(packstreamV2); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var BoltProtocol = -/*#__PURE__*/ -function (_BoltProtocolV) { - (0, _inherits2["default"])(BoltProtocol, _BoltProtocolV); - - function BoltProtocol() { - (0, _classCallCheck2["default"])(this, BoltProtocol); - return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(BoltProtocol).apply(this, arguments)); - } - - (0, _createClass2["default"])(BoltProtocol, [{ - key: "_createPacker", - value: function _createPacker(chunker) { - return new v2.Packer(chunker); - } - }, { - key: "_createUnpacker", - value: function _createUnpacker(disableLosslessIntegers) { - return new v2.Unpacker(disableLosslessIntegers); - } - }, { - key: "version", - get: function get() { - return constants.BOLT_PROTOCOL_V2; - } - }]); - return BoltProtocol; -}(_boltProtocolV["default"]); - -exports["default"] = BoltProtocol; -}); - -var boltProtocolV3 = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _boltProtocolV = interopRequireDefault(boltProtocolV2); - -var _requestMessage = interopRequireDefault(requestMessage); - - - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var noOpObserver = new streamObservers.StreamObserver(); - -var BoltProtocol = -/*#__PURE__*/ -function (_BoltProtocolV) { - (0, _inherits2["default"])(BoltProtocol, _BoltProtocolV); - - function BoltProtocol() { - (0, _classCallCheck2["default"])(this, BoltProtocol); - return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(BoltProtocol).apply(this, arguments)); - } - - (0, _createClass2["default"])(BoltProtocol, [{ - key: "transformMetadata", - value: function transformMetadata(metadata) { - if ('t_first' in metadata) { - // Bolt V3 uses shorter key 't_first' to represent 'result_available_after' - // adjust the key to be the same as in Bolt V1 so that ResultSummary can retrieve the value - metadata.result_available_after = metadata.t_first; - delete metadata.t_first; - } - - if ('t_last' in metadata) { - // Bolt V3 uses shorter key 't_last' to represent 'result_consumed_after' - // adjust the key to be the same as in Bolt V1 so that ResultSummary can retrieve the value - metadata.result_consumed_after = metadata.t_last; - delete metadata.t_last; - } - - return metadata; - } - }, { - key: "initialize", - value: function initialize() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - userAgent = _ref.userAgent, - authToken = _ref.authToken, - onError = _ref.onError, - onComplete = _ref.onComplete; - - var observer = new streamObservers.LoginObserver({ - connection: this._connection, - afterError: onError, - afterComplete: onComplete - }); - - this._connection.write(_requestMessage["default"].hello(userAgent, authToken), observer, true); - - return observer; - } - }, { - key: "prepareToClose", - value: function prepareToClose() { - this._connection.write(_requestMessage["default"].goodbye(), noOpObserver, true); - } - }, { - key: "beginTransaction", - value: function beginTransaction() { - var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - bookmark = _ref2.bookmark, - txConfig = _ref2.txConfig, - database = _ref2.database, - mode = _ref2.mode, - beforeError = _ref2.beforeError, - afterError = _ref2.afterError, - beforeComplete = _ref2.beforeComplete, - afterComplete = _ref2.afterComplete; - - var observer = new streamObservers.ResultStreamObserver({ - connection: this._connection, - beforeError: beforeError, - afterError: afterError, - beforeComplete: beforeComplete, - afterComplete: afterComplete - }); - observer.prepareToHandleSingleResponse(); // passing in a database name on this protocol version throws an error - - (0, boltProtocolUtil.assertDatabaseIsEmpty)(database, this._connection, observer); - - this._connection.write(_requestMessage["default"].begin({ - bookmark: bookmark, - txConfig: txConfig, - mode: mode - }), observer, true); - - return observer; - } - }, { - key: "commitTransaction", - value: function commitTransaction() { - var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - beforeError = _ref3.beforeError, - afterError = _ref3.afterError, - beforeComplete = _ref3.beforeComplete, - afterComplete = _ref3.afterComplete; - - var observer = new streamObservers.ResultStreamObserver({ - connection: this._connection, - beforeError: beforeError, - afterError: afterError, - beforeComplete: beforeComplete, - afterComplete: afterComplete - }); - observer.prepareToHandleSingleResponse(); - - this._connection.write(_requestMessage["default"].commit(), observer, true); - - return observer; - } - }, { - key: "rollbackTransaction", - value: function rollbackTransaction() { - var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - beforeError = _ref4.beforeError, - afterError = _ref4.afterError, - beforeComplete = _ref4.beforeComplete, - afterComplete = _ref4.afterComplete; - - var observer = new streamObservers.ResultStreamObserver({ - connection: this._connection, - beforeError: beforeError, - afterError: afterError, - beforeComplete: beforeComplete, - afterComplete: afterComplete - }); - observer.prepareToHandleSingleResponse(); - - this._connection.write(_requestMessage["default"].rollback(), observer, true); - - return observer; - } - }, { - key: "run", - value: function run(query, parameters) { - var _ref5 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - bookmark = _ref5.bookmark, - txConfig = _ref5.txConfig, - database = _ref5.database, - mode = _ref5.mode, - beforeKeys = _ref5.beforeKeys, - afterKeys = _ref5.afterKeys, - beforeError = _ref5.beforeError, - afterError = _ref5.afterError, - beforeComplete = _ref5.beforeComplete, - afterComplete = _ref5.afterComplete, - _ref5$flush = _ref5.flush, - flush = _ref5$flush === void 0 ? true : _ref5$flush; - - var observer = new streamObservers.ResultStreamObserver({ - connection: this._connection, - beforeKeys: beforeKeys, - afterKeys: afterKeys, - beforeError: beforeError, - afterError: afterError, - beforeComplete: beforeComplete, - afterComplete: afterComplete - }); // passing in a database name on this protocol version throws an error - - (0, boltProtocolUtil.assertDatabaseIsEmpty)(database, this._connection, observer); - - this._connection.write(_requestMessage["default"].runWithMetadata(query, parameters, { - bookmark: bookmark, - txConfig: txConfig, - mode: mode - }), observer, false); - - this._connection.write(_requestMessage["default"].pullAll(), observer, flush); - - return observer; - } - }, { - key: "version", - get: function get() { - return constants.BOLT_PROTOCOL_V3; - } - }]); - return BoltProtocol; -}(_boltProtocolV["default"]); - -exports["default"] = BoltProtocol; -}); - -var boltProtocolV4x0 = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _boltProtocolV = interopRequireDefault(boltProtocolV3); - -var _requestMessage = interopRequireWildcard(requestMessage); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var BoltProtocol = -/*#__PURE__*/ -function (_BoltProtocolV) { - (0, _inherits2["default"])(BoltProtocol, _BoltProtocolV); - - function BoltProtocol() { - (0, _classCallCheck2["default"])(this, BoltProtocol); - return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(BoltProtocol).apply(this, arguments)); - } - - (0, _createClass2["default"])(BoltProtocol, [{ - key: "beginTransaction", - value: function beginTransaction() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - bookmark = _ref.bookmark, - txConfig = _ref.txConfig, - database = _ref.database, - mode = _ref.mode, - beforeError = _ref.beforeError, - afterError = _ref.afterError, - beforeComplete = _ref.beforeComplete, - afterComplete = _ref.afterComplete; - - var observer = new streamObservers.ResultStreamObserver({ - connection: this._connection, - beforeError: beforeError, - afterError: afterError, - beforeComplete: beforeComplete, - afterComplete: afterComplete - }); - observer.prepareToHandleSingleResponse(); - - this._connection.write(_requestMessage["default"].begin({ - bookmark: bookmark, - txConfig: txConfig, - database: database, - mode: mode - }), observer, true); - - return observer; - } - }, { - key: "run", - value: function run(query, parameters) { - var _ref2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, - bookmark = _ref2.bookmark, - txConfig = _ref2.txConfig, - database = _ref2.database, - mode = _ref2.mode, - beforeKeys = _ref2.beforeKeys, - afterKeys = _ref2.afterKeys, - beforeError = _ref2.beforeError, - afterError = _ref2.afterError, - beforeComplete = _ref2.beforeComplete, - afterComplete = _ref2.afterComplete, - _ref2$flush = _ref2.flush, - flush = _ref2$flush === void 0 ? true : _ref2$flush, - _ref2$reactive = _ref2.reactive, - reactive = _ref2$reactive === void 0 ? false : _ref2$reactive, - _ref2$fetchSize = _ref2.fetchSize, - fetchSize = _ref2$fetchSize === void 0 ? _requestMessage.ALL : _ref2$fetchSize; - - var observer = new streamObservers.ResultStreamObserver({ - connection: this._connection, - reactive: reactive, - fetchSize: fetchSize, - moreFunction: this._requestMore, - discardFunction: this._requestDiscard, - beforeKeys: beforeKeys, - afterKeys: afterKeys, - beforeError: beforeError, - afterError: afterError, - beforeComplete: beforeComplete, - afterComplete: afterComplete - }); - var flushRun = reactive; - - this._connection.write(_requestMessage["default"].runWithMetadata(query, parameters, { - bookmark: bookmark, - txConfig: txConfig, - database: database, - mode: mode - }), observer, flushRun && flush); - - if (!reactive) { - this._connection.write(_requestMessage["default"].pull({ - n: fetchSize - }), observer, flush); - } - - return observer; - } - }, { - key: "_requestMore", - value: function _requestMore(connection, stmtId, n, observer) { - connection.write(_requestMessage["default"].pull({ - stmtId: stmtId, - n: n - }), observer, true); - } - }, { - key: "_requestDiscard", - value: function _requestDiscard(connection, stmtId, observer) { - connection.write(_requestMessage["default"].discard({ - stmtId: stmtId - }), observer, true); - } - }, { - key: "_noOp", - value: function _noOp() {} - }, { - key: "version", - get: function get() { - return constants.BOLT_PROTOCOL_V4_0; - } - }]); - return BoltProtocol; -}(_boltProtocolV["default"]); - -exports["default"] = BoltProtocol; -}); - -var boltProtocolV4x1 = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _boltProtocolV4x = interopRequireDefault(boltProtocolV4x0); - -var _requestMessage = interopRequireWildcard(requestMessage); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var BoltProtocol = -/*#__PURE__*/ -function (_BoltProtocolV) { - (0, _inherits2["default"])(BoltProtocol, _BoltProtocolV); - - /** - * @constructor - * @param {Connection} connection the connection. - * @param {Chunker} chunker the chunker. - * @param {boolean} disableLosslessIntegers if this connection should convert all received integers to native JS numbers. - * @param {Object} serversideRouting - */ - function BoltProtocol(connection, chunker, disableLosslessIntegers, serversideRouting) { - var _this; - - (0, _classCallCheck2["default"])(this, BoltProtocol); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(BoltProtocol).call(this, connection, chunker, disableLosslessIntegers)); - _this._serversideRouting = serversideRouting; - return _this; - } - - (0, _createClass2["default"])(BoltProtocol, [{ - key: "initialize", - value: function initialize() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - userAgent = _ref.userAgent, - authToken = _ref.authToken, - onError = _ref.onError, - onComplete = _ref.onComplete; - - var observer = new streamObservers.LoginObserver({ - connection: this._connection, - afterError: onError, - afterComplete: onComplete - }); - - this._connection.write(_requestMessage["default"].hello(userAgent, authToken, this._serversideRouting), observer, true); - - return observer; - } - }, { - key: "version", - get: function get() { - return constants.BOLT_PROTOCOL_V4_1; - } - }]); - return BoltProtocol; -}(_boltProtocolV4x["default"]); - -exports["default"] = BoltProtocol; -}); - -var boltProtocolV4x2 = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _boltProtocolV4x = interopRequireDefault(boltProtocolV4x1); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var BoltProtocol = -/*#__PURE__*/ -function (_BoltProtocolV) { - (0, _inherits2["default"])(BoltProtocol, _BoltProtocolV); - - /** - * @constructor - * @param {Connection} connection the connection. - * @param {Chunker} chunker the chunker. - * @param {boolean} disableLosslessIntegers if this connection should convert all received integers to native JS numbers. - * @param {Object} serversideRouting - */ - function BoltProtocol(connection, chunker, disableLosslessIntegers, serversideRouting) { - (0, _classCallCheck2["default"])(this, BoltProtocol); - return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(BoltProtocol).call(this, connection, chunker, disableLosslessIntegers, serversideRouting)); - } - - (0, _createClass2["default"])(BoltProtocol, [{ - key: "version", - get: function get() { - return constants.BOLT_PROTOCOL_V4_2; - } - }]); - return BoltProtocol; -}(_boltProtocolV4x["default"]); - -exports["default"] = BoltProtocol; -}); - -var protocolHandshaker = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - - - -var _boltProtocolV = interopRequireDefault(boltProtocolV1); - -var _boltProtocolV2 = interopRequireDefault(boltProtocolV2); - -var _boltProtocolV3 = interopRequireDefault(boltProtocolV3); - -var _boltProtocolV4x = interopRequireDefault(boltProtocolV4x0); - -var _boltProtocolV4x2 = interopRequireDefault(boltProtocolV4x1); - -var _boltProtocolV4x3 = interopRequireDefault(boltProtocolV4x2); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var BOLT_MAGIC_PREAMBLE = 0x6060b017; - -var ProtocolHandshaker = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {Connection} connection the connection owning this protocol. - * @param {Channel} channel the network channel. - * @param {Chunker} chunker the message chunker. - * @param {boolean} disableLosslessIntegers flag to use native JS numbers. - * @param {Logger} log the logger. - */ - function ProtocolHandshaker(connection, channel, chunker, disableLosslessIntegers, log) { - var serversideRouting = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; - (0, _classCallCheck2["default"])(this, ProtocolHandshaker); - this._connection = connection; - this._channel = channel; - this._chunker = chunker; - this._disableLosslessIntegers = disableLosslessIntegers; - this._log = log; - this._serversideRouting = serversideRouting; - } - /** - * Write a Bolt handshake into the underlying network channel. - */ - - - (0, _createClass2["default"])(ProtocolHandshaker, [{ - key: "writeHandshakeRequest", - value: function writeHandshakeRequest() { - this._channel.write(newHandshakeBuffer()); - } - /** - * Read the given handshake response and create the negotiated bolt protocol. - * @param {BaseBuffer} buffer byte buffer containing the handshake response. - * @return {BoltProtocol} bolt protocol corresponding to the version suggested by the database. - * @throws {Neo4jError} when bolt protocol can't be instantiated. - */ - - }, { - key: "createNegotiatedProtocol", - value: function createNegotiatedProtocol(buffer) { - var h = [buffer.readUInt8(), buffer.readUInt8(), buffer.readUInt8(), buffer.readUInt8()]; - - if (h[0] === 0x48 && h[1] === 0x54 && h[2] === 0x54 && h[3] === 0x50) { - throw (0, error.newError)('Server responded HTTP. Make sure you are not trying to connect to the http endpoint ' + '(HTTP defaults to port 7474 whereas BOLT defaults to port 7687)'); - } - - var negotiatedVersion = Number(h[3] + '.' + h[2]); - - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(this._connection, " negotiated protocol version ").concat(negotiatedVersion)); - } - - return this._createProtocolWithVersion(negotiatedVersion); - } - /** - * @return {BoltProtocol} - * @private - */ - - }, { - key: "_createProtocolWithVersion", - value: function _createProtocolWithVersion(version) { - switch (version) { - case 1: - return new _boltProtocolV["default"](this._connection, this._chunker, this._disableLosslessIntegers); - - case 2: - return new _boltProtocolV2["default"](this._connection, this._chunker, this._disableLosslessIntegers); - - case 3: - return new _boltProtocolV3["default"](this._connection, this._chunker, this._disableLosslessIntegers); - - case 4.0: - return new _boltProtocolV4x["default"](this._connection, this._chunker, this._disableLosslessIntegers); - - case 4.1: - return new _boltProtocolV4x2["default"](this._connection, this._chunker, this._disableLosslessIntegers, this._serversideRouting); - - case 4.2: - return new _boltProtocolV4x3["default"](this._connection, this._chunker, this._disableLosslessIntegers, this._serversideRouting); - - default: - throw (0, error.newError)('Unknown Bolt protocol version: ' + version); - } - } - }]); - return ProtocolHandshaker; -}(); -/** - * @return {BaseBuffer} - * @private - */ - - -exports["default"] = ProtocolHandshaker; - -function newHandshakeBuffer() { - var handshakeBuffer = (0, node.alloc)(5 * 4); // magic preamble - - handshakeBuffer.writeInt32(BOLT_MAGIC_PREAMBLE); // proposed versions - - handshakeBuffer.writeInt32(2 << 8 | 4); - handshakeBuffer.writeInt32(1 << 8 | 4); - handshakeBuffer.writeInt32(4); - handshakeBuffer.writeInt32(3); // reset the reader position - - handshakeBuffer.reset(); - return handshakeBuffer; -} -}); - -var connectionChannel = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _regenerator = interopRequireDefault(regenerator); - -var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _assertThisInitialized2 = interopRequireDefault(assertThisInitialized); - -var _inherits2 = interopRequireDefault(inherits); - - - - - - - -var _channelConfig = interopRequireDefault(channelConfig); - -var _protocolHandshaker = interopRequireDefault(protocolHandshaker); - -var _connection = interopRequireDefault(connection); - -interopRequireDefault(boltProtocolV1); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// Signature bytes for each response message type -var SUCCESS = 0x70; // 0111 0000 // SUCCESS - -var RECORD = 0x71; // 0111 0001 // RECORD - -var IGNORED = 0x7e; // 0111 1110 // IGNORED - -var FAILURE = 0x7f; // 0111 1111 // FAILURE - -function NO_OP() {} - -var NO_OP_OBSERVER = { - onNext: NO_OP, - onCompleted: NO_OP, - onError: NO_OP -}; -var idGenerator = 0; - -var ChannelConnection = -/*#__PURE__*/ -function (_Connection) { - (0, _inherits2["default"])(ChannelConnection, _Connection); - - /** - * @constructor - * @param {Channel} channel - channel with a 'write' function and a 'onmessage' callback property. - * @param {ConnectionErrorHandler} errorHandler the error handler. - * @param {ServerAddress} address - the server address to connect to. - * @param {Logger} log - the configured logger. - * @param {boolean} disableLosslessIntegers if this connection should convert all received integers to native JS numbers. - */ - function ChannelConnection(channel, errorHandler, address, log) { - var _this; - - var disableLosslessIntegers = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; - var serversideRouting = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; - (0, _classCallCheck2["default"])(this, ChannelConnection); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ChannelConnection).call(this, errorHandler)); - _this._id = idGenerator++; - _this._address = address; - _this._server = { - address: address.asHostPort() - }; - _this.creationTimestamp = Date.now(); - _this._disableLosslessIntegers = disableLosslessIntegers; - _this._pendingObservers = []; - _this._currentObserver = undefined; - _this._ch = channel; - _this._dechunker = new chunking.Dechunker(); - _this._chunker = new chunking.Chunker(channel); - _this._log = log; - _this._serversideRouting = serversideRouting; // connection from the database, returned in response for HELLO message and might not be available - - _this._dbConnectionId = null; // bolt protocol is initially not initialized - - /** - * @private - * @type {BoltProtocol} - */ - - _this._protocol = null; // error extracted from a FAILURE message - - _this._currentFailure = null; // Set to true on fatal errors, to get this out of connection pool. - - _this._isBroken = false; - - if (_this._log.isDebugEnabled()) { - _this._log.debug("".concat((0, _assertThisInitialized2["default"])(_this), " created towards ").concat(address)); - } - - return _this; - } - /** - * Crete new connection to the provided address. Returned connection is not connected. - * @param {ServerAddress} address - the Bolt endpoint to connect to. - * @param {Object} config - the driver configuration. - * @param {ConnectionErrorHandler} errorHandler - the error handler for connection errors. - * @param {Logger} log - configured logger. - * @return {Connection} - new connection. - */ - - - (0, _createClass2["default"])(ChannelConnection, [{ - key: "connect", - - /** - * Connect to the target address, negotiate Bolt protocol and send initialization message. - * @param {string} userAgent the user agent for this driver. - * @param {Object} authToken the object containing auth information. - * @return {Promise} promise resolved with the current connection if connection is successful. Rejected promise otherwise. - */ - value: function connect(userAgent, authToken) { - var _this2 = this; - - return this._negotiateProtocol().then(function () { - return _this2._initialize(userAgent, authToken); - }); - } - /** - * Execute Bolt protocol handshake to initialize the protocol version. - * @return {Promise} promise resolved with the current connection if handshake is successful. Rejected promise otherwise. - */ - - }, { - key: "_negotiateProtocol", - value: function _negotiateProtocol() { - var _this3 = this; - - var protocolHandshaker = new _protocolHandshaker["default"](this, this._ch, this._chunker, this._disableLosslessIntegers, this._log, this._serversideRouting); - return new Promise(function (resolve, reject) { - var handshakeErrorHandler = function handshakeErrorHandler(error) { - _this3._handleFatalError(error); - - reject(error); - }; - - _this3._ch.onerror = handshakeErrorHandler.bind(_this3); - - if (_this3._ch._error) { - // channel is already broken - handshakeErrorHandler(_this3._ch._error); - } - - _this3._ch.onmessage = function (buffer) { - try { - // read the response buffer and initialize the protocol - _this3._protocol = protocolHandshaker.createNegotiatedProtocol(buffer); // reset the error handler to just handle errors and forget about the handshake promise - - _this3._ch.onerror = _this3._handleFatalError.bind(_this3); // Ok, protocol running. Simply forward all messages to the dechunker - - _this3._ch.onmessage = function (buf) { - return _this3._dechunker.write(buf); - }; // setup dechunker to dechunk messages and forward them to the message handler - - - _this3._dechunker.onmessage = function (buf) { - _this3._handleMessage(_this3._protocol.unpacker().unpack(buf)); - }; // forward all pending bytes to the dechunker - - - if (buffer.hasRemaining()) { - _this3._dechunker.write(buffer.readSlice(buffer.remaining())); - } - - resolve(_this3); - } catch (e) { - _this3._handleFatalError(e); - - reject(e); - } - }; - - protocolHandshaker.writeHandshakeRequest(); - }); - } - /** - * Perform protocol-specific initialization which includes authentication. - * @param {string} userAgent the user agent for this driver. - * @param {Object} authToken the object containing auth information. - * @return {Promise} promise resolved with the current connection if initialization is successful. Rejected promise otherwise. - */ - - }, { - key: "_initialize", - value: function _initialize(userAgent, authToken) { - var _this4 = this; - - var self = this; - return new Promise(function (resolve, reject) { - _this4._protocol.initialize({ - userAgent: userAgent, - authToken: authToken, - onError: function onError(err) { - return reject(err); - }, - onComplete: function onComplete() { - return resolve(self); - } - }); - }); - } - /** - * Get the Bolt protocol for the connection. - * @return {BoltProtocol} the protocol. - */ - - }, { - key: "protocol", - value: function protocol() { - return this._protocol; - } - }, { - key: "write", - - /** - * Write a message to the network channel. - * @param {RequestMessage} message the message to write. - * @param {ResultStreamObserver} observer the response observer. - * @param {boolean} flush `true` if flush should happen after the message is written to the buffer. - */ - value: function write(message, observer, flush) { - var _this5 = this; - - var queued = this._queueObserver(observer); - - if (queued) { - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(this, " C: ").concat(message)); - } - - this._protocol.packer().packStruct(message.signature, message.fields.map(function (field) { - return _this5._packable(field); - })); - - this._chunker.messageBoundary(); - - if (flush) { - this._chunker.flush(); - } - } - } - /** - * "Fatal" means the connection is dead. Only call this if something - * happens that cannot be recovered from. This will lead to all subscribers - * failing, and the connection getting ejected from the session pool. - * - * @param error an error object, forwarded to all current and future subscribers - */ - - }, { - key: "_handleFatalError", - value: function _handleFatalError(error) { - this._isBroken = true; - this._error = this.handleAndTransformError(error, this._address); - - if (this._log.isErrorEnabled()) { - this._log.error("".concat(this, " experienced a fatal error ").concat(JSON.stringify(this._error))); - } - - if (this._currentObserver && this._currentObserver.onError) { - this._currentObserver.onError(this._error); - } - - while (this._pendingObservers.length > 0) { - var observer = this._pendingObservers.shift(); - - if (observer && observer.onError) { - observer.onError(this._error); - } - } - } - }, { - key: "_handleMessage", - value: function _handleMessage(msg) { - if (this._isBroken) { - // ignore all incoming messages when this connection is broken. all previously pending observers failed - // with the fatal error. all future observers will fail with same fatal error. - return; - } - - var payload = msg.fields[0]; - - switch (msg.signature) { - case RECORD: - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(this, " S: RECORD ").concat(JSON.stringify(msg))); - } - - this._currentObserver.onNext(payload); - - break; - - case SUCCESS: - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(this, " S: SUCCESS ").concat(JSON.stringify(msg))); - } - - try { - var metadata = this._protocol.transformMetadata(payload); - - this._currentObserver.onCompleted(metadata); - } finally { - this._updateCurrentObserver(); - } - - break; - - case FAILURE: - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(this, " S: FAILURE ").concat(JSON.stringify(msg))); - } - - try { - var error$1 = (0, error.newError)(payload.message, payload.code); - this._currentFailure = this.handleAndTransformError(error$1, this._address); - - this._currentObserver.onError(this._currentFailure); - } finally { - this._updateCurrentObserver(); // Things are now broken. Pending observers will get FAILURE messages routed until we are done handling this failure. - - - this._resetOnFailure(); - } - - break; - - case IGNORED: - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(this, " S: IGNORED ").concat(JSON.stringify(msg))); - } - - try { - if (this._currentFailure && this._currentObserver.onError) { - this._currentObserver.onError(this._currentFailure); - } else if (this._currentObserver.onError) { - this._currentObserver.onError((0, error.newError)('Ignored either because of an error or RESET')); - } - } finally { - this._updateCurrentObserver(); - } - - break; - - default: - this._handleFatalError((0, error.newError)('Unknown Bolt protocol message: ' + msg)); - - } - } - /** - * Send a RESET-message to the database. Message is immediately flushed to the network. - * @return {Promise} promise resolved when SUCCESS-message response arrives, or failed when other response messages arrives. - */ - - }, { - key: "resetAndFlush", - value: function resetAndFlush() { - var _this6 = this; - - return new Promise(function (resolve, reject) { - _this6._protocol.reset({ - onError: function onError(error) { - if (_this6._isBroken) { - // handling a fatal error, no need to raise a protocol violation - reject(error); - } else { - var neo4jError = _this6._handleProtocolError('Received FAILURE as a response for RESET: ' + error); - - reject(neo4jError); - } - }, - onComplete: function onComplete() { - resolve(); - } - }); - }); - } - }, { - key: "_resetOnFailure", - value: function _resetOnFailure() { - var _this7 = this; - - this._protocol.reset({ - onError: function onError() { - _this7._currentFailure = null; - }, - onComplete: function onComplete() { - _this7._currentFailure = null; - } - }); - } - }, { - key: "_queueObserver", - value: function _queueObserver(observer) { - if (this._isBroken) { - if (observer && observer.onError) { - observer.onError(this._error); - } - - return false; - } - - observer = observer || NO_OP_OBSERVER; - observer.onCompleted = observer.onCompleted || NO_OP; - observer.onError = observer.onError || NO_OP; - observer.onNext = observer.onNext || NO_OP; - - if (this._currentObserver === undefined) { - this._currentObserver = observer; - } else { - this._pendingObservers.push(observer); - } - - return true; - } - /* - * Pop next pending observer form the list of observers and make it current observer. - * @protected - */ - - }, { - key: "_updateCurrentObserver", - value: function _updateCurrentObserver() { - this._currentObserver = this._pendingObservers.shift(); - } - /** Check if this connection is in working condition */ - - }, { - key: "isOpen", - value: function isOpen() { - return !this._isBroken && this._ch._open; - } - /** - * Call close on the channel. - * @returns {Promise} - A promise that will be resolved when the underlying channel is closed. - */ - - }, { - key: "close", - value: function () { - var _close = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee() { - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(this, " closing")); - } - - if (this._protocol && this.isOpen()) { - // protocol has been initialized and this connection is healthy - // notify the database about the upcoming close of the connection - this._protocol.prepareToClose(); - } - - _context.next = 4; - return this._ch.close(); - - case 4: - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(this, " closed")); - } - - case 5: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function close() { - return _close.apply(this, arguments); - } - - return close; - }() - }, { - key: "toString", - value: function toString() { - return "Connection [".concat(this.id, "][").concat(this.databaseId || '', "]"); - } - }, { - key: "_packable", - value: function _packable(value) { - return this._protocol.packer().packable(value); - } - }, { - key: "_handleProtocolError", - value: function _handleProtocolError(message) { - this._currentFailure = null; - - this._updateCurrentObserver(); - - var error$1 = (0, error.newError)(message, error.PROTOCOL_ERROR); - - this._handleFatalError(error$1); - - return error$1; - } - }, { - key: "id", - get: function get() { - return this._id; - } - }, { - key: "databaseId", - get: function get() { - return this._dbConnectionId; - }, - set: function set(value) { - this._dbConnectionId = value; - } - }, { - key: "address", - get: function get() { - return this._address; - } - /** - * Get the version of the connected server. - * Available only after initialization - * - * @returns {ServerVersion} version - */ - - }, { - key: "version", - get: function get() { - return this._server.version; - }, - set: function set(value) { - this._server.version = value; - } - }, { - key: "server", - get: function get() { - return this._server; - } - }], [{ - key: "create", - value: function create(address, config, errorHandler, log) { - var serversideRouting = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; - var channelConfig = new _channelConfig["default"](address, config, errorHandler.errorCode()); - return new ChannelConnection(new node.Channel(channelConfig), errorHandler, address, log, config.disableLosslessIntegers, serversideRouting); - } - }]); - return ChannelConnection; -}(_connection["default"]); - -exports["default"] = ChannelConnection; -}); - -var poolConfig = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.DEFAULT_ACQUISITION_TIMEOUT = exports.DEFAULT_MAX_SIZE = exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DEFAULT_MAX_SIZE = 100; -exports.DEFAULT_MAX_SIZE = DEFAULT_MAX_SIZE; -var DEFAULT_ACQUISITION_TIMEOUT = 60 * 1000; // 60 seconds - -exports.DEFAULT_ACQUISITION_TIMEOUT = DEFAULT_ACQUISITION_TIMEOUT; - -var PoolConfig = -/*#__PURE__*/ -function () { - function PoolConfig(maxSize, acquisitionTimeout) { - (0, _classCallCheck2["default"])(this, PoolConfig); - this.maxSize = valueOrDefault(maxSize, DEFAULT_MAX_SIZE); - this.acquisitionTimeout = valueOrDefault(acquisitionTimeout, DEFAULT_ACQUISITION_TIMEOUT); - } - - (0, _createClass2["default"])(PoolConfig, null, [{ - key: "defaultConfig", - value: function defaultConfig() { - return new PoolConfig(DEFAULT_MAX_SIZE, DEFAULT_ACQUISITION_TIMEOUT); - } - }, { - key: "fromDriverConfig", - value: function fromDriverConfig(config) { - var maxSizeConfigured = isConfigured(config.maxConnectionPoolSize); - var maxSize = maxSizeConfigured ? config.maxConnectionPoolSize : DEFAULT_MAX_SIZE; - var acquisitionTimeoutConfigured = isConfigured(config.connectionAcquisitionTimeout); - var acquisitionTimeout = acquisitionTimeoutConfigured ? config.connectionAcquisitionTimeout : DEFAULT_ACQUISITION_TIMEOUT; - return new PoolConfig(maxSize, acquisitionTimeout); - } - }]); - return PoolConfig; -}(); - -exports["default"] = PoolConfig; - -function valueOrDefault(value, defaultValue) { - return value === 0 || value ? value : defaultValue; -} - -function isConfigured(value) { - return value === 0 || value; -} -}); - -var logger = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _defineProperty2 = interopRequireDefault(defineProperty$1); - - - -var _levels; - -var ERROR = 'error'; -var WARN = 'warn'; -var INFO = 'info'; -var DEBUG = 'debug'; -var DEFAULT_LEVEL = INFO; -var levels = (_levels = {}, (0, _defineProperty2["default"])(_levels, ERROR, 0), (0, _defineProperty2["default"])(_levels, WARN, 1), (0, _defineProperty2["default"])(_levels, INFO, 2), (0, _defineProperty2["default"])(_levels, DEBUG, 3), _levels); -/** - * Logger used by the driver to notify about various internal events. Single logger should be used per driver. - */ - -var Logger = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {string} level the enabled logging level. - * @param {function(level: string, message: string)} loggerFunction the function to write the log level and message. - */ - function Logger(level, loggerFunction) { - (0, _classCallCheck2["default"])(this, Logger); - this._level = level; - this._loggerFunction = loggerFunction; - } - /** - * Create a new logger based on the given driver configuration. - * @param {Object} driverConfig the driver configuration as supplied by the user. - * @return {Logger} a new logger instance or a no-op logger when not configured. - */ - - - (0, _createClass2["default"])(Logger, [{ - key: "isErrorEnabled", - - /** - * Check if error logging is enabled, i.e. it is not a no-op implementation. - * @return {boolean} `true` when enabled, `false` otherwise. - */ - value: function isErrorEnabled() { - return isLevelEnabled(this._level, ERROR); - } - /** - * Log an error message. - * @param {string} message the message to log. - */ - - }, { - key: "error", - value: function error(message) { - if (this.isErrorEnabled()) { - this._loggerFunction(ERROR, message); - } - } - /** - * Check if warn logging is enabled, i.e. it is not a no-op implementation. - * @return {boolean} `true` when enabled, `false` otherwise. - */ - - }, { - key: "isWarnEnabled", - value: function isWarnEnabled() { - return isLevelEnabled(this._level, WARN); - } - /** - * Log an warning message. - * @param {string} message the message to log. - */ - - }, { - key: "warn", - value: function warn(message) { - if (this.isWarnEnabled()) { - this._loggerFunction(WARN, message); - } - } - /** - * Check if info logging is enabled, i.e. it is not a no-op implementation. - * @return {boolean} `true` when enabled, `false` otherwise. - */ - - }, { - key: "isInfoEnabled", - value: function isInfoEnabled() { - return isLevelEnabled(this._level, INFO); - } - /** - * Log an info message. - * @param {string} message the message to log. - */ - - }, { - key: "info", - value: function info(message) { - if (this.isInfoEnabled()) { - this._loggerFunction(INFO, message); - } - } - /** - * Check if debug logging is enabled, i.e. it is not a no-op implementation. - * @return {boolean} `true` when enabled, `false` otherwise. - */ - - }, { - key: "isDebugEnabled", - value: function isDebugEnabled() { - return isLevelEnabled(this._level, DEBUG); - } - /** - * Log a debug message. - * @param {string} message the message to log. - */ - - }, { - key: "debug", - value: function debug(message) { - if (this.isDebugEnabled()) { - this._loggerFunction(DEBUG, message); - } - } - }], [{ - key: "create", - value: function create(driverConfig) { - if (driverConfig && driverConfig.logging) { - var loggingConfig = driverConfig.logging; - var level = extractConfiguredLevel(loggingConfig); - var loggerFunction = extractConfiguredLogger(loggingConfig); - return new Logger(level, loggerFunction); - } - - return this.noOp(); - } - /** - * Create a no-op logger implementation. - * @return {Logger} the no-op logger implementation. - */ - - }, { - key: "noOp", - value: function noOp() { - return noOpLogger; - } - }]); - return Logger; -}(); - -var NoOpLogger = -/*#__PURE__*/ -function (_Logger) { - (0, _inherits2["default"])(NoOpLogger, _Logger); - - function NoOpLogger() { - (0, _classCallCheck2["default"])(this, NoOpLogger); - return (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(NoOpLogger).call(this, null, null)); - } - - (0, _createClass2["default"])(NoOpLogger, [{ - key: "isErrorEnabled", - value: function isErrorEnabled() { - return false; - } - }, { - key: "error", - value: function error(message) {} - }, { - key: "isWarnEnabled", - value: function isWarnEnabled() { - return false; - } - }, { - key: "warn", - value: function warn(message) {} - }, { - key: "isInfoEnabled", - value: function isInfoEnabled() { - return false; - } - }, { - key: "info", - value: function info(message) {} - }, { - key: "isDebugEnabled", - value: function isDebugEnabled() { - return false; - } - }, { - key: "debug", - value: function debug(message) {} - }]); - return NoOpLogger; -}(Logger); - -var noOpLogger = new NoOpLogger(); -/** - * Check if the given logging level is enabled. - * @param {string} configuredLevel the configured level. - * @param {string} targetLevel the level to check. - * @return {boolean} value of `true` when enabled, `false` otherwise. - */ - -function isLevelEnabled(configuredLevel, targetLevel) { - return levels[configuredLevel] >= levels[targetLevel]; -} -/** - * Extract the configured logging level from the driver's logging configuration. - * @param {Object} loggingConfig the logging configuration. - * @return {string} the configured log level or default when none configured. - */ - - -function extractConfiguredLevel(loggingConfig) { - if (loggingConfig && loggingConfig.level) { - var configuredLevel = loggingConfig.level; - var value = levels[configuredLevel]; - - if (!value && value !== 0) { - throw (0, error.newError)("Illegal logging level: ".concat(configuredLevel, ". Supported levels are: ").concat(Object.keys(levels))); - } - - return configuredLevel; - } - - return DEFAULT_LEVEL; -} -/** - * Extract the configured logger function from the driver's logging configuration. - * @param {Object} loggingConfig the logging configuration. - * @return {function(level: string, message: string)} the configured logging function. - */ - - -function extractConfiguredLogger(loggingConfig) { - if (loggingConfig && loggingConfig.logger) { - var configuredLogger = loggingConfig.logger; - - if (configuredLogger && typeof configuredLogger === 'function') { - return configuredLogger; - } - } - - throw (0, error.newError)("Illegal logger function: ".concat(loggingConfig.logger)); -} - -var _default = Logger; -exports["default"] = _default; -}); - -var pool = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _regenerator = interopRequireDefault(regenerator); - -var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _poolConfig = interopRequireDefault(poolConfig); - - - -var _logger = interopRequireDefault(logger); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Pool = -/*#__PURE__*/ -function () { - /** - * @param {function(address: ServerAddress, function(address: ServerAddress, resource: object): Promise): Promise} create - * an allocation function that creates a promise with a new resource. It's given an address for which to - * allocate the connection and a function that will return the resource to the pool if invoked, which is - * meant to be called on .dispose or .close or whatever mechanism the resource uses to finalize. - * @param {function(resource: object): Promise} destroy - * called with the resource when it is evicted from this pool - * @param {function(resource: object): boolean} validate - * called at various times (like when an instance is acquired and when it is returned. - * If this returns false, the resource will be evicted - * @param {function(resource: object, observer: { onError }): void} installIdleObserver - * called when the resource is released back to pool - * @param {function(resource: object): void} removeIdleObserver - * called when the resource is acquired from the pool - * @param {PoolConfig} config configuration for the new driver. - * @param {Logger} log the driver logger. - */ - function Pool() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref$create = _ref.create, - create = _ref$create === void 0 ? function (address, release) { - return Promise.resolve(); - } : _ref$create, - _ref$destroy = _ref.destroy, - destroy = _ref$destroy === void 0 ? function (conn) { - return Promise.resolve(); - } : _ref$destroy, - _ref$validate = _ref.validate, - validate = _ref$validate === void 0 ? function (conn) { - return true; - } : _ref$validate, - _ref$installIdleObser = _ref.installIdleObserver, - installIdleObserver = _ref$installIdleObser === void 0 ? function (conn, observer) {} : _ref$installIdleObser, - _ref$removeIdleObserv = _ref.removeIdleObserver, - removeIdleObserver = _ref$removeIdleObserv === void 0 ? function (conn) {} : _ref$removeIdleObserv, - _ref$config = _ref.config, - config = _ref$config === void 0 ? _poolConfig["default"].defaultConfig() : _ref$config, - _ref$log = _ref.log, - log = _ref$log === void 0 ? _logger["default"].noOp() : _ref$log; - - (0, _classCallCheck2["default"])(this, Pool); - this._create = create; - this._destroy = destroy; - this._validate = validate; - this._installIdleObserver = installIdleObserver; - this._removeIdleObserver = removeIdleObserver; - this._maxSize = config.maxSize; - this._acquisitionTimeout = config.acquisitionTimeout; - this._pools = {}; - this._pendingCreates = {}; - this._acquireRequests = {}; - this._activeResourceCounts = {}; - this._release = this._release.bind(this); - this._log = log; - this._closed = false; - } - /** - * Acquire and idle resource fom the pool or create a new one. - * @param {ServerAddress} address the address for which we're acquiring. - * @return {Object} resource that is ready to use. - */ - - - (0, _createClass2["default"])(Pool, [{ - key: "acquire", - value: function acquire(address) { - var _this = this; - - return this._acquire(address).then(function (resource) { - var key = address.asKey(); - - if (resource) { - // New or existing resource acquired - return resource; - } // We're out of resources and will try to acquire later on when an existing resource is released. - - - var allRequests = _this._acquireRequests; - var requests = allRequests[key]; - - if (!requests) { - allRequests[key] = []; - } - - return new Promise(function (resolve, reject) { - var request; - var timeoutId = setTimeout(function () { - // acquisition timeout fired - // remove request from the queue of pending requests, if it's still there - // request might've been taken out by the release operation - var pendingRequests = allRequests[key]; - - if (pendingRequests) { - allRequests[key] = pendingRequests.filter(function (item) { - return item !== request; - }); - } - - if (request.isCompleted()) ; else { - // request is still pending and needs to be failed - var activeCount = _this.activeResourceCount(address); - - var idleCount = _this.has(address) ? _this._pools[key].length : 0; - request.reject((0, error.newError)("Connection acquisition timed out in ".concat(_this._acquisitionTimeout, " ms. Poos status: Active conn count = ").concat(activeCount, ", Idle conn count = ").concat(idleCount, "."))); - } - }, _this._acquisitionTimeout); - request = new PendingRequest(key, resolve, reject, timeoutId, _this._log); - allRequests[key].push(request); - }); - }); - } - /** - * Destroy all idle resources for the given address. - * @param {ServerAddress} address the address of the server to purge its pool. - * @returns {Promise} A promise that is resolved when the resources are purged - */ - - }, { - key: "purge", - value: function purge(address) { - return this._purgeKey(address.asKey()); - } - /** - * Destroy all idle resources in this pool. - * @returns {Promise} A promise that is resolved when the resources are purged - */ - - }, { - key: "close", - value: function close() { - var _this2 = this; - - this._closed = true; - return Promise.all(Object.keys(this._pools).map(function (key) { - return _this2._purgeKey(key); - })); - } - /** - * Keep the idle resources for the provided addresses and purge the rest. - * @returns {Promise} A promise that is resolved when the other resources are purged - */ - - }, { - key: "keepAll", - value: function keepAll(addresses) { - var _this3 = this; - - var keysToKeep = addresses.map(function (a) { - return a.asKey(); - }); - var keysPresent = Object.keys(this._pools); - var keysToPurge = keysPresent.filter(function (k) { - return keysToKeep.indexOf(k) === -1; - }); - return Promise.all(keysToPurge.map(function (key) { - return _this3._purgeKey(key); - })); - } - /** - * Check if this pool contains resources for the given address. - * @param {ServerAddress} address the address of the server to check. - * @return {boolean} `true` when pool contains entries for the given key, false otherwise. - */ - - }, { - key: "has", - value: function has(address) { - return address.asKey() in this._pools; - } - /** - * Get count of active (checked out of the pool) resources for the given key. - * @param {ServerAddress} address the address of the server to check. - * @return {number} count of resources acquired by clients. - */ - - }, { - key: "activeResourceCount", - value: function activeResourceCount(address) { - return this._activeResourceCounts[address.asKey()] || 0; - } - }, { - key: "_acquire", - value: function () { - var _acquire2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee(address) { - var key, pool, _resource, numConnections, resource; - - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!this._closed) { - _context.next = 2; - break; - } - - throw (0, error.newError)('Pool is closed, it is no more able to serve requests.'); - - case 2: - key = address.asKey(); - pool = this._pools[key]; - - if (!pool) { - pool = []; - this._pools[key] = pool; - this._pendingCreates[key] = 0; - } - - case 5: - if (!pool.length) { - _context.next = 18; - break; - } - - _resource = pool.pop(); - - if (!this._validate(_resource)) { - _context.next = 14; - break; - } - - if (this._removeIdleObserver) { - this._removeIdleObserver(_resource); - } // idle resource is valid and can be acquired - - - resourceAcquired(key, this._activeResourceCounts); - - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(_resource, " acquired from the pool ").concat(key)); - } - - return _context.abrupt("return", _resource); - - case 14: - _context.next = 16; - return this._destroy(_resource); - - case 16: - _context.next = 5; - break; - - case 18: - if (!(this._maxSize > 0)) { - _context.next = 22; - break; - } - - // Include pending creates when checking pool size since these probably will add - // to the number when fulfilled. - numConnections = this.activeResourceCount(address) + this._pendingCreates[key]; - - if (!(numConnections >= this._maxSize)) { - _context.next = 22; - break; - } - - return _context.abrupt("return", null); - - case 22: - // there exist no idle valid resources, create a new one for acquisition - // Keep track of how many pending creates there are to avoid making too many connections. - this._pendingCreates[key] = this._pendingCreates[key] + 1; - _context.prev = 23; - _context.next = 26; - return this._create(address, this._release); - - case 26: - resource = _context.sent; - resourceAcquired(key, this._activeResourceCounts); - - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(resource, " created for the pool ").concat(key)); - } - - case 29: - _context.prev = 29; - this._pendingCreates[key] = this._pendingCreates[key] - 1; - return _context.finish(29); - - case 32: - return _context.abrupt("return", resource); - - case 33: - case "end": - return _context.stop(); - } - } - }, _callee, this, [[23,, 29, 32]]); - })); - - function _acquire(_x) { - return _acquire2.apply(this, arguments); - } - - return _acquire; - }() - }, { - key: "_release", - value: function () { - var _release2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee2(address, resource) { - var _this4 = this; - - var key, pool; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - key = address.asKey(); - pool = this._pools[key]; - - if (!pool) { - _context2.next = 14; - break; - } - - if (this._validate(resource)) { - _context2.next = 9; - break; - } - - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(resource, " destroyed and can't be released to the pool ").concat(key, " because it is not functional")); - } - - _context2.next = 7; - return this._destroy(resource); - - case 7: - _context2.next = 12; - break; - - case 9: - if (this._installIdleObserver) { - this._installIdleObserver(resource, { - onError: function onError(error) { - _this4._log.debug("Idle connection ".concat(resource, " destroyed because of error: ").concat(error)); - - var pool = _this4._pools[key]; - - if (pool) { - _this4._pools[key] = pool.filter(function (r) { - return r !== resource; - }); - } // let's not care about background clean-ups due to errors but just trigger the destroy - // process for the resource, we especially catch any errors and ignore them to avoid - // unhandled promise rejection warnings - - - _this4._destroy(resource)["catch"](function () {}); - } - }); - } - - pool.push(resource); - - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(resource, " released to the pool ").concat(key)); - } - - case 12: - _context2.next = 17; - break; - - case 14: - // key has been purged, don't put it back, just destroy the resource - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(resource, " destroyed and can't be released to the pool ").concat(key, " because pool has been purged")); - } - - _context2.next = 17; - return this._destroy(resource); - - case 17: - resourceReleased(key, this._activeResourceCounts); - - this._processPendingAcquireRequests(address); - - case 19: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - function _release(_x2, _x3) { - return _release2.apply(this, arguments); - } - - return _release; - }() - }, { - key: "_purgeKey", - value: function () { - var _purgeKey2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee3(key) { - var pool, resource; - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - pool = this._pools[key] || []; - - case 1: - if (!pool.length) { - _context3.next = 8; - break; - } - - resource = pool.pop(); - - if (this._removeIdleObserver) { - this._removeIdleObserver(resource); - } - - _context3.next = 6; - return this._destroy(resource); - - case 6: - _context3.next = 1; - break; - - case 8: - delete this._pools[key]; - - case 9: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - function _purgeKey(_x4) { - return _purgeKey2.apply(this, arguments); - } - - return _purgeKey; - }() - }, { - key: "_processPendingAcquireRequests", - value: function _processPendingAcquireRequests(address) { - var _this5 = this; - - var key = address.asKey(); - var requests = this._acquireRequests[key]; - - if (requests) { - var pendingRequest = requests.shift(); // pop a pending acquire request - - if (pendingRequest) { - this._acquire(address)["catch"](function (error) { - // failed to acquire/create a new connection to resolve the pending acquire request - // propagate the error by failing the pending request - pendingRequest.reject(error); - return null; - }).then(function (resource) { - if (resource) { - // managed to acquire a valid resource from the pool - if (pendingRequest.isCompleted()) { - // request has been completed, most likely failed by a timeout - // return the acquired resource back to the pool - _this5._release(address, resource); - } else { - // request is still pending and can be resolved with the newly acquired resource - pendingRequest.resolve(resource); // resolve the pending request with the acquired resource - } - } - }); - } else { - delete this._acquireRequests[key]; - } - } - } - }]); - return Pool; -}(); -/** - * Increment active (checked out of the pool) resource counter. - * @param {string} key the resource group identifier (server address for connections). - * @param {Object.} activeResourceCounts the object holding active counts per key. - */ - - -function resourceAcquired(key, activeResourceCounts) { - var currentCount = activeResourceCounts[key] || 0; - activeResourceCounts[key] = currentCount + 1; -} -/** - * Decrement active (checked out of the pool) resource counter. - * @param {string} key the resource group identifier (server address for connections). - * @param {Object.} activeResourceCounts the object holding active counts per key. - */ - - -function resourceReleased(key, activeResourceCounts) { - var currentCount = activeResourceCounts[key] || 0; - var nextCount = currentCount - 1; - - if (nextCount > 0) { - activeResourceCounts[key] = nextCount; - } else { - delete activeResourceCounts[key]; - } -} - -var PendingRequest = -/*#__PURE__*/ -function () { - function PendingRequest(key, resolve, reject, timeoutId, log) { - (0, _classCallCheck2["default"])(this, PendingRequest); - this._key = key; - this._resolve = resolve; - this._reject = reject; - this._timeoutId = timeoutId; - this._log = log; - this._completed = false; - } - - (0, _createClass2["default"])(PendingRequest, [{ - key: "isCompleted", - value: function isCompleted() { - return this._completed; - } - }, { - key: "resolve", - value: function resolve(resource) { - if (this._completed) { - return; - } - - this._completed = true; - clearTimeout(this._timeoutId); - - if (this._log.isDebugEnabled()) { - this._log.debug("".concat(resource, " acquired from the pool ").concat(this._key)); - } - - this._resolve(resource); - } - }, { - key: "reject", - value: function reject(error) { - if (this._completed) { - return; - } - - this._completed = true; - clearTimeout(this._timeoutId); - - this._reject(error); - } - }]); - return PendingRequest; -}(); - -var _default = Pool; -exports["default"] = _default; -}); - -var connectionErrorHandler = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var ConnectionErrorHandler = -/*#__PURE__*/ -function () { - function ConnectionErrorHandler(errorCode, handleUnavailability, handleWriteFailure) { - (0, _classCallCheck2["default"])(this, ConnectionErrorHandler); - this._errorCode = errorCode; - this._handleUnavailability = handleUnavailability || noOpHandler; - this._handleWriteFailure = handleWriteFailure || noOpHandler; - } - /** - * Error code to use for network errors. - * @return {string} the error code. - */ - - - (0, _createClass2["default"])(ConnectionErrorHandler, [{ - key: "errorCode", - value: function errorCode() { - return this._errorCode; - } - /** - * Handle and transform the error. - * @param {Neo4jError} error the original error. - * @param {ServerAddress} address the address of the connection where the error happened. - * @return {Neo4jError} new error that should be propagated to the user. - */ - - }, { - key: "handleAndTransformError", - value: function handleAndTransformError(error, address) { - if (isAvailabilityError(error)) { - return this._handleUnavailability(error, address); - } - - if (isFailureToWrite(error)) { - return this._handleWriteFailure(error, address); - } - - return error; - } - }]); - return ConnectionErrorHandler; -}(); - -exports["default"] = ConnectionErrorHandler; - -function isAvailabilityError(error$1) { - if (error$1) { - return error$1.code === error.SESSION_EXPIRED || error$1.code === error.SERVICE_UNAVAILABLE || error$1.code === 'Neo.TransientError.General.DatabaseUnavailable'; - } - - return false; -} - -function isFailureToWrite(error) { - if (error) { - return error.code === 'Neo.ClientError.Cluster.NotALeader' || error.code === 'Neo.ClientError.General.ForbiddenOnReadOnlyDatabase'; - } - - return false; -} - -function noOpHandler(error) { - return error; -} -}); - -var connectionProviderPooled = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _regenerator = interopRequireDefault(regenerator); - -var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _assertThisInitialized2 = interopRequireDefault(assertThisInitialized); - -var _inherits2 = interopRequireDefault(inherits); - -var _connectionChannel = interopRequireDefault(connectionChannel); - -var _pool = interopRequireDefault(pool); - -var _poolConfig = interopRequireDefault(poolConfig); - -var _connectionErrorHandler = interopRequireDefault(connectionErrorHandler); - - - -var _connectionProvider = interopRequireDefault(connectionProvider); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var PooledConnectionProvider = -/*#__PURE__*/ -function (_ConnectionProvider) { - (0, _inherits2["default"])(PooledConnectionProvider, _ConnectionProvider); - - function PooledConnectionProvider(_ref) { - var _this; - - var id = _ref.id, - config = _ref.config, - log = _ref.log, - userAgent = _ref.userAgent, - authToken = _ref.authToken; - var createChannelConnectionHook = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; - (0, _classCallCheck2["default"])(this, PooledConnectionProvider); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(PooledConnectionProvider).call(this)); - _this._id = id; - _this._config = config; - _this._log = log; - _this._userAgent = userAgent; - _this._authToken = authToken; - - _this._createChannelConnection = createChannelConnectionHook || function (address) { - return _connectionChannel["default"].create(address, _this._config, _this._createConnectionErrorHandler(), _this._log); - }; - - _this._connectionPool = new _pool["default"]({ - create: _this._createConnection.bind((0, _assertThisInitialized2["default"])(_this)), - destroy: _this._destroyConnection.bind((0, _assertThisInitialized2["default"])(_this)), - validate: _this._validateConnection.bind((0, _assertThisInitialized2["default"])(_this)), - installIdleObserver: PooledConnectionProvider._installIdleObserverOnConnection.bind((0, _assertThisInitialized2["default"])(_this)), - removeIdleObserver: PooledConnectionProvider._removeIdleObserverOnConnection.bind((0, _assertThisInitialized2["default"])(_this)), - config: _poolConfig["default"].fromDriverConfig(config), - log: _this._log - }); - _this._openConnections = {}; - return _this; - } - - (0, _createClass2["default"])(PooledConnectionProvider, [{ - key: "_createConnectionErrorHandler", - value: function _createConnectionErrorHandler() { - return new _connectionErrorHandler["default"](error.SERVICE_UNAVAILABLE); - } - /** - * Create a new connection and initialize it. - * @return {Promise} promise resolved with a new connection or rejected when failed to connect. - * @access private - */ - - }, { - key: "_createConnection", - value: function _createConnection(address, release) { - var _this2 = this; - - var connection = this._createChannelConnection(address); - - connection._release = function () { - return release(address, connection); - }; - - this._openConnections[connection.id] = connection; - return connection.connect(this._userAgent, this._authToken)["catch"](function (error) { - // let's destroy this connection - _this2._destroyConnection(connection); // propagate the error because connection failed to connect / initialize - - - throw error; - }); - } - /** - * Check that a connection is usable - * @return {boolean} true if the connection is open - * @access private - **/ - - }, { - key: "_validateConnection", - value: function _validateConnection(conn) { - if (!conn.isOpen()) { - return false; - } - - var maxConnectionLifetime = this._config.maxConnectionLifetime; - var lifetime = Date.now() - conn.creationTimestamp; - return lifetime <= maxConnectionLifetime; - } - /** - * Dispose of a connection. - * @return {Connection} the connection to dispose. - * @access private - */ - - }, { - key: "_destroyConnection", - value: function _destroyConnection(conn) { - delete this._openConnections[conn.id]; - return conn.close(); - } - }, { - key: "close", - value: function () { - var _close = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee() { - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this._connectionPool.close(); - - case 2: - _context.next = 4; - return Promise.all(Object.values(this._openConnections).map(function (c) { - return c.close(); - })); - - case 4: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function close() { - return _close.apply(this, arguments); - } - - return close; - }() - }], [{ - key: "_installIdleObserverOnConnection", - value: function _installIdleObserverOnConnection(conn, observer) { - conn._queueObserver(observer); - } - }, { - key: "_removeIdleObserverOnConnection", - value: function _removeIdleObserverOnConnection(conn) { - conn._updateCurrentObserver(); - } - }]); - return PooledConnectionProvider; -}(_connectionProvider["default"]); - -exports["default"] = PooledConnectionProvider; -}); - -var connectionDelegate = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _connection = interopRequireDefault(connection); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DelegateConnection = -/*#__PURE__*/ -function (_Connection) { - (0, _inherits2["default"])(DelegateConnection, _Connection); - - /** - * @param delegate {Connection} the delegated connection - * @param errorHandler {ConnectionErrorHandler} the error handler - */ - function DelegateConnection(delegate, errorHandler) { - var _this; - - (0, _classCallCheck2["default"])(this, DelegateConnection); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(DelegateConnection).call(this, errorHandler)); - - if (errorHandler) { - _this._originalErrorHandler = delegate._errorHandler; - delegate._errorHandler = _this._errorHandler; - } - - _this._delegate = delegate; - return _this; - } - - (0, _createClass2["default"])(DelegateConnection, [{ - key: "isOpen", - value: function isOpen() { - return this._delegate.isOpen(); - } - }, { - key: "protocol", - value: function protocol() { - return this._delegate.protocol(); - } - }, { - key: "connect", - value: function connect(userAgent, authToken) { - return this._delegate.connect(userAgent, authToken); - } - }, { - key: "write", - value: function write(message, observer, flush) { - return this._delegate.write(message, observer, flush); - } - }, { - key: "resetAndFlush", - value: function resetAndFlush() { - return this._delegate.resetAndFlush(); - } - }, { - key: "close", - value: function close() { - return this._delegate.close(); - } - }, { - key: "_release", - value: function _release() { - if (this._originalErrorHandler) { - this._delegate._errorHandler = this._originalErrorHandler; - } - - return this._delegate._release(); - } - }, { - key: "id", - get: function get() { - return this._delegate.id; - } - }, { - key: "databaseId", - get: function get() { - return this._delegate.databaseId; - }, - set: function set(value) { - this._delegate.databaseId = value; - } - }, { - key: "server", - get: function get() { - return this._delegate.server; - } - }, { - key: "address", - get: function get() { - return this._delegate.address; - } - }, { - key: "version", - get: function get() { - return this._delegate.version; - }, - set: function set(value) { - this._delegate.version = value; - } - }]); - return DelegateConnection; -}(_connection["default"]); - -exports["default"] = DelegateConnection; -}); - -var connectionProviderDirect = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _regenerator = interopRequireDefault(regenerator); - -var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _connectionProviderPooled = interopRequireDefault(connectionProviderPooled); - -var _connectionDelegate = interopRequireDefault(connectionDelegate); - -var _connectionChannel = interopRequireDefault(connectionChannel); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DirectConnectionProvider = -/*#__PURE__*/ -function (_PooledConnectionProv) { - (0, _inherits2["default"])(DirectConnectionProvider, _PooledConnectionProv); - - function DirectConnectionProvider(_ref) { - var _this; - - var id = _ref.id, - config = _ref.config, - log = _ref.log, - address = _ref.address, - userAgent = _ref.userAgent, - authToken = _ref.authToken; - (0, _classCallCheck2["default"])(this, DirectConnectionProvider); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(DirectConnectionProvider).call(this, { - id: id, - config: config, - log: log, - userAgent: userAgent, - authToken: authToken - })); - _this._address = address; - return _this; - } - /** - * See {@link ConnectionProvider} for more information about this method and - * its arguments. - */ - - - (0, _createClass2["default"])(DirectConnectionProvider, [{ - key: "acquireConnection", - value: function acquireConnection() { - var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - _ref2.accessMode; - _ref2.database; - _ref2.bookmarks; - - return this._connectionPool.acquire(this._address).then(function (connection) { - return new _connectionDelegate["default"](connection, null); - }); - } - }, { - key: "_hasProtocolVersion", - value: function () { - var _hasProtocolVersion2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee(versionPredicate) { - var connection, protocol; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - connection = _connectionChannel["default"].create(this._address, this._config, this._createConnectionErrorHandler(), this._log); - _context.prev = 1; - _context.next = 4; - return connection._negotiateProtocol(); - - case 4: - protocol = connection.protocol(); - - if (!protocol) { - _context.next = 7; - break; - } - - return _context.abrupt("return", versionPredicate(protocol.version)); - - case 7: - return _context.abrupt("return", false); - - case 8: - _context.prev = 8; - _context.next = 11; - return connection.close(); - - case 11: - return _context.finish(8); - - case 12: - case "end": - return _context.stop(); - } - } - }, _callee, this, [[1,, 8, 12]]); - })); - - function _hasProtocolVersion(_x) { - return _hasProtocolVersion2.apply(this, arguments); - } - - return _hasProtocolVersion; - }() - }, { - key: "supportsMultiDb", - value: function () { - var _supportsMultiDb = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee2() { - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return this._hasProtocolVersion(function (version) { - return version >= constants.BOLT_PROTOCOL_V4_0; - }); - - case 2: - return _context2.abrupt("return", _context2.sent); - - case 3: - case "end": - return _context2.stop(); - } - } - }, _callee2, this); - })); - - function supportsMultiDb() { - return _supportsMultiDb.apply(this, arguments); - } - - return supportsMultiDb; - }() - }, { - key: "supportsTransactionConfig", - value: function () { - var _supportsTransactionConfig = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee3() { - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return this._hasProtocolVersion(function (version) { - return version >= constants.BOLT_PROTOCOL_V3; - }); - - case 2: - return _context3.abrupt("return", _context3.sent); - - case 3: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - function supportsTransactionConfig() { - return _supportsTransactionConfig.apply(this, arguments); - } - - return supportsTransactionConfig; - }() - }]); - return DirectConnectionProvider; -}(_connectionProviderPooled["default"]); - -exports["default"] = DirectConnectionProvider; -}); - -var connectivityVerifier = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _connectionHolder = interopRequireDefault(connectionHolder); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Verifies connectivity using the given connection provider. - */ -var ConnectivityVerifier = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {ConnectionProvider} connectionProvider the provider to obtain connections from. - */ - function ConnectivityVerifier(connectionProvider) { - (0, _classCallCheck2["default"])(this, ConnectivityVerifier); - this._connectionProvider = connectionProvider; - } - /** - * Try to obtain a working connection from the connection provider. - * @returns {Promise} promise resolved with server info or rejected with error. - */ - - - (0, _createClass2["default"])(ConnectivityVerifier, [{ - key: "verify", - value: function verify() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref$database = _ref.database, - database = _ref$database === void 0 ? '' : _ref$database; - - return acquireAndReleaseDummyConnection(this._connectionProvider, database); - } - }]); - return ConnectivityVerifier; -}(); -/** - * @private - * @param {ConnectionProvider} connectionProvider the provider to obtain connections from. - * @return {Promise} promise resolved with server info or rejected with error. - */ - - -exports["default"] = ConnectivityVerifier; - -function acquireAndReleaseDummyConnection(connectionProvider, database) { - var connectionHolder = new _connectionHolder["default"]({ - mode: driver.READ, - database: database, - connectionProvider: connectionProvider - }); - connectionHolder.initializeConnection(); - return connectionHolder.getConnection().then(function (connection) { - // able to establish a connection - return connectionHolder.close().then(function () { - return connection.server; - }); - })["catch"](function (error) { - // failed to establish a connection - return connectionHolder.close()["catch"](function (ignoredError) {// ignore connection release error - }).then(function () { - return Promise.reject(error); - }); - }); -} -}); - -var connectionHolderReadonly = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _connectionHolder = interopRequireDefault(connectionHolder); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Provides a interaction with a ConnectionHolder without change it state by - * releasing or initilizing - */ -var ReadOnlyConnectionHolder = -/*#__PURE__*/ -function (_ConnectionHolder) { - (0, _inherits2["default"])(ReadOnlyConnectionHolder, _ConnectionHolder); - - /** - * Contructor - * @param {ConnectionHolder} connectionHolder the connection holder which will treat the requests - */ - function ReadOnlyConnectionHolder(connectionHolder) { - var _this; - - (0, _classCallCheck2["default"])(this, ReadOnlyConnectionHolder); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(ReadOnlyConnectionHolder).call(this, { - mode: connectionHolder._mode, - database: connectionHolder._database, - bookmark: connectionHolder._bookmark, - connectionProvider: connectionHolder._connectionProvider - })); - _this._connectionHolder = connectionHolder; - return _this; - } - /** - * Return the true if the connection is suppose to be initilized with the command. - * - * @return {boolean} - */ - - - (0, _createClass2["default"])(ReadOnlyConnectionHolder, [{ - key: "initializeConnection", - value: function initializeConnection() { - if (this._connectionHolder._referenceCount === 0) { - return false; - } - - return true; - } - /** - * Get the current connection promise. - * @return {Promise} promise resolved with the current connection. - */ - - }, { - key: "getConnection", - value: function getConnection() { - return this._connectionHolder.getConnection(); - } - /** - * Get the current connection promise, doesn't performs the release - * @return {Promise} promise with the resolved current connection - */ - - }, { - key: "releaseConnection", - value: function releaseConnection() { - return this._connectionHolder.getConnection()["catch"](function () { - return Promise.resolve(); - }); - } - /** - * Get the current connection promise, doesn't performs the connection close - * @return {Promise} promise with the resolved current connection - */ - - }, { - key: "close", - value: function close() { - return this._connectionHolder.getConnection()["catch"](function () { - return function () { - return Promise.resolve(); - }; - }); - } - }]); - return ReadOnlyConnectionHolder; -}(_connectionHolder["default"]); - -exports["default"] = ReadOnlyConnectionHolder; -}); - -var transaction = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _result = interopRequireDefault(result); - - - -var _connectionHolder = interopRequireWildcard(connectionHolder); - -var _connectionHolderReadonly = interopRequireDefault(connectionHolderReadonly); - -var _bookmark = interopRequireDefault(bookmark); - -var _txConfig = interopRequireDefault(txConfig); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Represents a transaction in the Neo4j database. - * - * @access public - */ -var Transaction = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {ConnectionHolder} connectionHolder - the connection holder to get connection from. - * @param {function()} onClose - Function to be called when transaction is committed or rolled back. - * @param {function(bookmark: Bookmark)} onBookmark callback invoked when new bookmark is produced. - * * @param {function()} onConnection - Function to be called when a connection is obtained to ensure the conneciton - * is not yet released. - * @param {boolean} reactive whether this transaction generates reactive streams - * @param {number} fetchSize - the record fetch size in each pulling batch. - */ - function Transaction(_ref) { - var connectionHolder = _ref.connectionHolder, - onClose = _ref.onClose, - onBookmark = _ref.onBookmark, - onConnection = _ref.onConnection, - reactive = _ref.reactive, - fetchSize = _ref.fetchSize; - (0, _classCallCheck2["default"])(this, Transaction); - this._connectionHolder = connectionHolder; - this._reactive = reactive; - this._state = _states.ACTIVE; - this._onClose = onClose; - this._onBookmark = onBookmark; - this._onConnection = onConnection; - this._onError = this._onErrorCallback.bind(this); - this._onComplete = this._onCompleteCallback.bind(this); - this._fetchSize = fetchSize; - this._results = []; - } - - (0, _createClass2["default"])(Transaction, [{ - key: "_begin", - value: function _begin(bookmark, txConfig) { - var _this = this; - - this._connectionHolder.getConnection().then(function (conn) { - _this._onConnection(); - - return conn.protocol().beginTransaction({ - bookmark: bookmark, - txConfig: txConfig, - mode: _this._connectionHolder.mode(), - database: _this._connectionHolder.database(), - beforeError: _this._onError, - afterComplete: _this._onComplete - }); - })["catch"](function (error) { - return _this._onError(error); - }); - } - /** - * Run Cypher query - * Could be called with a query object i.e.: `{text: "MATCH ...", parameters: {param: 1}}` - * or with the query and parameters as separate arguments. - * @param {mixed} query - Cypher query to execute - * @param {Object} parameters - Map with parameters to use in query - * @return {Result} New Result - */ - - }, { - key: "run", - value: function run(query, parameters) { - var _validateQueryAndPara = (0, util.validateQueryAndParameters)(query, parameters), - validatedQuery = _validateQueryAndPara.validatedQuery, - params = _validateQueryAndPara.params; - - var result = this._state.run(validatedQuery, params, { - connectionHolder: this._connectionHolder, - onError: this._onError, - onComplete: this._onComplete, - onConnection: this._onConnection, - reactive: this._reactive, - fetchSize: this._fetchSize - }); - - this._results.push(result); - - return result; - } - /** - * Commits the transaction and returns the result. - * - * After committing the transaction can no longer be used. - * - * @returns {Promise} An empty promise if committed successfully or error if any error happened during commit. - */ - - }, { - key: "commit", - value: function commit() { - var committed = this._state.commit({ - connectionHolder: this._connectionHolder, - onError: this._onError, - onComplete: this._onComplete, - onConnection: this._onConnection, - pendingResults: this._results - }); - - this._state = committed.state; // clean up - - this._onClose(); - - return new Promise(function (resolve, reject) { - committed.result.subscribe({ - onCompleted: function onCompleted() { - return resolve(); - }, - onError: function onError(error) { - return reject(error); - } - }); - }); - } - /** - * Rollbacks the transaction. - * - * After rolling back, the transaction can no longer be used. - * - * @returns {Promise} An empty promise if rolled back successfully or error if any error happened during - * rollback. - */ - - }, { - key: "rollback", - value: function rollback() { - var rolledback = this._state.rollback({ - connectionHolder: this._connectionHolder, - onError: this._onError, - onComplete: this._onComplete, - onConnection: this._onConnection, - pendingResults: this._results - }); - - this._state = rolledback.state; // clean up - - this._onClose(); - - return new Promise(function (resolve, reject) { - rolledback.result.subscribe({ - onCompleted: function onCompleted() { - return resolve(); - }, - onError: function onError(error) { - return reject(error); - } - }); - }); - } - /** - * Check if this transaction is active, which means commit and rollback did not happen. - * @return {boolean} `true` when not committed and not rolled back, `false` otherwise. - */ - - }, { - key: "isOpen", - value: function isOpen() { - return this._state === _states.ACTIVE; - } - }, { - key: "_onErrorCallback", - value: function _onErrorCallback(err) { - // error will be "acknowledged" by sending a RESET message - // database will then forget about this transaction and cleanup all corresponding resources - // it is thus safe to move this transaction to a FAILED state and disallow any further interactions with it - this._state = _states.FAILED; - - this._onClose(); // release connection back to the pool - - - return this._connectionHolder.releaseConnection(); - } - }, { - key: "_onCompleteCallback", - value: function _onCompleteCallback(meta) { - this._onBookmark(new _bookmark["default"](meta.bookmark)); - } - }]); - return Transaction; -}(); - -var _states = { - // The transaction is running with no explicit success or failure marked - ACTIVE: { - commit: function commit(_ref2) { - var connectionHolder = _ref2.connectionHolder, - onError = _ref2.onError, - onComplete = _ref2.onComplete, - onConnection = _ref2.onConnection, - pendingResults = _ref2.pendingResults; - return { - result: finishTransaction(true, connectionHolder, onError, onComplete, onConnection, pendingResults), - state: _states.SUCCEEDED - }; - }, - rollback: function rollback(_ref3) { - var connectionHolder = _ref3.connectionHolder, - onError = _ref3.onError, - onComplete = _ref3.onComplete, - onConnection = _ref3.onConnection, - pendingResults = _ref3.pendingResults; - return { - result: finishTransaction(false, connectionHolder, onError, onComplete, onConnection, pendingResults), - state: _states.ROLLED_BACK - }; - }, - run: function run(query, parameters, _ref4) { - var connectionHolder = _ref4.connectionHolder, - onError = _ref4.onError, - onComplete = _ref4.onComplete, - onConnection = _ref4.onConnection, - reactive = _ref4.reactive, - fetchSize = _ref4.fetchSize; - // RUN in explicit transaction can't contain bookmarks and transaction configuration - // No need to include mode and database name as it shall be inclued in begin - var observerPromise = connectionHolder.getConnection().then(function (conn) { - onConnection(); - return conn.protocol().run(query, parameters, { - bookmark: _bookmark["default"].empty(), - txConfig: _txConfig["default"].empty(), - beforeError: onError, - afterComplete: onComplete, - reactive: reactive, - fetchSize: fetchSize - }); - })["catch"](function (error) { - return new streamObservers.FailedObserver({ - error: error, - onError: onError - }); - }); - return newCompletedResult(observerPromise, query, parameters, connectionHolder); - } - }, - // An error has occurred, transaction can no longer be used and no more messages will - // be sent for this transaction. - FAILED: { - commit: function commit(_ref5) { - var connectionHolder = _ref5.connectionHolder, - onError = _ref5.onError; - _ref5.onComplete; - return { - result: newCompletedResult(new streamObservers.FailedObserver({ - error: (0, error.newError)('Cannot commit this transaction, because it has been rolled back either because of an error or explicit termination.'), - onError: onError - }), 'COMMIT', {}, connectionHolder), - state: _states.FAILED - }; - }, - rollback: function rollback(_ref6) { - var connectionHolder = _ref6.connectionHolder; - _ref6.onError; - _ref6.onComplete; - return { - result: newCompletedResult(new streamObservers.CompletedObserver(), 'ROLLBACK', {}, connectionHolder), - state: _states.FAILED - }; - }, - run: function run(query, parameters, _ref7) { - var connectionHolder = _ref7.connectionHolder, - onError = _ref7.onError; - _ref7.onComplete; - return newCompletedResult(new streamObservers.FailedObserver({ - error: (0, error.newError)('Cannot run query in this transaction, because it has been rolled back either because of an error or explicit termination.'), - onError: onError - }), query, parameters, connectionHolder); - } - }, - // This transaction has successfully committed - SUCCEEDED: { - commit: function commit(_ref8) { - var connectionHolder = _ref8.connectionHolder, - onError = _ref8.onError; - _ref8.onComplete; - return { - result: newCompletedResult(new streamObservers.FailedObserver({ - error: (0, error.newError)('Cannot commit this transaction, because it has already been committed.'), - onError: onError - }), 'COMMIT', {}), - state: _states.SUCCEEDED, - connectionHolder: connectionHolder - }; - }, - rollback: function rollback(_ref9) { - var connectionHolder = _ref9.connectionHolder, - onError = _ref9.onError; - _ref9.onComplete; - return { - result: newCompletedResult(new streamObservers.FailedObserver({ - error: (0, error.newError)('Cannot rollback this transaction, because it has already been committed.'), - onError: onError - }), 'ROLLBACK', {}), - state: _states.SUCCEEDED, - connectionHolder: connectionHolder - }; - }, - run: function run(query, parameters, _ref10) { - var connectionHolder = _ref10.connectionHolder, - onError = _ref10.onError; - _ref10.onComplete; - return newCompletedResult(new streamObservers.FailedObserver({ - error: (0, error.newError)('Cannot run query in this transaction, because it has already been committed.'), - onError: onError - }), query, parameters, connectionHolder); - } - }, - // This transaction has been rolled back - ROLLED_BACK: { - commit: function commit(_ref11) { - var connectionHolder = _ref11.connectionHolder, - onError = _ref11.onError; - _ref11.onComplete; - return { - result: newCompletedResult(new streamObservers.FailedObserver({ - error: (0, error.newError)('Cannot commit this transaction, because it has already been rolled back.'), - onError: onError - }), 'COMMIT', {}, connectionHolder), - state: _states.ROLLED_BACK - }; - }, - rollback: function rollback(_ref12) { - var connectionHolder = _ref12.connectionHolder; - _ref12.onError; - _ref12.onComplete; - return { - result: newCompletedResult(new streamObservers.FailedObserver({ - error: (0, error.newError)('Cannot rollback this transaction, because it has already been rolled back.') - }), 'ROLLBACK', {}, connectionHolder), - state: _states.ROLLED_BACK - }; - }, - run: function run(query, parameters, _ref13) { - var connectionHolder = _ref13.connectionHolder, - onError = _ref13.onError; - _ref13.onComplete; - return newCompletedResult(new streamObservers.FailedObserver({ - error: (0, error.newError)('Cannot run query in this transaction, because it has already been rolled back.'), - onError: onError - }), query, parameters, connectionHolder); - } - } - /** - * - * @param {boolean} commit - * @param {ConnectionHolder} connectionHolder - * @param {function(err:Error): any} onError - * @param {function(metadata:object): any} onComplete - * @param {function() : any} onConnection - * @param {list>}pendingResults all run results in this transaction - */ - -}; - -function finishTransaction(commit, connectionHolder, onError, onComplete, onConnection, pendingResults) { - var observerPromise = connectionHolder.getConnection().then(function (connection) { - onConnection(); - pendingResults.forEach(function (r) { - return r._cancel(); - }); - return Promise.all(pendingResults).then(function (results) { - if (commit) { - return connection.protocol().commitTransaction({ - beforeError: onError, - afterComplete: onComplete - }); - } else { - return connection.protocol().rollbackTransaction({ - beforeError: onError, - afterComplete: onComplete - }); - } - }); - })["catch"](function (error) { - return new streamObservers.FailedObserver({ - error: error, - onError: onError - }); - }); // for commit & rollback we need result that uses real connection holder and notifies it when - // connection is not needed and can be safely released to the pool - - return new _result["default"](observerPromise, commit ? 'COMMIT' : 'ROLLBACK', {}, connectionHolder); -} -/** - * Creates a {@link Result} with empty connection holder. - * For cases when result represents an intermediate or failed action, does not require any metadata and does not - * need to influence real connection holder to release connections. - * @param {ResultStreamObserver} observer - an observer for the created result. - * @param {string} query - the cypher query that produced the result. - * @param {Object} parameters - the parameters for cypher query that produced the result. - * @param {ConnectionHolder} connectionHolder - the connection holder used to get the result - * @return {Result} new result. - * @private - */ - - -function newCompletedResult(observerPromise, query, parameters) { - var connectionHolder = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _connectionHolder.EMPTY_CONNECTION_HOLDER; - return new _result["default"](Promise.resolve(observerPromise), query, parameters, new _connectionHolderReadonly["default"](connectionHolder || _connectionHolder.EMPTY_CONNECTION_HOLDER)); -} - -var _default = Transaction; -exports["default"] = _default; -}); - -var transactionExecutor = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DEFAULT_MAX_RETRY_TIME_MS = 30 * 1000; // 30 seconds - -var DEFAULT_INITIAL_RETRY_DELAY_MS = 1000; // 1 seconds - -var DEFAULT_RETRY_DELAY_MULTIPLIER = 2.0; -var DEFAULT_RETRY_DELAY_JITTER_FACTOR = 0.2; - -var TransactionExecutor = -/*#__PURE__*/ -function () { - function TransactionExecutor(maxRetryTimeMs, initialRetryDelayMs, multiplier, jitterFactor) { - (0, _classCallCheck2["default"])(this, TransactionExecutor); - this._maxRetryTimeMs = _valueOrDefault(maxRetryTimeMs, DEFAULT_MAX_RETRY_TIME_MS); - this._initialRetryDelayMs = _valueOrDefault(initialRetryDelayMs, DEFAULT_INITIAL_RETRY_DELAY_MS); - this._multiplier = _valueOrDefault(multiplier, DEFAULT_RETRY_DELAY_MULTIPLIER); - this._jitterFactor = _valueOrDefault(jitterFactor, DEFAULT_RETRY_DELAY_JITTER_FACTOR); - this._inFlightTimeoutIds = []; - - this._verifyAfterConstruction(); - } - - (0, _createClass2["default"])(TransactionExecutor, [{ - key: "execute", - value: function execute(transactionCreator, transactionWork) { - var _this = this; - - return new Promise(function (resolve, reject) { - _this._executeTransactionInsidePromise(transactionCreator, transactionWork, resolve, reject); - })["catch"](function (error) { - var retryStartTimeMs = Date.now(); - var retryDelayMs = _this._initialRetryDelayMs; - return _this._retryTransactionPromise(transactionCreator, transactionWork, error, retryStartTimeMs, retryDelayMs); - }); - } - }, { - key: "close", - value: function close() { - // cancel all existing timeouts to prevent further retries - this._inFlightTimeoutIds.forEach(function (timeoutId) { - return clearTimeout(timeoutId); - }); - - this._inFlightTimeoutIds = []; - } - }, { - key: "_retryTransactionPromise", - value: function _retryTransactionPromise(transactionCreator, transactionWork, error, retryStartTime, retryDelayMs) { - var _this2 = this; - - var elapsedTimeMs = Date.now() - retryStartTime; - - if (elapsedTimeMs > this._maxRetryTimeMs || !TransactionExecutor._canRetryOn(error)) { - return Promise.reject(error); - } - - return new Promise(function (resolve, reject) { - var nextRetryTime = _this2._computeDelayWithJitter(retryDelayMs); - - var timeoutId = setTimeout(function () { - // filter out this timeoutId when time has come and function is being executed - _this2._inFlightTimeoutIds = _this2._inFlightTimeoutIds.filter(function (id) { - return id !== timeoutId; - }); - - _this2._executeTransactionInsidePromise(transactionCreator, transactionWork, resolve, reject); - }, nextRetryTime); // add newly created timeoutId to the list of all in-flight timeouts - - _this2._inFlightTimeoutIds.push(timeoutId); - })["catch"](function (error) { - var nextRetryDelayMs = retryDelayMs * _this2._multiplier; - return _this2._retryTransactionPromise(transactionCreator, transactionWork, error, retryStartTime, nextRetryDelayMs); - }); - } - }, { - key: "_executeTransactionInsidePromise", - value: function _executeTransactionInsidePromise(transactionCreator, transactionWork, resolve, reject) { - var _this3 = this; - - var tx; - - try { - tx = transactionCreator(); - } catch (error) { - // failed to create a transaction - reject(error); - return; - } - - var resultPromise = this._safeExecuteTransactionWork(tx, transactionWork); - - resultPromise.then(function (result) { - return _this3._handleTransactionWorkSuccess(result, tx, resolve, reject); - })["catch"](function (error) { - return _this3._handleTransactionWorkFailure(error, tx, reject); - }); - } - }, { - key: "_safeExecuteTransactionWork", - value: function _safeExecuteTransactionWork(tx, transactionWork) { - try { - var result = transactionWork(tx); // user defined callback is supposed to return a promise, but it might not; so to protect against an - // incorrect API usage we wrap the returned value with a resolved promise; this is effectively a - // validation step without type checks - - return Promise.resolve(result); - } catch (error) { - return Promise.reject(error); - } - } - }, { - key: "_handleTransactionWorkSuccess", - value: function _handleTransactionWorkSuccess(result, tx, resolve, reject) { - if (tx.isOpen()) { - // transaction work returned resolved promise and transaction has not been committed/rolled back - // try to commit the transaction - tx.commit().then(function () { - // transaction was committed, return result to the user - resolve(result); - })["catch"](function (error) { - // transaction failed to commit, propagate the failure - reject(error); - }); - } else { - // transaction work returned resolved promise and transaction is already committed/rolled back - // return the result returned by given transaction work - resolve(result); - } - } - }, { - key: "_handleTransactionWorkFailure", - value: function _handleTransactionWorkFailure(error, tx, reject) { - if (tx.isOpen()) { - // transaction work failed and the transaction is still open, roll it back and propagate the failure - tx.rollback()["catch"](function (ignore) {// ignore the rollback error - }).then(function () { - return reject(error); - }); // propagate the original error we got from the transaction work - } else { - // transaction is already rolled back, propagate the error - reject(error); - } - } - }, { - key: "_computeDelayWithJitter", - value: function _computeDelayWithJitter(delayMs) { - var jitter = delayMs * this._jitterFactor; - var min = delayMs - jitter; - var max = delayMs + jitter; - return Math.random() * (max - min) + min; - } - }, { - key: "_verifyAfterConstruction", - value: function _verifyAfterConstruction() { - if (this._maxRetryTimeMs < 0) { - throw (0, error.newError)('Max retry time should be >= 0: ' + this._maxRetryTimeMs); - } - - if (this._initialRetryDelayMs < 0) { - throw (0, error.newError)('Initial retry delay should >= 0: ' + this._initialRetryDelayMs); - } - - if (this._multiplier < 1.0) { - throw (0, error.newError)('Multiplier should be >= 1.0: ' + this._multiplier); - } - - if (this._jitterFactor < 0 || this._jitterFactor > 1) { - throw (0, error.newError)('Jitter factor should be in [0.0, 1.0]: ' + this._jitterFactor); - } - } - }], [{ - key: "_canRetryOn", - value: function _canRetryOn(error$1) { - return error$1 && error$1 instanceof error.Neo4jError && error$1.code && (error$1.code === error.SERVICE_UNAVAILABLE || error$1.code === error.SESSION_EXPIRED || this._isTransientError(error$1)); - } - }, { - key: "_isTransientError", - value: function _isTransientError(error) { - // Retries should not happen when transaction was explicitly terminated by the user. - // Termination of transaction might result in two different error codes depending on where it was - // terminated. These are really client errors but classification on the server is not entirely correct and - // they are classified as transient. - var code = error.code; - - if (code.indexOf('TransientError') >= 0) { - if (code === 'Neo.TransientError.Transaction.Terminated' || code === 'Neo.TransientError.Transaction.LockClientStopped') { - return false; - } - - return true; - } - - return false; - } - }]); - return TransactionExecutor; -}(); - -exports["default"] = TransactionExecutor; - -function _valueOrDefault(value, defaultValue) { - if (value || value === 0) { - return value; - } - - return defaultValue; -} -}); - -var session = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _regenerator = interopRequireDefault(regenerator); - -var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -var _result = interopRequireDefault(result); - -var _transaction = interopRequireDefault(transaction); - - - - - -var _connectionHolder = interopRequireDefault(connectionHolder); - -var _driver = interopRequireDefault(driver); - - - -var _transactionExecutor = interopRequireDefault(transactionExecutor); - -var _bookmark = interopRequireDefault(bookmark); - -var _txConfig = interopRequireDefault(txConfig); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * A Session instance is used for handling the connection and - * sending queries through the connection. - * In a single session, multiple queries will be executed serially. - * In order to execute parallel queries, multiple sessions are required. - * @access public - */ -var Session = -/*#__PURE__*/ -function () { - /** - * @constructor - * @protected - * @param {Object} args - * @param {string} args.mode the default access mode for this session. - * @param {ConnectionProvider} args.connectionProvider - The connection provider to acquire connections from. - * @param {Bookmark} args.bookmark - The initial bookmark for this session. - * @param {string} args.database the database name - * @param {Object} args.config={} - This driver configuration. - * @param {boolean} args.reactive - Whether this session should create reactive streams - * @param {number} args.fetchSize - Defines how many records is pulled in each pulling batch - */ - function Session(_ref) { - var mode = _ref.mode, - connectionProvider = _ref.connectionProvider, - bookmark = _ref.bookmark, - database = _ref.database, - config = _ref.config, - reactive = _ref.reactive, - fetchSize = _ref.fetchSize; - (0, _classCallCheck2["default"])(this, Session); - this._mode = mode; - this._database = database; - this._reactive = reactive; - this._fetchSize = fetchSize; - this._readConnectionHolder = new _connectionHolder["default"]({ - mode: constants.ACCESS_MODE_READ, - database: database, - bookmark: bookmark, - connectionProvider: connectionProvider - }); - this._writeConnectionHolder = new _connectionHolder["default"]({ - mode: constants.ACCESS_MODE_WRITE, - database: database, - bookmark: bookmark, - connectionProvider: connectionProvider - }); - this._open = true; - this._hasTx = false; - this._lastBookmark = bookmark; - this._transactionExecutor = _createTransactionExecutor(config); - this._onComplete = this._onCompleteCallback.bind(this); - } - /** - * Run Cypher query - * Could be called with a query object i.e.: `{text: "MATCH ...", prameters: {param: 1}}` - * or with the query and parameters as separate arguments. - * - * @public - * @param {mixed} query - Cypher query to execute - * @param {Object} parameters - Map with parameters to use in query - * @param {TransactionConfig} [transactionConfig] - Configuration for the new auto-commit transaction. - * @return {Result} New Result. - */ - - - (0, _createClass2["default"])(Session, [{ - key: "run", - value: function run(query, parameters, transactionConfig) { - var _this = this; - - var _validateQueryAndPara = (0, util.validateQueryAndParameters)(query, parameters), - validatedQuery = _validateQueryAndPara.validatedQuery, - params = _validateQueryAndPara.params; - - var autoCommitTxConfig = transactionConfig ? new _txConfig["default"](transactionConfig) : _txConfig["default"].empty(); - return this._run(validatedQuery, params, function (connection) { - _this._assertSessionIsOpen(); - - return connection.protocol().run(validatedQuery, params, { - bookmark: _this._lastBookmark, - txConfig: autoCommitTxConfig, - mode: _this._mode, - database: _this._database, - afterComplete: _this._onComplete, - reactive: _this._reactive, - fetchSize: _this._fetchSize - }); - }); - } - }, { - key: "_run", - value: function _run(query, parameters, customRunner) { - var connectionHolder = this._connectionHolderWithMode(this._mode); - - var observerPromise; - - if (!this._open) { - observerPromise = Promise.resolve(new streamObservers.FailedObserver({ - error: (0, error.newError)('Cannot run query in a closed session.') - })); - } else if (!this._hasTx && connectionHolder.initializeConnection()) { - observerPromise = connectionHolder.getConnection().then(function (connection) { - return customRunner(connection); - })["catch"](function (error) { - return Promise.resolve(new streamObservers.FailedObserver({ - error: error - })); - }); - } else { - observerPromise = Promise.resolve(new streamObservers.FailedObserver({ - error: (0, error.newError)('Queries cannot be run directly on a ' + 'session with an open transaction; either run from within the ' + 'transaction or use a different session.') - })); - } - - return new _result["default"](observerPromise, query, parameters, connectionHolder); - } - /** - * Begin a new transaction in this session. A session can have at most one transaction running at a time, if you - * want to run multiple concurrent transactions, you should use multiple concurrent sessions. - * - * While a transaction is open the session cannot be used to run queries outside the transaction. - * - * @param {TransactionConfig} [transactionConfig] - Configuration for the new auto-commit transaction. - * @returns {Transaction} New Transaction. - */ - - }, { - key: "beginTransaction", - value: function beginTransaction(transactionConfig) { - // this function needs to support bookmarks parameter for backwards compatibility - // parameter was of type {string|string[]} and represented either a single or multiple bookmarks - // that's why we need to check parameter type and decide how to interpret the value - var arg = transactionConfig; - - var txConfig = _txConfig["default"].empty(); - - if (arg) { - txConfig = new _txConfig["default"](arg); - } - - return this._beginTransaction(this._mode, txConfig); - } - }, { - key: "_beginTransaction", - value: function _beginTransaction(accessMode, txConfig) { - if (!this._open) { - throw (0, error.newError)('Cannot begin a transaction on a closed session.'); - } - - if (this._hasTx) { - throw (0, error.newError)('You cannot begin a transaction on a session with an open transaction; ' + 'either run from within the transaction or use a different session.'); - } - - var mode = _driver["default"]._validateSessionMode(accessMode); - - var connectionHolder = this._connectionHolderWithMode(mode); - - connectionHolder.initializeConnection(); - this._hasTx = true; - var tx = new _transaction["default"]({ - connectionHolder: connectionHolder, - onClose: this._transactionClosed.bind(this), - onBookmark: this._updateBookmark.bind(this), - onConnection: this._assertSessionIsOpen.bind(this), - reactive: this._reactive, - fetchSize: this._fetchSize - }); - - tx._begin(this._lastBookmark, txConfig); - - return tx; - } - }, { - key: "_assertSessionIsOpen", - value: function _assertSessionIsOpen() { - if (!this._open) { - throw (0, error.newError)('You cannot run more transactions on a closed session.'); - } - } - }, { - key: "_transactionClosed", - value: function _transactionClosed() { - this._hasTx = false; - } - /** - * Return the bookmark received following the last completed {@link Transaction}. - * - * @return {string[]} A reference to a previous transaction. - */ - - }, { - key: "lastBookmark", - value: function lastBookmark() { - return this._lastBookmark.values(); - } - /** - * Execute given unit of work in a {@link READ} transaction. - * - * Transaction will automatically be committed unless the given function throws or returns a rejected promise. - * Some failures of the given function or the commit itself will be retried with exponential backoff with initial - * delay of 1 second and maximum retry time of 30 seconds. Maximum retry time is configurable via driver config's - * `maxTransactionRetryTime` property in milliseconds. - * - * @param {function(tx: Transaction): Promise} transactionWork - Callback that executes operations against - * a given {@link Transaction}. - * @param {TransactionConfig} [transactionConfig] - Configuration for all transactions started to execute the unit of work. - * @return {Promise} Resolved promise as returned by the given function or rejected promise when given - * function or commit fails. - */ - - }, { - key: "readTransaction", - value: function readTransaction(transactionWork, transactionConfig) { - var config = new _txConfig["default"](transactionConfig); - return this._runTransaction(constants.ACCESS_MODE_READ, config, transactionWork); - } - /** - * Execute given unit of work in a {@link WRITE} transaction. - * - * Transaction will automatically be committed unless the given function throws or returns a rejected promise. - * Some failures of the given function or the commit itself will be retried with exponential backoff with initial - * delay of 1 second and maximum retry time of 30 seconds. Maximum retry time is configurable via driver config's - * `maxTransactionRetryTime` property in milliseconds. - * - * @param {function(tx: Transaction): Promise} transactionWork - Callback that executes operations against - * a given {@link Transaction}. - * @param {TransactionConfig} [transactionConfig] - Configuration for all transactions started to execute the unit of work. - * @return {Promise} Resolved promise as returned by the given function or rejected promise when given - * function or commit fails. - */ - - }, { - key: "writeTransaction", - value: function writeTransaction(transactionWork, transactionConfig) { - var config = new _txConfig["default"](transactionConfig); - return this._runTransaction(constants.ACCESS_MODE_WRITE, config, transactionWork); - } - }, { - key: "_runTransaction", - value: function _runTransaction(accessMode, transactionConfig, transactionWork) { - var _this2 = this; - - return this._transactionExecutor.execute(function () { - return _this2._beginTransaction(accessMode, transactionConfig); - }, transactionWork); - } - /** - * Update value of the last bookmark. - * @param {Bookmark} newBookmark - The new bookmark. - */ - - }, { - key: "_updateBookmark", - value: function _updateBookmark(newBookmark) { - if (newBookmark && !newBookmark.isEmpty()) { - this._lastBookmark = newBookmark; - } - } - /** - * Close this session. - * @return {Promise} - */ - - }, { - key: "close", - value: function () { - var _close = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee() { - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - if (!this._open) { - _context.next = 7; - break; - } - - this._open = false; - - this._transactionExecutor.close(); - - _context.next = 5; - return this._readConnectionHolder.close(); - - case 5: - _context.next = 7; - return this._writeConnectionHolder.close(); - - case 7: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function close() { - return _close.apply(this, arguments); - } - - return close; - }() - }, { - key: "_connectionHolderWithMode", - value: function _connectionHolderWithMode(mode) { - if (mode === constants.ACCESS_MODE_READ) { - return this._readConnectionHolder; - } else if (mode === constants.ACCESS_MODE_WRITE) { - return this._writeConnectionHolder; - } else { - throw (0, error.newError)('Unknown access mode: ' + mode); - } - } - }, { - key: "_onCompleteCallback", - value: function _onCompleteCallback(meta) { - this._updateBookmark(new _bookmark["default"](meta.bookmark)); - } - }]); - return Session; -}(); - -function _createTransactionExecutor(config) { - var maxRetryTimeMs = config && config.maxTransactionRetryTime ? config.maxTransactionRetryTime : null; - return new _transactionExecutor["default"](maxRetryTimeMs); -} - -var _default = Session; -exports["default"] = _default; -}); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isFunction$1(x) { - return typeof x === 'function'; -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var _enable_super_gross_mode_that_will_cause_bad_things = false; -var config = { - Promise: undefined, - set useDeprecatedSynchronousErrorHandling(value) { - if (value) { - var error = /*@__PURE__*/ new Error(); - /*@__PURE__*/ console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \n' + error.stack); - } - _enable_super_gross_mode_that_will_cause_bad_things = value; - }, - get useDeprecatedSynchronousErrorHandling() { - return _enable_super_gross_mode_that_will_cause_bad_things; - }, -}; - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function hostReportError(err) { - setTimeout(function () { throw err; }, 0); -} - -/** PURE_IMPORTS_START _config,_util_hostReportError PURE_IMPORTS_END */ -var empty = { - closed: true, - next: function (value) { }, - error: function (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - hostReportError(err); - } - }, - complete: function () { } -}; - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var isArray$1 = /*@__PURE__*/ (function () { return Array.isArray || (function (x) { return x && typeof x.length === 'number'; }); })(); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isObject$1(x) { - return x !== null && typeof x === 'object'; -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var UnsubscriptionErrorImpl = /*@__PURE__*/ (function () { - function UnsubscriptionErrorImpl(errors) { - Error.call(this); - this.message = errors ? - errors.length + " errors occurred during unsubscription:\n" + errors.map(function (err, i) { return i + 1 + ") " + err.toString(); }).join('\n ') : ''; - this.name = 'UnsubscriptionError'; - this.errors = errors; - return this; - } - UnsubscriptionErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return UnsubscriptionErrorImpl; -})(); -var UnsubscriptionError = UnsubscriptionErrorImpl; - -/** PURE_IMPORTS_START _util_isArray,_util_isObject,_util_isFunction,_util_UnsubscriptionError PURE_IMPORTS_END */ -var Subscription = /*@__PURE__*/ (function () { - function Subscription(unsubscribe) { - this.closed = false; - this._parentOrParents = null; - this._subscriptions = null; - if (unsubscribe) { - this._ctorUnsubscribe = true; - this._unsubscribe = unsubscribe; - } - } - Subscription.prototype.unsubscribe = function () { - var errors; - if (this.closed) { - return; - } - var _a = this, _parentOrParents = _a._parentOrParents, _ctorUnsubscribe = _a._ctorUnsubscribe, _unsubscribe = _a._unsubscribe, _subscriptions = _a._subscriptions; - this.closed = true; - this._parentOrParents = null; - this._subscriptions = null; - if (_parentOrParents instanceof Subscription) { - _parentOrParents.remove(this); - } - else if (_parentOrParents !== null) { - for (var index = 0; index < _parentOrParents.length; ++index) { - var parent_1 = _parentOrParents[index]; - parent_1.remove(this); - } - } - if (isFunction$1(_unsubscribe)) { - if (_ctorUnsubscribe) { - this._unsubscribe = undefined; - } - try { - _unsubscribe.call(this); - } - catch (e) { - errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e]; - } - } - if (isArray$1(_subscriptions)) { - var index = -1; - var len = _subscriptions.length; - while (++index < len) { - var sub = _subscriptions[index]; - if (isObject$1(sub)) { - try { - sub.unsubscribe(); - } - catch (e) { - errors = errors || []; - if (e instanceof UnsubscriptionError) { - errors = errors.concat(flattenUnsubscriptionErrors(e.errors)); - } - else { - errors.push(e); - } - } - } - } - } - if (errors) { - throw new UnsubscriptionError(errors); - } - }; - Subscription.prototype.add = function (teardown) { - var subscription = teardown; - if (!teardown) { - return Subscription.EMPTY; - } - switch (typeof teardown) { - case 'function': - subscription = new Subscription(teardown); - case 'object': - if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') { - return subscription; - } - else if (this.closed) { - subscription.unsubscribe(); - return subscription; - } - else if (!(subscription instanceof Subscription)) { - var tmp = subscription; - subscription = new Subscription(); - subscription._subscriptions = [tmp]; - } - break; - default: { - throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.'); - } - } - var _parentOrParents = subscription._parentOrParents; - if (_parentOrParents === null) { - subscription._parentOrParents = this; - } - else if (_parentOrParents instanceof Subscription) { - if (_parentOrParents === this) { - return subscription; - } - subscription._parentOrParents = [_parentOrParents, this]; - } - else if (_parentOrParents.indexOf(this) === -1) { - _parentOrParents.push(this); - } - else { - return subscription; - } - var subscriptions = this._subscriptions; - if (subscriptions === null) { - this._subscriptions = [subscription]; - } - else { - subscriptions.push(subscription); - } - return subscription; - }; - Subscription.prototype.remove = function (subscription) { - var subscriptions = this._subscriptions; - if (subscriptions) { - var subscriptionIndex = subscriptions.indexOf(subscription); - if (subscriptionIndex !== -1) { - subscriptions.splice(subscriptionIndex, 1); - } - } - }; - Subscription.EMPTY = (function (empty) { - empty.closed = true; - return empty; - }(new Subscription())); - return Subscription; -}()); -function flattenUnsubscriptionErrors(errors) { - return errors.reduce(function (errs, err) { return errs.concat((err instanceof UnsubscriptionError) ? err.errors : err); }, []); -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var rxSubscriber = /*@__PURE__*/ (function () { - return typeof Symbol === 'function' - ? /*@__PURE__*/ Symbol('rxSubscriber') - : '@@rxSubscriber_' + /*@__PURE__*/ Math.random(); -})(); - -/** PURE_IMPORTS_START tslib,_util_isFunction,_Observer,_Subscription,_internal_symbol_rxSubscriber,_config,_util_hostReportError PURE_IMPORTS_END */ -var Subscriber = /*@__PURE__*/ (function (_super) { - __extends(Subscriber, _super); - function Subscriber(destinationOrNext, error, complete) { - var _this = _super.call(this) || this; - _this.syncErrorValue = null; - _this.syncErrorThrown = false; - _this.syncErrorThrowable = false; - _this.isStopped = false; - switch (arguments.length) { - case 0: - _this.destination = empty; - break; - case 1: - if (!destinationOrNext) { - _this.destination = empty; - break; - } - if (typeof destinationOrNext === 'object') { - if (destinationOrNext instanceof Subscriber) { - _this.syncErrorThrowable = destinationOrNext.syncErrorThrowable; - _this.destination = destinationOrNext; - destinationOrNext.add(_this); - } - else { - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext); - } - break; - } - default: - _this.syncErrorThrowable = true; - _this.destination = new SafeSubscriber(_this, destinationOrNext, error, complete); - break; - } - return _this; - } - Subscriber.prototype[rxSubscriber] = function () { return this; }; - Subscriber.create = function (next, error, complete) { - var subscriber = new Subscriber(next, error, complete); - subscriber.syncErrorThrowable = false; - return subscriber; - }; - Subscriber.prototype.next = function (value) { - if (!this.isStopped) { - this._next(value); - } - }; - Subscriber.prototype.error = function (err) { - if (!this.isStopped) { - this.isStopped = true; - this._error(err); - } - }; - Subscriber.prototype.complete = function () { - if (!this.isStopped) { - this.isStopped = true; - this._complete(); - } - }; - Subscriber.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.isStopped = true; - _super.prototype.unsubscribe.call(this); - }; - Subscriber.prototype._next = function (value) { - this.destination.next(value); - }; - Subscriber.prototype._error = function (err) { - this.destination.error(err); - this.unsubscribe(); - }; - Subscriber.prototype._complete = function () { - this.destination.complete(); - this.unsubscribe(); - }; - Subscriber.prototype._unsubscribeAndRecycle = function () { - var _parentOrParents = this._parentOrParents; - this._parentOrParents = null; - this.unsubscribe(); - this.closed = false; - this.isStopped = false; - this._parentOrParents = _parentOrParents; - return this; - }; - return Subscriber; -}(Subscription)); -var SafeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SafeSubscriber, _super); - function SafeSubscriber(_parentSubscriber, observerOrNext, error, complete) { - var _this = _super.call(this) || this; - _this._parentSubscriber = _parentSubscriber; - var next; - var context = _this; - if (isFunction$1(observerOrNext)) { - next = observerOrNext; - } - else if (observerOrNext) { - next = observerOrNext.next; - error = observerOrNext.error; - complete = observerOrNext.complete; - if (observerOrNext !== empty) { - context = Object.create(observerOrNext); - if (isFunction$1(context.unsubscribe)) { - _this.add(context.unsubscribe.bind(context)); - } - context.unsubscribe = _this.unsubscribe.bind(_this); - } - } - _this._context = context; - _this._next = next; - _this._error = error; - _this._complete = complete; - return _this; - } - SafeSubscriber.prototype.next = function (value) { - if (!this.isStopped && this._next) { - var _parentSubscriber = this._parentSubscriber; - if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._next, value); - } - else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - var useDeprecatedSynchronousErrorHandling = config.useDeprecatedSynchronousErrorHandling; - if (this._error) { - if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(this._error, err); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, this._error, err); - this.unsubscribe(); - } - } - else if (!_parentSubscriber.syncErrorThrowable) { - this.unsubscribe(); - if (useDeprecatedSynchronousErrorHandling) { - throw err; - } - hostReportError(err); - } - else { - if (useDeprecatedSynchronousErrorHandling) { - _parentSubscriber.syncErrorValue = err; - _parentSubscriber.syncErrorThrown = true; - } - else { - hostReportError(err); - } - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.complete = function () { - var _this = this; - if (!this.isStopped) { - var _parentSubscriber = this._parentSubscriber; - if (this._complete) { - var wrappedComplete = function () { return _this._complete.call(_this._context); }; - if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) { - this.__tryOrUnsub(wrappedComplete); - this.unsubscribe(); - } - else { - this.__tryOrSetError(_parentSubscriber, wrappedComplete); - this.unsubscribe(); - } - } - else { - this.unsubscribe(); - } - } - }; - SafeSubscriber.prototype.__tryOrUnsub = function (fn, value) { - try { - fn.call(this._context, value); - } - catch (err) { - this.unsubscribe(); - if (config.useDeprecatedSynchronousErrorHandling) { - throw err; - } - else { - hostReportError(err); - } - } - }; - SafeSubscriber.prototype.__tryOrSetError = function (parent, fn, value) { - if (!config.useDeprecatedSynchronousErrorHandling) { - throw new Error('bad call'); - } - try { - fn.call(this._context, value); - } - catch (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - parent.syncErrorValue = err; - parent.syncErrorThrown = true; - return true; - } - else { - hostReportError(err); - return true; - } - } - return false; - }; - SafeSubscriber.prototype._unsubscribe = function () { - var _parentSubscriber = this._parentSubscriber; - this._context = null; - this._parentSubscriber = null; - _parentSubscriber.unsubscribe(); - }; - return SafeSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _Subscriber PURE_IMPORTS_END */ -function canReportError(observer) { - while (observer) { - var _a = observer, closed_1 = _a.closed, destination = _a.destination, isStopped = _a.isStopped; - if (closed_1 || isStopped) { - return false; - } - else if (destination && destination instanceof Subscriber) { - observer = destination; - } - else { - observer = null; - } - } - return true; -} - -/** PURE_IMPORTS_START _Subscriber,_symbol_rxSubscriber,_Observer PURE_IMPORTS_END */ -function toSubscriber(nextOrObserver, error, complete) { - if (nextOrObserver) { - if (nextOrObserver instanceof Subscriber) { - return nextOrObserver; - } - if (nextOrObserver[rxSubscriber]) { - return nextOrObserver[rxSubscriber](); - } - } - if (!nextOrObserver && !error && !complete) { - return new Subscriber(empty); - } - return new Subscriber(nextOrObserver, error, complete); -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var observable = /*@__PURE__*/ (function () { return typeof Symbol === 'function' && Symbol.observable || '@@observable'; })(); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function identity$1(x) { - return x; -} - -/** PURE_IMPORTS_START _identity PURE_IMPORTS_END */ -function pipe() { - var fns = []; - for (var _i = 0; _i < arguments.length; _i++) { - fns[_i] = arguments[_i]; - } - return pipeFromArray(fns); -} -function pipeFromArray(fns) { - if (fns.length === 0) { - return identity$1; - } - if (fns.length === 1) { - return fns[0]; - } - return function piped(input) { - return fns.reduce(function (prev, fn) { return fn(prev); }, input); - }; -} - -/** PURE_IMPORTS_START _util_canReportError,_util_toSubscriber,_symbol_observable,_util_pipe,_config PURE_IMPORTS_END */ -var Observable = /*@__PURE__*/ (function () { - function Observable(subscribe) { - this._isScalar = false; - if (subscribe) { - this._subscribe = subscribe; - } - } - Observable.prototype.lift = function (operator) { - var observable = new Observable(); - observable.source = this; - observable.operator = operator; - return observable; - }; - Observable.prototype.subscribe = function (observerOrNext, error, complete) { - var operator = this.operator; - var sink = toSubscriber(observerOrNext, error, complete); - if (operator) { - sink.add(operator.call(sink, this.source)); - } - else { - sink.add(this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ? - this._subscribe(sink) : - this._trySubscribe(sink)); - } - if (config.useDeprecatedSynchronousErrorHandling) { - if (sink.syncErrorThrowable) { - sink.syncErrorThrowable = false; - if (sink.syncErrorThrown) { - throw sink.syncErrorValue; - } - } - } - return sink; - }; - Observable.prototype._trySubscribe = function (sink) { - try { - return this._subscribe(sink); - } - catch (err) { - if (config.useDeprecatedSynchronousErrorHandling) { - sink.syncErrorThrown = true; - sink.syncErrorValue = err; - } - if (canReportError(sink)) { - sink.error(err); - } - else { - console.warn(err); - } - } - }; - Observable.prototype.forEach = function (next, promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var subscription; - subscription = _this.subscribe(function (value) { - try { - next(value); - } - catch (err) { - reject(err); - if (subscription) { - subscription.unsubscribe(); - } - } - }, reject, resolve); - }); - }; - Observable.prototype._subscribe = function (subscriber) { - var source = this.source; - return source && source.subscribe(subscriber); - }; - Observable.prototype[observable] = function () { - return this; - }; - Observable.prototype.pipe = function () { - var operations = []; - for (var _i = 0; _i < arguments.length; _i++) { - operations[_i] = arguments[_i]; - } - if (operations.length === 0) { - return this; - } - return pipeFromArray(operations)(this); - }; - Observable.prototype.toPromise = function (promiseCtor) { - var _this = this; - promiseCtor = getPromiseCtor(promiseCtor); - return new promiseCtor(function (resolve, reject) { - var value; - _this.subscribe(function (x) { return value = x; }, function (err) { return reject(err); }, function () { return resolve(value); }); - }); - }; - Observable.create = function (subscribe) { - return new Observable(subscribe); - }; - return Observable; -}()); -function getPromiseCtor(promiseCtor) { - if (!promiseCtor) { - promiseCtor = config.Promise || Promise; - } - if (!promiseCtor) { - throw new Error('no Promise impl found'); - } - return promiseCtor; -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var ObjectUnsubscribedErrorImpl = /*@__PURE__*/ (function () { - function ObjectUnsubscribedErrorImpl() { - Error.call(this); - this.message = 'object unsubscribed'; - this.name = 'ObjectUnsubscribedError'; - return this; - } - ObjectUnsubscribedErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return ObjectUnsubscribedErrorImpl; -})(); -var ObjectUnsubscribedError = ObjectUnsubscribedErrorImpl; - -/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ -var SubjectSubscription = /*@__PURE__*/ (function (_super) { - __extends(SubjectSubscription, _super); - function SubjectSubscription(subject, subscriber) { - var _this = _super.call(this) || this; - _this.subject = subject; - _this.subscriber = subscriber; - _this.closed = false; - return _this; - } - SubjectSubscription.prototype.unsubscribe = function () { - if (this.closed) { - return; - } - this.closed = true; - var subject = this.subject; - var observers = subject.observers; - this.subject = null; - if (!observers || observers.length === 0 || subject.isStopped || subject.closed) { - return; - } - var subscriberIndex = observers.indexOf(this.subscriber); - if (subscriberIndex !== -1) { - observers.splice(subscriberIndex, 1); - } - }; - return SubjectSubscription; -}(Subscription)); - -/** PURE_IMPORTS_START tslib,_Observable,_Subscriber,_Subscription,_util_ObjectUnsubscribedError,_SubjectSubscription,_internal_symbol_rxSubscriber PURE_IMPORTS_END */ -var SubjectSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SubjectSubscriber, _super); - function SubjectSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - return _this; - } - return SubjectSubscriber; -}(Subscriber)); -var Subject = /*@__PURE__*/ (function (_super) { - __extends(Subject, _super); - function Subject() { - var _this = _super.call(this) || this; - _this.observers = []; - _this.closed = false; - _this.isStopped = false; - _this.hasError = false; - _this.thrownError = null; - return _this; - } - Subject.prototype[rxSubscriber] = function () { - return new SubjectSubscriber(this); - }; - Subject.prototype.lift = function (operator) { - var subject = new AnonymousSubject(this, this); - subject.operator = operator; - return subject; - }; - Subject.prototype.next = function (value) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - if (!this.isStopped) { - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].next(value); - } - } - }; - Subject.prototype.error = function (err) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - this.hasError = true; - this.thrownError = err; - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].error(err); - } - this.observers.length = 0; - }; - Subject.prototype.complete = function () { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - this.isStopped = true; - var observers = this.observers; - var len = observers.length; - var copy = observers.slice(); - for (var i = 0; i < len; i++) { - copy[i].complete(); - } - this.observers.length = 0; - }; - Subject.prototype.unsubscribe = function () { - this.isStopped = true; - this.closed = true; - this.observers = null; - }; - Subject.prototype._trySubscribe = function (subscriber) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else { - return _super.prototype._trySubscribe.call(this, subscriber); - } - }; - Subject.prototype._subscribe = function (subscriber) { - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else if (this.hasError) { - subscriber.error(this.thrownError); - return Subscription.EMPTY; - } - else if (this.isStopped) { - subscriber.complete(); - return Subscription.EMPTY; - } - else { - this.observers.push(subscriber); - return new SubjectSubscription(this, subscriber); - } - }; - Subject.prototype.asObservable = function () { - var observable = new Observable(); - observable.source = this; - return observable; - }; - Subject.create = function (destination, source) { - return new AnonymousSubject(destination, source); - }; - return Subject; -}(Observable)); -var AnonymousSubject = /*@__PURE__*/ (function (_super) { - __extends(AnonymousSubject, _super); - function AnonymousSubject(destination, source) { - var _this = _super.call(this) || this; - _this.destination = destination; - _this.source = source; - return _this; - } - AnonymousSubject.prototype.next = function (value) { - var destination = this.destination; - if (destination && destination.next) { - destination.next(value); - } - }; - AnonymousSubject.prototype.error = function (err) { - var destination = this.destination; - if (destination && destination.error) { - this.destination.error(err); - } - }; - AnonymousSubject.prototype.complete = function () { - var destination = this.destination; - if (destination && destination.complete) { - this.destination.complete(); - } - }; - AnonymousSubject.prototype._subscribe = function (subscriber) { - var source = this.source; - if (source) { - return this.source.subscribe(subscriber); - } - else { - return Subscription.EMPTY; - } - }; - return AnonymousSubject; -}(Subject)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function refCount() { - return function refCountOperatorFunction(source) { - return source.lift(new RefCountOperator(source)); - }; -} -var RefCountOperator = /*@__PURE__*/ (function () { - function RefCountOperator(connectable) { - this.connectable = connectable; - } - RefCountOperator.prototype.call = function (subscriber, source) { - var connectable = this.connectable; - connectable._refCount++; - var refCounter = new RefCountSubscriber(subscriber, connectable); - var subscription = source.subscribe(refCounter); - if (!refCounter.closed) { - refCounter.connection = connectable.connect(); - } - return subscription; - }; - return RefCountOperator; -}()); -var RefCountSubscriber = /*@__PURE__*/ (function (_super) { - __extends(RefCountSubscriber, _super); - function RefCountSubscriber(destination, connectable) { - var _this = _super.call(this, destination) || this; - _this.connectable = connectable; - return _this; - } - RefCountSubscriber.prototype._unsubscribe = function () { - var connectable = this.connectable; - if (!connectable) { - this.connection = null; - return; - } - this.connectable = null; - var refCount = connectable._refCount; - if (refCount <= 0) { - this.connection = null; - return; - } - connectable._refCount = refCount - 1; - if (refCount > 1) { - this.connection = null; - return; - } - var connection = this.connection; - var sharedConnection = connectable._connection; - this.connection = null; - if (sharedConnection && (!connection || sharedConnection === connection)) { - sharedConnection.unsubscribe(); - } - }; - return RefCountSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subject,_Observable,_Subscriber,_Subscription,_operators_refCount PURE_IMPORTS_END */ -var ConnectableObservable = /*@__PURE__*/ (function (_super) { - __extends(ConnectableObservable, _super); - function ConnectableObservable(source, subjectFactory) { - var _this = _super.call(this) || this; - _this.source = source; - _this.subjectFactory = subjectFactory; - _this._refCount = 0; - _this._isComplete = false; - return _this; - } - ConnectableObservable.prototype._subscribe = function (subscriber) { - return this.getSubject().subscribe(subscriber); - }; - ConnectableObservable.prototype.getSubject = function () { - var subject = this._subject; - if (!subject || subject.isStopped) { - this._subject = this.subjectFactory(); - } - return this._subject; - }; - ConnectableObservable.prototype.connect = function () { - var connection = this._connection; - if (!connection) { - this._isComplete = false; - connection = this._connection = new Subscription(); - connection.add(this.source - .subscribe(new ConnectableSubscriber(this.getSubject(), this))); - if (connection.closed) { - this._connection = null; - connection = Subscription.EMPTY; - } - } - return connection; - }; - ConnectableObservable.prototype.refCount = function () { - return refCount()(this); - }; - return ConnectableObservable; -}(Observable)); -var connectableObservableDescriptor = /*@__PURE__*/ (function () { - var connectableProto = ConnectableObservable.prototype; - return { - operator: { value: null }, - _refCount: { value: 0, writable: true }, - _subject: { value: null, writable: true }, - _connection: { value: null, writable: true }, - _subscribe: { value: connectableProto._subscribe }, - _isComplete: { value: connectableProto._isComplete, writable: true }, - getSubject: { value: connectableProto.getSubject }, - connect: { value: connectableProto.connect }, - refCount: { value: connectableProto.refCount } - }; -})(); -var ConnectableSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ConnectableSubscriber, _super); - function ConnectableSubscriber(destination, connectable) { - var _this = _super.call(this, destination) || this; - _this.connectable = connectable; - return _this; - } - ConnectableSubscriber.prototype._error = function (err) { - this._unsubscribe(); - _super.prototype._error.call(this, err); - }; - ConnectableSubscriber.prototype._complete = function () { - this.connectable._isComplete = true; - this._unsubscribe(); - _super.prototype._complete.call(this); - }; - ConnectableSubscriber.prototype._unsubscribe = function () { - var connectable = this.connectable; - if (connectable) { - this.connectable = null; - var connection = connectable._connection; - connectable._refCount = 0; - connectable._subject = null; - connectable._connection = null; - if (connection) { - connection.unsubscribe(); - } - } - }; - return ConnectableSubscriber; -}(SubjectSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber,_Subscription,_Observable,_Subject PURE_IMPORTS_END */ -function groupBy(keySelector, elementSelector, durationSelector, subjectSelector) { - return function (source) { - return source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector)); - }; -} -var GroupByOperator = /*@__PURE__*/ (function () { - function GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector) { - this.keySelector = keySelector; - this.elementSelector = elementSelector; - this.durationSelector = durationSelector; - this.subjectSelector = subjectSelector; - } - GroupByOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new GroupBySubscriber(subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector)); - }; - return GroupByOperator; -}()); -var GroupBySubscriber = /*@__PURE__*/ (function (_super) { - __extends(GroupBySubscriber, _super); - function GroupBySubscriber(destination, keySelector, elementSelector, durationSelector, subjectSelector) { - var _this = _super.call(this, destination) || this; - _this.keySelector = keySelector; - _this.elementSelector = elementSelector; - _this.durationSelector = durationSelector; - _this.subjectSelector = subjectSelector; - _this.groups = null; - _this.attemptedToUnsubscribe = false; - _this.count = 0; - return _this; - } - GroupBySubscriber.prototype._next = function (value) { - var key; - try { - key = this.keySelector(value); - } - catch (err) { - this.error(err); - return; - } - this._group(value, key); - }; - GroupBySubscriber.prototype._group = function (value, key) { - var groups = this.groups; - if (!groups) { - groups = this.groups = new Map(); - } - var group = groups.get(key); - var element; - if (this.elementSelector) { - try { - element = this.elementSelector(value); - } - catch (err) { - this.error(err); - } - } - else { - element = value; - } - if (!group) { - group = (this.subjectSelector ? this.subjectSelector() : new Subject()); - groups.set(key, group); - var groupedObservable = new GroupedObservable(key, group, this); - this.destination.next(groupedObservable); - if (this.durationSelector) { - var duration = void 0; - try { - duration = this.durationSelector(new GroupedObservable(key, group)); - } - catch (err) { - this.error(err); - return; - } - this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this))); - } - } - if (!group.closed) { - group.next(element); - } - }; - GroupBySubscriber.prototype._error = function (err) { - var groups = this.groups; - if (groups) { - groups.forEach(function (group, key) { - group.error(err); - }); - groups.clear(); - } - this.destination.error(err); - }; - GroupBySubscriber.prototype._complete = function () { - var groups = this.groups; - if (groups) { - groups.forEach(function (group, key) { - group.complete(); - }); - groups.clear(); - } - this.destination.complete(); - }; - GroupBySubscriber.prototype.removeGroup = function (key) { - this.groups.delete(key); - }; - GroupBySubscriber.prototype.unsubscribe = function () { - if (!this.closed) { - this.attemptedToUnsubscribe = true; - if (this.count === 0) { - _super.prototype.unsubscribe.call(this); - } - } - }; - return GroupBySubscriber; -}(Subscriber)); -var GroupDurationSubscriber = /*@__PURE__*/ (function (_super) { - __extends(GroupDurationSubscriber, _super); - function GroupDurationSubscriber(key, group, parent) { - var _this = _super.call(this, group) || this; - _this.key = key; - _this.group = group; - _this.parent = parent; - return _this; - } - GroupDurationSubscriber.prototype._next = function (value) { - this.complete(); - }; - GroupDurationSubscriber.prototype._unsubscribe = function () { - var _a = this, parent = _a.parent, key = _a.key; - this.key = this.parent = null; - if (parent) { - parent.removeGroup(key); - } - }; - return GroupDurationSubscriber; -}(Subscriber)); -var GroupedObservable = /*@__PURE__*/ (function (_super) { - __extends(GroupedObservable, _super); - function GroupedObservable(key, groupSubject, refCountSubscription) { - var _this = _super.call(this) || this; - _this.key = key; - _this.groupSubject = groupSubject; - _this.refCountSubscription = refCountSubscription; - return _this; - } - GroupedObservable.prototype._subscribe = function (subscriber) { - var subscription = new Subscription(); - var _a = this, refCountSubscription = _a.refCountSubscription, groupSubject = _a.groupSubject; - if (refCountSubscription && !refCountSubscription.closed) { - subscription.add(new InnerRefCountSubscription(refCountSubscription)); - } - subscription.add(groupSubject.subscribe(subscriber)); - return subscription; - }; - return GroupedObservable; -}(Observable)); -var InnerRefCountSubscription = /*@__PURE__*/ (function (_super) { - __extends(InnerRefCountSubscription, _super); - function InnerRefCountSubscription(parent) { - var _this = _super.call(this) || this; - _this.parent = parent; - parent.count++; - return _this; - } - InnerRefCountSubscription.prototype.unsubscribe = function () { - var parent = this.parent; - if (!parent.closed && !this.closed) { - _super.prototype.unsubscribe.call(this); - parent.count -= 1; - if (parent.count === 0 && parent.attemptedToUnsubscribe) { - parent.unsubscribe(); - } - } - }; - return InnerRefCountSubscription; -}(Subscription)); - -/** PURE_IMPORTS_START tslib,_Subject,_util_ObjectUnsubscribedError PURE_IMPORTS_END */ -var BehaviorSubject = /*@__PURE__*/ (function (_super) { - __extends(BehaviorSubject, _super); - function BehaviorSubject(_value) { - var _this = _super.call(this) || this; - _this._value = _value; - return _this; - } - Object.defineProperty(BehaviorSubject.prototype, "value", { - get: function () { - return this.getValue(); - }, - enumerable: true, - configurable: true - }); - BehaviorSubject.prototype._subscribe = function (subscriber) { - var subscription = _super.prototype._subscribe.call(this, subscriber); - if (subscription && !subscription.closed) { - subscriber.next(this._value); - } - return subscription; - }; - BehaviorSubject.prototype.getValue = function () { - if (this.hasError) { - throw this.thrownError; - } - else if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else { - return this._value; - } - }; - BehaviorSubject.prototype.next = function (value) { - _super.prototype.next.call(this, this._value = value); - }; - return BehaviorSubject; -}(Subject)); - -/** PURE_IMPORTS_START tslib,_Subscription PURE_IMPORTS_END */ -var Action = /*@__PURE__*/ (function (_super) { - __extends(Action, _super); - function Action(scheduler, work) { - return _super.call(this) || this; - } - Action.prototype.schedule = function (state, delay) { - return this; - }; - return Action; -}(Subscription)); - -/** PURE_IMPORTS_START tslib,_Action PURE_IMPORTS_END */ -var AsyncAction = /*@__PURE__*/ (function (_super) { - __extends(AsyncAction, _super); - function AsyncAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - _this.pending = false; - return _this; - } - AsyncAction.prototype.schedule = function (state, delay) { - if (delay === void 0) { - delay = 0; - } - if (this.closed) { - return this; - } - this.state = state; - var id = this.id; - var scheduler = this.scheduler; - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, delay); - } - this.pending = true; - this.delay = delay; - this.id = this.id || this.requestAsyncId(scheduler, this.id, delay); - return this; - }; - AsyncAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - return setInterval(scheduler.flush.bind(scheduler, this), delay); - }; - AsyncAction.prototype.recycleAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if (delay !== null && this.delay === delay && this.pending === false) { - return id; - } - clearInterval(id); - return undefined; - }; - AsyncAction.prototype.execute = function (state, delay) { - if (this.closed) { - return new Error('executing a cancelled action'); - } - this.pending = false; - var error = this._execute(state, delay); - if (error) { - return error; - } - else if (this.pending === false && this.id != null) { - this.id = this.recycleAsyncId(this.scheduler, this.id, null); - } - }; - AsyncAction.prototype._execute = function (state, delay) { - var errored = false; - var errorValue = undefined; - try { - this.work(state); - } - catch (e) { - errored = true; - errorValue = !!e && e || new Error(e); - } - if (errored) { - this.unsubscribe(); - return errorValue; - } - }; - AsyncAction.prototype._unsubscribe = function () { - var id = this.id; - var scheduler = this.scheduler; - var actions = scheduler.actions; - var index = actions.indexOf(this); - this.work = null; - this.state = null; - this.pending = false; - this.scheduler = null; - if (index !== -1) { - actions.splice(index, 1); - } - if (id != null) { - this.id = this.recycleAsyncId(scheduler, id, null); - } - this.delay = null; - }; - return AsyncAction; -}(Action)); - -/** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */ -var QueueAction = /*@__PURE__*/ (function (_super) { - __extends(QueueAction, _super); - function QueueAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - return _this; - } - QueueAction.prototype.schedule = function (state, delay) { - if (delay === void 0) { - delay = 0; - } - if (delay > 0) { - return _super.prototype.schedule.call(this, state, delay); - } - this.delay = delay; - this.state = state; - this.scheduler.flush(this); - return this; - }; - QueueAction.prototype.execute = function (state, delay) { - return (delay > 0 || this.closed) ? - _super.prototype.execute.call(this, state, delay) : - this._execute(state, delay); - }; - QueueAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { - return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); - } - return scheduler.flush(this); - }; - return QueueAction; -}(AsyncAction)); - -var Scheduler = /*@__PURE__*/ (function () { - function Scheduler(SchedulerAction, now) { - if (now === void 0) { - now = Scheduler.now; - } - this.SchedulerAction = SchedulerAction; - this.now = now; - } - Scheduler.prototype.schedule = function (work, delay, state) { - if (delay === void 0) { - delay = 0; - } - return new this.SchedulerAction(this, work).schedule(state, delay); - }; - Scheduler.now = function () { return Date.now(); }; - return Scheduler; -}()); - -/** PURE_IMPORTS_START tslib,_Scheduler PURE_IMPORTS_END */ -var AsyncScheduler = /*@__PURE__*/ (function (_super) { - __extends(AsyncScheduler, _super); - function AsyncScheduler(SchedulerAction, now) { - if (now === void 0) { - now = Scheduler.now; - } - var _this = _super.call(this, SchedulerAction, function () { - if (AsyncScheduler.delegate && AsyncScheduler.delegate !== _this) { - return AsyncScheduler.delegate.now(); - } - else { - return now(); - } - }) || this; - _this.actions = []; - _this.active = false; - _this.scheduled = undefined; - return _this; - } - AsyncScheduler.prototype.schedule = function (work, delay, state) { - if (delay === void 0) { - delay = 0; - } - if (AsyncScheduler.delegate && AsyncScheduler.delegate !== this) { - return AsyncScheduler.delegate.schedule(work, delay, state); - } - else { - return _super.prototype.schedule.call(this, work, delay, state); - } - }; - AsyncScheduler.prototype.flush = function (action) { - var actions = this.actions; - if (this.active) { - actions.push(action); - return; - } - var error; - this.active = true; - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while (action = actions.shift()); - this.active = false; - if (error) { - while (action = actions.shift()) { - action.unsubscribe(); - } - throw error; - } - }; - return AsyncScheduler; -}(Scheduler)); - -/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ -var QueueScheduler = /*@__PURE__*/ (function (_super) { - __extends(QueueScheduler, _super); - function QueueScheduler() { - return _super !== null && _super.apply(this, arguments) || this; - } - return QueueScheduler; -}(AsyncScheduler)); - -/** PURE_IMPORTS_START _QueueAction,_QueueScheduler PURE_IMPORTS_END */ -var queueScheduler = /*@__PURE__*/ new QueueScheduler(QueueAction); -var queue = queueScheduler; - -/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ -var EMPTY = /*@__PURE__*/ new Observable(function (subscriber) { return subscriber.complete(); }); -function empty$1(scheduler) { - return scheduler ? emptyScheduled(scheduler) : EMPTY; -} -function emptyScheduled(scheduler) { - return new Observable(function (subscriber) { return scheduler.schedule(function () { return subscriber.complete(); }); }); -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isScheduler(value) { - return value && typeof value.schedule === 'function'; -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var subscribeToArray = function (array) { - return function (subscriber) { - for (var i = 0, len = array.length; i < len && !subscriber.closed; i++) { - subscriber.next(array[i]); - } - subscriber.complete(); - }; -}; - -/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ -function scheduleArray(input, scheduler) { - return new Observable(function (subscriber) { - var sub = new Subscription(); - var i = 0; - sub.add(scheduler.schedule(function () { - if (i === input.length) { - subscriber.complete(); - return; - } - subscriber.next(input[i++]); - if (!subscriber.closed) { - sub.add(this.schedule()); - } - })); - return sub; - }); -} - -/** PURE_IMPORTS_START _Observable,_util_subscribeToArray,_scheduled_scheduleArray PURE_IMPORTS_END */ -function fromArray(input, scheduler) { - if (!scheduler) { - return new Observable(subscribeToArray(input)); - } - else { - return scheduleArray(input, scheduler); - } -} - -/** PURE_IMPORTS_START _util_isScheduler,_fromArray,_scheduled_scheduleArray PURE_IMPORTS_END */ -function of() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var scheduler = args[args.length - 1]; - if (isScheduler(scheduler)) { - args.pop(); - return scheduleArray(args, scheduler); - } - else { - return fromArray(args); - } -} - -/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ -function throwError(error, scheduler) { - if (!scheduler) { - return new Observable(function (subscriber) { return subscriber.error(error); }); - } - else { - return new Observable(function (subscriber) { return scheduler.schedule(dispatch, 0, { error: error, subscriber: subscriber }); }); - } -} -function dispatch(_a) { - var error = _a.error, subscriber = _a.subscriber; - subscriber.error(error); -} - -/** PURE_IMPORTS_START _observable_empty,_observable_of,_observable_throwError PURE_IMPORTS_END */ -var NotificationKind; -/*@__PURE__*/ (function (NotificationKind) { - NotificationKind["NEXT"] = "N"; - NotificationKind["ERROR"] = "E"; - NotificationKind["COMPLETE"] = "C"; -})(NotificationKind || (NotificationKind = {})); -var Notification = /*@__PURE__*/ (function () { - function Notification(kind, value, error) { - this.kind = kind; - this.value = value; - this.error = error; - this.hasValue = kind === 'N'; - } - Notification.prototype.observe = function (observer) { - switch (this.kind) { - case 'N': - return observer.next && observer.next(this.value); - case 'E': - return observer.error && observer.error(this.error); - case 'C': - return observer.complete && observer.complete(); - } - }; - Notification.prototype.do = function (next, error, complete) { - var kind = this.kind; - switch (kind) { - case 'N': - return next && next(this.value); - case 'E': - return error && error(this.error); - case 'C': - return complete && complete(); - } - }; - Notification.prototype.accept = function (nextOrObserver, error, complete) { - if (nextOrObserver && typeof nextOrObserver.next === 'function') { - return this.observe(nextOrObserver); - } - else { - return this.do(nextOrObserver, error, complete); - } - }; - Notification.prototype.toObservable = function () { - var kind = this.kind; - switch (kind) { - case 'N': - return of(this.value); - case 'E': - return throwError(this.error); - case 'C': - return empty$1(); - } - throw new Error('unexpected notification kind value'); - }; - Notification.createNext = function (value) { - if (typeof value !== 'undefined') { - return new Notification('N', value); - } - return Notification.undefinedValueNotification; - }; - Notification.createError = function (err) { - return new Notification('E', undefined, err); - }; - Notification.createComplete = function () { - return Notification.completeNotification; - }; - Notification.completeNotification = new Notification('C'); - Notification.undefinedValueNotification = new Notification('N', undefined); - return Notification; -}()); - -/** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */ -function observeOn(scheduler, delay) { - if (delay === void 0) { - delay = 0; - } - return function observeOnOperatorFunction(source) { - return source.lift(new ObserveOnOperator(scheduler, delay)); - }; -} -var ObserveOnOperator = /*@__PURE__*/ (function () { - function ObserveOnOperator(scheduler, delay) { - if (delay === void 0) { - delay = 0; - } - this.scheduler = scheduler; - this.delay = delay; - } - ObserveOnOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ObserveOnSubscriber(subscriber, this.scheduler, this.delay)); - }; - return ObserveOnOperator; -}()); -var ObserveOnSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ObserveOnSubscriber, _super); - function ObserveOnSubscriber(destination, scheduler, delay) { - if (delay === void 0) { - delay = 0; - } - var _this = _super.call(this, destination) || this; - _this.scheduler = scheduler; - _this.delay = delay; - return _this; - } - ObserveOnSubscriber.dispatch = function (arg) { - var notification = arg.notification, destination = arg.destination; - notification.observe(destination); - this.unsubscribe(); - }; - ObserveOnSubscriber.prototype.scheduleMessage = function (notification) { - var destination = this.destination; - destination.add(this.scheduler.schedule(ObserveOnSubscriber.dispatch, this.delay, new ObserveOnMessage(notification, this.destination))); - }; - ObserveOnSubscriber.prototype._next = function (value) { - this.scheduleMessage(Notification.createNext(value)); - }; - ObserveOnSubscriber.prototype._error = function (err) { - this.scheduleMessage(Notification.createError(err)); - this.unsubscribe(); - }; - ObserveOnSubscriber.prototype._complete = function () { - this.scheduleMessage(Notification.createComplete()); - this.unsubscribe(); - }; - return ObserveOnSubscriber; -}(Subscriber)); -var ObserveOnMessage = /*@__PURE__*/ (function () { - function ObserveOnMessage(notification, destination) { - this.notification = notification; - this.destination = destination; - } - return ObserveOnMessage; -}()); - -/** PURE_IMPORTS_START tslib,_Subject,_scheduler_queue,_Subscription,_operators_observeOn,_util_ObjectUnsubscribedError,_SubjectSubscription PURE_IMPORTS_END */ -var ReplaySubject = /*@__PURE__*/ (function (_super) { - __extends(ReplaySubject, _super); - function ReplaySubject(bufferSize, windowTime, scheduler) { - if (bufferSize === void 0) { - bufferSize = Number.POSITIVE_INFINITY; - } - if (windowTime === void 0) { - windowTime = Number.POSITIVE_INFINITY; - } - var _this = _super.call(this) || this; - _this.scheduler = scheduler; - _this._events = []; - _this._infiniteTimeWindow = false; - _this._bufferSize = bufferSize < 1 ? 1 : bufferSize; - _this._windowTime = windowTime < 1 ? 1 : windowTime; - if (windowTime === Number.POSITIVE_INFINITY) { - _this._infiniteTimeWindow = true; - _this.next = _this.nextInfiniteTimeWindow; - } - else { - _this.next = _this.nextTimeWindow; - } - return _this; - } - ReplaySubject.prototype.nextInfiniteTimeWindow = function (value) { - if (!this.isStopped) { - var _events = this._events; - _events.push(value); - if (_events.length > this._bufferSize) { - _events.shift(); - } - } - _super.prototype.next.call(this, value); - }; - ReplaySubject.prototype.nextTimeWindow = function (value) { - if (!this.isStopped) { - this._events.push(new ReplayEvent(this._getNow(), value)); - this._trimBufferThenGetEvents(); - } - _super.prototype.next.call(this, value); - }; - ReplaySubject.prototype._subscribe = function (subscriber) { - var _infiniteTimeWindow = this._infiniteTimeWindow; - var _events = _infiniteTimeWindow ? this._events : this._trimBufferThenGetEvents(); - var scheduler = this.scheduler; - var len = _events.length; - var subscription; - if (this.closed) { - throw new ObjectUnsubscribedError(); - } - else if (this.isStopped || this.hasError) { - subscription = Subscription.EMPTY; - } - else { - this.observers.push(subscriber); - subscription = new SubjectSubscription(this, subscriber); - } - if (scheduler) { - subscriber.add(subscriber = new ObserveOnSubscriber(subscriber, scheduler)); - } - if (_infiniteTimeWindow) { - for (var i = 0; i < len && !subscriber.closed; i++) { - subscriber.next(_events[i]); - } - } - else { - for (var i = 0; i < len && !subscriber.closed; i++) { - subscriber.next(_events[i].value); - } - } - if (this.hasError) { - subscriber.error(this.thrownError); - } - else if (this.isStopped) { - subscriber.complete(); - } - return subscription; - }; - ReplaySubject.prototype._getNow = function () { - return (this.scheduler || queue).now(); - }; - ReplaySubject.prototype._trimBufferThenGetEvents = function () { - var now = this._getNow(); - var _bufferSize = this._bufferSize; - var _windowTime = this._windowTime; - var _events = this._events; - var eventsCount = _events.length; - var spliceCount = 0; - while (spliceCount < eventsCount) { - if ((now - _events[spliceCount].time) < _windowTime) { - break; - } - spliceCount++; - } - if (eventsCount > _bufferSize) { - spliceCount = Math.max(spliceCount, eventsCount - _bufferSize); - } - if (spliceCount > 0) { - _events.splice(0, spliceCount); - } - return _events; - }; - return ReplaySubject; -}(Subject)); -var ReplayEvent = /*@__PURE__*/ (function () { - function ReplayEvent(time, value) { - this.time = time; - this.value = value; - } - return ReplayEvent; -}()); - -/** PURE_IMPORTS_START tslib,_Subject,_Subscription PURE_IMPORTS_END */ -var AsyncSubject = /*@__PURE__*/ (function (_super) { - __extends(AsyncSubject, _super); - function AsyncSubject() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.value = null; - _this.hasNext = false; - _this.hasCompleted = false; - return _this; - } - AsyncSubject.prototype._subscribe = function (subscriber) { - if (this.hasError) { - subscriber.error(this.thrownError); - return Subscription.EMPTY; - } - else if (this.hasCompleted && this.hasNext) { - subscriber.next(this.value); - subscriber.complete(); - return Subscription.EMPTY; - } - return _super.prototype._subscribe.call(this, subscriber); - }; - AsyncSubject.prototype.next = function (value) { - if (!this.hasCompleted) { - this.value = value; - this.hasNext = true; - } - }; - AsyncSubject.prototype.error = function (error) { - if (!this.hasCompleted) { - _super.prototype.error.call(this, error); - } - }; - AsyncSubject.prototype.complete = function () { - this.hasCompleted = true; - if (this.hasNext) { - _super.prototype.next.call(this, this.value); - } - _super.prototype.complete.call(this); - }; - return AsyncSubject; -}(Subject)); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var nextHandle = 1; -var RESOLVED = /*@__PURE__*/ (function () { return /*@__PURE__*/ Promise.resolve(); })(); -var activeHandles = {}; -function findAndClearHandle(handle) { - if (handle in activeHandles) { - delete activeHandles[handle]; - return true; - } - return false; -} -var Immediate = { - setImmediate: function (cb) { - var handle = nextHandle++; - activeHandles[handle] = true; - RESOLVED.then(function () { return findAndClearHandle(handle) && cb(); }); - return handle; - }, - clearImmediate: function (handle) { - findAndClearHandle(handle); - }, -}; - -/** PURE_IMPORTS_START tslib,_util_Immediate,_AsyncAction PURE_IMPORTS_END */ -var AsapAction = /*@__PURE__*/ (function (_super) { - __extends(AsapAction, _super); - function AsapAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - return _this; - } - AsapAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if (delay !== null && delay > 0) { - return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); - } - scheduler.actions.push(this); - return scheduler.scheduled || (scheduler.scheduled = Immediate.setImmediate(scheduler.flush.bind(scheduler, null))); - }; - AsapAction.prototype.recycleAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { - return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay); - } - if (scheduler.actions.length === 0) { - Immediate.clearImmediate(id); - scheduler.scheduled = undefined; - } - return undefined; - }; - return AsapAction; -}(AsyncAction)); - -/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ -var AsapScheduler = /*@__PURE__*/ (function (_super) { - __extends(AsapScheduler, _super); - function AsapScheduler() { - return _super !== null && _super.apply(this, arguments) || this; - } - AsapScheduler.prototype.flush = function (action) { - this.active = true; - this.scheduled = undefined; - var actions = this.actions; - var error; - var index = -1; - var count = actions.length; - action = action || actions.shift(); - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while (++index < count && (action = actions.shift())); - this.active = false; - if (error) { - while (++index < count && (action = actions.shift())) { - action.unsubscribe(); - } - throw error; - } - }; - return AsapScheduler; -}(AsyncScheduler)); - -/** PURE_IMPORTS_START _AsapAction,_AsapScheduler PURE_IMPORTS_END */ -var asapScheduler = /*@__PURE__*/ new AsapScheduler(AsapAction); -var asap = asapScheduler; - -/** PURE_IMPORTS_START _AsyncAction,_AsyncScheduler PURE_IMPORTS_END */ -var asyncScheduler = /*@__PURE__*/ new AsyncScheduler(AsyncAction); -var async = asyncScheduler; - -/** PURE_IMPORTS_START tslib,_AsyncAction PURE_IMPORTS_END */ -var AnimationFrameAction = /*@__PURE__*/ (function (_super) { - __extends(AnimationFrameAction, _super); - function AnimationFrameAction(scheduler, work) { - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - return _this; - } - AnimationFrameAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if (delay !== null && delay > 0) { - return _super.prototype.requestAsyncId.call(this, scheduler, id, delay); - } - scheduler.actions.push(this); - return scheduler.scheduled || (scheduler.scheduled = requestAnimationFrame(function () { return scheduler.flush(null); })); - }; - AnimationFrameAction.prototype.recycleAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - if ((delay !== null && delay > 0) || (delay === null && this.delay > 0)) { - return _super.prototype.recycleAsyncId.call(this, scheduler, id, delay); - } - if (scheduler.actions.length === 0) { - cancelAnimationFrame(id); - scheduler.scheduled = undefined; - } - return undefined; - }; - return AnimationFrameAction; -}(AsyncAction)); - -/** PURE_IMPORTS_START tslib,_AsyncScheduler PURE_IMPORTS_END */ -var AnimationFrameScheduler = /*@__PURE__*/ (function (_super) { - __extends(AnimationFrameScheduler, _super); - function AnimationFrameScheduler() { - return _super !== null && _super.apply(this, arguments) || this; - } - AnimationFrameScheduler.prototype.flush = function (action) { - this.active = true; - this.scheduled = undefined; - var actions = this.actions; - var error; - var index = -1; - var count = actions.length; - action = action || actions.shift(); - do { - if (error = action.execute(action.state, action.delay)) { - break; - } - } while (++index < count && (action = actions.shift())); - this.active = false; - if (error) { - while (++index < count && (action = actions.shift())) { - action.unsubscribe(); - } - throw error; - } - }; - return AnimationFrameScheduler; -}(AsyncScheduler)); - -/** PURE_IMPORTS_START _AnimationFrameAction,_AnimationFrameScheduler PURE_IMPORTS_END */ -var animationFrameScheduler = /*@__PURE__*/ new AnimationFrameScheduler(AnimationFrameAction); -var animationFrame = animationFrameScheduler; - -/** PURE_IMPORTS_START tslib,_AsyncAction,_AsyncScheduler PURE_IMPORTS_END */ -var VirtualTimeScheduler = /*@__PURE__*/ (function (_super) { - __extends(VirtualTimeScheduler, _super); - function VirtualTimeScheduler(SchedulerAction, maxFrames) { - if (SchedulerAction === void 0) { - SchedulerAction = VirtualAction; - } - if (maxFrames === void 0) { - maxFrames = Number.POSITIVE_INFINITY; - } - var _this = _super.call(this, SchedulerAction, function () { return _this.frame; }) || this; - _this.maxFrames = maxFrames; - _this.frame = 0; - _this.index = -1; - return _this; - } - VirtualTimeScheduler.prototype.flush = function () { - var _a = this, actions = _a.actions, maxFrames = _a.maxFrames; - var error, action; - while ((action = actions[0]) && action.delay <= maxFrames) { - actions.shift(); - this.frame = action.delay; - if (error = action.execute(action.state, action.delay)) { - break; - } - } - if (error) { - while (action = actions.shift()) { - action.unsubscribe(); - } - throw error; - } - }; - VirtualTimeScheduler.frameTimeFactor = 10; - return VirtualTimeScheduler; -}(AsyncScheduler)); -var VirtualAction = /*@__PURE__*/ (function (_super) { - __extends(VirtualAction, _super); - function VirtualAction(scheduler, work, index) { - if (index === void 0) { - index = scheduler.index += 1; - } - var _this = _super.call(this, scheduler, work) || this; - _this.scheduler = scheduler; - _this.work = work; - _this.index = index; - _this.active = true; - _this.index = scheduler.index = index; - return _this; - } - VirtualAction.prototype.schedule = function (state, delay) { - if (delay === void 0) { - delay = 0; - } - if (!this.id) { - return _super.prototype.schedule.call(this, state, delay); - } - this.active = false; - var action = new VirtualAction(this.scheduler, this.work); - this.add(action); - return action.schedule(state, delay); - }; - VirtualAction.prototype.requestAsyncId = function (scheduler, id, delay) { - if (delay === void 0) { - delay = 0; - } - this.delay = scheduler.frame + delay; - var actions = scheduler.actions; - actions.push(this); - actions.sort(VirtualAction.sortActions); - return true; - }; - VirtualAction.prototype.recycleAsyncId = function (scheduler, id, delay) { - return undefined; - }; - VirtualAction.prototype._execute = function (state, delay) { - if (this.active === true) { - return _super.prototype._execute.call(this, state, delay); - } - }; - VirtualAction.sortActions = function (a, b) { - if (a.delay === b.delay) { - if (a.index === b.index) { - return 0; - } - else if (a.index > b.index) { - return 1; - } - else { - return -1; - } - } - else if (a.delay > b.delay) { - return 1; - } - else { - return -1; - } - }; - return VirtualAction; -}(AsyncAction)); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function noop() { } - -/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ -function isObservable(obj) { - return !!obj && (obj instanceof Observable || (typeof obj.lift === 'function' && typeof obj.subscribe === 'function')); -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var ArgumentOutOfRangeErrorImpl = /*@__PURE__*/ (function () { - function ArgumentOutOfRangeErrorImpl() { - Error.call(this); - this.message = 'argument out of range'; - this.name = 'ArgumentOutOfRangeError'; - return this; - } - ArgumentOutOfRangeErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return ArgumentOutOfRangeErrorImpl; -})(); -var ArgumentOutOfRangeError = ArgumentOutOfRangeErrorImpl; - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var EmptyErrorImpl = /*@__PURE__*/ (function () { - function EmptyErrorImpl() { - Error.call(this); - this.message = 'no elements in sequence'; - this.name = 'EmptyError'; - return this; - } - EmptyErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return EmptyErrorImpl; -})(); -var EmptyError = EmptyErrorImpl; - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var TimeoutErrorImpl = /*@__PURE__*/ (function () { - function TimeoutErrorImpl() { - Error.call(this); - this.message = 'Timeout has occurred'; - this.name = 'TimeoutError'; - return this; - } - TimeoutErrorImpl.prototype = /*@__PURE__*/ Object.create(Error.prototype); - return TimeoutErrorImpl; -})(); -var TimeoutError = TimeoutErrorImpl; - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function map$1(project, thisArg) { - return function mapOperation(source) { - if (typeof project !== 'function') { - throw new TypeError('argument is not a function. Are you looking for `mapTo()`?'); - } - return source.lift(new MapOperator(project, thisArg)); - }; -} -var MapOperator = /*@__PURE__*/ (function () { - function MapOperator(project, thisArg) { - this.project = project; - this.thisArg = thisArg; - } - MapOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg)); - }; - return MapOperator; -}()); -var MapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(MapSubscriber, _super); - function MapSubscriber(destination, project, thisArg) { - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.count = 0; - _this.thisArg = thisArg || _this; - return _this; - } - MapSubscriber.prototype._next = function (value) { - var result; - try { - result = this.project.call(this.thisArg, value, this.count++); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - return MapSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _Observable,_AsyncSubject,_operators_map,_util_canReportError,_util_isArray,_util_isScheduler PURE_IMPORTS_END */ -function bindCallback(callbackFunc, resultSelector, scheduler) { - if (resultSelector) { - if (isScheduler(resultSelector)) { - scheduler = resultSelector; - } - else { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return bindCallback(callbackFunc, scheduler).apply(void 0, args).pipe(map$1(function (args) { return isArray$1(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); - }; - } - } - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var context = this; - var subject; - var params = { - context: context, - subject: subject, - callbackFunc: callbackFunc, - scheduler: scheduler, - }; - return new Observable(function (subscriber) { - if (!scheduler) { - if (!subject) { - subject = new AsyncSubject(); - var handler = function () { - var innerArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - innerArgs[_i] = arguments[_i]; - } - subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs); - subject.complete(); - }; - try { - callbackFunc.apply(context, args.concat([handler])); - } - catch (err) { - if (canReportError(subject)) { - subject.error(err); - } - else { - console.warn(err); - } - } - } - return subject.subscribe(subscriber); - } - else { - var state = { - args: args, subscriber: subscriber, params: params, - }; - return scheduler.schedule(dispatch$1, 0, state); - } - }); - }; -} -function dispatch$1(state) { - var _this = this; - var args = state.args, subscriber = state.subscriber, params = state.params; - var callbackFunc = params.callbackFunc, context = params.context, scheduler = params.scheduler; - var subject = params.subject; - if (!subject) { - subject = params.subject = new AsyncSubject(); - var handler = function () { - var innerArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - innerArgs[_i] = arguments[_i]; - } - var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs; - _this.add(scheduler.schedule(dispatchNext, 0, { value: value, subject: subject })); - }; - try { - callbackFunc.apply(context, args.concat([handler])); - } - catch (err) { - subject.error(err); - } - } - this.add(subject.subscribe(subscriber)); -} -function dispatchNext(state) { - var value = state.value, subject = state.subject; - subject.next(value); - subject.complete(); -} - -/** PURE_IMPORTS_START _Observable,_AsyncSubject,_operators_map,_util_canReportError,_util_isScheduler,_util_isArray PURE_IMPORTS_END */ -function bindNodeCallback(callbackFunc, resultSelector, scheduler) { - if (resultSelector) { - if (isScheduler(resultSelector)) { - scheduler = resultSelector; - } - else { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return bindNodeCallback(callbackFunc, scheduler).apply(void 0, args).pipe(map$1(function (args) { return isArray$1(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); - }; - } - } - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var params = { - subject: undefined, - args: args, - callbackFunc: callbackFunc, - scheduler: scheduler, - context: this, - }; - return new Observable(function (subscriber) { - var context = params.context; - var subject = params.subject; - if (!scheduler) { - if (!subject) { - subject = params.subject = new AsyncSubject(); - var handler = function () { - var innerArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - innerArgs[_i] = arguments[_i]; - } - var err = innerArgs.shift(); - if (err) { - subject.error(err); - return; - } - subject.next(innerArgs.length <= 1 ? innerArgs[0] : innerArgs); - subject.complete(); - }; - try { - callbackFunc.apply(context, args.concat([handler])); - } - catch (err) { - if (canReportError(subject)) { - subject.error(err); - } - else { - console.warn(err); - } - } - } - return subject.subscribe(subscriber); - } - else { - return scheduler.schedule(dispatch$2, 0, { params: params, subscriber: subscriber, context: context }); - } - }); - }; -} -function dispatch$2(state) { - var _this = this; - var params = state.params, subscriber = state.subscriber, context = state.context; - var callbackFunc = params.callbackFunc, args = params.args, scheduler = params.scheduler; - var subject = params.subject; - if (!subject) { - subject = params.subject = new AsyncSubject(); - var handler = function () { - var innerArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - innerArgs[_i] = arguments[_i]; - } - var err = innerArgs.shift(); - if (err) { - _this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject })); - } - else { - var value = innerArgs.length <= 1 ? innerArgs[0] : innerArgs; - _this.add(scheduler.schedule(dispatchNext$1, 0, { value: value, subject: subject })); - } - }; - try { - callbackFunc.apply(context, args.concat([handler])); - } - catch (err) { - this.add(scheduler.schedule(dispatchError, 0, { err: err, subject: subject })); - } - } - this.add(subject.subscribe(subscriber)); -} -function dispatchNext$1(arg) { - var value = arg.value, subject = arg.subject; - subject.next(value); - subject.complete(); -} -function dispatchError(arg) { - var err = arg.err, subject = arg.subject; - subject.error(err); -} - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -var OuterSubscriber = /*@__PURE__*/ (function (_super) { - __extends(OuterSubscriber, _super); - function OuterSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; - } - OuterSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - this.destination.next(innerValue); - }; - OuterSubscriber.prototype.notifyError = function (error, innerSub) { - this.destination.error(error); - }; - OuterSubscriber.prototype.notifyComplete = function (innerSub) { - this.destination.complete(); - }; - return OuterSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -var InnerSubscriber = /*@__PURE__*/ (function (_super) { - __extends(InnerSubscriber, _super); - function InnerSubscriber(parent, outerValue, outerIndex) { - var _this = _super.call(this) || this; - _this.parent = parent; - _this.outerValue = outerValue; - _this.outerIndex = outerIndex; - _this.index = 0; - return _this; - } - InnerSubscriber.prototype._next = function (value) { - this.parent.notifyNext(this.outerValue, value, this.outerIndex, this.index++, this); - }; - InnerSubscriber.prototype._error = function (error) { - this.parent.notifyError(error, this); - this.unsubscribe(); - }; - InnerSubscriber.prototype._complete = function () { - this.parent.notifyComplete(this); - this.unsubscribe(); - }; - return InnerSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _hostReportError PURE_IMPORTS_END */ -var subscribeToPromise = function (promise) { - return function (subscriber) { - promise.then(function (value) { - if (!subscriber.closed) { - subscriber.next(value); - subscriber.complete(); - } - }, function (err) { return subscriber.error(err); }) - .then(null, hostReportError); - return subscriber; - }; -}; - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function getSymbolIterator() { - if (typeof Symbol !== 'function' || !Symbol.iterator) { - return '@@iterator'; - } - return Symbol.iterator; -} -var iterator = /*@__PURE__*/ getSymbolIterator(); - -/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ -var subscribeToIterable = function (iterable) { - return function (subscriber) { - var iterator$1 = iterable[iterator](); - do { - var item = void 0; - try { - item = iterator$1.next(); - } - catch (err) { - subscriber.error(err); - return subscriber; - } - if (item.done) { - subscriber.complete(); - break; - } - subscriber.next(item.value); - if (subscriber.closed) { - break; - } - } while (true); - if (typeof iterator$1.return === 'function') { - subscriber.add(function () { - if (iterator$1.return) { - iterator$1.return(); - } - }); - } - return subscriber; - }; -}; - -/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ -var subscribeToObservable = function (obj) { - return function (subscriber) { - var obs = obj[observable](); - if (typeof obs.subscribe !== 'function') { - throw new TypeError('Provided object does not correctly implement Symbol.observable'); - } - else { - return obs.subscribe(subscriber); - } - }; -}; - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -var isArrayLike$1 = (function (x) { return x && typeof x.length === 'number' && typeof x !== 'function'; }); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isPromise(value) { - return !!value && typeof value.subscribe !== 'function' && typeof value.then === 'function'; -} - -/** PURE_IMPORTS_START _subscribeToArray,_subscribeToPromise,_subscribeToIterable,_subscribeToObservable,_isArrayLike,_isPromise,_isObject,_symbol_iterator,_symbol_observable PURE_IMPORTS_END */ -var subscribeTo = function (result) { - if (!!result && typeof result[observable] === 'function') { - return subscribeToObservable(result); - } - else if (isArrayLike$1(result)) { - return subscribeToArray(result); - } - else if (isPromise(result)) { - return subscribeToPromise(result); - } - else if (!!result && typeof result[iterator] === 'function') { - return subscribeToIterable(result); - } - else { - var value = isObject$1(result) ? 'an invalid object' : "'" + result + "'"; - var msg = "You provided " + value + " where a stream was expected." - + ' You can provide an Observable, Promise, Array, or Iterable.'; - throw new TypeError(msg); - } -}; - -/** PURE_IMPORTS_START _InnerSubscriber,_subscribeTo,_Observable PURE_IMPORTS_END */ -function subscribeToResult(outerSubscriber, result, outerValue, outerIndex, innerSubscriber) { - if (innerSubscriber === void 0) { - innerSubscriber = new InnerSubscriber(outerSubscriber, outerValue, outerIndex); - } - if (innerSubscriber.closed) { - return undefined; - } - if (result instanceof Observable) { - return result.subscribe(innerSubscriber); - } - return subscribeTo(result)(innerSubscriber); -} - -/** PURE_IMPORTS_START tslib,_util_isScheduler,_util_isArray,_OuterSubscriber,_util_subscribeToResult,_fromArray PURE_IMPORTS_END */ -var NONE = {}; -function combineLatest() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - var resultSelector = undefined; - var scheduler = undefined; - if (isScheduler(observables[observables.length - 1])) { - scheduler = observables.pop(); - } - if (typeof observables[observables.length - 1] === 'function') { - resultSelector = observables.pop(); - } - if (observables.length === 1 && isArray$1(observables[0])) { - observables = observables[0]; - } - return fromArray(observables, scheduler).lift(new CombineLatestOperator(resultSelector)); -} -var CombineLatestOperator = /*@__PURE__*/ (function () { - function CombineLatestOperator(resultSelector) { - this.resultSelector = resultSelector; - } - CombineLatestOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new CombineLatestSubscriber(subscriber, this.resultSelector)); - }; - return CombineLatestOperator; -}()); -var CombineLatestSubscriber = /*@__PURE__*/ (function (_super) { - __extends(CombineLatestSubscriber, _super); - function CombineLatestSubscriber(destination, resultSelector) { - var _this = _super.call(this, destination) || this; - _this.resultSelector = resultSelector; - _this.active = 0; - _this.values = []; - _this.observables = []; - return _this; - } - CombineLatestSubscriber.prototype._next = function (observable) { - this.values.push(NONE); - this.observables.push(observable); - }; - CombineLatestSubscriber.prototype._complete = function () { - var observables = this.observables; - var len = observables.length; - if (len === 0) { - this.destination.complete(); - } - else { - this.active = len; - this.toRespond = len; - for (var i = 0; i < len; i++) { - var observable = observables[i]; - this.add(subscribeToResult(this, observable, undefined, i)); - } - } - }; - CombineLatestSubscriber.prototype.notifyComplete = function (unused) { - if ((this.active -= 1) === 0) { - this.destination.complete(); - } - }; - CombineLatestSubscriber.prototype.notifyNext = function (_outerValue, innerValue, outerIndex) { - var values = this.values; - var oldVal = values[outerIndex]; - var toRespond = !this.toRespond - ? 0 - : oldVal === NONE ? --this.toRespond : this.toRespond; - values[outerIndex] = innerValue; - if (toRespond === 0) { - if (this.resultSelector) { - this._tryResultSelector(values); - } - else { - this.destination.next(values.slice()); - } - } - }; - CombineLatestSubscriber.prototype._tryResultSelector = function (values) { - var result; - try { - result = this.resultSelector.apply(this, values); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - return CombineLatestSubscriber; -}(OuterSubscriber)); - -/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_observable PURE_IMPORTS_END */ -function scheduleObservable(input, scheduler) { - return new Observable(function (subscriber) { - var sub = new Subscription(); - sub.add(scheduler.schedule(function () { - var observable$1 = input[observable](); - sub.add(observable$1.subscribe({ - next: function (value) { sub.add(scheduler.schedule(function () { return subscriber.next(value); })); }, - error: function (err) { sub.add(scheduler.schedule(function () { return subscriber.error(err); })); }, - complete: function () { sub.add(scheduler.schedule(function () { return subscriber.complete(); })); }, - })); - })); - return sub; - }); -} - -/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ -function schedulePromise(input, scheduler) { - return new Observable(function (subscriber) { - var sub = new Subscription(); - sub.add(scheduler.schedule(function () { - return input.then(function (value) { - sub.add(scheduler.schedule(function () { - subscriber.next(value); - sub.add(scheduler.schedule(function () { return subscriber.complete(); })); - })); - }, function (err) { - sub.add(scheduler.schedule(function () { return subscriber.error(err); })); - }); - })); - return sub; - }); -} - -/** PURE_IMPORTS_START _Observable,_Subscription,_symbol_iterator PURE_IMPORTS_END */ -function scheduleIterable(input, scheduler) { - if (!input) { - throw new Error('Iterable cannot be null'); - } - return new Observable(function (subscriber) { - var sub = new Subscription(); - var iterator$1; - sub.add(function () { - if (iterator$1 && typeof iterator$1.return === 'function') { - iterator$1.return(); - } - }); - sub.add(scheduler.schedule(function () { - iterator$1 = input[iterator](); - sub.add(scheduler.schedule(function () { - if (subscriber.closed) { - return; - } - var value; - var done; - try { - var result = iterator$1.next(); - value = result.value; - done = result.done; - } - catch (err) { - subscriber.error(err); - return; - } - if (done) { - subscriber.complete(); - } - else { - subscriber.next(value); - this.schedule(); - } - })); - })); - return sub; - }); -} - -/** PURE_IMPORTS_START _symbol_observable PURE_IMPORTS_END */ -function isInteropObservable(input) { - return input && typeof input[observable] === 'function'; -} - -/** PURE_IMPORTS_START _symbol_iterator PURE_IMPORTS_END */ -function isIterable(input) { - return input && typeof input[iterator] === 'function'; -} - -/** PURE_IMPORTS_START _scheduleObservable,_schedulePromise,_scheduleArray,_scheduleIterable,_util_isInteropObservable,_util_isPromise,_util_isArrayLike,_util_isIterable PURE_IMPORTS_END */ -function scheduled(input, scheduler) { - if (input != null) { - if (isInteropObservable(input)) { - return scheduleObservable(input, scheduler); - } - else if (isPromise(input)) { - return schedulePromise(input, scheduler); - } - else if (isArrayLike$1(input)) { - return scheduleArray(input, scheduler); - } - else if (isIterable(input) || typeof input === 'string') { - return scheduleIterable(input, scheduler); - } - } - throw new TypeError((input !== null && typeof input || input) + ' is not observable'); -} - -/** PURE_IMPORTS_START _Observable,_util_subscribeTo,_scheduled_scheduled PURE_IMPORTS_END */ -function from(input, scheduler) { - if (!scheduler) { - if (input instanceof Observable) { - return input; - } - return new Observable(subscribeTo(input)); - } - else { - return scheduled(input, scheduler); - } -} - -/** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_util_subscribeTo PURE_IMPORTS_END */ -var SimpleInnerSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SimpleInnerSubscriber, _super); - function SimpleInnerSubscriber(parent) { - var _this = _super.call(this) || this; - _this.parent = parent; - return _this; - } - SimpleInnerSubscriber.prototype._next = function (value) { - this.parent.notifyNext(value); - }; - SimpleInnerSubscriber.prototype._error = function (error) { - this.parent.notifyError(error); - this.unsubscribe(); - }; - SimpleInnerSubscriber.prototype._complete = function () { - this.parent.notifyComplete(); - this.unsubscribe(); - }; - return SimpleInnerSubscriber; -}(Subscriber)); -var SimpleOuterSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SimpleOuterSubscriber, _super); - function SimpleOuterSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; - } - SimpleOuterSubscriber.prototype.notifyNext = function (innerValue) { - this.destination.next(innerValue); - }; - SimpleOuterSubscriber.prototype.notifyError = function (err) { - this.destination.error(err); - }; - SimpleOuterSubscriber.prototype.notifyComplete = function () { - this.destination.complete(); - }; - return SimpleOuterSubscriber; -}(Subscriber)); -function innerSubscribe(result, innerSubscriber) { - if (innerSubscriber.closed) { - return undefined; - } - if (result instanceof Observable) { - return result.subscribe(innerSubscriber); - } - var subscription; - try { - subscription = subscribeTo(result)(innerSubscriber); - } - catch (error) { - innerSubscriber.error(error); - } - return subscription; -} - -/** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */ -function mergeMap(project, resultSelector, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - if (typeof resultSelector === 'function') { - return function (source) { return source.pipe(mergeMap(function (a, i) { return from(project(a, i)).pipe(map$1(function (b, ii) { return resultSelector(a, b, i, ii); })); }, concurrent)); }; - } - else if (typeof resultSelector === 'number') { - concurrent = resultSelector; - } - return function (source) { return source.lift(new MergeMapOperator(project, concurrent)); }; -} -var MergeMapOperator = /*@__PURE__*/ (function () { - function MergeMapOperator(project, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - this.project = project; - this.concurrent = concurrent; - } - MergeMapOperator.prototype.call = function (observer, source) { - return source.subscribe(new MergeMapSubscriber(observer, this.project, this.concurrent)); - }; - return MergeMapOperator; -}()); -var MergeMapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(MergeMapSubscriber, _super); - function MergeMapSubscriber(destination, project, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.concurrent = concurrent; - _this.hasCompleted = false; - _this.buffer = []; - _this.active = 0; - _this.index = 0; - return _this; - } - MergeMapSubscriber.prototype._next = function (value) { - if (this.active < this.concurrent) { - this._tryNext(value); - } - else { - this.buffer.push(value); - } - }; - MergeMapSubscriber.prototype._tryNext = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (err) { - this.destination.error(err); - return; - } - this.active++; - this._innerSub(result); - }; - MergeMapSubscriber.prototype._innerSub = function (ish) { - var innerSubscriber = new SimpleInnerSubscriber(this); - var destination = this.destination; - destination.add(innerSubscriber); - var innerSubscription = innerSubscribe(ish, innerSubscriber); - if (innerSubscription !== innerSubscriber) { - destination.add(innerSubscription); - } - }; - MergeMapSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.active === 0 && this.buffer.length === 0) { - this.destination.complete(); - } - this.unsubscribe(); - }; - MergeMapSubscriber.prototype.notifyNext = function (innerValue) { - this.destination.next(innerValue); - }; - MergeMapSubscriber.prototype.notifyComplete = function () { - var buffer = this.buffer; - this.active--; - if (buffer.length > 0) { - this._next(buffer.shift()); - } - else if (this.active === 0 && this.hasCompleted) { - this.destination.complete(); - } - }; - return MergeMapSubscriber; -}(SimpleOuterSubscriber)); -var flatMap$1 = mergeMap; - -/** PURE_IMPORTS_START _mergeMap,_util_identity PURE_IMPORTS_END */ -function mergeAll(concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - return mergeMap(identity$1, concurrent); -} - -/** PURE_IMPORTS_START _mergeAll PURE_IMPORTS_END */ -function concatAll() { - return mergeAll(1); -} - -/** PURE_IMPORTS_START _of,_operators_concatAll PURE_IMPORTS_END */ -function concat$1() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - return concatAll()(of.apply(void 0, observables)); -} - -/** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */ -function defer(observableFactory) { - return new Observable(function (subscriber) { - var input; - try { - input = observableFactory(); - } - catch (err) { - subscriber.error(err); - return undefined; - } - var source = input ? from(input) : empty$1(); - return source.subscribe(subscriber); - }); -} - -/** PURE_IMPORTS_START _Observable,_util_isArray,_operators_map,_util_isObject,_from PURE_IMPORTS_END */ -function forkJoin() { - var sources = []; - for (var _i = 0; _i < arguments.length; _i++) { - sources[_i] = arguments[_i]; - } - if (sources.length === 1) { - var first_1 = sources[0]; - if (isArray$1(first_1)) { - return forkJoinInternal(first_1, null); - } - if (isObject$1(first_1) && Object.getPrototypeOf(first_1) === Object.prototype) { - var keys = Object.keys(first_1); - return forkJoinInternal(keys.map(function (key) { return first_1[key]; }), keys); - } - } - if (typeof sources[sources.length - 1] === 'function') { - var resultSelector_1 = sources.pop(); - sources = (sources.length === 1 && isArray$1(sources[0])) ? sources[0] : sources; - return forkJoinInternal(sources, null).pipe(map$1(function (args) { return resultSelector_1.apply(void 0, args); })); - } - return forkJoinInternal(sources, null); -} -function forkJoinInternal(sources, keys) { - return new Observable(function (subscriber) { - var len = sources.length; - if (len === 0) { - subscriber.complete(); - return; - } - var values = new Array(len); - var completed = 0; - var emitted = 0; - var _loop_1 = function (i) { - var source = from(sources[i]); - var hasValue = false; - subscriber.add(source.subscribe({ - next: function (value) { - if (!hasValue) { - hasValue = true; - emitted++; - } - values[i] = value; - }, - error: function (err) { return subscriber.error(err); }, - complete: function () { - completed++; - if (completed === len || !hasValue) { - if (emitted === len) { - subscriber.next(keys ? - keys.reduce(function (result, key, i) { return (result[key] = values[i], result); }, {}) : - values); - } - subscriber.complete(); - } - } - })); - }; - for (var i = 0; i < len; i++) { - _loop_1(i); - } - }); -} - -/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */ -function fromEvent(target, eventName, options, resultSelector) { - if (isFunction$1(options)) { - resultSelector = options; - options = undefined; - } - if (resultSelector) { - return fromEvent(target, eventName, options).pipe(map$1(function (args) { return isArray$1(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); - } - return new Observable(function (subscriber) { - function handler(e) { - if (arguments.length > 1) { - subscriber.next(Array.prototype.slice.call(arguments)); - } - else { - subscriber.next(e); - } - } - setupSubscription(target, eventName, handler, subscriber, options); - }); -} -function setupSubscription(sourceObj, eventName, handler, subscriber, options) { - var unsubscribe; - if (isEventTarget(sourceObj)) { - var source_1 = sourceObj; - sourceObj.addEventListener(eventName, handler, options); - unsubscribe = function () { return source_1.removeEventListener(eventName, handler, options); }; - } - else if (isJQueryStyleEventEmitter(sourceObj)) { - var source_2 = sourceObj; - sourceObj.on(eventName, handler); - unsubscribe = function () { return source_2.off(eventName, handler); }; - } - else if (isNodeStyleEventEmitter(sourceObj)) { - var source_3 = sourceObj; - sourceObj.addListener(eventName, handler); - unsubscribe = function () { return source_3.removeListener(eventName, handler); }; - } - else if (sourceObj && sourceObj.length) { - for (var i = 0, len = sourceObj.length; i < len; i++) { - setupSubscription(sourceObj[i], eventName, handler, subscriber, options); - } - } - else { - throw new TypeError('Invalid event target'); - } - subscriber.add(unsubscribe); -} -function isNodeStyleEventEmitter(sourceObj) { - return sourceObj && typeof sourceObj.addListener === 'function' && typeof sourceObj.removeListener === 'function'; -} -function isJQueryStyleEventEmitter(sourceObj) { - return sourceObj && typeof sourceObj.on === 'function' && typeof sourceObj.off === 'function'; -} -function isEventTarget(sourceObj) { - return sourceObj && typeof sourceObj.addEventListener === 'function' && typeof sourceObj.removeEventListener === 'function'; -} - -/** PURE_IMPORTS_START _Observable,_util_isArray,_util_isFunction,_operators_map PURE_IMPORTS_END */ -function fromEventPattern(addHandler, removeHandler, resultSelector) { - if (resultSelector) { - return fromEventPattern(addHandler, removeHandler).pipe(map$1(function (args) { return isArray$1(args) ? resultSelector.apply(void 0, args) : resultSelector(args); })); - } - return new Observable(function (subscriber) { - var handler = function () { - var e = []; - for (var _i = 0; _i < arguments.length; _i++) { - e[_i] = arguments[_i]; - } - return subscriber.next(e.length === 1 ? e[0] : e); - }; - var retValue; - try { - retValue = addHandler(handler); - } - catch (err) { - subscriber.error(err); - return undefined; - } - if (!isFunction$1(removeHandler)) { - return undefined; - } - return function () { return removeHandler(handler, retValue); }; - }); -} - -/** PURE_IMPORTS_START _Observable,_util_identity,_util_isScheduler PURE_IMPORTS_END */ -function generate(initialStateOrOptions, condition, iterate, resultSelectorOrObservable, scheduler) { - var resultSelector; - var initialState; - if (arguments.length == 1) { - var options = initialStateOrOptions; - initialState = options.initialState; - condition = options.condition; - iterate = options.iterate; - resultSelector = options.resultSelector || identity$1; - scheduler = options.scheduler; - } - else if (resultSelectorOrObservable === undefined || isScheduler(resultSelectorOrObservable)) { - initialState = initialStateOrOptions; - resultSelector = identity$1; - scheduler = resultSelectorOrObservable; - } - else { - initialState = initialStateOrOptions; - resultSelector = resultSelectorOrObservable; - } - return new Observable(function (subscriber) { - var state = initialState; - if (scheduler) { - return scheduler.schedule(dispatch$3, 0, { - subscriber: subscriber, - iterate: iterate, - condition: condition, - resultSelector: resultSelector, - state: state - }); - } - do { - if (condition) { - var conditionResult = void 0; - try { - conditionResult = condition(state); - } - catch (err) { - subscriber.error(err); - return undefined; - } - if (!conditionResult) { - subscriber.complete(); - break; - } - } - var value = void 0; - try { - value = resultSelector(state); - } - catch (err) { - subscriber.error(err); - return undefined; - } - subscriber.next(value); - if (subscriber.closed) { - break; - } - try { - state = iterate(state); - } - catch (err) { - subscriber.error(err); - return undefined; - } - } while (true); - return undefined; - }); -} -function dispatch$3(state) { - var subscriber = state.subscriber, condition = state.condition; - if (subscriber.closed) { - return undefined; - } - if (state.needIterate) { - try { - state.state = state.iterate(state.state); - } - catch (err) { - subscriber.error(err); - return undefined; - } - } - else { - state.needIterate = true; - } - if (condition) { - var conditionResult = void 0; - try { - conditionResult = condition(state.state); - } - catch (err) { - subscriber.error(err); - return undefined; - } - if (!conditionResult) { - subscriber.complete(); - return undefined; - } - if (subscriber.closed) { - return undefined; - } - } - var value; - try { - value = state.resultSelector(state.state); - } - catch (err) { - subscriber.error(err); - return undefined; - } - if (subscriber.closed) { - return undefined; - } - subscriber.next(value); - if (subscriber.closed) { - return undefined; - } - return this.schedule(state); -} - -/** PURE_IMPORTS_START _defer,_empty PURE_IMPORTS_END */ -function iif(condition, trueResult, falseResult) { - if (trueResult === void 0) { - trueResult = EMPTY; - } - if (falseResult === void 0) { - falseResult = EMPTY; - } - return defer(function () { return condition() ? trueResult : falseResult; }); -} - -/** PURE_IMPORTS_START _isArray PURE_IMPORTS_END */ -function isNumeric(val) { - return !isArray$1(val) && (val - parseFloat(val) + 1) >= 0; -} - -/** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric PURE_IMPORTS_END */ -function interval(period, scheduler) { - if (period === void 0) { - period = 0; - } - if (scheduler === void 0) { - scheduler = async; - } - if (!isNumeric(period) || period < 0) { - period = 0; - } - if (!scheduler || typeof scheduler.schedule !== 'function') { - scheduler = async; - } - return new Observable(function (subscriber) { - subscriber.add(scheduler.schedule(dispatch$4, period, { subscriber: subscriber, counter: 0, period: period })); - return subscriber; - }); -} -function dispatch$4(state) { - var subscriber = state.subscriber, counter = state.counter, period = state.period; - subscriber.next(counter); - this.schedule({ subscriber: subscriber, counter: counter + 1, period: period }, period); -} - -/** PURE_IMPORTS_START _Observable,_util_isScheduler,_operators_mergeAll,_fromArray PURE_IMPORTS_END */ -function merge() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - var concurrent = Number.POSITIVE_INFINITY; - var scheduler = null; - var last = observables[observables.length - 1]; - if (isScheduler(last)) { - scheduler = observables.pop(); - if (observables.length > 1 && typeof observables[observables.length - 1] === 'number') { - concurrent = observables.pop(); - } - } - else if (typeof last === 'number') { - concurrent = observables.pop(); - } - if (scheduler === null && observables.length === 1 && observables[0] instanceof Observable) { - return observables[0]; - } - return mergeAll(concurrent)(fromArray(observables, scheduler)); -} - -/** PURE_IMPORTS_START _Observable,_util_noop PURE_IMPORTS_END */ -var NEVER = /*@__PURE__*/ new Observable(noop); -function never() { - return NEVER; -} - -/** PURE_IMPORTS_START _Observable,_from,_util_isArray,_empty PURE_IMPORTS_END */ -function onErrorResumeNext() { - var sources = []; - for (var _i = 0; _i < arguments.length; _i++) { - sources[_i] = arguments[_i]; - } - if (sources.length === 0) { - return EMPTY; - } - var first = sources[0], remainder = sources.slice(1); - if (sources.length === 1 && isArray$1(first)) { - return onErrorResumeNext.apply(void 0, first); - } - return new Observable(function (subscriber) { - var subNext = function () { return subscriber.add(onErrorResumeNext.apply(void 0, remainder).subscribe(subscriber)); }; - return from(first).subscribe({ - next: function (value) { subscriber.next(value); }, - error: subNext, - complete: subNext, - }); - }); -} - -/** PURE_IMPORTS_START _Observable,_Subscription PURE_IMPORTS_END */ -function pairs(obj, scheduler) { - if (!scheduler) { - return new Observable(function (subscriber) { - var keys = Object.keys(obj); - for (var i = 0; i < keys.length && !subscriber.closed; i++) { - var key = keys[i]; - if (obj.hasOwnProperty(key)) { - subscriber.next([key, obj[key]]); - } - } - subscriber.complete(); - }); - } - else { - return new Observable(function (subscriber) { - var keys = Object.keys(obj); - var subscription = new Subscription(); - subscription.add(scheduler.schedule(dispatch$5, 0, { keys: keys, index: 0, subscriber: subscriber, subscription: subscription, obj: obj })); - return subscription; - }); - } -} -function dispatch$5(state) { - var keys = state.keys, index = state.index, subscriber = state.subscriber, subscription = state.subscription, obj = state.obj; - if (!subscriber.closed) { - if (index < keys.length) { - var key = keys[index]; - subscriber.next([key, obj[key]]); - subscription.add(this.schedule({ keys: keys, index: index + 1, subscriber: subscriber, subscription: subscription, obj: obj })); - } - else { - subscriber.complete(); - } - } -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function not(pred, thisArg) { - function notPred() { - return !(notPred.pred.apply(notPred.thisArg, arguments)); - } - notPred.pred = pred; - notPred.thisArg = thisArg; - return notPred; -} - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function filter(predicate, thisArg) { - return function filterOperatorFunction(source) { - return source.lift(new FilterOperator(predicate, thisArg)); - }; -} -var FilterOperator = /*@__PURE__*/ (function () { - function FilterOperator(predicate, thisArg) { - this.predicate = predicate; - this.thisArg = thisArg; - } - FilterOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new FilterSubscriber(subscriber, this.predicate, this.thisArg)); - }; - return FilterOperator; -}()); -var FilterSubscriber = /*@__PURE__*/ (function (_super) { - __extends(FilterSubscriber, _super); - function FilterSubscriber(destination, predicate, thisArg) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.thisArg = thisArg; - _this.count = 0; - return _this; - } - FilterSubscriber.prototype._next = function (value) { - var result; - try { - result = this.predicate.call(this.thisArg, value, this.count++); - } - catch (err) { - this.destination.error(err); - return; - } - if (result) { - this.destination.next(value); - } - }; - return FilterSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _util_not,_util_subscribeTo,_operators_filter,_Observable PURE_IMPORTS_END */ -function partition(source, predicate, thisArg) { - return [ - filter(predicate, thisArg)(new Observable(subscribeTo(source))), - filter(not(predicate, thisArg))(new Observable(subscribeTo(source))) - ]; -} - -/** PURE_IMPORTS_START tslib,_util_isArray,_fromArray,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function race() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - if (observables.length === 1) { - if (isArray$1(observables[0])) { - observables = observables[0]; - } - else { - return observables[0]; - } - } - return fromArray(observables, undefined).lift(new RaceOperator()); -} -var RaceOperator = /*@__PURE__*/ (function () { - function RaceOperator() { - } - RaceOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RaceSubscriber(subscriber)); - }; - return RaceOperator; -}()); -var RaceSubscriber = /*@__PURE__*/ (function (_super) { - __extends(RaceSubscriber, _super); - function RaceSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.hasFirst = false; - _this.observables = []; - _this.subscriptions = []; - return _this; - } - RaceSubscriber.prototype._next = function (observable) { - this.observables.push(observable); - }; - RaceSubscriber.prototype._complete = function () { - var observables = this.observables; - var len = observables.length; - if (len === 0) { - this.destination.complete(); - } - else { - for (var i = 0; i < len && !this.hasFirst; i++) { - var observable = observables[i]; - var subscription = subscribeToResult(this, observable, undefined, i); - if (this.subscriptions) { - this.subscriptions.push(subscription); - } - this.add(subscription); - } - this.observables = null; - } - }; - RaceSubscriber.prototype.notifyNext = function (_outerValue, innerValue, outerIndex) { - if (!this.hasFirst) { - this.hasFirst = true; - for (var i = 0; i < this.subscriptions.length; i++) { - if (i !== outerIndex) { - var subscription = this.subscriptions[i]; - subscription.unsubscribe(); - this.remove(subscription); - } - } - this.subscriptions = null; - } - this.destination.next(innerValue); - }; - return RaceSubscriber; -}(OuterSubscriber)); - -/** PURE_IMPORTS_START _Observable PURE_IMPORTS_END */ -function range(start, count, scheduler) { - if (start === void 0) { - start = 0; - } - return new Observable(function (subscriber) { - if (count === undefined) { - count = start; - start = 0; - } - var index = 0; - var current = start; - if (scheduler) { - return scheduler.schedule(dispatch$6, 0, { - index: index, count: count, start: start, subscriber: subscriber - }); - } - else { - do { - if (index++ >= count) { - subscriber.complete(); - break; - } - subscriber.next(current++); - if (subscriber.closed) { - break; - } - } while (true); - } - return undefined; - }); -} -function dispatch$6(state) { - var start = state.start, index = state.index, count = state.count, subscriber = state.subscriber; - if (index >= count) { - subscriber.complete(); - return; - } - subscriber.next(start); - if (subscriber.closed) { - return; - } - state.index = index + 1; - state.start = start + 1; - this.schedule(state); -} - -/** PURE_IMPORTS_START _Observable,_scheduler_async,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */ -function timer(dueTime, periodOrScheduler, scheduler) { - if (dueTime === void 0) { - dueTime = 0; - } - var period = -1; - if (isNumeric(periodOrScheduler)) { - period = Number(periodOrScheduler) < 1 && 1 || Number(periodOrScheduler); - } - else if (isScheduler(periodOrScheduler)) { - scheduler = periodOrScheduler; - } - if (!isScheduler(scheduler)) { - scheduler = async; - } - return new Observable(function (subscriber) { - var due = isNumeric(dueTime) - ? dueTime - : (+dueTime - scheduler.now()); - return scheduler.schedule(dispatch$7, due, { - index: 0, period: period, subscriber: subscriber - }); - }); -} -function dispatch$7(state) { - var index = state.index, period = state.period, subscriber = state.subscriber; - subscriber.next(index); - if (subscriber.closed) { - return; - } - else if (period === -1) { - return subscriber.complete(); - } - state.index = index + 1; - this.schedule(state, period); -} - -/** PURE_IMPORTS_START _Observable,_from,_empty PURE_IMPORTS_END */ -function using(resourceFactory, observableFactory) { - return new Observable(function (subscriber) { - var resource; - try { - resource = resourceFactory(); - } - catch (err) { - subscriber.error(err); - return undefined; - } - var result; - try { - result = observableFactory(resource); - } - catch (err) { - subscriber.error(err); - return undefined; - } - var source = result ? from(result) : EMPTY; - var subscription = source.subscribe(subscriber); - return function () { - subscription.unsubscribe(); - if (resource) { - resource.unsubscribe(); - } - }; - }); -} - -/** PURE_IMPORTS_START tslib,_fromArray,_util_isArray,_Subscriber,_.._internal_symbol_iterator,_innerSubscribe PURE_IMPORTS_END */ -function zip() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - var resultSelector = observables[observables.length - 1]; - if (typeof resultSelector === 'function') { - observables.pop(); - } - return fromArray(observables, undefined).lift(new ZipOperator(resultSelector)); -} -var ZipOperator = /*@__PURE__*/ (function () { - function ZipOperator(resultSelector) { - this.resultSelector = resultSelector; - } - ZipOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ZipSubscriber(subscriber, this.resultSelector)); - }; - return ZipOperator; -}()); -var ZipSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ZipSubscriber, _super); - function ZipSubscriber(destination, resultSelector, values) { - var _this = _super.call(this, destination) || this; - _this.resultSelector = resultSelector; - _this.iterators = []; - _this.active = 0; - _this.resultSelector = (typeof resultSelector === 'function') ? resultSelector : undefined; - return _this; - } - ZipSubscriber.prototype._next = function (value) { - var iterators = this.iterators; - if (isArray$1(value)) { - iterators.push(new StaticArrayIterator(value)); - } - else if (typeof value[iterator] === 'function') { - iterators.push(new StaticIterator(value[iterator]())); - } - else { - iterators.push(new ZipBufferIterator(this.destination, this, value)); - } - }; - ZipSubscriber.prototype._complete = function () { - var iterators = this.iterators; - var len = iterators.length; - this.unsubscribe(); - if (len === 0) { - this.destination.complete(); - return; - } - this.active = len; - for (var i = 0; i < len; i++) { - var iterator = iterators[i]; - if (iterator.stillUnsubscribed) { - var destination = this.destination; - destination.add(iterator.subscribe()); - } - else { - this.active--; - } - } - }; - ZipSubscriber.prototype.notifyInactive = function () { - this.active--; - if (this.active === 0) { - this.destination.complete(); - } - }; - ZipSubscriber.prototype.checkIterators = function () { - var iterators = this.iterators; - var len = iterators.length; - var destination = this.destination; - for (var i = 0; i < len; i++) { - var iterator = iterators[i]; - if (typeof iterator.hasValue === 'function' && !iterator.hasValue()) { - return; - } - } - var shouldComplete = false; - var args = []; - for (var i = 0; i < len; i++) { - var iterator = iterators[i]; - var result = iterator.next(); - if (iterator.hasCompleted()) { - shouldComplete = true; - } - if (result.done) { - destination.complete(); - return; - } - args.push(result.value); - } - if (this.resultSelector) { - this._tryresultSelector(args); - } - else { - destination.next(args); - } - if (shouldComplete) { - destination.complete(); - } - }; - ZipSubscriber.prototype._tryresultSelector = function (args) { - var result; - try { - result = this.resultSelector.apply(this, args); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - return ZipSubscriber; -}(Subscriber)); -var StaticIterator = /*@__PURE__*/ (function () { - function StaticIterator(iterator) { - this.iterator = iterator; - this.nextResult = iterator.next(); - } - StaticIterator.prototype.hasValue = function () { - return true; - }; - StaticIterator.prototype.next = function () { - var result = this.nextResult; - this.nextResult = this.iterator.next(); - return result; - }; - StaticIterator.prototype.hasCompleted = function () { - var nextResult = this.nextResult; - return Boolean(nextResult && nextResult.done); - }; - return StaticIterator; -}()); -var StaticArrayIterator = /*@__PURE__*/ (function () { - function StaticArrayIterator(array) { - this.array = array; - this.index = 0; - this.length = 0; - this.length = array.length; - } - StaticArrayIterator.prototype[iterator] = function () { - return this; - }; - StaticArrayIterator.prototype.next = function (value) { - var i = this.index++; - var array = this.array; - return i < this.length ? { value: array[i], done: false } : { value: null, done: true }; - }; - StaticArrayIterator.prototype.hasValue = function () { - return this.array.length > this.index; - }; - StaticArrayIterator.prototype.hasCompleted = function () { - return this.array.length === this.index; - }; - return StaticArrayIterator; -}()); -var ZipBufferIterator = /*@__PURE__*/ (function (_super) { - __extends(ZipBufferIterator, _super); - function ZipBufferIterator(destination, parent, observable) { - var _this = _super.call(this, destination) || this; - _this.parent = parent; - _this.observable = observable; - _this.stillUnsubscribed = true; - _this.buffer = []; - _this.isComplete = false; - return _this; - } - ZipBufferIterator.prototype[iterator] = function () { - return this; - }; - ZipBufferIterator.prototype.next = function () { - var buffer = this.buffer; - if (buffer.length === 0 && this.isComplete) { - return { value: null, done: true }; - } - else { - return { value: buffer.shift(), done: false }; - } - }; - ZipBufferIterator.prototype.hasValue = function () { - return this.buffer.length > 0; - }; - ZipBufferIterator.prototype.hasCompleted = function () { - return this.buffer.length === 0 && this.isComplete; - }; - ZipBufferIterator.prototype.notifyComplete = function () { - if (this.buffer.length > 0) { - this.isComplete = true; - this.parent.notifyInactive(); - } - else { - this.destination.complete(); - } - }; - ZipBufferIterator.prototype.notifyNext = function (innerValue) { - this.buffer.push(innerValue); - this.parent.checkIterators(); - }; - ZipBufferIterator.prototype.subscribe = function () { - return innerSubscribe(this.observable, new SimpleInnerSubscriber(this)); - }; - return ZipBufferIterator; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ - -var _esm5 = /*#__PURE__*/Object.freeze({ - __proto__: null, - Observable: Observable, - ConnectableObservable: ConnectableObservable, - GroupedObservable: GroupedObservable, - observable: observable, - Subject: Subject, - BehaviorSubject: BehaviorSubject, - ReplaySubject: ReplaySubject, - AsyncSubject: AsyncSubject, - asap: asap, - asapScheduler: asapScheduler, - async: async, - asyncScheduler: asyncScheduler, - queue: queue, - queueScheduler: queueScheduler, - animationFrame: animationFrame, - animationFrameScheduler: animationFrameScheduler, - VirtualTimeScheduler: VirtualTimeScheduler, - VirtualAction: VirtualAction, - Scheduler: Scheduler, - Subscription: Subscription, - Subscriber: Subscriber, - Notification: Notification, - get NotificationKind () { return NotificationKind; }, - pipe: pipe, - noop: noop, - identity: identity$1, - isObservable: isObservable, - ArgumentOutOfRangeError: ArgumentOutOfRangeError, - EmptyError: EmptyError, - ObjectUnsubscribedError: ObjectUnsubscribedError, - UnsubscriptionError: UnsubscriptionError, - TimeoutError: TimeoutError, - bindCallback: bindCallback, - bindNodeCallback: bindNodeCallback, - combineLatest: combineLatest, - concat: concat$1, - defer: defer, - empty: empty$1, - forkJoin: forkJoin, - from: from, - fromEvent: fromEvent, - fromEventPattern: fromEventPattern, - generate: generate, - iif: iif, - interval: interval, - merge: merge, - never: never, - of: of, - onErrorResumeNext: onErrorResumeNext, - pairs: pairs, - partition: partition, - race: race, - range: range, - throwError: throwError, - timer: timer, - using: using, - zip: zip, - scheduled: scheduled, - EMPTY: EMPTY, - NEVER: NEVER, - config: config -}); - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function audit(durationSelector) { - return function auditOperatorFunction(source) { - return source.lift(new AuditOperator(durationSelector)); - }; -} -var AuditOperator = /*@__PURE__*/ (function () { - function AuditOperator(durationSelector) { - this.durationSelector = durationSelector; - } - AuditOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new AuditSubscriber(subscriber, this.durationSelector)); - }; - return AuditOperator; -}()); -var AuditSubscriber = /*@__PURE__*/ (function (_super) { - __extends(AuditSubscriber, _super); - function AuditSubscriber(destination, durationSelector) { - var _this = _super.call(this, destination) || this; - _this.durationSelector = durationSelector; - _this.hasValue = false; - return _this; - } - AuditSubscriber.prototype._next = function (value) { - this.value = value; - this.hasValue = true; - if (!this.throttled) { - var duration = void 0; - try { - var durationSelector = this.durationSelector; - duration = durationSelector(value); - } - catch (err) { - return this.destination.error(err); - } - var innerSubscription = innerSubscribe(duration, new SimpleInnerSubscriber(this)); - if (!innerSubscription || innerSubscription.closed) { - this.clearThrottle(); - } - else { - this.add(this.throttled = innerSubscription); - } - } - }; - AuditSubscriber.prototype.clearThrottle = function () { - var _a = this, value = _a.value, hasValue = _a.hasValue, throttled = _a.throttled; - if (throttled) { - this.remove(throttled); - this.throttled = undefined; - throttled.unsubscribe(); - } - if (hasValue) { - this.value = undefined; - this.hasValue = false; - this.destination.next(value); - } - }; - AuditSubscriber.prototype.notifyNext = function () { - this.clearThrottle(); - }; - AuditSubscriber.prototype.notifyComplete = function () { - this.clearThrottle(); - }; - return AuditSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START _scheduler_async,_audit,_observable_timer PURE_IMPORTS_END */ -function auditTime(duration, scheduler) { - if (scheduler === void 0) { - scheduler = async; - } - return audit(function () { return timer(duration, scheduler); }); -} - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function buffer(closingNotifier) { - return function bufferOperatorFunction(source) { - return source.lift(new BufferOperator(closingNotifier)); - }; -} -var BufferOperator = /*@__PURE__*/ (function () { - function BufferOperator(closingNotifier) { - this.closingNotifier = closingNotifier; - } - BufferOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new BufferSubscriber(subscriber, this.closingNotifier)); - }; - return BufferOperator; -}()); -var BufferSubscriber = /*@__PURE__*/ (function (_super) { - __extends(BufferSubscriber, _super); - function BufferSubscriber(destination, closingNotifier) { - var _this = _super.call(this, destination) || this; - _this.buffer = []; - _this.add(innerSubscribe(closingNotifier, new SimpleInnerSubscriber(_this))); - return _this; - } - BufferSubscriber.prototype._next = function (value) { - this.buffer.push(value); - }; - BufferSubscriber.prototype.notifyNext = function () { - var buffer = this.buffer; - this.buffer = []; - this.destination.next(buffer); - }; - return BufferSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function bufferCount(bufferSize, startBufferEvery) { - if (startBufferEvery === void 0) { - startBufferEvery = null; - } - return function bufferCountOperatorFunction(source) { - return source.lift(new BufferCountOperator(bufferSize, startBufferEvery)); - }; -} -var BufferCountOperator = /*@__PURE__*/ (function () { - function BufferCountOperator(bufferSize, startBufferEvery) { - this.bufferSize = bufferSize; - this.startBufferEvery = startBufferEvery; - if (!startBufferEvery || bufferSize === startBufferEvery) { - this.subscriberClass = BufferCountSubscriber; - } - else { - this.subscriberClass = BufferSkipCountSubscriber; - } - } - BufferCountOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new this.subscriberClass(subscriber, this.bufferSize, this.startBufferEvery)); - }; - return BufferCountOperator; -}()); -var BufferCountSubscriber = /*@__PURE__*/ (function (_super) { - __extends(BufferCountSubscriber, _super); - function BufferCountSubscriber(destination, bufferSize) { - var _this = _super.call(this, destination) || this; - _this.bufferSize = bufferSize; - _this.buffer = []; - return _this; - } - BufferCountSubscriber.prototype._next = function (value) { - var buffer = this.buffer; - buffer.push(value); - if (buffer.length == this.bufferSize) { - this.destination.next(buffer); - this.buffer = []; - } - }; - BufferCountSubscriber.prototype._complete = function () { - var buffer = this.buffer; - if (buffer.length > 0) { - this.destination.next(buffer); - } - _super.prototype._complete.call(this); - }; - return BufferCountSubscriber; -}(Subscriber)); -var BufferSkipCountSubscriber = /*@__PURE__*/ (function (_super) { - __extends(BufferSkipCountSubscriber, _super); - function BufferSkipCountSubscriber(destination, bufferSize, startBufferEvery) { - var _this = _super.call(this, destination) || this; - _this.bufferSize = bufferSize; - _this.startBufferEvery = startBufferEvery; - _this.buffers = []; - _this.count = 0; - return _this; - } - BufferSkipCountSubscriber.prototype._next = function (value) { - var _a = this, bufferSize = _a.bufferSize, startBufferEvery = _a.startBufferEvery, buffers = _a.buffers, count = _a.count; - this.count++; - if (count % startBufferEvery === 0) { - buffers.push([]); - } - for (var i = buffers.length; i--;) { - var buffer = buffers[i]; - buffer.push(value); - if (buffer.length === bufferSize) { - buffers.splice(i, 1); - this.destination.next(buffer); - } - } - }; - BufferSkipCountSubscriber.prototype._complete = function () { - var _a = this, buffers = _a.buffers, destination = _a.destination; - while (buffers.length > 0) { - var buffer = buffers.shift(); - if (buffer.length > 0) { - destination.next(buffer); - } - } - _super.prototype._complete.call(this); - }; - return BufferSkipCountSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_scheduler_async,_Subscriber,_util_isScheduler PURE_IMPORTS_END */ -function bufferTime(bufferTimeSpan) { - var length = arguments.length; - var scheduler = async; - if (isScheduler(arguments[arguments.length - 1])) { - scheduler = arguments[arguments.length - 1]; - length--; - } - var bufferCreationInterval = null; - if (length >= 2) { - bufferCreationInterval = arguments[1]; - } - var maxBufferSize = Number.POSITIVE_INFINITY; - if (length >= 3) { - maxBufferSize = arguments[2]; - } - return function bufferTimeOperatorFunction(source) { - return source.lift(new BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler)); - }; -} -var BufferTimeOperator = /*@__PURE__*/ (function () { - function BufferTimeOperator(bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { - this.bufferTimeSpan = bufferTimeSpan; - this.bufferCreationInterval = bufferCreationInterval; - this.maxBufferSize = maxBufferSize; - this.scheduler = scheduler; - } - BufferTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new BufferTimeSubscriber(subscriber, this.bufferTimeSpan, this.bufferCreationInterval, this.maxBufferSize, this.scheduler)); - }; - return BufferTimeOperator; -}()); -var Context = /*@__PURE__*/ (function () { - function Context() { - this.buffer = []; - } - return Context; -}()); -var BufferTimeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(BufferTimeSubscriber, _super); - function BufferTimeSubscriber(destination, bufferTimeSpan, bufferCreationInterval, maxBufferSize, scheduler) { - var _this = _super.call(this, destination) || this; - _this.bufferTimeSpan = bufferTimeSpan; - _this.bufferCreationInterval = bufferCreationInterval; - _this.maxBufferSize = maxBufferSize; - _this.scheduler = scheduler; - _this.contexts = []; - var context = _this.openContext(); - _this.timespanOnly = bufferCreationInterval == null || bufferCreationInterval < 0; - if (_this.timespanOnly) { - var timeSpanOnlyState = { subscriber: _this, context: context, bufferTimeSpan: bufferTimeSpan }; - _this.add(context.closeAction = scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); - } - else { - var closeState = { subscriber: _this, context: context }; - var creationState = { bufferTimeSpan: bufferTimeSpan, bufferCreationInterval: bufferCreationInterval, subscriber: _this, scheduler: scheduler }; - _this.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, closeState)); - _this.add(scheduler.schedule(dispatchBufferCreation, bufferCreationInterval, creationState)); - } - return _this; - } - BufferTimeSubscriber.prototype._next = function (value) { - var contexts = this.contexts; - var len = contexts.length; - var filledBufferContext; - for (var i = 0; i < len; i++) { - var context_1 = contexts[i]; - var buffer = context_1.buffer; - buffer.push(value); - if (buffer.length == this.maxBufferSize) { - filledBufferContext = context_1; - } - } - if (filledBufferContext) { - this.onBufferFull(filledBufferContext); - } - }; - BufferTimeSubscriber.prototype._error = function (err) { - this.contexts.length = 0; - _super.prototype._error.call(this, err); - }; - BufferTimeSubscriber.prototype._complete = function () { - var _a = this, contexts = _a.contexts, destination = _a.destination; - while (contexts.length > 0) { - var context_2 = contexts.shift(); - destination.next(context_2.buffer); - } - _super.prototype._complete.call(this); - }; - BufferTimeSubscriber.prototype._unsubscribe = function () { - this.contexts = null; - }; - BufferTimeSubscriber.prototype.onBufferFull = function (context) { - this.closeContext(context); - var closeAction = context.closeAction; - closeAction.unsubscribe(); - this.remove(closeAction); - if (!this.closed && this.timespanOnly) { - context = this.openContext(); - var bufferTimeSpan = this.bufferTimeSpan; - var timeSpanOnlyState = { subscriber: this, context: context, bufferTimeSpan: bufferTimeSpan }; - this.add(context.closeAction = this.scheduler.schedule(dispatchBufferTimeSpanOnly, bufferTimeSpan, timeSpanOnlyState)); - } - }; - BufferTimeSubscriber.prototype.openContext = function () { - var context = new Context(); - this.contexts.push(context); - return context; - }; - BufferTimeSubscriber.prototype.closeContext = function (context) { - this.destination.next(context.buffer); - var contexts = this.contexts; - var spliceIndex = contexts ? contexts.indexOf(context) : -1; - if (spliceIndex >= 0) { - contexts.splice(contexts.indexOf(context), 1); - } - }; - return BufferTimeSubscriber; -}(Subscriber)); -function dispatchBufferTimeSpanOnly(state) { - var subscriber = state.subscriber; - var prevContext = state.context; - if (prevContext) { - subscriber.closeContext(prevContext); - } - if (!subscriber.closed) { - state.context = subscriber.openContext(); - state.context.closeAction = this.schedule(state, state.bufferTimeSpan); - } -} -function dispatchBufferCreation(state) { - var bufferCreationInterval = state.bufferCreationInterval, bufferTimeSpan = state.bufferTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler; - var context = subscriber.openContext(); - var action = this; - if (!subscriber.closed) { - subscriber.add(context.closeAction = scheduler.schedule(dispatchBufferClose, bufferTimeSpan, { subscriber: subscriber, context: context })); - action.schedule(state, bufferCreationInterval); - } -} -function dispatchBufferClose(arg) { - var subscriber = arg.subscriber, context = arg.context; - subscriber.closeContext(context); -} - -/** PURE_IMPORTS_START tslib,_Subscription,_util_subscribeToResult,_OuterSubscriber PURE_IMPORTS_END */ -function bufferToggle(openings, closingSelector) { - return function bufferToggleOperatorFunction(source) { - return source.lift(new BufferToggleOperator(openings, closingSelector)); - }; -} -var BufferToggleOperator = /*@__PURE__*/ (function () { - function BufferToggleOperator(openings, closingSelector) { - this.openings = openings; - this.closingSelector = closingSelector; - } - BufferToggleOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new BufferToggleSubscriber(subscriber, this.openings, this.closingSelector)); - }; - return BufferToggleOperator; -}()); -var BufferToggleSubscriber = /*@__PURE__*/ (function (_super) { - __extends(BufferToggleSubscriber, _super); - function BufferToggleSubscriber(destination, openings, closingSelector) { - var _this = _super.call(this, destination) || this; - _this.closingSelector = closingSelector; - _this.contexts = []; - _this.add(subscribeToResult(_this, openings)); - return _this; - } - BufferToggleSubscriber.prototype._next = function (value) { - var contexts = this.contexts; - var len = contexts.length; - for (var i = 0; i < len; i++) { - contexts[i].buffer.push(value); - } - }; - BufferToggleSubscriber.prototype._error = function (err) { - var contexts = this.contexts; - while (contexts.length > 0) { - var context_1 = contexts.shift(); - context_1.subscription.unsubscribe(); - context_1.buffer = null; - context_1.subscription = null; - } - this.contexts = null; - _super.prototype._error.call(this, err); - }; - BufferToggleSubscriber.prototype._complete = function () { - var contexts = this.contexts; - while (contexts.length > 0) { - var context_2 = contexts.shift(); - this.destination.next(context_2.buffer); - context_2.subscription.unsubscribe(); - context_2.buffer = null; - context_2.subscription = null; - } - this.contexts = null; - _super.prototype._complete.call(this); - }; - BufferToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue) { - outerValue ? this.closeBuffer(outerValue) : this.openBuffer(innerValue); - }; - BufferToggleSubscriber.prototype.notifyComplete = function (innerSub) { - this.closeBuffer(innerSub.context); - }; - BufferToggleSubscriber.prototype.openBuffer = function (value) { - try { - var closingSelector = this.closingSelector; - var closingNotifier = closingSelector.call(this, value); - if (closingNotifier) { - this.trySubscribe(closingNotifier); - } - } - catch (err) { - this._error(err); - } - }; - BufferToggleSubscriber.prototype.closeBuffer = function (context) { - var contexts = this.contexts; - if (contexts && context) { - var buffer = context.buffer, subscription = context.subscription; - this.destination.next(buffer); - contexts.splice(contexts.indexOf(context), 1); - this.remove(subscription); - subscription.unsubscribe(); - } - }; - BufferToggleSubscriber.prototype.trySubscribe = function (closingNotifier) { - var contexts = this.contexts; - var buffer = []; - var subscription = new Subscription(); - var context = { buffer: buffer, subscription: subscription }; - contexts.push(context); - var innerSubscription = subscribeToResult(this, closingNotifier, context); - if (!innerSubscription || innerSubscription.closed) { - this.closeBuffer(context); - } - else { - innerSubscription.context = context; - this.add(innerSubscription); - subscription.add(innerSubscription); - } - }; - return BufferToggleSubscriber; -}(OuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscription,_innerSubscribe PURE_IMPORTS_END */ -function bufferWhen(closingSelector) { - return function (source) { - return source.lift(new BufferWhenOperator(closingSelector)); - }; -} -var BufferWhenOperator = /*@__PURE__*/ (function () { - function BufferWhenOperator(closingSelector) { - this.closingSelector = closingSelector; - } - BufferWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new BufferWhenSubscriber(subscriber, this.closingSelector)); - }; - return BufferWhenOperator; -}()); -var BufferWhenSubscriber = /*@__PURE__*/ (function (_super) { - __extends(BufferWhenSubscriber, _super); - function BufferWhenSubscriber(destination, closingSelector) { - var _this = _super.call(this, destination) || this; - _this.closingSelector = closingSelector; - _this.subscribing = false; - _this.openBuffer(); - return _this; - } - BufferWhenSubscriber.prototype._next = function (value) { - this.buffer.push(value); - }; - BufferWhenSubscriber.prototype._complete = function () { - var buffer = this.buffer; - if (buffer) { - this.destination.next(buffer); - } - _super.prototype._complete.call(this); - }; - BufferWhenSubscriber.prototype._unsubscribe = function () { - this.buffer = undefined; - this.subscribing = false; - }; - BufferWhenSubscriber.prototype.notifyNext = function () { - this.openBuffer(); - }; - BufferWhenSubscriber.prototype.notifyComplete = function () { - if (this.subscribing) { - this.complete(); - } - else { - this.openBuffer(); - } - }; - BufferWhenSubscriber.prototype.openBuffer = function () { - var closingSubscription = this.closingSubscription; - if (closingSubscription) { - this.remove(closingSubscription); - closingSubscription.unsubscribe(); - } - var buffer = this.buffer; - if (this.buffer) { - this.destination.next(buffer); - } - this.buffer = []; - var closingNotifier; - try { - var closingSelector = this.closingSelector; - closingNotifier = closingSelector(); - } - catch (err) { - return this.error(err); - } - closingSubscription = new Subscription(); - this.closingSubscription = closingSubscription; - this.add(closingSubscription); - this.subscribing = true; - closingSubscription.add(innerSubscribe(closingNotifier, new SimpleInnerSubscriber(this))); - this.subscribing = false; - }; - return BufferWhenSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function catchError(selector) { - return function catchErrorOperatorFunction(source) { - var operator = new CatchOperator(selector); - var caught = source.lift(operator); - return (operator.caught = caught); - }; -} -var CatchOperator = /*@__PURE__*/ (function () { - function CatchOperator(selector) { - this.selector = selector; - } - CatchOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new CatchSubscriber(subscriber, this.selector, this.caught)); - }; - return CatchOperator; -}()); -var CatchSubscriber = /*@__PURE__*/ (function (_super) { - __extends(CatchSubscriber, _super); - function CatchSubscriber(destination, selector, caught) { - var _this = _super.call(this, destination) || this; - _this.selector = selector; - _this.caught = caught; - return _this; - } - CatchSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var result = void 0; - try { - result = this.selector(err, this.caught); - } - catch (err2) { - _super.prototype.error.call(this, err2); - return; - } - this._unsubscribeAndRecycle(); - var innerSubscriber = new SimpleInnerSubscriber(this); - this.add(innerSubscriber); - var innerSubscription = innerSubscribe(result, innerSubscriber); - if (innerSubscription !== innerSubscriber) { - this.add(innerSubscription); - } - } - }; - return CatchSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START _observable_combineLatest PURE_IMPORTS_END */ -function combineAll(project) { - return function (source) { return source.lift(new CombineLatestOperator(project)); }; -} - -/** PURE_IMPORTS_START _util_isArray,_observable_combineLatest,_observable_from PURE_IMPORTS_END */ -function combineLatest$1() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - var project = null; - if (typeof observables[observables.length - 1] === 'function') { - project = observables.pop(); - } - if (observables.length === 1 && isArray$1(observables[0])) { - observables = observables[0].slice(); - } - return function (source) { return source.lift.call(from([source].concat(observables)), new CombineLatestOperator(project)); }; -} - -/** PURE_IMPORTS_START _observable_concat PURE_IMPORTS_END */ -function concat$2() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - return function (source) { return source.lift.call(concat$1.apply(void 0, [source].concat(observables))); }; -} - -/** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ -function concatMap(project, resultSelector) { - return mergeMap(project, resultSelector, 1); -} - -/** PURE_IMPORTS_START _concatMap PURE_IMPORTS_END */ -function concatMapTo(innerObservable, resultSelector) { - return concatMap(function () { return innerObservable; }, resultSelector); -} - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function count(predicate) { - return function (source) { return source.lift(new CountOperator(predicate, source)); }; -} -var CountOperator = /*@__PURE__*/ (function () { - function CountOperator(predicate, source) { - this.predicate = predicate; - this.source = source; - } - CountOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new CountSubscriber(subscriber, this.predicate, this.source)); - }; - return CountOperator; -}()); -var CountSubscriber = /*@__PURE__*/ (function (_super) { - __extends(CountSubscriber, _super); - function CountSubscriber(destination, predicate, source) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.source = source; - _this.count = 0; - _this.index = 0; - return _this; - } - CountSubscriber.prototype._next = function (value) { - if (this.predicate) { - this._tryPredicate(value); - } - else { - this.count++; - } - }; - CountSubscriber.prototype._tryPredicate = function (value) { - var result; - try { - result = this.predicate(value, this.index++, this.source); - } - catch (err) { - this.destination.error(err); - return; - } - if (result) { - this.count++; - } - }; - CountSubscriber.prototype._complete = function () { - this.destination.next(this.count); - this.destination.complete(); - }; - return CountSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function debounce(durationSelector) { - return function (source) { return source.lift(new DebounceOperator(durationSelector)); }; -} -var DebounceOperator = /*@__PURE__*/ (function () { - function DebounceOperator(durationSelector) { - this.durationSelector = durationSelector; - } - DebounceOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DebounceSubscriber(subscriber, this.durationSelector)); - }; - return DebounceOperator; -}()); -var DebounceSubscriber = /*@__PURE__*/ (function (_super) { - __extends(DebounceSubscriber, _super); - function DebounceSubscriber(destination, durationSelector) { - var _this = _super.call(this, destination) || this; - _this.durationSelector = durationSelector; - _this.hasValue = false; - return _this; - } - DebounceSubscriber.prototype._next = function (value) { - try { - var result = this.durationSelector.call(this, value); - if (result) { - this._tryNext(value, result); - } - } - catch (err) { - this.destination.error(err); - } - }; - DebounceSubscriber.prototype._complete = function () { - this.emitValue(); - this.destination.complete(); - }; - DebounceSubscriber.prototype._tryNext = function (value, duration) { - var subscription = this.durationSubscription; - this.value = value; - this.hasValue = true; - if (subscription) { - subscription.unsubscribe(); - this.remove(subscription); - } - subscription = innerSubscribe(duration, new SimpleInnerSubscriber(this)); - if (subscription && !subscription.closed) { - this.add(this.durationSubscription = subscription); - } - }; - DebounceSubscriber.prototype.notifyNext = function () { - this.emitValue(); - }; - DebounceSubscriber.prototype.notifyComplete = function () { - this.emitValue(); - }; - DebounceSubscriber.prototype.emitValue = function () { - if (this.hasValue) { - var value = this.value; - var subscription = this.durationSubscription; - if (subscription) { - this.durationSubscription = undefined; - subscription.unsubscribe(); - this.remove(subscription); - } - this.value = undefined; - this.hasValue = false; - _super.prototype._next.call(this, value); - } - }; - return DebounceSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async PURE_IMPORTS_END */ -function debounceTime(dueTime, scheduler) { - if (scheduler === void 0) { - scheduler = async; - } - return function (source) { return source.lift(new DebounceTimeOperator(dueTime, scheduler)); }; -} -var DebounceTimeOperator = /*@__PURE__*/ (function () { - function DebounceTimeOperator(dueTime, scheduler) { - this.dueTime = dueTime; - this.scheduler = scheduler; - } - DebounceTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DebounceTimeSubscriber(subscriber, this.dueTime, this.scheduler)); - }; - return DebounceTimeOperator; -}()); -var DebounceTimeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(DebounceTimeSubscriber, _super); - function DebounceTimeSubscriber(destination, dueTime, scheduler) { - var _this = _super.call(this, destination) || this; - _this.dueTime = dueTime; - _this.scheduler = scheduler; - _this.debouncedSubscription = null; - _this.lastValue = null; - _this.hasValue = false; - return _this; - } - DebounceTimeSubscriber.prototype._next = function (value) { - this.clearDebounce(); - this.lastValue = value; - this.hasValue = true; - this.add(this.debouncedSubscription = this.scheduler.schedule(dispatchNext$2, this.dueTime, this)); - }; - DebounceTimeSubscriber.prototype._complete = function () { - this.debouncedNext(); - this.destination.complete(); - }; - DebounceTimeSubscriber.prototype.debouncedNext = function () { - this.clearDebounce(); - if (this.hasValue) { - var lastValue = this.lastValue; - this.lastValue = null; - this.hasValue = false; - this.destination.next(lastValue); - } - }; - DebounceTimeSubscriber.prototype.clearDebounce = function () { - var debouncedSubscription = this.debouncedSubscription; - if (debouncedSubscription !== null) { - this.remove(debouncedSubscription); - debouncedSubscription.unsubscribe(); - this.debouncedSubscription = null; - } - }; - return DebounceTimeSubscriber; -}(Subscriber)); -function dispatchNext$2(subscriber) { - subscriber.debouncedNext(); -} - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function defaultIfEmpty(defaultValue) { - if (defaultValue === void 0) { - defaultValue = null; - } - return function (source) { return source.lift(new DefaultIfEmptyOperator(defaultValue)); }; -} -var DefaultIfEmptyOperator = /*@__PURE__*/ (function () { - function DefaultIfEmptyOperator(defaultValue) { - this.defaultValue = defaultValue; - } - DefaultIfEmptyOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DefaultIfEmptySubscriber(subscriber, this.defaultValue)); - }; - return DefaultIfEmptyOperator; -}()); -var DefaultIfEmptySubscriber = /*@__PURE__*/ (function (_super) { - __extends(DefaultIfEmptySubscriber, _super); - function DefaultIfEmptySubscriber(destination, defaultValue) { - var _this = _super.call(this, destination) || this; - _this.defaultValue = defaultValue; - _this.isEmpty = true; - return _this; - } - DefaultIfEmptySubscriber.prototype._next = function (value) { - this.isEmpty = false; - this.destination.next(value); - }; - DefaultIfEmptySubscriber.prototype._complete = function () { - if (this.isEmpty) { - this.destination.next(this.defaultValue); - } - this.destination.complete(); - }; - return DefaultIfEmptySubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ -function isDate(value) { - return value instanceof Date && !isNaN(+value); -} - -/** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_Subscriber,_Notification PURE_IMPORTS_END */ -function delay(delay, scheduler) { - if (scheduler === void 0) { - scheduler = async; - } - var absoluteDelay = isDate(delay); - var delayFor = absoluteDelay ? (+delay - scheduler.now()) : Math.abs(delay); - return function (source) { return source.lift(new DelayOperator(delayFor, scheduler)); }; -} -var DelayOperator = /*@__PURE__*/ (function () { - function DelayOperator(delay, scheduler) { - this.delay = delay; - this.scheduler = scheduler; - } - DelayOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DelaySubscriber(subscriber, this.delay, this.scheduler)); - }; - return DelayOperator; -}()); -var DelaySubscriber = /*@__PURE__*/ (function (_super) { - __extends(DelaySubscriber, _super); - function DelaySubscriber(destination, delay, scheduler) { - var _this = _super.call(this, destination) || this; - _this.delay = delay; - _this.scheduler = scheduler; - _this.queue = []; - _this.active = false; - _this.errored = false; - return _this; - } - DelaySubscriber.dispatch = function (state) { - var source = state.source; - var queue = source.queue; - var scheduler = state.scheduler; - var destination = state.destination; - while (queue.length > 0 && (queue[0].time - scheduler.now()) <= 0) { - queue.shift().notification.observe(destination); - } - if (queue.length > 0) { - var delay_1 = Math.max(0, queue[0].time - scheduler.now()); - this.schedule(state, delay_1); - } - else { - this.unsubscribe(); - source.active = false; - } - }; - DelaySubscriber.prototype._schedule = function (scheduler) { - this.active = true; - var destination = this.destination; - destination.add(scheduler.schedule(DelaySubscriber.dispatch, this.delay, { - source: this, destination: this.destination, scheduler: scheduler - })); - }; - DelaySubscriber.prototype.scheduleNotification = function (notification) { - if (this.errored === true) { - return; - } - var scheduler = this.scheduler; - var message = new DelayMessage(scheduler.now() + this.delay, notification); - this.queue.push(message); - if (this.active === false) { - this._schedule(scheduler); - } - }; - DelaySubscriber.prototype._next = function (value) { - this.scheduleNotification(Notification.createNext(value)); - }; - DelaySubscriber.prototype._error = function (err) { - this.errored = true; - this.queue = []; - this.destination.error(err); - this.unsubscribe(); - }; - DelaySubscriber.prototype._complete = function () { - this.scheduleNotification(Notification.createComplete()); - this.unsubscribe(); - }; - return DelaySubscriber; -}(Subscriber)); -var DelayMessage = /*@__PURE__*/ (function () { - function DelayMessage(time, notification) { - this.time = time; - this.notification = notification; - } - return DelayMessage; -}()); - -/** PURE_IMPORTS_START tslib,_Subscriber,_Observable,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function delayWhen(delayDurationSelector, subscriptionDelay) { - if (subscriptionDelay) { - return function (source) { - return new SubscriptionDelayObservable(source, subscriptionDelay) - .lift(new DelayWhenOperator(delayDurationSelector)); - }; - } - return function (source) { return source.lift(new DelayWhenOperator(delayDurationSelector)); }; -} -var DelayWhenOperator = /*@__PURE__*/ (function () { - function DelayWhenOperator(delayDurationSelector) { - this.delayDurationSelector = delayDurationSelector; - } - DelayWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DelayWhenSubscriber(subscriber, this.delayDurationSelector)); - }; - return DelayWhenOperator; -}()); -var DelayWhenSubscriber = /*@__PURE__*/ (function (_super) { - __extends(DelayWhenSubscriber, _super); - function DelayWhenSubscriber(destination, delayDurationSelector) { - var _this = _super.call(this, destination) || this; - _this.delayDurationSelector = delayDurationSelector; - _this.completed = false; - _this.delayNotifierSubscriptions = []; - _this.index = 0; - return _this; - } - DelayWhenSubscriber.prototype.notifyNext = function (outerValue, _innerValue, _outerIndex, _innerIndex, innerSub) { - this.destination.next(outerValue); - this.removeSubscription(innerSub); - this.tryComplete(); - }; - DelayWhenSubscriber.prototype.notifyError = function (error, innerSub) { - this._error(error); - }; - DelayWhenSubscriber.prototype.notifyComplete = function (innerSub) { - var value = this.removeSubscription(innerSub); - if (value) { - this.destination.next(value); - } - this.tryComplete(); - }; - DelayWhenSubscriber.prototype._next = function (value) { - var index = this.index++; - try { - var delayNotifier = this.delayDurationSelector(value, index); - if (delayNotifier) { - this.tryDelay(delayNotifier, value); - } - } - catch (err) { - this.destination.error(err); - } - }; - DelayWhenSubscriber.prototype._complete = function () { - this.completed = true; - this.tryComplete(); - this.unsubscribe(); - }; - DelayWhenSubscriber.prototype.removeSubscription = function (subscription) { - subscription.unsubscribe(); - var subscriptionIdx = this.delayNotifierSubscriptions.indexOf(subscription); - if (subscriptionIdx !== -1) { - this.delayNotifierSubscriptions.splice(subscriptionIdx, 1); - } - return subscription.outerValue; - }; - DelayWhenSubscriber.prototype.tryDelay = function (delayNotifier, value) { - var notifierSubscription = subscribeToResult(this, delayNotifier, value); - if (notifierSubscription && !notifierSubscription.closed) { - var destination = this.destination; - destination.add(notifierSubscription); - this.delayNotifierSubscriptions.push(notifierSubscription); - } - }; - DelayWhenSubscriber.prototype.tryComplete = function () { - if (this.completed && this.delayNotifierSubscriptions.length === 0) { - this.destination.complete(); - } - }; - return DelayWhenSubscriber; -}(OuterSubscriber)); -var SubscriptionDelayObservable = /*@__PURE__*/ (function (_super) { - __extends(SubscriptionDelayObservable, _super); - function SubscriptionDelayObservable(source, subscriptionDelay) { - var _this = _super.call(this) || this; - _this.source = source; - _this.subscriptionDelay = subscriptionDelay; - return _this; - } - SubscriptionDelayObservable.prototype._subscribe = function (subscriber) { - this.subscriptionDelay.subscribe(new SubscriptionDelaySubscriber(subscriber, this.source)); - }; - return SubscriptionDelayObservable; -}(Observable)); -var SubscriptionDelaySubscriber = /*@__PURE__*/ (function (_super) { - __extends(SubscriptionDelaySubscriber, _super); - function SubscriptionDelaySubscriber(parent, source) { - var _this = _super.call(this) || this; - _this.parent = parent; - _this.source = source; - _this.sourceSubscribed = false; - return _this; - } - SubscriptionDelaySubscriber.prototype._next = function (unused) { - this.subscribeToSource(); - }; - SubscriptionDelaySubscriber.prototype._error = function (err) { - this.unsubscribe(); - this.parent.error(err); - }; - SubscriptionDelaySubscriber.prototype._complete = function () { - this.unsubscribe(); - this.subscribeToSource(); - }; - SubscriptionDelaySubscriber.prototype.subscribeToSource = function () { - if (!this.sourceSubscribed) { - this.sourceSubscribed = true; - this.unsubscribe(); - this.source.subscribe(this.parent); - } - }; - return SubscriptionDelaySubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function dematerialize() { - return function dematerializeOperatorFunction(source) { - return source.lift(new DeMaterializeOperator()); - }; -} -var DeMaterializeOperator = /*@__PURE__*/ (function () { - function DeMaterializeOperator() { - } - DeMaterializeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DeMaterializeSubscriber(subscriber)); - }; - return DeMaterializeOperator; -}()); -var DeMaterializeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(DeMaterializeSubscriber, _super); - function DeMaterializeSubscriber(destination) { - return _super.call(this, destination) || this; - } - DeMaterializeSubscriber.prototype._next = function (value) { - value.observe(this.destination); - }; - return DeMaterializeSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function distinct(keySelector, flushes) { - return function (source) { return source.lift(new DistinctOperator(keySelector, flushes)); }; -} -var DistinctOperator = /*@__PURE__*/ (function () { - function DistinctOperator(keySelector, flushes) { - this.keySelector = keySelector; - this.flushes = flushes; - } - DistinctOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DistinctSubscriber(subscriber, this.keySelector, this.flushes)); - }; - return DistinctOperator; -}()); -var DistinctSubscriber = /*@__PURE__*/ (function (_super) { - __extends(DistinctSubscriber, _super); - function DistinctSubscriber(destination, keySelector, flushes) { - var _this = _super.call(this, destination) || this; - _this.keySelector = keySelector; - _this.values = new Set(); - if (flushes) { - _this.add(innerSubscribe(flushes, new SimpleInnerSubscriber(_this))); - } - return _this; - } - DistinctSubscriber.prototype.notifyNext = function () { - this.values.clear(); - }; - DistinctSubscriber.prototype.notifyError = function (error) { - this._error(error); - }; - DistinctSubscriber.prototype._next = function (value) { - if (this.keySelector) { - this._useKeySelector(value); - } - else { - this._finalizeNext(value, value); - } - }; - DistinctSubscriber.prototype._useKeySelector = function (value) { - var key; - var destination = this.destination; - try { - key = this.keySelector(value); - } - catch (err) { - destination.error(err); - return; - } - this._finalizeNext(key, value); - }; - DistinctSubscriber.prototype._finalizeNext = function (key, value) { - var values = this.values; - if (!values.has(key)) { - values.add(key); - this.destination.next(value); - } - }; - return DistinctSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function distinctUntilChanged(compare, keySelector) { - return function (source) { return source.lift(new DistinctUntilChangedOperator(compare, keySelector)); }; -} -var DistinctUntilChangedOperator = /*@__PURE__*/ (function () { - function DistinctUntilChangedOperator(compare, keySelector) { - this.compare = compare; - this.keySelector = keySelector; - } - DistinctUntilChangedOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new DistinctUntilChangedSubscriber(subscriber, this.compare, this.keySelector)); - }; - return DistinctUntilChangedOperator; -}()); -var DistinctUntilChangedSubscriber = /*@__PURE__*/ (function (_super) { - __extends(DistinctUntilChangedSubscriber, _super); - function DistinctUntilChangedSubscriber(destination, compare, keySelector) { - var _this = _super.call(this, destination) || this; - _this.keySelector = keySelector; - _this.hasKey = false; - if (typeof compare === 'function') { - _this.compare = compare; - } - return _this; - } - DistinctUntilChangedSubscriber.prototype.compare = function (x, y) { - return x === y; - }; - DistinctUntilChangedSubscriber.prototype._next = function (value) { - var key; - try { - var keySelector = this.keySelector; - key = keySelector ? keySelector(value) : value; - } - catch (err) { - return this.destination.error(err); - } - var result = false; - if (this.hasKey) { - try { - var compare = this.compare; - result = compare(this.key, key); - } - catch (err) { - return this.destination.error(err); - } - } - else { - this.hasKey = true; - } - if (!result) { - this.key = key; - this.destination.next(value); - } - }; - return DistinctUntilChangedSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _distinctUntilChanged PURE_IMPORTS_END */ -function distinctUntilKeyChanged(key, compare) { - return distinctUntilChanged(function (x, y) { return compare ? compare(x[key], y[key]) : x[key] === y[key]; }); -} - -/** PURE_IMPORTS_START tslib,_util_EmptyError,_Subscriber PURE_IMPORTS_END */ -function throwIfEmpty(errorFactory) { - if (errorFactory === void 0) { - errorFactory = defaultErrorFactory; - } - return function (source) { - return source.lift(new ThrowIfEmptyOperator(errorFactory)); - }; -} -var ThrowIfEmptyOperator = /*@__PURE__*/ (function () { - function ThrowIfEmptyOperator(errorFactory) { - this.errorFactory = errorFactory; - } - ThrowIfEmptyOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ThrowIfEmptySubscriber(subscriber, this.errorFactory)); - }; - return ThrowIfEmptyOperator; -}()); -var ThrowIfEmptySubscriber = /*@__PURE__*/ (function (_super) { - __extends(ThrowIfEmptySubscriber, _super); - function ThrowIfEmptySubscriber(destination, errorFactory) { - var _this = _super.call(this, destination) || this; - _this.errorFactory = errorFactory; - _this.hasValue = false; - return _this; - } - ThrowIfEmptySubscriber.prototype._next = function (value) { - this.hasValue = true; - this.destination.next(value); - }; - ThrowIfEmptySubscriber.prototype._complete = function () { - if (!this.hasValue) { - var err = void 0; - try { - err = this.errorFactory(); - } - catch (e) { - err = e; - } - this.destination.error(err); - } - else { - return this.destination.complete(); - } - }; - return ThrowIfEmptySubscriber; -}(Subscriber)); -function defaultErrorFactory() { - return new EmptyError(); -} - -/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */ -function take(count) { - return function (source) { - if (count === 0) { - return empty$1(); - } - else { - return source.lift(new TakeOperator(count)); - } - }; -} -var TakeOperator = /*@__PURE__*/ (function () { - function TakeOperator(total) { - this.total = total; - if (this.total < 0) { - throw new ArgumentOutOfRangeError; - } - } - TakeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TakeSubscriber(subscriber, this.total)); - }; - return TakeOperator; -}()); -var TakeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(TakeSubscriber, _super); - function TakeSubscriber(destination, total) { - var _this = _super.call(this, destination) || this; - _this.total = total; - _this.count = 0; - return _this; - } - TakeSubscriber.prototype._next = function (value) { - var total = this.total; - var count = ++this.count; - if (count <= total) { - this.destination.next(value); - if (count === total) { - this.destination.complete(); - this.unsubscribe(); - } - } - }; - return TakeSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _util_ArgumentOutOfRangeError,_filter,_throwIfEmpty,_defaultIfEmpty,_take PURE_IMPORTS_END */ -function elementAt(index, defaultValue) { - if (index < 0) { - throw new ArgumentOutOfRangeError(); - } - var hasDefaultValue = arguments.length >= 2; - return function (source) { - return source.pipe(filter(function (v, i) { return i === index; }), take(1), hasDefaultValue - ? defaultIfEmpty(defaultValue) - : throwIfEmpty(function () { return new ArgumentOutOfRangeError(); })); - }; -} - -/** PURE_IMPORTS_START _observable_concat,_observable_of PURE_IMPORTS_END */ -function endWith() { - var array = []; - for (var _i = 0; _i < arguments.length; _i++) { - array[_i] = arguments[_i]; - } - return function (source) { return concat$1(source, of.apply(void 0, array)); }; -} - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function every$1(predicate, thisArg) { - return function (source) { return source.lift(new EveryOperator(predicate, thisArg, source)); }; -} -var EveryOperator = /*@__PURE__*/ (function () { - function EveryOperator(predicate, thisArg, source) { - this.predicate = predicate; - this.thisArg = thisArg; - this.source = source; - } - EveryOperator.prototype.call = function (observer, source) { - return source.subscribe(new EverySubscriber(observer, this.predicate, this.thisArg, this.source)); - }; - return EveryOperator; -}()); -var EverySubscriber = /*@__PURE__*/ (function (_super) { - __extends(EverySubscriber, _super); - function EverySubscriber(destination, predicate, thisArg, source) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.thisArg = thisArg; - _this.source = source; - _this.index = 0; - _this.thisArg = thisArg || _this; - return _this; - } - EverySubscriber.prototype.notifyComplete = function (everyValueMatch) { - this.destination.next(everyValueMatch); - this.destination.complete(); - }; - EverySubscriber.prototype._next = function (value) { - var result = false; - try { - result = this.predicate.call(this.thisArg, value, this.index++, this.source); - } - catch (err) { - this.destination.error(err); - return; - } - if (!result) { - this.notifyComplete(false); - } - }; - EverySubscriber.prototype._complete = function () { - this.notifyComplete(true); - }; - return EverySubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function exhaust() { - return function (source) { return source.lift(new SwitchFirstOperator()); }; -} -var SwitchFirstOperator = /*@__PURE__*/ (function () { - function SwitchFirstOperator() { - } - SwitchFirstOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SwitchFirstSubscriber(subscriber)); - }; - return SwitchFirstOperator; -}()); -var SwitchFirstSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SwitchFirstSubscriber, _super); - function SwitchFirstSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.hasCompleted = false; - _this.hasSubscription = false; - return _this; - } - SwitchFirstSubscriber.prototype._next = function (value) { - if (!this.hasSubscription) { - this.hasSubscription = true; - this.add(innerSubscribe(value, new SimpleInnerSubscriber(this))); - } - }; - SwitchFirstSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (!this.hasSubscription) { - this.destination.complete(); - } - }; - SwitchFirstSubscriber.prototype.notifyComplete = function () { - this.hasSubscription = false; - if (this.hasCompleted) { - this.destination.complete(); - } - }; - return SwitchFirstSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */ -function exhaustMap(project, resultSelector) { - if (resultSelector) { - return function (source) { return source.pipe(exhaustMap(function (a, i) { return from(project(a, i)).pipe(map$1(function (b, ii) { return resultSelector(a, b, i, ii); })); })); }; - } - return function (source) { - return source.lift(new ExhaustMapOperator(project)); - }; -} -var ExhaustMapOperator = /*@__PURE__*/ (function () { - function ExhaustMapOperator(project) { - this.project = project; - } - ExhaustMapOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ExhaustMapSubscriber(subscriber, this.project)); - }; - return ExhaustMapOperator; -}()); -var ExhaustMapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ExhaustMapSubscriber, _super); - function ExhaustMapSubscriber(destination, project) { - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.hasSubscription = false; - _this.hasCompleted = false; - _this.index = 0; - return _this; - } - ExhaustMapSubscriber.prototype._next = function (value) { - if (!this.hasSubscription) { - this.tryNext(value); - } - }; - ExhaustMapSubscriber.prototype.tryNext = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (err) { - this.destination.error(err); - return; - } - this.hasSubscription = true; - this._innerSub(result); - }; - ExhaustMapSubscriber.prototype._innerSub = function (result) { - var innerSubscriber = new SimpleInnerSubscriber(this); - var destination = this.destination; - destination.add(innerSubscriber); - var innerSubscription = innerSubscribe(result, innerSubscriber); - if (innerSubscription !== innerSubscriber) { - destination.add(innerSubscription); - } - }; - ExhaustMapSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (!this.hasSubscription) { - this.destination.complete(); - } - this.unsubscribe(); - }; - ExhaustMapSubscriber.prototype.notifyNext = function (innerValue) { - this.destination.next(innerValue); - }; - ExhaustMapSubscriber.prototype.notifyError = function (err) { - this.destination.error(err); - }; - ExhaustMapSubscriber.prototype.notifyComplete = function () { - this.hasSubscription = false; - if (this.hasCompleted) { - this.destination.complete(); - } - }; - return ExhaustMapSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function expand(project, concurrent, scheduler) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - concurrent = (concurrent || 0) < 1 ? Number.POSITIVE_INFINITY : concurrent; - return function (source) { return source.lift(new ExpandOperator(project, concurrent, scheduler)); }; -} -var ExpandOperator = /*@__PURE__*/ (function () { - function ExpandOperator(project, concurrent, scheduler) { - this.project = project; - this.concurrent = concurrent; - this.scheduler = scheduler; - } - ExpandOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ExpandSubscriber(subscriber, this.project, this.concurrent, this.scheduler)); - }; - return ExpandOperator; -}()); -var ExpandSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ExpandSubscriber, _super); - function ExpandSubscriber(destination, project, concurrent, scheduler) { - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.concurrent = concurrent; - _this.scheduler = scheduler; - _this.index = 0; - _this.active = 0; - _this.hasCompleted = false; - if (concurrent < Number.POSITIVE_INFINITY) { - _this.buffer = []; - } - return _this; - } - ExpandSubscriber.dispatch = function (arg) { - var subscriber = arg.subscriber, result = arg.result, value = arg.value, index = arg.index; - subscriber.subscribeToProjection(result, value, index); - }; - ExpandSubscriber.prototype._next = function (value) { - var destination = this.destination; - if (destination.closed) { - this._complete(); - return; - } - var index = this.index++; - if (this.active < this.concurrent) { - destination.next(value); - try { - var project = this.project; - var result = project(value, index); - if (!this.scheduler) { - this.subscribeToProjection(result, value, index); - } - else { - var state = { subscriber: this, result: result, value: value, index: index }; - var destination_1 = this.destination; - destination_1.add(this.scheduler.schedule(ExpandSubscriber.dispatch, 0, state)); - } - } - catch (e) { - destination.error(e); - } - } - else { - this.buffer.push(value); - } - }; - ExpandSubscriber.prototype.subscribeToProjection = function (result, value, index) { - this.active++; - var destination = this.destination; - destination.add(innerSubscribe(result, new SimpleInnerSubscriber(this))); - }; - ExpandSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.hasCompleted && this.active === 0) { - this.destination.complete(); - } - this.unsubscribe(); - }; - ExpandSubscriber.prototype.notifyNext = function (innerValue) { - this._next(innerValue); - }; - ExpandSubscriber.prototype.notifyComplete = function () { - var buffer = this.buffer; - this.active--; - if (buffer && buffer.length > 0) { - this._next(buffer.shift()); - } - if (this.hasCompleted && this.active === 0) { - this.destination.complete(); - } - }; - return ExpandSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber,_Subscription PURE_IMPORTS_END */ -function finalize(callback) { - return function (source) { return source.lift(new FinallyOperator(callback)); }; -} -var FinallyOperator = /*@__PURE__*/ (function () { - function FinallyOperator(callback) { - this.callback = callback; - } - FinallyOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new FinallySubscriber(subscriber, this.callback)); - }; - return FinallyOperator; -}()); -var FinallySubscriber = /*@__PURE__*/ (function (_super) { - __extends(FinallySubscriber, _super); - function FinallySubscriber(destination, callback) { - var _this = _super.call(this, destination) || this; - _this.add(new Subscription(callback)); - return _this; - } - return FinallySubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function find(predicate, thisArg) { - if (typeof predicate !== 'function') { - throw new TypeError('predicate is not a function'); - } - return function (source) { return source.lift(new FindValueOperator(predicate, source, false, thisArg)); }; -} -var FindValueOperator = /*@__PURE__*/ (function () { - function FindValueOperator(predicate, source, yieldIndex, thisArg) { - this.predicate = predicate; - this.source = source; - this.yieldIndex = yieldIndex; - this.thisArg = thisArg; - } - FindValueOperator.prototype.call = function (observer, source) { - return source.subscribe(new FindValueSubscriber(observer, this.predicate, this.source, this.yieldIndex, this.thisArg)); - }; - return FindValueOperator; -}()); -var FindValueSubscriber = /*@__PURE__*/ (function (_super) { - __extends(FindValueSubscriber, _super); - function FindValueSubscriber(destination, predicate, source, yieldIndex, thisArg) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.source = source; - _this.yieldIndex = yieldIndex; - _this.thisArg = thisArg; - _this.index = 0; - return _this; - } - FindValueSubscriber.prototype.notifyComplete = function (value) { - var destination = this.destination; - destination.next(value); - destination.complete(); - this.unsubscribe(); - }; - FindValueSubscriber.prototype._next = function (value) { - var _a = this, predicate = _a.predicate, thisArg = _a.thisArg; - var index = this.index++; - try { - var result = predicate.call(thisArg || this, value, index, this.source); - if (result) { - this.notifyComplete(this.yieldIndex ? index : value); - } - } - catch (err) { - this.destination.error(err); - } - }; - FindValueSubscriber.prototype._complete = function () { - this.notifyComplete(this.yieldIndex ? -1 : undefined); - }; - return FindValueSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _operators_find PURE_IMPORTS_END */ -function findIndex(predicate, thisArg) { - return function (source) { return source.lift(new FindValueOperator(predicate, source, true, thisArg)); }; -} - -/** PURE_IMPORTS_START _util_EmptyError,_filter,_take,_defaultIfEmpty,_throwIfEmpty,_util_identity PURE_IMPORTS_END */ -function first(predicate, defaultValue) { - var hasDefaultValue = arguments.length >= 2; - return function (source) { return source.pipe(predicate ? filter(function (v, i) { return predicate(v, i, source); }) : identity$1, take(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError(); })); }; -} - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function ignoreElements() { - return function ignoreElementsOperatorFunction(source) { - return source.lift(new IgnoreElementsOperator()); - }; -} -var IgnoreElementsOperator = /*@__PURE__*/ (function () { - function IgnoreElementsOperator() { - } - IgnoreElementsOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new IgnoreElementsSubscriber(subscriber)); - }; - return IgnoreElementsOperator; -}()); -var IgnoreElementsSubscriber = /*@__PURE__*/ (function (_super) { - __extends(IgnoreElementsSubscriber, _super); - function IgnoreElementsSubscriber() { - return _super !== null && _super.apply(this, arguments) || this; - } - IgnoreElementsSubscriber.prototype._next = function (unused) { - }; - return IgnoreElementsSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function isEmpty$1() { - return function (source) { return source.lift(new IsEmptyOperator()); }; -} -var IsEmptyOperator = /*@__PURE__*/ (function () { - function IsEmptyOperator() { - } - IsEmptyOperator.prototype.call = function (observer, source) { - return source.subscribe(new IsEmptySubscriber(observer)); - }; - return IsEmptyOperator; -}()); -var IsEmptySubscriber = /*@__PURE__*/ (function (_super) { - __extends(IsEmptySubscriber, _super); - function IsEmptySubscriber(destination) { - return _super.call(this, destination) || this; - } - IsEmptySubscriber.prototype.notifyComplete = function (isEmpty) { - var destination = this.destination; - destination.next(isEmpty); - destination.complete(); - }; - IsEmptySubscriber.prototype._next = function (value) { - this.notifyComplete(false); - }; - IsEmptySubscriber.prototype._complete = function () { - this.notifyComplete(true); - }; - return IsEmptySubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError,_observable_empty PURE_IMPORTS_END */ -function takeLast(count) { - return function takeLastOperatorFunction(source) { - if (count === 0) { - return empty$1(); - } - else { - return source.lift(new TakeLastOperator(count)); - } - }; -} -var TakeLastOperator = /*@__PURE__*/ (function () { - function TakeLastOperator(total) { - this.total = total; - if (this.total < 0) { - throw new ArgumentOutOfRangeError; - } - } - TakeLastOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TakeLastSubscriber(subscriber, this.total)); - }; - return TakeLastOperator; -}()); -var TakeLastSubscriber = /*@__PURE__*/ (function (_super) { - __extends(TakeLastSubscriber, _super); - function TakeLastSubscriber(destination, total) { - var _this = _super.call(this, destination) || this; - _this.total = total; - _this.ring = new Array(); - _this.count = 0; - return _this; - } - TakeLastSubscriber.prototype._next = function (value) { - var ring = this.ring; - var total = this.total; - var count = this.count++; - if (ring.length < total) { - ring.push(value); - } - else { - var index = count % total; - ring[index] = value; - } - }; - TakeLastSubscriber.prototype._complete = function () { - var destination = this.destination; - var count = this.count; - if (count > 0) { - var total = this.count >= this.total ? this.total : this.count; - var ring = this.ring; - for (var i = 0; i < total; i++) { - var idx = (count++) % total; - destination.next(ring[idx]); - } - } - destination.complete(); - }; - return TakeLastSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _util_EmptyError,_filter,_takeLast,_throwIfEmpty,_defaultIfEmpty,_util_identity PURE_IMPORTS_END */ -function last(predicate, defaultValue) { - var hasDefaultValue = arguments.length >= 2; - return function (source) { return source.pipe(predicate ? filter(function (v, i) { return predicate(v, i, source); }) : identity$1, takeLast(1), hasDefaultValue ? defaultIfEmpty(defaultValue) : throwIfEmpty(function () { return new EmptyError(); })); }; -} - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function mapTo(value) { - return function (source) { return source.lift(new MapToOperator(value)); }; -} -var MapToOperator = /*@__PURE__*/ (function () { - function MapToOperator(value) { - this.value = value; - } - MapToOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new MapToSubscriber(subscriber, this.value)); - }; - return MapToOperator; -}()); -var MapToSubscriber = /*@__PURE__*/ (function (_super) { - __extends(MapToSubscriber, _super); - function MapToSubscriber(destination, value) { - var _this = _super.call(this, destination) || this; - _this.value = value; - return _this; - } - MapToSubscriber.prototype._next = function (x) { - this.destination.next(this.value); - }; - return MapToSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber,_Notification PURE_IMPORTS_END */ -function materialize() { - return function materializeOperatorFunction(source) { - return source.lift(new MaterializeOperator()); - }; -} -var MaterializeOperator = /*@__PURE__*/ (function () { - function MaterializeOperator() { - } - MaterializeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new MaterializeSubscriber(subscriber)); - }; - return MaterializeOperator; -}()); -var MaterializeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(MaterializeSubscriber, _super); - function MaterializeSubscriber(destination) { - return _super.call(this, destination) || this; - } - MaterializeSubscriber.prototype._next = function (value) { - this.destination.next(Notification.createNext(value)); - }; - MaterializeSubscriber.prototype._error = function (err) { - var destination = this.destination; - destination.next(Notification.createError(err)); - destination.complete(); - }; - MaterializeSubscriber.prototype._complete = function () { - var destination = this.destination; - destination.next(Notification.createComplete()); - destination.complete(); - }; - return MaterializeSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function scan(accumulator, seed) { - var hasSeed = false; - if (arguments.length >= 2) { - hasSeed = true; - } - return function scanOperatorFunction(source) { - return source.lift(new ScanOperator(accumulator, seed, hasSeed)); - }; -} -var ScanOperator = /*@__PURE__*/ (function () { - function ScanOperator(accumulator, seed, hasSeed) { - if (hasSeed === void 0) { - hasSeed = false; - } - this.accumulator = accumulator; - this.seed = seed; - this.hasSeed = hasSeed; - } - ScanOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ScanSubscriber(subscriber, this.accumulator, this.seed, this.hasSeed)); - }; - return ScanOperator; -}()); -var ScanSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ScanSubscriber, _super); - function ScanSubscriber(destination, accumulator, _seed, hasSeed) { - var _this = _super.call(this, destination) || this; - _this.accumulator = accumulator; - _this._seed = _seed; - _this.hasSeed = hasSeed; - _this.index = 0; - return _this; - } - Object.defineProperty(ScanSubscriber.prototype, "seed", { - get: function () { - return this._seed; - }, - set: function (value) { - this.hasSeed = true; - this._seed = value; - }, - enumerable: true, - configurable: true - }); - ScanSubscriber.prototype._next = function (value) { - if (!this.hasSeed) { - this.seed = value; - this.destination.next(value); - } - else { - return this._tryNext(value); - } - }; - ScanSubscriber.prototype._tryNext = function (value) { - var index = this.index++; - var result; - try { - result = this.accumulator(this.seed, value, index); - } - catch (err) { - this.destination.error(err); - } - this.seed = result; - this.destination.next(result); - }; - return ScanSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _scan,_takeLast,_defaultIfEmpty,_util_pipe PURE_IMPORTS_END */ -function reduce$1(accumulator, seed) { - if (arguments.length >= 2) { - return function reduceOperatorFunctionWithSeed(source) { - return pipe(scan(accumulator, seed), takeLast(1), defaultIfEmpty(seed))(source); - }; - } - return function reduceOperatorFunction(source) { - return pipe(scan(function (acc, value, index) { return accumulator(acc, value, index + 1); }), takeLast(1))(source); - }; -} - -/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ -function max(comparer) { - var max = (typeof comparer === 'function') - ? function (x, y) { return comparer(x, y) > 0 ? x : y; } - : function (x, y) { return x > y ? x : y; }; - return reduce$1(max); -} - -/** PURE_IMPORTS_START _observable_merge PURE_IMPORTS_END */ -function merge$1() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - return function (source) { return source.lift.call(merge.apply(void 0, [source].concat(observables))); }; -} - -/** PURE_IMPORTS_START _mergeMap PURE_IMPORTS_END */ -function mergeMapTo(innerObservable, resultSelector, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - if (typeof resultSelector === 'function') { - return mergeMap(function () { return innerObservable; }, resultSelector, concurrent); - } - if (typeof resultSelector === 'number') { - concurrent = resultSelector; - } - return mergeMap(function () { return innerObservable; }, concurrent); -} - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function mergeScan(accumulator, seed, concurrent) { - if (concurrent === void 0) { - concurrent = Number.POSITIVE_INFINITY; - } - return function (source) { return source.lift(new MergeScanOperator(accumulator, seed, concurrent)); }; -} -var MergeScanOperator = /*@__PURE__*/ (function () { - function MergeScanOperator(accumulator, seed, concurrent) { - this.accumulator = accumulator; - this.seed = seed; - this.concurrent = concurrent; - } - MergeScanOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new MergeScanSubscriber(subscriber, this.accumulator, this.seed, this.concurrent)); - }; - return MergeScanOperator; -}()); -var MergeScanSubscriber = /*@__PURE__*/ (function (_super) { - __extends(MergeScanSubscriber, _super); - function MergeScanSubscriber(destination, accumulator, acc, concurrent) { - var _this = _super.call(this, destination) || this; - _this.accumulator = accumulator; - _this.acc = acc; - _this.concurrent = concurrent; - _this.hasValue = false; - _this.hasCompleted = false; - _this.buffer = []; - _this.active = 0; - _this.index = 0; - return _this; - } - MergeScanSubscriber.prototype._next = function (value) { - if (this.active < this.concurrent) { - var index = this.index++; - var destination = this.destination; - var ish = void 0; - try { - var accumulator = this.accumulator; - ish = accumulator(this.acc, value, index); - } - catch (e) { - return destination.error(e); - } - this.active++; - this._innerSub(ish); - } - else { - this.buffer.push(value); - } - }; - MergeScanSubscriber.prototype._innerSub = function (ish) { - var innerSubscriber = new SimpleInnerSubscriber(this); - var destination = this.destination; - destination.add(innerSubscriber); - var innerSubscription = innerSubscribe(ish, innerSubscriber); - if (innerSubscription !== innerSubscriber) { - destination.add(innerSubscription); - } - }; - MergeScanSubscriber.prototype._complete = function () { - this.hasCompleted = true; - if (this.active === 0 && this.buffer.length === 0) { - if (this.hasValue === false) { - this.destination.next(this.acc); - } - this.destination.complete(); - } - this.unsubscribe(); - }; - MergeScanSubscriber.prototype.notifyNext = function (innerValue) { - var destination = this.destination; - this.acc = innerValue; - this.hasValue = true; - destination.next(innerValue); - }; - MergeScanSubscriber.prototype.notifyComplete = function () { - var buffer = this.buffer; - this.active--; - if (buffer.length > 0) { - this._next(buffer.shift()); - } - else if (this.active === 0 && this.hasCompleted) { - if (this.hasValue === false) { - this.destination.next(this.acc); - } - this.destination.complete(); - } - }; - return MergeScanSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ -function min(comparer) { - var min = (typeof comparer === 'function') - ? function (x, y) { return comparer(x, y) < 0 ? x : y; } - : function (x, y) { return x < y ? x : y; }; - return reduce$1(min); -} - -/** PURE_IMPORTS_START _observable_ConnectableObservable PURE_IMPORTS_END */ -function multicast(subjectOrSubjectFactory, selector) { - return function multicastOperatorFunction(source) { - var subjectFactory; - if (typeof subjectOrSubjectFactory === 'function') { - subjectFactory = subjectOrSubjectFactory; - } - else { - subjectFactory = function subjectFactory() { - return subjectOrSubjectFactory; - }; - } - if (typeof selector === 'function') { - return source.lift(new MulticastOperator(subjectFactory, selector)); - } - var connectable = Object.create(source, connectableObservableDescriptor); - connectable.source = source; - connectable.subjectFactory = subjectFactory; - return connectable; - }; -} -var MulticastOperator = /*@__PURE__*/ (function () { - function MulticastOperator(subjectFactory, selector) { - this.subjectFactory = subjectFactory; - this.selector = selector; - } - MulticastOperator.prototype.call = function (subscriber, source) { - var selector = this.selector; - var subject = this.subjectFactory(); - var subscription = selector(subject).subscribe(subscriber); - subscription.add(source.subscribe(subject)); - return subscription; - }; - return MulticastOperator; -}()); - -/** PURE_IMPORTS_START tslib,_observable_from,_util_isArray,_innerSubscribe PURE_IMPORTS_END */ -function onErrorResumeNext$1() { - var nextSources = []; - for (var _i = 0; _i < arguments.length; _i++) { - nextSources[_i] = arguments[_i]; - } - if (nextSources.length === 1 && isArray$1(nextSources[0])) { - nextSources = nextSources[0]; - } - return function (source) { return source.lift(new OnErrorResumeNextOperator(nextSources)); }; -} -var OnErrorResumeNextOperator = /*@__PURE__*/ (function () { - function OnErrorResumeNextOperator(nextSources) { - this.nextSources = nextSources; - } - OnErrorResumeNextOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new OnErrorResumeNextSubscriber(subscriber, this.nextSources)); - }; - return OnErrorResumeNextOperator; -}()); -var OnErrorResumeNextSubscriber = /*@__PURE__*/ (function (_super) { - __extends(OnErrorResumeNextSubscriber, _super); - function OnErrorResumeNextSubscriber(destination, nextSources) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - _this.nextSources = nextSources; - return _this; - } - OnErrorResumeNextSubscriber.prototype.notifyError = function () { - this.subscribeToNextSource(); - }; - OnErrorResumeNextSubscriber.prototype.notifyComplete = function () { - this.subscribeToNextSource(); - }; - OnErrorResumeNextSubscriber.prototype._error = function (err) { - this.subscribeToNextSource(); - this.unsubscribe(); - }; - OnErrorResumeNextSubscriber.prototype._complete = function () { - this.subscribeToNextSource(); - this.unsubscribe(); - }; - OnErrorResumeNextSubscriber.prototype.subscribeToNextSource = function () { - var next = this.nextSources.shift(); - if (!!next) { - var innerSubscriber = new SimpleInnerSubscriber(this); - var destination = this.destination; - destination.add(innerSubscriber); - var innerSubscription = innerSubscribe(next, innerSubscriber); - if (innerSubscription !== innerSubscriber) { - destination.add(innerSubscription); - } - } - else { - this.destination.complete(); - } - }; - return OnErrorResumeNextSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function pairwise() { - return function (source) { return source.lift(new PairwiseOperator()); }; -} -var PairwiseOperator = /*@__PURE__*/ (function () { - function PairwiseOperator() { - } - PairwiseOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new PairwiseSubscriber(subscriber)); - }; - return PairwiseOperator; -}()); -var PairwiseSubscriber = /*@__PURE__*/ (function (_super) { - __extends(PairwiseSubscriber, _super); - function PairwiseSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.hasPrev = false; - return _this; - } - PairwiseSubscriber.prototype._next = function (value) { - var pair; - if (this.hasPrev) { - pair = [this.prev, value]; - } - else { - this.hasPrev = true; - } - this.prev = value; - if (pair) { - this.destination.next(pair); - } - }; - return PairwiseSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _util_not,_filter PURE_IMPORTS_END */ -function partition$1(predicate, thisArg) { - return function (source) { - return [ - filter(predicate, thisArg)(source), - filter(not(predicate, thisArg))(source) - ]; - }; -} - -/** PURE_IMPORTS_START _map PURE_IMPORTS_END */ -function pluck() { - var properties = []; - for (var _i = 0; _i < arguments.length; _i++) { - properties[_i] = arguments[_i]; - } - var length = properties.length; - if (length === 0) { - throw new Error('list of properties cannot be empty.'); - } - return function (source) { return map$1(plucker(properties, length))(source); }; -} -function plucker(props, length) { - var mapper = function (x) { - var currentProp = x; - for (var i = 0; i < length; i++) { - var p = currentProp != null ? currentProp[props[i]] : undefined; - if (p !== void 0) { - currentProp = p; - } - else { - return undefined; - } - } - return currentProp; - }; - return mapper; -} - -/** PURE_IMPORTS_START _Subject,_multicast PURE_IMPORTS_END */ -function publish(selector) { - return selector ? - multicast(function () { return new Subject(); }, selector) : - multicast(new Subject()); -} - -/** PURE_IMPORTS_START _BehaviorSubject,_multicast PURE_IMPORTS_END */ -function publishBehavior(value) { - return function (source) { return multicast(new BehaviorSubject(value))(source); }; -} - -/** PURE_IMPORTS_START _AsyncSubject,_multicast PURE_IMPORTS_END */ -function publishLast() { - return function (source) { return multicast(new AsyncSubject())(source); }; -} - -/** PURE_IMPORTS_START _ReplaySubject,_multicast PURE_IMPORTS_END */ -function publishReplay(bufferSize, windowTime, selectorOrScheduler, scheduler) { - if (selectorOrScheduler && typeof selectorOrScheduler !== 'function') { - scheduler = selectorOrScheduler; - } - var selector = typeof selectorOrScheduler === 'function' ? selectorOrScheduler : undefined; - var subject = new ReplaySubject(bufferSize, windowTime, scheduler); - return function (source) { return multicast(function () { return subject; }, selector)(source); }; -} - -/** PURE_IMPORTS_START _util_isArray,_observable_race PURE_IMPORTS_END */ -function race$1() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - return function raceOperatorFunction(source) { - if (observables.length === 1 && isArray$1(observables[0])) { - observables = observables[0]; - } - return source.lift.call(race.apply(void 0, [source].concat(observables))); - }; -} - -/** PURE_IMPORTS_START tslib,_Subscriber,_observable_empty PURE_IMPORTS_END */ -function repeat(count) { - if (count === void 0) { - count = -1; - } - return function (source) { - if (count === 0) { - return empty$1(); - } - else if (count < 0) { - return source.lift(new RepeatOperator(-1, source)); - } - else { - return source.lift(new RepeatOperator(count - 1, source)); - } - }; -} -var RepeatOperator = /*@__PURE__*/ (function () { - function RepeatOperator(count, source) { - this.count = count; - this.source = source; - } - RepeatOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RepeatSubscriber(subscriber, this.count, this.source)); - }; - return RepeatOperator; -}()); -var RepeatSubscriber = /*@__PURE__*/ (function (_super) { - __extends(RepeatSubscriber, _super); - function RepeatSubscriber(destination, count, source) { - var _this = _super.call(this, destination) || this; - _this.count = count; - _this.source = source; - return _this; - } - RepeatSubscriber.prototype.complete = function () { - if (!this.isStopped) { - var _a = this, source = _a.source, count = _a.count; - if (count === 0) { - return _super.prototype.complete.call(this); - } - else if (count > -1) { - this.count = count - 1; - } - source.subscribe(this._unsubscribeAndRecycle()); - } - }; - return RepeatSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subject,_innerSubscribe PURE_IMPORTS_END */ -function repeatWhen(notifier) { - return function (source) { return source.lift(new RepeatWhenOperator(notifier)); }; -} -var RepeatWhenOperator = /*@__PURE__*/ (function () { - function RepeatWhenOperator(notifier) { - this.notifier = notifier; - } - RepeatWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RepeatWhenSubscriber(subscriber, this.notifier, source)); - }; - return RepeatWhenOperator; -}()); -var RepeatWhenSubscriber = /*@__PURE__*/ (function (_super) { - __extends(RepeatWhenSubscriber, _super); - function RepeatWhenSubscriber(destination, notifier, source) { - var _this = _super.call(this, destination) || this; - _this.notifier = notifier; - _this.source = source; - _this.sourceIsBeingSubscribedTo = true; - return _this; - } - RepeatWhenSubscriber.prototype.notifyNext = function () { - this.sourceIsBeingSubscribedTo = true; - this.source.subscribe(this); - }; - RepeatWhenSubscriber.prototype.notifyComplete = function () { - if (this.sourceIsBeingSubscribedTo === false) { - return _super.prototype.complete.call(this); - } - }; - RepeatWhenSubscriber.prototype.complete = function () { - this.sourceIsBeingSubscribedTo = false; - if (!this.isStopped) { - if (!this.retries) { - this.subscribeToRetries(); - } - if (!this.retriesSubscription || this.retriesSubscription.closed) { - return _super.prototype.complete.call(this); - } - this._unsubscribeAndRecycle(); - this.notifications.next(undefined); - } - }; - RepeatWhenSubscriber.prototype._unsubscribe = function () { - var _a = this, notifications = _a.notifications, retriesSubscription = _a.retriesSubscription; - if (notifications) { - notifications.unsubscribe(); - this.notifications = undefined; - } - if (retriesSubscription) { - retriesSubscription.unsubscribe(); - this.retriesSubscription = undefined; - } - this.retries = undefined; - }; - RepeatWhenSubscriber.prototype._unsubscribeAndRecycle = function () { - var _unsubscribe = this._unsubscribe; - this._unsubscribe = null; - _super.prototype._unsubscribeAndRecycle.call(this); - this._unsubscribe = _unsubscribe; - return this; - }; - RepeatWhenSubscriber.prototype.subscribeToRetries = function () { - this.notifications = new Subject(); - var retries; - try { - var notifier = this.notifier; - retries = notifier(this.notifications); - } - catch (e) { - return _super.prototype.complete.call(this); - } - this.retries = retries; - this.retriesSubscription = innerSubscribe(retries, new SimpleInnerSubscriber(this)); - }; - return RepeatWhenSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function retry(count) { - if (count === void 0) { - count = -1; - } - return function (source) { return source.lift(new RetryOperator(count, source)); }; -} -var RetryOperator = /*@__PURE__*/ (function () { - function RetryOperator(count, source) { - this.count = count; - this.source = source; - } - RetryOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RetrySubscriber(subscriber, this.count, this.source)); - }; - return RetryOperator; -}()); -var RetrySubscriber = /*@__PURE__*/ (function (_super) { - __extends(RetrySubscriber, _super); - function RetrySubscriber(destination, count, source) { - var _this = _super.call(this, destination) || this; - _this.count = count; - _this.source = source; - return _this; - } - RetrySubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var _a = this, source = _a.source, count = _a.count; - if (count === 0) { - return _super.prototype.error.call(this, err); - } - else if (count > -1) { - this.count = count - 1; - } - source.subscribe(this._unsubscribeAndRecycle()); - } - }; - return RetrySubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subject,_innerSubscribe PURE_IMPORTS_END */ -function retryWhen(notifier) { - return function (source) { return source.lift(new RetryWhenOperator(notifier, source)); }; -} -var RetryWhenOperator = /*@__PURE__*/ (function () { - function RetryWhenOperator(notifier, source) { - this.notifier = notifier; - this.source = source; - } - RetryWhenOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new RetryWhenSubscriber(subscriber, this.notifier, this.source)); - }; - return RetryWhenOperator; -}()); -var RetryWhenSubscriber = /*@__PURE__*/ (function (_super) { - __extends(RetryWhenSubscriber, _super); - function RetryWhenSubscriber(destination, notifier, source) { - var _this = _super.call(this, destination) || this; - _this.notifier = notifier; - _this.source = source; - return _this; - } - RetryWhenSubscriber.prototype.error = function (err) { - if (!this.isStopped) { - var errors = this.errors; - var retries = this.retries; - var retriesSubscription = this.retriesSubscription; - if (!retries) { - errors = new Subject(); - try { - var notifier = this.notifier; - retries = notifier(errors); - } - catch (e) { - return _super.prototype.error.call(this, e); - } - retriesSubscription = innerSubscribe(retries, new SimpleInnerSubscriber(this)); - } - else { - this.errors = undefined; - this.retriesSubscription = undefined; - } - this._unsubscribeAndRecycle(); - this.errors = errors; - this.retries = retries; - this.retriesSubscription = retriesSubscription; - errors.next(err); - } - }; - RetryWhenSubscriber.prototype._unsubscribe = function () { - var _a = this, errors = _a.errors, retriesSubscription = _a.retriesSubscription; - if (errors) { - errors.unsubscribe(); - this.errors = undefined; - } - if (retriesSubscription) { - retriesSubscription.unsubscribe(); - this.retriesSubscription = undefined; - } - this.retries = undefined; - }; - RetryWhenSubscriber.prototype.notifyNext = function () { - var _unsubscribe = this._unsubscribe; - this._unsubscribe = null; - this._unsubscribeAndRecycle(); - this._unsubscribe = _unsubscribe; - this.source.subscribe(this); - }; - return RetryWhenSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function sample(notifier) { - return function (source) { return source.lift(new SampleOperator(notifier)); }; -} -var SampleOperator = /*@__PURE__*/ (function () { - function SampleOperator(notifier) { - this.notifier = notifier; - } - SampleOperator.prototype.call = function (subscriber, source) { - var sampleSubscriber = new SampleSubscriber(subscriber); - var subscription = source.subscribe(sampleSubscriber); - subscription.add(innerSubscribe(this.notifier, new SimpleInnerSubscriber(sampleSubscriber))); - return subscription; - }; - return SampleOperator; -}()); -var SampleSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SampleSubscriber, _super); - function SampleSubscriber() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this.hasValue = false; - return _this; - } - SampleSubscriber.prototype._next = function (value) { - this.value = value; - this.hasValue = true; - }; - SampleSubscriber.prototype.notifyNext = function () { - this.emitValue(); - }; - SampleSubscriber.prototype.notifyComplete = function () { - this.emitValue(); - }; - SampleSubscriber.prototype.emitValue = function () { - if (this.hasValue) { - this.hasValue = false; - this.destination.next(this.value); - } - }; - return SampleSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async PURE_IMPORTS_END */ -function sampleTime(period, scheduler) { - if (scheduler === void 0) { - scheduler = async; - } - return function (source) { return source.lift(new SampleTimeOperator(period, scheduler)); }; -} -var SampleTimeOperator = /*@__PURE__*/ (function () { - function SampleTimeOperator(period, scheduler) { - this.period = period; - this.scheduler = scheduler; - } - SampleTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SampleTimeSubscriber(subscriber, this.period, this.scheduler)); - }; - return SampleTimeOperator; -}()); -var SampleTimeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SampleTimeSubscriber, _super); - function SampleTimeSubscriber(destination, period, scheduler) { - var _this = _super.call(this, destination) || this; - _this.period = period; - _this.scheduler = scheduler; - _this.hasValue = false; - _this.add(scheduler.schedule(dispatchNotification, period, { subscriber: _this, period: period })); - return _this; - } - SampleTimeSubscriber.prototype._next = function (value) { - this.lastValue = value; - this.hasValue = true; - }; - SampleTimeSubscriber.prototype.notifyNext = function () { - if (this.hasValue) { - this.hasValue = false; - this.destination.next(this.lastValue); - } - }; - return SampleTimeSubscriber; -}(Subscriber)); -function dispatchNotification(state) { - var subscriber = state.subscriber, period = state.period; - subscriber.notifyNext(); - this.schedule(state, period); -} - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function sequenceEqual(compareTo, comparator) { - return function (source) { return source.lift(new SequenceEqualOperator(compareTo, comparator)); }; -} -var SequenceEqualOperator = /*@__PURE__*/ (function () { - function SequenceEqualOperator(compareTo, comparator) { - this.compareTo = compareTo; - this.comparator = comparator; - } - SequenceEqualOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SequenceEqualSubscriber(subscriber, this.compareTo, this.comparator)); - }; - return SequenceEqualOperator; -}()); -var SequenceEqualSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SequenceEqualSubscriber, _super); - function SequenceEqualSubscriber(destination, compareTo, comparator) { - var _this = _super.call(this, destination) || this; - _this.compareTo = compareTo; - _this.comparator = comparator; - _this._a = []; - _this._b = []; - _this._oneComplete = false; - _this.destination.add(compareTo.subscribe(new SequenceEqualCompareToSubscriber(destination, _this))); - return _this; - } - SequenceEqualSubscriber.prototype._next = function (value) { - if (this._oneComplete && this._b.length === 0) { - this.emit(false); - } - else { - this._a.push(value); - this.checkValues(); - } - }; - SequenceEqualSubscriber.prototype._complete = function () { - if (this._oneComplete) { - this.emit(this._a.length === 0 && this._b.length === 0); - } - else { - this._oneComplete = true; - } - this.unsubscribe(); - }; - SequenceEqualSubscriber.prototype.checkValues = function () { - var _c = this, _a = _c._a, _b = _c._b, comparator = _c.comparator; - while (_a.length > 0 && _b.length > 0) { - var a = _a.shift(); - var b = _b.shift(); - var areEqual = false; - try { - areEqual = comparator ? comparator(a, b) : a === b; - } - catch (e) { - this.destination.error(e); - } - if (!areEqual) { - this.emit(false); - } - } - }; - SequenceEqualSubscriber.prototype.emit = function (value) { - var destination = this.destination; - destination.next(value); - destination.complete(); - }; - SequenceEqualSubscriber.prototype.nextB = function (value) { - if (this._oneComplete && this._a.length === 0) { - this.emit(false); - } - else { - this._b.push(value); - this.checkValues(); - } - }; - SequenceEqualSubscriber.prototype.completeB = function () { - if (this._oneComplete) { - this.emit(this._a.length === 0 && this._b.length === 0); - } - else { - this._oneComplete = true; - } - }; - return SequenceEqualSubscriber; -}(Subscriber)); -var SequenceEqualCompareToSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SequenceEqualCompareToSubscriber, _super); - function SequenceEqualCompareToSubscriber(destination, parent) { - var _this = _super.call(this, destination) || this; - _this.parent = parent; - return _this; - } - SequenceEqualCompareToSubscriber.prototype._next = function (value) { - this.parent.nextB(value); - }; - SequenceEqualCompareToSubscriber.prototype._error = function (err) { - this.parent.error(err); - this.unsubscribe(); - }; - SequenceEqualCompareToSubscriber.prototype._complete = function () { - this.parent.completeB(); - this.unsubscribe(); - }; - return SequenceEqualCompareToSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _multicast,_refCount,_Subject PURE_IMPORTS_END */ -function shareSubjectFactory() { - return new Subject(); -} -function share() { - return function (source) { return refCount()(multicast(shareSubjectFactory)(source)); }; -} - -/** PURE_IMPORTS_START _ReplaySubject PURE_IMPORTS_END */ -function shareReplay(configOrBufferSize, windowTime, scheduler) { - var config; - if (configOrBufferSize && typeof configOrBufferSize === 'object') { - config = configOrBufferSize; - } - else { - config = { - bufferSize: configOrBufferSize, - windowTime: windowTime, - refCount: false, - scheduler: scheduler, - }; - } - return function (source) { return source.lift(shareReplayOperator(config)); }; -} -function shareReplayOperator(_a) { - var _b = _a.bufferSize, bufferSize = _b === void 0 ? Number.POSITIVE_INFINITY : _b, _c = _a.windowTime, windowTime = _c === void 0 ? Number.POSITIVE_INFINITY : _c, useRefCount = _a.refCount, scheduler = _a.scheduler; - var subject; - var refCount = 0; - var subscription; - var hasError = false; - var isComplete = false; - return function shareReplayOperation(source) { - refCount++; - var innerSub; - if (!subject || hasError) { - hasError = false; - subject = new ReplaySubject(bufferSize, windowTime, scheduler); - innerSub = subject.subscribe(this); - subscription = source.subscribe({ - next: function (value) { - subject.next(value); - }, - error: function (err) { - hasError = true; - subject.error(err); - }, - complete: function () { - isComplete = true; - subscription = undefined; - subject.complete(); - }, - }); - if (isComplete) { - subscription = undefined; - } - } - else { - innerSub = subject.subscribe(this); - } - this.add(function () { - refCount--; - innerSub.unsubscribe(); - innerSub = undefined; - if (subscription && !isComplete && useRefCount && refCount === 0) { - subscription.unsubscribe(); - subscription = undefined; - subject = undefined; - } - }); - }; -} - -/** PURE_IMPORTS_START tslib,_Subscriber,_util_EmptyError PURE_IMPORTS_END */ -function single(predicate) { - return function (source) { return source.lift(new SingleOperator(predicate, source)); }; -} -var SingleOperator = /*@__PURE__*/ (function () { - function SingleOperator(predicate, source) { - this.predicate = predicate; - this.source = source; - } - SingleOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SingleSubscriber(subscriber, this.predicate, this.source)); - }; - return SingleOperator; -}()); -var SingleSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SingleSubscriber, _super); - function SingleSubscriber(destination, predicate, source) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.source = source; - _this.seenValue = false; - _this.index = 0; - return _this; - } - SingleSubscriber.prototype.applySingleValue = function (value) { - if (this.seenValue) { - this.destination.error('Sequence contains more than one element'); - } - else { - this.seenValue = true; - this.singleValue = value; - } - }; - SingleSubscriber.prototype._next = function (value) { - var index = this.index++; - if (this.predicate) { - this.tryNext(value, index); - } - else { - this.applySingleValue(value); - } - }; - SingleSubscriber.prototype.tryNext = function (value, index) { - try { - if (this.predicate(value, index, this.source)) { - this.applySingleValue(value); - } - } - catch (err) { - this.destination.error(err); - } - }; - SingleSubscriber.prototype._complete = function () { - var destination = this.destination; - if (this.index > 0) { - destination.next(this.seenValue ? this.singleValue : undefined); - destination.complete(); - } - else { - destination.error(new EmptyError); - } - }; - return SingleSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function skip(count) { - return function (source) { return source.lift(new SkipOperator(count)); }; -} -var SkipOperator = /*@__PURE__*/ (function () { - function SkipOperator(total) { - this.total = total; - } - SkipOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SkipSubscriber(subscriber, this.total)); - }; - return SkipOperator; -}()); -var SkipSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SkipSubscriber, _super); - function SkipSubscriber(destination, total) { - var _this = _super.call(this, destination) || this; - _this.total = total; - _this.count = 0; - return _this; - } - SkipSubscriber.prototype._next = function (x) { - if (++this.count > this.total) { - this.destination.next(x); - } - }; - return SkipSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber,_util_ArgumentOutOfRangeError PURE_IMPORTS_END */ -function skipLast(count) { - return function (source) { return source.lift(new SkipLastOperator(count)); }; -} -var SkipLastOperator = /*@__PURE__*/ (function () { - function SkipLastOperator(_skipCount) { - this._skipCount = _skipCount; - if (this._skipCount < 0) { - throw new ArgumentOutOfRangeError; - } - } - SkipLastOperator.prototype.call = function (subscriber, source) { - if (this._skipCount === 0) { - return source.subscribe(new Subscriber(subscriber)); - } - else { - return source.subscribe(new SkipLastSubscriber(subscriber, this._skipCount)); - } - }; - return SkipLastOperator; -}()); -var SkipLastSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SkipLastSubscriber, _super); - function SkipLastSubscriber(destination, _skipCount) { - var _this = _super.call(this, destination) || this; - _this._skipCount = _skipCount; - _this._count = 0; - _this._ring = new Array(_skipCount); - return _this; - } - SkipLastSubscriber.prototype._next = function (value) { - var skipCount = this._skipCount; - var count = this._count++; - if (count < skipCount) { - this._ring[count] = value; - } - else { - var currentIndex = count % skipCount; - var ring = this._ring; - var oldValue = ring[currentIndex]; - ring[currentIndex] = value; - this.destination.next(oldValue); - } - }; - return SkipLastSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function skipUntil(notifier) { - return function (source) { return source.lift(new SkipUntilOperator(notifier)); }; -} -var SkipUntilOperator = /*@__PURE__*/ (function () { - function SkipUntilOperator(notifier) { - this.notifier = notifier; - } - SkipUntilOperator.prototype.call = function (destination, source) { - return source.subscribe(new SkipUntilSubscriber(destination, this.notifier)); - }; - return SkipUntilOperator; -}()); -var SkipUntilSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SkipUntilSubscriber, _super); - function SkipUntilSubscriber(destination, notifier) { - var _this = _super.call(this, destination) || this; - _this.hasValue = false; - var innerSubscriber = new SimpleInnerSubscriber(_this); - _this.add(innerSubscriber); - _this.innerSubscription = innerSubscriber; - var innerSubscription = innerSubscribe(notifier, innerSubscriber); - if (innerSubscription !== innerSubscriber) { - _this.add(innerSubscription); - _this.innerSubscription = innerSubscription; - } - return _this; - } - SkipUntilSubscriber.prototype._next = function (value) { - if (this.hasValue) { - _super.prototype._next.call(this, value); - } - }; - SkipUntilSubscriber.prototype.notifyNext = function () { - this.hasValue = true; - if (this.innerSubscription) { - this.innerSubscription.unsubscribe(); - } - }; - SkipUntilSubscriber.prototype.notifyComplete = function () { - }; - return SkipUntilSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function skipWhile(predicate) { - return function (source) { return source.lift(new SkipWhileOperator(predicate)); }; -} -var SkipWhileOperator = /*@__PURE__*/ (function () { - function SkipWhileOperator(predicate) { - this.predicate = predicate; - } - SkipWhileOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SkipWhileSubscriber(subscriber, this.predicate)); - }; - return SkipWhileOperator; -}()); -var SkipWhileSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SkipWhileSubscriber, _super); - function SkipWhileSubscriber(destination, predicate) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.skipping = true; - _this.index = 0; - return _this; - } - SkipWhileSubscriber.prototype._next = function (value) { - var destination = this.destination; - if (this.skipping) { - this.tryCallPredicate(value); - } - if (!this.skipping) { - destination.next(value); - } - }; - SkipWhileSubscriber.prototype.tryCallPredicate = function (value) { - try { - var result = this.predicate(value, this.index++); - this.skipping = Boolean(result); - } - catch (err) { - this.destination.error(err); - } - }; - return SkipWhileSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START _observable_concat,_util_isScheduler PURE_IMPORTS_END */ -function startWith() { - var array = []; - for (var _i = 0; _i < arguments.length; _i++) { - array[_i] = arguments[_i]; - } - var scheduler = array[array.length - 1]; - if (isScheduler(scheduler)) { - array.pop(); - return function (source) { return concat$1(array, source, scheduler); }; - } - else { - return function (source) { return concat$1(array, source); }; - } -} - -/** PURE_IMPORTS_START tslib,_Observable,_scheduler_asap,_util_isNumeric PURE_IMPORTS_END */ -var SubscribeOnObservable = /*@__PURE__*/ (function (_super) { - __extends(SubscribeOnObservable, _super); - function SubscribeOnObservable(source, delayTime, scheduler) { - if (delayTime === void 0) { - delayTime = 0; - } - if (scheduler === void 0) { - scheduler = asap; - } - var _this = _super.call(this) || this; - _this.source = source; - _this.delayTime = delayTime; - _this.scheduler = scheduler; - if (!isNumeric(delayTime) || delayTime < 0) { - _this.delayTime = 0; - } - if (!scheduler || typeof scheduler.schedule !== 'function') { - _this.scheduler = asap; - } - return _this; - } - SubscribeOnObservable.create = function (source, delay, scheduler) { - if (delay === void 0) { - delay = 0; - } - if (scheduler === void 0) { - scheduler = asap; - } - return new SubscribeOnObservable(source, delay, scheduler); - }; - SubscribeOnObservable.dispatch = function (arg) { - var source = arg.source, subscriber = arg.subscriber; - return this.add(source.subscribe(subscriber)); - }; - SubscribeOnObservable.prototype._subscribe = function (subscriber) { - var delay = this.delayTime; - var source = this.source; - var scheduler = this.scheduler; - return scheduler.schedule(SubscribeOnObservable.dispatch, delay, { - source: source, subscriber: subscriber - }); - }; - return SubscribeOnObservable; -}(Observable)); - -/** PURE_IMPORTS_START _observable_SubscribeOnObservable PURE_IMPORTS_END */ -function subscribeOn(scheduler, delay) { - if (delay === void 0) { - delay = 0; - } - return function subscribeOnOperatorFunction(source) { - return source.lift(new SubscribeOnOperator(scheduler, delay)); - }; -} -var SubscribeOnOperator = /*@__PURE__*/ (function () { - function SubscribeOnOperator(scheduler, delay) { - this.scheduler = scheduler; - this.delay = delay; - } - SubscribeOnOperator.prototype.call = function (subscriber, source) { - return new SubscribeOnObservable(source, this.delay, this.scheduler).subscribe(subscriber); - }; - return SubscribeOnOperator; -}()); - -/** PURE_IMPORTS_START tslib,_map,_observable_from,_innerSubscribe PURE_IMPORTS_END */ -function switchMap(project, resultSelector) { - if (typeof resultSelector === 'function') { - return function (source) { return source.pipe(switchMap(function (a, i) { return from(project(a, i)).pipe(map$1(function (b, ii) { return resultSelector(a, b, i, ii); })); })); }; - } - return function (source) { return source.lift(new SwitchMapOperator(project)); }; -} -var SwitchMapOperator = /*@__PURE__*/ (function () { - function SwitchMapOperator(project) { - this.project = project; - } - SwitchMapOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new SwitchMapSubscriber(subscriber, this.project)); - }; - return SwitchMapOperator; -}()); -var SwitchMapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(SwitchMapSubscriber, _super); - function SwitchMapSubscriber(destination, project) { - var _this = _super.call(this, destination) || this; - _this.project = project; - _this.index = 0; - return _this; - } - SwitchMapSubscriber.prototype._next = function (value) { - var result; - var index = this.index++; - try { - result = this.project(value, index); - } - catch (error) { - this.destination.error(error); - return; - } - this._innerSub(result); - }; - SwitchMapSubscriber.prototype._innerSub = function (result) { - var innerSubscription = this.innerSubscription; - if (innerSubscription) { - innerSubscription.unsubscribe(); - } - var innerSubscriber = new SimpleInnerSubscriber(this); - var destination = this.destination; - destination.add(innerSubscriber); - this.innerSubscription = innerSubscribe(result, innerSubscriber); - if (this.innerSubscription !== innerSubscriber) { - destination.add(this.innerSubscription); - } - }; - SwitchMapSubscriber.prototype._complete = function () { - var innerSubscription = this.innerSubscription; - if (!innerSubscription || innerSubscription.closed) { - _super.prototype._complete.call(this); - } - this.unsubscribe(); - }; - SwitchMapSubscriber.prototype._unsubscribe = function () { - this.innerSubscription = undefined; - }; - SwitchMapSubscriber.prototype.notifyComplete = function () { - this.innerSubscription = undefined; - if (this.isStopped) { - _super.prototype._complete.call(this); - } - }; - SwitchMapSubscriber.prototype.notifyNext = function (innerValue) { - this.destination.next(innerValue); - }; - return SwitchMapSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START _switchMap,_util_identity PURE_IMPORTS_END */ -function switchAll() { - return switchMap(identity$1); -} - -/** PURE_IMPORTS_START _switchMap PURE_IMPORTS_END */ -function switchMapTo(innerObservable, resultSelector) { - return resultSelector ? switchMap(function () { return innerObservable; }, resultSelector) : switchMap(function () { return innerObservable; }); -} - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -function takeUntil(notifier) { - return function (source) { return source.lift(new TakeUntilOperator(notifier)); }; -} -var TakeUntilOperator = /*@__PURE__*/ (function () { - function TakeUntilOperator(notifier) { - this.notifier = notifier; - } - TakeUntilOperator.prototype.call = function (subscriber, source) { - var takeUntilSubscriber = new TakeUntilSubscriber(subscriber); - var notifierSubscription = innerSubscribe(this.notifier, new SimpleInnerSubscriber(takeUntilSubscriber)); - if (notifierSubscription && !takeUntilSubscriber.seenValue) { - takeUntilSubscriber.add(notifierSubscription); - return source.subscribe(takeUntilSubscriber); - } - return takeUntilSubscriber; - }; - return TakeUntilOperator; -}()); -var TakeUntilSubscriber = /*@__PURE__*/ (function (_super) { - __extends(TakeUntilSubscriber, _super); - function TakeUntilSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.seenValue = false; - return _this; - } - TakeUntilSubscriber.prototype.notifyNext = function () { - this.seenValue = true; - this.complete(); - }; - TakeUntilSubscriber.prototype.notifyComplete = function () { - }; - return TakeUntilSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber PURE_IMPORTS_END */ -function takeWhile(predicate, inclusive) { - if (inclusive === void 0) { - inclusive = false; - } - return function (source) { - return source.lift(new TakeWhileOperator(predicate, inclusive)); - }; -} -var TakeWhileOperator = /*@__PURE__*/ (function () { - function TakeWhileOperator(predicate, inclusive) { - this.predicate = predicate; - this.inclusive = inclusive; - } - TakeWhileOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TakeWhileSubscriber(subscriber, this.predicate, this.inclusive)); - }; - return TakeWhileOperator; -}()); -var TakeWhileSubscriber = /*@__PURE__*/ (function (_super) { - __extends(TakeWhileSubscriber, _super); - function TakeWhileSubscriber(destination, predicate, inclusive) { - var _this = _super.call(this, destination) || this; - _this.predicate = predicate; - _this.inclusive = inclusive; - _this.index = 0; - return _this; - } - TakeWhileSubscriber.prototype._next = function (value) { - var destination = this.destination; - var result; - try { - result = this.predicate(value, this.index++); - } - catch (err) { - destination.error(err); - return; - } - this.nextOrComplete(value, result); - }; - TakeWhileSubscriber.prototype.nextOrComplete = function (value, predicateResult) { - var destination = this.destination; - if (Boolean(predicateResult)) { - destination.next(value); - } - else { - if (this.inclusive) { - destination.next(value); - } - destination.complete(); - } - }; - return TakeWhileSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber,_util_noop,_util_isFunction PURE_IMPORTS_END */ -function tap(nextOrObserver, error, complete) { - return function tapOperatorFunction(source) { - return source.lift(new DoOperator(nextOrObserver, error, complete)); - }; -} -var DoOperator = /*@__PURE__*/ (function () { - function DoOperator(nextOrObserver, error, complete) { - this.nextOrObserver = nextOrObserver; - this.error = error; - this.complete = complete; - } - DoOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TapSubscriber(subscriber, this.nextOrObserver, this.error, this.complete)); - }; - return DoOperator; -}()); -var TapSubscriber = /*@__PURE__*/ (function (_super) { - __extends(TapSubscriber, _super); - function TapSubscriber(destination, observerOrNext, error, complete) { - var _this = _super.call(this, destination) || this; - _this._tapNext = noop; - _this._tapError = noop; - _this._tapComplete = noop; - _this._tapError = error || noop; - _this._tapComplete = complete || noop; - if (isFunction$1(observerOrNext)) { - _this._context = _this; - _this._tapNext = observerOrNext; - } - else if (observerOrNext) { - _this._context = observerOrNext; - _this._tapNext = observerOrNext.next || noop; - _this._tapError = observerOrNext.error || noop; - _this._tapComplete = observerOrNext.complete || noop; - } - return _this; - } - TapSubscriber.prototype._next = function (value) { - try { - this._tapNext.call(this._context, value); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(value); - }; - TapSubscriber.prototype._error = function (err) { - try { - this._tapError.call(this._context, err); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.error(err); - }; - TapSubscriber.prototype._complete = function () { - try { - this._tapComplete.call(this._context); - } - catch (err) { - this.destination.error(err); - return; - } - return this.destination.complete(); - }; - return TapSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_innerSubscribe PURE_IMPORTS_END */ -var defaultThrottleConfig = { - leading: true, - trailing: false -}; -function throttle(durationSelector, config) { - if (config === void 0) { - config = defaultThrottleConfig; - } - return function (source) { return source.lift(new ThrottleOperator(durationSelector, !!config.leading, !!config.trailing)); }; -} -var ThrottleOperator = /*@__PURE__*/ (function () { - function ThrottleOperator(durationSelector, leading, trailing) { - this.durationSelector = durationSelector; - this.leading = leading; - this.trailing = trailing; - } - ThrottleOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ThrottleSubscriber(subscriber, this.durationSelector, this.leading, this.trailing)); - }; - return ThrottleOperator; -}()); -var ThrottleSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ThrottleSubscriber, _super); - function ThrottleSubscriber(destination, durationSelector, _leading, _trailing) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - _this.durationSelector = durationSelector; - _this._leading = _leading; - _this._trailing = _trailing; - _this._hasValue = false; - return _this; - } - ThrottleSubscriber.prototype._next = function (value) { - this._hasValue = true; - this._sendValue = value; - if (!this._throttled) { - if (this._leading) { - this.send(); - } - else { - this.throttle(value); - } - } - }; - ThrottleSubscriber.prototype.send = function () { - var _a = this, _hasValue = _a._hasValue, _sendValue = _a._sendValue; - if (_hasValue) { - this.destination.next(_sendValue); - this.throttle(_sendValue); - } - this._hasValue = false; - this._sendValue = undefined; - }; - ThrottleSubscriber.prototype.throttle = function (value) { - var duration = this.tryDurationSelector(value); - if (!!duration) { - this.add(this._throttled = innerSubscribe(duration, new SimpleInnerSubscriber(this))); - } - }; - ThrottleSubscriber.prototype.tryDurationSelector = function (value) { - try { - return this.durationSelector(value); - } - catch (err) { - this.destination.error(err); - return null; - } - }; - ThrottleSubscriber.prototype.throttlingDone = function () { - var _a = this, _throttled = _a._throttled, _trailing = _a._trailing; - if (_throttled) { - _throttled.unsubscribe(); - } - this._throttled = undefined; - if (_trailing) { - this.send(); - } - }; - ThrottleSubscriber.prototype.notifyNext = function () { - this.throttlingDone(); - }; - ThrottleSubscriber.prototype.notifyComplete = function () { - this.throttlingDone(); - }; - return ThrottleSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber,_scheduler_async,_throttle PURE_IMPORTS_END */ -function throttleTime(duration, scheduler, config) { - if (scheduler === void 0) { - scheduler = async; - } - if (config === void 0) { - config = defaultThrottleConfig; - } - return function (source) { return source.lift(new ThrottleTimeOperator(duration, scheduler, config.leading, config.trailing)); }; -} -var ThrottleTimeOperator = /*@__PURE__*/ (function () { - function ThrottleTimeOperator(duration, scheduler, leading, trailing) { - this.duration = duration; - this.scheduler = scheduler; - this.leading = leading; - this.trailing = trailing; - } - ThrottleTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new ThrottleTimeSubscriber(subscriber, this.duration, this.scheduler, this.leading, this.trailing)); - }; - return ThrottleTimeOperator; -}()); -var ThrottleTimeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(ThrottleTimeSubscriber, _super); - function ThrottleTimeSubscriber(destination, duration, scheduler, leading, trailing) { - var _this = _super.call(this, destination) || this; - _this.duration = duration; - _this.scheduler = scheduler; - _this.leading = leading; - _this.trailing = trailing; - _this._hasTrailingValue = false; - _this._trailingValue = null; - return _this; - } - ThrottleTimeSubscriber.prototype._next = function (value) { - if (this.throttled) { - if (this.trailing) { - this._trailingValue = value; - this._hasTrailingValue = true; - } - } - else { - this.add(this.throttled = this.scheduler.schedule(dispatchNext$3, this.duration, { subscriber: this })); - if (this.leading) { - this.destination.next(value); - } - else if (this.trailing) { - this._trailingValue = value; - this._hasTrailingValue = true; - } - } - }; - ThrottleTimeSubscriber.prototype._complete = function () { - if (this._hasTrailingValue) { - this.destination.next(this._trailingValue); - this.destination.complete(); - } - else { - this.destination.complete(); - } - }; - ThrottleTimeSubscriber.prototype.clearThrottle = function () { - var throttled = this.throttled; - if (throttled) { - if (this.trailing && this._hasTrailingValue) { - this.destination.next(this._trailingValue); - this._trailingValue = null; - this._hasTrailingValue = false; - } - throttled.unsubscribe(); - this.remove(throttled); - this.throttled = null; - } - }; - return ThrottleTimeSubscriber; -}(Subscriber)); -function dispatchNext$3(arg) { - var subscriber = arg.subscriber; - subscriber.clearThrottle(); -} - -/** PURE_IMPORTS_START _scheduler_async,_scan,_observable_defer,_map PURE_IMPORTS_END */ -function timeInterval(scheduler) { - if (scheduler === void 0) { - scheduler = async; - } - return function (source) { - return defer(function () { - return source.pipe(scan(function (_a, value) { - var current = _a.current; - return ({ value: value, current: scheduler.now(), last: current }); - }, { current: scheduler.now(), value: undefined, last: undefined }), map$1(function (_a) { - var current = _a.current, last = _a.last, value = _a.value; - return new TimeInterval(value, current - last); - })); - }); - }; -} -var TimeInterval = /*@__PURE__*/ (function () { - function TimeInterval(value, interval) { - this.value = value; - this.interval = interval; - } - return TimeInterval; -}()); - -/** PURE_IMPORTS_START tslib,_scheduler_async,_util_isDate,_innerSubscribe PURE_IMPORTS_END */ -function timeoutWith(due, withObservable, scheduler) { - if (scheduler === void 0) { - scheduler = async; - } - return function (source) { - var absoluteTimeout = isDate(due); - var waitFor = absoluteTimeout ? (+due - scheduler.now()) : Math.abs(due); - return source.lift(new TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler)); - }; -} -var TimeoutWithOperator = /*@__PURE__*/ (function () { - function TimeoutWithOperator(waitFor, absoluteTimeout, withObservable, scheduler) { - this.waitFor = waitFor; - this.absoluteTimeout = absoluteTimeout; - this.withObservable = withObservable; - this.scheduler = scheduler; - } - TimeoutWithOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new TimeoutWithSubscriber(subscriber, this.absoluteTimeout, this.waitFor, this.withObservable, this.scheduler)); - }; - return TimeoutWithOperator; -}()); -var TimeoutWithSubscriber = /*@__PURE__*/ (function (_super) { - __extends(TimeoutWithSubscriber, _super); - function TimeoutWithSubscriber(destination, absoluteTimeout, waitFor, withObservable, scheduler) { - var _this = _super.call(this, destination) || this; - _this.absoluteTimeout = absoluteTimeout; - _this.waitFor = waitFor; - _this.withObservable = withObservable; - _this.scheduler = scheduler; - _this.scheduleTimeout(); - return _this; - } - TimeoutWithSubscriber.dispatchTimeout = function (subscriber) { - var withObservable = subscriber.withObservable; - subscriber._unsubscribeAndRecycle(); - subscriber.add(innerSubscribe(withObservable, new SimpleInnerSubscriber(subscriber))); - }; - TimeoutWithSubscriber.prototype.scheduleTimeout = function () { - var action = this.action; - if (action) { - this.action = action.schedule(this, this.waitFor); - } - else { - this.add(this.action = this.scheduler.schedule(TimeoutWithSubscriber.dispatchTimeout, this.waitFor, this)); - } - }; - TimeoutWithSubscriber.prototype._next = function (value) { - if (!this.absoluteTimeout) { - this.scheduleTimeout(); - } - _super.prototype._next.call(this, value); - }; - TimeoutWithSubscriber.prototype._unsubscribe = function () { - this.action = undefined; - this.scheduler = null; - this.withObservable = null; - }; - return TimeoutWithSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START _scheduler_async,_util_TimeoutError,_timeoutWith,_observable_throwError PURE_IMPORTS_END */ -function timeout(due, scheduler) { - if (scheduler === void 0) { - scheduler = async; - } - return timeoutWith(due, throwError(new TimeoutError()), scheduler); -} - -/** PURE_IMPORTS_START _scheduler_async,_map PURE_IMPORTS_END */ -function timestamp(scheduler) { - if (scheduler === void 0) { - scheduler = async; - } - return map$1(function (value) { return new Timestamp(value, scheduler.now()); }); -} -var Timestamp = /*@__PURE__*/ (function () { - function Timestamp(value, timestamp) { - this.value = value; - this.timestamp = timestamp; - } - return Timestamp; -}()); - -/** PURE_IMPORTS_START _reduce PURE_IMPORTS_END */ -function toArrayReducer(arr, item, index) { - if (index === 0) { - return [item]; - } - arr.push(item); - return arr; -} -function toArray() { - return reduce$1(toArrayReducer, []); -} - -/** PURE_IMPORTS_START tslib,_Subject,_innerSubscribe PURE_IMPORTS_END */ -function window$1(windowBoundaries) { - return function windowOperatorFunction(source) { - return source.lift(new WindowOperator(windowBoundaries)); - }; -} -var WindowOperator = /*@__PURE__*/ (function () { - function WindowOperator(windowBoundaries) { - this.windowBoundaries = windowBoundaries; - } - WindowOperator.prototype.call = function (subscriber, source) { - var windowSubscriber = new WindowSubscriber(subscriber); - var sourceSubscription = source.subscribe(windowSubscriber); - if (!sourceSubscription.closed) { - windowSubscriber.add(innerSubscribe(this.windowBoundaries, new SimpleInnerSubscriber(windowSubscriber))); - } - return sourceSubscription; - }; - return WindowOperator; -}()); -var WindowSubscriber = /*@__PURE__*/ (function (_super) { - __extends(WindowSubscriber, _super); - function WindowSubscriber(destination) { - var _this = _super.call(this, destination) || this; - _this.window = new Subject(); - destination.next(_this.window); - return _this; - } - WindowSubscriber.prototype.notifyNext = function () { - this.openWindow(); - }; - WindowSubscriber.prototype.notifyError = function (error) { - this._error(error); - }; - WindowSubscriber.prototype.notifyComplete = function () { - this._complete(); - }; - WindowSubscriber.prototype._next = function (value) { - this.window.next(value); - }; - WindowSubscriber.prototype._error = function (err) { - this.window.error(err); - this.destination.error(err); - }; - WindowSubscriber.prototype._complete = function () { - this.window.complete(); - this.destination.complete(); - }; - WindowSubscriber.prototype._unsubscribe = function () { - this.window = null; - }; - WindowSubscriber.prototype.openWindow = function () { - var prevWindow = this.window; - if (prevWindow) { - prevWindow.complete(); - } - var destination = this.destination; - var newWindow = this.window = new Subject(); - destination.next(newWindow); - }; - return WindowSubscriber; -}(SimpleOuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subscriber,_Subject PURE_IMPORTS_END */ -function windowCount(windowSize, startWindowEvery) { - if (startWindowEvery === void 0) { - startWindowEvery = 0; - } - return function windowCountOperatorFunction(source) { - return source.lift(new WindowCountOperator(windowSize, startWindowEvery)); - }; -} -var WindowCountOperator = /*@__PURE__*/ (function () { - function WindowCountOperator(windowSize, startWindowEvery) { - this.windowSize = windowSize; - this.startWindowEvery = startWindowEvery; - } - WindowCountOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new WindowCountSubscriber(subscriber, this.windowSize, this.startWindowEvery)); - }; - return WindowCountOperator; -}()); -var WindowCountSubscriber = /*@__PURE__*/ (function (_super) { - __extends(WindowCountSubscriber, _super); - function WindowCountSubscriber(destination, windowSize, startWindowEvery) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - _this.windowSize = windowSize; - _this.startWindowEvery = startWindowEvery; - _this.windows = [new Subject()]; - _this.count = 0; - destination.next(_this.windows[0]); - return _this; - } - WindowCountSubscriber.prototype._next = function (value) { - var startWindowEvery = (this.startWindowEvery > 0) ? this.startWindowEvery : this.windowSize; - var destination = this.destination; - var windowSize = this.windowSize; - var windows = this.windows; - var len = windows.length; - for (var i = 0; i < len && !this.closed; i++) { - windows[i].next(value); - } - var c = this.count - windowSize + 1; - if (c >= 0 && c % startWindowEvery === 0 && !this.closed) { - windows.shift().complete(); - } - if (++this.count % startWindowEvery === 0 && !this.closed) { - var window_1 = new Subject(); - windows.push(window_1); - destination.next(window_1); - } - }; - WindowCountSubscriber.prototype._error = function (err) { - var windows = this.windows; - if (windows) { - while (windows.length > 0 && !this.closed) { - windows.shift().error(err); - } - } - this.destination.error(err); - }; - WindowCountSubscriber.prototype._complete = function () { - var windows = this.windows; - if (windows) { - while (windows.length > 0 && !this.closed) { - windows.shift().complete(); - } - } - this.destination.complete(); - }; - WindowCountSubscriber.prototype._unsubscribe = function () { - this.count = 0; - this.windows = null; - }; - return WindowCountSubscriber; -}(Subscriber)); - -/** PURE_IMPORTS_START tslib,_Subject,_scheduler_async,_Subscriber,_util_isNumeric,_util_isScheduler PURE_IMPORTS_END */ -function windowTime(windowTimeSpan) { - var scheduler = async; - var windowCreationInterval = null; - var maxWindowSize = Number.POSITIVE_INFINITY; - if (isScheduler(arguments[3])) { - scheduler = arguments[3]; - } - if (isScheduler(arguments[2])) { - scheduler = arguments[2]; - } - else if (isNumeric(arguments[2])) { - maxWindowSize = Number(arguments[2]); - } - if (isScheduler(arguments[1])) { - scheduler = arguments[1]; - } - else if (isNumeric(arguments[1])) { - windowCreationInterval = Number(arguments[1]); - } - return function windowTimeOperatorFunction(source) { - return source.lift(new WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler)); - }; -} -var WindowTimeOperator = /*@__PURE__*/ (function () { - function WindowTimeOperator(windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) { - this.windowTimeSpan = windowTimeSpan; - this.windowCreationInterval = windowCreationInterval; - this.maxWindowSize = maxWindowSize; - this.scheduler = scheduler; - } - WindowTimeOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new WindowTimeSubscriber(subscriber, this.windowTimeSpan, this.windowCreationInterval, this.maxWindowSize, this.scheduler)); - }; - return WindowTimeOperator; -}()); -var CountedSubject = /*@__PURE__*/ (function (_super) { - __extends(CountedSubject, _super); - function CountedSubject() { - var _this = _super !== null && _super.apply(this, arguments) || this; - _this._numberOfNextedValues = 0; - return _this; - } - CountedSubject.prototype.next = function (value) { - this._numberOfNextedValues++; - _super.prototype.next.call(this, value); - }; - Object.defineProperty(CountedSubject.prototype, "numberOfNextedValues", { - get: function () { - return this._numberOfNextedValues; - }, - enumerable: true, - configurable: true - }); - return CountedSubject; -}(Subject)); -var WindowTimeSubscriber = /*@__PURE__*/ (function (_super) { - __extends(WindowTimeSubscriber, _super); - function WindowTimeSubscriber(destination, windowTimeSpan, windowCreationInterval, maxWindowSize, scheduler) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - _this.windowTimeSpan = windowTimeSpan; - _this.windowCreationInterval = windowCreationInterval; - _this.maxWindowSize = maxWindowSize; - _this.scheduler = scheduler; - _this.windows = []; - var window = _this.openWindow(); - if (windowCreationInterval !== null && windowCreationInterval >= 0) { - var closeState = { subscriber: _this, window: window, context: null }; - var creationState = { windowTimeSpan: windowTimeSpan, windowCreationInterval: windowCreationInterval, subscriber: _this, scheduler: scheduler }; - _this.add(scheduler.schedule(dispatchWindowClose, windowTimeSpan, closeState)); - _this.add(scheduler.schedule(dispatchWindowCreation, windowCreationInterval, creationState)); - } - else { - var timeSpanOnlyState = { subscriber: _this, window: window, windowTimeSpan: windowTimeSpan }; - _this.add(scheduler.schedule(dispatchWindowTimeSpanOnly, windowTimeSpan, timeSpanOnlyState)); - } - return _this; - } - WindowTimeSubscriber.prototype._next = function (value) { - var windows = this.windows; - var len = windows.length; - for (var i = 0; i < len; i++) { - var window_1 = windows[i]; - if (!window_1.closed) { - window_1.next(value); - if (window_1.numberOfNextedValues >= this.maxWindowSize) { - this.closeWindow(window_1); - } - } - } - }; - WindowTimeSubscriber.prototype._error = function (err) { - var windows = this.windows; - while (windows.length > 0) { - windows.shift().error(err); - } - this.destination.error(err); - }; - WindowTimeSubscriber.prototype._complete = function () { - var windows = this.windows; - while (windows.length > 0) { - var window_2 = windows.shift(); - if (!window_2.closed) { - window_2.complete(); - } - } - this.destination.complete(); - }; - WindowTimeSubscriber.prototype.openWindow = function () { - var window = new CountedSubject(); - this.windows.push(window); - var destination = this.destination; - destination.next(window); - return window; - }; - WindowTimeSubscriber.prototype.closeWindow = function (window) { - window.complete(); - var windows = this.windows; - windows.splice(windows.indexOf(window), 1); - }; - return WindowTimeSubscriber; -}(Subscriber)); -function dispatchWindowTimeSpanOnly(state) { - var subscriber = state.subscriber, windowTimeSpan = state.windowTimeSpan, window = state.window; - if (window) { - subscriber.closeWindow(window); - } - state.window = subscriber.openWindow(); - this.schedule(state, windowTimeSpan); -} -function dispatchWindowCreation(state) { - var windowTimeSpan = state.windowTimeSpan, subscriber = state.subscriber, scheduler = state.scheduler, windowCreationInterval = state.windowCreationInterval; - var window = subscriber.openWindow(); - var action = this; - var context = { action: action, subscription: null }; - var timeSpanState = { subscriber: subscriber, window: window, context: context }; - context.subscription = scheduler.schedule(dispatchWindowClose, windowTimeSpan, timeSpanState); - action.add(context.subscription); - action.schedule(state, windowCreationInterval); -} -function dispatchWindowClose(state) { - var subscriber = state.subscriber, window = state.window, context = state.context; - if (context && context.action && context.subscription) { - context.action.remove(context.subscription); - } - subscriber.closeWindow(window); -} - -/** PURE_IMPORTS_START tslib,_Subject,_Subscription,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function windowToggle(openings, closingSelector) { - return function (source) { return source.lift(new WindowToggleOperator(openings, closingSelector)); }; -} -var WindowToggleOperator = /*@__PURE__*/ (function () { - function WindowToggleOperator(openings, closingSelector) { - this.openings = openings; - this.closingSelector = closingSelector; - } - WindowToggleOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new WindowToggleSubscriber(subscriber, this.openings, this.closingSelector)); - }; - return WindowToggleOperator; -}()); -var WindowToggleSubscriber = /*@__PURE__*/ (function (_super) { - __extends(WindowToggleSubscriber, _super); - function WindowToggleSubscriber(destination, openings, closingSelector) { - var _this = _super.call(this, destination) || this; - _this.openings = openings; - _this.closingSelector = closingSelector; - _this.contexts = []; - _this.add(_this.openSubscription = subscribeToResult(_this, openings, openings)); - return _this; - } - WindowToggleSubscriber.prototype._next = function (value) { - var contexts = this.contexts; - if (contexts) { - var len = contexts.length; - for (var i = 0; i < len; i++) { - contexts[i].window.next(value); - } - } - }; - WindowToggleSubscriber.prototype._error = function (err) { - var contexts = this.contexts; - this.contexts = null; - if (contexts) { - var len = contexts.length; - var index = -1; - while (++index < len) { - var context_1 = contexts[index]; - context_1.window.error(err); - context_1.subscription.unsubscribe(); - } - } - _super.prototype._error.call(this, err); - }; - WindowToggleSubscriber.prototype._complete = function () { - var contexts = this.contexts; - this.contexts = null; - if (contexts) { - var len = contexts.length; - var index = -1; - while (++index < len) { - var context_2 = contexts[index]; - context_2.window.complete(); - context_2.subscription.unsubscribe(); - } - } - _super.prototype._complete.call(this); - }; - WindowToggleSubscriber.prototype._unsubscribe = function () { - var contexts = this.contexts; - this.contexts = null; - if (contexts) { - var len = contexts.length; - var index = -1; - while (++index < len) { - var context_3 = contexts[index]; - context_3.window.unsubscribe(); - context_3.subscription.unsubscribe(); - } - } - }; - WindowToggleSubscriber.prototype.notifyNext = function (outerValue, innerValue, outerIndex, innerIndex, innerSub) { - if (outerValue === this.openings) { - var closingNotifier = void 0; - try { - var closingSelector = this.closingSelector; - closingNotifier = closingSelector(innerValue); - } - catch (e) { - return this.error(e); - } - var window_1 = new Subject(); - var subscription = new Subscription(); - var context_4 = { window: window_1, subscription: subscription }; - this.contexts.push(context_4); - var innerSubscription = subscribeToResult(this, closingNotifier, context_4); - if (innerSubscription.closed) { - this.closeWindow(this.contexts.length - 1); - } - else { - innerSubscription.context = context_4; - subscription.add(innerSubscription); - } - this.destination.next(window_1); - } - else { - this.closeWindow(this.contexts.indexOf(outerValue)); - } - }; - WindowToggleSubscriber.prototype.notifyError = function (err) { - this.error(err); - }; - WindowToggleSubscriber.prototype.notifyComplete = function (inner) { - if (inner !== this.openSubscription) { - this.closeWindow(this.contexts.indexOf(inner.context)); - } - }; - WindowToggleSubscriber.prototype.closeWindow = function (index) { - if (index === -1) { - return; - } - var contexts = this.contexts; - var context = contexts[index]; - var window = context.window, subscription = context.subscription; - contexts.splice(index, 1); - window.complete(); - subscription.unsubscribe(); - }; - return WindowToggleSubscriber; -}(OuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_Subject,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function windowWhen(closingSelector) { - return function windowWhenOperatorFunction(source) { - return source.lift(new WindowOperator$1(closingSelector)); - }; -} -var WindowOperator$1 = /*@__PURE__*/ (function () { - function WindowOperator(closingSelector) { - this.closingSelector = closingSelector; - } - WindowOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new WindowSubscriber$1(subscriber, this.closingSelector)); - }; - return WindowOperator; -}()); -var WindowSubscriber$1 = /*@__PURE__*/ (function (_super) { - __extends(WindowSubscriber, _super); - function WindowSubscriber(destination, closingSelector) { - var _this = _super.call(this, destination) || this; - _this.destination = destination; - _this.closingSelector = closingSelector; - _this.openWindow(); - return _this; - } - WindowSubscriber.prototype.notifyNext = function (_outerValue, _innerValue, _outerIndex, _innerIndex, innerSub) { - this.openWindow(innerSub); - }; - WindowSubscriber.prototype.notifyError = function (error) { - this._error(error); - }; - WindowSubscriber.prototype.notifyComplete = function (innerSub) { - this.openWindow(innerSub); - }; - WindowSubscriber.prototype._next = function (value) { - this.window.next(value); - }; - WindowSubscriber.prototype._error = function (err) { - this.window.error(err); - this.destination.error(err); - this.unsubscribeClosingNotification(); - }; - WindowSubscriber.prototype._complete = function () { - this.window.complete(); - this.destination.complete(); - this.unsubscribeClosingNotification(); - }; - WindowSubscriber.prototype.unsubscribeClosingNotification = function () { - if (this.closingNotification) { - this.closingNotification.unsubscribe(); - } - }; - WindowSubscriber.prototype.openWindow = function (innerSub) { - if (innerSub === void 0) { - innerSub = null; - } - if (innerSub) { - this.remove(innerSub); - innerSub.unsubscribe(); - } - var prevWindow = this.window; - if (prevWindow) { - prevWindow.complete(); - } - var window = this.window = new Subject(); - this.destination.next(window); - var closingNotifier; - try { - var closingSelector = this.closingSelector; - closingNotifier = closingSelector(); - } - catch (e) { - this.destination.error(e); - this.window.error(e); - return; - } - this.add(this.closingNotification = subscribeToResult(this, closingNotifier)); - }; - return WindowSubscriber; -}(OuterSubscriber)); - -/** PURE_IMPORTS_START tslib,_OuterSubscriber,_util_subscribeToResult PURE_IMPORTS_END */ -function withLatestFrom() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return function (source) { - var project; - if (typeof args[args.length - 1] === 'function') { - project = args.pop(); - } - var observables = args; - return source.lift(new WithLatestFromOperator(observables, project)); - }; -} -var WithLatestFromOperator = /*@__PURE__*/ (function () { - function WithLatestFromOperator(observables, project) { - this.observables = observables; - this.project = project; - } - WithLatestFromOperator.prototype.call = function (subscriber, source) { - return source.subscribe(new WithLatestFromSubscriber(subscriber, this.observables, this.project)); - }; - return WithLatestFromOperator; -}()); -var WithLatestFromSubscriber = /*@__PURE__*/ (function (_super) { - __extends(WithLatestFromSubscriber, _super); - function WithLatestFromSubscriber(destination, observables, project) { - var _this = _super.call(this, destination) || this; - _this.observables = observables; - _this.project = project; - _this.toRespond = []; - var len = observables.length; - _this.values = new Array(len); - for (var i = 0; i < len; i++) { - _this.toRespond.push(i); - } - for (var i = 0; i < len; i++) { - var observable = observables[i]; - _this.add(subscribeToResult(_this, observable, undefined, i)); - } - return _this; - } - WithLatestFromSubscriber.prototype.notifyNext = function (_outerValue, innerValue, outerIndex) { - this.values[outerIndex] = innerValue; - var toRespond = this.toRespond; - if (toRespond.length > 0) { - var found = toRespond.indexOf(outerIndex); - if (found !== -1) { - toRespond.splice(found, 1); - } - } - }; - WithLatestFromSubscriber.prototype.notifyComplete = function () { - }; - WithLatestFromSubscriber.prototype._next = function (value) { - if (this.toRespond.length === 0) { - var args = [value].concat(this.values); - if (this.project) { - this._tryProject(args); - } - else { - this.destination.next(args); - } - } - }; - WithLatestFromSubscriber.prototype._tryProject = function (args) { - var result; - try { - result = this.project.apply(this, args); - } - catch (err) { - this.destination.error(err); - return; - } - this.destination.next(result); - }; - return WithLatestFromSubscriber; -}(OuterSubscriber)); - -/** PURE_IMPORTS_START _observable_zip PURE_IMPORTS_END */ -function zip$1() { - var observables = []; - for (var _i = 0; _i < arguments.length; _i++) { - observables[_i] = arguments[_i]; - } - return function zipOperatorFunction(source) { - return source.lift.call(zip.apply(void 0, [source].concat(observables))); - }; -} - -/** PURE_IMPORTS_START _observable_zip PURE_IMPORTS_END */ -function zipAll(project) { - return function (source) { return source.lift(new ZipOperator(project)); }; -} - -/** PURE_IMPORTS_START PURE_IMPORTS_END */ - -var operators = /*#__PURE__*/Object.freeze({ - __proto__: null, - audit: audit, - auditTime: auditTime, - buffer: buffer, - bufferCount: bufferCount, - bufferTime: bufferTime, - bufferToggle: bufferToggle, - bufferWhen: bufferWhen, - catchError: catchError, - combineAll: combineAll, - combineLatest: combineLatest$1, - concat: concat$2, - concatAll: concatAll, - concatMap: concatMap, - concatMapTo: concatMapTo, - count: count, - debounce: debounce, - debounceTime: debounceTime, - defaultIfEmpty: defaultIfEmpty, - delay: delay, - delayWhen: delayWhen, - dematerialize: dematerialize, - distinct: distinct, - distinctUntilChanged: distinctUntilChanged, - distinctUntilKeyChanged: distinctUntilKeyChanged, - elementAt: elementAt, - endWith: endWith, - every: every$1, - exhaust: exhaust, - exhaustMap: exhaustMap, - expand: expand, - filter: filter, - finalize: finalize, - find: find, - findIndex: findIndex, - first: first, - groupBy: groupBy, - ignoreElements: ignoreElements, - isEmpty: isEmpty$1, - last: last, - map: map$1, - mapTo: mapTo, - materialize: materialize, - max: max, - merge: merge$1, - mergeAll: mergeAll, - mergeMap: mergeMap, - flatMap: flatMap$1, - mergeMapTo: mergeMapTo, - mergeScan: mergeScan, - min: min, - multicast: multicast, - observeOn: observeOn, - onErrorResumeNext: onErrorResumeNext$1, - pairwise: pairwise, - partition: partition$1, - pluck: pluck, - publish: publish, - publishBehavior: publishBehavior, - publishLast: publishLast, - publishReplay: publishReplay, - race: race$1, - reduce: reduce$1, - repeat: repeat, - repeatWhen: repeatWhen, - retry: retry, - retryWhen: retryWhen, - refCount: refCount, - sample: sample, - sampleTime: sampleTime, - scan: scan, - sequenceEqual: sequenceEqual, - share: share, - shareReplay: shareReplay, - single: single, - skip: skip, - skipLast: skipLast, - skipUntil: skipUntil, - skipWhile: skipWhile, - startWith: startWith, - subscribeOn: subscribeOn, - switchAll: switchAll, - switchMap: switchMap, - switchMapTo: switchMapTo, - take: take, - takeLast: takeLast, - takeUntil: takeUntil, - takeWhile: takeWhile, - tap: tap, - throttle: throttle, - throttleTime: throttleTime, - throwIfEmpty: throwIfEmpty, - timeInterval: timeInterval, - timeout: timeout, - timeoutWith: timeoutWith, - timestamp: timestamp, - toArray: toArray, - window: window$1, - windowCount: windowCount, - windowTime: windowTime, - windowToggle: windowToggle, - windowWhen: windowWhen, - withLatestFrom: withLatestFrom, - zip: zip$1, - zipAll: zipAll -}); - -var _rxjs = /*@__PURE__*/getAugmentedNamespace(_esm5); - -var _operators = /*@__PURE__*/getAugmentedNamespace(operators); - -var resultRx = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -interopRequireDefault(resultSummary); - - - - - -interopRequireDefault(record); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var States = { - READY: 0, - STREAMING: 1, - COMPLETED: 2 - /** - * The reactive result interface. - */ - -}; - -var RxResult = -/*#__PURE__*/ -function () { - /** - * @constructor - * @protected - * @param {Observable} result - An observable of single Result instance to relay requests. - */ - function RxResult(result) { - (0, _classCallCheck2["default"])(this, RxResult); - var replayedResult = result.pipe((0, _operators.publishReplay)(1), (0, _operators.refCount)()); - this._result = replayedResult; - this._keys = replayedResult.pipe((0, _operators.flatMap)(function (r) { - return (0, _rxjs.from)(r.keys()); - }), (0, _operators.publishReplay)(1), (0, _operators.refCount)()); - this._records = new _rxjs.Subject(); - this._summary = new _rxjs.ReplaySubject(); - this._state = States.READY; - } - /** - * Returns an observable that exposes a single item containing field names - * returned by the executing query. - * - * Errors raised by actual query execution can surface on the returned - * observable stream. - * - * @public - * @returns {Observable} - An observable stream (with exactly one element) of field names. - */ - - - (0, _createClass2["default"])(RxResult, [{ - key: "keys", - value: function keys() { - return this._keys; - } - /** - * Returns an observable that exposes each record returned by the executing query. - * - * Errors raised during the streaming phase can surface on the returned observable stream. - * - * @public - * @returns {Observable} - An observable stream of records. - */ - - }, { - key: "records", - value: function records() { - var _this = this; - - return this._result.pipe((0, _operators.flatMap)(function (result) { - return new _rxjs.Observable(function (recordsObserver) { - return _this._startStreaming({ - result: result, - recordsObserver: recordsObserver - }); - }); - })); - } - /** - * Returns an observable that exposes a single item of {@link ResultSummary} that is generated by - * the server after the streaming of the executing query is completed. - * - * *Subscribing to this stream before subscribing to records() stream causes the results to be discarded on the server.* - * - * @public - * @returns {Observable} - An observable stream (with exactly one element) of result summary. - */ - - }, { - key: "consume", - value: function consume() { - var _this2 = this; - - return this._result.pipe((0, _operators.flatMap)(function (result) { - return new _rxjs.Observable(function (summaryObserver) { - return _this2._startStreaming({ - result: result, - summaryObserver: summaryObserver - }); - }); - })); - } - }, { - key: "_startStreaming", - value: function _startStreaming() { - var _this3 = this; - - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - result = _ref.result, - _ref$recordsObserver = _ref.recordsObserver, - recordsObserver = _ref$recordsObserver === void 0 ? null : _ref$recordsObserver, - _ref$summaryObserver = _ref.summaryObserver, - summaryObserver = _ref$summaryObserver === void 0 ? null : _ref$summaryObserver; - - var subscriptions = []; - - if (summaryObserver) { - subscriptions.push(this._summary.subscribe(summaryObserver)); - } - - if (this._state < States.STREAMING) { - this._state = States.STREAMING; - - if (recordsObserver) { - subscriptions.push(this._records.subscribe(recordsObserver)); - } - - subscriptions.push({ - unsubscribe: function unsubscribe() { - if (result._cancel) { - result._cancel(); - } - } - }); - - if (this._records.observers.length === 0) { - result._cancel(); - } - - result.subscribe({ - onNext: function onNext(record) { - _this3._records.next(record); - }, - onCompleted: function onCompleted(summary) { - _this3._records.complete(); - - _this3._summary.next(summary); - - _this3._summary.complete(); - - _this3._state = States.COMPLETED; - }, - onError: function onError(err) { - _this3._records.error(err); - - _this3._summary.error(err); - - _this3._state = States.COMPLETED; - } - }); - } else if (recordsObserver) { - recordsObserver.error((0, error.newError)('Streaming has already started/consumed with a previous records or summary subscription.')); - } - - return function () { - subscriptions.forEach(function (s) { - return s.unsubscribe(); - }); - }; - } - }]); - return RxResult; -}(); - -exports["default"] = RxResult; -}); - -var transactionRx = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -var _resultRx = interopRequireDefault(resultRx); - -interopRequireDefault(transaction); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * A reactive transaction, which provides the same functionality as {@link Transaction} but through a Reactive API. - */ -var RxTransaction = -/*#__PURE__*/ -function () { - /** - * @constructor - * @protected - * @param {Transaction} txc - The underlying transaction instance to relay requests - */ - function RxTransaction(txc) { - (0, _classCallCheck2["default"])(this, RxTransaction); - this._txc = txc; - } - /** - * Creates a reactive result that will execute the query in this transaction, with the provided parameters. - * - * @public - * @param {string} query - Query to be executed. - * @param {Object} parameters - Parameter values to use in query execution. - * @returns {RxResult} - A reactive result - */ - - - (0, _createClass2["default"])(RxTransaction, [{ - key: "run", - value: function run(query, parameters) { - var _this = this; - - return new _resultRx["default"](new _rxjs.Observable(function (observer) { - try { - observer.next(_this._txc.run(query, parameters)); - observer.complete(); - } catch (err) { - observer.error(err); - } - - return function () {}; - })); - } - /** - * Commits the transaction. - * - * @public - * @returns {Observable} - An empty observable - */ - - }, { - key: "commit", - value: function commit() { - var _this2 = this; - - return new _rxjs.Observable(function (observer) { - _this2._txc.commit().then(function () { - observer.complete(); - })["catch"](function (err) { - return observer.error(err); - }); - }); - } - /** - * Rolls back the transaction. - * - * @public - * @returns {Observable} - An empty observable - */ - - }, { - key: "rollback", - value: function rollback() { - var _this3 = this; - - return new _rxjs.Observable(function (observer) { - _this3._txc.rollback().then(function () { - observer.complete(); - })["catch"](function (err) { - return observer.error(err); - }); - }); - } - }]); - return RxTransaction; -}(); - -exports["default"] = RxTransaction; -}); - -var retryLogicRx = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - - - - - -interopRequireDefault(logger); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DEFAULT_MAX_RETRY_TIME_MS = 30 * 1000; // 30 seconds - -var DEFAULT_INITIAL_RETRY_DELAY_MS = 1000; // 1 seconds - -var DEFAULT_RETRY_DELAY_MULTIPLIER = 2.0; -var DEFAULT_RETRY_DELAY_JITTER_FACTOR = 0.2; - -var RxRetryLogic = -/*#__PURE__*/ -function () { - /** - * - * @param {Object} args - * @param {Logger} args.logger - */ - function RxRetryLogic() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref$maxRetryTimeout = _ref.maxRetryTimeout, - maxRetryTimeout = _ref$maxRetryTimeout === void 0 ? DEFAULT_MAX_RETRY_TIME_MS : _ref$maxRetryTimeout, - _ref$initialDelay = _ref.initialDelay, - initialDelay = _ref$initialDelay === void 0 ? DEFAULT_INITIAL_RETRY_DELAY_MS : _ref$initialDelay, - _ref$delayMultiplier = _ref.delayMultiplier, - delayMultiplier = _ref$delayMultiplier === void 0 ? DEFAULT_RETRY_DELAY_MULTIPLIER : _ref$delayMultiplier, - _ref$delayJitter = _ref.delayJitter, - delayJitter = _ref$delayJitter === void 0 ? DEFAULT_RETRY_DELAY_JITTER_FACTOR : _ref$delayJitter, - _ref$logger = _ref.logger, - logger = _ref$logger === void 0 ? null : _ref$logger; - - (0, _classCallCheck2["default"])(this, RxRetryLogic); - this._maxRetryTimeout = valueOrDefault(maxRetryTimeout, DEFAULT_MAX_RETRY_TIME_MS); - this._initialDelay = valueOrDefault(initialDelay, DEFAULT_INITIAL_RETRY_DELAY_MS); - this._delayMultiplier = valueOrDefault(delayMultiplier, DEFAULT_RETRY_DELAY_MULTIPLIER); - this._delayJitter = valueOrDefault(delayJitter, DEFAULT_RETRY_DELAY_JITTER_FACTOR); - this._logger = logger; - } - /** - * - * @param {Observable} work - */ - - - (0, _createClass2["default"])(RxRetryLogic, [{ - key: "retry", - value: function retry(work) { - var _this = this; - - return work.pipe((0, _operators.retryWhen)(function (failedWork) { - var handledExceptions = []; - var startTime = Date.now(); - var retryCount = 1; - var delayDuration = _this._initialDelay; - return failedWork.pipe((0, _operators.flatMap)(function (err) { - if (!RxRetryLogic._canRetryOn(err)) { - return (0, _rxjs.throwError)(err); - } - - handledExceptions.push(err); - - if (retryCount >= 2 && Date.now() - startTime >= _this._maxRetryTimeout) { - var error$1 = (0, error.newError)("Failed after retried for ".concat(retryCount, " times in ").concat(_this._maxRetryTimeout, " ms. Make sure that your database is online and retry again."), error.SERVICE_UNAVAILABLE); - error$1.seenErrors = handledExceptions; - return (0, _rxjs.throwError)(error$1); - } - - var nextDelayDuration = _this._computeNextDelay(delayDuration); - - delayDuration = delayDuration * _this._delayMultiplier; - retryCount++; - - if (_this._logger) { - _this._logger.warn("Transaction failed and will be retried in ".concat(nextDelayDuration)); - } - - return (0, _rxjs.of)(1).pipe((0, _operators.delay)(nextDelayDuration)); - })); - })); - } - }, { - key: "_computeNextDelay", - value: function _computeNextDelay(delay) { - var jitter = delay * this._delayJitter; - return delay - jitter + 2 * jitter * Math.random(); - } - }], [{ - key: "_canRetryOn", - value: function _canRetryOn(error$1) { - return error$1 && error$1.code && (error$1.code === error.SERVICE_UNAVAILABLE || error$1.code === error.SESSION_EXPIRED || this._isTransientError(error$1)); - } - }, { - key: "_isTransientError", - value: function _isTransientError(error) { - // Retries should not happen when transaction was explicitly terminated by the user. - // Termination of transaction might result in two different error codes depending on where it was - // terminated. These are really client errors but classification on the server is not entirely correct and - // they are classified as transient. - var code = error.code; - - if (code.indexOf('TransientError') >= 0) { - if (code === 'Neo.TransientError.Transaction.Terminated' || code === 'Neo.TransientError.Transaction.LockClientStopped') { - return false; - } - - return true; - } - - return false; - } - }]); - return RxRetryLogic; -}(); - -exports["default"] = RxRetryLogic; - -function valueOrDefault(value, defaultValue) { - if (value || value === 0) { - return value; - } - - return defaultValue; -} -}); - -var sessionRx = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - - - -var _resultRx = interopRequireDefault(resultRx); - -interopRequireDefault(session); - -var _transactionRx = interopRequireDefault(transactionRx); - - - -var _txConfig = interopRequireDefault(txConfig); - -var _retryLogicRx = interopRequireDefault(retryLogicRx); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * A Reactive session, which provides the same functionality as {@link Session} but through a Reactive API. - */ -var RxSession = -/*#__PURE__*/ -function () { - /** - * Constructs a reactive session with given default session instance and provided driver configuration. - * - * @protected - * @param {Object} param - Object parameter - * @param {Session} param.session - The underlying session instance to relay requests - */ - function RxSession() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - session = _ref.session, - config = _ref.config; - - (0, _classCallCheck2["default"])(this, RxSession); - this._session = session; - this._retryLogic = _createRetryLogic(config); - } - /** - * Creates a reactive result that will execute the query with the provided parameters and the provided - * transaction configuration that applies to the underlying auto-commit transaction. - * - * @public - * @param {string} query - Query to be executed. - * @param {Object} parameters - Parameter values to use in query execution. - * @param {TransactionConfig} transactionConfig - Configuration for the new auto-commit transaction. - * @returns {RxResult} - A reactive result - */ - - - (0, _createClass2["default"])(RxSession, [{ - key: "run", - value: function run(query, parameters, transactionConfig) { - var _this = this; - - return new _resultRx["default"](new _rxjs.Observable(function (observer) { - try { - observer.next(_this._session.run(query, parameters, transactionConfig)); - observer.complete(); - } catch (err) { - observer.error(err); - } - - return function () {}; - })); - } - /** - * Starts a new explicit transaction with the provided transaction configuration. - * - * @public - * @param {TransactionConfig} transactionConfig - Configuration for the new transaction. - * @returns {Observable} - A reactive stream that will generate at most **one** RxTransaction instance. - */ - - }, { - key: "beginTransaction", - value: function beginTransaction(transactionConfig) { - return this._beginTransaction(this._session._mode, transactionConfig); - } - /** - * Executes the provided unit of work in a {@link READ} reactive transaction which is created with the provided - * transaction configuration. - * @public - * @param {function(txc: RxTransaction): Observable} work - A unit of work to be executed. - * @param {TransactionConfig} transactionConfig - Configuration for the enclosing transaction created by the driver. - * @returns {Observable} - A reactive stream returned by the unit of work. - */ - - }, { - key: "readTransaction", - value: function readTransaction(work, transactionConfig) { - return this._runTransaction(constants.ACCESS_MODE_READ, work, transactionConfig); - } - /** - * Executes the provided unit of work in a {@link WRITE} reactive transaction which is created with the provided - * transaction configuration. - * @public - * @param {function(txc: RxTransaction): Observable} work - A unit of work to be executed. - * @param {TransactionConfig} transactionConfig - Configuration for the enclosing transaction created by the driver. - * @returns {Observable} - A reactive stream returned by the unit of work. - */ - - }, { - key: "writeTransaction", - value: function writeTransaction(work, transactionConfig) { - return this._runTransaction(constants.ACCESS_MODE_WRITE, work, transactionConfig); - } - /** - * Closes this reactive session. - * - * @public - * @returns {Observable} - An empty reactive stream - */ - - }, { - key: "close", - value: function close() { - var _this2 = this; - - return new _rxjs.Observable(function (observer) { - _this2._session.close().then(function () { - observer.complete(); - })["catch"](function (err) { - return observer.error(err); - }); - }); - } - /** - * Returns the bookmark received following the last successfully completed query, which is executed - * either in an {@link RxTransaction} obtained from this session instance or directly through one of - * the {@link RxSession#run} method of this session instance. - * - * If no bookmark was received or if this transaction was rolled back, the bookmark value will not be - * changed. - * - * @public - * @returns {string} - */ - - }, { - key: "lastBookmark", - value: function lastBookmark() { - return this._session.lastBookmark(); - } - /** - * @private - */ - - }, { - key: "_beginTransaction", - value: function _beginTransaction(accessMode, transactionConfig) { - var _this3 = this; - - var txConfig = _txConfig["default"].empty(); - - if (transactionConfig) { - txConfig = new _txConfig["default"](transactionConfig); - } - - return new _rxjs.Observable(function (observer) { - try { - observer.next(new _transactionRx["default"](_this3._session._beginTransaction(accessMode, txConfig))); - observer.complete(); - } catch (err) { - observer.error(err); - } - - return function () {}; - }); - } - /** - * @private - */ - - }, { - key: "_runTransaction", - value: function _runTransaction(accessMode, work, transactionConfig) { - _txConfig["default"].empty(); - - if (transactionConfig) { - new _txConfig["default"](transactionConfig); - } - - return this._retryLogic.retry(this._beginTransaction(accessMode, transactionConfig).pipe((0, _operators.flatMap)(function (txc) { - return (0, _rxjs.defer)(function () { - try { - return work(txc); - } catch (err) { - return (0, _rxjs.throwError)(err); - } - }).pipe((0, _operators.catchError)(function (err) { - return txc.rollback().pipe((0, _operators.concat)((0, _rxjs.throwError)(err))); - }), (0, _operators.concat)(txc.commit())); - }))); - } - }]); - return RxSession; -}(); - -exports["default"] = RxSession; - -function _createRetryLogic(config) { - var maxRetryTimeout = config && config.maxTransactionRetryTime ? config.maxTransactionRetryTime : null; - return new _retryLogicRx["default"]({ - maxRetryTimeout: maxRetryTimeout - }); -} -}); - -var driver = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = exports.WRITE = exports.READ = exports.Driver = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -interopRequireDefault(connectionProvider); - -var _bookmark = interopRequireDefault(bookmark); - -var _connectionProviderDirect = interopRequireDefault(connectionProviderDirect); - -var _connectivityVerifier = interopRequireDefault(connectivityVerifier); - - - -var _logger = interopRequireDefault(logger); - - - -var _session = interopRequireDefault(session); - -var _sessionRx = interopRequireDefault(sessionRx); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DEFAULT_MAX_CONNECTION_LIFETIME = 60 * 60 * 1000; // 1 hour - -/** - * The default record fetch size. This is used in Bolt V4 protocol to pull query execution result in batches. - * @type {number} - */ - -var DEFAULT_FETCH_SIZE = 1000; -/** - * Constant that represents read session access mode. - * Should be used like this: `driver.session({ defaultAccessMode: neo4j.session.READ })`. - * @type {string} - */ - -var READ = constants.ACCESS_MODE_READ; -/** - * Constant that represents write session access mode. - * Should be used like this: `driver.session({ defaultAccessMode: neo4j.session.WRITE })`. - * @type {string} - */ - -exports.READ = READ; -var WRITE = constants.ACCESS_MODE_WRITE; -exports.WRITE = WRITE; -var idGenerator = 0; -/** - * A driver maintains one or more {@link Session}s with a remote - * Neo4j instance. Through the {@link Session}s you can send queries - * and retrieve results from the database. - * - * Drivers are reasonably expensive to create - you should strive to keep one - * driver instance around per Neo4j Instance you connect to. - * - * @access public - */ - -var Driver = -/*#__PURE__*/ -function () { - /** - * You should not be calling this directly, instead use {@link driver}. - * @constructor - * @protected - * @param {ServerAddress} address - * @param {string} userAgent - * @param {Object} authToken - * @param {Object} config - */ - function Driver(address, userAgent) { - var authToken = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var config = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - (0, _classCallCheck2["default"])(this, Driver); - sanitizeConfig(config); - this._id = idGenerator++; - this._address = address; - this._userAgent = userAgent; - this._authToken = authToken; - this._config = config; - this._log = _logger["default"].create(config); - /** - * Reference to the connection provider. Initialized lazily by {@link _getOrCreateConnectionProvider}. - * @type {ConnectionProvider} - * @protected - */ - - this._connectionProvider = null; - - this._afterConstruction(); - } - /** - * Verifies connectivity of this driver by trying to open a connection with the provided driver options. - * - * @public - * @param {Object} param - The object parameter - * @param {string} param.database - The target database to verify connectivity for. - * @returns {Promise} promise resolved with server info or rejected with error. - */ - - - (0, _createClass2["default"])(Driver, [{ - key: "verifyConnectivity", - value: function verifyConnectivity() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref$database = _ref.database, - database = _ref$database === void 0 ? '' : _ref$database; - - var connectionProvider = this._getOrCreateConnectionProvider(); - - var connectivityVerifier = new _connectivityVerifier["default"](connectionProvider); - return connectivityVerifier.verify({ - database: database - }); - } - /** - * Returns whether the server supports multi database capabilities based on the protocol - * version negotiated via handshake. - * - * Note that this function call _always_ causes a round-trip to the server. - * - * @returns {Promise} promise resolved with a boolean or rejected with error. - */ - - }, { - key: "supportsMultiDb", - value: function supportsMultiDb() { - var connectionProvider = this._getOrCreateConnectionProvider(); - - return connectionProvider.supportsMultiDb(); - } - /** - * Returns whether the server supports transaction config capabilities based on the protocol - * version negotiated via handshake. - * - * Note that this function call _always_ causes a round-trip to the server. - * - * @returns {Promise} promise resolved with a boolean or rejected with error. - */ - - }, { - key: "supportsTransactionConfig", - value: function supportsTransactionConfig() { - var connectionProvider = this._getOrCreateConnectionProvider(); - - return connectionProvider.supportsTransactionConfig(); - } - /** - * @protected - * @returns {boolean} - */ - - }, { - key: "_supportsRouting", - value: function _supportsRouting() { - return false; - } - /** - * Returns boolean to indicate if driver has been configured with encryption enabled. - * - * @protected - * @returns {boolean} - */ - - }, { - key: "_isEncrypted", - value: function _isEncrypted() { - return this._config.encrypted === util.ENCRYPTION_ON; - } - /** - * Returns the configured trust strategy that the driver has been configured with. - * - * @protected - * @returns {TrustStrategy} - */ - - }, { - key: "_getTrust", - value: function _getTrust() { - return this._config.trust; - } - /** - * Acquire a session to communicate with the database. The session will - * borrow connections from the underlying connection pool as required and - * should be considered lightweight and disposable. - * - * This comes with some responsibility - make sure you always call - * {@link close} when you are done using a session, and likewise, - * make sure you don't close your session before you are done using it. Once - * it is closed, the underlying connection will be released to the connection - * pool and made available for others to use. - * - * @public - * @param {Object} param - The object parameter - * @param {string} param.defaultAccessMode=WRITE - The access mode of this session, allowed values are {@link READ} and {@link WRITE}. - * @param {string|string[]} param.bookmarks - The initial reference or references to some previous - * transactions. Value is optional and absence indicates that that the bookmarks do not exist or are unknown. - * @param {number} param.fetchSize - The record fetch size of each batch of this session. - * Use {@link ALL} to always pull all records in one batch. This will override the config value set on driver config. - * @param {string} param.database - The database this session will operate on. - * @return {Session} new session. - */ - - }, { - key: "session", - value: function session() { - var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref2$defaultAccessMo = _ref2.defaultAccessMode, - defaultAccessMode = _ref2$defaultAccessMo === void 0 ? WRITE : _ref2$defaultAccessMo, - bookmarkOrBookmarks = _ref2.bookmarks, - _ref2$database = _ref2.database, - database = _ref2$database === void 0 ? '' : _ref2$database, - fetchSize = _ref2.fetchSize; - - return this._newSession({ - defaultAccessMode: defaultAccessMode, - bookmarkOrBookmarks: bookmarkOrBookmarks, - database: database, - reactive: false, - fetchSize: validateFetchSizeValue(fetchSize, this._config.fetchSize) - }); - } - /** - * Acquire a reactive session to communicate with the database. The session will - * borrow connections from the underlying connection pool as required and - * should be considered lightweight and disposable. - * - * This comes with some responsibility - make sure you always call - * {@link close} when you are done using a session, and likewise, - * make sure you don't close your session before you are done using it. Once - * it is closed, the underlying connection will be released to the connection - * pool and made available for others to use. - * - * @public - * @param {Object} param - * @param {string} param.defaultAccessMode=WRITE - The access mode of this session, allowed values are {@link READ} and {@link WRITE}. - * @param {string|string[]} param.bookmarks - The initial reference or references to some previous transactions. Value is optional and - * absence indicates that the bookmarks do not exist or are unknown. - * @param {string} param.database - The database this session will operate on. - * @returns {RxSession} new reactive session. - */ - - }, { - key: "rxSession", - value: function rxSession() { - var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - _ref3$defaultAccessMo = _ref3.defaultAccessMode, - defaultAccessMode = _ref3$defaultAccessMo === void 0 ? WRITE : _ref3$defaultAccessMo, - bookmarks = _ref3.bookmarks, - _ref3$database = _ref3.database, - database = _ref3$database === void 0 ? '' : _ref3$database, - fetchSize = _ref3.fetchSize; - - return new _sessionRx["default"]({ - session: this._newSession({ - defaultAccessMode: defaultAccessMode, - bookmarks: bookmarks, - database: database, - reactive: true, - fetchSize: validateFetchSizeValue(fetchSize, this._config.fetchSize) - }), - config: this._config - }); - } - /** - * Close all open sessions and other associated resources. You should - * make sure to use this when you are done with this driver instance. - * @public - * @return {Promise} promise resolved when the driver is closed. - */ - - }, { - key: "close", - value: function close() { - this._log.info("Driver ".concat(this._id, " closing")); - - if (this._connectionProvider) { - return this._connectionProvider.close(); - } - - return Promise.resolve(); - } - /** - * @protected - */ - - }, { - key: "_afterConstruction", - value: function _afterConstruction() { - this._log.info("Direct driver ".concat(this._id, " created for server address ").concat(this._address)); - } - /** - * @protected - */ - - }, { - key: "_createConnectionProvider", - value: function _createConnectionProvider(address, userAgent, authToken) { - return new _connectionProviderDirect["default"]({ - id: this._id, - config: this._config, - log: this._log, - address: address, - userAgent: userAgent, - authToken: authToken - }); - } - /** - * @protected - */ - - }, { - key: "_newSession", - - /** - * @private - */ - value: function _newSession(_ref4) { - var defaultAccessMode = _ref4.defaultAccessMode, - bookmarkOrBookmarks = _ref4.bookmarkOrBookmarks, - database = _ref4.database, - reactive = _ref4.reactive, - fetchSize = _ref4.fetchSize; - - var sessionMode = Driver._validateSessionMode(defaultAccessMode); - - var connectionProvider = this._getOrCreateConnectionProvider(); - - var bookmark = bookmarkOrBookmarks ? new _bookmark["default"](bookmarkOrBookmarks) : _bookmark["default"].empty(); - return new _session["default"]({ - mode: sessionMode, - database: database, - connectionProvider: connectionProvider, - bookmark: bookmark, - config: this._config, - reactive: reactive, - fetchSize: fetchSize - }); - } - /** - * @private - */ - - }, { - key: "_getOrCreateConnectionProvider", - value: function _getOrCreateConnectionProvider() { - if (!this._connectionProvider) { - this._connectionProvider = this._createConnectionProvider(this._address, this._userAgent, this._authToken); - } - - return this._connectionProvider; - } - }], [{ - key: "_validateSessionMode", - value: function _validateSessionMode(rawMode) { - var mode = rawMode || WRITE; - - if (mode !== constants.ACCESS_MODE_READ && mode !== constants.ACCESS_MODE_WRITE) { - throw (0, error.newError)('Illegal session mode ' + mode); - } - - return mode; - } - }]); - return Driver; -}(); -/** - * @private - */ - - -exports.Driver = Driver; - -function sanitizeConfig(config) { - config.maxConnectionLifetime = sanitizeIntValue(config.maxConnectionLifetime, DEFAULT_MAX_CONNECTION_LIFETIME); - config.maxConnectionPoolSize = sanitizeIntValue(config.maxConnectionPoolSize, poolConfig.DEFAULT_MAX_SIZE); - config.connectionAcquisitionTimeout = sanitizeIntValue(config.connectionAcquisitionTimeout, poolConfig.DEFAULT_ACQUISITION_TIMEOUT); - config.fetchSize = validateFetchSizeValue(config.fetchSize, DEFAULT_FETCH_SIZE); -} -/** - * @private - */ - - -function sanitizeIntValue(rawValue, defaultWhenAbsent) { - var sanitizedValue = parseInt(rawValue, 10); - - if (sanitizedValue > 0 || sanitizedValue === 0) { - return sanitizedValue; - } else if (sanitizedValue < 0) { - return Number.MAX_SAFE_INTEGER; - } else { - return defaultWhenAbsent; - } -} -/** - * @private - */ - - -function validateFetchSizeValue(rawValue, defaultWhenAbsent) { - var fetchSize = parseInt(rawValue, 10); - - if (fetchSize > 0 || fetchSize === requestMessage.ALL) { - return fetchSize; - } else if (fetchSize === 0 || fetchSize < 0) { - throw new Error('The fetch size can only be a positive value or -1 for ALL. However fetchSize = ' + fetchSize); - } else { - return defaultWhenAbsent; - } -} - -var _default = Driver; -exports["default"] = _default; -}); - -var arrayWithoutHoles = createCommonjsModule(function (module) { -function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return arrayLikeToArray(arr); -} - -module.exports = _arrayWithoutHoles; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var iterableToArray = createCommonjsModule(function (module) { -function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); -} - -module.exports = _iterableToArray; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var nonIterableSpread = createCommonjsModule(function (module) { -function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); -} - -module.exports = _nonIterableSpread; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var toConsumableArray = createCommonjsModule(function (module) { -function _toConsumableArray(arr) { - return arrayWithoutHoles(arr) || iterableToArray(arr) || unsupportedIterableToArray(arr) || nonIterableSpread(); -} - -module.exports = _toConsumableArray; -module.exports["default"] = module.exports, module.exports.__esModule = true; -}); - -var routingTable = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _toConsumableArray2 = interopRequireDefault(toConsumableArray); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var MIN_ROUTERS = 1; - -var RoutingTable = -/*#__PURE__*/ -function () { - function RoutingTable() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - database = _ref.database, - routers = _ref.routers, - readers = _ref.readers, - writers = _ref.writers, - expirationTime = _ref.expirationTime; - - (0, _classCallCheck2["default"])(this, RoutingTable); - this.database = database; - this.databaseName = database || 'default database'; - this.routers = routers || []; - this.readers = readers || []; - this.writers = writers || []; - this.expirationTime = expirationTime || (0, integer["int"])(0); - } - - (0, _createClass2["default"])(RoutingTable, [{ - key: "forget", - value: function forget(address) { - // Don't remove it from the set of routers, since that might mean we lose our ability to re-discover, - // just remove it from the set of readers and writers, so that we don't use it for actual work without - // performing discovery first. - this.readers = removeFromArray(this.readers, address); - this.writers = removeFromArray(this.writers, address); - } - }, { - key: "forgetRouter", - value: function forgetRouter(address) { - this.routers = removeFromArray(this.routers, address); - } - }, { - key: "forgetWriter", - value: function forgetWriter(address) { - this.writers = removeFromArray(this.writers, address); - } - /** - * Check if this routing table is fresh to perform the required operation. - * @param {string} accessMode the type of operation. Allowed values are {@link READ} and {@link WRITE}. - * @return {boolean} `true` when this table contains servers to serve the required operation, `false` otherwise. - */ - - }, { - key: "isStaleFor", - value: function isStaleFor(accessMode) { - return this.expirationTime.lessThan(Date.now()) || this.routers.length < MIN_ROUTERS || accessMode === driver.READ && this.readers.length === 0 || accessMode === driver.WRITE && this.writers.length === 0; - } - /** - * Check if this routing table is expired for specified amount of duration - * - * @param {Integer} duration amount of duration in milliseconds to check for expiration - * @returns {boolean} - */ - - }, { - key: "isExpiredFor", - value: function isExpiredFor(duration) { - return this.expirationTime.add(duration).lessThan(Date.now()); - } - }, { - key: "allServers", - value: function allServers() { - return [].concat((0, _toConsumableArray2["default"])(this.routers), (0, _toConsumableArray2["default"])(this.readers), (0, _toConsumableArray2["default"])(this.writers)); - } - }, { - key: "toString", - value: function toString() { - return 'RoutingTable[' + "database=".concat(this.databaseName, ", ") + "expirationTime=".concat(this.expirationTime, ", ") + "currentTime=".concat(Date.now(), ", ") + "routers=[".concat(this.routers, "], ") + "readers=[".concat(this.readers, "], ") + "writers=[".concat(this.writers, "]]"); - } - }]); - return RoutingTable; -}(); -/** - * Remove all occurrences of the element in the array. - * @param {Array} array the array to filter. - * @param {Object} element the element to remove. - * @return {Array} new filtered array. - */ - - -exports["default"] = RoutingTable; - -function removeFromArray(array, element) { - return array.filter(function (item) { - return item.asKey() !== element.asKey(); - }); -} -}); - -createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.VERSION_IN_DEV = exports.VERSION_4_0_0 = exports.VERSION_3_5_0 = exports.VERSION_3_4_0 = exports.VERSION_3_2_0 = exports.ServerVersion = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var SERVER_VERSION_REGEX = new RegExp('^(Neo4j/)?(\\d+)\\.(\\d+)(?:\\.)?(\\d*)(\\.|-|\\+)?([0-9A-Za-z-.]*)?$'); -var NEO4J_IN_DEV_VERSION_STRING = 'Neo4j/dev'; - -var ServerVersion = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {number} major the major version number. - * @param {number} minor the minor version number. - * @param {number} patch the patch version number. - * @param {string} the original version string - */ - function ServerVersion(major, minor, patch, originalVersionString) { - (0, _classCallCheck2["default"])(this, ServerVersion); - this.major = major; - this.minor = minor; - this.patch = patch; - this._originalVersionString = originalVersionString; - } - /** - * Fetch server version using the given driver. - * @param {Driver} driver the driver to use. - * @return {Promise} promise resolved with a {@link ServerVersion} object or rejected with error. - */ - - - (0, _createClass2["default"])(ServerVersion, [{ - key: "compareTo", - - /** - * Compare this version to the given one. - * @param {ServerVersion} other the version to compare with. - * @return {number} value 0 if this version is the same as the given one, value less then 0 when this version - * was released earlier than the given one and value greater then 0 when this version was released after - * than the given one. - */ - value: function compareTo(other) { - var result = compareInts(this.major, other.major); - - if (result === 0) { - result = compareInts(this.minor, other.minor); - - if (result === 0) { - result = compareInts(this.patch, other.patch); - } - } - - return result; - } - }, { - key: "toString", - value: function toString() { - if (this._originalVersionString) { - return this._originalVersionString; - } - - return "".concat(this.major, ".").concat(this.minor, ".").concat(this.patch); - } - }], [{ - key: "fromDriver", - value: function fromDriver(driver) { - var session = driver.session(); - return session.run('RETURN 1').then(function (result) { - return session.close().then(function () { - return ServerVersion.fromString(result.summary.server.version); - }); - }); - } - /** - * Parse given string to a {@link ServerVersion} object. - * @param {string} versionStr the string to parse. - * @return {ServerVersion} version for the given string. - * @throws Error if given string can't be parsed. - */ - - }, { - key: "fromString", - value: function fromString(versionStr) { - if (!versionStr) { - return new ServerVersion(3, 0, 0); - } - - (0, util.assertString)(versionStr, 'Neo4j version string'); - - if (versionStr.toLowerCase() === NEO4J_IN_DEV_VERSION_STRING.toLowerCase()) { - return VERSION_IN_DEV; - } - - var version = versionStr.match(SERVER_VERSION_REGEX); - - if (!version) { - throw new Error("Unparsable Neo4j version: ".concat(versionStr)); - } - - var major = parseIntStrict(version[2]); - var minor = parseIntStrict(version[3]); - var patch = parseIntStrict(version[4] || 0); - return new ServerVersion(major, minor, patch, versionStr); - } - }]); - return ServerVersion; -}(); - -exports.ServerVersion = ServerVersion; - -function parseIntStrict(str, name) { - var value = parseInt(str, 10); - - if (!value && value !== 0) { - throw new Error("Unparsable number ".concat(name, ": '").concat(str, "'")); - } - - return value; -} - -function compareInts(x, y) { - return x < y ? -1 : x === y ? 0 : 1; -} - -var VERSION_3_2_0 = ServerVersion.fromString('Neo4j/3.2.0'); -exports.VERSION_3_2_0 = VERSION_3_2_0; -var VERSION_3_4_0 = ServerVersion.fromString('Neo4j/3.4.0'); -exports.VERSION_3_4_0 = VERSION_3_4_0; -var VERSION_3_5_0 = ServerVersion.fromString('Neo4j/3.5.0'); -exports.VERSION_3_5_0 = VERSION_3_5_0; -var VERSION_4_0_0 = ServerVersion.fromString('Neo4j/4.0.0'); -exports.VERSION_4_0_0 = VERSION_4_0_0; -var maxVer = Number.MAX_SAFE_INTEGER; -var VERSION_IN_DEV = new ServerVersion(maxVer, maxVer, maxVer, NEO4J_IN_DEV_VERSION_STRING); -exports.VERSION_IN_DEV = VERSION_IN_DEV; -}); - -/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ - -var uri_all = createCommonjsModule(function (module, exports) { -(function (global, factory) { - factory(exports) ; -}(commonjsGlobal, (function (exports) { -function merge() { - for (var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++) { - sets[_key] = arguments[_key]; - } - - if (sets.length > 1) { - sets[0] = sets[0].slice(0, -1); - var xl = sets.length - 1; - for (var x = 1; x < xl; ++x) { - sets[x] = sets[x].slice(1, -1); - } - sets[xl] = sets[xl].slice(1); - return sets.join(''); - } else { - return sets[0]; - } -} -function subexp(str) { - return "(?:" + str + ")"; -} -function typeOf(o) { - return o === undefined ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase(); -} -function toUpperCase(str) { - return str.toUpperCase(); -} -function toArray(obj) { - return obj !== undefined && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : []; -} -function assign(target, source) { - var obj = target; - if (source) { - for (var key in source) { - obj[key] = source[key]; - } - } - return obj; -} - -function buildExps(isIRI) { - var ALPHA$$ = "[A-Za-z]", - DIGIT$$ = "[0-9]", - HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), - PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), - //expanded - GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", - SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", - RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), - UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", - //subset, excludes bidi control characters - IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", - //subset - UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$); - subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"); - subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"); - var DEC_OCTET_RELAXED$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$), - //relaxed parsing rules - IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), - H16$ = subexp(HEXDIG$$ + "{1,4}"), - LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), - IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), - // 6( h16 ":" ) ls32 - IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), - // "::" 5( h16 ":" ) ls32 - IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), - //[ h16 ] "::" 4( h16 ":" ) ls32 - IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), - //[ *1( h16 ":" ) h16 ] "::" 3( h16 ":" ) ls32 - IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), - //[ *2( h16 ":" ) h16 ] "::" 2( h16 ":" ) ls32 - IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), - //[ *3( h16 ":" ) h16 ] "::" h16 ":" ls32 - IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), - //[ *4( h16 ":" ) h16 ] "::" ls32 - IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), - //[ *5( h16 ":" ) h16 ] "::" h16 - IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), - //[ *6( h16 ":" ) h16 ] "::" - IPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join("|")), - ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"); - //RFC 6874, with relaxed parsing rules - subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"); - //RFC 6874 - subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"); - var PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")); - subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"); - subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*"); - return { - NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"), - NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"), - NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"), - NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"), - ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"), - UNRESERVED: new RegExp(UNRESERVED$$, "g"), - OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"), - PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"), - IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"), - IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$") //RFC 6874, with relaxed parsing rules - }; -} -var URI_PROTOCOL = buildExps(false); - -var IRI_PROTOCOL = buildExps(true); - -var slicedToArray = function () { - function sliceIterator(arr, i) { - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"]) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - return function (arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if (Symbol.iterator in Object(arr)) { - return sliceIterator(arr, i); - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } - }; -}(); - - - - - - - - - - - - - -var toConsumableArray = function (arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; - - return arr2; - } else { - return Array.from(arr); - } -}; - -/** Highest positive signed 32-bit float value */ - -var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 - -/** Bootstring parameters */ -var base = 36; -var tMin = 1; -var tMax = 26; -var skew = 38; -var damp = 700; -var initialBias = 72; -var initialN = 128; // 0x80 -var delimiter = '-'; // '\x2D' - -/** Regular expressions */ -var regexPunycode = /^xn--/; -var regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars -var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators - -/** Error messages */ -var errors = { - 'overflow': 'Overflow: input needs wider integers to process', - 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', - 'invalid-input': 'Invalid input' -}; - -/** Convenience shortcuts */ -var baseMinusTMin = base - tMin; -var floor = Math.floor; -var stringFromCharCode = String.fromCharCode; - -/*--------------------------------------------------------------------------*/ - -/** - * A generic error utility function. - * @private - * @param {String} type The error type. - * @returns {Error} Throws a `RangeError` with the applicable error message. - */ -function error$1(type) { - throw new RangeError(errors[type]); -} - -/** - * A generic `Array#map` utility function. - * @private - * @param {Array} array The array to iterate over. - * @param {Function} callback The function that gets called for every array - * item. - * @returns {Array} A new array of values returned by the callback function. - */ -function map(array, fn) { - var result = []; - var length = array.length; - while (length--) { - result[length] = fn(array[length]); - } - return result; -} - -/** - * A simple `Array#map`-like wrapper to work with domain name strings or email - * addresses. - * @private - * @param {String} domain The domain name or email address. - * @param {Function} callback The function that gets called for every - * character. - * @returns {Array} A new string of characters returned by the callback - * function. - */ -function mapDomain(string, fn) { - var parts = string.split('@'); - var result = ''; - if (parts.length > 1) { - // In email addresses, only the domain name should be punycoded. Leave - // the local part (i.e. everything up to `@`) intact. - result = parts[0] + '@'; - string = parts[1]; - } - // Avoid `split(regex)` for IE8 compatibility. See #17. - string = string.replace(regexSeparators, '\x2E'); - var labels = string.split('.'); - var encoded = map(labels, fn).join('.'); - return result + encoded; -} - -/** - * Creates an array containing the numeric code points of each Unicode - * character in the string. While JavaScript uses UCS-2 internally, - * this function will convert a pair of surrogate halves (each of which - * UCS-2 exposes as separate characters) into a single code point, - * matching UTF-16. - * @see `punycode.ucs2.encode` - * @see - * @memberOf punycode.ucs2 - * @name decode - * @param {String} string The Unicode input string (UCS-2). - * @returns {Array} The new array of code points. - */ -function ucs2decode(string) { - var output = []; - var counter = 0; - var length = string.length; - while (counter < length) { - var value = string.charCodeAt(counter++); - if (value >= 0xD800 && value <= 0xDBFF && counter < length) { - // It's a high surrogate, and there is a next character. - var extra = string.charCodeAt(counter++); - if ((extra & 0xFC00) == 0xDC00) { - // Low surrogate. - output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); - } else { - // It's an unmatched surrogate; only append this code unit, in case the - // next code unit is the high surrogate of a surrogate pair. - output.push(value); - counter--; - } - } else { - output.push(value); - } - } - return output; -} - -/** - * Creates a string based on an array of numeric code points. - * @see `punycode.ucs2.decode` - * @memberOf punycode.ucs2 - * @name encode - * @param {Array} codePoints The array of numeric code points. - * @returns {String} The new Unicode string (UCS-2). - */ -var ucs2encode = function ucs2encode(array) { - return String.fromCodePoint.apply(String, toConsumableArray(array)); -}; - -/** - * Converts a basic code point into a digit/integer. - * @see `digitToBasic()` - * @private - * @param {Number} codePoint The basic numeric code point value. - * @returns {Number} The numeric value of a basic code point (for use in - * representing integers) in the range `0` to `base - 1`, or `base` if - * the code point does not represent a value. - */ -var basicToDigit = function basicToDigit(codePoint) { - if (codePoint - 0x30 < 0x0A) { - return codePoint - 0x16; - } - if (codePoint - 0x41 < 0x1A) { - return codePoint - 0x41; - } - if (codePoint - 0x61 < 0x1A) { - return codePoint - 0x61; - } - return base; -}; - -/** - * Converts a digit/integer into a basic code point. - * @see `basicToDigit()` - * @private - * @param {Number} digit The numeric value of a basic code point. - * @returns {Number} The basic code point whose value (when used for - * representing integers) is `digit`, which needs to be in the range - * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is - * used; else, the lowercase form is used. The behavior is undefined - * if `flag` is non-zero and `digit` has no uppercase form. - */ -var digitToBasic = function digitToBasic(digit, flag) { - // 0..25 map to ASCII a..z or A..Z - // 26..35 map to ASCII 0..9 - return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); -}; - -/** - * Bias adaptation function as per section 3.4 of RFC 3492. - * https://tools.ietf.org/html/rfc3492#section-3.4 - * @private - */ -var adapt = function adapt(delta, numPoints, firstTime) { - var k = 0; - delta = firstTime ? floor(delta / damp) : delta >> 1; - delta += floor(delta / numPoints); - for (; /* no initialization */delta > baseMinusTMin * tMax >> 1; k += base) { - delta = floor(delta / baseMinusTMin); - } - return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); -}; - -/** - * Converts a Punycode string of ASCII-only symbols to a string of Unicode - * symbols. - * @memberOf punycode - * @param {String} input The Punycode string of ASCII-only symbols. - * @returns {String} The resulting string of Unicode symbols. - */ -var decode = function decode(input) { - // Don't use UCS-2. - var output = []; - var inputLength = input.length; - var i = 0; - var n = initialN; - var bias = initialBias; - - // Handle the basic code points: let `basic` be the number of input code - // points before the last delimiter, or `0` if there is none, then copy - // the first basic code points to the output. - - var basic = input.lastIndexOf(delimiter); - if (basic < 0) { - basic = 0; - } - - for (var j = 0; j < basic; ++j) { - // if it's not a basic code point - if (input.charCodeAt(j) >= 0x80) { - error$1('not-basic'); - } - output.push(input.charCodeAt(j)); - } - - // Main decoding loop: start just after the last delimiter if any basic code - // points were copied; start at the beginning otherwise. - - for (var index = basic > 0 ? basic + 1 : 0; index < inputLength;) /* no final expression */{ - - // `index` is the index of the next character to be consumed. - // Decode a generalized variable-length integer into `delta`, - // which gets added to `i`. The overflow checking is easier - // if we increase `i` as we go, then subtract off its starting - // value at the end to obtain `delta`. - var oldi = i; - for (var w = 1, k = base;; /* no condition */k += base) { - - if (index >= inputLength) { - error$1('invalid-input'); - } - - var digit = basicToDigit(input.charCodeAt(index++)); - - if (digit >= base || digit > floor((maxInt - i) / w)) { - error$1('overflow'); - } - - i += digit * w; - var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - - if (digit < t) { - break; - } - - var baseMinusT = base - t; - if (w > floor(maxInt / baseMinusT)) { - error$1('overflow'); - } - - w *= baseMinusT; - } - - var out = output.length + 1; - bias = adapt(i - oldi, out, oldi == 0); - - // `i` was supposed to wrap around from `out` to `0`, - // incrementing `n` each time, so we'll fix that now: - if (floor(i / out) > maxInt - n) { - error$1('overflow'); - } - - n += floor(i / out); - i %= out; - - // Insert `n` at position `i` of the output. - output.splice(i++, 0, n); - } - - return String.fromCodePoint.apply(String, output); -}; - -/** - * Converts a string of Unicode symbols (e.g. a domain name label) to a - * Punycode string of ASCII-only symbols. - * @memberOf punycode - * @param {String} input The string of Unicode symbols. - * @returns {String} The resulting Punycode string of ASCII-only symbols. - */ -var encode = function encode(input) { - var output = []; - - // Convert the input in UCS-2 to an array of Unicode code points. - input = ucs2decode(input); - - // Cache the length. - var inputLength = input.length; - - // Initialize the state. - var n = initialN; - var delta = 0; - var bias = initialBias; - - // Handle the basic code points. - var _iteratorNormalCompletion = true; - var _didIteratorError = false; - var _iteratorError = undefined; - - try { - for (var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { - var _currentValue2 = _step.value; - - if (_currentValue2 < 0x80) { - output.push(stringFromCharCode(_currentValue2)); - } - } - } catch (err) { - _didIteratorError = true; - _iteratorError = err; - } finally { - try { - if (!_iteratorNormalCompletion && _iterator.return) { - _iterator.return(); - } - } finally { - if (_didIteratorError) { - throw _iteratorError; - } - } - } - - var basicLength = output.length; - var handledCPCount = basicLength; - - // `handledCPCount` is the number of code points that have been handled; - // `basicLength` is the number of basic code points. - - // Finish the basic string with a delimiter unless it's empty. - if (basicLength) { - output.push(delimiter); - } - - // Main encoding loop: - while (handledCPCount < inputLength) { - - // All non-basic code points < n have been handled already. Find the next - // larger one: - var m = maxInt; - var _iteratorNormalCompletion2 = true; - var _didIteratorError2 = false; - var _iteratorError2 = undefined; - - try { - for (var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { - var currentValue = _step2.value; - - if (currentValue >= n && currentValue < m) { - m = currentValue; - } - } - - // Increase `delta` enough to advance the decoder's state to , - // but guard against overflow. - } catch (err) { - _didIteratorError2 = true; - _iteratorError2 = err; - } finally { - try { - if (!_iteratorNormalCompletion2 && _iterator2.return) { - _iterator2.return(); - } - } finally { - if (_didIteratorError2) { - throw _iteratorError2; - } - } - } - - var handledCPCountPlusOne = handledCPCount + 1; - if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { - error$1('overflow'); - } - - delta += (m - n) * handledCPCountPlusOne; - n = m; - - var _iteratorNormalCompletion3 = true; - var _didIteratorError3 = false; - var _iteratorError3 = undefined; - - try { - for (var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { - var _currentValue = _step3.value; - - if (_currentValue < n && ++delta > maxInt) { - error$1('overflow'); - } - if (_currentValue == n) { - // Represent delta as a generalized variable-length integer. - var q = delta; - for (var k = base;; /* no condition */k += base) { - var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias; - if (q < t) { - break; - } - var qMinusT = q - t; - var baseMinusT = base - t; - output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))); - q = floor(qMinusT / baseMinusT); - } - - output.push(stringFromCharCode(digitToBasic(q, 0))); - bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); - delta = 0; - ++handledCPCount; - } - } - } catch (err) { - _didIteratorError3 = true; - _iteratorError3 = err; - } finally { - try { - if (!_iteratorNormalCompletion3 && _iterator3.return) { - _iterator3.return(); - } - } finally { - if (_didIteratorError3) { - throw _iteratorError3; - } - } - } - - ++delta; - ++n; - } - return output.join(''); -}; - -/** - * Converts a Punycode string representing a domain name or an email address - * to Unicode. Only the Punycoded parts of the input will be converted, i.e. - * it doesn't matter if you call it on a string that has already been - * converted to Unicode. - * @memberOf punycode - * @param {String} input The Punycoded domain name or email address to - * convert to Unicode. - * @returns {String} The Unicode representation of the given Punycode - * string. - */ -var toUnicode = function toUnicode(input) { - return mapDomain(input, function (string) { - return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; - }); -}; - -/** - * Converts a Unicode string representing a domain name or an email address to - * Punycode. Only the non-ASCII parts of the domain name will be converted, - * i.e. it doesn't matter if you call it with a domain that's already in - * ASCII. - * @memberOf punycode - * @param {String} input The domain name or email address to convert, as a - * Unicode string. - * @returns {String} The Punycode representation of the given domain name or - * email address. - */ -var toASCII = function toASCII(input) { - return mapDomain(input, function (string) { - return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; - }); -}; - -/*--------------------------------------------------------------------------*/ - -/** Define the public API */ -var punycode = { - /** - * A string representing the current Punycode.js version number. - * @memberOf punycode - * @type String - */ - 'version': '2.1.0', - /** - * An object of methods to convert from JavaScript's internal character - * representation (UCS-2) to Unicode code points, and back. - * @see - * @memberOf punycode - * @type Object - */ - 'ucs2': { - 'decode': ucs2decode, - 'encode': ucs2encode - }, - 'decode': decode, - 'encode': encode, - 'toASCII': toASCII, - 'toUnicode': toUnicode -}; - -/** - * URI.js - * - * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. - * @author Gary Court - * @see http://github.com/garycourt/uri-js - */ -/** - * Copyright 2011 Gary Court. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without modification, are - * permitted provided that the following conditions are met: - * - * 1. Redistributions of source code must retain the above copyright notice, this list of - * conditions and the following disclaimer. - * - * 2. Redistributions in binary form must reproduce the above copyright notice, this list - * of conditions and the following disclaimer in the documentation and/or other materials - * provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED - * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND - * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - * - * The views and conclusions contained in the software and documentation are those of the - * authors and should not be interpreted as representing official policies, either expressed - * or implied, of Gary Court. - */ -var SCHEMES = {}; -function pctEncChar(chr) { - var c = chr.charCodeAt(0); - var e = void 0; - if (c < 16) e = "%0" + c.toString(16).toUpperCase();else if (c < 128) e = "%" + c.toString(16).toUpperCase();else if (c < 2048) e = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();else e = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase(); - return e; -} -function pctDecChars(str) { - var newStr = ""; - var i = 0; - var il = str.length; - while (i < il) { - var c = parseInt(str.substr(i + 1, 2), 16); - if (c < 128) { - newStr += String.fromCharCode(c); - i += 3; - } else if (c >= 194 && c < 224) { - if (il - i >= 6) { - var c2 = parseInt(str.substr(i + 4, 2), 16); - newStr += String.fromCharCode((c & 31) << 6 | c2 & 63); - } else { - newStr += str.substr(i, 6); - } - i += 6; - } else if (c >= 224) { - if (il - i >= 9) { - var _c = parseInt(str.substr(i + 4, 2), 16); - var c3 = parseInt(str.substr(i + 7, 2), 16); - newStr += String.fromCharCode((c & 15) << 12 | (_c & 63) << 6 | c3 & 63); - } else { - newStr += str.substr(i, 9); - } - i += 9; - } else { - newStr += str.substr(i, 3); - i += 3; - } - } - return newStr; -} -function _normalizeComponentEncoding(components, protocol) { - function decodeUnreserved(str) { - var decStr = pctDecChars(str); - return !decStr.match(protocol.UNRESERVED) ? str : decStr; - } - if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, ""); - if (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - if (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase); - return components; -} - -function _stripLeadingZeros(str) { - return str.replace(/^0*(.*)/, "$1") || "0"; -} -function _normalizeIPv4(host, protocol) { - var matches = host.match(protocol.IPV4ADDRESS) || []; - - var _matches = slicedToArray(matches, 2), - address = _matches[1]; - - if (address) { - return address.split(".").map(_stripLeadingZeros).join("."); - } else { - return host; - } -} -function _normalizeIPv6(host, protocol) { - var matches = host.match(protocol.IPV6ADDRESS) || []; - - var _matches2 = slicedToArray(matches, 3), - address = _matches2[1], - zone = _matches2[2]; - - if (address) { - var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), - _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), - last = _address$toLowerCase$2[0], - first = _address$toLowerCase$2[1]; - - var firstFields = first ? first.split(":").map(_stripLeadingZeros) : []; - var lastFields = last.split(":").map(_stripLeadingZeros); - var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]); - var fieldCount = isLastFieldIPv4Address ? 7 : 8; - var lastFieldsStart = lastFields.length - fieldCount; - var fields = Array(fieldCount); - for (var x = 0; x < fieldCount; ++x) { - fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || ''; - } - if (isLastFieldIPv4Address) { - fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol); - } - var allZeroFields = fields.reduce(function (acc, field, index) { - if (!field || field === "0") { - var lastLongest = acc[acc.length - 1]; - if (lastLongest && lastLongest.index + lastLongest.length === index) { - lastLongest.length++; - } else { - acc.push({ index: index, length: 1 }); - } - } - return acc; - }, []); - var longestZeroFields = allZeroFields.sort(function (a, b) { - return b.length - a.length; - })[0]; - var newHost = void 0; - if (longestZeroFields && longestZeroFields.length > 1) { - var newFirst = fields.slice(0, longestZeroFields.index); - var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length); - newHost = newFirst.join(":") + "::" + newLast.join(":"); - } else { - newHost = fields.join(":"); - } - if (zone) { - newHost += "%" + zone; - } - return newHost; - } else { - return host; - } -} -var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i; -var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === undefined; -function parse(uriString) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var components = {}; - var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; - if (options.reference === "suffix") uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString; - var matches = uriString.match(URI_PARSE); - if (matches) { - if (NO_MATCH_IS_UNDEFINED) { - //store each component - components.scheme = matches[1]; - components.userinfo = matches[3]; - components.host = matches[4]; - components.port = parseInt(matches[5], 10); - components.path = matches[6] || ""; - components.query = matches[7]; - components.fragment = matches[8]; - //fix port number - if (isNaN(components.port)) { - components.port = matches[5]; - } - } else { - //IE FIX for improper RegExp matching - //store each component - components.scheme = matches[1] || undefined; - components.userinfo = uriString.indexOf("@") !== -1 ? matches[3] : undefined; - components.host = uriString.indexOf("//") !== -1 ? matches[4] : undefined; - components.port = parseInt(matches[5], 10); - components.path = matches[6] || ""; - components.query = uriString.indexOf("?") !== -1 ? matches[7] : undefined; - components.fragment = uriString.indexOf("#") !== -1 ? matches[8] : undefined; - //fix port number - if (isNaN(components.port)) { - components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : undefined; - } - } - if (components.host) { - //normalize IP hosts - components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol); - } - //determine reference type - if (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) { - components.reference = "same-document"; - } else if (components.scheme === undefined) { - components.reference = "relative"; - } else if (components.fragment === undefined) { - components.reference = "absolute"; - } else { - components.reference = "uri"; - } - //check for reference errors - if (options.reference && options.reference !== "suffix" && options.reference !== components.reference) { - components.error = components.error || "URI is not a " + options.reference + " reference."; - } - //find scheme handler - var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; - //check if scheme can't handle IRIs - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - //if host component is a domain name - if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) { - //convert Unicode IDN -> ASCII IDN - try { - components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()); - } catch (e) { - components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e; - } - } - //convert IRI -> URI - _normalizeComponentEncoding(components, URI_PROTOCOL); - } else { - //normalize encodings - _normalizeComponentEncoding(components, protocol); - } - //perform scheme specific parsing - if (schemeHandler && schemeHandler.parse) { - schemeHandler.parse(components, options); - } - } else { - components.error = components.error || "URI can not be parsed."; - } - return components; -} - -function _recomposeAuthority(components, options) { - var protocol = options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL; - var uriTokens = []; - if (components.userinfo !== undefined) { - uriTokens.push(components.userinfo); - uriTokens.push("@"); - } - if (components.host !== undefined) { - //normalize IP hosts, add brackets and escape zone separator for IPv6 - uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function (_, $1, $2) { - return "[" + $1 + ($2 ? "%25" + $2 : "") + "]"; - })); - } - if (typeof components.port === "number" || typeof components.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(components.port)); - } - return uriTokens.length ? uriTokens.join("") : undefined; -} - -var RDS1 = /^\.\.?\//; -var RDS2 = /^\/\.(\/|$)/; -var RDS3 = /^\/\.\.(\/|$)/; -var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/; -function removeDotSegments(input) { - var output = []; - while (input.length) { - if (input.match(RDS1)) { - input = input.replace(RDS1, ""); - } else if (input.match(RDS2)) { - input = input.replace(RDS2, "/"); - } else if (input.match(RDS3)) { - input = input.replace(RDS3, "/"); - output.pop(); - } else if (input === "." || input === "..") { - input = ""; - } else { - var im = input.match(RDS5); - if (im) { - var s = im[0]; - input = input.slice(s.length); - output.push(s); - } else { - throw new Error("Unexpected dot segment condition"); - } - } - } - return output.join(""); -} - -function serialize(components) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - - var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL; - var uriTokens = []; - //find scheme handler - var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()]; - //perform scheme specific serialization - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options); - if (components.host) { - //if host component is an IPv6 address - if (protocol.IPV6ADDRESS.test(components.host)) ; - //TODO: normalize IPv6 address as per RFC 5952 - - //if host component is a domain name - else if (options.domainHost || schemeHandler && schemeHandler.domainHost) { - //convert IDN via punycode - try { - components.host = !options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host); - } catch (e) { - components.error = components.error || "Host's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; - } - } - } - //normalize encoding - _normalizeComponentEncoding(components, protocol); - if (options.reference !== "suffix" && components.scheme) { - uriTokens.push(components.scheme); - uriTokens.push(":"); - } - var authority = _recomposeAuthority(components, options); - if (authority !== undefined) { - if (options.reference !== "suffix") { - uriTokens.push("//"); - } - uriTokens.push(authority); - if (components.path && components.path.charAt(0) !== "/") { - uriTokens.push("/"); - } - } - if (components.path !== undefined) { - var s = components.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { - s = removeDotSegments(s); - } - if (authority === undefined) { - s = s.replace(/^\/\//, "/%2F"); //don't allow the path to start with "//" - } - uriTokens.push(s); - } - if (components.query !== undefined) { - uriTokens.push("?"); - uriTokens.push(components.query); - } - if (components.fragment !== undefined) { - uriTokens.push("#"); - uriTokens.push(components.fragment); - } - return uriTokens.join(""); //merge tokens into a string -} - -function resolveComponents(base, relative) { - var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - var skipNormalization = arguments[3]; - - var target = {}; - if (!skipNormalization) { - base = parse(serialize(base, options), options); //normalize base components - relative = parse(serialize(relative, options), options); //normalize relative components - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - //target.authority = relative.authority; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { - //target.authority = relative.authority; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== undefined) { - target.query = relative.query; - } else { - target.query = base.query; - } - } else { - if (relative.path.charAt(0) === "/") { - target.path = removeDotSegments(relative.path); - } else { - if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { - target.path = "/" + relative.path; - } else if (!base.path) { - target.path = relative.path; - } else { - target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; - } - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - //target.authority = base.authority; - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target; -} - -function resolve(baseURI, relativeURI, options) { - var schemelessOptions = assign({ scheme: 'null' }, options); - return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions); -} - -function normalize(uri, options) { - if (typeof uri === "string") { - uri = serialize(parse(uri, options), options); - } else if (typeOf(uri) === "object") { - uri = parse(serialize(uri, options), options); - } - return uri; -} - -function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = serialize(parse(uriA, options), options); - } else if (typeOf(uriA) === "object") { - uriA = serialize(uriA, options); - } - if (typeof uriB === "string") { - uriB = serialize(parse(uriB, options), options); - } else if (typeOf(uriB) === "object") { - uriB = serialize(uriB, options); - } - return uriA === uriB; -} - -function escapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar); -} - -function unescapeComponent(str, options) { - return str && str.toString().replace(!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars); -} - -var handler = { - scheme: "http", - domainHost: true, - parse: function parse(components, options) { - //report missing host - if (!components.host) { - components.error = components.error || "HTTP URIs must have a host."; - } - return components; - }, - serialize: function serialize(components, options) { - var secure = String(components.scheme).toLowerCase() === "https"; - //normalize the default port - if (components.port === (secure ? 443 : 80) || components.port === "") { - components.port = undefined; - } - //normalize the empty path - if (!components.path) { - components.path = "/"; - } - //NOTE: We do not parse query strings for HTTP URIs - //as WWW Form Url Encoded query strings are part of the HTML4+ spec, - //and not the HTTP spec. - return components; - } -}; - -var handler$1 = { - scheme: "https", - domainHost: handler.domainHost, - parse: handler.parse, - serialize: handler.serialize -}; - -function isSecure(wsComponents) { - return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss"; -} -//RFC 6455 -var handler$2 = { - scheme: "ws", - domainHost: true, - parse: function parse(components, options) { - var wsComponents = components; - //indicate if the secure flag is set - wsComponents.secure = isSecure(wsComponents); - //construct resouce name - wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : ''); - wsComponents.path = undefined; - wsComponents.query = undefined; - return wsComponents; - }, - serialize: function serialize(wsComponents, options) { - //normalize the default port - if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") { - wsComponents.port = undefined; - } - //ensure scheme matches secure flag - if (typeof wsComponents.secure === 'boolean') { - wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws'; - wsComponents.secure = undefined; - } - //reconstruct path from resource name - if (wsComponents.resourceName) { - var _wsComponents$resourc = wsComponents.resourceName.split('?'), - _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), - path = _wsComponents$resourc2[0], - query = _wsComponents$resourc2[1]; - - wsComponents.path = path && path !== '/' ? path : undefined; - wsComponents.query = query; - wsComponents.resourceName = undefined; - } - //forbid fragment component - wsComponents.fragment = undefined; - return wsComponents; - } -}; - -var handler$3 = { - scheme: "wss", - domainHost: handler$2.domainHost, - parse: handler$2.parse, - serialize: handler$2.serialize -}; - -var O = {}; -//RFC 3986 -var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + ("\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" ) + "]"; -var HEXDIG$$ = "[0-9A-Fa-f]"; //case-insensitive -var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)); //expanded -//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; = -//const ATEXT$$ = "[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~]"; -//const WSP$$ = "[\\x20\\x09]"; -//const OBS_QTEXT$$ = "[\\x01-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F]"; //(%d1-8 / %d11-12 / %d14-31 / %d127) -//const QTEXT$$ = merge("[\\x21\\x23-\\x5B\\x5D-\\x7E]", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext -//const VCHAR$$ = "[\\x21-\\x7E]"; -//const WSP$$ = "[\\x20\\x09]"; -//const OBS_QP$ = subexp("\\\\" + merge("[\\x00\\x0D\\x0A]", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext -//const FWS$ = subexp(subexp(WSP$$ + "*" + "\\x0D\\x0A") + "?" + WSP$$ + "+"); -//const QUOTED_PAIR$ = subexp(subexp("\\\\" + subexp(VCHAR$$ + "|" + WSP$$)) + "|" + OBS_QP$); -//const QUOTED_STRING$ = subexp('\\"' + subexp(FWS$ + "?" + QCONTENT$) + "*" + FWS$ + "?" + '\\"'); -var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]"; -var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]"; -var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]"); -var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]"; -var UNRESERVED = new RegExp(UNRESERVED$$, "g"); -var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g"); -var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g"); -var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g"); -var NOT_HFVALUE = NOT_HFNAME; -function decodeUnreserved(str) { - var decStr = pctDecChars(str); - return !decStr.match(UNRESERVED) ? str : decStr; -} -var handler$4 = { - scheme: "mailto", - parse: function parse$$1(components, options) { - var mailtoComponents = components; - var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : []; - mailtoComponents.path = undefined; - if (mailtoComponents.query) { - var unknownHeaders = false; - var headers = {}; - var hfields = mailtoComponents.query.split("&"); - for (var x = 0, xl = hfields.length; x < xl; ++x) { - var hfield = hfields[x].split("="); - switch (hfield[0]) { - case "to": - var toAddrs = hfield[1].split(","); - for (var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x) { - to.push(toAddrs[_x]); - } - break; - case "subject": - mailtoComponents.subject = unescapeComponent(hfield[1], options); - break; - case "body": - mailtoComponents.body = unescapeComponent(hfield[1], options); - break; - default: - unknownHeaders = true; - headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options); - break; - } - } - if (unknownHeaders) mailtoComponents.headers = headers; - } - mailtoComponents.query = undefined; - for (var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2) { - var addr = to[_x2].split("@"); - addr[0] = unescapeComponent(addr[0]); - if (!options.unicodeSupport) { - //convert Unicode IDN -> ASCII IDN - try { - addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase()); - } catch (e) { - mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e; - } - } else { - addr[1] = unescapeComponent(addr[1], options).toLowerCase(); - } - to[_x2] = addr.join("@"); - } - return mailtoComponents; - }, - serialize: function serialize$$1(mailtoComponents, options) { - var components = mailtoComponents; - var to = toArray(mailtoComponents.to); - if (to) { - for (var x = 0, xl = to.length; x < xl; ++x) { - var toAddr = String(to[x]); - var atIdx = toAddr.lastIndexOf("@"); - var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar); - var domain = toAddr.slice(atIdx + 1); - //convert IDN via punycode - try { - domain = !options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain); - } catch (e) { - components.error = components.error || "Email address's domain name can not be converted to " + (!options.iri ? "ASCII" : "Unicode") + " via punycode: " + e; - } - to[x] = localPart + "@" + domain; - } - components.path = to.join(","); - } - var headers = mailtoComponents.headers = mailtoComponents.headers || {}; - if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject; - if (mailtoComponents.body) headers["body"] = mailtoComponents.body; - var fields = []; - for (var name in headers) { - if (headers[name] !== O[name]) { - fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)); - } - } - if (fields.length) { - components.query = fields.join("&"); - } - return components; - } -}; - -var URN_PARSE = /^([^\:]+)\:(.*)/; -//RFC 2141 -var handler$5 = { - scheme: "urn", - parse: function parse$$1(components, options) { - var matches = components.path && components.path.match(URN_PARSE); - var urnComponents = components; - if (matches) { - var scheme = options.scheme || urnComponents.scheme || "urn"; - var nid = matches[1].toLowerCase(); - var nss = matches[2]; - var urnScheme = scheme + ":" + (options.nid || nid); - var schemeHandler = SCHEMES[urnScheme]; - urnComponents.nid = nid; - urnComponents.nss = nss; - urnComponents.path = undefined; - if (schemeHandler) { - urnComponents = schemeHandler.parse(urnComponents, options); - } - } else { - urnComponents.error = urnComponents.error || "URN can not be parsed."; - } - return urnComponents; - }, - serialize: function serialize$$1(urnComponents, options) { - var scheme = options.scheme || urnComponents.scheme || "urn"; - var nid = urnComponents.nid; - var urnScheme = scheme + ":" + (options.nid || nid); - var schemeHandler = SCHEMES[urnScheme]; - if (schemeHandler) { - urnComponents = schemeHandler.serialize(urnComponents, options); - } - var uriComponents = urnComponents; - var nss = urnComponents.nss; - uriComponents.path = (nid || options.nid) + ":" + nss; - return uriComponents; - } -}; - -var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/; -//RFC 4122 -var handler$6 = { - scheme: "urn:uuid", - parse: function parse(urnComponents, options) { - var uuidComponents = urnComponents; - uuidComponents.uuid = uuidComponents.nss; - uuidComponents.nss = undefined; - if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) { - uuidComponents.error = uuidComponents.error || "UUID is not valid."; - } - return uuidComponents; - }, - serialize: function serialize(uuidComponents, options) { - var urnComponents = uuidComponents; - //normalize UUID - urnComponents.nss = (uuidComponents.uuid || "").toLowerCase(); - return urnComponents; - } -}; - -SCHEMES[handler.scheme] = handler; -SCHEMES[handler$1.scheme] = handler$1; -SCHEMES[handler$2.scheme] = handler$2; -SCHEMES[handler$3.scheme] = handler$3; -SCHEMES[handler$4.scheme] = handler$4; -SCHEMES[handler$5.scheme] = handler$5; -SCHEMES[handler$6.scheme] = handler$6; - -exports.SCHEMES = SCHEMES; -exports.pctEncChar = pctEncChar; -exports.pctDecChars = pctDecChars; -exports.parse = parse; -exports.removeDotSegments = removeDotSegments; -exports.serialize = serialize; -exports.resolveComponents = resolveComponents; -exports.resolve = resolve; -exports.normalize = normalize; -exports.equal = equal; -exports.escapeComponent = escapeComponent; -exports.unescapeComponent = unescapeComponent; - -Object.defineProperty(exports, '__esModule', { value: true }); - -}))); - -}); - -var urlUtil = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _slicedToArray2 = interopRequireDefault(slicedToArray); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var DEFAULT_BOLT_PORT = 7687; -var DEFAULT_HTTP_PORT = 7474; -var DEFAULT_HTTPS_PORT = 7473; - -var Url = function Url(scheme, host, port, hostAndPort, query) { - (0, _classCallCheck2["default"])(this, Url); - - /** - * Nullable scheme (protocol) of the URL. - * Example: 'bolt', 'neo4j', 'http', 'https', etc. - * @type {string} - */ - this.scheme = scheme; - /** - * Nonnull host name or IP address. IPv6 not wrapped in square brackets. - * Example: 'neo4j.com', 'localhost', '127.0.0.1', '192.168.10.15', '::1', '2001:4860:4860::8844', etc. - * @type {string} - */ - - this.host = host; - /** - * Nonnull number representing port. Default port for the given scheme is used if given URL string - * does not contain port. Example: 7687 for bolt, 7474 for HTTP and 7473 for HTTPS. - * @type {number} - */ - - this.port = port; - /** - * Nonnull host name or IP address plus port, separated by ':'. IPv6 wrapped in square brackets. - * Example: 'neo4j.com', 'neo4j.com:7687', '127.0.0.1', '127.0.0.1:8080', '[2001:4860:4860::8844]', - * '[2001:4860:4860::8844]:9090', etc. - * @type {string} - */ - - this.hostAndPort = hostAndPort; - /** - * Nonnull object representing parsed query string key-value pairs. Duplicated keys not supported. - * Example: '{}', '{'key1': 'value1', 'key2': 'value2'}', etc. - * @type {Object} - */ - - this.query = query; -}; - -function parseDatabaseUrl(url) { - (0, util.assertString)(url, 'URL'); - var sanitized = sanitizeUrl(url); - var parsedUrl = (0, uri_all.parse)(sanitized.url); - var scheme = sanitized.schemeMissing ? null : extractScheme(parsedUrl.scheme); - var host = extractHost(parsedUrl.host); // no square brackets for IPv6 - - var formattedHost = formatHost(host); // has square brackets for IPv6 - - var port = extractPort(parsedUrl.port, scheme); - var hostAndPort = "".concat(formattedHost, ":").concat(port); - var query = extractQuery(parsedUrl.query || extractResourceQueryString(parsedUrl.resourceName), url); - return new Url(scheme, host, port, hostAndPort, query); -} - -function extractResourceQueryString(resource) { - if (typeof resource !== 'string') { - return null; - } - - var _resource$split = resource.split('?'), - _resource$split2 = (0, _slicedToArray2["default"])(_resource$split, 2); - _resource$split2[0]; - var query = _resource$split2[1]; - - return query; -} - -function sanitizeUrl(url) { - url = url.trim(); - - if (url.indexOf('://') === -1) { - // url does not contain scheme, add dummy 'none://' to make parser work correctly - return { - schemeMissing: true, - url: "none://".concat(url) - }; - } - - return { - schemeMissing: false, - url: url - }; -} - -function extractScheme(scheme) { - if (scheme) { - scheme = scheme.trim(); - - if (scheme.charAt(scheme.length - 1) === ':') { - scheme = scheme.substring(0, scheme.length - 1); - } - - return scheme; - } - - return null; -} - -function extractHost(host, url) { - if (!host) { - throw new Error("Unable to extract host from ".concat(url)); - } - - return host.trim(); -} - -function extractPort(portString, scheme) { - var port = parseInt(portString, 10); - return port === 0 || port ? port : defaultPortForScheme(scheme); -} - -function extractQuery(queryString, url) { - var query = trimAndSanitizeQuery(queryString); - var context = {}; - - if (query) { - query.split('&').forEach(function (pair) { - var keyValue = pair.split('='); - - if (keyValue.length !== 2) { - throw new Error("Invalid parameters: '".concat(keyValue, "' in URL '").concat(url, "'.")); - } - - var key = trimAndVerifyQueryElement(keyValue[0], 'key', url); - var value = trimAndVerifyQueryElement(keyValue[1], 'value', url); - - if (context[key]) { - throw new Error("Duplicated query parameters with key '".concat(key, "' in URL '").concat(url, "'")); - } - - context[key] = value; - }); - } - - return context; -} - -function trimAndSanitizeQuery(query) { - query = (query || '').trim(); - - if (query && query.charAt(0) === '?') { - query = query.substring(1, query.length); - } - - return query; -} - -function trimAndVerifyQueryElement(element, name, url) { - element = (element || '').trim(); - - if (!element) { - throw new Error("Illegal empty ".concat(name, " in URL query '").concat(url, "'")); - } - - return element; -} - -function escapeIPv6Address(address) { - var startsWithSquareBracket = address.charAt(0) === '['; - var endsWithSquareBracket = address.charAt(address.length - 1) === ']'; - - if (!startsWithSquareBracket && !endsWithSquareBracket) { - return "[".concat(address, "]"); - } else if (startsWithSquareBracket && endsWithSquareBracket) { - return address; - } else { - throw new Error("Illegal IPv6 address ".concat(address)); - } -} - -function formatHost(host) { - if (!host) { - throw new Error("Illegal host ".concat(host)); - } - - var isIPv6Address = host.indexOf(':') >= 0; - return isIPv6Address ? escapeIPv6Address(host) : host; -} - -function formatIPv4Address(address, port) { - return "".concat(address, ":").concat(port); -} - -function formatIPv6Address(address, port) { - var escapedAddress = escapeIPv6Address(address); - return "".concat(escapedAddress, ":").concat(port); -} - -function defaultPortForScheme(scheme) { - if (scheme === 'http') { - return DEFAULT_HTTP_PORT; - } else if (scheme === 'https') { - return DEFAULT_HTTPS_PORT; - } else { - return DEFAULT_BOLT_PORT; - } -} - -var _default = { - parseDatabaseUrl: parseDatabaseUrl, - defaultPortForScheme: defaultPortForScheme, - formatIPv4Address: formatIPv4Address, - formatIPv6Address: formatIPv6Address -}; -exports["default"] = _default; -}); - -var serverAddress = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -var _urlUtil = interopRequireDefault(urlUtil); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var ServerAddress = -/*#__PURE__*/ -function () { - function ServerAddress(host, resolved, port, hostPort) { - (0, _classCallCheck2["default"])(this, ServerAddress); - this._host = (0, util.assertString)(host, 'host'); - this._resolved = resolved ? (0, util.assertString)(resolved, 'resolved') : null; - this._port = (0, util.assertNumber)(port, 'port'); - this._hostPort = hostPort; - this._stringValue = resolved ? "".concat(hostPort, "(").concat(resolved, ")") : "".concat(hostPort); - } - - (0, _createClass2["default"])(ServerAddress, [{ - key: "host", - value: function host() { - return this._host; - } - }, { - key: "resolvedHost", - value: function resolvedHost() { - return this._resolved ? this._resolved : this._host; - } - }, { - key: "port", - value: function port() { - return this._port; - } - }, { - key: "resolveWith", - value: function resolveWith(resolved) { - return new ServerAddress(this._host, resolved, this._port, this._hostPort); - } - }, { - key: "asHostPort", - value: function asHostPort() { - return this._hostPort; - } - }, { - key: "asKey", - value: function asKey() { - return this._hostPort; - } - }, { - key: "toString", - value: function toString() { - return this._stringValue; - } - }], [{ - key: "fromUrl", - value: function fromUrl(url) { - var urlParsed = _urlUtil["default"].parseDatabaseUrl(url); - - return new ServerAddress(urlParsed.host, null, urlParsed.port, urlParsed.hostAndPort); - } - }]); - return ServerAddress; -}(); - -exports["default"] = ServerAddress; -}); - -var routingUtil = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _regenerator = interopRequireDefault(regenerator); - -var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - - - -var _integer = interopRequireWildcard(integer); - - - -interopRequireDefault(bookmark); - -interopRequireDefault(session); - -var _txConfig = interopRequireDefault(txConfig); - -var _serverAddress = interopRequireDefault(serverAddress); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var CONTEXT = 'context'; -var CALL_GET_ROUTING_TABLE = "CALL dbms.cluster.routing.getRoutingTable($".concat(CONTEXT, ")"); -var DATABASE = 'database'; -var CALL_GET_ROUTING_TABLE_MULTI_DB = "CALL dbms.routing.getRoutingTable($".concat(CONTEXT, ", $").concat(DATABASE, ")"); -var PROCEDURE_NOT_FOUND_CODE = 'Neo.ClientError.Procedure.ProcedureNotFound'; -var DATABASE_NOT_FOUND_CODE = 'Neo.ClientError.Database.DatabaseNotFound'; - -var RoutingUtil = -/*#__PURE__*/ -function () { - function RoutingUtil(routingContext, initialAddress) { - (0, _classCallCheck2["default"])(this, RoutingUtil); - this._routingContext = routingContext; // The address that the driver is connecting to, used by routing as a fallback when routing - // and clustering isn't configured. - - this._initialAddress = initialAddress; - } - /** - * Invoke routing procedure using the given session. - * @param {Session} session the session to use. - * @param {string} routerAddress the URL of the router. - * @return {Promise} promise resolved with records returned by the procedure call or null if - * connection error happened. - */ - - - (0, _createClass2["default"])(RoutingUtil, [{ - key: "callRoutingProcedure", - value: function () { - var _callRoutingProcedure = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee(session, database, routerAddress) { - var result; - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.prev = 0; - _context.next = 3; - return this._callAvailableRoutingProcedure(session, database); - - case 3: - result = _context.sent; - _context.next = 6; - return session.close(); - - case 6: - return _context.abrupt("return", result.records); - - case 9: - _context.prev = 9; - _context.t0 = _context["catch"](0); - - if (!(_context.t0.code === DATABASE_NOT_FOUND_CODE)) { - _context.next = 15; - break; - } - - throw _context.t0; - - case 15: - if (!(_context.t0.code === PROCEDURE_NOT_FOUND_CODE)) { - _context.next = 19; - break; - } - - throw (0, error.newError)("Server at ".concat(routerAddress.asHostPort(), " can't perform routing. Make sure you are connecting to a causal cluster"), error.SERVICE_UNAVAILABLE); - - case 19: - return _context.abrupt("return", null); - - case 20: - case "end": - return _context.stop(); - } - } - }, _callee, this, [[0, 9]]); - })); - - function callRoutingProcedure(_x, _x2, _x3) { - return _callRoutingProcedure.apply(this, arguments); - } - - return callRoutingProcedure; - }() - }, { - key: "parseTtl", - value: function parseTtl(record, routerAddress) { - try { - var now = (0, _integer["int"])(Date.now()); - var expires = (0, _integer["int"])(record.get('ttl')).multiply(1000).add(now); // if the server uses a really big expire time like Long.MAX_VALUE this may have overflowed - - if (expires.lessThan(now)) { - return _integer["default"].MAX_VALUE; - } - - return expires; - } catch (error$1) { - throw (0, error.newError)("Unable to parse TTL entry from router ".concat(routerAddress, " from record:\n").concat(JSON.stringify(record), "\nError message: ").concat(error$1.message), error.PROTOCOL_ERROR); - } - } - }, { - key: "parseServers", - value: function parseServers(record, routerAddress) { - try { - var servers = record.get('servers'); - var routers = []; - var readers = []; - var writers = []; - servers.forEach(function (server) { - var role = server.role; - var addresses = server.addresses; - - if (role === 'ROUTE') { - routers = parseArray(addresses).map(function (address) { - return _serverAddress["default"].fromUrl(address); - }); - } else if (role === 'WRITE') { - writers = parseArray(addresses).map(function (address) { - return _serverAddress["default"].fromUrl(address); - }); - } else if (role === 'READ') { - readers = parseArray(addresses).map(function (address) { - return _serverAddress["default"].fromUrl(address); - }); - } else { - throw (0, error.newError)('Unknown server role "' + role + '"', error.PROTOCOL_ERROR); - } - }); - return { - routers: routers, - readers: readers, - writers: writers - }; - } catch (error$1) { - throw (0, error.newError)("Unable to parse servers entry from router ".concat(routerAddress, " from record:\n").concat(JSON.stringify(record), "\nError message: ").concat(error$1.message), error.PROTOCOL_ERROR); - } - } - }, { - key: "_callAvailableRoutingProcedure", - value: function _callAvailableRoutingProcedure(session, database) { - var _this = this; - - return session._run(null, null, function (connection) { - var query; - var params; - var protocolVersion = connection.protocol().version; - - if (protocolVersion >= 4.0) { - query = CALL_GET_ROUTING_TABLE_MULTI_DB; - params = { - context: _this._routingContext || {}, - database: database || null - }; - params.context.address = _this._initialAddress; - } else { - query = CALL_GET_ROUTING_TABLE; - params = { - context: _this._routingContext - }; - } - - return connection.protocol().run(query, params, { - bookmark: session._lastBookmark, - txConfig: _txConfig["default"].empty(), - mode: session._mode, - database: session._database, - afterComplete: session._onComplete - }); - }); - } - }]); - return RoutingUtil; -}(); - -exports["default"] = RoutingUtil; - -function parseArray(addresses) { - if (!Array.isArray(addresses)) { - throw new TypeError('Array expected but got: ' + addresses); - } - - return Array.from(addresses); -} -}); - -var rediscovery = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _regenerator = interopRequireDefault(regenerator); - -var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _routingTable = interopRequireDefault(routingTable); - -interopRequireDefault(routingUtil); - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var Rediscovery = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {RoutingUtil} routingUtil the util to use. - */ - function Rediscovery(routingUtil) { - (0, _classCallCheck2["default"])(this, Rediscovery); - this._routingUtil = routingUtil; - } - /** - * Try to fetch new routing table from the given router. - * @param {Session} session the session to use. - * @param {string} database the database for which to lookup routing table. - * @param {string} routerAddress the URL of the router. - * @return {Promise} promise resolved with new routing table or null when connection error happened. - */ - - - (0, _createClass2["default"])(Rediscovery, [{ - key: "lookupRoutingTableOnRouter", - value: function () { - var _lookupRoutingTableOnRouter = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee(session, database, routerAddress) { - var records, record, expirationTime, _this$_routingUtil$pa, routers, readers, writers; - - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _context.next = 2; - return this._routingUtil.callRoutingProcedure(session, database, routerAddress); - - case 2: - records = _context.sent; - - if (!(records === null)) { - _context.next = 5; - break; - } - - return _context.abrupt("return", null); - - case 5: - if (!(records.length !== 1)) { - _context.next = 7; - break; - } - - throw (0, error.newError)('Illegal response from router "' + routerAddress + '". ' + 'Received ' + records.length + ' records but expected only one.\n' + JSON.stringify(records), error.PROTOCOL_ERROR); - - case 7: - record = records[0]; - expirationTime = this._routingUtil.parseTtl(record, routerAddress); - _this$_routingUtil$pa = this._routingUtil.parseServers(record, routerAddress), routers = _this$_routingUtil$pa.routers, readers = _this$_routingUtil$pa.readers, writers = _this$_routingUtil$pa.writers; - - Rediscovery._assertNonEmpty(routers, 'routers', routerAddress); - - Rediscovery._assertNonEmpty(readers, 'readers', routerAddress); // case with no writers is processed higher in the promise chain because only RoutingDriver knows - // how to deal with such table and how to treat router that returned such table - - - return _context.abrupt("return", new _routingTable["default"]({ - database: database, - routers: routers, - readers: readers, - writers: writers, - expirationTime: expirationTime - })); - - case 13: - case "end": - return _context.stop(); - } - } - }, _callee, this); - })); - - function lookupRoutingTableOnRouter(_x, _x2, _x3) { - return _lookupRoutingTableOnRouter.apply(this, arguments); - } - - return lookupRoutingTableOnRouter; - }() - }], [{ - key: "_assertNonEmpty", - value: function _assertNonEmpty(serverAddressesArray, serversName, routerAddress) { - if (serverAddressesArray.length === 0) { - throw (0, error.newError)('Received no ' + serversName + ' from router ' + routerAddress, error.PROTOCOL_ERROR); - } - } - }]); - return Rediscovery; -}(); - -exports["default"] = Rediscovery; -}); - -var connectionProviderSingle = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _connectionProvider = interopRequireDefault(connectionProvider); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var SingleConnectionProvider = -/*#__PURE__*/ -function (_ConnectionProvider) { - (0, _inherits2["default"])(SingleConnectionProvider, _ConnectionProvider); - - function SingleConnectionProvider(connection) { - var _this; - - (0, _classCallCheck2["default"])(this, SingleConnectionProvider); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(SingleConnectionProvider).call(this)); - _this._connection = connection; - return _this; - } - /** - * See {@link ConnectionProvider} for more information about this method and - * its arguments. - */ - - - (0, _createClass2["default"])(SingleConnectionProvider, [{ - key: "acquireConnection", - value: function acquireConnection() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - _ref.accessMode; - _ref.database; - _ref.bookmarks; - - var connection = this._connection; - this._connection = null; - return Promise.resolve(connection); - } - }]); - return SingleConnectionProvider; -}(_connectionProvider["default"]); - -exports["default"] = SingleConnectionProvider; -}); - -var roundRobinArrayIndex = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var RoundRobinArrayIndex = -/*#__PURE__*/ -function () { - /** - * @constructor - * @param {number} [initialOffset=0] the initial offset for round robin. - */ - function RoundRobinArrayIndex(initialOffset) { - (0, _classCallCheck2["default"])(this, RoundRobinArrayIndex); - this._offset = initialOffset || 0; - } - /** - * Get next index for an array with given length. - * @param {number} arrayLength the array length. - * @return {number} index in the array. - */ - - - (0, _createClass2["default"])(RoundRobinArrayIndex, [{ - key: "next", - value: function next(arrayLength) { - if (arrayLength === 0) { - return -1; - } - - var nextOffset = this._offset; - this._offset += 1; - - if (this._offset === Number.MAX_SAFE_INTEGER) { - this._offset = 0; - } - - return nextOffset % arrayLength; - } - }]); - return RoundRobinArrayIndex; -}(); - -exports["default"] = RoundRobinArrayIndex; -}); - -var loadBalancingStrategy = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * A facility to select most appropriate reader or writer among the given addresses for request processing. - */ -var LoadBalancingStrategy = -/*#__PURE__*/ -function () { - function LoadBalancingStrategy() { - (0, _classCallCheck2["default"])(this, LoadBalancingStrategy); - } - - (0, _createClass2["default"])(LoadBalancingStrategy, [{ - key: "selectReader", - - /** - * Select next most appropriate reader from the list of given readers. - * @param {string[]} knownReaders an array of currently known readers to select from. - * @return {string} most appropriate reader or `null` if given array is empty. - */ - value: function selectReader(knownReaders) { - throw new Error('Abstract function'); - } - /** - * Select next most appropriate writer from the list of given writers. - * @param {string[]} knownWriters an array of currently known writers to select from. - * @return {string} most appropriate writer or `null` if given array is empty. - */ - - }, { - key: "selectWriter", - value: function selectWriter(knownWriters) { - throw new Error('Abstract function'); - } - }]); - return LoadBalancingStrategy; -}(); - -exports["default"] = LoadBalancingStrategy; -}); - -var leastConnectedLoadBalancingStrategy = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - -var _roundRobinArrayIndex = interopRequireDefault(roundRobinArrayIndex); - -var _loadBalancingStrategy = interopRequireDefault(loadBalancingStrategy); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var LeastConnectedLoadBalancingStrategy = -/*#__PURE__*/ -function (_LoadBalancingStrateg) { - (0, _inherits2["default"])(LeastConnectedLoadBalancingStrategy, _LoadBalancingStrateg); - - /** - * @constructor - * @param {Pool} connectionPool the connection pool of this driver. - */ - function LeastConnectedLoadBalancingStrategy(connectionPool) { - var _this; - - (0, _classCallCheck2["default"])(this, LeastConnectedLoadBalancingStrategy); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(LeastConnectedLoadBalancingStrategy).call(this)); - _this._readersIndex = new _roundRobinArrayIndex["default"](); - _this._writersIndex = new _roundRobinArrayIndex["default"](); - _this._connectionPool = connectionPool; - return _this; - } - /** - * @inheritDoc - */ - - - (0, _createClass2["default"])(LeastConnectedLoadBalancingStrategy, [{ - key: "selectReader", - value: function selectReader(knownReaders) { - return this._select(knownReaders, this._readersIndex); - } - /** - * @inheritDoc - */ - - }, { - key: "selectWriter", - value: function selectWriter(knownWriters) { - return this._select(knownWriters, this._writersIndex); - } - }, { - key: "_select", - value: function _select(addresses, roundRobinIndex) { - var length = addresses.length; - - if (length === 0) { - return null; - } // choose start index for iteration in round-robin fashion - - - var startIndex = roundRobinIndex.next(length); - var index = startIndex; - var leastConnectedAddress = null; - var leastActiveConnections = Number.MAX_SAFE_INTEGER; // iterate over the array to find least connected address - - do { - var address = addresses[index]; - - var activeConnections = this._connectionPool.activeResourceCount(address); - - if (activeConnections < leastActiveConnections) { - leastConnectedAddress = address; - leastActiveConnections = activeConnections; - } // loop over to the start of the array when end is reached - - - if (index === length - 1) { - index = 0; - } else { - index++; - } - } while (index !== startIndex); - - return leastConnectedAddress; - } - }]); - return LeastConnectedLoadBalancingStrategy; -}(_loadBalancingStrategy["default"]); - -exports["default"] = LeastConnectedLoadBalancingStrategy; -}); - -var connectionProviderRouting = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _regenerator = interopRequireDefault(regenerator); - -var _asyncToGenerator2 = interopRequireDefault(asyncToGenerator); - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - - - - - -var _session = interopRequireDefault(session); - -var _routingTable = interopRequireDefault(routingTable); - -var _rediscovery = interopRequireDefault(rediscovery); - -var _routingUtil = interopRequireDefault(routingUtil); - - - -var _connectionProviderSingle = interopRequireDefault(connectionProviderSingle); - -var _connectionProviderPooled = interopRequireDefault(connectionProviderPooled); - -var _connectionErrorHandler = interopRequireDefault(connectionErrorHandler); - -var _connectionDelegate = interopRequireDefault(connectionDelegate); - -var _leastConnectedLoadBalancingStrategy = interopRequireDefault(leastConnectedLoadBalancingStrategy); - -var _bookmark = interopRequireDefault(bookmark); - -var _connectionChannel = interopRequireDefault(connectionChannel); - - - - - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var UNAUTHORIZED_ERROR_CODE = 'Neo.ClientError.Security.Unauthorized'; -var DATABASE_NOT_FOUND_ERROR_CODE = 'Neo.ClientError.Database.DatabaseNotFound'; -var SYSTEM_DB_NAME = 'system'; -var DEFAULT_DB_NAME = ''; -var DEFAULT_ROUTING_TABLE_PURGE_DELAY = (0, integer["int"])(30000); - -var RoutingConnectionProvider = -/*#__PURE__*/ -function (_PooledConnectionProv) { - (0, _inherits2["default"])(RoutingConnectionProvider, _PooledConnectionProv); - - function RoutingConnectionProvider(_ref) { - var _this; - - var id = _ref.id, - address = _ref.address, - routingContext = _ref.routingContext, - hostNameResolver = _ref.hostNameResolver, - config = _ref.config, - log = _ref.log, - userAgent = _ref.userAgent, - authToken = _ref.authToken, - routingTablePurgeDelay = _ref.routingTablePurgeDelay; - (0, _classCallCheck2["default"])(this, RoutingConnectionProvider); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(RoutingConnectionProvider).call(this, { - id: id, - config: config, - log: log, - userAgent: userAgent, - authToken: authToken - }, function (address) { - return _connectionChannel["default"].create(address, _this._config, _this._createConnectionErrorHandler(), _this._log, routingContext || {}); - })); - _this._seedRouter = address; - _this._routingTables = {}; - _this._rediscovery = new _rediscovery["default"](new _routingUtil["default"](routingContext, address.toString())); - _this._loadBalancingStrategy = new _leastConnectedLoadBalancingStrategy["default"](_this._connectionPool); - _this._hostNameResolver = hostNameResolver; - _this._dnsResolver = new node.HostNameResolver(); - _this._log = log; - _this._useSeedRouter = true; - _this._routingTablePurgeDelay = routingTablePurgeDelay ? (0, integer["int"])(routingTablePurgeDelay) : DEFAULT_ROUTING_TABLE_PURGE_DELAY; - return _this; - } - - (0, _createClass2["default"])(RoutingConnectionProvider, [{ - key: "_createConnectionErrorHandler", - value: function _createConnectionErrorHandler() { - // connection errors mean SERVICE_UNAVAILABLE for direct driver but for routing driver they should only - // result in SESSION_EXPIRED because there might still exist other servers capable of serving the request - return new _connectionErrorHandler["default"](error.SESSION_EXPIRED); - } - }, { - key: "_handleUnavailability", - value: function _handleUnavailability(error, address, database) { - this._log.warn("Routing driver ".concat(this._id, " will forget ").concat(address, " for database '").concat(database, "' because of an error ").concat(error.code, " '").concat(error.message, "'")); - - this.forget(address, database || ''); - return error; - } - }, { - key: "_handleWriteFailure", - value: function _handleWriteFailure(error$1, address, database) { - this._log.warn("Routing driver ".concat(this._id, " will forget writer ").concat(address, " for database '").concat(database, "' because of an error ").concat(error$1.code, " '").concat(error$1.message, "'")); - - this.forgetWriter(address, database || ''); - return (0, error.newError)('No longer possible to write to server at ' + address, error.SESSION_EXPIRED); - } - /** - * See {@link ConnectionProvider} for more information about this method and - * its arguments. - */ - - }, { - key: "acquireConnection", - value: function () { - var _acquireConnection = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee() { - var _this2 = this; - - var _ref2, - accessMode, - database, - bookmark, - name, - address, - databaseSpecificErrorHandler, - routingTable, - connection, - transformed, - _args = arguments; - - return _regenerator["default"].wrap(function _callee$(_context) { - while (1) { - switch (_context.prev = _context.next) { - case 0: - _ref2 = _args.length > 0 && _args[0] !== undefined ? _args[0] : {}, accessMode = _ref2.accessMode, database = _ref2.database, bookmark = _ref2.bookmark; - databaseSpecificErrorHandler = new _connectionErrorHandler["default"](error.SESSION_EXPIRED, function (error, address) { - return _this2._handleUnavailability(error, address, database); - }, function (error, address) { - return _this2._handleWriteFailure(error, address, database); - }); - _context.next = 4; - return this._freshRoutingTable({ - accessMode: accessMode, - database: database || DEFAULT_DB_NAME, - bookmark: bookmark - }); - - case 4: - routingTable = _context.sent; - - if (!(accessMode === driver.READ)) { - _context.next = 10; - break; - } - - address = this._loadBalancingStrategy.selectReader(routingTable.readers); - name = 'read'; - _context.next = 16; - break; - - case 10: - if (!(accessMode === driver.WRITE)) { - _context.next = 15; - break; - } - - address = this._loadBalancingStrategy.selectWriter(routingTable.writers); - name = 'write'; - _context.next = 16; - break; - - case 15: - throw (0, error.newError)('Illegal mode ' + accessMode); - - case 16: - if (address) { - _context.next = 18; - break; - } - - throw (0, error.newError)("Failed to obtain connection towards ".concat(name, " server. Known routing table is: ").concat(routingTable), error.SESSION_EXPIRED); - - case 18: - _context.prev = 18; - _context.next = 21; - return this._acquireConnectionToServer(address, name, routingTable); - - case 21: - connection = _context.sent; - return _context.abrupt("return", new _connectionDelegate["default"](connection, databaseSpecificErrorHandler)); - - case 25: - _context.prev = 25; - _context.t0 = _context["catch"](18); - transformed = databaseSpecificErrorHandler.handleAndTransformError(_context.t0, address); - throw transformed; - - case 29: - case "end": - return _context.stop(); - } - } - }, _callee, this, [[18, 25]]); - })); - - function acquireConnection() { - return _acquireConnection.apply(this, arguments); - } - - return acquireConnection; - }() - }, { - key: "_hasProtocolVersion", - value: function () { - var _hasProtocolVersion2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee2(versionPredicate) { - var addresses, lastError, i, connection, protocol; - return _regenerator["default"].wrap(function _callee2$(_context2) { - while (1) { - switch (_context2.prev = _context2.next) { - case 0: - _context2.next = 2; - return this._resolveSeedRouter(this._seedRouter); - - case 2: - addresses = _context2.sent; - i = 0; - - case 4: - if (!(i < addresses.length)) { - _context2.next = 25; - break; - } - - connection = _connectionChannel["default"].create(addresses[i], this._config, this._createConnectionErrorHandler(), this._log); - _context2.prev = 6; - _context2.next = 9; - return connection._negotiateProtocol(); - - case 9: - protocol = connection.protocol(); - - if (!protocol) { - _context2.next = 12; - break; - } - - return _context2.abrupt("return", versionPredicate(protocol.version)); - - case 12: - return _context2.abrupt("return", false); - - case 15: - _context2.prev = 15; - _context2.t0 = _context2["catch"](6); - lastError = _context2.t0; - - case 18: - _context2.prev = 18; - _context2.next = 21; - return connection.close(); - - case 21: - return _context2.finish(18); - - case 22: - i++; - _context2.next = 4; - break; - - case 25: - if (!lastError) { - _context2.next = 27; - break; - } - - throw lastError; - - case 27: - return _context2.abrupt("return", false); - - case 28: - case "end": - return _context2.stop(); - } - } - }, _callee2, this, [[6, 15, 18, 22]]); - })); - - function _hasProtocolVersion(_x) { - return _hasProtocolVersion2.apply(this, arguments); - } - - return _hasProtocolVersion; - }() - }, { - key: "supportsMultiDb", - value: function () { - var _supportsMultiDb = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee3() { - return _regenerator["default"].wrap(function _callee3$(_context3) { - while (1) { - switch (_context3.prev = _context3.next) { - case 0: - _context3.next = 2; - return this._hasProtocolVersion(function (version) { - return version >= constants.BOLT_PROTOCOL_V4_0; - }); - - case 2: - return _context3.abrupt("return", _context3.sent); - - case 3: - case "end": - return _context3.stop(); - } - } - }, _callee3, this); - })); - - function supportsMultiDb() { - return _supportsMultiDb.apply(this, arguments); - } - - return supportsMultiDb; - }() - }, { - key: "supportsTransactionConfig", - value: function () { - var _supportsTransactionConfig = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee4() { - return _regenerator["default"].wrap(function _callee4$(_context4) { - while (1) { - switch (_context4.prev = _context4.next) { - case 0: - _context4.next = 2; - return this._hasProtocolVersion(function (version) { - return version >= constants.BOLT_PROTOCOL_V3; - }); - - case 2: - return _context4.abrupt("return", _context4.sent); - - case 3: - case "end": - return _context4.stop(); - } - } - }, _callee4, this); - })); - - function supportsTransactionConfig() { - return _supportsTransactionConfig.apply(this, arguments); - } - - return supportsTransactionConfig; - }() - }, { - key: "forget", - value: function forget(address, database) { - if (database || database === '') { - this._routingTables[database].forget(address); - } else { - Object.values(this._routingTables).forEach(function (routingTable) { - return routingTable.forget(address); - }); - } // We're firing and forgetting this operation explicitly and listening for any - // errors to avoid unhandled promise rejection - - - this._connectionPool.purge(address)["catch"](function () {}); - } - }, { - key: "forgetWriter", - value: function forgetWriter(address, database) { - if (database || database === '') { - this._routingTables[database].forgetWriter(address); - } else { - Object.values(this._routingTables).forEach(function (routingTable) { - return routingTable.forgetWriter(address); - }); - } - } - }, { - key: "_acquireConnectionToServer", - value: function _acquireConnectionToServer(address, serverName, routingTable) { - return this._connectionPool.acquire(address); - } - }, { - key: "_freshRoutingTable", - value: function _freshRoutingTable() { - var _ref3 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - accessMode = _ref3.accessMode, - database = _ref3.database, - bookmark = _ref3.bookmark; - - var currentRoutingTable = this._routingTables[database] || new _routingTable["default"]({ - database: database - }); - - if (!currentRoutingTable.isStaleFor(accessMode)) { - return currentRoutingTable; - } - - this._log.info("Routing table is stale for database: \"".concat(database, "\" and access mode: \"").concat(accessMode, "\": ").concat(currentRoutingTable)); - - return this._refreshRoutingTable(currentRoutingTable, bookmark); - } - }, { - key: "_refreshRoutingTable", - value: function _refreshRoutingTable(currentRoutingTable, bookmark) { - var knownRouters = currentRoutingTable.routers; - - if (this._useSeedRouter) { - return this._fetchRoutingTableFromSeedRouterFallbackToKnownRouters(knownRouters, currentRoutingTable, bookmark); - } - - return this._fetchRoutingTableFromKnownRoutersFallbackToSeedRouter(knownRouters, currentRoutingTable, bookmark); - } - }, { - key: "_fetchRoutingTableFromSeedRouterFallbackToKnownRouters", - value: function () { - var _fetchRoutingTableFromSeedRouterFallbackToKnownRouters2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee5(knownRouters, currentRoutingTable, bookmark) { - var seenRouters, newRoutingTable; - return _regenerator["default"].wrap(function _callee5$(_context5) { - while (1) { - switch (_context5.prev = _context5.next) { - case 0: - // we start with seed router, no routers were probed before - seenRouters = []; - _context5.next = 3; - return this._fetchRoutingTableUsingSeedRouter(seenRouters, this._seedRouter, currentRoutingTable, bookmark); - - case 3: - newRoutingTable = _context5.sent; - - if (!newRoutingTable) { - _context5.next = 8; - break; - } - - this._useSeedRouter = false; - _context5.next = 11; - break; - - case 8: - _context5.next = 10; - return this._fetchRoutingTableUsingKnownRouters(knownRouters, currentRoutingTable, bookmark); - - case 10: - newRoutingTable = _context5.sent; - - case 11: - _context5.next = 13; - return this._applyRoutingTableIfPossible(currentRoutingTable, newRoutingTable); - - case 13: - return _context5.abrupt("return", _context5.sent); - - case 14: - case "end": - return _context5.stop(); - } - } - }, _callee5, this); - })); - - function _fetchRoutingTableFromSeedRouterFallbackToKnownRouters(_x2, _x3, _x4) { - return _fetchRoutingTableFromSeedRouterFallbackToKnownRouters2.apply(this, arguments); - } - - return _fetchRoutingTableFromSeedRouterFallbackToKnownRouters; - }() - }, { - key: "_fetchRoutingTableFromKnownRoutersFallbackToSeedRouter", - value: function () { - var _fetchRoutingTableFromKnownRoutersFallbackToSeedRouter2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee6(knownRouters, currentRoutingTable, bookmark) { - var newRoutingTable; - return _regenerator["default"].wrap(function _callee6$(_context6) { - while (1) { - switch (_context6.prev = _context6.next) { - case 0: - _context6.next = 2; - return this._fetchRoutingTableUsingKnownRouters(knownRouters, currentRoutingTable, bookmark); - - case 2: - newRoutingTable = _context6.sent; - - if (newRoutingTable) { - _context6.next = 7; - break; - } - - _context6.next = 6; - return this._fetchRoutingTableUsingSeedRouter(knownRouters, this._seedRouter, currentRoutingTable, bookmark); - - case 6: - newRoutingTable = _context6.sent; - - case 7: - _context6.next = 9; - return this._applyRoutingTableIfPossible(currentRoutingTable, newRoutingTable); - - case 9: - return _context6.abrupt("return", _context6.sent); - - case 10: - case "end": - return _context6.stop(); - } - } - }, _callee6, this); - })); - - function _fetchRoutingTableFromKnownRoutersFallbackToSeedRouter(_x5, _x6, _x7) { - return _fetchRoutingTableFromKnownRoutersFallbackToSeedRouter2.apply(this, arguments); - } - - return _fetchRoutingTableFromKnownRoutersFallbackToSeedRouter; - }() - }, { - key: "_fetchRoutingTableUsingKnownRouters", - value: function () { - var _fetchRoutingTableUsingKnownRouters2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee7(knownRouters, currentRoutingTable, bookmark) { - var newRoutingTable, lastRouterIndex; - return _regenerator["default"].wrap(function _callee7$(_context7) { - while (1) { - switch (_context7.prev = _context7.next) { - case 0: - _context7.next = 2; - return this._fetchRoutingTable(knownRouters, currentRoutingTable, bookmark); - - case 2: - newRoutingTable = _context7.sent; - - if (!newRoutingTable) { - _context7.next = 5; - break; - } - - return _context7.abrupt("return", newRoutingTable); - - case 5: - // returned routing table was undefined, this means a connection error happened and the last known - // router did not return a valid routing table, so we need to forget it - lastRouterIndex = knownRouters.length - 1; - - RoutingConnectionProvider._forgetRouter(currentRoutingTable, knownRouters, lastRouterIndex); - - return _context7.abrupt("return", null); - - case 8: - case "end": - return _context7.stop(); - } - } - }, _callee7, this); - })); - - function _fetchRoutingTableUsingKnownRouters(_x8, _x9, _x10) { - return _fetchRoutingTableUsingKnownRouters2.apply(this, arguments); - } - - return _fetchRoutingTableUsingKnownRouters; - }() - }, { - key: "_fetchRoutingTableUsingSeedRouter", - value: function () { - var _fetchRoutingTableUsingSeedRouter2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee8(seenRouters, seedRouter, routingTable, bookmark) { - var resolvedAddresses, newAddresses; - return _regenerator["default"].wrap(function _callee8$(_context8) { - while (1) { - switch (_context8.prev = _context8.next) { - case 0: - _context8.next = 2; - return this._resolveSeedRouter(seedRouter); - - case 2: - resolvedAddresses = _context8.sent; - // filter out all addresses that we've already tried - newAddresses = resolvedAddresses.filter(function (address) { - return seenRouters.indexOf(address) < 0; - }); - _context8.next = 6; - return this._fetchRoutingTable(newAddresses, routingTable, bookmark); - - case 6: - return _context8.abrupt("return", _context8.sent); - - case 7: - case "end": - return _context8.stop(); - } - } - }, _callee8, this); - })); - - function _fetchRoutingTableUsingSeedRouter(_x11, _x12, _x13, _x14) { - return _fetchRoutingTableUsingSeedRouter2.apply(this, arguments); - } - - return _fetchRoutingTableUsingSeedRouter; - }() - }, { - key: "_resolveSeedRouter", - value: function () { - var _resolveSeedRouter2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee9(seedRouter) { - var _this3 = this; - - var resolvedAddresses, dnsResolvedAddresses; - return _regenerator["default"].wrap(function _callee9$(_context9) { - while (1) { - switch (_context9.prev = _context9.next) { - case 0: - _context9.next = 2; - return this._hostNameResolver.resolve(seedRouter); - - case 2: - resolvedAddresses = _context9.sent; - _context9.next = 5; - return Promise.all(resolvedAddresses.map(function (address) { - return _this3._dnsResolver.resolve(address); - })); - - case 5: - dnsResolvedAddresses = _context9.sent; - return _context9.abrupt("return", [].concat.apply([], dnsResolvedAddresses)); - - case 7: - case "end": - return _context9.stop(); - } - } - }, _callee9, this); - })); - - function _resolveSeedRouter(_x15) { - return _resolveSeedRouter2.apply(this, arguments); - } - - return _resolveSeedRouter; - }() - }, { - key: "_fetchRoutingTable", - value: function _fetchRoutingTable(routerAddresses, routingTable, bookmark) { - var _this4 = this; - - return routerAddresses.reduce( - /*#__PURE__*/ - function () { - var _ref4 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee10(refreshedTablePromise, currentRouter, currentIndex) { - var newRoutingTable, previousRouterIndex, session; - return _regenerator["default"].wrap(function _callee10$(_context10) { - while (1) { - switch (_context10.prev = _context10.next) { - case 0: - _context10.next = 2; - return refreshedTablePromise; - - case 2: - newRoutingTable = _context10.sent; - - if (!newRoutingTable) { - _context10.next = 7; - break; - } - - return _context10.abrupt("return", newRoutingTable); - - case 7: - // returned routing table was undefined, this means a connection error happened and we need to forget the - // previous router and try the next one - previousRouterIndex = currentIndex - 1; - - RoutingConnectionProvider._forgetRouter(routingTable, routerAddresses, previousRouterIndex); - - case 9: - _context10.next = 11; - return _this4._createSessionForRediscovery(currentRouter, bookmark); - - case 11: - session = _context10.sent; - - if (!session) { - _context10.next = 27; - break; - } - - _context10.prev = 13; - _context10.next = 16; - return _this4._rediscovery.lookupRoutingTableOnRouter(session, routingTable.database, currentRouter); - - case 16: - return _context10.abrupt("return", _context10.sent); - - case 19: - _context10.prev = 19; - _context10.t0 = _context10["catch"](13); - - if (!(_context10.t0 && _context10.t0.code === DATABASE_NOT_FOUND_ERROR_CODE)) { - _context10.next = 23; - break; - } - - throw _context10.t0; - - case 23: - _this4._log.warn("unable to fetch routing table because of an error ".concat(_context10.t0)); - - return _context10.abrupt("return", null); - - case 25: - _context10.next = 28; - break; - - case 27: - return _context10.abrupt("return", null); - - case 28: - case "end": - return _context10.stop(); - } - } - }, _callee10, null, [[13, 19]]); - })); - - return function (_x16, _x17, _x18) { - return _ref4.apply(this, arguments); - }; - }(), Promise.resolve(null)); - } - }, { - key: "_createSessionForRediscovery", - value: function () { - var _createSessionForRediscovery2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee11(routerAddress, bookmark) { - var connection, connectionProvider, protocolVersion; - return _regenerator["default"].wrap(function _callee11$(_context11) { - while (1) { - switch (_context11.prev = _context11.next) { - case 0: - _context11.prev = 0; - _context11.next = 3; - return this._connectionPool.acquire(routerAddress); - - case 3: - connection = _context11.sent; - connectionProvider = new _connectionProviderSingle["default"](connection); - protocolVersion = connection.protocol().version; - - if (!(protocolVersion < 4.0)) { - _context11.next = 8; - break; - } - - return _context11.abrupt("return", new _session["default"]({ - mode: driver.WRITE, - bookmark: _bookmark["default"].empty(), - connectionProvider: connectionProvider - })); - - case 8: - return _context11.abrupt("return", new _session["default"]({ - mode: driver.READ, - database: SYSTEM_DB_NAME, - bookmark: bookmark, - connectionProvider: connectionProvider - })); - - case 11: - _context11.prev = 11; - _context11.t0 = _context11["catch"](0); - - if (!(_context11.t0 && _context11.t0.code === UNAUTHORIZED_ERROR_CODE)) { - _context11.next = 15; - break; - } - - throw _context11.t0; - - case 15: - return _context11.abrupt("return", null); - - case 16: - case "end": - return _context11.stop(); - } - } - }, _callee11, this, [[0, 11]]); - })); - - function _createSessionForRediscovery(_x19, _x20) { - return _createSessionForRediscovery2.apply(this, arguments); - } - - return _createSessionForRediscovery; - }() - }, { - key: "_applyRoutingTableIfPossible", - value: function () { - var _applyRoutingTableIfPossible2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee12(currentRoutingTable, newRoutingTable) { - return _regenerator["default"].wrap(function _callee12$(_context12) { - while (1) { - switch (_context12.prev = _context12.next) { - case 0: - if (newRoutingTable) { - _context12.next = 2; - break; - } - - throw (0, error.newError)("Could not perform discovery. No routing servers available. Known routing table: ".concat(currentRoutingTable), error.SERVICE_UNAVAILABLE); - - case 2: - if (newRoutingTable.writers.length === 0) { - // use seed router next time. this is important when cluster is partitioned. it tries to make sure driver - // does not always get routing table without writers because it talks exclusively to a minority partition - this._useSeedRouter = true; - } - - _context12.next = 5; - return this._updateRoutingTable(newRoutingTable); - - case 5: - return _context12.abrupt("return", newRoutingTable); - - case 6: - case "end": - return _context12.stop(); - } - } - }, _callee12, this); - })); - - function _applyRoutingTableIfPossible(_x21, _x22) { - return _applyRoutingTableIfPossible2.apply(this, arguments); - } - - return _applyRoutingTableIfPossible; - }() - }, { - key: "_updateRoutingTable", - value: function () { - var _updateRoutingTable2 = (0, _asyncToGenerator2["default"])( - /*#__PURE__*/ - _regenerator["default"].mark(function _callee13(newRoutingTable) { - var _this5 = this; - - return _regenerator["default"].wrap(function _callee13$(_context13) { - while (1) { - switch (_context13.prev = _context13.next) { - case 0: - _context13.next = 2; - return this._connectionPool.keepAll(newRoutingTable.allServers()); - - case 2: - // filter out expired to purge (expired for a pre-configured amount of time) routing table entries - Object.values(this._routingTables).forEach(function (value) { - if (value.isExpiredFor(_this5._routingTablePurgeDelay)) { - delete _this5._routingTables[value.database]; - } - }); // make this driver instance aware of the new table - - this._routingTables[newRoutingTable.database] = newRoutingTable; - - this._log.info("Updated routing table ".concat(newRoutingTable)); - - case 5: - case "end": - return _context13.stop(); - } - } - }, _callee13, this); - })); - - function _updateRoutingTable(_x23) { - return _updateRoutingTable2.apply(this, arguments); - } - - return _updateRoutingTable; - }() - }], [{ - key: "_forgetRouter", - value: function _forgetRouter(routingTable, routersArray, routerIndex) { - var address = routersArray[routerIndex]; - - if (routingTable && address) { - routingTable.forgetRouter(address); - } - } - }]); - return RoutingConnectionProvider; -}(_connectionProviderPooled["default"]); - -exports["default"] = RoutingConnectionProvider; -}); - -var configuredCustomResolver = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _serverAddress = interopRequireDefault(serverAddress); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function resolveToSelf(address) { - return Promise.resolve([address]); -} - -var ConfiguredCustomResolver = -/*#__PURE__*/ -function () { - function ConfiguredCustomResolver(resolverFunction) { - (0, _classCallCheck2["default"])(this, ConfiguredCustomResolver); - this._resolverFunction = resolverFunction || resolveToSelf; - } - - (0, _createClass2["default"])(ConfiguredCustomResolver, [{ - key: "resolve", - value: function resolve(seedRouter) { - var _this = this; - - return new Promise(function (resolve) { - return resolve(_this._resolverFunction(seedRouter.asHostPort())); - }).then(function (resolved) { - if (!Array.isArray(resolved)) { - throw new TypeError('Configured resolver function should either return an array of addresses or a Promise resolved with an array of addresses.' + "Each address is ':'. Got: ".concat(resolved)); - } - - return resolved.map(function (r) { - return _serverAddress["default"].fromUrl(r); - }); - }); - } - }]); - return ConfiguredCustomResolver; -}(); - -exports["default"] = ConfiguredCustomResolver; -}); - -var routingDriver = createCommonjsModule(function (module, exports) { - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -var _classCallCheck2 = interopRequireDefault(classCallCheck); - -var _createClass2 = interopRequireDefault(createClass); - -var _possibleConstructorReturn2 = interopRequireDefault(possibleConstructorReturn); - -var _getPrototypeOf2 = interopRequireDefault(getPrototypeOf); - -var _inherits2 = interopRequireDefault(inherits); - - - - - -var _connectionProviderRouting = interopRequireDefault(connectionProviderRouting); - -interopRequireDefault(leastConnectedLoadBalancingStrategy); - -interopRequireDefault(connectionErrorHandler); - -var _configuredCustomResolver = interopRequireDefault(configuredCustomResolver); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * A driver that supports routing in a causal cluster. - * @private - */ -var RoutingDriver = -/*#__PURE__*/ -function (_Driver) { - (0, _inherits2["default"])(RoutingDriver, _Driver); - - function RoutingDriver(address, routingContext, userAgent) { - var _this; - - var token = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; - var config = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : {}; - (0, _classCallCheck2["default"])(this, RoutingDriver); - _this = (0, _possibleConstructorReturn2["default"])(this, (0, _getPrototypeOf2["default"])(RoutingDriver).call(this, address, userAgent, token, validateConfig(config))); - _this._routingContext = routingContext; - return _this; - } - - (0, _createClass2["default"])(RoutingDriver, [{ - key: "_afterConstruction", - value: function _afterConstruction() { - this._log.info("Routing driver ".concat(this._id, " created for server address ").concat(this._address)); - } - }, { - key: "_createConnectionProvider", - value: function _createConnectionProvider(address, userAgent, authToken) { - return new _connectionProviderRouting["default"]({ - id: this._id, - address: address, - routingContext: this._routingContext, - hostNameResolver: createHostNameResolver(this._config), - config: this._config, - log: this._log, - userAgent: userAgent, - authToken: authToken - }); - } - }, { - key: "_supportsRouting", - value: function _supportsRouting() { - return true; - } - }]); - return RoutingDriver; -}(driver.Driver); -/** - * @private - * @returns {ConfiguredCustomResolver} new custom resolver that wraps the passed-in resolver function. - * If resolved function is not specified, it defaults to an identity resolver. - */ - - -function createHostNameResolver(config) { - return new _configuredCustomResolver["default"](config.resolver); -} -/** - * @private - * @returns {Object} the given config. - */ - - -function validateConfig(config) { - var resolver = config.resolver; - - if (resolver && typeof resolver !== 'function') { - throw new TypeError("Configured resolver should be a function. Got: ".concat(resolver)); - } - - return config; -} - -var _default = RoutingDriver; -exports["default"] = _default; -}); - -var version = createCommonjsModule(function (module, exports) { - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports["default"] = void 0; - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// DO NOT CHANGE THE VERSION BELOW HERE -// This is set by the build system at release time, using -// -// gulp set --x -// -// This is set up this way to keep the version in the code in -// sync with the npm package version, and to allow the build -// system to control version names at packaging time. -var _default = '4.2.3'; -exports["default"] = _default; -}); - -var lib = createCommonjsModule(function (module, exports) { - - - - - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.driver = driver$1; -Object.defineProperty(exports, "int", { - enumerable: true, - get: function get() { - return _integer["int"]; - } -}); -Object.defineProperty(exports, "isInt", { - enumerable: true, - get: function get() { - return _integer.isInt; - } -}); -Object.defineProperty(exports, "Neo4jError", { - enumerable: true, - get: function get() { - return error.Neo4jError; - } -}); -Object.defineProperty(exports, "isPoint", { - enumerable: true, - get: function get() { - return spatialTypes.isPoint; - } -}); -Object.defineProperty(exports, "isDate", { - enumerable: true, - get: function get() { - return temporalTypes.isDate; - } -}); -Object.defineProperty(exports, "isDateTime", { - enumerable: true, - get: function get() { - return temporalTypes.isDateTime; - } -}); -Object.defineProperty(exports, "isDuration", { - enumerable: true, - get: function get() { - return temporalTypes.isDuration; - } -}); -Object.defineProperty(exports, "isLocalDateTime", { - enumerable: true, - get: function get() { - return temporalTypes.isLocalDateTime; - } -}); -Object.defineProperty(exports, "isLocalTime", { - enumerable: true, - get: function get() { - return temporalTypes.isLocalTime; - } -}); -Object.defineProperty(exports, "isTime", { - enumerable: true, - get: function get() { - return temporalTypes.isTime; - } -}); -exports["default"] = exports.temporal = exports.spatial = exports.error = exports.session = exports.types = exports.logging = exports.auth = exports.integer = void 0; - -var _integer = interopRequireWildcard(integer); - - - - - -var _result = interopRequireDefault(result); - -var _resultSummary = interopRequireDefault(resultSummary); - -var _record = interopRequireDefault(record); - - - -var _routingDriver = interopRequireDefault(routingDriver); - -var _version = interopRequireDefault(version); - - - -var _urlUtil = interopRequireDefault(urlUtil); - - - - - -var _serverAddress = interopRequireDefault(serverAddress); - -/** - * Copyright (c) "Neo4j" - * Neo4j Sweden AB [http://neo4j.com] - * - * This file is part of Neo4j. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -/** - * Construct a new Neo4j Driver. This is your main entry point for this - * library. - * - * ## Configuration - * - * This function optionally takes a configuration argument. Available configuration - * options are as follows: - * - * { - * // Encryption level: ENCRYPTION_ON or ENCRYPTION_OFF. - * encrypted: ENCRYPTION_ON|ENCRYPTION_OFF - * - * // Trust strategy to use if encryption is enabled. There is no mode to disable - * // trust other than disabling encryption altogether. The reason for - * // this is that if you don't know who you are talking to, it is easy for an - * // attacker to hijack your encrypted connection, rendering encryption pointless. - * // - * // TRUST_SYSTEM_CA_SIGNED_CERTIFICATES is the default choice. For NodeJS environments, this - * // means that you trust whatever certificates are in the default trusted certificate - * // store of the underlying system. For Browser environments, the trusted certificate - * // store is usually managed by the browser. Refer to your system or browser documentation - * // if you want to explicitly add a certificate as trusted. - * // - * // TRUST_CUSTOM_CA_SIGNED_CERTIFICATES is another option for trust verification - - * // whenever we establish an encrypted connection, we ensure the host is using - * // an encryption certificate that is in, or is signed by, a certificate given - * // as trusted through configuration. This option is only available for NodeJS environments. - * // - * // TRUST_ALL_CERTIFICATES means that you trust everything without any verifications - * // steps carried out. This option is only available for NodeJS environments and should not - * // be used on production systems. - * trust: "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES" | "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES" | - * "TRUST_ALL_CERTIFICATES", - * - * // List of one or more paths to trusted encryption certificates. This only - * // works in the NodeJS bundle, and only matters if you use "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES". - * // The certificate files should be in regular X.509 PEM format. - * // For instance, ['./trusted.pem'] - * trustedCertificates: [], - * - * // The maximum total number of connections allowed to be managed by the connection pool, per host. - * // This includes both in-use and idle connections. No maximum connection pool size is imposed - * // by default. - * maxConnectionPoolSize: 100, - * - * // The maximum allowed lifetime for a pooled connection in milliseconds. Pooled connections older than this - * // threshold will be closed and removed from the pool. Such discarding happens during connection acquisition - * // so that new session is never backed by an old connection. Setting this option to a low value will cause - * // a high connection churn and might result in a performance hit. It is recommended to set maximum lifetime - * // to a slightly smaller value than the one configured in network equipment (load balancer, proxy, firewall, - * // etc. can also limit maximum connection lifetime). No maximum lifetime limit is imposed by default. Zero - * // and negative values result in lifetime not being checked. - * maxConnectionLifetime: 60 * 60 * 1000, // 1 hour - * - * // The maximum amount of time to wait to acquire a connection from the pool (to either create a new - * // connection or borrow an existing one. - * connectionAcquisitionTimeout: 60000, // 1 minute - * - * // Specify the maximum time in milliseconds transactions are allowed to retry via - * // `Session#readTransaction()` and `Session#writeTransaction()` functions. - * // These functions will retry the given unit of work on `ServiceUnavailable`, `SessionExpired` and transient - * // errors with exponential backoff using initial delay of 1 second. - * // Default value is 30000 which is 30 seconds. - * maxTransactionRetryTime: 30000, // 30 seconds - * - * // Specify socket connection timeout in milliseconds. Numeric values are expected. Negative and zero values - * // result in no timeout being applied. Connection establishment will be then bound by the timeout configured - * // on the operating system level. Default value is 30000, which is 30 seconds. - * connectionTimeout: 30000, // 30 seconds - * - * // Make this driver always return native JavaScript numbers for integer values, instead of the - * // dedicated {@link Integer} class. Values that do not fit in native number bit range will be represented as - * // `Number.NEGATIVE_INFINITY` or `Number.POSITIVE_INFINITY`. - * // **Warning:** ResultSummary It is not always safe to enable this setting when JavaScript applications are not the only ones - * // interacting with the database. Stored numbers might in such case be not representable by native - * // {@link Number} type and thus driver will return lossy values. This might also happen when data was - * // initially imported using neo4j import tool and contained numbers larger than - * // `Number.MAX_SAFE_INTEGER`. Driver will then return positive infinity, which is lossy. - * // Default value for this option is `false` because native JavaScript numbers might result - * // in loss of precision in the general case. - * disableLosslessIntegers: false, - * - * // Specify the logging configuration for the driver. Object should have two properties `level` and `logger`. - * // - * // Property `level` represents the logging level which should be one of: 'error', 'warn', 'info' or 'debug'. This property is optional and - * // its default value is 'info'. Levels have priorities: 'error': 0, 'warn': 1, 'info': 2, 'debug': 3. Enabling a certain level also enables all - * // levels with lower priority. For example: 'error', 'warn' and 'info' will be logged when 'info' level is configured. - * // - * // Property `logger` represents the logging function which will be invoked for every log call with an acceptable level. The function should - * // take two string arguments `level` and `message`. The function should not execute any blocking or long-running operations - * // because it is often executed on a hot path. - * // - * // No logging is done by default. See `neo4j.logging` object that contains predefined logging implementations. - * logging: { - * level: 'info', - * logger: (level, message) => console.log(level + ' ' + message) - * }, - * - * // Specify a custom server address resolver function used by the routing driver to resolve the initial address used to create the driver. - * // Such resolution happens: - * // * during the very first rediscovery when driver is created - * // * when all the known routers from the current routing table have failed and driver needs to fallback to the initial address - * // - * // In NodeJS environment driver defaults to performing a DNS resolution of the initial address using 'dns' module. - * // In browser environment driver uses the initial address as-is. - * // Value should be a function that takes a single string argument - the initial address. It should return an array of new addresses. - * // Address is a string of shape ':'. Provided function can return either a Promise resolved with an array of addresses - * // or array of addresses directly. - * resolver: function(address) { - * return ['127.0.0.1:8888', 'fallback.db.com:7687']; - * }, - * - * // Optionally override the default user agent name. - * userAgent: USER_AGENT - * } - * - * @param {string} url The URL for the Neo4j database, for instance "neo4j://localhost" and/or "bolt://localhost" - * @param {Map} authToken Authentication credentials. See {@link auth} for helpers. - * @param {Object} config Configuration object. See the configuration section above for details. - * @returns {Driver} - */ -function driver$1(url, authToken) { - var config = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; - (0, util.assertString)(url, 'Bolt URL'); - - var parsedUrl = _urlUtil["default"].parseDatabaseUrl(url); // Determine entryption/trust options from the URL. - - - var routing = false; - var encrypted = false; - var trust; - - switch (parsedUrl.scheme) { - case 'bolt': - break; - - case 'bolt+s': - encrypted = true; - trust = 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'; - break; - - case 'bolt+ssc': - encrypted = true; - trust = 'TRUST_ALL_CERTIFICATES'; - break; - - case 'neo4j': - routing = true; - break; - - case 'neo4j+s': - encrypted = true; - trust = 'TRUST_SYSTEM_CA_SIGNED_CERTIFICATES'; - routing = true; - break; - - case 'neo4j+ssc': - encrypted = true; - trust = 'TRUST_ALL_CERTIFICATES'; - routing = true; - break; - - default: - throw new Error("Unknown scheme: ".concat(parsedUrl.scheme)); - } // Encryption enabled on URL, propagate trust to the config. - - - if (encrypted) { - // Check for configuration conflict between URL and config. - if ('encrypted' in config || 'trust' in config) { - throw new Error('Encryption/trust can only be configured either through URL or config, not both'); - } - - config.encrypted = util.ENCRYPTION_ON; - config.trust = trust; - } // Sanitize authority token. Nicer error from server when a scheme is set. - - - authToken = authToken || {}; - authToken.scheme = authToken.scheme || 'none'; // Use default user agent or user agent specified by user. - - config.userAgent = config.userAgent || USER_AGENT; - - if (routing) { - return new _routingDriver["default"](_serverAddress["default"].fromUrl(parsedUrl.hostAndPort), parsedUrl.query, config.userAgent, authToken, config); - } else { - if (!(0, util.isEmptyObjectOrNull)(parsedUrl.query)) { - throw new Error("Parameters are not supported with none routed scheme. Given URL: '".concat(url, "'")); - } - - return new driver.Driver(_serverAddress["default"].fromUrl(parsedUrl.hostAndPort), config.userAgent, authToken, config); - } -} -/** - * @property {function(username: string, password: string, realm: ?string)} basic the function to create a - * basic authentication token. - * @property {function(base64EncodedTicket: string)} kerberos the function to create a Kerberos authentication token. - * Accepts a single string argument - base64 encoded Kerberos ticket. - * @property {function(principal: string, credentials: string, realm: string, scheme: string, parameters: ?object)} custom - * the function to create a custom authentication token. - */ - - -var auth = { - basic: function basic(username, password) { - var realm = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; - - if (realm) { - return { - scheme: 'basic', - principal: username, - credentials: password, - realm: realm - }; - } else { - return { - scheme: 'basic', - principal: username, - credentials: password - }; - } - }, - kerberos: function kerberos(base64EncodedTicket) { - return { - scheme: 'kerberos', - principal: '', - // This empty string is required for backwards compatibility. - credentials: base64EncodedTicket - }; - }, - custom: function custom(principal, credentials, realm, scheme) { - var parameters = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : undefined; - - if (parameters) { - return { - scheme: scheme, - principal: principal, - credentials: credentials, - realm: realm, - parameters: parameters - }; - } else { - return { - scheme: scheme, - principal: principal, - credentials: credentials, - realm: realm - }; - } - } -}; -exports.auth = auth; -var USER_AGENT = 'neo4j-javascript/' + _version["default"]; -/** - * Object containing predefined logging configurations. These are expected to be used as values of the driver config's `logging` property. - * @property {function(level: ?string): object} console the function to create a logging config that prints all messages to `console.log` with - * timestamp, level and message. It takes an optional `level` parameter which represents the maximum log level to be logged. Default value is 'info'. - */ - -var logging = { - console: function (_console) { - function console(_x) { - return _console.apply(this, arguments); - } - - console.toString = function () { - return _console.toString(); - }; - - return console; - }(function (level) { - return { - level: level, - logger: function logger(level, message) { - return console.log("".concat(commonjsGlobal.Date.now(), " ").concat(level.toUpperCase(), " ").concat(message)); - } - }; - }) - /** - * Object containing constructors for all neo4j types. - */ - -}; -exports.logging = logging; -var types = { - Node: graphTypes.Node, - Relationship: graphTypes.Relationship, - UnboundRelationship: graphTypes.UnboundRelationship, - PathSegment: graphTypes.PathSegment, - Path: graphTypes.Path, - Result: _result["default"], - ResultSummary: _resultSummary["default"], - Record: _record["default"], - Point: spatialTypes.Point, - Date: temporalTypes.Date, - DateTime: temporalTypes.DateTime, - Duration: temporalTypes.Duration, - LocalDateTime: temporalTypes.LocalDateTime, - LocalTime: temporalTypes.LocalTime, - Time: temporalTypes.Time, - Integer: _integer["default"] - /** - * Object containing string constants representing session access modes. - */ - -}; -exports.types = types; -var session = { - READ: driver.READ, - WRITE: driver.WRITE - /** - * Object containing string constants representing predefined {@link Neo4jError} codes. - */ - -}; -exports.session = session; -var error$1 = { - SERVICE_UNAVAILABLE: error.SERVICE_UNAVAILABLE, - SESSION_EXPIRED: error.SESSION_EXPIRED, - PROTOCOL_ERROR: error.PROTOCOL_ERROR - /** - * Object containing functions to work with {@link Integer} objects. - */ - -}; -exports.error = error$1; -var integer$1 = { - toNumber: _integer.toNumber, - toString: _integer.toString, - inSafeRange: _integer.inSafeRange - /** - * Object containing functions to work with spatial types, like {@link Point}. - */ - -}; -exports.integer = integer$1; -var spatial = { - isPoint: spatialTypes.isPoint - /** - * Object containing functions to work with temporal types, like {@link Time} or {@link Duration}. - */ - -}; -exports.spatial = spatial; -var temporal = { - isDuration: temporalTypes.isDuration, - isLocalTime: temporalTypes.isLocalTime, - isTime: temporalTypes.isTime, - isDate: temporalTypes.isDate, - isLocalDateTime: temporalTypes.isLocalDateTime, - isDateTime: temporalTypes.isDateTime - /** - * @private - */ - -}; -exports.temporal = temporal; -var forExport = { - driver: driver$1, - "int": _integer["int"], - isInt: _integer.isInt, - isPoint: spatialTypes.isPoint, - isDuration: temporalTypes.isDuration, - isLocalTime: temporalTypes.isLocalTime, - isTime: temporalTypes.isTime, - isDate: temporalTypes.isDate, - isLocalDateTime: temporalTypes.isLocalDateTime, - isDateTime: temporalTypes.isDateTime, - integer: integer$1, - Neo4jError: error.Neo4jError, - auth: auth, - logging: logging, - types: types, - session: session, - error: error$1, - spatial: spatial, - temporal: temporal -}; -var _default = forExport; -exports["default"] = _default; -}); - -var neo4j = /*@__PURE__*/getDefaultExportFromCjs(lib); - -/** `Object#toString` result references. */ -var regexpTag$2 = '[object RegExp]'; - -/** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ -function baseIsRegExp(value) { - return isObjectLike_1(value) && _baseGetTag(value) == regexpTag$2; -} - -var _baseIsRegExp = baseIsRegExp; - -/* Node.js helper references. */ -var nodeIsRegExp = _nodeUtil && _nodeUtil.isRegExp; - -/** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true - * - * _.isRegExp('/abc/'); - * // => false - */ -var isRegExp = nodeIsRegExp ? _baseUnary(nodeIsRegExp) : _baseIsRegExp; - -var isRegExp_1 = isRegExp; - -/** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - */ -function last$1(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; -} - -var last_1 = last$1; - -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike_1(value) && isArrayLike_1(value); -} - -var isArrayLikeObject_1 = isArrayLikeObject; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax$1 = Math.max; - -/** - * This method is like `_.zip` except that it accepts an array of grouped - * elements and creates an array regrouping the elements to their pre-zip - * configuration. - * - * @static - * @memberOf _ - * @since 1.2.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] - */ -function unzip(array) { - if (!(array && array.length)) { - return []; - } - var length = 0; - array = _arrayFilter(array, function(group) { - if (isArrayLikeObject_1(group)) { - length = nativeMax$1(group.length, length); - return true; - } - }); - return _baseTimes(length, function(index) { - return _arrayMap(array, _baseProperty(index)); - }); -} - -var unzip_1 = unzip; - -/** - * Creates an array of grouped elements, the first of which contains the - * first elements of the given arrays, the second of which contains the - * second elements of the given arrays, and so on. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @returns {Array} Returns the new array of grouped elements. - * @example - * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] - */ -var zip$2 = _baseRest(unzip_1); - -var zip_1 = zip$2; - -/** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ -function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? _baseFlatten(array, 1) : []; -} - -var flatten_1 = flatten; - -/****************************************************************************** -nodeCleanup() installs functions -- cleanup handlers -- that perform cleanup activities just before the node process exits, except on SIGKILL, which can't be intercepted. nodeCleanup() can also install messages to be written to stderr on either SIGINT or an uncaught exception. - -Each cleanup handler has the following (FlowType) signature: - - cleanupHandler(exitCode: number|null, signal: string|null): boolean? - -If the process is terminating for a reason other than a signal, exitCode is an integer that provides the reason for termination, and signal is null. If the process received a POSIX signal, signal is the signal's string name, and exitCode is null. These are also the arguments passed to a process' `exit` event handler, mirrored in node-cleanup for consistency. - -The process terminates after cleanup, except possibly on signals. If any cleanup handler returns a boolean false for a signal, the process will not exit; otherwise the process exits. SIGKILL cannot be intercepted. - -Install a cleanup handler as follows: - - var nodeCleanup = require('node-cleanup'); - nodeCleanup(cleanupHandler, stderrMessages); - -Or to only install stderr messages: - - nodeCleanup(stderrMessages); - -Or to install the default stderr messages: - - nodeCleanup(); - -nodeCleanup() may be called multiple times to install multiple cleanup handlers. However, only the most recently installed stderr messages get used. The messages available are ctrl_C and uncaughtException. - -The following uninstalls all cleanup handlers and may be called multiple times in succession: - - nodeCleanup.uninstall(); - -This module has its origin in code by @CanyonCasa at http://stackoverflow.com/a/21947851/650894, but the module was significantly rewritten to resolve issues raised by @Banjocat at http://stackoverflow.com/questions/14031763/doing-a-cleanup-action-just-before-node-js-exits#comment68567869_21947851. It has also been extended for greater configurability. -******************************************************************************/ -//// CONSTANTS //////////////////////////////////////////////////////////////// - -var DEFAULT_MESSAGES = { - ctrl_C: '[ctrl-C]', - uncaughtException: 'Uncaught exception...' -}; - -//// CONFIGURATION //////////////////////////////////////////////////////////// - -var cleanupHandlers = null; // array of cleanup handlers to call -var messages = null; // messages to write to stderr - -var sigintHandler; // POSIX signal handlers -var sighupHandler; -var sigquitHandler; -var sigtermHandler; - -//// HANDLERS ///////////////////////////////////////////////////////////////// - -function signalHandler(signal) -{ - var exit = true; - cleanupHandlers.forEach(function (cleanup) { - if (cleanup(null, signal) === false) - exit = false; - }); - if (exit) { - if (signal === 'SIGINT' && messages && messages.ctrl_C !== '') - process.stderr.write(messages.ctrl_C + "\n"); - uninstall(); // don't cleanup again - // necessary to communicate the signal to the parent process - process.kill(process.pid, signal); - } -} - -function exceptionHandler(e) -{ - if (messages && messages.uncaughtException !== '') - process.stderr.write(messages.uncaughtException + "\n"); - process.stderr.write(e.stack + "\n"); - process.exit(1); // will call exitHandler() for cleanup -} - -function exitHandler(exitCode, signal) -{ - cleanupHandlers.forEach(function (cleanup) { - cleanup(exitCode, signal); - }); -} - -//// MAIN ///////////////////////////////////////////////////////////////////// - -function install(cleanupHandler, stderrMessages) -{ - if (cleanupHandler) { - if (typeof cleanupHandler === 'object') { - stderrMessages = cleanupHandler; - cleanupHandler = null; - } - } - else if (!stderrMessages) - stderrMessages = DEFAULT_MESSAGES; - - if (stderrMessages) { - if (messages === null) - messages = { ctrl_C: '', uncaughtException: '' }; - if (typeof stderrMessages.ctrl_C === 'string') - messages.ctrl_C = stderrMessages.ctrl_C; - if (typeof stderrMessages.uncaughtException === 'string') - messages.uncaughtException = stderrMessages.uncaughtException; - } - - if (cleanupHandlers === null) { - cleanupHandlers = []; // establish before installing handlers - - sigintHandler = signalHandler.bind(this, 'SIGINT'); - sighupHandler = signalHandler.bind(this, 'SIGHUP'); - sigquitHandler = signalHandler.bind(this, 'SIGQUIT'); - sigtermHandler = signalHandler.bind(this, 'SIGTERM'); - - process.on('SIGINT', sigintHandler); - process.on('SIGHUP', sighupHandler); - process.on('SIGQUIT', sigquitHandler); - process.on('SIGTERM', sigtermHandler); - process.on('uncaughtException', exceptionHandler); - process.on('exit', exitHandler); - - cleanupHandlers.push(cleanupHandler || noCleanup); - } - else if (cleanupHandler) - cleanupHandlers.push(cleanupHandler); -} - -function uninstall() -{ - if (cleanupHandlers !== null) { - process.removeListener('SIGINT', sigintHandler); - process.removeListener('SIGHUP', sighupHandler); - process.removeListener('SIGQUIT', sigquitHandler); - process.removeListener('SIGTERM', sigtermHandler); - process.removeListener('uncaughtException', exceptionHandler); - process.removeListener('exit', exitHandler); - cleanupHandlers = null; // null only after uninstalling - } -} - -function noCleanup() -{ - return true; // signals will always terminate process -} - -//// EXPORTS ////////////////////////////////////////////////////////////////// - -var nodeCleanup = install; -install.uninstall = uninstall; - -/** - * Converts a string to camel case and ensures it is unique in the provided - * list. - * @param {string} str - * @param {Array} existing - * @return {string} - */ -function uniqueString(str, existing) { - var camelString = camelCase_1(str); // Check if the string already has a number extension - - - var number = null; - var matches = camelString.match(/[0-9]+$/); - - if (matches) { - number = +matches[0]; - camelString = camelString.substr(0, camelString.length - matches[0].length); - } // Compute all taken suffixes that are similar to the given string - - - var regex = new RegExp("^" + camelString + "([0-9]*)$"); - - var takenSuffixes = reduce_1(existing, function (suffixes, existingString) { - var matches = existingString.match(regex); - - if (matches) { - var suffix = matches[1]; - suffixes.push(suffix ? +suffix : 1); - } - - return suffixes; - }, []); // If there was no suffix on the given string or it was already taken, - // compute the new suffix. - - - if (!number || takenSuffixes.indexOf(number) !== -1) { - number = Math.max.apply(Math, __spreadArrays([0], takenSuffixes)) + 1; - } // Append the suffix if it is not 1 - - - return camelString + (number === 1 ? '' : number); -} -/** - * Converts a Javascript value into a string suitable for a cypher query. - * @param {object|Array|string|boolean|number} value - * @return {string} - */ - -function stringifyValue(value) { - if (isNumber_1(value) || isBoolean_1(value)) { - return "" + value; - } - - if (isString_1(value)) { - return "'" + value + "'"; - } - - if (isArray_1(value)) { - var str = map_1(value, stringifyValue).join(', '); - - return "[ " + str + " ]"; - } - - if (isObject_1(value)) { - var pairs = map_1(value, function (el, key) { - return key + ": " + stringifyValue(el); - }); - - var str = pairs.join(', '); - return "{ " + str + " }"; - } - - return ''; -} -/** - * Converts labels into a string that can be put into a pattern. - * - * @param {string|array} labels - * @param relation When true, joins labels by a | instead of : - * @return {string} - */ - -function stringifyLabels(labels, relation) { - if (relation === void 0) { - relation = false; - } - - if (labels.length === 0) { - return ''; - } - - return ":" + castArray_1(labels).join(relation ? '|' : ':'); -} -/** - * Converts a path length bounds into a string to put into a relationship. - * @param {Array|int} bounds An array of bounds - * @return {string} - */ - -function stringifyPathLength(bounds) { - if (isNil_1(bounds)) { - return ''; - } - - if (bounds === '*') { - return '*'; - } - - if (isNumber_1(bounds)) { - return "*" + bounds; - } - - var lower = isNil_1(bounds[0]) ? '' : "" + bounds[0]; - var upper = isNil_1(bounds[1]) ? '' : "" + bounds[1]; - return lower || upper ? "*" + lower + ".." + upper : '*'; -} - -var Parameter = -/** @class */ -function () { - function Parameter(name, value) { - this.name = name; - this.value = value; - } - - Parameter.prototype.toString = function () { - return "$" + this.name; - }; - - return Parameter; -}(); - -var ParameterBag = -/** @class */ -function () { - function ParameterBag() { - this.parameterMap = {}; - } - /** - * Constructs a unique name for this parameter bag. - * @return {string} - */ - - - ParameterBag.prototype.getName = function (name) { - if (name === void 0) { - name = 'p'; - } - - return uniqueString(name, keys_1(this.parameterMap)); - }; - /** - * Adds a new parameter to this bag. - * @param {*} value - * @param {string|undefined} name - * @return {Parameter} Newly created parameter object. - */ - - - ParameterBag.prototype.addParam = function (value, name) { - var actualName = this.getName(name); - var param = new Parameter(actualName, value); - this.parameterMap[actualName] = param; - return param; - }; - /** - * Adds an existing parameter to this bag. The name may be changed if - * it is already taken, however, the Parameter object will not be recreated. - * @param {Parameter} param - * @return {Parameter} - */ - - - ParameterBag.prototype.addExistingParam = function (param) { - param.name = this.getName(param.name); - this.parameterMap[param.name] = param; - return param; - }; - /** - * Returns the params in a name: value object suitable for putting into a - * query object. - * @return {object} - */ - - - ParameterBag.prototype.getParams = function () { - return mapValues_1(this.parameterMap, 'value'); - }; - /** - * Removes a parameter from the internal map. - * @param {string} name - */ - - - ParameterBag.prototype.deleteParam = function (name) { - delete this.parameterMap[name]; - }; - /** - * Copies all parameters from another bag into this bag. - */ - - - ParameterBag.prototype.importParams = function (other) { - for (var key in other.parameterMap) { - this.addExistingParam(other.parameterMap[key]); - } - }; - /** - * Returns a parameter with the given name. - */ - - - ParameterBag.prototype.getParam = function (name) { - return this.parameterMap[name]; - }; - - return ParameterBag; -}(); - -var ParameterContainer = -/** @class */ -function () { - function ParameterContainer() { - this.parameterBag = new ParameterBag(); - } - - ParameterContainer.prototype.useParameterBag = function (newBag) { - newBag.importParams(this.parameterBag); - this.parameterBag = newBag; - }; - - ParameterContainer.prototype.getParams = function () { - return this.parameterBag.getParams(); - }; - /** - * Adds a new parameter to the bag. - * @param {*} value - * @param {string|undefined} name - * @return {Parameter} Newly created parameter object. - */ - - - ParameterContainer.prototype.addParam = function (value, name) { - return this.parameterBag.addParam(value, name); - }; - - ParameterContainer.prototype.getParameterBag = function () { - return this.parameterBag; - }; - - return ParameterContainer; -}(); - -var Clause = -/** @class */ -function (_super) { - __extends(Clause, _super); - - function Clause() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * Turns the clause into a query string. - * @return {string} Partial query string. - */ - - - Clause.prototype.toString = function () { - return this.build(); - }; - /** - * Turns the clause into a query object. - * @return {object} Query object with two parameters: query and params. - */ - - - Clause.prototype.buildQueryObject = function () { - return { - query: this.build(), - params: this.getParams() - }; - }; - /** - * Turns the clause into a query string with parameters - * interpolated into the string. For debugging purposes only. - * @return {string} - */ - - - Clause.prototype.interpolate = function () { - var query = this.build(); - var params = this.getParams(); - - for (var name in params) { - var pattern = new RegExp("\\$" + name + "(?![a-zA-Z0-9_])", 'g'); - query = query.replace(pattern, stringifyValue(params[name])); - } - - return query; - }; - - return Clause; -}(ParameterContainer); - -var Pattern = -/** @class */ -function (_super) { - __extends(Pattern, _super); - - function Pattern(name, labels, conditions, options) { - if (options === void 0) { - options = { - expanded: true - }; - } - - var _this = _super.call(this) || this; - - _this.options = options; - _this.conditionParams = {}; - - var isConditions = function (a) { - return isObjectLike_1(a) && !isArray_1(a); - }; - - var tempName = name; - var tempLabels = labels; - var tempConditions = conditions; - - if (isNil_1(tempConditions)) { - if (isConditions(tempLabels)) { - tempConditions = tempLabels; - tempLabels = undefined; - } else if (isNil_1(tempLabels) && isConditions(tempName)) { - tempConditions = tempName; - tempName = undefined; - } else { - tempConditions = {}; - } - } - - if (isNil_1(tempLabels)) { - if (isArray_1(tempName)) { - tempLabels = tempName; - tempName = undefined; - } else { - tempLabels = []; - } - } - - if (isNil_1(tempName)) { - tempName = ''; - } - - if (!isString_1(tempName)) { - throw new TypeError('Name must be a string.'); - } - - if (!isString_1(tempLabels) && !isArray_1(tempLabels)) { - throw new TypeError('Labels must be a string or an array'); - } - - if (!isConditions(tempConditions)) { - throw new TypeError('Conditions must be an object.'); - } - - _this.labels = castArray_1(tempLabels); - _this.name = tempName; - _this.conditions = tempConditions; - - _this.setExpandedConditions(options.expanded); - - return _this; - } - - Pattern.prototype.setExpandedConditions = function (expanded) { - if (this.useExpandedConditions !== expanded) { - this.useExpandedConditions = expanded; - this.rebindConditionParams(); - } - }; - - Pattern.prototype.rebindConditionParams = function () { - var _this = this; // Delete old bindings - - - if (this.conditionParams instanceof Parameter) { - this.parameterBag.deleteParam(this.conditionParams.name); - } else { - for (var key in this.conditionParams) { - this.parameterBag.deleteParam(this.conditionParams[key].name); - } - } // Rebind params - - - if (!isEmpty_1(this.conditions)) { - if (this.useExpandedConditions) { - this.conditionParams = mapValues_1(this.conditions, function (value, name) { - return _this.parameterBag.addParam(value, name); - }); - } else { - this.conditionParams = this.parameterBag.addParam(this.conditions, 'conditions'); - } - } else { - this.conditionParams = {}; - } - }; - - Pattern.prototype.getNameString = function () { - return this.name ? this.name : ''; - }; - - Pattern.prototype.getLabelsString = function (relation) { - if (relation === void 0) { - relation = false; - } - - return stringifyLabels(this.labels, relation); - }; - - Pattern.prototype.getConditionsParamString = function () { - if (isEmpty_1(this.conditions)) { - return ''; - } - - if (this.useExpandedConditions) { - var strings = map_1(this.conditionParams, function (param, name) { - return name + ": " + param; - }); - - return "{ " + strings.join(', ') + " }"; - } - - return this.conditionParams.toString(); - }; - - return Pattern; -}(Clause); - -var NodePattern = -/** @class */ -function (_super) { - __extends(NodePattern, _super); - - function NodePattern(name, labels, conditions) { - return _super.call(this, name, labels, conditions) || this; - } - - NodePattern.prototype.build = function () { - var query = this.getNameString(); - query += this.getLabelsString(); - query += " " + this.getConditionsParamString(); - return "(" + trim_1(query) + ")"; - }; - - return NodePattern; -}(Pattern); - -var isPathLengthArray = function (value) { - return isArray_1(value) && every_1(value, function (item) { - return isNumber_1(item) || isNil_1(item); - }) && value.length > 0; -}; - -var isPathLength = function (value) { - return value === '*' || isNumber_1(value) || isPathLengthArray(value); -}; - -var RelationPattern = -/** @class */ -function (_super) { - __extends(RelationPattern, _super); - - function RelationPattern(dir, name, labels, conditions, length) { - var _this = this; - - var tempName = name; - var tempLabels = labels; - var tempConditions = conditions; - var tempLength = length; - - if (isNil_1(tempLength)) { - if (isPathLength(tempConditions)) { - tempLength = tempConditions; - tempConditions = undefined; - } else if (isNil_1(tempConditions) && isPathLength(tempLabels)) { - tempLength = tempLabels; - tempLabels = undefined; - } else if (isNil_1(tempConditions) && isNil_1(tempLabels) && isPathLength(tempName)) { - tempLength = tempName; - tempName = undefined; - } - } - - if (isPathLength(tempName) || isPathLength(tempLabels) || isPathLength(tempConditions)) { - throw new TypeError('Invalid argument combination.'); - } - - _this = _super.call(this, tempName, tempLabels, tempConditions) || this; - _this.dir = dir; - _this.length = tempLength; - return _this; - } - - RelationPattern.prototype.build = function () { - var name = this.getNameString(); - var labels = this.getLabelsString(true); - var length = stringifyPathLength(this.length); - var conditions = this.getConditionsParamString(); - - var query = trim_1("" + name + labels + length + " " + conditions); - - var arrows = { - in: ['<-', '-'], - out: ['-', '->'], - either: ['-', '-'] - }; - return arrows[this.dir].join(query.length > 0 ? "[" + query + "]" : ''); - }; - - return RelationPattern; -}(Pattern); - -var PatternClause = -/** @class */ -function (_super) { - __extends(PatternClause, _super); - - function PatternClause(patterns, options) { - if (options === void 0) { - options = { - useExpandedConditions: false - }; - } - - var _this = _super.call(this) || this; - - var defaultOptions = { - useExpandedConditions: true - }; - - var useExpandedConditions = assign_1(defaultOptions, options).useExpandedConditions; // Ensure patterns is a two dimensional array. - - - var arr = castArray_1(patterns); - - _this.patterns = isArray_1(arr[0]) ? arr : [arr]; // Add child patterns as clauses - - _this.patterns.forEach(function (arr) { - return arr.forEach(function (pat) { - pat.setExpandedConditions(useExpandedConditions); - pat.useParameterBag(_this.parameterBag); - }); - }); - - return _this; - } - - PatternClause.prototype.build = function () { - var patternStrings = map_1(this.patterns, function (pattern) { - return reduce_1(pattern, function (str, clause) { - return str + clause.build(); - }, ''); - }); - - return patternStrings.join(', '); - }; - - return PatternClause; -}(Clause); - -var Create = -/** @class */ -function (_super) { - __extends(Create, _super); - - function Create(patterns, options) { - if (options === void 0) { - options = {}; - } - - var _this = _super.call(this, patterns, { - useExpandedConditions: false - }) || this; - - _this.options = options; - return _this; - } - - Create.prototype.build = function () { - var unique = this.options.unique ? ' UNIQUE' : ''; - return "CREATE" + unique + " " + _super.prototype.build.call(this); - }; - - return Create; -}(PatternClause); - -var TermListClause = -/** @class */ -function (_super) { - __extends(TermListClause, _super); - /** - * Accepts: - * node -> string - * many nodes -> string[] - * nodes with aliases -> Dictionary - * node properties -> Dictionary - * node properties with aliases -> Dictionary[]> - * or an array of any combination - */ - - - function TermListClause(terms) { - var _this = _super.call(this) || this; - - _this.terms = castArray_1(terms); - return _this; - } - - TermListClause.prototype.build = function () { - return this.toString(); - }; - - TermListClause.prototype.toString = function () { - var _this = this; - - return flatMapDeep_1(this.terms, function (term) { - return _this.stringifyTerm(term); - }).join(', '); - }; - - TermListClause.prototype.stringifyTerm = function (term) { - // Just a node - if (isString_1(term)) { - return [this.stringifyProperty(term)]; - } // Node properties or aliases - - - if (isPlainObject_1(term)) { - return this.stringifyDictionary(term); - } - - return []; - }; - - TermListClause.prototype.stringifyProperty = function (prop, alias, node) { - var prefixString = node ? node + "." : ''; - var aliasString = alias ? alias + " AS " : ''; - return prefixString + aliasString + prop; - }; - - TermListClause.prototype.stringifyProperties = function (props, alias, node) { - var _this = this; - - var convertToString = function (list, prop) { - if (isString_1(prop)) { - // Single node property - list.push(_this.stringifyProperty(prop, alias, node)); - } else { - // Node properties with aliases - list.push.apply(list, map_1(prop, function (name, alias) { - return _this.stringifyProperty(name, alias, node); - })); - } - - return list; - }; - - return reduce_1(castArray_1(props), convertToString, []); - }; - - TermListClause.prototype.stringifyDictionary = function (node) { - var _this = this; - - return reduce_1(node, function (list, prop, key) { - if (isString_1(prop)) { - // Alias - list.push(_this.stringifyProperty(prop, key)); - } else { - // Node with properties - list.push.apply(list, _this.stringifyProperties(prop, undefined, key)); - } - - return list; - }, []); - }; - - return TermListClause; -}(Clause); - -var With = -/** @class */ -function (_super) { - __extends(With, _super); - /** - * Creates a with clause - * @param {string|object|array} terms - */ - - - function With(terms) { - return _super.call(this, terms) || this; - } - - With.prototype.build = function () { - return "WITH " + _super.prototype.build.call(this); - }; - - return With; -}(TermListClause); - -var Unwind = -/** @class */ -function (_super) { - __extends(Unwind, _super); - - function Unwind(list, name) { - var _this = _super.call(this) || this; - - _this.list = list; - _this.name = name; - _this.listParam = _this.parameterBag.addParam(_this.list, 'list'); - return _this; - } - - Unwind.prototype.build = function () { - return "UNWIND " + this.listParam + " AS " + this.name; - }; - - return Unwind; -}(Clause); - -var Delete = -/** @class */ -function (_super) { - __extends(Delete, _super); - - function Delete(variables, options) { - if (options === void 0) { - options = {}; - } - - var _this = _super.call(this) || this; - - _this.options = options; - _this.variables = castArray_1(variables); - return _this; - } - - Delete.prototype.build = function () { - var detach = this.options.detach ? 'DETACH ' : ''; - return detach + "DELETE " + this.variables.join(', '); - }; - - return Delete; -}(Clause); - -var Set$2 = -/** @class */ -function (_super) { - __extends(Set, _super); - - function Set(_a, options) { - var labels = _a.labels, - values = _a.values, - variables = _a.variables; - - if (options === void 0) { - options = {}; - } - - var _this = _super.call(this) || this; - - _this.makeLabelStatement = function (labels, key) { - return key + stringifyLabels(labels); - }; - - _this.makeValueStatement = function (value, key) { - var valueIsObject = value instanceof Parameter ? isObject_1(value.value) : isObject_1(value); - var op = _this.merge && valueIsObject ? ' += ' : ' = '; - return key + op + value; - }; - - _this.makeVariableStatement = function (value, key) { - var op = _this.merge ? ' += ' : ' = '; - - if (isString_1(value)) { - return key + op + value; - } - - var operationStrings = map_1(value, function (value, prop) { - return key + "." + prop + op + value; - }); - - return operationStrings.join(', '); - }; - - _this.labels = mapValues_1(labels, castArray_1); - _this.values = mapValues_1(values, function (value, name) { - return _this.parameterBag.addParam(value, name); - }); - _this.variables = variables || {}; - _this.merge = !!options.merge; - return _this; - } - - Set.prototype.build = function () { - var labels = map_1(this.labels, this.makeLabelStatement); - - var values = map_1(this.values, this.makeValueStatement); - - var variables = map_1(this.variables, this.makeVariableStatement); - - return "SET " + concat_1(labels, values, variables).join(', '); - }; - - return Set; -}(Clause); - -var Match = -/** @class */ -function (_super) { - __extends(Match, _super); - - function Match(patterns, options) { - if (options === void 0) { - options = { - optional: false - }; - } - - var _this = _super.call(this, patterns, { - useExpandedConditions: true - }) || this; - - _this.options = options; - return _this; - } - - Match.prototype.build = function () { - var str = 'MATCH '; - - if (this.options.optional) { - str = "OPTIONAL " + str; - } - - return str + _super.prototype.build.call(this); - }; - - return Match; -}(PatternClause); - -var Remove = -/** @class */ -function (_super) { - __extends(Remove, _super); - - function Remove(_a) { - var _b = _a.labels, - labels = _b === void 0 ? {} : _b, - _c = _a.properties, - properties = _c === void 0 ? {} : _c; - - var _this = _super.call(this) || this; - - _this.labels = mapValues_1(labels, castArray_1); - _this.properties = mapValues_1(properties, castArray_1); - return _this; - } - - Remove.prototype.build = function () { - var labels = map_1(this.labels, function (labels, key) { - return key + stringifyLabels(labels); - }); - - var properties = flatMap_1(this.properties, function (properties, key) { - return map_1(properties, function (property) { - return key + "." + property; - }); - }); - - return "REMOVE " + __spreadArrays(labels, properties).join(', '); - }; - - return Remove; -}(Clause); - -var Return = -/** @class */ -function (_super) { - __extends(Return, _super); - - function Return(terms, options) { - if (options === void 0) { - options = {}; - } - - var _this = _super.call(this, terms) || this; - - _this.options = options; - return _this; - } - - Return.prototype.build = function () { - var distinct = this.options.distinct ? ' DISTINCT' : ''; - return "RETURN" + distinct + " " + _super.prototype.build.call(this); - }; - - return Return; -}(TermListClause); - -var Skip = -/** @class */ -function (_super) { - __extends(Skip, _super); - - function Skip(amount) { - var _this = _super.call(this) || this; - - _this.amount = amount; - _this.amountParam = _this.addParam(neo4j.int(amount), 'skipCount'); - return _this; - } - - Skip.prototype.build = function () { - return "SKIP " + this.amountParam; - }; - - return Skip; -}(Clause); - -var Limit = -/** @class */ -function (_super) { - __extends(Limit, _super); - - function Limit(amount) { - var _this = _super.call(this) || this; - - _this.amount = amount; - _this.amountParam = _this.addParam(neo4j.int(amount), 'limitCount'); - return _this; - } - - Limit.prototype.build = function () { - return "LIMIT " + this.amountParam; - }; - - return Limit; -}(Clause); - -function compare(operator, value, variable, paramName) { - return function (params, name) { - var baseParamName = paramName || last_1(name.split('.')); - - var parts = [name, operator, variable ? value : params.addParam(value, baseParamName)]; - return parts.join(' '); - }; -} -/** - * Regexp comparator for use in where clauses. Also accepts a case insensitive - * to make it easier to add the `'(?i)'` flag to the start of your regexp. - * If you are already using flags in your regexp, you should not set insensitive - * to true because it will prepend `'(?i)'` which will make your regexp - * malformed. - * - * For convenience you can also pass a Javascript RegExp object into this - * comparator, which will then be converted into a string before it is - * passed to cypher. *However*, beware that the cypher regexp syntax is - * inherited from [java]{@link - * https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html}, - * and may have slight differences to the Javascript syntax. For example, - * Javascript RegExp flags will not be preserved when sent to cypher. - * - * If you want to compare against a Neo4j variable you can set `variable` to - * true and the value will be inserted literally into the query. - * - * ``` - * query.where({ name: regexp('s.*e') }) - * // WHERE name =~ 's.*e' - * - * query.where({ name: regexp('s.*e', true) }) - * // WHERE name =~ '(?i)s.*e' - * - * query.where({ name: regexp('clientPattern', false, true) }) - * // WHERE name =~ clientPattern - * ``` - * @param exp - * @param insensitive - * @param {boolean} variable - * @returns {Comparator} - */ - -function regexp(exp, insensitive, variable) { - var stringExp = exp; - - if (exp instanceof RegExp) { - // Convert regular expression to string and strip slashes and trailing flags. - // This regular expression will always match something so we can use the ! operator to ignore - // type errors. - stringExp = exp.toString().match(/\/(.*)\/[a-z]*/)[1]; - } - - return compare('=~', insensitive ? "(?i)" + stringExp : stringExp, variable); -} - -var Precedence; - -(function (Precedence) { - Precedence[Precedence["None"] = 0] = "None"; - Precedence[Precedence["Or"] = 1] = "Or"; - Precedence[Precedence["Xor"] = 2] = "Xor"; - Precedence[Precedence["And"] = 3] = "And"; - Precedence[Precedence["Not"] = 4] = "Not"; -})(Precedence || (Precedence = {})); - -var WhereOp = -/** @class */ -function () { - function WhereOp() {} - - return WhereOp; -}(); -function stringifyCondition(params, condition, name) { - if (name === void 0) { - name = ''; - } - - if (isFunction_1(condition)) { - return condition(params, name); - } - - var conditionName = last_1(name.split('.')); - - return name + " = " + params.addParam(condition, conditionName); -} -function stringCons(params, conditions, precedence, name) { - if (precedence === void 0) { - precedence = Precedence.None; - } - - if (name === void 0) { - name = ''; - } - - if (isArray_1(conditions)) { - return combineOr(params, conditions, precedence, name); - } - - if (isPlainObject_1(conditions)) { - return combineAnd(params, conditions, precedence, name); - } - - if (conditions instanceof WhereOp) { - return conditions.evaluate(params, precedence, name); - } - - if (isRegExp_1(conditions)) { - return stringifyCondition(params, regexp(conditions), name); - } - - return stringifyCondition(params, conditions, name); -} -function combineNot(params, conditions, precedence, name) { - if (precedence === void 0) { - precedence = Precedence.None; - } - - if (name === void 0) { - name = ''; - } - - var string = "NOT " + stringCons(params, conditions, Precedence.Not, name); - var braces = precedence !== Precedence.None && precedence > Precedence.Not; - return braces ? "(" + string + ")" : string; -} -function combineOr(params, conditions, precedence, name) { - if (precedence === void 0) { - precedence = Precedence.None; - } - - if (name === void 0) { - name = ''; - } // If this operator will not be used, precedence should not be altered - - - var newPrecedence = conditions.length < 2 ? precedence : Precedence.Or; - - var strings = map_1(conditions, function (condition) { - return stringCons(params, condition, newPrecedence, name); - }); - - var string = strings.join(' OR '); - var braces = precedence !== Precedence.None && precedence > newPrecedence; - return braces ? "(" + string + ")" : string; -} -function combineXor(params, conditions, precedence, name) { - if (precedence === void 0) { - precedence = Precedence.None; - } - - if (name === void 0) { - name = ''; - } // If this operator will not be used, precedence should not be altered - - - var newPrecedence = conditions.length < 2 ? precedence : Precedence.Xor; - - var strings = map_1(conditions, function (condition) { - return stringCons(params, condition, newPrecedence, name); - }); - - var string = strings.join(' XOR '); - var braces = precedence !== Precedence.None && precedence > newPrecedence; - return braces ? "(" + string + ")" : string; -} -function combineAnd(params, conditions, precedence, name) { - if (precedence === void 0) { - precedence = Precedence.None; - } - - if (name === void 0) { - name = ''; - } // Prepare name to be joined with the key of the object - - - var namePrefix = name.length > 0 ? name + "." : ''; // If this operator will not be used, precedence should not be altered - - var newPrecedence = keys_1(conditions).length < 2 ? precedence : Precedence.And; - - var strings = map_1(conditions, function (condition, key) { - return stringCons(params, condition, newPrecedence, namePrefix + key); - }); - - var string = strings.join(' AND '); - var braces = precedence !== Precedence.None && precedence > newPrecedence; - return braces ? "(" + string + ")" : string; -} - -var Where = -/** @class */ -function (_super) { - __extends(Where, _super); - - function Where(conditions) { - var _this = _super.call(this) || this; - - _this.conditions = conditions; - return _this; - } - - Where.prototype.build = function () { - return "WHERE " + stringCons(this.parameterBag, this.conditions); - }; - - return Where; -}(Clause); - -var Raw = -/** @class */ -function (_super) { - __extends(Raw, _super); - - function Raw(clause) { - var args = []; - - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - - var _this = _super.call(this) || this; - - if (isString_1(clause)) { - _this.clause = clause; - var params = args[0]; - - if (isObjectLike_1(params)) { - for (var key in params) { - if (Object.hasOwnProperty.call(params, key)) { - _this.addParam(params[key], key); - } - } - } else if (!isNil_1(params)) { - throw new TypeError('When passing a string clause to Raw, params should be an object'); - } - } else if (isArray_1(clause)) { - var queryParams = map_1(args, function (param) { - return _this.addParam(param); - }); - - _this.clause = flatten_1(zip_1(clause, queryParams)).join(''); - } else { - throw new TypeError('Clause should be a string or an array'); - } - - return _this; - } - - Raw.prototype.build = function () { - return this.clause; - }; - - return Raw; -}(Clause); - -var OrderBy = -/** @class */ -function (_super) { - __extends(OrderBy, _super); - - function OrderBy(fields, dir) { - var _this = _super.call(this) || this; - - var direction = OrderBy.normalizeDirection(dir); - - if (isString_1(fields)) { - _this.constraints = [{ - direction: direction, - field: fields - }]; - } else if (isArray_1(fields)) { - _this.constraints = map_1(fields, function (field) { - if (!isArray_1(field)) { - return { - field: field, - direction: direction - }; - } - - var fieldDirection = field[1] ? OrderBy.normalizeDirection(field[1]) : direction; - return { - field: field[0], - direction: fieldDirection - }; - }); - } else { - _this.constraints = map_1(fields, function (fieldDirection, field) { - return { - field: field, - direction: OrderBy.normalizeDirection(fieldDirection) - }; - }); - } - - return _this; - } - - OrderBy.prototype.build = function () { - var constraints = map_1(this.constraints, function (_a) { - var field = _a.field, - direction = _a.direction; - return trim_1(field + " " + direction); - }); - - return "ORDER BY " + constraints.join(', '); - }; - - OrderBy.normalizeDirection = function (dir) { - var upperDir = typeof dir === 'string' ? dir.toUpperCase() : dir; - var isDescending = upperDir === 'DESC' || upperDir === 'DESCENDING' || upperDir === true; - return isDescending ? 'DESC' : ''; - }; - - return OrderBy; -}(Clause); - -var Merge = -/** @class */ -function (_super) { - __extends(Merge, _super); - - function Merge(patterns) { - return _super.call(this, patterns, { - useExpandedConditions: true - }) || this; - } - - Merge.prototype.build = function () { - return "MERGE " + _super.prototype.build.call(this); - }; - - return Merge; -}(PatternClause); - -var OnMatch = -/** @class */ -function (_super) { - __extends(OnMatch, _super); - - function OnMatch(clause) { - var _this = _super.call(this) || this; - - _this.clause = clause; - clause.useParameterBag(_this.parameterBag); - return _this; - } - - OnMatch.prototype.build = function () { - return "ON MATCH " + this.clause.build(); - }; - - return OnMatch; -}(Clause); - -var OnCreate = -/** @class */ -function (_super) { - __extends(OnCreate, _super); - - function OnCreate(clause) { - var _this = _super.call(this) || this; - - _this.clause = clause; - clause.useParameterBag(_this.parameterBag); - return _this; - } - - OnCreate.prototype.build = function () { - return "ON CREATE " + this.clause.build(); - }; - - return OnCreate; -}(Clause); - -/** @class */ -(function (_super) { - __extends(WhereAnd, _super); - - function WhereAnd(conditions) { - var _this = _super.call(this) || this; - - _this.conditions = conditions; - return _this; - } - - WhereAnd.prototype.evaluate = function (params, precedence, name) { - if (precedence === void 0) { - precedence = Precedence.None; - } - - if (name === void 0) { - name = ''; - } - - return combineAnd(params, this.conditions, precedence, name); - }; - - return WhereAnd; -})(WhereOp); - -/** @class */ -(function (_super) { - __extends(WhereOr, _super); - - function WhereOr(conditions) { - var _this = _super.call(this) || this; - - _this.conditions = conditions; - return _this; - } - - WhereOr.prototype.evaluate = function (params, precedence, name) { - if (precedence === void 0) { - precedence = Precedence.None; - } - - if (name === void 0) { - name = ''; - } - - return combineOr(params, this.conditions, precedence, name); - }; - - return WhereOr; -})(WhereOp); - -/** @class */ -(function (_super) { - __extends(WhereXor, _super); - - function WhereXor(conditions) { - var _this = _super.call(this) || this; - - _this.conditions = conditions; - return _this; - } - - WhereXor.prototype.evaluate = function (params, precedence, name) { - if (precedence === void 0) { - precedence = Precedence.None; - } - - if (name === void 0) { - name = ''; - } - - return combineXor(params, this.conditions, precedence, name); - }; - - return WhereXor; -})(WhereOp); - -/** @class */ -(function (_super) { - __extends(WhereNot, _super); - - function WhereNot(conditions) { - var _this = _super.call(this) || this; - - _this.conditions = conditions; - return _this; - } - - WhereNot.prototype.evaluate = function (params, precedence, name) { - if (precedence === void 0) { - precedence = Precedence.None; - } - - if (name === void 0) { - name = ''; - } - - return combineNot(params, this.conditions, precedence, name); - }; - - return WhereNot; -})(WhereOp); - -/** - * Creates a node pattern like `(parent:Person { name: 'Gwenn' })`. - * - * All of the arguments are optional and most of the time you can supply only - * the ones you want, assuming you keep the order the same of course. - * - * Use the following signatures as a reference: - * - * ```typescript - * node(conditions: Dictionary) - * node(labels: string[], conditions?: Dictionary) - * node(name: string, conditions?: Dictionary) - * node(name: string, labels?: string | string[], conditions?: Dictionary) - * ``` - * *Note that labels must be an array when it is the first argument.* - * - * - * - * Some examples - * - * ```typescript - * node() - * // () - * - * node('parent') - * // (parent) - * - * node('parent', 'Person') - * // (parent:Person) - * - * node([ 'Person' ]) - * // (:Person) - * - * node('parent', [ 'Person', 'Adult' ]) - * // (parent:Person:Adult) - * - * node({ name: 'Gwenn' }) - * // ({ name: 'Gwenn' }) - * - * node('parent', { name: 'Gwenn' }) - * // (parent { name: 'Gwenn' }) - * - * node([ 'Person' ], { name: 'Gwenn' }) - * // (:Person { name: 'Gwenn' }) - * - * node('parent', 'Person', { name: 'Gwenn' }) - * // (parent:Person { name: 'Gwenn' }) - * ``` - * - * For more details on node patterns see the cypher - * [docs]{@link - * https://neo4j.com/docs/developer-manual/current/cypher/syntax/patterns/#cypher-pattern-node} - * - * @param {_.Many | _.Dictionary} name - * @param {_.Many | _.Dictionary} labels - * @param {_.Dictionary} conditions A dictionary of conditions to attach - * to the node. These are stored as parameters so there is no need to worry - * about escaping. - * @returns {NodePattern} An object representing the node pattern. - */ - -function node$1(name, labels, conditions) { - return new NodePattern(name, labels, conditions); -} // Need to disable line length because there is a long link in the documentation - -/* tslint:disable:max-line-length */ - -/** - * Creates a relation pattern like `-[rel:FriendsWith { active: true }]->`. - * - * The only required argument is direction. All other arguments are optional and all combinations of - * them are valid. The only exception is that when labels is the first argument after direction, it - * must be an array, otherwise it will be interpreted as the relation name. - * - * Some examples - * - * ```typescript - * relation('either') - * // -- - * - * relation('out', 'rel') - * // -[rel]-> - * - * relation('out', 'rel', 'FriendsWith') - * // -[rel:FriendsWith]-> - * - * relation('in', [ 'FriendsWith', 'RelatedTo' ]) - * // <-[:FriendsWith|RelatedTo]- - * // Note that this will match a relation with either the FriendsWith label or - * // the RelatedTo label. You cannot use this syntax when creating relations. - * - * relation('in', [4, 10]) - * // <-[*4..10]- - * - * relation('in', { active: true }) - * // <-[{ active: true }] - * - * relation('in', 'rel', { active: true }) - * // <-[rel { active: true }]- - * - * relation('either', [ 'FriendsWith' ], { active: true }) - * // -[:FriendsWith { active: true }]- - * - * relation('either', 'rel', 'FriendsWith', { active: true }, 3) - * // -[rel:FriendsWith*3 { active: true }]- - * - * relation('either', 'rel', 'FriendsWith', { active: true }, [ 3 ]) - * // -[rel:FriendsWith*3.. { active: true }]- - * - * relation('either', 'rel', 'FriendsWith', { active: true }, [ 3, 5 ]) - * // -[rel:FriendsWith*3..5 { active: true }]- - * - * relation('either', 'rel', 'FriendsWith', { active: true }, '*') - * // -[rel:FriendsWith* { active: true }]- - * ``` - * - * For more details on relation patterns see the cypher - * [docs]{@link - * https://neo4j.com/docs/developer-manual/current/cypher/syntax/patterns/#cypher-pattern-relationship}. - * - * @param dir Direction of the relation. `in` means to the left, `out` means to - * the right and `either` means no direction. - * @param {_.Many | _.Dictionary} name - * @param {_.Many | _.Dictionary} labels - * @param {_.Dictionary} conditions - * @param length Length of the relation for flexible length paths. Can be the - * string `'*'` to represent any length, a single number `3` to represent the - * maximum length of the path, or an array of two numbers which represent the - * minimum and maximum length of the path. When passing an array, the second - * number is optional, see the examples above. - * @returns {RelationPattern} An object representing the relation pattern. - */ - -/* tslint:disable:max-line-length */ - -function relation(dir, name, labels, conditions, length) { - return new RelationPattern(dir, name, labels, conditions, length); -} - -var Union = -/** @class */ -function (_super) { - __extends(Union, _super); - - function Union(all) { - if (all === void 0) { - all = false; - } - - var _this = _super.call(this) || this; - - _this.all = all; - return _this; - } - - Union.prototype.build = function () { - return "UNION" + (this.all ? ' ALL' : ''); - }; - - return Union; -}(Clause); - -/** - * @internal - */ - -var SetBlock = -/** @class */ -function () { - function SetBlock(chain, wrapper) { - this.chain = chain; - this.wrapper = wrapper; - } - /** - * Adds a [set]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/set} - * clause to the query. - * - * `set` lets you updates a nodes labels and properties in one clause. Most of - * the time it will be easier to use one of the variants such as `setLabels`, - * `setValues` or `setVariables`. - * - * This function accepts three different kind of properties, each of which is - * described in more detail in the variants. - * - * ``` - * query.set({ - * labels: { - * sale: 'Active', - * }, - * variables: { - * sale: { - * activatedAt: 'timestamp()', - * }, - * }, - * values: { - * sale: { - * activatedBy: user.id, - * }, - * }, - * }) - * // SET sale:Active, sale.activatedAt = timestamp(), sale.activatedBy = $userId - * ``` - * - * `set` also accepts an options object which currently only contains a - * single setting: `override`. Override controls whether the `=` or `+=` - * operator is used in the set clause. `true` causes the existing object to be - * cleared and replaced by the new object. `false` on the other hand will - * merge the existing and new objects together, with new properties replacing - * the ones on the existing object. - * The default value of override is a little inconsistent and it will be - * improved in the next major version. If you don't pass any settings object, - * override will default to `true`. If you pass an options object without an - * `override` key, override will be `false`. In future versions, override will - * always default to `false` to be more consistent with `setVariables` and - * `setValues`. - * - * @param {SetProperties} properties - * @param {SetOptions} options - * @returns {Q} - */ - - - SetBlock.prototype.set = function (properties, options) { - return this.chain(this.wrap(new Set$2(properties, options))); - }; - /** - * Adds labels to a node using a [set]{@link - * https://neo4j.com/docs/developer-manual/current/cypher/clauses/set} - * clause. - * - * ``` - * query.setLabels({ - * sale: 'Active', - * }) - * // SET sale:Active - * ``` - * - * `setLabels` accepts a dictionary where the keys are nodes to be updated - * and the value is a single label or an array of labels to add to the node. - * - * @param {_.Dictionary<_.Many>} labels - * @returns {Q} - */ - - - SetBlock.prototype.setLabels = function (labels) { - return this.chain(this.wrap(new Set$2({ - labels: labels - }))); - }; - /** - * Updates a node from parameters using a [set]{@link - * https://neo4j.com/docs/developer-manual/current/cypher/clauses/set} - * clause. This function treats all values as parameters which is different to - * `setVariables` which assumes values are cypher variables. - * - * ``` - * query.setValues({ - * 'sale.activatedBy': user.id, - * }) - * // SET sale.activatedBy += $userId - * ``` - * - * `setValues` accepts a dictionary where the keys are nodes or property names - * to be updated. - * - * To use the `+=` operator to merge properties of a node, you can pass - * `true` to the merge option. - * ``` - * query.setValues({ - * 'sale': { active: true }, - * }, true) - * // SET sale += $sale - * ``` - */ - - - SetBlock.prototype.setValues = function (values, merge) { - return this.chain(this.wrap(new Set$2({ - values: values - }, { - merge: merge - }))); - }; - /** - * Updates a node from a variable that was previously declared in the query - * using a [set]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/set} - * clause. This function only accepts strings as its values which are not - * escaped in any way so beware. If you want to store some user supplied - * information in the database, `setValues` is the function you want. - * - * ``` - * query.setVariables({ - * 'sale.activatedAt': 'timestamp()', - * }) - * // SET sale.activatedAt = timestamp() - * ``` - * Note how values are inserted into the query, as is. - * - * To use the `+=` operator to merge properties of a node, you can pass - * `true` to the merge option. - * ``` - * query.setVariables({ - * 'sale': 'newSaleDetails' - * }, true) - * // SET sale += newSaleDetails - * ``` - */ - - - SetBlock.prototype.setVariables = function (variables, merge) { - return this.chain(this.wrap(new Set$2({ - variables: variables - }, { - merge: merge - }))); - }; - - SetBlock.prototype.wrap = function (clause) { - return this.wrapper ? new this.wrapper(clause) : clause; - }; - - return SetBlock; -}(); -/** - * Root class for all query chains, namely the {@link Connection} and - * {@link Query} classes. - * @internal - */ - -var Builder = -/** @class */ -function (_super) { - __extends(Builder, _super); - - function Builder() { - var _this = _super.call(this, function (c) { - return _this.continueChainClause(c); - }) || this; - /** - * Used to add an `ON CREATE` clause to the query. Any following query will be prefixed with - * `ON CREATE`. - * - * Example: - * ```javascript - * query.onCreate.setLabels({ node: 'Active' }); - * // ON CREATE SET node:Active - * query.onCreate.setVariables({ 'node.createdAt': 'timestamp()' }); - * // ON CREATE SET node.createdAt = timestamp() - * ```` - * - * The only methods that are available after `onCreate` are the set family of clauses. - */ - - - _this.onCreate = new SetBlock(_this.continueChainClause.bind(_this), OnCreate); - /** - * Used to add an `ON MATCH` clause to the query. Any following query will be prefixed with - * `ON MATCH`. - * - * Example: - * ```javascript - * query.onMatch.setLabels({ node: 'Active' }); - * // ON MATCH SET node:Active - * query.onMatch.setVariables({ 'node.updatedAt': 'timestamp()' }); - * // ON MATCH SET node.createdAt = timestamp() - * ```` - * - * The only methods that are available after `onMatch` are the set family of clauses. - */ - - _this.onMatch = new SetBlock(_this.continueChainClause.bind(_this), OnMatch); - return _this; - } - /** - * Adds a [create]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/create} - * clause to the query. - * - * Create accepts a single pattern, a list of patterns or a list of a list of - * patterns. Each pattern represents a single part of a cypher pattern. For - * example: `(people:Person { age: 30 })` would be a node pattern and - * `-[:FriendsWith]->` would be a relationship pattern. - * - * If an array of patterns is provided, they are joined together to form a - * composite pattern. For example: - * ```javascript - * query.create([ - * node('people', 'Person', { age: 30 }), - * relation('out', '', 'FriendsWith'), - * node('friend', 'Friend'), - * ]) - * ``` - * - * Would equate to the cypher pattern - * ``` - * CREATE (people:Person { age: 30 })-[:FriendsWith]->(friend:Friend) - * ``` - * - * The create method also accepts a `unique` option which will cause a `CREATE UNIQUE` clause to - * be emitted instead. - * ```javascript - * query.create([node('people', 'Person', { age: 30 })], { unique: true }); - * // CREATE UNIQUE (people:Person { age: 30 }) - * ``` - */ - - - Builder.prototype.create = function (patterns, options) { - return this.continueChainClause(new Create(patterns, options)); - }; - /** - * Shorthand for `create(patterns, { unique: true })` - */ - - - Builder.prototype.createUnique = function (patterns) { - return this.create(patterns, { - unique: true - }); - }; - /** - * Shorthand for `create(node(name, labels, conditions), options)`. For more details - * the arguments see @{link node}. - */ - - - Builder.prototype.createNode = function (name, labels, conditions, options) { - var clause = new Create(new NodePattern(name, labels, conditions), options); - return this.continueChainClause(clause); - }; - /** - * Shorthand for `createNode(name, labels, conditions, { unique: true })` - */ - - - Builder.prototype.createUniqueNode = function (name, labels, conditions) { - return this.createNode(name, labels, conditions, { - unique: true - }); - }; - /** - * Adds a [delete]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/delete} - * clause to the query. - * - * Delete accepts a single string or an array of them and all of them are - * joined together with commas. *Note that these strings are not escaped or - * passed to Neo4j using parameters, therefore you should not pass user - * input into this clause without escaping it first*. - * - * You can set `detach: true` in the options to make it a `DETACH DELETE` - * clause. - * - * @param {_.Many} terms - * @param {DeleteOptions} options - * @returns {Q} - */ - - - Builder.prototype.delete = function (terms, options) { - return this.continueChainClause(new Delete(terms, options)); - }; - /** - * Shorthand for `delete(terms, { detach: true })`. - * - * @param {_.Many} terms - * @param {DeleteOptions} options - * @returns {Q} - */ - - - Builder.prototype.detachDelete = function (terms, options) { - if (options === void 0) { - options = {}; - } - - return this.continueChainClause(new Delete(terms, assign_1(options, { - detach: true - }))); - }; - /** - * Adds a [limit]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/limit} - * clause to the query. - * - * @param {string | number} amount - * @returns {Q} - */ - - - Builder.prototype.limit = function (amount) { - return this.continueChainClause(new Limit(amount)); - }; - /** - * Adds a [match]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/match} - * clause to the query. - * - * Match accepts a single pattern, a list of patterns or a list of a list of - * patterns. Each pattern represents a single part of a cypher pattern. For - * example: `(people:Person { age: 30 })` would be a node pattern and - * `-[:FriendsWith]->` would be a relationship pattern. - * - * If an array of patterns is provided, they are joined together to form a - * composite pattern. For example: - * ```javascript - * query.match([ - * node('people', 'Person', { age: 30 }), - * relation('out', '', 'FriendsWith'), - * node('friends'), - * ]) - * ``` - * - * Would equate to the cypher pattern - * ``` - * MATCH (people:Person { age: 30 })-[:FriendsWith]->(friends) - * ``` - * - * If an array of an array of patterns is provided each array is joined - * together like above, and then each composite pattern is joined with a comma - * to allow matching of multiple distinct patterns. Note: matching many - * distinct patterns will produce a cross product of the results as noted in - * the [cypher docs]{@link - * https://neo4j.com/developer/kb/cross-product-cypher-queries-will-not-perform-well/}. - * - * You can also provide `optional: true` in the options to create and - * `OPTIONAL MATCH` clause. - * - * @param {PatternCollection} patterns List of patterns to be matched. - * @param {MatchOptions} options - * @returns {Q} - */ - - - Builder.prototype.match = function (patterns, options) { - return this.continueChainClause(new Match(patterns, options)); - }; - /** - * Shorthand for `match(node(name, labels, conditions))`. For more details on - * the arguments see {@link node}. - * - * @param {_.Many | _.Dictionary} name - * @param {_.Many | _.Dictionary} labels - * @param {_.Dictionary} conditions - * @returns {Q} - */ - - - Builder.prototype.matchNode = function (name, labels, conditions) { - var clause = new Match(new NodePattern(name, labels, conditions)); - return this.continueChainClause(clause); - }; - /** - * Shorthand for `match(patterns, { optional: true })`. - * - * @param {PatternCollection} patterns - * @param {MatchOptions} options - * @returns {Q} - */ - - - Builder.prototype.optionalMatch = function (patterns, options) { - if (options === void 0) { - options = {}; - } - - return this.continueChainClause(new Match(patterns, assign_1(options, { - optional: true - }))); - }; - /** - * Adds a [merge]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/merge/} - * clause to the query. It accepts the same parameters as `match` and `create` so refer to them - * for more information. - * - * ```javascript - * query.merge([ - * node('user', 'User', { id: 1 }), - * relation('out', 'rel', 'OwnsProject'), - * node('project', 'Project', { id: 20 }), - * ]) - * .onMatch.setVariables({ 'rel.updatedAt': `timestamp` }); - * // MERGE (user:User { id: 1 })-[rel:OwnsProject]->(project:Project { id: 20 }) - * // ON MATCH SET rel.updatedAt = timestamp() - * ``` - */ - - - Builder.prototype.merge = function (patterns) { - return this.continueChainClause(new Merge(patterns)); - }; - /** - * Adds an [order by]{@link - * https://neo4j.com/docs/developer-manual/current/cypher/clauses/order-by} - * to the query. - * - * Pass a single string or an array of strings to order by. - * ```javascript - * query.orderBy([ - * 'name', - * 'occupation', - * ]) - * // ORDER BY name, occupation - * ``` - * - * You can control the sort direction by adding a direction to each property. - * ```javascript - * query.orderBy([ - * ['name', 'DESC'], - * 'occupation', // Same as ['occupation', 'ASC'] - * ]) - * // ORDER BY name DESC, occupation - * ``` - * - * The second parameter is the default search direction for all properties that - * don't have a direction specified. So the above query could instead be - * written as: - * ```javascript - * query.orderBy([ - * 'name', - * ['occupation', 'ASC'] - * ], 'DESC') - * // ORDER BY name DESC, occupation - * ``` - * - * It is also acceptable to pass an object where each key is the - * property and the value is a direction. Eg: - * ```javascript - * query.orderBy({ - * name: 'DESC', - * occupation: 'ASC', - * }) - * ``` - * However, the underlying iteration order is not always guaranteed and - * it may cause subtle bugs in your code. It is still accepted but it - * is recommended that you use the array syntax above. - * - * Valid values for directions are `DESC`, `DESCENDING`, `ASC`, `ASCENDING`. - * `true` and `false` are also accepted (`true` being the same as `DESC` and - * `false` the same as `ASC`), however they should be avoided as they are - * quite ambiguous. Directions always default to `ASC` as it does in cypher. - * - * @param {_.Many | OrderConstraints} fields - * @param {Direction} dir - * @returns {Q} - */ - - - Builder.prototype.orderBy = function (fields, dir) { - return this.continueChainClause(new OrderBy(fields, dir)); - }; - /** - * Adds a clause to the query as is. You can also provide an object of params - * as well. - * - * ```javascript - * query.raw('MATCH (:Event { date: $date }', { date: '2017-01-01' }) - * ``` - * - * `raw` can also be used as a template tag - * - * ```javascript - * query.matchNode('event', 'Event', { id: 1 }) - * .raw`SET event.finishedAt = ${Date.now()}` - * ``` - * - * But note that using template parameters where they are not supported in a query will produce - * an malformed query. - * - * ```javascript - * query.raw`SET node.${property} = 'value'` - * // Invalid query: - * // SET node.$param1 = 'value' - * ``` - * - * @param {string} clause - * @param args - * @returns {Q} - */ - - - Builder.prototype.raw = function (clause) { - var args = []; - - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - - return this.continueChainClause(new (Raw.bind.apply(Raw, __spreadArrays([void 0, clause], args)))()); - }; - /** - * Adds a [remove]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/remove/} - * clause to the query. - * - * Pass objects containing the list of properties and labels to remove from a node. Each key in an - * object is the name of a node and the values are the names of the labels and properties to - * remove. The values of each object can be either a single string, or an array of strings. - * ```javascript - * query.remove({ - * labels: { - * coupon: 'Active', - * }, - * properties: { - * customer: ['inactive', 'new'], - * }, - * }); - * // REMOVE coupon:Active, customer.inactive, customer.new - * ``` - * - * Both labels and properties objects are optional, but you must provide at least one of them for - * the query to be syntatically valid. - * ``` - * query.remove({ - * - * }); - * // Invalid query: - * // REMOVE - * ``` - * - * If you only need to remove labels *or* properties, you may find `removeProperties` or - * `removeLabels` more convenient. - */ - - - Builder.prototype.remove = function (properties) { - return this.continueChainClause(new Remove(properties)); - }; - /** - * Adds a [remove]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/remove/} - * clause to the query. - * - * Pass an object containing the list of properties to remove from a node. Each key in the - * object is the name of a node and the values are the names of the properties to remove. The - * values can be either a single string, or an array of strings. - * ```javascript - * query.remove({ - * customer: ['inactive', 'new'], - * coupon: 'available', - * }); - * // REMOVE customer.inactive, customer.new, coupon.available - * ``` - */ - - - Builder.prototype.removeProperties = function (properties) { - return this.continueChainClause(new Remove({ - properties: properties - })); - }; - /** - * Adds a [remove]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/remove/} - * clause to the query. - * - * Pass an object containing the list of labels to remove from a node. Each key in the - * object is the name of a node and the values are the names of the labels to remove. The - * values can be either a single string, or an array of strings. - * ```javascript - * query.remove({ - * customer: ['Inactive', 'New'], - * coupon: 'Available', - * }); - * // REMOVE customer:Inactive, customer:New, coupon:Available - * ``` - */ - - - Builder.prototype.removeLabels = function (labels) { - return this.continueChainClause(new Remove({ - labels: labels - })); - }; - /** - * Adds a [return]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/return} - * clause to the query. - * - * There are many different ways to pass arguments to `return` so each is - * documented in turn below. - * - * A single string: - * ```javascript - * query.return('people') - * // RETURN people - * ``` - * - * An array of strings to return multiple variables: - * ```javascript - * query.return([ 'people', 'pets' ]) - * // RETURN people, pets - * ``` - * - * A single object to rename variables: - * ```javascript - * query.return({ people: 'employees' }) - * // RETURN people AS employees - * ``` - * - * A single object with an array for each value: - * ```javascript - * query.return({ - * people: [ 'name', 'age' ], - * pets: [ 'name', 'breed' ], - * }) - * // RETURN people.name, people.age, pets.name, pets.breed - * ``` - * This gives you a shortcut to specifying many node properties. You can also - * rename each property by adding an object inside the array or by providing - * an object as the value: - * ```javascript - * query.return({ - * people: [{ name: 'personName' }, 'age' ], - * }) - * // RETURN people.name AS personName, people.age - * ``` - * or - * ```javascript - * query.return({ - * people: { - * name: 'personName', - * age: 'personAge', - * }, - * }) - * // RETURN people.name AS personName, people.age AS personAge - * ``` - * - * You can also pass an array of any of the above methods. - * - * The return method also accepts a `distinct` option which will cause a `RETURN DISTINCT` clause - * to be emitted instead. - * ```javascript - * query.return('people', { distinct: true }) - * // RETURN DISTINCT people - * ``` - */ - - - Builder.prototype.return = function (terms, options) { - return this.continueChainClause(new Return(terms, options)); - }; - /** - * Shorthand for `return(terms, { distinct: true }); - */ - - - Builder.prototype.returnDistinct = function (terms) { - return this.return(terms, { - distinct: true - }); - }; - /** - * Adds a [skip]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/skip} - * clause to the query. - * - * @param {string | number} amount - * @returns {Q} - */ - - - Builder.prototype.skip = function (amount) { - return this.continueChainClause(new Skip(amount)); - }; - /** - * Add a [union]{@link https://neo4j.com/docs/cypher-manual/current/clauses/union/} clause to the - * query. - * - * ```javascript - * query.matchNode('people', 'People') - * .return({ 'people.name': 'name' }) - * .union() - * .matchNode('departments', 'Department') - * .return({ 'departments.name': 'name' }); - * // MATCH (people:People) - * // RETURN people.name AS name - * // UNION - * // MATCH (departments:Department) - * // RETURN departments.name AS name - * ``` - */ - - - Builder.prototype.union = function (all) { - return this.continueChainClause(new Union(all)); - }; - /** - * Add a [union all]{@link https://neo4j.com/docs/cypher-manual/current/clauses/union/} clause to - * the query. Just shorthand for `union(true)`. - * - * ```javascript - * query.matchNode('people', 'People') - * .return({ 'people.name': 'name' }) - * .unionAll() - * .matchNode('departments', 'Department') - * .return({ 'departments.name': 'name' }); - * // MATCH (people:People) - * // RETURN people.name AS name - * // UNION ALL - * // MATCH (departments:Department) - * // RETURN departments.name AS name - * ``` - */ - - - Builder.prototype.unionAll = function () { - return this.continueChainClause(new Union(true)); - }; - /** - * Adds an [unwind]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/unwind} - * clause to the query. - * - * @param {any[]} list Any kind of array to unwind in the query - * @param {string} name Name of the variable to use in the unwinding - * @returns {Q} - */ - - - Builder.prototype.unwind = function (list, name) { - return this.continueChainClause(new Unwind(list, name)); - }; - /** - * Adds a [where]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/where} - * clause to the query. - * - * `where` is probably the most complex clause in this package because of the flexible ways to - * combine conditions. A handy rule of thumb is when you see an array it becomes an `OR` and when - * you see a dictionary, it becomes an `AND`. The many different ways of specifying your - * constraints are listed below. - * - * As a simple object, the comparison of each property is just `AND`ed together. - * ```javascript - * query.where({ - * name: 'Alan', - * age: 54, - * }) - * // WHERE name = 'Alan' AND age = 54 - * ``` - * - * You can wrap your constraints in a top level dictionary in which case the key of the outer - * dictionary will be considered the name of the node. - * ```javascript - * query.where({ - * person: { - * name: 'Alan', - * age: 54, - * }, - * }) - * // WHERE person.name = 'Alan' AND person.age = 54 - * ``` - * - * Using an array, you can generate `OR`ed conditions. - * ```javascript - * query.where([ - * { name: 'Alan' }, - * { age: 54 }, - * ]) - * // WHERE name = 'Alan' OR age = 54 - * ``` - * - * Arrays can be placed at many levels in the conditions. - * ```javascript - * query.where({ - * name: [ 'Alan', 'Steve', 'Bob' ], - * }) - * // WHERE name = 'Alan' OR name = 'Steve' OR name = 'Bob' - * - * query.where({ - * person: [ - * { name: 'Alan' }, - * { age: 54 }, - * ], - * }) - * // WHERE person.name = 'Alan' OR person.age = 54 - * - * query.where([ - * { employee: { name: 'Alan' } }, - * { department: { code: 765 } }, - * }) - * // WHERE employee.name = 'Alan' OR department.code = 765 - * ``` - * - * For more complex comparisons, you can use the comparator functions such as: - * ```javascript - * query.where({ - * age: greaterThan(30), - * }) - * // WHERE age > 30 - * ``` - * - * The full list of comparators currently supported are: - * - [between]{@link http://jamesfer.me/cypher-query-builder/globals.html#between} - * - [contains]{@link http://jamesfer.me/cypher-query-builder/globals.html#contains} - * - [endsWith]{@link http://jamesfer.me/cypher-query-builder/globals.html#endswith} - * - [equals]{@link http://jamesfer.me/cypher-query-builder/globals.html#equals} - * - [exists]{@link http://jamesfer.me/cypher-query-builder/globals.html#exists} - * - [greaterEqualTo]{@link http://jamesfer.me/cypher-query-builder/globals.html#greaterequalto} - * - [greaterThan]{@link http://jamesfer.me/cypher-query-builder/globals.html#greaterthan} - * - [hasLabel]{@link http://jamesfer.me/cypher-query-builder/globals.html#haslabel} - * - [inArray]{@link http://jamesfer.me/cypher-query-builder/globals.html#inarray} - * - [isNull]{@link http://jamesfer.me/cypher-query-builder/globals.html#isnull} - * - [lessEqualTo]{@link http://jamesfer.me/cypher-query-builder/globals.html#lessequalto} - * - [lessThan]{@link http://jamesfer.me/cypher-query-builder/globals.html#lessthan} - * - [regexp]{@link http://jamesfer.me/cypher-query-builder/globals.html#regexp} - * - [startsWith]{@link http://jamesfer.me/cypher-query-builder/globals.html#startswith} - * - * You can import the comparisons one at a time or all at once. - * ```javascript - * import { greaterThan, regexp } from 'cypher-query-builder'; - * // or - * import { comparisons } form 'cypher-query-builder'; - * ``` - * - * For convenience you can also pass a Javascript RegExp object as a value, - * which will then be converted into a string before it is passed to cypher. - * *However*, beware that the cypher regexp syntax is inherited from - * [java]{@link - * https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html}, - * and may have slight differences to the Javascript syntax. If you would - * prefer, you can use the `regexp` comparator and use strings instead of - * RegExp objects. For example, Javascript RegExp flags will not be - * preserved when sent to cypher. - * ```javascript - * query.where({ - * name: /[A-Z].*son/, - * }) - * // WHERE age =~ '[A-Z].*son' - * ``` - * - * All the binary operators including `xor` and `not` are available as well and can also be - * imported individually or all at once. - * ```javascript - * import { xor, and } from 'cypher-query-builder'; - * // or - * import { operators } form 'cypher-query-builder'; - * ``` - * - * The operators can be placed at any level of the query. - * ```javascript - * query.where({ - * age: xor([lessThan(12), greaterThan(65)]) - * }) - * // WHERE age < 12 XOR age > 65 - * ``` - * - * @param {AnyConditions} conditions - * @returns {Q} - */ - - - Builder.prototype.where = function (conditions) { - return this.continueChainClause(new Where(conditions)); - }; - /** - * Adds a [with]{@link https://neo4j.com/docs/developer-manual/current/cypher/clauses/with} - * clause to the query. - * - * There are many different ways to pass arguments to `with` so each is - * documented in turn below. - * - * A single string: - * ```javascript - * query.with('people') - * // WITH people - * ``` - * - * An array of strings to return multiple variables: - * ```javascript - * query.with([ 'people', 'pets' ]) - * // WITH people, pets - * ``` - * - * A single object to rename variables: - * ```javascript - * query.with({ people: 'employees' }) - * // WITH people AS employees - * ``` - * - * A single object with an array for each value: - * ```javascript - * query.with({ - * people: [ 'name', 'age' ], - * pets: [ 'name', 'breed' ], - * }) - * // WITH people.name, people.age, pets.name, pets.breed - * ``` - * This gives you a shortcut to specifying many node properties. You can also - * rename each property by adding an object inside the array or by providing - * an object as the value: - * ```javascript - * query.with({ - * people: [{ name: 'personName' }, 'age' ], - * }) - * // WITH people.name AS personName, people.age - * ``` - * or - * ```javascript - * query.with({ - * people: { - * name: 'personName', - * age: 'personAge', - * }, - * }) - * // WITH people.name AS personName, people.age AS personAge - * ``` - * - * You can also pass an array of any of the above methods. - * - * @param {_.Many} terms - * @returns {Q} - */ - - - Builder.prototype.with = function (terms) { - return this.continueChainClause(new With(terms)); - }; - - return Builder; -}(SetBlock); - -var Transformer = -/** @class */ -function () { - function Transformer() {} - - Transformer.prototype.transformRecords = function (records) { - var _this = this; - - return map_1(records, function (rec) { - return _this.transformRecord(rec); - }); - }; - - Transformer.prototype.transformRecord = function (record) { - var _this = this; - - return mapValues_1(record.toObject(), function (node) { - return _this.transformValue(node); - }); - }; - - Transformer.prototype.transformValue = function (value) { - var _this = this; - - if (this.isPlainValue(value)) { - return value; - } - - if (isArray_1(value)) { - return map_1(value, function (v) { - return _this.transformValue(v); - }); - } - - if (lib.isInt(value)) { - return this.convertInteger(value); - } - - if (this.isNode(value)) { - return this.transformNode(value); - } - - if (this.isRelation(value)) { - return this.transformRelation(value); - } - - if (typeof value === 'object') { - return mapValues_1(value, function (v) { - return _this.transformValue(v); - }); - } - - return null; - }; - - Transformer.prototype.isPlainValue = function (value) { - var type = typeof value; - return value == null || type === 'string' || type === 'boolean' || type === 'number'; - }; - - Transformer.prototype.isNode = function (node) { - return node !== null && typeof node === 'object' && !isArray_1(node) && node.identity && node.labels && node.properties; - }; - - Transformer.prototype.transformNode = function (node) { - return { - identity: lib.integer.toString(node.identity), - labels: node.labels, - properties: mapValues_1(node.properties, this.transformValue.bind(this)) - }; - }; - - Transformer.prototype.isRelation = function (rel) { - return rel.identity && rel.type && rel.properties && rel.start && rel.end; - }; - - Transformer.prototype.transformRelation = function (rel) { - return { - identity: lib.integer.toString(rel.identity), - start: lib.integer.toString(rel.start), - end: lib.integer.toString(rel.end), - label: rel.type, - properties: mapValues_1(rel.properties, this.transformValue.bind(this)) - }; - }; - - Transformer.prototype.convertInteger = function (num) { - if (lib.integer.inSafeRange(num)) { - return lib.integer.toNumber(num); - } - - return lib.integer.toString(num); - }; - - return Transformer; -}(); - -var ClauseCollection = -/** @class */ -function (_super) { - __extends(ClauseCollection, _super); - - function ClauseCollection() { - var _this = _super !== null && _super.apply(this, arguments) || this; - - _this.clauses = []; - return _this; - } - /** - * Returns all clauses in this collection. - * @returns {Clause[]} - */ - - - ClauseCollection.prototype.getClauses = function () { - return this.clauses; - }; - /** - * Adds a clause to the child list. - * @param {Clause} clause - */ - - - ClauseCollection.prototype.addClause = function (clause) { - clause.useParameterBag(this.parameterBag); - this.clauses.push(clause); - }; - /** - * @inheritDoc - */ - - - ClauseCollection.prototype.build = function () { - return map_1(this.clauses, function (s) { - return s.build(); - }).join('\n') + ";"; - }; - - return ClauseCollection; -}(Clause); - -var Query = -/** @class */ -function (_super) { - __extends(Query, _super); - /** - * Creates a new query with a given connection. - * - * @param {Connection} connection - */ - - - function Query(connection) { - if (connection === void 0) { - connection = null; - } - - var _this = _super.call(this) || this; - - _this.connection = connection; - _this.clauses = new ClauseCollection(); - return _this; - } - - Query.prototype.continueChainClause = function (clause) { - return this.addClause(clause); - }; - /** - * Runs this query on its connection. If this query was created by calling a - * chainable method of a connection, then its connection was automatically - * set. - * - * Returns a promise that resolves to an array of records. Each key of the - * record is the name of a variable that you specified in your `RETURN` - * clause. - * Eg: - * ```typescript - * connection.match([ - * node('steve', { name: 'Steve' }), - * relation('out', [ 'FriendsWith' ]), - * node('friends'), - * ]) - * .return([ 'steve', 'friends' ]) - * .run(); - * ``` - * - * Would result in the value: - * ``` - * [ - * { - * steve: { ... } // steve node, - * friends: { ... } // first friend, - * }, - * { - * steve: { ... } // steve node, - * friends: { ... } // second friend, - * }, - * { - * steve: { ... } // steve node, - * friends: { ... } // third friend, - * }, - * ] - * ``` - * - * Notice how the steve record is returned for each row, this is how cypher - * works. If you use lodash you can extract all of Steve's friends from the - * results like using `_.map(results, 'friends')`. If you don't, you can use - * ES2015/ES6: `results.map(record => record.friends)`. - * - * If you use typescript you can use the type parameter to hint at the type of - * the return value which is `Dictionary[]`. - * - * Throws an exception if this query does not have a connection or has no - * clauses. - * - * @returns {Promise[]>} - */ - - - Query.prototype.run = function () { - return __awaiter(this, void 0, Promise, function () { - return __generator(this, function (_a) { - if (!this.connection) { - throw new Error('Cannot run query; no connection object available.'); - } - - return [2 - /*return*/ - , this.connection.run(this)]; - }); - }); - }; - /** - * Runs this query on its connection. If this query was created by calling a - * chainable method of a connection, then its connection was automatically - * set. - * - * Returns an RxJS observable that emits each record as it is received from the - * database. This is the most efficient way of working with very large - * datasets. Each record is an object where each key is the name of a variable - * that you specified in your return clause. - * - * Eg: - * ```typescript - * const result$ = connection.match([ - * node('steve', { name: 'Steve' }), - * relation('out', [ 'FriendsWith' ]), - * node('friends'), - * ]) - * .return([ 'steve', 'friends' ]) - * .stream(); - * - * // Emits - * // { - * // steve: { ... } // steve node, - * // friends: { ... } // first friend, - * // }, - * // Then emits - * // { - * // steve: { ... } // steve node, - * // friends: { ... } // first friend, - * // }, - * // And so on - * ``` - * - * Notice how the steve record is returned for each row, this is how cypher - * works. You can extract all of steve's friends from the query by using RxJS - * operators: - * ``` - * const friends$ = results$.map(row => row.friends); - * ``` - * - * If you use typescript you can use the type parameter to hint at the type of - * the return value which is `Observable>`. - * - * Throws an exception if this query does not have a connection or has no - * clauses. - */ - - - Query.prototype.stream = function () { - if (!this.connection) { - return new Observable(function (subscriber) { - subscriber.error(new Error('Cannot run query; no connection object available.')); - }); - } - - return this.connection.stream(this); - }; - /** - * Runs the current query on its connection and returns the first result. - * If the query was created by calling a chainable method of a connection, - * the query's connection was automatically set. - * - * If 0 results were returned from the database, returns `undefined`. - * - * Returns a promise that resolves to a single record. Each key of the - * record is the name of a variable that you specified in your `RETURN` - * clause. - * - * If you use typescript you can use the type parameter to hint at the type of - * the return value which is `Dictionary`. Note that this function returns - * `undefined` if the result set was empty. - */ - - - Query.prototype.first = function () { - return this.run().then(function (results) { - return results && results.length > 0 ? results[0] : undefined; - }); - }; // Clause proxied methods - - /** - * Returns the query as a string with parameter variables. - * - * Eg: - * ```typescript - * connection.match([ - * node('steve', { name: 'Steve' }), - * relation('out', [ 'FriendsWith' ]), - * node('friends'), - * ]) - * .return([ 'steve', 'friends' ]) - * .build(); - * - * // MATCH (steve { name: $name })-[:FriendsWith]->(friends) - * // RETURN steve, friends - * ``` - * - * @returns {string} - */ - - - Query.prototype.build = function () { - return this.clauses.build(); - }; - /** - * Synonym for `build()`. - * @returns {string} - */ - - - Query.prototype.toString = function () { - return this.clauses.toString(); - }; - /** - * Returns an object that includes both the query and the params ready to be - * passed to the neo4j driver. - */ - - - Query.prototype.buildQueryObject = function () { - return this.clauses.buildQueryObject(); - }; - /** - * Like `build`, but will insert the values of the parameters into the string - * so queries are easier to debug. __Note: this should only ever be used for - * debugging__. - * - * ```typescript - * connection.match([ - * node('steve', { name: 'Steve' }), - * relation('out', [ 'FriendsWith' ]), - * node('friends'), - * ]) - * .return([ 'steve', 'friends' ]) - * .build(); - * - * // MATCH (steve { name: 'Steve' })-[:FriendsWith]->(friends) - * // RETURN steve, friends - * ``` - * - * @returns {string} - */ - - - Query.prototype.interpolate = function () { - return this.clauses.interpolate(); - }; - /** - * Returns an array of all the clauses in this query. - * @returns {Clause[]} - */ - - - Query.prototype.getClauses = function () { - return this.clauses.getClauses(); - }; - /** - * Adds a new clause to the query. You probably won't ever need to call this - * directly, but there is nothing stopping you. - * - * @param {Clause} clause - * @returns {this} - */ - - - Query.prototype.addClause = function (clause) { - this.clauses.addClause(clause); - return this; - }; - - return Query; -}(Builder); - -var connections = []; // Closes all open connections - -nodeCleanup(function () { - connections.forEach(function (con) { - return con.close(); - }); - connections = []; -}); - -function isCredentials(credentials) { - return 'username' in credentials && 'password' in credentials; -} // We have to correct the type of lodash's isFunction method because it doesn't correctly narrow -// union types such as the options parameter passed to the connection constructor. - - -var isTrueFunction = isFunction_1; // tslint:disable max-line-length - -/** - * The Connection class lets you access the Neo4j server and run queries against it. Under the hood, - * the Connection class uses the official Neo4j Nodejs driver which manages connection pooling on a - * [session basis]{@link https://neo4j.com/docs/api/javascript-driver/current/class/src/v1/driver.js~Driver.html#instance-method-session}. - * It should be enough to have a single Connection instance per database per application. - * - * To create the connection, simply call the - * [constructor]{@link https://jamesfer.me/cypher-query-builder/classes/connection.html#constructor} - * and pass in the database url, username and password. - * ``` - * const db = new Connection('bolt://localhost', { - * username: 'neo4j', - * password: 'password', - * }) - * ``` - * - * To use the connection, just start calling any of the clause methods such as `match`, `create` or - * `matchNode` etc. They automatically create a {@link Query} object that you can then chain other - * methods off of. - * ``` - * db.matchNode('people', 'Person') - * .where({ 'people.age': greaterThan(18) }) - * .return('people') - * .run() - * ``` - * - * You can also pass a query to the - * [run]{@link https://jamesfer.me/cypher-query-builder/classes/connection.html#run} method, - * however, this is probably much less convenient. - * ``` - * db.run( - * new Query().matchNode('people', 'Person') - * .where({ 'people.age': greaterThan(18) }) - * .return('people') - * .run() - * ); - * ``` - * - * Once you've finished with the connection you should close the connection. - * ``` - * db.close() - * ``` - * - * The library will attempt to clean up all connections when the process exits, but it is better to - * be explicit. - */ -// tslint:enable max-line-length - -/** @class */ -(function (_super) { - __extends(Connection, _super); - /** - * Creates a new connection to the database. - * - * @param url Url of the database such as `'bolt://localhost'` - * @param auth Auth can either be an object in the form `{ username: ..., password: ... }`, or a - * Neo4j AuthToken object which contains the `scheme`, `principal` and `credentials` properties - * for more advanced authentication scenarios. The AuthToken object is what is passed directly to - * the neo4j javascript driver so checkout their docs for more information on it. - * @param options Additional configuration options. If you provide a function instead of an - * object, it will be used as the driver constructor. While passing a driver constructor function - * here is not deprecated, it is the legacy way of setting it and you should prefer to pass an - * options object with the `driverConstructor` parameter. - * @param options.driverConstructor An optional driver constructor to use for - * this connection. Defaults to the official Neo4j driver. The constructor is - * given the url you pass to this constructor and an auth token that is - * generated from calling [`neo4j.auth.basic`]{@link - * https://neo4j.com/docs/api/javascript-driver/current#usage-examples}. - * @param options.driverConfig Neo4j options that are passed directly to the underlying driver. - */ - - - function Connection(url, auth$1, options) { - if (options === void 0) { - options = lib.driver; - } - - var _this = _super.call(this) || this; - - _this.url = url; - _this.transformer = new Transformer(); - _this.auth = isCredentials(auth$1) ? lib.auth.basic(auth$1.username, auth$1.password) : auth$1; - var driverConstructor = isTrueFunction(options) ? options : options.driverConstructor ? options.driverConstructor : lib.driver; - var driverConfig = isTrueFunction(options) || !options.driverConfig ? {} : options.driverConfig; - _this.options = { - driverConstructor: driverConstructor, - driverConfig: driverConfig - }; - _this.driver = driverConstructor(_this.url, _this.auth, _this.options.driverConfig); - _this.open = true; - connections.push(_this); - return _this; - } - /** - * Closes this connection if it is open. Closed connections cannot be - * reopened. - */ - - - Connection.prototype.close = function () { - return __awaiter(this, void 0, Promise, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - if (!this.open) return [3 - /*break*/ - , 2]; - return [4 - /*yield*/ - , this.driver.close()]; - - case 1: - _a.sent(); - - this.open = false; - _a.label = 2; - - case 2: - return [2 - /*return*/ - ]; - } - }); - }); - }; - /** - * Opens and returns a session. You should never need to use this directly. - * Your probably better off with `run` instead. - */ - - - Connection.prototype.session = function () { - if (this.open) { - return this.driver.session(); - } - - return null; - }; - /** - * Returns a new query that uses this connection. The methods such as `match` - * or `create` are probably more useful to you as they automatically create a - * new chainable query for you. - * @return {Query} - */ - - - Connection.prototype.query = function () { - return new Query(this); - }; - - Connection.prototype.continueChainClause = function (clause) { - return this.query().addClause(clause); - }; - /** - * Runs the provided query on this connection, regardless of which connection - * the query was created from. Each query is run on it's own session. - * - * Run returns a promise that resolves to an array of records. Each key of the - * record is the name of a variable that you specified in your `RETURN` - * clause. - * Eg: - * ```typescript - * connection.match([ - * node('steve', { name: 'Steve' }), - * relation('out', [ 'FriendsWith' ]), - * node('friends'), - * ]) - * .return([ 'steve', 'friends' ]) - * .run(); - * ``` - * - * Would result in the value: - * ``` - * [ - * { - * steve: { ... } // steve node, - * friends: { ... } // first friend, - * }, - * { - * steve: { ... } // steve node, - * friends: { ... } // second friend, - * }, - * { - * steve: { ... } // steve node, - * friends: { ... } // third friend, - * }, - * ] - * ``` - * - * Notice how the steve record is returned for each row, this is how cypher - * works. If you use lodash you can extract all of Steve's friends from the - * results like using `_.map(results, 'friends')`. If you don't, you can use - * ES2015/ES6: `results.map(record => record.friends)`. - * - * If you use typescript you can use the type parameter to hint at the type of - * the return value which is `Dictionary[]`. - * - * Throws an exception if this connection is not open or there are no clauses - * in the query. - * - * @param {Query} query - * @returns {Promise[]>} - */ - - - Connection.prototype.run = function (query) { - return __awaiter(this, void 0, Promise, function () { - var session, queryObj; - - var _this = this; - - return __generator(this, function (_a) { - if (!this.open) { - throw new Error('Cannot run query; connection is not open.'); - } - - if (query.getClauses().length === 0) { - throw new Error('Cannot run query: no clauses attached to the query.'); - } - - session = this.session(); - - if (!session) { - throw new Error('Cannot run query: connection is not open.'); - } - - queryObj = query.buildQueryObject(); - return [2 - /*return*/ - , session.run(queryObj.query, queryObj.params).then(function (_a) { - var records = _a.records; - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_b) { - switch (_b.label) { - case 0: - return [4 - /*yield*/ - , session.close()]; - - case 1: - _b.sent(); - - return [2 - /*return*/ - , this.transformer.transformRecords(records)]; - } - }); - }); - }, function (error) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 - /*yield*/ - , session.close()]; - - case 1: - _a.sent(); - - throw error; - } - }); - }); - })]; - }); - }); - }; - /** - * Runs the provided query on this connection, regardless of which connection - * the query was created from. Each query is run on it's own session. - * - * Returns an RxJS observable that emits each record as it is received from the - * database. This is the most efficient way of working with very large - * datasets. Each record is an object where each key is the name of a variable - * that you specified in your return clause. - * - * Eg: - * ```typescript - * const results$ = connection.match([ - * node('steve', { name: 'Steve' }), - * relation('out', [ 'FriendsWith' ]), - * node('friends'), - * ]) - * .return([ 'steve', 'friends' ]) - * .stream(); - * - * // Emits - * // { - * // steve: { ... } // steve node, - * // friends: { ... } // first friend, - * // }, - * // Then emits - * // { - * // steve: { ... } // steve node, - * // friends: { ... } // first friend, - * // }, - * // And so on - * ``` - * - * Notice how the steve record is returned for each row, this is how cypher - * works. You can extract all of steve's friends from the query by using - * operators: - * ``` - * const friends$ = results$.map(row => row.friends); - * ``` - * - * If you use typescript you can use the type parameter to hint at the type of - * the return value which is `Dictionary`. - * - * Throws an exception if this connection is not open or there are no clauses - * in the query. - * - * The query is run when you call stream so you should subscribe to the results - * immediately to prevent missing any data. - * - * Due to the way the Neo4j javascript driver works, once you call stream there - * is no way to stop the query until it is complete. Even if you unsubscribe from - * the observable, all the remaining rows will still be parsed by the driver but - * then immediately discarded. - * ```typescript - * const results$ = connection.matchNode('records') - * .return('records') - * .limit(1000) // 1000 records will be loaded and parsed from the database - * .stream() - * .take(10) // even though you only take the first 10 - * .subscribe(record => {}); - * ``` - * In practice this should never happen unless you're doing some strange things. - */ - - - Connection.prototype.stream = function (query) { - var _this = this; - - return new Observable(function (subscriber) { - if (!_this.open) { - subscriber.error(new Error('Cannot run query: connection is not open.')); - return; - } - - if (query.getClauses().length === 0) { - subscriber.error(new Error('Cannot run query: no clauses attached to the query.')); - return; - } - - var session = _this.session(); - - if (!session) { - subscriber.error(new Error('Cannot run query: connection is not open.')); - return; - } // Run the query - - - var queryObj = query.buildQueryObject(); - var result = session.run(queryObj.query, queryObj.params); // Subscribe to the result and clean up the session - // Note: Neo4j observables use a different subscribe syntax to RxJS observables - - result.subscribe({ - onNext: function (record) { - if (!subscriber.closed) { - subscriber.next(_this.transformer.transformRecord(record)); - } - }, - onError: function (error) { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 - /*yield*/ - , session.close()]; - - case 1: - _a.sent(); - - if (!subscriber.closed) { - subscriber.error(error); - } - - return [2 - /*return*/ - ]; - } - }); - }); - }, - onCompleted: function () { - return __awaiter(_this, void 0, void 0, function () { - return __generator(this, function (_a) { - switch (_a.label) { - case 0: - return [4 - /*yield*/ - , session.close()]; - - case 1: - _a.sent(); - - if (!subscriber.closed) { - subscriber.complete(); - } - - return [2 - /*return*/ - ]; - } - }); - }); - } - }); - }); - }; - - return Connection; -})(Builder); - -// Ensures synchronous execution of queries to prevent problems with race conditions on Neo4j. -// Problem: Is it thread-safe? Probably right, because js is single-threaded? -class SyncQueue { - constructor(toBind) { - this.callbackQueue = []; - this.activeCallback = null; - this.toBind = toBind; - } - async execute(callback, ...data) { - this.callbackQueue.push([callback, data]); - if (this.callbackQueue.length === 1 && this.activeCallback === null) { - // On empty queue, make active and assume responsibility of handling the queue. - while (this.callbackQueue.length > 0) { - const nextEvent = this.callbackQueue.shift(); - this.activeCallback = nextEvent[0]; - console.log('starting callback'); - await this.activeCallback.call(this.toBind, ...nextEvent[1]); - console.log('ending callback'); - } - this.activeCallback = null; - console.log('exiting execute'); - } - } -} - -const CAT_DANGLING = 'dangling'; -const CORE_STORE_ID = 'core'; -class VizId { - constructor(id, storeId) { - this.id = id; - this.storeId = storeId; - } - toString() { - return `${this.storeId}:${this.id}`; - } - toId() { - return this.toString(); - } - static fromId(id) { - const split = id.split(':'); - const storeId = split[0]; - const _id = split.slice(1).join(':'); - return new VizId(_id, storeId); - } - static fromNode(node) { - return VizId.fromId(node.id()); - } - static fromNodes(nodes) { - return nodes.map((n) => VizId.fromNode(n)); - } - static fromFile(file) { - return new VizId(file.name, 'core'); - } - static toId(id, storeId) { - return new VizId(id, storeId).toId(); - } -} -const _parseTags = function (tags) { - return [].concat(...tags - .map((tag) => { - tag = tag.slice(1); - const hSplit = tag.split('/'); - const tags = []; - for (const i in hSplit) { - const hTag = hSplit.slice(0, parseInt(i) + 1).join('-'); - tags.push(`tag-${hTag}`); - } - return tags; - })); -}; -const getClasses = function (file, metadataCache) { - if (file) { - const classes = []; - if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'svg', 'tiff'].contains(file.extension)) { - classes.push('image'); - } - else if (['mp3', 'webm', 'wav', 'm4a', 'ogg', '3gp', 'flac'].contains(file.extension)) { - classes.push('audio'); - } - else if (['mp4', 'webm', 'ogv'].contains(file.extension)) { - classes.push('video'); - } - else if (file.extension === 'pdf') { - classes.push('pdf'); - } - // This is replaced by the 'path' data attribute. - // if (!(file.parent.name === '/' || file.parent.name === '')) { - // classes.push(`folder-${file.parent.name - // .replace(' ', '_')}`); - // } else { - // classes.push('root'); - // } - if (file.extension === 'md') { - classes.push('note'); - const cache = metadataCache.getFileCache(file); - if (cache?.frontmatter) { - if ('image' in cache.frontmatter) { - classes.push('image'); - } - if ('tags' in cache.frontmatter) { - const tags = obsidian.parseFrontMatterTags(cache.frontmatter); - if (tags) { - classes.push(..._parseTags(tags)); - } - } - if ('cssclass' in cache.frontmatter) { - const clazzes = obsidian.parseFrontMatterStringArray(cache.frontmatter, 'cssclass'); - if (clazzes) { - classes.push(...clazzes); - } - } - } - if (cache?.tags) { - classes.push(..._parseTags(cache.tags.map((t) => t.tag))); - } - } - else { - classes.push('file'); - } - return classes; - } - return [CAT_DANGLING]; -}; -const nodeFromFile = async function (file, plugin) { - const cache = plugin.app.metadataCache.getFileCache(file); - const name = file.extension === 'md' ? file.basename : file.name; - const classes = getClasses(file, plugin.app.metadataCache).join(' '); - const data = { - id: VizId.toId(file.name, CORE_STORE_ID), - name: name, - path: file.path, - }; - if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'svg', 'tiff'].contains(file.extension)) { - try { - // @ts-ignore - data['resource_url'] = `http://localhost:${plugin.settings.imgServerPort}/${encodeURI(file.path)}`; - } - catch { } - } - if (file.extension == 'md') { - data['content'] = await plugin.app.vault.cachedRead(file); - } - const frontmatter = cache?.frontmatter; - if (frontmatter) { - Object.keys(frontmatter).forEach((k) => { - if (!(k === 'position')) { - if (k === 'image') { - const imageField = frontmatter[k]; - try { - // Check if url. throws error otherwise - new URL(imageField); - data[k] = imageField; - } - catch { - try { - // @ts-ignore - data[k] = `http://localhost:${plugin.settings.imgServerPort}/${encodeURI(imageField)}`; - } - catch { } - } - } - else { - data[k] = frontmatter[k]; - } - } - }); - } - return { - group: 'nodes', - data: data, - classes: classes, - }; -}; -const nodeDangling = function (path) { - return { - group: 'nodes', - data: { - id: VizId.toId(path, CORE_STORE_ID), - name: path, - }, - classes: 'dangling', - }; -}; - -const CAT_DANGLING$1 = 'SMD_dangling'; -const nameRegex = '[^\\W\\d]\\w*'; -// Match around [[ and ]], and ensure content isn't a wikilnk closure -// This doesn't explicitly parse aliases. -const wikilinkRegex = '\\[\\[([^\\]\\r\\n]+?)\\]\\]'; -class QueryMetadata { - constructor() { - this.nodeIndex = 0; - this.nodeVars = {}; - } - nextNodeVar(name, prefix = 'n') { - const varName = `${prefix}${this.nodeIndex.toString()}`; - this.nodeVars[name] = varName; - this.nodeIndex += 1; - return varName; - } - values() { - return Object.keys(this.nodeVars).map((k) => this.nodeVars[k]); - } -} -class Neo4jStream extends obsidian.Component { - constructor(plugin) { - super(); - this.plugin = plugin; - this.workspace = plugin.app.workspace; - this.vault = plugin.app.vault; - this.settings = plugin.settings; - this.metadataCache = plugin.app.metadataCache; - this.eventQueue = new SyncQueue(this); - } - async start() { - if (this.driver) { - await this.driver.close(); - } - this.driver = neo4j.driver('neo4j://localhost', neo4j.auth.basic('neo4j', this.settings.password), { - maxTransactionRetryTime: 30000, - }); - const connection = this.session(); - if (this.settings.debug) { - console.log('Removing existing data'); - } - // await this.connection.run("MATCH (n) RETURN n LIMIT 10").then(res => { - // console.log(res); - // }); - await this.executeQueries([new Query() - .matchNode('n', { SMD_vault: this.vault.getName() }) - .detachDelete('n')]); - console.log('Iterating md files'); - // let noteQueries: Query[] = []; - const markdownFiles = this.vault.getMarkdownFiles(); - let query = new Query(); - const queryMetadata = new QueryMetadata(); - for (const file of markdownFiles) { - queryMetadata.nextNodeVar(file.basename); - query = await this.queryCreateNote(file, query, queryMetadata); - } - for (const file of markdownFiles) { - await this.queryCreateRels(file, query, queryMetadata); - } - console.log('Pushing to Neo4j'); - await this.executeQueries([query], connection); - // TODO: Define schema/indexes - new obsidian.Notice('Neo4j stream online!'); - this.plugin.statusBar.setText('Neo4j stream online'); - await connection.close(); - } - session() { - return this.driver.session(); - } - async createNode(file, name) { - let nodeDef = null; - if (file) { - nodeDef = await nodeFromFile(file, this.plugin); - } - else { - nodeDef = nodeDangling(name); - } - nodeDef.data.vault = this.vault.getName(); - nodeDef.data.obsidian_url = `obsidian://open?vault=${encodeURIComponent(this.vault.getName())}&file=${encodeURIComponent(nodeDef.data.name)}`; - // @ts-ignore - const labels = nodeDef.classes.replaceAll('-', '_').split(' '); - return { - labels: labels, - properties: nodeDef.data, - }; - } - runQuery(query, session = null) { - let newSess = false; - if (session === null) { - newSess = true; - session = this.driver.session(); - } - const queryO = query.buildQueryObject(); - if (this.settings.debug) { - console.log(queryO); - } - const q = session.run(queryO.query, queryO.params); - if (newSess) { - q.subscribe({ - async onCompleted(summary) { - await session.close(); - }, - }); - } - return q; - } - async executeQueries(queries, session = null) { - for (const query of queries) { - // Note: The await here is important, as a connection cannot run multiple transactions simultaneously. - await this.runQuery(query, session).then((value) => { - if (this.settings.debug) { - console.log(value); - } - }).catch((reason) => { - console.log('Query failed'); - console.log(query.buildQueryObject()); - console.log(reason); - }); - } - } - node(varName, name) { - return node$1(varName, { name: name, vault: this.vault.getName() }); - } - async queryUpdateNote(file, query, queryMetadata) { - return this.queryCreateOrUpdateNote(file, query, queryMetadata, true); - } - async queryCreateNote(file, query, queryMetadata) { - return this.queryCreateOrUpdateNote(file, query, queryMetadata, false); - } - async queryCreateOrUpdateNote(file, query, queryMetadata, update) { - const nodeDef = await this.createNode(file, file.name); - if (nodeDef) { - const nodeVar = queryMetadata.nodeVars[file.basename]; - if (update) { - return query.set({ - labels: { - [nodeVar]: nodeDef.labels, - }, - values: { - [nodeVar]: nodeDef.properties, - }, - }, { - merge: false, - }); - } - else { - return query.createNode(nodeVar, nodeDef.labels, nodeDef.properties); - } - } - console.log('File without metadata'); - console.log(file); - return null; - } - regexEscape(str) { - return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'); - } - parseTypedLink(link, line) { - // TODO: This is something specific I use, but shouldn't keep being in this repo. - const regexPublishedIn = new RegExp(`^${this.regexEscape(this.settings.typedLinkPrefix)} (publishedIn) (\\d\\d\\d\\d) (${wikilinkRegex},? *)+$`); - const matchPI = regexPublishedIn.exec(line); - if (!(matchPI === null)) { - return { - type: 'publishedIn', - isInline: false, - properties: { - year: matchPI[2], - context: '', - type: 'publishedIn', - }, - class: 'publishedIn', - }; - } - // Intuition: Start with the typed link prefix. Then a neo4j name (nameRegex). - // Then one or more of the wikilink group: wikilink regex separated by optional comma and multiple spaces - const regex = new RegExp(`^${this.regexEscape(this.settings.typedLinkPrefix)} (${nameRegex}) (${wikilinkRegex},? *)+$`); - const match = regex.exec(line); - if (!(match === null)) { - return { - type: match[1], - isInline: false, - properties: { - context: '', - type: match[1], - }, - class: match[1], - }; - } - return null; - } - async queryCreateRels(file, query, queryMetadata, merge = false) { - const metadata = this.metadataCache.getFileCache(file); - const content = (await this.vault.cachedRead(file)).split('\n'); - const srcVar = queryMetadata.nodeVars[file.basename]; - if (metadata) { - const links = metadata.links; - if (links === undefined) { - return query; - } - for (const link of links) { - let baseName = obsidian.getLinkpath(link.link); // - // Returns NULL for dangling notes! - const trgtFile = this.metadataCache.getFirstLinkpathDest(baseName, file.path); - if (trgtFile) { - // This is an existing object. - baseName = trgtFile.basename; - } - let trgtVar; - if (baseName in queryMetadata.nodeVars) { - trgtVar = queryMetadata.nodeVars[baseName]; - } - else if (trgtFile && merge) { - // When merging, there's likely no var created for this note yet. - trgtVar = queryMetadata.nextNodeVar(baseName); - query = query.match(this.node(trgtVar, baseName)); - } - else { - // This node hasn't been seen before, so we need to create it. - // Creates dangling nodes if untyped, otherwise creates attachment nodes - trgtVar = queryMetadata.nextNodeVar(baseName); - const nodeDef = await this.createNode(trgtFile, baseName); - if (merge) { - query = query.merge(node$1(trgtVar, nodeDef.labels, nodeDef.properties)); - } - else { - query = query.createNode(trgtVar, nodeDef.labels, nodeDef.properties); - } - } - const line = content[link.position.start.line]; - let typedLink = this.parseTypedLink(link, line); - if (typedLink === null) { - typedLink = { - class: 'inline', - isInline: true, - properties: { - context: line, - type: '', - }, - }; - } - query = query.create([ - node$1(srcVar), - relation('out', [typedLink.class], typedLink.properties), - node$1(trgtVar) - ]); - if (merge) { - query.with(queryMetadata.values()); - } - } - return query; - } - console.log('File without metadata'); - console.log(file); - return null; - } - async metadataCacheOnChanged(file) { - // It's always called after the respective other events. - // Note: This is NOT called on rename, unless there's a reflexive link to itself. - // When a file is created, this is fired with an empty filecache. We synchronize the event firing, - // so we let the create callback handle the creation of the node. - console.log('changed metadata'); - console.log(file); - const session = this.session(); - if (file instanceof obsidian.TFile) { - const name = file.basename; - const queryMetadata = new QueryMetadata(); - const nodeVar = 'n0'; - // Find all labels on node - const result = await this.runQuery(new Query().match(this.node(nodeVar, name)).return(nodeVar), session); - const oldLabels = result.records[0].get(0).labels; - if (oldLabels.length > 0) { - console.log(oldLabels); - // Remove all labels on node - await this.runQuery(new Query().match(this.node(nodeVar, name)) - // @ts-ignore - .removeLabels({ n0: oldLabels }), session); - } - queryMetadata.nodeIndex = 1; - queryMetadata.nodeVars[name] = nodeVar; - let query = new Query().match(this.node(nodeVar, name)); - // Update node with new info - query = await this.queryUpdateNote(file, query, queryMetadata); - await this.executeQueries([query], session); - // Delete all outgoing edges: - const dRelQuery = new Query().match([ - this.node(nodeVar, name), - relation('out', 'r'), node$1('plc') - ]) - .delete('r'); - await this.executeQueries([dRelQuery]); - // Recreate relations, taking into account any changes - const relQuery = await this.queryCreateRels(file, new Query().match(this.node(nodeVar, name)), queryMetadata, true); - await this.executeQueries([relQuery.return(nodeVar)], session); - } - await session.close(); - } - async vaultOnRename(file, oldPath) { - // This is called BEFORE metadataCache vault change. - // So if we just rename the neo4j node, it should be fine when rebuilding relations. But rebuilding relations - // should happen before the rename event is resolved... Hopefully it works async - console.log('onRename'); - if (file instanceof obsidian.TFile) { - const oldName = path.basename(oldPath, '.md'); - console.log(oldName); - const query = new Query().match(this.node('n', oldName)) - .setValues({ n: { name: file.basename } }, true); - await this.executeQueries([query]); - } - this.lastFileEvent = 'rename'; - } - async vaultOnModify(file) { - // Called BEFORE metadataCache changed event. - // At this point, the metadataCache HASN'T been updated yet! - // It shouldn't be needed to do anything related with relation/tag updating here. - // At most, we could update the content property of the node. - this.lastFileEvent = 'modify'; - console.log('onModify'); - } - async vaultOnDelete(file) { - // After deleting, no metadatacache changed event is fired. - // Note: MetadataCache event isn't called either for incoming edges - this.lastFileEvent = 'delete'; - console.log('onDelete'); - const session = this.session(); - if (file instanceof obsidian.TFile) { - const name = file.basename; - const result = await this.runQuery(new Query().match([ - this.node('n', name), - relation('in'), - node$1('m') - ]).return('n'), session); - console.log(result); - if (result.records.length === 0) { - // If there are no incoming links, detach delete the node - await this.executeQueries([ - new Query().match(this.node('n', name)) - .detachDelete('n') - ], session); - } - else { - // If there are any incoming links, change labels to dangling and empty properties - const result = await this.runQuery(new Query() - .match(this.node('n', name)).return('n'), session); - // return query.setValues({}).removeLabels(dict); - let query = new Query().match(this.node('n', name)); - const oldLabels = result.records[0].get(0).labels; - if (oldLabels.length > 0) { - query = query.removeLabels({ n: oldLabels }); - } - query = query.setLabels({ n: CAT_DANGLING$1 }) - .setValues({ - SMD_vault: this.vault.getName(), - name: name, - }, false); - await this.executeQueries([query], session); - } - } - await session.close(); - } - async vaultOnCreate(file) { - // This is called BEFORE metadataCache vault change. - // Create the node as a blank state, then fill in later with on metadatacache changed etc. - // Note: it's possible the node already exists as a dangling node. In that case, just do nothing - // and let the metadatacache event handle it - this.lastFileEvent = 'create'; - console.log('onCreate'); - const session = this.session(); - console.log('sess created'); - if (file instanceof obsidian.TFile) { - const name = file.basename; - const result = await this.runQuery(new Query().match(this.node('n', name)) - .return('n'), session); - console.log(result); - if (result.records.length == 0) { - // if not exists: - await this.executeQueries([new Query().create(this.node('n', name))], session); - } - } - } - async stop() { - await this.driver.close(); - } -} - -const DefaultNeo4jStreamSettings = { - password: '', - typedLinkPrefix: '-', - neo4jServerPort: 7687, - server: 'localhost', - indexContent: true, - debug: false, -}; -class Neo4jStreamSettingsTab extends obsidian.PluginSettingTab { - constructor(app, plugin) { - super(app, plugin); - this.plugin = plugin; - } - display() { - const { containerEl } = this; - containerEl.empty(); - containerEl.createEl('h3'); - containerEl.createEl('h3', { text: 'Neo4j Stream' }); - const doc_link = document.createElement('a'); - doc_link.href = 'https://juggl.io'; - doc_link.target = '_blank'; - doc_link.innerHTML = 'the documentation'; - const discord_link = document.createElement('a'); - discord_link.href = 'https://discord.gg/sAmSGpaPgM'; - discord_link.target = '_blank'; - discord_link.innerHTML = 'the Discord server'; - const introPar = document.createElement('p'); - introPar.innerHTML = - 'Check out ' + doc_link.outerHTML + ' for documentation on how to use the plugin.
' + - 'Join ' + discord_link.outerHTML + ' for help, nice discussion and insight into development.'; - containerEl.appendChild(introPar); - new obsidian.Setting(containerEl) - .setName('Neo4j server') - .setDesc('Set the Neo4j server to use. Default localhost.') - .addText((text) => { - text.setValue(this.plugin.settings.server + '') - .setPlaceholder('localhost') - .onChange((new_value) => { - this.plugin.settings.server = new_value.trim(); - this.plugin.saveData(this.plugin.settings); - }); - }); - new obsidian.Setting(containerEl) - .setName('Neo4j server port') - .setDesc('Set the port of the Neo4j server. Default 7687.') - .addText((text) => { - text.setValue(this.plugin.settings.neo4jServerPort + '') - .setPlaceholder('7687') - .onChange((new_value) => { - this.plugin.settings.neo4jServerPort = parseInt(new_value.trim()); - this.plugin.saveData(this.plugin.settings); - }); - }); - new obsidian.Setting(containerEl) - .setName('Neo4j database password') - .setDesc('The password of your neo4j graph database. WARNING: This is stored in plaintext in your vault. ' + - 'Don\'t use sensitive passwords here!') - .addText((text) => { - text.setPlaceholder('') - .setValue(this.plugin.settings.password) - .onChange((newFolder) => { - this.plugin.settings.password = newFolder; - this.plugin.saveData(this.plugin.settings); - }).inputEl.setAttribute('type', 'password'); - }); - new obsidian.Setting(containerEl) - .setName('Index note content') - .setDesc('This will full-text index the content of notes. ' + - 'This allows searching within notes using the Neo4j Bloom search bar. However, it could decrease performance.') - .addToggle((toggle) => { - toggle.setValue(this.plugin.settings.indexContent) - .onChange((new_value) => { - this.plugin.settings.indexContent = new_value; - this.plugin.saveData(this.plugin.settings); - }); - }); - new obsidian.Setting(containerEl) - .setName('Typed links prefix') - .setDesc('Prefix to use for typed links. Default is \'-\'. Requires a server restart.') - .addText((text) => { - text.setPlaceholder('') - .setValue(this.plugin.settings.typedLinkPrefix) - .onChange((new_folder) => { - this.plugin.settings.typedLinkPrefix = new_folder; - this.plugin.saveData(this.plugin.settings); - }); - }); - new obsidian.Setting(containerEl) - .setName('Debug') - .setDesc('Enable debug mode, which prints a lot of stuff in the developers console.') - .addToggle((toggle) => { - toggle.setValue(this.plugin.settings.debug) - .onChange((new_value) => { - this.plugin.settings.debug = new_value; - this.plugin.saveData(this.plugin.settings); - }); - }); - } -} - -const STATUS_OFFLINE = 'Neo4j stream offline'; - -class Neo4jPlugin extends obsidian.Plugin { - async onload() { - super.onload(); - console.log('Loading Neo4j stream'); - this.settings = Object.assign({}, DefaultNeo4jStreamSettings, await this.loadData()); - this.vault = this.app.vault; - this.metadata = this.app.metadataCache; - this.statusBar = this.addStatusBarItem(); - this.statusBar.setText(STATUS_OFFLINE); - this.neo4jStream = new Neo4jStream(this); - this.addChild(this.neo4jStream); - this.addCommand({ - id: 'restart-stream', - name: 'Restart Neo4j stream', - callback: () => { - console.log('Restarting stream'); - this.neo4jStream.stop(); - this.neo4jStream.start(); - }, - }); - this.addCommand({ - id: 'stop-stream', - name: 'Stop Neo4j stream', - callback: () => { - this.neo4jStream.stop(); - }, - }); - // this.addCommand({ - // id: 'open-bloom-link', - // name: 'Open note in Neo4j Bloom', - // callback: () => { - // if (!this.stream_process) { - // new Notice("Cannot open in Neo4j Bloom as neo4j stream is not active.") - // } - // let active_view = this.app.workspace.getActiveViewOfType(MarkdownView); - // if (active_view == null) { - // return; - // } - // let name = active_view.getDisplayText(); - // // active_view.getState(). - // - // console.log(encodeURI("neo4j://graphapps/neo4j-bloom?search=SMD_no_tags with name " + name)); - // open(encodeURI("neo4j://graphapps/neo4j-bloom?search=SMD_no_tags with name " + name)); - // // require("electron").shell.openExternal("www.google.com"); - // }, - // }); - this.addSettingTab(new Neo4jStreamSettingsTab(this.app, this)); - this.app.workspace.onLayoutReady(() => { - this.neo4jStream.start(); - }); - } - // nodeCypher(label: string): string { - // return 'MATCH (n) WHERE n.name="' + label + - // '" AND n.' + PROP_VAULT + '="' + this.app.vault.getName() + - // '" RETURN n'; - // } - // - // localNeighborhoodCypher(label:string): string { - // return 'MATCH (n {name: "' + label + - // '", ' + PROP_VAULT + ':"' + this.app.vault.getName() + - // '"}) OPTIONAL MATCH (n)-[r]-(m) RETURN n,r,m'; - // } - // executeQuery() { - // // Code taken from https://github.com/mrjackphil/obsidian-text-expand/blob/0.6.4/main.ts - // const currentView = this.app.workspace.activeLeaf.view; - // - // if (!(currentView instanceof MarkdownView)) { - // return; - // } - // - // const cmDoc = currentView.sourceMode.cmEditor; - // const curNum = cmDoc.getCursor().line; - // const query = this.getContentBetweenLines(curNum, '```cypher', '```', cmDoc); - // if (query.length > 0) { - // const leaf = this.app.workspace.splitActiveLeaf(this.settings.splitDirection); - // try { - // // TODO: Pass query. - // // const neovisView = new NeoVisView((leaf, this, name, [new ObsidianStore(this)]); - // // leaf.open(neovisView); - // } catch (e) { - // if (e instanceof Neo4jError) { - // new Notice('Invalid cypher query. Check console for more info.'); - // } else { - // throw e; - // } - // } - // } - // } - async onunload() { - super.onunload(); - console.log('Unloading Neo4j stream'); - } -} - -module.exports = Neo4jPlugin; From 4e3997ee4f00f1715650f13caf27cc45bb532375 Mon Sep 17 00:00:00 2001 From: Emile Date: Thu, 30 Sep 2021 11:46:05 +0200 Subject: [PATCH 3/8] Removed .obsidian --- .obsidian/app.json | 4 -- .obsidian/appearance.json | 3 -- .obsidian/core-plugins.json | 14 ----- .obsidian/hotkeys.json | 1 - .obsidian/workspace | 102 ------------------------------------ 5 files changed, 124 deletions(-) delete mode 100644 .obsidian/app.json delete mode 100644 .obsidian/appearance.json delete mode 100644 .obsidian/core-plugins.json delete mode 100644 .obsidian/hotkeys.json delete mode 100644 .obsidian/workspace diff --git a/.obsidian/app.json b/.obsidian/app.json deleted file mode 100644 index 4d49ab3..0000000 --- a/.obsidian/app.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "promptDelete": false, - "alwaysUpdateLinks": true -} \ No newline at end of file diff --git a/.obsidian/appearance.json b/.obsidian/appearance.json deleted file mode 100644 index 990f337..0000000 --- a/.obsidian/appearance.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "baseFontSize": 16 -} \ No newline at end of file diff --git a/.obsidian/core-plugins.json b/.obsidian/core-plugins.json deleted file mode 100644 index 26bc70e..0000000 --- a/.obsidian/core-plugins.json +++ /dev/null @@ -1,14 +0,0 @@ -[ - "file-explorer", - "global-search", - "switcher", - "graph", - "backlink", - "page-preview", - "note-composer", - "command-palette", - "markdown-importer", - "word-count", - "open-with-default-app", - "file-recovery" -] \ No newline at end of file diff --git a/.obsidian/hotkeys.json b/.obsidian/hotkeys.json deleted file mode 100644 index 9e26dfe..0000000 --- a/.obsidian/hotkeys.json +++ /dev/null @@ -1 +0,0 @@ -{} \ No newline at end of file diff --git a/.obsidian/workspace b/.obsidian/workspace deleted file mode 100644 index 7a717f1..0000000 --- a/.obsidian/workspace +++ /dev/null @@ -1,102 +0,0 @@ -{ - "main": { - "id": "d13b041b8342f362", - "type": "split", - "children": [ - { - "id": "f115cb69bdb5c6c8", - "type": "leaf", - "state": { - "type": "markdown", - "state": { - "file": "docs/Neo4j Stream/Install Neo4j Stream Plugin.md", - "mode": "source" - } - } - } - ], - "direction": "vertical" - }, - "left": { - "id": "93bfacddf0364031", - "type": "split", - "children": [ - { - "id": "5b4877b1c8bd0811", - "type": "tabs", - "children": [ - { - "id": "2e5f52a1b8eb32e4", - "type": "leaf", - "state": { - "type": "file-explorer", - "state": {} - } - }, - { - "id": "e4fcc2a575d3634d", - "type": "leaf", - "state": { - "type": "search", - "state": { - "query": "", - "matchingCase": false, - "explainSearch": false, - "collapseAll": false, - "extraContext": false, - "sortOrder": "alphabetical" - } - } - } - ] - } - ], - "direction": "horizontal", - "width": 300 - }, - "right": { - "id": "7f3a0fb38d3bb8d3", - "type": "split", - "children": [ - { - "id": "2bff59fdb21c113b", - "type": "tabs", - "children": [ - { - "id": "8f597588ddd527d6", - "type": "leaf", - "state": { - "type": "backlink", - "state": { - "file": "docs/Neo4j Stream/Install Neo4j Stream Plugin.md", - "collapseAll": false, - "extraContext": false, - "sortOrder": "alphabetical", - "showSearch": false, - "searchQuery": "", - "backlinkCollapsed": false, - "unlinkedCollapsed": true - } - } - } - ] - } - ], - "direction": "horizontal", - "width": 300, - "collapsed": true - }, - "active": "f115cb69bdb5c6c8", - "lastOpenFiles": [ - "docs/Neo4j Stream/Install Neo4j Stream Plugin.md", - "docs/Neo4j Stream/Neo4j graph visualizations.md", - "docs/Neo4j Stream/Neo4j Stream Plugin.md", - "docs/Neo4j Stream/Installation of Neo4j Stream Plugin.md", - "docs/files/Pasted image 20201231181103.png", - "docs/files/Pasted image 20201231180930.png", - "Obsidian.md", - "Neo4j Graph View settings.md", - "docs/files/Pasted image 20201231175530.png", - "docs/Archieved/Installation of Neo4j Graph View Plugin.md" - ] -} \ No newline at end of file From a0811ea8993ce993a13332cff5a5bcc2747402ee Mon Sep 17 00:00:00 2001 From: Emile Date: Thu, 30 Sep 2021 11:52:09 +0200 Subject: [PATCH 4/8] Improved writing --- docs/{Archieved => Archived}/Edge styling.md | 0 .../Installation of Neo4j Graph View Plugin.md | 0 docs/{Archieved => Archived}/Neo4j Graph View Plugin.md | 0 docs/{Archieved => Archived}/Neo4j graph visualizations.md | 0 docs/{Archieved => Archived}/Node styling.md | 0 .../Semantic Markdown Converter Semantics.md | 0 docs/{Archieved => Archived}/Semantic Markdown Converter.md | 0 .../{Archieved => Archived}/Semantic Obsidian edge styling.md | 0 .../{Archieved => Archived}/Semantic Obsidian node styling.md | 0 docs/{Archieved => Archived}/Using the Neo4j Graph View.md | 0 ...Stream Plugin.md => Installing the Neo4j Stream Plugin.md} | 2 +- docs/Neo4j Stream/Neo4j Stream Plugin.md | 4 ++-- docs/Neo4j Stream/Neo4j graph visualizations.md | 2 +- 13 files changed, 4 insertions(+), 4 deletions(-) rename docs/{Archieved => Archived}/Edge styling.md (100%) rename docs/{Archieved => Archived}/Installation of Neo4j Graph View Plugin.md (100%) rename docs/{Archieved => Archived}/Neo4j Graph View Plugin.md (100%) rename docs/{Archieved => Archived}/Neo4j graph visualizations.md (100%) rename docs/{Archieved => Archived}/Node styling.md (100%) rename docs/{Archieved => Archived}/Semantic Markdown Converter Semantics.md (100%) rename docs/{Archieved => Archived}/Semantic Markdown Converter.md (100%) rename docs/{Archieved => Archived}/Semantic Obsidian edge styling.md (100%) rename docs/{Archieved => Archived}/Semantic Obsidian node styling.md (100%) rename docs/{Archieved => Archived}/Using the Neo4j Graph View.md (100%) rename docs/Neo4j Stream/{Install Neo4j Stream Plugin.md => Installing the Neo4j Stream Plugin.md} (99%) diff --git a/docs/Archieved/Edge styling.md b/docs/Archived/Edge styling.md similarity index 100% rename from docs/Archieved/Edge styling.md rename to docs/Archived/Edge styling.md diff --git a/docs/Archieved/Installation of Neo4j Graph View Plugin.md b/docs/Archived/Installation of Neo4j Graph View Plugin.md similarity index 100% rename from docs/Archieved/Installation of Neo4j Graph View Plugin.md rename to docs/Archived/Installation of Neo4j Graph View Plugin.md diff --git a/docs/Archieved/Neo4j Graph View Plugin.md b/docs/Archived/Neo4j Graph View Plugin.md similarity index 100% rename from docs/Archieved/Neo4j Graph View Plugin.md rename to docs/Archived/Neo4j Graph View Plugin.md diff --git a/docs/Archieved/Neo4j graph visualizations.md b/docs/Archived/Neo4j graph visualizations.md similarity index 100% rename from docs/Archieved/Neo4j graph visualizations.md rename to docs/Archived/Neo4j graph visualizations.md diff --git a/docs/Archieved/Node styling.md b/docs/Archived/Node styling.md similarity index 100% rename from docs/Archieved/Node styling.md rename to docs/Archived/Node styling.md diff --git a/docs/Archieved/Semantic Markdown Converter Semantics.md b/docs/Archived/Semantic Markdown Converter Semantics.md similarity index 100% rename from docs/Archieved/Semantic Markdown Converter Semantics.md rename to docs/Archived/Semantic Markdown Converter Semantics.md diff --git a/docs/Archieved/Semantic Markdown Converter.md b/docs/Archived/Semantic Markdown Converter.md similarity index 100% rename from docs/Archieved/Semantic Markdown Converter.md rename to docs/Archived/Semantic Markdown Converter.md diff --git a/docs/Archieved/Semantic Obsidian edge styling.md b/docs/Archived/Semantic Obsidian edge styling.md similarity index 100% rename from docs/Archieved/Semantic Obsidian edge styling.md rename to docs/Archived/Semantic Obsidian edge styling.md diff --git a/docs/Archieved/Semantic Obsidian node styling.md b/docs/Archived/Semantic Obsidian node styling.md similarity index 100% rename from docs/Archieved/Semantic Obsidian node styling.md rename to docs/Archived/Semantic Obsidian node styling.md diff --git a/docs/Archieved/Using the Neo4j Graph View.md b/docs/Archived/Using the Neo4j Graph View.md similarity index 100% rename from docs/Archieved/Using the Neo4j Graph View.md rename to docs/Archived/Using the Neo4j Graph View.md diff --git a/docs/Neo4j Stream/Install Neo4j Stream Plugin.md b/docs/Neo4j Stream/Installing the Neo4j Stream Plugin.md similarity index 99% rename from docs/Neo4j Stream/Install Neo4j Stream Plugin.md rename to docs/Neo4j Stream/Installing the Neo4j Stream Plugin.md index ae8ce85..e088844 100644 --- a/docs/Neo4j Stream/Install Neo4j Stream Plugin.md +++ b/docs/Neo4j Stream/Installing the Neo4j Stream Plugin.md @@ -42,7 +42,7 @@ Every now and then, the Graph database fails to start. ## 3. Installing the Obsidian plugin Time to install the plugin! Since Neo4j Stream is unfinished, you will have to download and install it manually. -1. Download the plugin from [this link](https://github.com/HEmile/obsidian-neo4j-graph-view/releases/tag/0.2.5). +1. Download the plugin from [this link](https://github.com/HEmile/obsidian-neo4j-stream/releases). 1. Open the Obsidian settings, and go to Third-party plugins. Disable the "Safe mode" toggle, then click "Turn off safe mode" to confirm this. 2. Now, more options appear. Click on the "open plugin folders" icon 3. In the resulting folder, create a new directory called `neo4j-stream` diff --git a/docs/Neo4j Stream/Neo4j Stream Plugin.md b/docs/Neo4j Stream/Neo4j Stream Plugin.md index 368a129..9734a17 100644 --- a/docs/Neo4j Stream/Neo4j Stream Plugin.md +++ b/docs/Neo4j Stream/Neo4j Stream Plugin.md @@ -1,6 +1,6 @@ -This plugin helps streaming your vault to a [Neo4j](https://neo4j.com/) database. This is a separate plugin to ensure non-advanced users of [[Juggl]] will not have to deal with installing Neo4j, and is completely optional for advanced users. +This plugin helps by streaming your vault to a [Neo4j](https://neo4j.com/) database. This is a separate plugin to ensure non-advanced users of [[Juggl]] will not have to deal with installing Neo4j, and is completely optional for advanced users. -⚠ Note: This is an unfinshed pluggin. Absolutely no guarantees that this works. +⚠ Note: This is an unfinshed pluggin. Absolutely no guarantees are given that this works. Please refer to [[Install Neo4j Stream Plugin]] and [[Neo4j graph visualizations]] for more information diff --git a/docs/Neo4j Stream/Neo4j graph visualizations.md b/docs/Neo4j Stream/Neo4j graph visualizations.md index 0326c0b..eb0e2ef 100644 --- a/docs/Neo4j Stream/Neo4j graph visualizations.md +++ b/docs/Neo4j Stream/Neo4j graph visualizations.md @@ -2,7 +2,7 @@ aliases: [] --- -Another use case for the [[Neo4j Stream Plugin]] is to use your Obsidian vault in one of the many apps in the [[Neo4j Desktop]] +The main use case for the [[Neo4j Stream Plugin]] is to use your Obsidian vault in one of the many apps in the [[Neo4j Desktop]] Graph Apps Store. Using with this plugin active will automatically connect it to your vault. Here are some suggestions: ### Neo4j Bloom From 01edb54c676a0e2f009f3d5fc7c9d48bd6438023 Mon Sep 17 00:00:00 2001 From: Emile Date: Thu, 30 Sep 2021 11:53:25 +0200 Subject: [PATCH 5/8] Update Roadmap.md --- docs/Roadmap.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/Roadmap.md b/docs/Roadmap.md index c9bb183..226a965 100644 --- a/docs/Roadmap.md +++ b/docs/Roadmap.md @@ -6,7 +6,8 @@ aliases: [] # Juggl ## Planned ### [[Neo4j Stream]] -Allow for [[Cypher]] querying in [[Juggl]] ^2d1fd7 +Export your vault to [[Neo4j]]. +Later on, this will allow for [[Cypher]] querying in [[Juggl]] ^2d1fd7 ### [[Link Types]] From e2bca2fd28d1cfeb5e6ec5895f531f6e0ffc4636 Mon Sep 17 00:00:00 2001 From: Emile Date: Thu, 30 Sep 2021 11:54:23 +0200 Subject: [PATCH 6/8] Removed empty files --- Neo4j Graph View settings.md | 0 Neo4j Graph View.md | 0 Neo4j.md | 0 Obsidian.md | 0 Roadmap^.md | 0 5 files changed, 0 insertions(+), 0 deletions(-) delete mode 100644 Neo4j Graph View settings.md delete mode 100644 Neo4j Graph View.md delete mode 100644 Neo4j.md delete mode 100644 Obsidian.md delete mode 100644 Roadmap^.md diff --git a/Neo4j Graph View settings.md b/Neo4j Graph View settings.md deleted file mode 100644 index e69de29..0000000 diff --git a/Neo4j Graph View.md b/Neo4j Graph View.md deleted file mode 100644 index e69de29..0000000 diff --git a/Neo4j.md b/Neo4j.md deleted file mode 100644 index e69de29..0000000 diff --git a/Obsidian.md b/Obsidian.md deleted file mode 100644 index e69de29..0000000 diff --git a/Roadmap^.md b/Roadmap^.md deleted file mode 100644 index e69de29..0000000 From 1c37840ee71bae0f2b53579b06a38b6aec265a22 Mon Sep 17 00:00:00 2001 From: Emile Date: Thu, 30 Sep 2021 11:55:36 +0200 Subject: [PATCH 7/8] Readded text --- docs/Features/Styling/CSS Styling.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs/Features/Styling/CSS Styling.md b/docs/Features/Styling/CSS Styling.md index 37b919a..9c4f4af 100644 --- a/docs/Features/Styling/CSS Styling.md +++ b/docs/Features/Styling/CSS Styling.md @@ -153,6 +153,11 @@ edge.inline { ![[Pasted image 20210414182140.png|400]] +# Current limitations + +- CSS variables like `var(--background-primary)` will not be recognized. If this is something you need, please add a pull request. + +- `not()` does not seem to work. --- #feature From 6d32cdd96889ea4d5ab6f979692930fdb540db20 Mon Sep 17 00:00:00 2001 From: Emile Date: Thu, 30 Sep 2021 11:56:06 +0200 Subject: [PATCH 8/8] Delete manifest.json --- docs/Neo4j Stream/manifest.json | 10 ---------- 1 file changed, 10 deletions(-) delete mode 100644 docs/Neo4j Stream/manifest.json diff --git a/docs/Neo4j Stream/manifest.json b/docs/Neo4j Stream/manifest.json deleted file mode 100644 index ec5dc0c..0000000 --- a/docs/Neo4j Stream/manifest.json +++ /dev/null @@ -1,10 +0,0 @@ -{ - "id": "neo4j-stream", - "name": "Neoj Stream", - "version": "0.0.1", - "minAppVersion": "0.11.5", - "description": "Adds a completely interactive, stylable and expandable graph view to Obsidian.", - "author": "Emile", - "authorUrl": "https://twitter.com/emilevankrieken", - "isDesktopOnly": true -}