@neo4j-labs/experimental-query-api-wrapper
Advanced tools
Comparing version
@@ -17,3 +17,2 @@ /** | ||
*/ | ||
// tag::code[] | ||
import neo4j from '@neo4j-labs/experimental-query-api-wrapper' | ||
@@ -37,2 +36,1 @@ | ||
} | ||
// end::code[] |
@@ -149,6 +149,5 @@ /* | ||
// The glob patterns Jest uses to detect test files | ||
// testMatch: [ | ||
// "**/__tests__/**/*.[jt]s?(x)", | ||
// "**/?(*.)+(spec|test).[tj]s?(x)" | ||
// ], | ||
testMatch: [ | ||
"**/test/unit/**/?(*.)+(spec|test).[tj]s?(x)" | ||
], | ||
@@ -155,0 +154,0 @@ // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped |
@@ -1,57 +0,1 @@ | ||
"use strict"; | ||
var __extends = (this && this.__extends) || (function () { | ||
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); | ||
}; | ||
return function (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 __()); | ||
}; | ||
})(); | ||
var __awaiter = (this && this.__awaiter) || function (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()); | ||
}); | ||
}; | ||
var __generator = (this && this.__generator) || function (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 (g && (g = 0, op[0] && (_ = 0)), _) 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 }; | ||
} | ||
}; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
/** | ||
@@ -73,56 +17,51 @@ * Copyright (c) "Neo4j" | ||
*/ | ||
var neo4j_driver_core_1 = require("neo4j-driver-core"); | ||
var connection_http_1 = __importDefault(require("./connection.http")); | ||
var HttpConnectionProvider = /** @class */ (function (_super) { | ||
__extends(HttpConnectionProvider, _super); | ||
function HttpConnectionProvider(config) { | ||
var _this = _super.call(this) || this; | ||
_this._id = config.id; | ||
_this._log = config.log; | ||
_this._address = config.address; | ||
_this._scheme = config.scheme; | ||
_this._authTokenManager = config.authTokenManager; | ||
_this._config = config.config; | ||
return _this; | ||
import { ConnectionProvider, ServerInfo } from "neo4j-driver-core"; | ||
import HttpConnection from "./connection.http"; | ||
export default class HttpConnectionProvider extends ConnectionProvider { | ||
constructor(config) { | ||
super(); | ||
this._id = config.id; | ||
this._log = config.log; | ||
this._address = config.address; | ||
this._scheme = config.scheme; | ||
this._authTokenManager = config.authTokenManager; | ||
this._config = config.config; | ||
} | ||
HttpConnectionProvider.prototype.acquireConnection = function (param) { | ||
var _a, _b; | ||
return __awaiter(this, void 0, void 0, function () { | ||
var auth, _c; | ||
var _this = this; | ||
return __generator(this, function (_d) { | ||
switch (_d.label) { | ||
case 0: | ||
if (!((_a = param === null || param === void 0 ? void 0 : param.auth) !== null && _a !== void 0)) return [3 /*break*/, 1]; | ||
_c = _a; | ||
return [3 /*break*/, 3]; | ||
case 1: return [4 /*yield*/, this._authTokenManager.getToken()]; | ||
case 2: | ||
_c = _d.sent(); | ||
_d.label = 3; | ||
case 3: | ||
auth = _c; | ||
return [2 /*return*/, new connection_http_1.default({ release: function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { | ||
return [2 /*return*/, console.log('release')]; | ||
}); }); }, auth: auth, address: this._address, database: ((_b = param === null || param === void 0 ? void 0 : param.database) !== null && _b !== void 0 ? _b : 'neo4j'), scheme: this._scheme, config: this._config })]; | ||
async acquireConnection(param) { | ||
if (this._queryEndpoint == null) { | ||
if (this._discoveryPromise == null) { | ||
this._discoveryPromise = HttpConnection.discover({ address: this._address, scheme: this._scheme }); | ||
} | ||
const discoveryResult = await this._discoveryPromise; | ||
this._queryEndpoint = discoveryResult.query; | ||
} | ||
const auth = param?.auth ?? await this._authTokenManager.getToken(); | ||
return new HttpConnection({ | ||
release: async () => { }, | ||
auth, | ||
address: this._address, | ||
queryEndpoint: this._queryEndpoint, | ||
config: this._config, | ||
logger: this._log, | ||
errorHandler: (error) => { | ||
if (error == null || typeof error.code !== 'string' || !error.code.startsWith('Neo.ClientError.Security.') || param?.auth != null) { | ||
return error; | ||
} | ||
}); | ||
const handled = this._authTokenManager.handleSecurityException(auth, error.code); | ||
if (handled) { | ||
error.retriable = true; | ||
} | ||
return error; | ||
} | ||
}); | ||
}; | ||
HttpConnectionProvider.prototype.verifyConnectivityAndGetServerInfo = function (param) { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/, new neo4j_driver_core_1.ServerInfo({}, 5.0)]; | ||
}); | ||
}); | ||
}; | ||
HttpConnectionProvider.prototype.close = function () { | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_a) { | ||
return [2 /*return*/]; | ||
}); | ||
}); | ||
}; | ||
return HttpConnectionProvider; | ||
}(neo4j_driver_core_1.ConnectionProvider)); | ||
exports.default = HttpConnectionProvider; | ||
} | ||
async verifyConnectivityAndGetServerInfo(param) { | ||
const discoveryInfo = await HttpConnection.discover({ scheme: this._scheme, address: this._address }); | ||
return new ServerInfo({ | ||
address: this._address, | ||
version: discoveryInfo.version | ||
}, parseFloat(discoveryInfo.version)); | ||
} | ||
async close() { | ||
} | ||
} |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
/** | ||
@@ -18,97 +17,28 @@ * Copyright (c) "Neo4j" | ||
*/ | ||
var __extends = (this && this.__extends) || (function () { | ||
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); | ||
}; | ||
return function (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 __()); | ||
}; | ||
})(); | ||
var __awaiter = (this && this.__awaiter) || function (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()); | ||
}); | ||
}; | ||
var __generator = (this && this.__generator) || function (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 (g && (g = 0, op[0] && (_ = 0)), _) 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 }; | ||
import { Connection, newError } from "neo4j-driver-core"; | ||
import { ResultStreamObserver } from "./stream-observers"; | ||
import { QueryRequestCodec, QueryResponseCodec } from "./query.codec"; | ||
let currentId = 0; | ||
export default class HttpConnection extends Connection { | ||
constructor(config) { | ||
super(); | ||
this._id = currentId++; | ||
this._release = config.release; | ||
this._auth = config.auth; | ||
this._queryEndpoint = config.queryEndpoint; | ||
this._config = config.config; | ||
this._log = config.logger; | ||
this._errorHandler = config.errorHandler; | ||
} | ||
}; | ||
var __read = (this && this.__read) || function (o, n) { | ||
var m = typeof Symbol === "function" && o[Symbol.iterator]; | ||
if (!m) return o; | ||
var i = m.call(o), r, ar = [], e; | ||
try { | ||
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); | ||
} | ||
catch (error) { e = { error: error }; } | ||
finally { | ||
try { | ||
if (r && !r.done && (m = i["return"])) m.call(i); | ||
} | ||
finally { if (e) throw e.error; } | ||
} | ||
return ar; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var neo4j_driver_core_1 = require("neo4j-driver-core"); | ||
var stream_observers_1 = require("./stream-observers"); | ||
var query_codec_1 = require("./query.codec"); | ||
var HttpConnection = /** @class */ (function (_super) { | ||
__extends(HttpConnection, _super); | ||
function HttpConnection(config) { | ||
var _this = _super.call(this) || this; | ||
_this._release = config.release; | ||
_this._auth = config.auth; | ||
_this._scheme = config.scheme; | ||
_this._address = config.address; | ||
_this._database = config.database; | ||
_this._config = config.config; | ||
return _this; | ||
} | ||
HttpConnection.prototype.run = function (query, parameters, config) { | ||
var _this = this; | ||
var _a, _b; | ||
var observer = new stream_observers_1.ResultStreamObserver({ | ||
highRecordWatermark: (_a = config === null || config === void 0 ? void 0 : config.highRecordWatermark) !== null && _a !== void 0 ? _a : Number.MAX_SAFE_INTEGER, | ||
lowRecordWatermark: (_b = config === null || config === void 0 ? void 0 : config.lowRecordWatermark) !== null && _b !== void 0 ? _b : Number.MIN_SAFE_INTEGER, | ||
afterComplete: config === null || config === void 0 ? void 0 : config.afterComplete, | ||
server: this._address | ||
run(query, parameters, config) { | ||
const observer = new ResultStreamObserver({ | ||
highRecordWatermark: config?.highRecordWatermark ?? Number.MAX_SAFE_INTEGER, | ||
lowRecordWatermark: config?.lowRecordWatermark ?? Number.MIN_SAFE_INTEGER, | ||
afterComplete: config?.afterComplete, | ||
server: this._address, | ||
}); | ||
var requestCodec = new query_codec_1.QueryRequestCodec(this._auth, query, parameters, config); | ||
const requestCodec = QueryRequestCodec.of(this._auth, query, parameters, config); | ||
this._abortController = new AbortController(); | ||
fetch(this._getTransactionApi(), { | ||
const request = { | ||
url: this._getTransactionApi(config?.database), | ||
method: 'POST', | ||
@@ -123,94 +53,88 @@ mode: 'cors', | ||
body: JSON.stringify(requestCodec.body) | ||
}). | ||
then(function (res) { return __awaiter(_this, void 0, void 0, function () { | ||
var _a; | ||
return __generator(this, function (_b) { | ||
switch (_b.label) { | ||
case 0: | ||
_a = [res.headers.get('content-type')]; | ||
return [4 /*yield*/, res.json()]; | ||
case 1: return [2 /*return*/, _a.concat([(_b.sent())])]; | ||
}; | ||
this._log?.debug(`${this} REQUEST: ${JSON.stringify(request)} `); | ||
fetch(request.url, request). | ||
then(async (res) => { | ||
return [res.headers.get('content-type'), (await res.json())]; | ||
}) | ||
.catch(this._handleAndReThrown.bind(this)) | ||
.catch((error) => observer.onError(error)) | ||
.then(async ([contentType, rawQueryResponse]) => { | ||
if (rawQueryResponse == null) { | ||
// is already dead | ||
return; | ||
} | ||
this._log?.debug(`${this} ${JSON.stringify(rawQueryResponse)}`); | ||
const batchSize = config?.fetchSize ?? Number.MAX_SAFE_INTEGER; | ||
const codec = QueryResponseCodec.of(this._config, contentType, rawQueryResponse); | ||
if (codec.error) { | ||
throw codec.error; | ||
} | ||
observer.onKeys(codec.keys); | ||
const stream = codec.stream(); | ||
while (!observer.completed) { | ||
if (observer.paused) { | ||
await new Promise((resolve) => setTimeout(resolve, 20)); | ||
continue; | ||
} | ||
}); | ||
}); }) | ||
.catch(function (error) { return observer.onError(error); }) | ||
.then(function (_a) { | ||
var _b = __read(_a, 2), contentType = _b[0], rawQueryResponse = _b[1]; | ||
return __awaiter(_this, void 0, void 0, function () { | ||
var batchSize, codec, stream, iterate, i, _c, done, rawRecord; | ||
var _d; | ||
return __generator(this, function (_e) { | ||
switch (_e.label) { | ||
case 0: | ||
console.log(JSON.stringify(rawQueryResponse, undefined, 4)); | ||
if (rawQueryResponse == null) { | ||
// is already dead | ||
return [2 /*return*/]; | ||
} | ||
batchSize = (_d = config === null || config === void 0 ? void 0 : config.fetchSize) !== null && _d !== void 0 ? _d : Number.MAX_SAFE_INTEGER; | ||
codec = new query_codec_1.QueryResponseCodec(this._config, contentType, rawQueryResponse); | ||
if (codec.hasError) { | ||
throw codec.error; | ||
} | ||
observer.onKeys(codec.keys); | ||
stream = codec.stream(); | ||
_e.label = 1; | ||
case 1: | ||
if (!!observer.completed) return [3 /*break*/, 4]; | ||
if (!observer.paused) return [3 /*break*/, 3]; | ||
return [4 /*yield*/, new Promise(function (resolve) { return setTimeout(resolve, 20); })]; | ||
case 2: | ||
_e.sent(); | ||
return [3 /*break*/, 1]; | ||
case 3: | ||
iterate = true; | ||
for (i = 0; iterate && !observer.paused && i < batchSize; i++) { | ||
_c = stream.next(), done = _c.done, rawRecord = _c.value; | ||
if (!done) { | ||
observer.onNext(rawRecord); | ||
} | ||
else { | ||
iterate = false; | ||
observer.onCompleted(codec.meta); | ||
} | ||
} | ||
return [3 /*break*/, 1]; | ||
case 4: return [2 /*return*/]; | ||
for (let i = 0; !observer.paused && i < batchSize && !observer.completed; i++) { | ||
const { done, value: rawRecord } = stream.next(); | ||
if (!done) { | ||
observer.onNext(rawRecord); | ||
} | ||
}); | ||
}); | ||
else { | ||
observer.onCompleted(codec.meta); | ||
} | ||
} | ||
} | ||
observer.onCompleted(codec.meta); | ||
}) | ||
.catch(function (error) { return observer.onError(error); }) | ||
.finally(function () { | ||
_this._abortController = undefined; | ||
.catch(this._handleAndReThrown.bind(this)) | ||
.catch(error => observer.onError(error)) | ||
.finally(() => { | ||
this._abortController = undefined; | ||
}); | ||
return observer; | ||
}; | ||
HttpConnection.prototype._getTransactionApi = function () { | ||
var address = "".concat(this._scheme, "://").concat(this._address.asHostPort(), "/db/").concat(this._database === '' ? 'neo4j' : this._database, "/query/v2"); | ||
return address; | ||
}; | ||
HttpConnection.prototype.getProtocolVersion = function () { | ||
} | ||
_handleAndReThrown(error) { | ||
throw this._errorHandler(error); | ||
} | ||
_getTransactionApi(database) { | ||
return this._queryEndpoint.replace('{databaseName}', database); | ||
} | ||
static async discover({ scheme, address }) { | ||
return await fetch(`${scheme}://${address.asHostPort()}`, { | ||
headers: { | ||
Accept: 'application/json', | ||
} | ||
}) | ||
.then(async (res) => (await res.json())) | ||
.then(json => { | ||
if (typeof json.query !== 'string') { | ||
throw new Error('Query API is not available'); | ||
} | ||
return { query: json.query, version: json.neo4j_version, edition: json.neo4j_edition }; | ||
}) | ||
.catch(e => { | ||
throw newError(`Failure discovering endpoints. Caused by: ${e.message}`, 'SERVICE_UNAVAILABLE', e); | ||
}); | ||
} | ||
getProtocolVersion() { | ||
return 0; | ||
}; | ||
HttpConnection.prototype.isOpen = function () { | ||
} | ||
isOpen() { | ||
return true; | ||
}; | ||
HttpConnection.prototype.hasOngoingObservableRequests = function () { | ||
} | ||
hasOngoingObservableRequests() { | ||
return this._abortController != null; | ||
}; | ||
HttpConnection.prototype.resetAndFlush = function () { | ||
var _a; | ||
return __awaiter(this, void 0, void 0, function () { | ||
return __generator(this, function (_b) { | ||
(_a = this._abortController) === null || _a === void 0 ? void 0 : _a.abort((0, neo4j_driver_core_1.newError)('User aborted operation.')); | ||
return [2 /*return*/]; | ||
}); | ||
}); | ||
}; | ||
HttpConnection.prototype.release = function () { | ||
} | ||
async resetAndFlush() { | ||
this._abortController?.abort(newError('User aborted operation.')); | ||
} | ||
release() { | ||
return this._release(); | ||
}; | ||
return HttpConnection; | ||
}(neo4j_driver_core_1.Connection)); | ||
exports.default = HttpConnection; | ||
} | ||
toString() { | ||
return `HttpConnection [${this._id}]`; | ||
} | ||
} |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
/** | ||
@@ -18,8 +17,3 @@ * Copyright (c) "Neo4j" | ||
*/ | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.HttpConnectionProvider = void 0; | ||
var connection_provider_http_1 = __importDefault(require("./connection-provider.http")); | ||
exports.HttpConnectionProvider = connection_provider_http_1.default; | ||
import HttpConnectionProvider from "./connection-provider.http"; | ||
export { HttpConnectionProvider }; |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
/** | ||
@@ -18,197 +17,78 @@ * Copyright (c) "Neo4j" | ||
*/ | ||
var __assign = (this && this.__assign) || function () { | ||
__assign = Object.assign || function(t) { | ||
for (var s, i = 1, n = arguments.length; i < n; i++) { | ||
s = arguments[i]; | ||
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) | ||
t[p] = s[p]; | ||
} | ||
return t; | ||
}; | ||
return __assign.apply(this, arguments); | ||
}; | ||
var __generator = (this && this.__generator) || function (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 (g && (g = 0, op[0] && (_ = 0)), _) 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; | ||
import { newError, Node, Relationship, int, error, Time, Date, LocalTime, Point, DateTime, LocalDateTime, Duration, isInt, isPoint, isDuration, isLocalTime, isTime, isDate, isLocalDateTime, isDateTime, isRelationship, isPath, isNode, isPathSegment, Path, PathSegment, internal, isUnboundRelationship } from "neo4j-driver-core"; | ||
const NEO4J_QUERY_CONTENT_TYPE = 'application/vnd.neo4j.query'; | ||
export class QueryResponseCodec { | ||
static of(config, contentType, response) { | ||
if (isSuccess(response)) { | ||
if (contentType === NEO4J_QUERY_CONTENT_TYPE) { | ||
return new QuerySuccessResponseCodec(config, response); | ||
} | ||
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 }; | ||
} | ||
}; | ||
var __values = (this && this.__values) || function(o) { | ||
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; | ||
if (m) return m.call(o); | ||
if (o && typeof o.length === "number") return { | ||
next: function () { | ||
if (o && i >= o.length) o = void 0; | ||
return { value: o && o[i++], done: !o }; | ||
return new QueryFailureResponseCodec(newError(`Wrong content-type. Expected "${NEO4J_QUERY_CONTENT_TYPE}", but got "${contentType}".`, error.PROTOCOL_ERROR)); | ||
} | ||
}; | ||
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); | ||
}; | ||
var __read = (this && this.__read) || function (o, n) { | ||
var m = typeof Symbol === "function" && o[Symbol.iterator]; | ||
if (!m) return o; | ||
var i = m.call(o), r, ar = [], e; | ||
try { | ||
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); | ||
return new QueryFailureResponseCodec(response.errors?.length > 0 ? | ||
newError(response.errors[0].message, | ||
// TODO: REMOVE THE ?? AND .ERROR WHEN SERVER IS FIXED | ||
response.errors[0].code ?? response.errors[0].error) : | ||
newError('Server replied an empty error response', error.PROTOCOL_ERROR)); | ||
} | ||
catch (error) { e = { error: error }; } | ||
finally { | ||
try { | ||
if (r && !r.done && (m = i["return"])) m.call(i); | ||
} | ||
finally { if (e) throw e.error; } | ||
get error() { | ||
throw new Error('Not implemented'); | ||
} | ||
return ar; | ||
}; | ||
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { | ||
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { | ||
if (ar || !(i in from)) { | ||
if (!ar) ar = Array.prototype.slice.call(from, 0, i); | ||
ar[i] = from[i]; | ||
} | ||
get keys() { | ||
throw new Error('Not implemented'); | ||
} | ||
return to.concat(ar || Array.prototype.slice.call(from)); | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.QueryRequestCodec = exports.QueryResponseCodec = void 0; | ||
var neo4j_driver_core_1 = require("neo4j-driver-core"); | ||
var QueryResponseCodec = /** @class */ (function () { | ||
function QueryResponseCodec(_config, _contentType, _rawQueryResponse) { | ||
get meta() { | ||
throw new Error('Not implemented'); | ||
} | ||
*stream() { | ||
throw new Error('Not implemented'); | ||
} | ||
} | ||
class QuerySuccessResponseCodec extends QueryResponseCodec { | ||
constructor(_config, _response) { | ||
super(); | ||
this._config = _config; | ||
this._contentType = _contentType; | ||
this._rawQueryResponse = _rawQueryResponse; | ||
this._response = _response; | ||
} | ||
Object.defineProperty(QueryResponseCodec.prototype, "hasError", { | ||
get: function () { | ||
if (this._rawQueryResponse.errors == null) { | ||
return false; | ||
} | ||
return this._rawQueryResponse.errors.length !== 0; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(QueryResponseCodec.prototype, "error", { | ||
get: function () { | ||
return (0, neo4j_driver_core_1.newError)( | ||
// @ts-expect-error | ||
this._rawQueryResponse.errors[0].message, | ||
// @ts-expect-error | ||
this._rawQueryResponse.errors[0].error); | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(QueryResponseCodec.prototype, "keys", { | ||
get: function () { | ||
return this._rawQueryResponse.data.fields; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
QueryResponseCodec.prototype.stream = function () { | ||
var rawRecord, _a, _b, value, e_1_1; | ||
var e_1, _c; | ||
return __generator(this, function (_d) { | ||
switch (_d.label) { | ||
case 0: | ||
rawRecord = []; | ||
_d.label = 1; | ||
case 1: | ||
_d.trys.push([1, 6, 7, 8]); | ||
_a = __values(this._rawQueryResponse.data.values), _b = _a.next(); | ||
_d.label = 2; | ||
case 2: | ||
if (!!_b.done) return [3 /*break*/, 5]; | ||
value = _b.value; | ||
rawRecord.push(this._decodeValue(value)); | ||
if (!(rawRecord.length === this.keys.length)) return [3 /*break*/, 4]; | ||
return [4 /*yield*/, rawRecord | ||
// erasing raw records | ||
]; | ||
case 3: | ||
_d.sent(); | ||
// erasing raw records | ||
rawRecord = []; | ||
_d.label = 4; | ||
case 4: | ||
_b = _a.next(); | ||
return [3 /*break*/, 2]; | ||
case 5: return [3 /*break*/, 8]; | ||
case 6: | ||
e_1_1 = _d.sent(); | ||
e_1 = { error: e_1_1 }; | ||
return [3 /*break*/, 8]; | ||
case 7: | ||
try { | ||
if (_b && !_b.done && (_c = _a.return)) _c.call(_a); | ||
} | ||
finally { if (e_1) throw e_1.error; } | ||
return [7 /*endfinally*/]; | ||
case 8: return [2 /*return*/]; | ||
} | ||
}); | ||
}; | ||
Object.defineProperty(QueryResponseCodec.prototype, "meta", { | ||
get: function () { | ||
// console.log('meta', this._rawQueryResponse.results[0].stats) | ||
// const meta: Record<string, unknown> = { ...this._rawQueryResponse.results[0].stats, bookmark: this._rawQueryResponse.lastBookmarks } | ||
// if (this._rawQueryResponse.notifications != null) { | ||
// meta.notifications = this._rawQueryResponse.notifications | ||
// } | ||
return { | ||
bookmark: this._rawQueryResponse.bookmarks, | ||
stats: this._decodeStats(this._rawQueryResponse.counters), | ||
profile: this._rawQueryResponse.profiledQueryPlan != null ? | ||
this._decodeProfile(this._rawQueryResponse.profiledQueryPlan) : null | ||
}; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
QueryResponseCodec.prototype._decodeStats = function (counters) { | ||
var _this = this; | ||
get error() { | ||
return undefined; | ||
} | ||
get keys() { | ||
return this._response.data.fields; | ||
} | ||
*stream() { | ||
for (const value of this._response.data.values) { | ||
yield value.map(this._decodeValue.bind(this)); | ||
} | ||
return; | ||
} | ||
get meta() { | ||
return { | ||
bookmark: this._response.bookmarks, | ||
stats: this._decodeStats(this._response.counters), | ||
profile: this._response.profiledQueryPlan != null ? | ||
this._decodeProfile(this._response.profiledQueryPlan) : null, | ||
notifications: this._response.notifications | ||
}; | ||
} | ||
_decodeStats(counters) { | ||
return Object.fromEntries(Object.entries(counters) | ||
.map(function (_a) { | ||
var _b = __read(_a, 2), key = _b[0], value = _b[1]; | ||
return [key, typeof value === 'number' ? _this._normalizeInteger((0, neo4j_driver_core_1.int)(value)) : value]; | ||
})); | ||
}; | ||
QueryResponseCodec.prototype._decodeProfile = function (queryPlan) { | ||
var _this = this; | ||
.map(([key, value]) => [key, typeof value === 'number' ? this._normalizeInteger(int(value)) : value])); | ||
} | ||
_decodeProfile(queryPlan) { | ||
return Object.fromEntries(Object.entries(queryPlan) | ||
.map(function (_a) { | ||
var _b = __read(_a, 2), key = _b[0], value = _b[1]; | ||
var actualKey = key; | ||
var actualValue = value; | ||
.map(([key, value]) => { | ||
let actualKey = key; | ||
let actualValue = value; | ||
switch (key) { | ||
case 'children': | ||
actualValue = value.map(_this._decodeProfile.bind(_this)); | ||
actualValue = value.map(this._decodeProfile.bind(this)); | ||
break; | ||
case 'arguments': | ||
actualKey = 'args'; | ||
actualValue = Object.fromEntries(Object.entries(value) | ||
.map(([k, v]) => [k, this._decodeValue(v)])); | ||
break; | ||
case 'records': | ||
actualKey = 'row'; | ||
actualKey = 'rows'; | ||
break; | ||
@@ -220,7 +100,7 @@ default: | ||
})); | ||
}; | ||
QueryResponseCodec.prototype._decodeValue = function (value) { | ||
} | ||
_decodeValue(value) { | ||
switch (value.$type) { | ||
case "Null": | ||
return value._value; | ||
return null; | ||
case "Boolean": | ||
@@ -264,6 +144,6 @@ return value._value; | ||
// @ts-expect-error It should never happen | ||
throw (0, neo4j_driver_core_1.newError)("Unknown type: ".concat(value.$type), neo4j_driver_core_1.error.PROTOCOL_ERROR); | ||
throw newError(`Unknown type: ${value.$type}`, error.PROTOCOL_ERROR); | ||
} | ||
}; | ||
QueryResponseCodec.prototype._decodeInteger = function (value) { | ||
} | ||
_decodeInteger(value) { | ||
if (this._config.useBigInt === true) { | ||
@@ -273,3 +153,3 @@ return BigInt(value); | ||
else { | ||
var integer = (0, neo4j_driver_core_1.int)(value); | ||
const integer = int(value); | ||
if (this._config.disableLosslessIntegers === true) { | ||
@@ -280,167 +160,168 @@ return integer.toNumber(); | ||
} | ||
}; | ||
QueryResponseCodec.prototype._decodeFloat = function (value) { | ||
} | ||
_decodeFloat(value) { | ||
return parseFloat(value); | ||
}; | ||
QueryResponseCodec.prototype._decodeTime = function (value) { | ||
} | ||
_decodeTime(value) { | ||
// 12:50:35.556+01:00 | ||
var _a = __read(value.split(':'), 4), hourStr = _a[0], minuteString = _a[1], secondMillisecondAndOffsetString = _a[2], offsetMinuteString = _a[3]; | ||
var _b = __read(secondMillisecondAndOffsetString.split('.'), 2), secondStr = _b[0], millisecondAndOffsetString = _b[1]; | ||
const [hourStr, minuteString, secondNanosecondAndOffsetString, offsetMinuteString] = value.split(':'); | ||
const [secondStr, nanosecondAndOffsetString] = secondNanosecondAndOffsetString.split('.'); | ||
// @ts-expect-error | ||
var _c = __read(millisecondAndOffsetString.indexOf('+') >= 0 ? __spreadArray(__spreadArray([], __read(millisecondAndOffsetString.split('+')), false), [true], false) : (millisecondAndOffsetString.indexOf('-') >= 0 ? __spreadArray(__spreadArray([], __read(millisecondAndOffsetString.split('-')), false), [false], false) : | ||
[millisecondAndOffsetString.slice(0, millisecondAndOffsetString.length - 1), '0', true]), 3), millisecondString = _c[0], offsetHourString = _c[1], isPositive = _c[2]; | ||
var nanosecond = (0, neo4j_driver_core_1.int)(millisecondString).multiply(1000000); | ||
var timeZoneOffsetInSeconds = (0, neo4j_driver_core_1.int)(offsetHourString).multiply(60).add((0, neo4j_driver_core_1.int)(offsetMinuteString)).multiply(60).multiply(isPositive ? 1 : -1); | ||
return new neo4j_driver_core_1.Time(this._decodeInteger(hourStr), this._decodeInteger(minuteString), this._decodeInteger(secondStr), this._normalizeInteger(nanosecond), this._normalizeInteger(timeZoneOffsetInSeconds)); | ||
}; | ||
QueryResponseCodec.prototype._decodeDate = function (value) { | ||
// 2015-03-26 | ||
var _a = __read(value.split(value), 3), yearStr = _a[0], monthStr = _a[1], dayStr = _a[2]; | ||
return new neo4j_driver_core_1.Date(this._decodeInteger(yearStr), this._decodeInteger(monthStr), this._decodeInteger(dayStr)); | ||
}; | ||
QueryResponseCodec.prototype._decodeLocalTime = function (value) { | ||
const [nanosecondString, offsetHourString, isPositive] = nanosecondAndOffsetString.indexOf('+') >= 0 ? | ||
[...nanosecondAndOffsetString.split('+'), true] : (nanosecondAndOffsetString.indexOf('-') >= 0 ? | ||
[...nanosecondAndOffsetString.split('-'), false] : (nanosecondAndOffsetString.indexOf('Z') >= 0 ? | ||
[nanosecondAndOffsetString.slice(0, nanosecondAndOffsetString.length - 1), undefined, true] : | ||
[nanosecondAndOffsetString.slice(0, nanosecondAndOffsetString.length - 1), '0', true])); | ||
let nanosecond = int(nanosecondString.padEnd(9, '0')); | ||
if (offsetHourString != null) { | ||
const timeZoneOffsetInSeconds = int(offsetHourString).multiply(60).add(int(offsetMinuteString)).multiply(60).multiply(isPositive ? 1 : -1); | ||
return new Time(this._decodeInteger(hourStr), this._decodeInteger(minuteString), this._decodeInteger(secondStr), this._normalizeInteger(nanosecond), this._normalizeInteger(timeZoneOffsetInSeconds)); | ||
} | ||
return new LocalTime(this._decodeInteger(hourStr), this._decodeInteger(minuteString), this._decodeInteger(secondStr), this._normalizeInteger(nanosecond)); | ||
} | ||
_decodeDate(value) { | ||
// (+|-)2015-03-26 | ||
// first might be signal or first digit on date | ||
const first = value[0]; | ||
const [yearStr, monthStr, dayStr] = value.substring(1).split('-'); | ||
return new Date(this._decodeInteger(first.concat(yearStr)), this._decodeInteger(monthStr), this._decodeInteger(dayStr)); | ||
} | ||
_decodeLocalTime(value) { | ||
// 12:50:35.556 | ||
var _a = __read(value.split(':'), 3), hourStr = _a[0], minuteString = _a[1], secondMillisecondAndOffsetString = _a[2]; | ||
var _b = __read(secondMillisecondAndOffsetString.split('.'), 2), secondStr = _b[0], millisecondString = _b[1]; | ||
var nanosecond = (0, neo4j_driver_core_1.int)(millisecondString).multiply(1000000); | ||
return new neo4j_driver_core_1.LocalTime(this._decodeInteger(hourStr), this._decodeInteger(minuteString), this._decodeInteger(secondStr), this._normalizeInteger(nanosecond)); | ||
}; | ||
QueryResponseCodec.prototype._decodeZonedDateTime = function (value) { | ||
const [hourStr, minuteString, secondNanosecondAndOffsetString] = value.split(':'); | ||
const [secondStr, nanosecondString] = secondNanosecondAndOffsetString.split('.'); | ||
const nanosecond = int(nanosecondString.padEnd(9, '0')); | ||
return new LocalTime(this._decodeInteger(hourStr), this._decodeInteger(minuteString), this._decodeInteger(secondStr), this._normalizeInteger(nanosecond)); | ||
} | ||
_decodeZonedDateTime(value) { | ||
// 2015-11-21T21:40:32.142Z[Antarctica/Troll] | ||
var _a = __read(value.split('['), 2), dateTimeStr = _a[0], timeZoneIdEndWithAngleBrackets = _a[1]; | ||
var timeZoneId = timeZoneIdEndWithAngleBrackets.slice(0, timeZoneIdEndWithAngleBrackets.length - 1); | ||
var dateTime = this._decodeOffsetDateTime(dateTimeStr); | ||
return new neo4j_driver_core_1.DateTime(dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute, dateTime.second, dateTime.nanosecond, dateTime.timeZoneOffsetSeconds, timeZoneId); | ||
}; | ||
QueryResponseCodec.prototype._decodeOffsetDateTime = function (value) { | ||
const [dateTimeStr, timeZoneIdEndWithAngleBrackets] = value.split('['); | ||
const timeZoneId = timeZoneIdEndWithAngleBrackets.slice(0, timeZoneIdEndWithAngleBrackets.length - 1); | ||
const dateTime = this._decodeOffsetDateTime(dateTimeStr); | ||
return new DateTime(dateTime.year, dateTime.month, dateTime.day, dateTime.hour, dateTime.minute, dateTime.second, dateTime.nanosecond, isDateTime(dateTime) ? dateTime.timeZoneOffsetSeconds : undefined, timeZoneId); | ||
} | ||
_decodeOffsetDateTime(value) { | ||
// 2015-06-24T12:50:35.556+01:00 | ||
var _a = __read(value.split('T'), 2), dateStr = _a[0], timeStr = _a[1]; | ||
var date = this._decodeDate(dateStr); | ||
var time = this._decodeTime(timeStr); | ||
return new neo4j_driver_core_1.DateTime(date.year, date.month, date.day, time.hour, time.minute, time.second, time.nanosecond, time.timeZoneOffsetSeconds); | ||
}; | ||
QueryResponseCodec.prototype._decodeLocalDateTime = function (value) { | ||
const [dateStr, timeStr] = value.split('T'); | ||
const date = this._decodeDate(dateStr); | ||
const time = this._decodeTime(timeStr); | ||
if (isTime(time)) { | ||
return new DateTime(date.year, date.month, date.day, time.hour, time.minute, time.second, time.nanosecond, time.timeZoneOffsetSeconds); | ||
} | ||
return new LocalDateTime(date.year, date.month, date.day, time.hour, time.minute, time.second, time.nanosecond); | ||
} | ||
_decodeLocalDateTime(value) { | ||
// 2015-06-24T12:50:35.556 | ||
var _a = __read(value.split('T'), 2), dateStr = _a[0], timeStr = _a[1]; | ||
var date = this._decodeDate(dateStr); | ||
var time = this._decodeLocalTime(timeStr); | ||
return new neo4j_driver_core_1.LocalDateTime(date.year, date.month, date.day, time.hour, time.minute, time.second, time.nanosecond); | ||
}; | ||
QueryResponseCodec.prototype._decodeDuration = function (value) { | ||
const [dateStr, timeStr] = value.split('T'); | ||
const date = this._decodeDate(dateStr); | ||
const time = this._decodeLocalTime(timeStr); | ||
return new LocalDateTime(date.year, date.month, date.day, time.hour, time.minute, time.second, time.nanosecond); | ||
} | ||
_decodeDuration(value) { | ||
// P14DT16H12M | ||
// Duration is PnW | ||
var e_2, _a; | ||
var durationStringWithP = value.slice(1, value.length); | ||
const durationStringWithP = value.slice(1, value.length); | ||
if (durationStringWithP.endsWith('W')) { | ||
var weeksString = durationStringWithP.slice(0, durationStringWithP.length - 1); | ||
var weeks = this._decodeInteger(weeksString); | ||
throw (0, neo4j_driver_core_1.newError)('Duration in weeks are not supported yet', neo4j_driver_core_1.error.PROTOCOL_ERROR); | ||
const weeksString = durationStringWithP.slice(0, durationStringWithP.length - 1); | ||
const weeks = this._decodeInteger(weeksString); | ||
throw newError('Duration in weeks are not supported yet', error.PROTOCOL_ERROR); | ||
} | ||
var month = '0'; | ||
var day = 'O'; | ||
var second = '0'; | ||
var currentNumber = ''; | ||
var timePart = false; | ||
try { | ||
for (var durationStringWithP_1 = __values(durationStringWithP), durationStringWithP_1_1 = durationStringWithP_1.next(); !durationStringWithP_1_1.done; durationStringWithP_1_1 = durationStringWithP_1.next()) { | ||
var ch = durationStringWithP_1_1.value; | ||
if (ch >= '0' && ch <= '9') { | ||
currentNumber = currentNumber + ch; | ||
} | ||
else { | ||
switch (ch) { | ||
case 'M': | ||
if (timePart) { | ||
throw (0, neo4j_driver_core_1.newError)("Unexpected Duration component ".concat(ch, " in date part"), neo4j_driver_core_1.error.PROTOCOL_ERROR); | ||
} | ||
month = currentNumber; | ||
break; | ||
case 'D': | ||
if (!timePart) { | ||
throw (0, neo4j_driver_core_1.newError)("Unexpected Duration component ".concat(ch, " in time part"), neo4j_driver_core_1.error.PROTOCOL_ERROR); | ||
} | ||
day = currentNumber; | ||
break; | ||
case 'S': | ||
if (!timePart) { | ||
throw (0, neo4j_driver_core_1.newError)("Unexpected Duration component ".concat(ch, " in time part"), neo4j_driver_core_1.error.PROTOCOL_ERROR); | ||
} | ||
second = currentNumber; | ||
case 'T': | ||
timePart = true; | ||
default: | ||
throw (0, neo4j_driver_core_1.newError)("Unexpected Duration component ".concat(ch), neo4j_driver_core_1.error.PROTOCOL_ERROR); | ||
} | ||
currentNumber = ''; | ||
} | ||
let month = '0'; | ||
let day = '0'; | ||
let second = '0'; | ||
let nanosecond = '0'; | ||
let currentNumber = ''; | ||
let timePart = false; | ||
for (const ch of durationStringWithP) { | ||
if (ch >= '0' && ch <= '9' || ch === '.' || ch === ',') { | ||
currentNumber = currentNumber + ch; | ||
} | ||
} | ||
catch (e_2_1) { e_2 = { error: e_2_1 }; } | ||
finally { | ||
try { | ||
if (durationStringWithP_1_1 && !durationStringWithP_1_1.done && (_a = durationStringWithP_1.return)) _a.call(durationStringWithP_1); | ||
} | ||
finally { if (e_2) throw e_2.error; } | ||
} | ||
return new neo4j_driver_core_1.Duration(this._decodeInteger(month), this._decodeInteger(day), this._decodeInteger(second), | ||
// nano not present | ||
this._decodeInteger('0')); | ||
}; | ||
QueryResponseCodec.prototype._decodeMap = function (value) { | ||
var e_3, _a; | ||
var result = {}; | ||
try { | ||
for (var _b = __values(Object.keys(value)), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var k = _c.value; | ||
if (Object.prototype.hasOwnProperty.call(value, k)) { | ||
result[k] = this._decodeValue(value[k]); | ||
else { | ||
switch (ch) { | ||
case 'M': | ||
if (timePart) { | ||
throw newError(`Unexpected Duration component ${ch} in time part`, error.PROTOCOL_ERROR); | ||
} | ||
month = currentNumber; | ||
break; | ||
case 'D': | ||
if (timePart) { | ||
throw newError(`Unexpected Duration component ${ch} in time part`, error.PROTOCOL_ERROR); | ||
} | ||
day = currentNumber; | ||
break; | ||
case 'S': | ||
if (!timePart) { | ||
throw newError(`Unexpected Duration component ${ch} in date part`, error.PROTOCOL_ERROR); | ||
} | ||
const nanosecondSeparator = currentNumber.includes(',') ? ',' : '.'; | ||
[second, nanosecond] = currentNumber.split(nanosecondSeparator); | ||
break; | ||
case 'T': | ||
timePart = true; | ||
break; | ||
default: | ||
throw newError(`Unexpected Duration component ${ch}`, error.PROTOCOL_ERROR); | ||
} | ||
currentNumber = ''; | ||
} | ||
} | ||
catch (e_3_1) { e_3 = { error: e_3_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
const nanosecondString = nanosecond ?? '0'; | ||
return new Duration(this._decodeInteger(month), this._decodeInteger(day), this._decodeInteger(second), this._decodeInteger(nanosecondString.padEnd(9, '0'))); | ||
} | ||
_decodeMap(value) { | ||
const result = {}; | ||
for (const k of Object.keys(value)) { | ||
if (Object.prototype.hasOwnProperty.call(value, k)) { | ||
result[k] = this._decodeValue(value[k]); | ||
} | ||
finally { if (e_3) throw e_3.error; } | ||
} | ||
return result; | ||
}; | ||
QueryResponseCodec.prototype._decodePoint = function (value) { | ||
return new neo4j_driver_core_1.Point(this._normalizeInteger((0, neo4j_driver_core_1.int)(value.srid)), this._decodeFloat(value.x), this._decodeFloat(value.y), value.z != null ? this._decodeFloat(value.z) : undefined); | ||
}; | ||
QueryResponseCodec.prototype._decodeBase64 = function (value) { | ||
var binaryString = atob(value); | ||
} | ||
_decodePoint(value) { | ||
const createProtocolError = () => internal.objectUtil.createBrokenObject(newError(`Wrong point format. RawValue: ${value}`, error.PROTOCOL_ERROR), new Point(0, 0, 0)); | ||
const splittedOnSeparator = value.split(';'); | ||
if (splittedOnSeparator.length !== 2 || !splittedOnSeparator[0].startsWith('SRID=') || | ||
!(splittedOnSeparator[1].startsWith('POINT (') || splittedOnSeparator[1].startsWith('POINT Z ('))) { | ||
return createProtocolError(); | ||
} | ||
const [_, sridString] = splittedOnSeparator[0].split('='); | ||
const srid = this._normalizeInteger(int(sridString)); | ||
const [__, coordinatesString] = splittedOnSeparator[1].split('('); | ||
const [x, y, z] = coordinatesString.substring(0, coordinatesString.length - 1).split(" ").filter(c => c != null).map(parseFloat); | ||
return new Point(srid, x, y, z); | ||
} | ||
_decodeBase64(value) { | ||
const binaryString = atob(value); | ||
// @ts-expect-error See https://developer.mozilla.org/en-US/docs/Glossary/Base64 | ||
return Uint8Array.from(binaryString, function (b) { return b.codePointAt(0); }); | ||
}; | ||
QueryResponseCodec.prototype._decodeList = function (value) { | ||
var _this = this; | ||
return value.map(function (v) { return _this._decodeValue(v); }); | ||
}; | ||
QueryResponseCodec.prototype._decodeNode = function (value) { | ||
var _a; | ||
return new neo4j_driver_core_1.Node( | ||
return Uint8Array.from(binaryString, (b) => b.codePointAt(0)); | ||
} | ||
_decodeList(value) { | ||
return value.map(v => this._decodeValue(v)); | ||
} | ||
_decodeNode(value) { | ||
return new Node( | ||
// @ts-expect-error identity doesn't return | ||
undefined, value._labels, this._decodeMap((_a = value._properties) !== null && _a !== void 0 ? _a : {}), value._element_id); | ||
}; | ||
QueryResponseCodec.prototype._decodeRelationship = function (value) { | ||
var _a; | ||
return new neo4j_driver_core_1.Relationship( | ||
undefined, value._labels, this._decodeMap(value._properties ?? {}), value._element_id); | ||
} | ||
_decodeRelationship(value) { | ||
return new Relationship( | ||
// @ts-expect-error identity doesn't return | ||
undefined, undefined, undefined, value._type, this._decodeMap((_a = value._properties) !== null && _a !== void 0 ? _a : {}), value._element_id, value._start_node_element_id, value._end_node_element_id); | ||
}; | ||
QueryResponseCodec.prototype._decodePath = function (value) { | ||
var _this = this; | ||
var decoded = value.map(function (v) { return _this._decodeValue(v); }); | ||
return new neo4j_driver_core_1.Path(decoded[0], decoded[decoded.length - 1], | ||
undefined, undefined, undefined, value._type, this._decodeMap(value._properties ?? {}), value._element_id, value._start_node_element_id, value._end_node_element_id); | ||
} | ||
_decodePath(value) { | ||
const decoded = value.map(v => this._decodeValue(v)); | ||
return new Path(decoded[0], decoded[decoded.length - 1], | ||
// @ts-expect-error | ||
decoded.reduce(function (previous, current) { | ||
decoded.reduce((previous, current) => { | ||
if (previous.acc.length === 2) { | ||
return { acc: [current], segments: __spreadArray(__spreadArray([], __read(previous.segments), false), [new neo4j_driver_core_1.PathSegment(previous.acc[0], previous.acc[1], current)], false) }; | ||
return { | ||
acc: [current], segments: [...previous.segments, | ||
new PathSegment(previous.acc[0], previous.acc[1], current)] | ||
}; | ||
} | ||
return __assign(__assign({}, previous), { acc: __spreadArray(__spreadArray([], __read(previous.acc), false), [current], false) }); | ||
return { ...previous, acc: [...previous.acc, current] }; | ||
}, { acc: [], segments: [] }).segments); | ||
}; | ||
QueryResponseCodec.prototype._normalizeInteger = function (integer) { | ||
} | ||
_normalizeInteger(integer) { | ||
if (this._config.useBigInt === true) { | ||
@@ -453,8 +334,27 @@ return integer.toBigInt(); | ||
return integer; | ||
}; | ||
return QueryResponseCodec; | ||
}()); | ||
exports.QueryResponseCodec = QueryResponseCodec; | ||
var QueryRequestCodec = /** @class */ (function () { | ||
function QueryRequestCodec(_auth, _query, _parameters, _config) { | ||
} | ||
} | ||
class QueryFailureResponseCodec extends QueryResponseCodec { | ||
constructor(_error) { | ||
super(); | ||
this._error = _error; | ||
} | ||
get error() { | ||
return this._error; | ||
} | ||
get keys() { | ||
throw this._error; | ||
} | ||
get meta() { | ||
throw this._error; | ||
} | ||
stream() { | ||
throw this._error; | ||
} | ||
} | ||
export class QueryRequestCodec { | ||
static of(auth, query, parameters, config) { | ||
return new QueryRequestCodec(auth, query, parameters, config); | ||
} | ||
constructor(_auth, _query, _parameters, _config) { | ||
this._auth = _auth; | ||
@@ -465,70 +365,53 @@ this._query = _query; | ||
} | ||
Object.defineProperty(QueryRequestCodec.prototype, "contentType", { | ||
get: function () { | ||
return 'application/vnd.neo4j.query'; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(QueryRequestCodec.prototype, "accept", { | ||
get: function () { | ||
return 'application/vnd.neo4j.query, application/json'; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(QueryRequestCodec.prototype, "authorization", { | ||
get: function () { | ||
return "Basic ".concat(btoa("".concat(this._auth.principal, ":").concat(this._auth.credentials))); | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(QueryRequestCodec.prototype, "body", { | ||
get: function () { | ||
var _a, _b, _c, _d, _e, _f; | ||
if (this._body != null) { | ||
return this._body; | ||
} | ||
this._body = { | ||
statement: this._query, | ||
includeCounters: true, | ||
bookmarks: (_b = (_a = this._config) === null || _a === void 0 ? void 0 : _a.bookmarks) === null || _b === void 0 ? void 0 : _b.values() | ||
}; | ||
if (Object.getOwnPropertyNames(this._parameters).length !== 0) { | ||
this._body.parameters = this._encodeParameters(this._parameters); | ||
} | ||
if (((_c = this._config) === null || _c === void 0 ? void 0 : _c.txConfig.timeout) != null) { | ||
this._body.max_execution_time = (_d = this._config) === null || _d === void 0 ? void 0 : _d.txConfig.timeout; | ||
} | ||
if (((_e = this._config) === null || _e === void 0 ? void 0 : _e.impersonatedUser) != null) { | ||
this._body.impersonated_user = (_f = this._config) === null || _f === void 0 ? void 0 : _f.impersonatedUser; | ||
} | ||
get contentType() { | ||
return NEO4J_QUERY_CONTENT_TYPE; | ||
} | ||
get accept() { | ||
return `${NEO4J_QUERY_CONTENT_TYPE}, application/json`; | ||
} | ||
get authorization() { | ||
switch (this._auth.scheme) { | ||
case 'bearer': | ||
return `Bearer ${btoa(this._auth.credentials)}`; | ||
case 'basic': | ||
return `Basic ${btoa(`${this._auth.principal}:${this._auth.credentials}`)}`; | ||
default: | ||
throw new Error(`Authorization scheme "${this._auth.scheme}" is not supported.`); | ||
} | ||
} | ||
get body() { | ||
if (this._body != null) { | ||
return this._body; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
QueryRequestCodec.prototype._encodeParameters = function (parameters) { | ||
var e_4, _a; | ||
var encodedParams = {}; | ||
try { | ||
for (var _b = __values(Object.keys(parameters)), _c = _b.next(); !_c.done; _c = _b.next()) { | ||
var k = _c.value; | ||
if (Object.prototype.hasOwnProperty.call(parameters, k)) { | ||
encodedParams[k] = this._encodeValue(parameters[k]); | ||
} | ||
} | ||
} | ||
catch (e_4_1) { e_4 = { error: e_4_1 }; } | ||
finally { | ||
try { | ||
if (_c && !_c.done && (_a = _b.return)) _a.call(_b); | ||
this._body = { | ||
statement: this._query, | ||
includeCounters: true | ||
}; | ||
if (this._parameters != null && Object.getOwnPropertyNames(this._parameters).length !== 0) { | ||
this._body.parameters = this._encodeParameters(this._parameters); | ||
} | ||
if (this._config?.bookmarks != null && !this._config.bookmarks.isEmpty()) { | ||
this._body.bookmarks = this._config?.bookmarks?.values(); | ||
} | ||
if (this._config?.txConfig.timeout != null) { | ||
this._body.maxExecutionTime = this._config?.txConfig.timeout.toInt(); | ||
} | ||
if (this._config?.impersonatedUser != null) { | ||
this._body.impersonatedUser = this._config?.impersonatedUser; | ||
} | ||
if (this._config?.mode) { | ||
this._body.accessMode = this._config.mode.toUpperCase(); | ||
} | ||
return this._body; | ||
} | ||
_encodeParameters(parameters) { | ||
const encodedParams = {}; | ||
for (const k of Object.keys(parameters)) { | ||
if (Object.prototype.hasOwnProperty.call(parameters, k)) { | ||
encodedParams[k] = this._encodeValue(parameters[k]); | ||
} | ||
finally { if (e_4) throw e_4.error; } | ||
} | ||
return encodedParams; | ||
}; | ||
QueryRequestCodec.prototype._encodeValue = function (value) { | ||
var _a; | ||
} | ||
_encodeValue(value) { | ||
if (value === null) { | ||
@@ -549,6 +432,6 @@ return { $type: 'Null', _value: null }; | ||
} | ||
else if ((0, neo4j_driver_core_1.isInt)(value)) { | ||
else if (isInt(value)) { | ||
return { $type: 'Integer', _value: value.toString() }; | ||
} | ||
else if (value instanceof Int8Array) { | ||
else if (value instanceof Uint8Array) { | ||
return { $type: 'Base64', _value: btoa(String.fromCharCode.apply(null, value)) }; | ||
@@ -562,26 +445,30 @@ } | ||
} | ||
else if ((0, neo4j_driver_core_1.isPoint)(value)) { | ||
return { $type: 'Point', _value: { | ||
srid: (0, neo4j_driver_core_1.int)(value.srid).toNumber(), | ||
x: value.x.toString(), | ||
y: value.y.toString(), | ||
z: (_a = value.z) === null || _a === void 0 ? void 0 : _a.toString() | ||
} }; | ||
else if (isPoint(value)) { | ||
return { | ||
$type: 'Point', _value: value.z == null ? | ||
`SRID=${int(value.srid).toString()};POINT (${value.x} ${value.y})` : | ||
`SRID=${int(value.srid).toString()};POINT Z (${value.x} ${value.y} ${value.z})` | ||
}; | ||
} | ||
else if ((0, neo4j_driver_core_1.isDuration)(value)) { | ||
else if (isDuration(value)) { | ||
return { $type: 'Duration', _value: value.toString() }; | ||
} | ||
else if ((0, neo4j_driver_core_1.isLocalTime)(value)) { | ||
else if (isLocalTime(value)) { | ||
return { $type: 'LocalTime', _value: value.toString() }; | ||
} | ||
else if ((0, neo4j_driver_core_1.isTime)(value)) { | ||
else if (isTime(value)) { | ||
return { $type: 'Time', _value: value.toString() }; | ||
} | ||
else if ((0, neo4j_driver_core_1.isDate)(value)) { | ||
else if (isDate(value)) { | ||
return { $type: 'Date', _value: value.toString() }; | ||
} | ||
else if ((0, neo4j_driver_core_1.isLocalDateTime)(value)) { | ||
else if (isLocalDateTime(value)) { | ||
return { $type: 'LocalDateTime', _value: value.toString() }; | ||
} | ||
else if ((0, neo4j_driver_core_1.isDateTime)(value)) { | ||
else if (isDateTime(value)) { | ||
if (value.timeZoneOffsetSeconds == null) { | ||
throw new Error('DateTime objects without "timeZoneOffsetSeconds" property ' + | ||
'are prone to bugs related to ambiguous times. For instance, ' + | ||
'2022-10-30T2:30:00[Europe/Berlin] could be GMT+1 or GMT+2.'); | ||
} | ||
if (value.timeZoneId != null) { | ||
@@ -592,4 +479,4 @@ return { $type: 'ZonedDateTime', _value: value.toString() }; | ||
} | ||
else if ((0, neo4j_driver_core_1.isRelationship)(value) || (0, neo4j_driver_core_1.isNode)(value) || (0, neo4j_driver_core_1.isPath)(value) || (0, neo4j_driver_core_1.isPathSegment)(value)) { | ||
throw (0, neo4j_driver_core_1.newError)('Graph types can not be ingested to the server', neo4j_driver_core_1.error.PROTOCOL_ERROR); | ||
else if (isRelationship(value) || isNode(value) || isPath(value) || isPathSegment(value) || isUnboundRelationship(value)) { | ||
throw newError('Graph types can not be ingested to the server', error.PROTOCOL_ERROR); | ||
} | ||
@@ -600,8 +487,6 @@ else if (typeof value === 'object') { | ||
else { | ||
throw (0, neo4j_driver_core_1.newError)("Unable to convert parameter to http request. Value: ".concat(value), neo4j_driver_core_1.error.PROTOCOL_ERROR); | ||
throw newError(`Unable to convert parameter to http request. Value: ${value}`, error.PROTOCOL_ERROR); | ||
} | ||
}; | ||
return QueryRequestCodec; | ||
}()); | ||
exports.QueryRequestCodec = QueryRequestCodec; | ||
} | ||
} | ||
function isIterable(obj) { | ||
@@ -614,1 +499,7 @@ if (obj == null) { | ||
} | ||
function isSuccess(obj) { | ||
if (obj.errors != null) { | ||
return false; | ||
} | ||
return true; | ||
} |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
/** | ||
@@ -18,7 +17,6 @@ * Copyright (c) "Neo4j" | ||
*/ | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ResultStreamObserver = void 0; | ||
var neo4j_driver_core_1 = require("neo4j-driver-core"); | ||
var ResultStreamObserver = /** @class */ (function () { | ||
function ResultStreamObserver(config) { | ||
import { Record } from "neo4j-driver-core"; | ||
import { FSM } from "./fsm"; | ||
export class ResultStreamObserver { | ||
constructor(config) { | ||
this._paused = false; | ||
@@ -32,32 +30,33 @@ this._completed = false; | ||
this._server = config.server; | ||
this._haveRecordStreamed = false; | ||
this._fsm = newFSM(this); | ||
this._resultObservers = []; | ||
} | ||
Object.defineProperty(ResultStreamObserver.prototype, "completed", { | ||
get: function () { | ||
return this._completed; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
Object.defineProperty(ResultStreamObserver.prototype, "paused", { | ||
get: function () { | ||
return this._paused; | ||
}, | ||
enumerable: false, | ||
configurable: true | ||
}); | ||
ResultStreamObserver.prototype.cancel = function () { | ||
get completed() { | ||
return this._completed; | ||
} | ||
get paused() { | ||
return this._paused; | ||
} | ||
cancel() { | ||
this._completed = true; | ||
this._queuedRecords = []; | ||
}; | ||
ResultStreamObserver.prototype.pause = function () { | ||
} | ||
pause() { | ||
this._paused = true; | ||
}; | ||
ResultStreamObserver.prototype.resume = function () { | ||
} | ||
resume() { | ||
this._paused = false; | ||
}; | ||
ResultStreamObserver.prototype.markCompleted = function () { | ||
} | ||
prepareToHandleSingleResponse() { | ||
this.onKeys([]); | ||
} | ||
markCompleted() { | ||
this._completed = true; | ||
}; | ||
ResultStreamObserver.prototype.subscribe = function (observer) { | ||
if (this._keys == null) { | ||
this.onKeys([]); | ||
} | ||
this.onCompleted(false); | ||
} | ||
subscribe(observer) { | ||
if (this._keys != null && observer.onKeys != null) { | ||
@@ -67,3 +66,3 @@ observer.onKeys(this._keys); | ||
if (this._queuedRecords.length > 0 && observer.onNext) { | ||
for (var i = 0; i < this._queuedRecords.length; i++) { | ||
for (let i = 0; i < this._queuedRecords.length; i++) { | ||
observer.onNext(this._queuedRecords[i]); | ||
@@ -83,16 +82,22 @@ if (this._queuedRecords.length - i - 1 <= this._lowRecordWatermark) { | ||
// start stream | ||
}; | ||
ResultStreamObserver.prototype.onKeys = function (keys) { | ||
var _this = this; | ||
} | ||
onKeys(keys) { | ||
this._fsm.onEvent('keys', keys); | ||
} | ||
_onKeys(keys) { | ||
this._keys = keys; | ||
var observingOnKeys = this._resultObservers.filter(function (o) { return o.onNext; }); | ||
const observingOnKeys = this._resultObservers.filter(o => o.onKeys); | ||
if (observingOnKeys.length > 0) { | ||
observingOnKeys.forEach(function (o) { return o.onKeys(_this._keys); }); | ||
observingOnKeys.forEach(o => o.onKeys(this._keys)); | ||
} | ||
}; | ||
ResultStreamObserver.prototype.onNext = function (rawRecord) { | ||
var record = new neo4j_driver_core_1.Record(this._keys, rawRecord); | ||
var observingOnNext = this._resultObservers.filter(function (o) { return o.onNext; }); | ||
} | ||
onNext(rawRecord) { | ||
this._fsm.onEvent('next', rawRecord); | ||
} | ||
_onNext(rawRecord) { | ||
this._haveRecordStreamed = true; | ||
const record = new Record(this._keys, rawRecord); | ||
const observingOnNext = this._resultObservers.filter(o => o.onNext); | ||
if (observingOnNext.length > 0) { | ||
observingOnNext.forEach(function (o) { return o.onNext(record); }); | ||
observingOnNext.forEach(o => o.onNext(record)); | ||
} | ||
@@ -105,13 +110,15 @@ else { | ||
} | ||
}; | ||
ResultStreamObserver.prototype.onError = function (error) { | ||
var _this = this; | ||
} | ||
onError(error) { | ||
this._fsm.onEvent('error', error); | ||
} | ||
_onError(error) { | ||
this._error = error; | ||
var beforeHandlerResult = null; | ||
let beforeHandlerResult = null; | ||
if (this._beforeError) { | ||
beforeHandlerResult = this._beforeError(error); | ||
} | ||
var continuation = function () { | ||
_this._resultObservers.filter(function (o) { return o.onError; }) | ||
.forEach(function (o) { return o.onError(error); }); | ||
const continuation = () => { | ||
this._resultObservers.filter(o => o.onError) | ||
.forEach(o => o.onError(error)); | ||
// if (this._afterError) { | ||
@@ -122,3 +129,3 @@ // this._afterError(error) | ||
if (beforeHandlerResult) { | ||
Promise.resolve(beforeHandlerResult).then(function () { return continuation(); }); | ||
Promise.resolve(beforeHandlerResult).then(() => continuation()); | ||
} | ||
@@ -128,21 +135,96 @@ else { | ||
} | ||
}; | ||
ResultStreamObserver.prototype.onCompleted = function (meta) { | ||
var _this = this; | ||
var completionMetadata = Object.assign(this._server ? { server: this._server } : {}, | ||
//this._meta, | ||
meta); | ||
} | ||
/** | ||
* | ||
* @param {any|false} meta The metadata returned from server. Or false, | ||
* if observer should complete with {} | ||
*/ | ||
onCompleted(meta) { | ||
this._fsm.onEvent('completed', meta); | ||
} | ||
_onCompleted(meta) { | ||
const completionMetadata = meta !== false ? Object.assign(this._server ? { server: this._server } : {}, meta, { | ||
stream_summary: { | ||
have_records_streamed: this._haveRecordStreamed, | ||
pulled: true, | ||
has_keys: this._keys.length > 0 | ||
} | ||
}) : {}; | ||
this._metadata = completionMetadata; | ||
this.markCompleted(); | ||
var observingOnCompleted = this._resultObservers.filter(function (o) { return o.onCompleted; }); | ||
this._completed = true; | ||
const observingOnCompleted = this._resultObservers.filter(o => o.onCompleted); | ||
if (observingOnCompleted.length > 0) { | ||
observingOnCompleted.forEach(function (o) { return o.onCompleted(_this._metadata); }); | ||
observingOnCompleted.forEach(o => o.onCompleted(this._metadata)); | ||
} | ||
if (this._afterComplete) { | ||
console.log('afterComplete', completionMetadata); | ||
this._afterComplete(completionMetadata); | ||
} | ||
} | ||
} | ||
function newFSM(observer) { | ||
const onInvalidTransition = (state, event) => (_) => { | ||
const result = observer._onError(new Error(`Invalid event. State: ${state}, Event: ${event}`)); | ||
return { | ||
nextState: 'FAILED', | ||
result | ||
}; | ||
}; | ||
return ResultStreamObserver; | ||
}()); | ||
exports.ResultStreamObserver = ResultStreamObserver; | ||
const onFailure = (error) => { | ||
const result = observer._onError(error); | ||
return { | ||
nextState: 'FAILED', | ||
result | ||
}; | ||
}; | ||
const ignore = () => ({}); | ||
return new FSM({ | ||
name: 'READY', | ||
events: { | ||
keys: (keys) => { | ||
const result = observer._onKeys(keys); | ||
return { | ||
nextState: 'STREAMING', | ||
result | ||
}; | ||
}, | ||
completed: onInvalidTransition('READY', 'completed'), | ||
next: onInvalidTransition('READY', 'next'), | ||
error: onFailure | ||
} | ||
}, { | ||
name: 'STREAMING', | ||
events: { | ||
keys: onInvalidTransition('STREAMING', 'keys'), | ||
completed: (metadata) => { | ||
const result = observer._onCompleted(metadata); | ||
return { | ||
nextState: 'SUCCEEDED', | ||
result | ||
}; | ||
}, | ||
next: (rawRecord) => { | ||
const result = observer._onNext(rawRecord); | ||
return { | ||
result | ||
}; | ||
}, | ||
error: onFailure | ||
} | ||
}, { | ||
name: 'SUCCEEDED', | ||
events: { | ||
keys: ignore, | ||
next: ignore, | ||
completed: ignore, | ||
error: ignore | ||
} | ||
}, { | ||
name: 'FAILED', | ||
events: { | ||
keys: ignore, | ||
next: ignore, | ||
completed: ignore, | ||
error: ignore | ||
} | ||
}); | ||
} |
326
lib/index.js
@@ -1,5 +0,1 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.ConnectionProvider = exports.DateTime = exports.LocalDateTime = exports.Date = exports.Time = exports.LocalTime = exports.Duration = exports.Point = exports.Session = exports.ServerInfo = exports.Notification = exports.QueryStatistics = exports.ProfiledPlan = exports.Plan = exports.Integer = exports.Path = exports.PathSegment = exports.UnboundRelationship = exports.Relationship = exports.Node = exports.ResultSummary = exports.Record = exports.Result = exports.Driver = exports.temporal = exports.spatial = exports.graph = exports.error = exports.session = exports.types = exports.logging = exports.auth = exports.isRetriableError = exports.Neo4jError = exports.integer = exports.isUnboundRelationship = exports.isRelationship = exports.isPathSegment = exports.isPath = exports.isNode = exports.isDateTime = exports.isLocalDateTime = exports.isDate = exports.isTime = exports.isLocalTime = exports.isDuration = exports.isPoint = exports.isInt = exports.int = exports.authTokenManagers = void 0; | ||
exports.wrapper = exports.notificationSeverityLevel = exports.notificationCategory = exports.resultTransformers = exports.bookmarkManager = exports.Connection = void 0; | ||
/** | ||
@@ -21,57 +17,8 @@ * Copyright (c) "Neo4j" | ||
*/ | ||
var neo4j_driver_core_1 = require("neo4j-driver-core"); | ||
Object.defineProperty(exports, "auth", { enumerable: true, get: function () { return neo4j_driver_core_1.auth; } }); | ||
Object.defineProperty(exports, "bookmarkManager", { enumerable: true, get: function () { return neo4j_driver_core_1.bookmarkManager; } }); | ||
Object.defineProperty(exports, "authTokenManagers", { enumerable: true, get: function () { return neo4j_driver_core_1.authTokenManagers; } }); | ||
Object.defineProperty(exports, "Connection", { enumerable: true, get: function () { return neo4j_driver_core_1.Connection; } }); | ||
Object.defineProperty(exports, "ConnectionProvider", { enumerable: true, get: function () { return neo4j_driver_core_1.ConnectionProvider; } }); | ||
Object.defineProperty(exports, "Date", { enumerable: true, get: function () { return neo4j_driver_core_1.Date; } }); | ||
Object.defineProperty(exports, "DateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.DateTime; } }); | ||
Object.defineProperty(exports, "Driver", { enumerable: true, get: function () { return neo4j_driver_core_1.Driver; } }); | ||
Object.defineProperty(exports, "Duration", { enumerable: true, get: function () { return neo4j_driver_core_1.Duration; } }); | ||
Object.defineProperty(exports, "error", { enumerable: true, get: function () { return neo4j_driver_core_1.error; } }); | ||
Object.defineProperty(exports, "int", { enumerable: true, get: function () { return neo4j_driver_core_1.int; } }); | ||
Object.defineProperty(exports, "Integer", { enumerable: true, get: function () { return neo4j_driver_core_1.Integer; } }); | ||
Object.defineProperty(exports, "isDate", { enumerable: true, get: function () { return neo4j_driver_core_1.isDate; } }); | ||
Object.defineProperty(exports, "isDateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isDateTime; } }); | ||
Object.defineProperty(exports, "isDuration", { enumerable: true, get: function () { return neo4j_driver_core_1.isDuration; } }); | ||
Object.defineProperty(exports, "isInt", { enumerable: true, get: function () { return neo4j_driver_core_1.isInt; } }); | ||
Object.defineProperty(exports, "isLocalDateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isLocalDateTime; } }); | ||
Object.defineProperty(exports, "isLocalTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isLocalTime; } }); | ||
Object.defineProperty(exports, "isNode", { enumerable: true, get: function () { return neo4j_driver_core_1.isNode; } }); | ||
Object.defineProperty(exports, "isPath", { enumerable: true, get: function () { return neo4j_driver_core_1.isPath; } }); | ||
Object.defineProperty(exports, "isPathSegment", { enumerable: true, get: function () { return neo4j_driver_core_1.isPathSegment; } }); | ||
Object.defineProperty(exports, "isPoint", { enumerable: true, get: function () { return neo4j_driver_core_1.isPoint; } }); | ||
Object.defineProperty(exports, "isRelationship", { enumerable: true, get: function () { return neo4j_driver_core_1.isRelationship; } }); | ||
Object.defineProperty(exports, "isRetriableError", { enumerable: true, get: function () { return neo4j_driver_core_1.isRetriableError; } }); | ||
Object.defineProperty(exports, "isTime", { enumerable: true, get: function () { return neo4j_driver_core_1.isTime; } }); | ||
Object.defineProperty(exports, "isUnboundRelationship", { enumerable: true, get: function () { return neo4j_driver_core_1.isUnboundRelationship; } }); | ||
Object.defineProperty(exports, "LocalDateTime", { enumerable: true, get: function () { return neo4j_driver_core_1.LocalDateTime; } }); | ||
Object.defineProperty(exports, "LocalTime", { enumerable: true, get: function () { return neo4j_driver_core_1.LocalTime; } }); | ||
Object.defineProperty(exports, "Neo4jError", { enumerable: true, get: function () { return neo4j_driver_core_1.Neo4jError; } }); | ||
Object.defineProperty(exports, "Node", { enumerable: true, get: function () { return neo4j_driver_core_1.Node; } }); | ||
Object.defineProperty(exports, "Notification", { enumerable: true, get: function () { return neo4j_driver_core_1.Notification; } }); | ||
Object.defineProperty(exports, "notificationCategory", { enumerable: true, get: function () { return neo4j_driver_core_1.notificationCategory; } }); | ||
Object.defineProperty(exports, "notificationSeverityLevel", { enumerable: true, get: function () { return neo4j_driver_core_1.notificationSeverityLevel; } }); | ||
Object.defineProperty(exports, "Path", { enumerable: true, get: function () { return neo4j_driver_core_1.Path; } }); | ||
Object.defineProperty(exports, "PathSegment", { enumerable: true, get: function () { return neo4j_driver_core_1.PathSegment; } }); | ||
Object.defineProperty(exports, "Plan", { enumerable: true, get: function () { return neo4j_driver_core_1.Plan; } }); | ||
Object.defineProperty(exports, "Point", { enumerable: true, get: function () { return neo4j_driver_core_1.Point; } }); | ||
Object.defineProperty(exports, "ProfiledPlan", { enumerable: true, get: function () { return neo4j_driver_core_1.ProfiledPlan; } }); | ||
Object.defineProperty(exports, "QueryStatistics", { enumerable: true, get: function () { return neo4j_driver_core_1.QueryStatistics; } }); | ||
Object.defineProperty(exports, "Record", { enumerable: true, get: function () { return neo4j_driver_core_1.Record; } }); | ||
Object.defineProperty(exports, "Relationship", { enumerable: true, get: function () { return neo4j_driver_core_1.Relationship; } }); | ||
Object.defineProperty(exports, "Result", { enumerable: true, get: function () { return neo4j_driver_core_1.Result; } }); | ||
Object.defineProperty(exports, "ResultSummary", { enumerable: true, get: function () { return neo4j_driver_core_1.ResultSummary; } }); | ||
Object.defineProperty(exports, "resultTransformers", { enumerable: true, get: function () { return neo4j_driver_core_1.resultTransformers; } }); | ||
Object.defineProperty(exports, "ServerInfo", { enumerable: true, get: function () { return neo4j_driver_core_1.ServerInfo; } }); | ||
Object.defineProperty(exports, "Session", { enumerable: true, get: function () { return neo4j_driver_core_1.Session; } }); | ||
Object.defineProperty(exports, "Time", { enumerable: true, get: function () { return neo4j_driver_core_1.Time; } }); | ||
Object.defineProperty(exports, "UnboundRelationship", { enumerable: true, get: function () { return neo4j_driver_core_1.UnboundRelationship; } }); | ||
var logging_1 = require("./logging"); | ||
Object.defineProperty(exports, "logging", { enumerable: true, get: function () { return logging_1.logging; } }); | ||
var wrapper_impl_1 = require("./wrapper.impl"); | ||
var http_connection_1 = require("./http-connection"); | ||
var _a = neo4j_driver_core_1.internal.util, ENCRYPTION_ON = _a.ENCRYPTION_ON, assertString = _a.assertString, ServerAddress = neo4j_driver_core_1.internal.serverAddress.ServerAddress, urlUtil = neo4j_driver_core_1.internal.urlUtil; | ||
var READ = neo4j_driver_core_1.driver.READ, WRITE = neo4j_driver_core_1.driver.WRITE; | ||
import { auth, bookmarkManager, authTokenManagers, staticAuthTokenManager, Connection, ConnectionProvider, Date, DateTime, Driver, Duration, error, inSafeRange, int, Integer, internal, isDate, isDateTime, isDuration, isInt, isLocalDateTime, isLocalTime, isNode, isPath, isPathSegment, isPoint, isRelationship, isRetriableError, isTime, isUnboundRelationship, LocalDateTime, LocalTime, Neo4jError, Node, Notification, notificationCategory, notificationSeverityLevel, Path, PathSegment, Plan, Point, ProfiledPlan, QueryStatistics, Record, Relationship, Result, ResultSummary, resultTransformers, ServerInfo, Session, Time, toNumber, toString, UnboundRelationship, driver as coreDriver, } from 'neo4j-driver-core'; | ||
import { logging } from './logging'; | ||
import { WrapperImpl } from './wrapper.impl'; | ||
import { HttpConnectionProvider } from './http-connection'; | ||
const { util: { ENCRYPTION_ON, assertString }, serverAddress: { ServerAddress }, urlUtil, } = internal; | ||
const { READ, WRITE } = coreDriver; | ||
function isAuthTokenManager(value) { | ||
@@ -82,3 +29,3 @@ if (typeof value === 'object' && | ||
'handleSecurityException' in value) { | ||
var manager = value; | ||
const manager = value; | ||
return typeof manager.getToken === 'function' && | ||
@@ -90,24 +37,21 @@ typeof manager.handleSecurityException === 'function'; | ||
function createAuthManager(authTokenOrProvider) { | ||
var _a; | ||
if (isAuthTokenManager(authTokenOrProvider)) { | ||
return authTokenOrProvider; | ||
} | ||
var authToken = authTokenOrProvider; | ||
let authToken = authTokenOrProvider; | ||
// Sanitize authority token. Nicer error from server when a scheme is set. | ||
authToken = authToken !== null && authToken !== void 0 ? authToken : {}; | ||
authToken.scheme = (_a = authToken.scheme) !== null && _a !== void 0 ? _a : 'none'; | ||
return (0, neo4j_driver_core_1.staticAuthTokenManager)({ authToken: authToken }); | ||
authToken = authToken ?? {}; | ||
authToken.scheme = authToken.scheme ?? 'none'; | ||
return staticAuthTokenManager({ authToken }); | ||
} | ||
function wrapper(url, authToken, config) { | ||
var _a; | ||
if (config === void 0) { config = {}; } | ||
function wrapper(url, authToken, config = {}) { | ||
assertString(url, 'Http URL'); | ||
var parsedUrl = urlUtil.parseDatabaseUrl(url); | ||
const parsedUrl = urlUtil.parseDatabaseUrl(url); | ||
// enabling set boltAgent | ||
var _config = config; | ||
const _config = config; | ||
// Determine encryption/trust options from the URL. | ||
var routing = false; | ||
var encrypted = false; | ||
var trust; | ||
var http = false; | ||
let routing = false; | ||
let encrypted = false; | ||
let trust; | ||
let http = false; | ||
switch (parsedUrl.scheme) { | ||
@@ -119,3 +63,3 @@ case 'http': | ||
default: | ||
throw new Error("Unknown scheme: ".concat((_a = parsedUrl.scheme) !== null && _a !== void 0 ? _a : 'null')); | ||
throw new Error(`Unknown scheme: ${parsedUrl.scheme ?? 'null'}`); | ||
} | ||
@@ -131,154 +75,148 @@ // Encryption enabled on URL, propagate trust to the config. | ||
} | ||
var authTokenManager = createAuthManager(authToken); | ||
var address = ServerAddress.fromUrl(parsedUrl.hostAndPort); | ||
var meta = { | ||
address: address, | ||
const authTokenManager = createAuthManager(authToken); | ||
const address = ServerAddress.fromUrl(parsedUrl.hostAndPort); | ||
const meta = { | ||
address, | ||
typename: 'HTTP', | ||
routing: routing | ||
routing | ||
}; | ||
var driver = new neo4j_driver_core_1.Driver(meta, _config, createConnectionProviderFunction()); | ||
return new wrapper_impl_1.WrapperImpl(driver); | ||
const driver = new Driver(meta, _config, createConnectionProviderFunction()); | ||
return new WrapperImpl(driver); | ||
function createConnectionProviderFunction() { | ||
return function (id, config, log, hostNameResolver) { return new http_connection_1.HttpConnectionProvider({ | ||
id: id, | ||
config: config, | ||
log: log, | ||
hostNameResolver: hostNameResolver, | ||
authTokenManager: authTokenManager, | ||
return (id, config, log, hostNameResolver) => new HttpConnectionProvider({ | ||
id, | ||
config, | ||
log, | ||
hostNameResolver, | ||
authTokenManager, | ||
scheme: parsedUrl.scheme, | ||
address: address, | ||
address, | ||
userAgent: config.userAgent, | ||
boltAgent: config.boltAgent, | ||
routingContext: parsedUrl.query | ||
}); }; | ||
}); | ||
} | ||
} | ||
exports.wrapper = wrapper; | ||
/** | ||
* Object containing constructors for all neo4j types. | ||
*/ | ||
var types = { | ||
Node: neo4j_driver_core_1.Node, | ||
Relationship: neo4j_driver_core_1.Relationship, | ||
UnboundRelationship: neo4j_driver_core_1.UnboundRelationship, | ||
PathSegment: neo4j_driver_core_1.PathSegment, | ||
Path: neo4j_driver_core_1.Path, | ||
Result: neo4j_driver_core_1.Result, | ||
ResultSummary: neo4j_driver_core_1.ResultSummary, | ||
Record: neo4j_driver_core_1.Record, | ||
Point: neo4j_driver_core_1.Point, | ||
Date: neo4j_driver_core_1.Date, | ||
DateTime: neo4j_driver_core_1.DateTime, | ||
Duration: neo4j_driver_core_1.Duration, | ||
LocalDateTime: neo4j_driver_core_1.LocalDateTime, | ||
LocalTime: neo4j_driver_core_1.LocalTime, | ||
Time: neo4j_driver_core_1.Time, | ||
Integer: neo4j_driver_core_1.Integer | ||
const types = { | ||
Node, | ||
Relationship, | ||
UnboundRelationship, | ||
PathSegment, | ||
Path, | ||
Result, | ||
ResultSummary, | ||
Record, | ||
Point, | ||
Date, | ||
DateTime, | ||
Duration, | ||
LocalDateTime, | ||
LocalTime, | ||
Time, | ||
Integer | ||
}; | ||
exports.types = types; | ||
/** | ||
* Object containing string constants representing session access modes. | ||
*/ | ||
var session = { | ||
READ: READ, | ||
WRITE: WRITE | ||
const session = { | ||
READ, | ||
WRITE | ||
}; | ||
exports.session = session; | ||
/** | ||
* Object containing functions to work with {@link Integer} objects. | ||
*/ | ||
var integer = { | ||
toNumber: neo4j_driver_core_1.toNumber, | ||
toString: neo4j_driver_core_1.toString, | ||
inSafeRange: neo4j_driver_core_1.inSafeRange | ||
const integer = { | ||
toNumber, | ||
toString, | ||
inSafeRange | ||
}; | ||
exports.integer = integer; | ||
/** | ||
* Object containing functions to work with spatial types, like {@link Point}. | ||
*/ | ||
var spatial = { | ||
isPoint: neo4j_driver_core_1.isPoint | ||
const spatial = { | ||
isPoint | ||
}; | ||
exports.spatial = spatial; | ||
/** | ||
* Object containing functions to work with temporal types, like {@link Time} or {@link Duration}. | ||
*/ | ||
var temporal = { | ||
isDuration: neo4j_driver_core_1.isDuration, | ||
isLocalTime: neo4j_driver_core_1.isLocalTime, | ||
isTime: neo4j_driver_core_1.isTime, | ||
isDate: neo4j_driver_core_1.isDate, | ||
isLocalDateTime: neo4j_driver_core_1.isLocalDateTime, | ||
isDateTime: neo4j_driver_core_1.isDateTime | ||
const temporal = { | ||
isDuration, | ||
isLocalTime, | ||
isTime, | ||
isDate, | ||
isLocalDateTime, | ||
isDateTime | ||
}; | ||
exports.temporal = temporal; | ||
/** | ||
* Object containing functions to work with graph types, like {@link Node} or {@link Relationship}. | ||
*/ | ||
var graph = { | ||
isNode: neo4j_driver_core_1.isNode, | ||
isPath: neo4j_driver_core_1.isPath, | ||
isPathSegment: neo4j_driver_core_1.isPathSegment, | ||
isRelationship: neo4j_driver_core_1.isRelationship, | ||
isUnboundRelationship: neo4j_driver_core_1.isUnboundRelationship | ||
const graph = { | ||
isNode, | ||
isPath, | ||
isPathSegment, | ||
isRelationship, | ||
isUnboundRelationship | ||
}; | ||
exports.graph = graph; | ||
var forExport = { | ||
authTokenManagers: neo4j_driver_core_1.authTokenManagers, | ||
int: neo4j_driver_core_1.int, | ||
isInt: neo4j_driver_core_1.isInt, | ||
isPoint: neo4j_driver_core_1.isPoint, | ||
isDuration: neo4j_driver_core_1.isDuration, | ||
isLocalTime: neo4j_driver_core_1.isLocalTime, | ||
isTime: neo4j_driver_core_1.isTime, | ||
isDate: neo4j_driver_core_1.isDate, | ||
isLocalDateTime: neo4j_driver_core_1.isLocalDateTime, | ||
isDateTime: neo4j_driver_core_1.isDateTime, | ||
isNode: neo4j_driver_core_1.isNode, | ||
isPath: neo4j_driver_core_1.isPath, | ||
isPathSegment: neo4j_driver_core_1.isPathSegment, | ||
isRelationship: neo4j_driver_core_1.isRelationship, | ||
isUnboundRelationship: neo4j_driver_core_1.isUnboundRelationship, | ||
integer: integer, | ||
Neo4jError: neo4j_driver_core_1.Neo4jError, | ||
isRetriableError: neo4j_driver_core_1.isRetriableError, | ||
auth: neo4j_driver_core_1.auth, | ||
logging: logging_1.logging, | ||
types: types, | ||
session: session, | ||
error: neo4j_driver_core_1.error, | ||
graph: graph, | ||
spatial: spatial, | ||
temporal: temporal, | ||
Driver: neo4j_driver_core_1.Driver, | ||
Result: neo4j_driver_core_1.Result, | ||
Record: neo4j_driver_core_1.Record, | ||
ResultSummary: neo4j_driver_core_1.ResultSummary, | ||
Node: neo4j_driver_core_1.Node, | ||
Relationship: neo4j_driver_core_1.Relationship, | ||
UnboundRelationship: neo4j_driver_core_1.UnboundRelationship, | ||
PathSegment: neo4j_driver_core_1.PathSegment, | ||
Path: neo4j_driver_core_1.Path, | ||
Integer: neo4j_driver_core_1.Integer, | ||
Plan: neo4j_driver_core_1.Plan, | ||
ProfiledPlan: neo4j_driver_core_1.ProfiledPlan, | ||
QueryStatistics: neo4j_driver_core_1.QueryStatistics, | ||
Notification: neo4j_driver_core_1.Notification, | ||
ServerInfo: neo4j_driver_core_1.ServerInfo, | ||
Session: neo4j_driver_core_1.Session, | ||
Point: neo4j_driver_core_1.Point, | ||
Duration: neo4j_driver_core_1.Duration, | ||
LocalTime: neo4j_driver_core_1.LocalTime, | ||
Time: neo4j_driver_core_1.Time, | ||
Date: neo4j_driver_core_1.Date, | ||
LocalDateTime: neo4j_driver_core_1.LocalDateTime, | ||
DateTime: neo4j_driver_core_1.DateTime, | ||
ConnectionProvider: neo4j_driver_core_1.ConnectionProvider, | ||
Connection: neo4j_driver_core_1.Connection, | ||
bookmarkManager: neo4j_driver_core_1.bookmarkManager, | ||
resultTransformers: neo4j_driver_core_1.resultTransformers, | ||
notificationCategory: neo4j_driver_core_1.notificationCategory, | ||
notificationSeverityLevel: neo4j_driver_core_1.notificationSeverityLevel, | ||
wrapper: wrapper | ||
const forExport = { | ||
authTokenManagers, | ||
int, | ||
isInt, | ||
isPoint, | ||
isDuration, | ||
isLocalTime, | ||
isTime, | ||
isDate, | ||
isLocalDateTime, | ||
isDateTime, | ||
isNode, | ||
isPath, | ||
isPathSegment, | ||
isRelationship, | ||
isUnboundRelationship, | ||
integer, | ||
Neo4jError, | ||
isRetriableError, | ||
auth, | ||
logging, | ||
types, | ||
session, | ||
error, | ||
graph, | ||
spatial, | ||
temporal, | ||
Driver, | ||
Result, | ||
Record, | ||
ResultSummary, | ||
Node, | ||
Relationship, | ||
UnboundRelationship, | ||
PathSegment, | ||
Path, | ||
Integer, | ||
Plan, | ||
ProfiledPlan, | ||
QueryStatistics, | ||
Notification, | ||
ServerInfo, | ||
Session, | ||
Point, | ||
Duration, | ||
LocalTime, | ||
Time, | ||
Date, | ||
LocalDateTime, | ||
DateTime, | ||
ConnectionProvider, | ||
Connection, | ||
bookmarkManager, | ||
resultTransformers, | ||
notificationCategory, | ||
notificationSeverityLevel, | ||
wrapper | ||
}; | ||
exports.default = forExport; | ||
export { authTokenManagers, int, isInt, isPoint, isDuration, isLocalTime, isTime, isDate, isLocalDateTime, isDateTime, isNode, isPath, isPathSegment, isRelationship, isUnboundRelationship, integer, Neo4jError, isRetriableError, auth, logging, types, session, error, graph, spatial, temporal, Driver, Result, Record, ResultSummary, Node, Relationship, UnboundRelationship, PathSegment, Path, Integer, Plan, ProfiledPlan, QueryStatistics, Notification, ServerInfo, Session, Point, Duration, LocalTime, Time, Date, LocalDateTime, DateTime, ConnectionProvider, Connection, bookmarkManager, resultTransformers, notificationCategory, notificationSeverityLevel, wrapper }; | ||
export default forExport; |
@@ -1,4 +0,1 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.logging = void 0; | ||
/** | ||
@@ -9,9 +6,7 @@ * Object containing predefined logging configurations. These are expected to be used as values of the driver config's `logging` property. | ||
*/ | ||
exports.logging = { | ||
console: function (level) { | ||
export const logging = { | ||
console: (level) => { | ||
return { | ||
level: level, | ||
logger: function (level, message) { | ||
return console.log("".concat(Date.now(), " ").concat(level.toUpperCase(), " ").concat(message)); | ||
} | ||
level, | ||
logger: (level, message) => console.log(`${Date.now()} ${level.toUpperCase()} ${message}`) | ||
// Note: This 'logging' object is in its own file so we can easily access the global Date object here without conflicting | ||
@@ -18,0 +13,0 @@ // with the Neo4j Date class, and without relying on 'globalThis' which isn't compatible with Node 10. |
@@ -1,2 +0,1 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
export {}; |
@@ -1,21 +0,17 @@ | ||
"use strict"; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
var WrapperSessionImpl = /** @class */ (function () { | ||
function WrapperSessionImpl(session) { | ||
export default class WrapperSessionImpl { | ||
constructor(session) { | ||
this.session = session; | ||
} | ||
WrapperSessionImpl.prototype[Symbol.asyncDispose] = function () { | ||
[Symbol.asyncDispose]() { | ||
return this.close(); | ||
}; | ||
WrapperSessionImpl.prototype.run = function (query, parameters, transactionConfig) { | ||
} | ||
run(query, parameters, transactionConfig) { | ||
return this.session.run(query, parameters, transactionConfig); | ||
}; | ||
WrapperSessionImpl.prototype.lastBookmarks = function () { | ||
} | ||
lastBookmarks() { | ||
return this.session.lastBookmarks(); | ||
}; | ||
WrapperSessionImpl.prototype.close = function () { | ||
} | ||
close() { | ||
return this.session.close(); | ||
}; | ||
return WrapperSessionImpl; | ||
}()); | ||
exports.default = WrapperSessionImpl; | ||
} | ||
} |
@@ -1,34 +0,26 @@ | ||
"use strict"; | ||
var __importDefault = (this && this.__importDefault) || function (mod) { | ||
return (mod && mod.__esModule) ? mod : { "default": mod }; | ||
}; | ||
Object.defineProperty(exports, "__esModule", { value: true }); | ||
exports.WrapperImpl = void 0; | ||
var wrapper_session_impl_1 = __importDefault(require("./wrapper-session.impl")); | ||
var WrapperImpl = /** @class */ (function () { | ||
function WrapperImpl(driver) { | ||
import WrapperSessionImpl from "./wrapper-session.impl"; | ||
export class WrapperImpl { | ||
constructor(driver) { | ||
this.driver = driver; | ||
} | ||
WrapperImpl.prototype.close = function () { | ||
close() { | ||
return this.driver.close(); | ||
}; | ||
WrapperImpl.prototype.verifyConnectivity = function (config) { | ||
} | ||
verifyConnectivity(config) { | ||
validateDatabase(config); | ||
return this.driver.verifyConnectivity(config); | ||
}; | ||
WrapperImpl.prototype[Symbol.asyncDispose] = function () { | ||
} | ||
[Symbol.asyncDispose]() { | ||
return this.driver.close(); | ||
}; | ||
WrapperImpl.prototype.session = function (config) { | ||
} | ||
session(config) { | ||
validateDatabase(config); | ||
var session = this.driver.session(); | ||
return new wrapper_session_impl_1.default(session); | ||
}; | ||
return WrapperImpl; | ||
}()); | ||
exports.WrapperImpl = WrapperImpl; | ||
const session = this.driver.session(config); | ||
return new WrapperSessionImpl(session); | ||
} | ||
} | ||
function validateDatabase(config) { | ||
if (config.database == null || config.database === '') { | ||
throw new TypeError("database must be a non-empty string, but got ".concat(config.database)); | ||
throw new TypeError(`database must be a non-empty string, but got ${config.database}`); | ||
} | ||
} |
{ | ||
"name": "@neo4j-labs/experimental-query-api-wrapper", | ||
"version": "0.0.1-alpha01", | ||
"version": "0.0.1-alpha02", | ||
"description": "Experimental wrapper library to access Neo4j Database using Query API with a neo4j-driver-like interface.", | ||
@@ -10,5 +10,8 @@ "main": "lib/index.js", | ||
"build": "tsc -p tsconfig.build.json", | ||
"test": "jest --passWithNoTests", | ||
"prepublish": "downdoc README.adoc", | ||
"postpublish": "downdoc README.adoc", | ||
"test": "yarn test::unit && yarn test::integration", | ||
"test::watch": "jest --watch", | ||
"test::unit": "npm run test", | ||
"test::unit": "jest --passWithNoTests", | ||
"test::integration": "jest --passWithNoTests -c jest.integration.config.ts", | ||
"prepare": "npm run build", | ||
@@ -34,13 +37,16 @@ "clean": "rm -fr node_modules lib types" | ||
"@types/jest": "^29.5.3", | ||
"downdoc": "^1.0.2-stable", | ||
"fast-check": "^3.10.0", | ||
"jest": "^29.6.2", | ||
"testcontainers": "^8.16.0", | ||
"ts-jest": "^29.1.1", | ||
"ts-node": "10.9.2", | ||
"typescript": "^4.9.5" | ||
}, | ||
"dependencies": { | ||
"neo4j-driver-core": "5.21.0" | ||
"neo4j-driver-core": "5.23.0" | ||
}, | ||
"engines" : { | ||
"node" : ">=18.0.0" | ||
"engines": { | ||
"node": ">=18.0.0" | ||
} | ||
} |
{ | ||
"compilerOptions": { | ||
"target": "ES5", | ||
"lib": ["ES6"], | ||
"target": "ES2020", | ||
"lib": ["ES2020"], | ||
"noImplicitAny": true, | ||
@@ -6,0 +6,0 @@ "noImplicitReturns": true, |
@@ -18,3 +18,3 @@ /** | ||
import { ConnectionProvider, internal, AuthTokenManager, Connection, Releasable, types, ServerInfo } from "neo4j-driver-core"; | ||
type HttpScheme = 'http' | 'https'; | ||
import { HttpScheme } from "./connection.http"; | ||
export interface HttpConnectionProviderConfig { | ||
@@ -36,2 +36,4 @@ id: number; | ||
private _config; | ||
private _queryEndpoint?; | ||
private _discoveryPromise?; | ||
constructor(config: HttpConnectionProviderConfig); | ||
@@ -52,2 +54,1 @@ acquireConnection(param?: { | ||
} | ||
export {}; |
@@ -19,10 +19,14 @@ /** | ||
import { RunQueryConfig } from "neo4j-driver-core/types/connection"; | ||
type HttpScheme = 'http' | 'https'; | ||
export type HttpScheme = 'http' | 'https'; | ||
export interface HttpConnectionConfig { | ||
release: () => Promise<void>; | ||
auth: types.AuthToken; | ||
scheme: HttpScheme; | ||
queryEndpoint: string; | ||
address: internal.serverAddress.ServerAddress; | ||
database: string; | ||
config: types.InternalConfig; | ||
logger: internal.logger.Logger; | ||
errorHandler: (error: Error & { | ||
code: string; | ||
retriable: boolean; | ||
}) => Error; | ||
} | ||
@@ -32,10 +36,21 @@ export default class HttpConnection extends Connection { | ||
private _auth; | ||
private _scheme; | ||
private _queryEndpoint; | ||
private _address; | ||
private _database; | ||
private _config; | ||
private _abortController?; | ||
private _log?; | ||
private _id; | ||
private _errorHandler; | ||
constructor(config: HttpConnectionConfig); | ||
run(query: string, parameters?: Record<string, unknown> | undefined, config?: RunQueryConfig | undefined): internal.observer.ResultStreamObserver; | ||
private _handleAndReThrown; | ||
private _getTransactionApi; | ||
static discover({ scheme, address }: { | ||
scheme: HttpScheme; | ||
address: internal.serverAddress.ServerAddress; | ||
}): Promise<{ | ||
query: string; | ||
version: string; | ||
edition: string; | ||
}>; | ||
getProtocolVersion(): number; | ||
@@ -46,3 +61,3 @@ isOpen(): boolean; | ||
release(): Promise<void>; | ||
toString(): string; | ||
} | ||
export {}; |
@@ -17,12 +17,6 @@ /** | ||
*/ | ||
import { Node, Relationship, types, Integer, Time, Date, LocalTime, Point, DateTime, LocalDateTime, Duration, Path } from "neo4j-driver-core"; | ||
import { types } from "neo4j-driver-core"; | ||
import { RunQueryConfig } from "neo4j-driver-core/types/connection"; | ||
type RawQueryValueTypes = 'Null' | 'Boolean' | 'Integer' | 'Float' | 'String' | 'Time' | 'Date' | 'LocalTime' | 'ZonedDateTime' | 'OffsetDateTime' | 'LocalDateTime' | 'Duration' | 'Point' | 'Base64' | 'Map' | 'List' | 'Node' | 'Relationship' | 'Path'; | ||
type PointShape = { | ||
srid: number; | ||
x: string; | ||
y: string; | ||
z?: string; | ||
}; | ||
type NodeShape = { | ||
export type RawQueryValueTypes = 'Null' | 'Boolean' | 'Integer' | 'Float' | 'String' | 'Time' | 'Date' | 'LocalTime' | 'ZonedDateTime' | 'OffsetDateTime' | 'LocalDateTime' | 'Duration' | 'Point' | 'Base64' | 'Map' | 'List' | 'Node' | 'Relationship' | 'Path'; | ||
export type NodeShape = { | ||
_element_id: string; | ||
@@ -32,3 +26,3 @@ _labels: string[]; | ||
}; | ||
type RelationshipShape = { | ||
export type RelationshipShape = { | ||
_element_id: string; | ||
@@ -40,30 +34,30 @@ _start_node_element_id: string; | ||
}; | ||
type PathShape = (RawQueryRelationship | RawQueryNode)[]; | ||
type RawQueryValueDef<T extends RawQueryValueTypes, V extends unknown> = { | ||
export type PathShape = (RawQueryRelationship | RawQueryNode)[]; | ||
export type RawQueryValueDef<T extends RawQueryValueTypes, V extends unknown> = { | ||
$type: T; | ||
_value: V; | ||
}; | ||
type RawQueryNull = RawQueryValueDef<'Null', null>; | ||
type RawQueryBoolean = RawQueryValueDef<'Boolean', boolean>; | ||
type RawQueryInteger = RawQueryValueDef<'Integer', string>; | ||
type RawQueryFloat = RawQueryValueDef<'Float', string>; | ||
type RawQueryString = RawQueryValueDef<'String', string>; | ||
type RawQueryTime = RawQueryValueDef<'Time', string>; | ||
type RawQueryDate = RawQueryValueDef<'Date', string>; | ||
type RawQueryLocalTime = RawQueryValueDef<'LocalTime', string>; | ||
type RawQueryZonedDateTime = RawQueryValueDef<'ZonedDateTime', string>; | ||
type RawQueryOffsetDateTime = RawQueryValueDef<'OffsetDateTime', string>; | ||
type RawQueryLocalDateTime = RawQueryValueDef<'LocalDateTime', string>; | ||
type RawQueryDuration = RawQueryValueDef<'Duration', string>; | ||
type RawQueryPoint = RawQueryValueDef<'Point', PointShape>; | ||
type RawQueryBinary = RawQueryValueDef<'Base64', string>; | ||
interface RawQueryMap extends RawQueryValueDef<'Map', Record<string, RawQueryValue>> { | ||
export type RawQueryNull = RawQueryValueDef<'Null', null>; | ||
export type RawQueryBoolean = RawQueryValueDef<'Boolean', boolean>; | ||
export type RawQueryInteger = RawQueryValueDef<'Integer', string>; | ||
export type RawQueryFloat = RawQueryValueDef<'Float', string>; | ||
export type RawQueryString = RawQueryValueDef<'String', string>; | ||
export type RawQueryTime = RawQueryValueDef<'Time', string>; | ||
export type RawQueryDate = RawQueryValueDef<'Date', string>; | ||
export type RawQueryLocalTime = RawQueryValueDef<'LocalTime', string>; | ||
export type RawQueryZonedDateTime = RawQueryValueDef<'ZonedDateTime', string>; | ||
export type RawQueryOffsetDateTime = RawQueryValueDef<'OffsetDateTime', string>; | ||
export type RawQueryLocalDateTime = RawQueryValueDef<'LocalDateTime', string>; | ||
export type RawQueryDuration = RawQueryValueDef<'Duration', string>; | ||
export type RawQueryPoint = RawQueryValueDef<'Point', string>; | ||
export type RawQueryBinary = RawQueryValueDef<'Base64', string>; | ||
export interface RawQueryMap extends RawQueryValueDef<'Map', Record<string, RawQueryValue>> { | ||
} | ||
interface RawQueryList extends RawQueryValueDef<'List', RawQueryValue[]> { | ||
export interface RawQueryList extends RawQueryValueDef<'List', RawQueryValue[]> { | ||
} | ||
type RawQueryNode = RawQueryValueDef<'Node', NodeShape>; | ||
type RawQueryRelationship = RawQueryValueDef<'Relationship', RelationshipShape>; | ||
type RawQueryPath = RawQueryValueDef<'Path', PathShape>; | ||
type RawQueryValue = RawQueryNull | RawQueryBoolean | RawQueryInteger | RawQueryFloat | RawQueryString | RawQueryTime | RawQueryDate | RawQueryLocalTime | RawQueryZonedDateTime | RawQueryOffsetDateTime | RawQueryLocalDateTime | RawQueryDuration | RawQueryPoint | RawQueryBinary | RawQueryMap | RawQueryList | RawQueryNode | RawQueryRelationship | RawQueryPath; | ||
type Counters = { | ||
export type RawQueryNode = RawQueryValueDef<'Node', NodeShape>; | ||
export type RawQueryRelationship = RawQueryValueDef<'Relationship', RelationshipShape>; | ||
export type RawQueryPath = RawQueryValueDef<'Path', PathShape>; | ||
export type RawQueryValue = RawQueryNull | RawQueryBoolean | RawQueryInteger | RawQueryFloat | RawQueryString | RawQueryTime | RawQueryDate | RawQueryLocalTime | RawQueryZonedDateTime | RawQueryOffsetDateTime | RawQueryLocalDateTime | RawQueryDuration | RawQueryPoint | RawQueryBinary | RawQueryMap | RawQueryList | RawQueryNode | RawQueryRelationship | RawQueryPath; | ||
export type Counters = { | ||
containsUpdates: boolean; | ||
@@ -84,3 +78,3 @@ nodesCreated: number; | ||
}; | ||
type ProfiledQueryPlan = { | ||
export type ProfiledQueryPlan = { | ||
dbHits: number; | ||
@@ -94,11 +88,23 @@ records: number; | ||
operatorType: string; | ||
arguments: Record<string, unknown>; | ||
arguments: Record<string, RawQueryValue>; | ||
identifiers: string[]; | ||
children: ProfiledQueryPlan[]; | ||
}; | ||
type RawQueryData = { | ||
export type NotificationShape = { | ||
code: string; | ||
title: string; | ||
description: string; | ||
position: { | ||
offset: number; | ||
line: number; | ||
column: number; | ||
} | {}; | ||
severity: string; | ||
category: string; | ||
}; | ||
export type RawQueryData = { | ||
fields: string[]; | ||
values: RawQueryValue[]; | ||
values: RawQueryValue[][]; | ||
}; | ||
export type RawQueryResponse = { | ||
export type RawQuerySuccessResponse = { | ||
data: RawQueryData; | ||
@@ -108,37 +114,22 @@ counters: Counters; | ||
profiledQueryPlan?: ProfiledQueryPlan; | ||
errors?: []; | ||
notifications?: unknown[]; | ||
notifications?: NotificationShape[]; | ||
[str: string]: unknown; | ||
}; | ||
export type RawQueryError = { | ||
code: string; | ||
message: string; | ||
error?: string; | ||
}; | ||
export type RawQueryFailuresResponse = { | ||
errors: RawQueryError[]; | ||
}; | ||
export type RawQueryResponse = RawQuerySuccessResponse | RawQueryFailuresResponse; | ||
export declare class QueryResponseCodec { | ||
private _config; | ||
private _contentType; | ||
private _rawQueryResponse; | ||
constructor(_config: types.InternalConfig, _contentType: string, _rawQueryResponse: RawQueryResponse); | ||
get hasError(): boolean; | ||
get error(): Error; | ||
static of(config: types.InternalConfig, contentType: string, response: RawQueryResponse): QueryResponseCodec; | ||
get error(): Error | undefined; | ||
get keys(): string[]; | ||
get meta(): Record<string, unknown>; | ||
stream(): Generator<any[]>; | ||
get meta(): Record<string, unknown>; | ||
private _decodeStats; | ||
private _decodeProfile; | ||
private _decodeValue; | ||
_decodeInteger(value: string): Integer | number | bigint; | ||
_decodeFloat(value: string): number; | ||
_decodeTime(value: string): Time<Integer | bigint | number>; | ||
_decodeDate(value: string): Date<Integer | bigint | number>; | ||
_decodeLocalTime(value: string): LocalTime<Integer | bigint | number>; | ||
_decodeZonedDateTime(value: string): DateTime<Integer | bigint | number>; | ||
_decodeOffsetDateTime(value: string): DateTime<Integer | bigint | number>; | ||
_decodeLocalDateTime(value: string): LocalDateTime<Integer | bigint | number>; | ||
_decodeDuration(value: string): Duration<Integer | bigint | number>; | ||
_decodeMap(value: Record<string, RawQueryValue>): Record<string, unknown>; | ||
_decodePoint(value: PointShape): Point<Integer | bigint | number>; | ||
_decodeBase64(value: string): Uint8Array; | ||
_decodeList(value: RawQueryValue[]): unknown[]; | ||
_decodeNode(value: NodeShape): Node<bigint | number | Integer>; | ||
_decodeRelationship(value: RelationshipShape): Relationship<bigint | number | Integer>; | ||
_decodePath(value: PathShape): Path<bigint | number | Integer>; | ||
_normalizeInteger(integer: Integer): Integer | number | bigint; | ||
} | ||
export type QueryRequestCodecConfig = Pick<RunQueryConfig, 'bookmarks' | 'txConfig' | 'mode' | 'impersonatedUser'>; | ||
export declare class QueryRequestCodec { | ||
@@ -150,3 +141,4 @@ private _auth; | ||
private _body?; | ||
constructor(_auth: types.AuthToken, _query: string, _parameters?: Record<string, unknown> | undefined, _config?: RunQueryConfig | undefined); | ||
static of(auth: types.AuthToken, query: string, parameters?: Record<string, unknown> | undefined, config?: QueryRequestCodecConfig | undefined): QueryRequestCodec; | ||
private constructor(); | ||
get contentType(): string; | ||
@@ -159,2 +151,1 @@ get accept(): string; | ||
} | ||
export {}; |
@@ -38,2 +38,4 @@ /** | ||
private _server; | ||
private _haveRecordStreamed; | ||
private readonly _fsm; | ||
constructor(config: ResultStreamObserverConfig); | ||
@@ -45,9 +47,18 @@ get completed(): boolean; | ||
resume(): void; | ||
prepareToHandleSingleResponse: () => void; | ||
prepareToHandleSingleResponse(): void; | ||
markCompleted(): void; | ||
subscribe(observer: ResultObserver): void; | ||
onKeys(keys: any[]): void; | ||
_onKeys(keys: any[]): void; | ||
onNext(rawRecord: any[]): void; | ||
_onNext(rawRecord: any[]): void; | ||
onError(error: Error): void; | ||
_onError(error: Error): void; | ||
/** | ||
* | ||
* @param {any|false} meta The metadata returned from server. Or false, | ||
* if observer should complete with {} | ||
*/ | ||
onCompleted(meta: any): void; | ||
_onCompleted(meta: any): void; | ||
} |
@@ -26,3 +26,3 @@ /** | ||
type Logger = internal.logger.Logger; | ||
declare function wrapper(url: HttpUrl | string, authToken: AuthToken, config?: Config): Wrapper; | ||
declare function wrapper(url: HttpUrl | string, authToken: AuthToken | AuthTokenManager, config?: Config): Wrapper; | ||
/** | ||
@@ -219,2 +219,3 @@ * Object containing constructors for all neo4j types. | ||
eagerResultTransformer<Entries extends RecordShape<PropertyKey, any> = RecordShape<PropertyKey, any>>(): ResultTransformer<import("neo4j-driver-core").EagerResult<Entries>>; | ||
eager<Entries_1 extends RecordShape<PropertyKey, any> = RecordShape<PropertyKey, any>>(): ResultTransformer<import("neo4j-driver-core").EagerResult<Entries_1>>; | ||
mappedResultTransformer<R = Record<RecordShape<PropertyKey, any>, PropertyKey, RecordShape<PropertyKey, number>>, T = { | ||
@@ -228,2 +229,12 @@ records: R[]; | ||
}): ResultTransformer<T>; | ||
mapped<R_1 = Record<RecordShape<PropertyKey, any>, PropertyKey, RecordShape<PropertyKey, number>>, T_1 = { | ||
records: R_1[]; | ||
keys: string[]; | ||
summary: ResultSummary<Integer>; | ||
}>(config: { | ||
map?: ((rec: Record<RecordShape<PropertyKey, any>, PropertyKey, RecordShape<PropertyKey, number>>) => R_1 | undefined) | undefined; | ||
collect?: ((records: R_1[], summary: ResultSummary<Integer>, keys: string[]) => T_1) | undefined; | ||
}): ResultTransformer<T_1>; | ||
first<Entries_2 extends RecordShape<PropertyKey, any> = RecordShape<PropertyKey, any>>(): ResultTransformer<Record<Entries_2, keyof Entries_2, RecordShape<keyof Entries_2, number>> | undefined>; | ||
summary<T_2 extends import("neo4j-driver-core/types/graph-types").NumberOrInteger = Integer>(): ResultTransformer<ResultSummary<T_2>>; | ||
}; | ||
@@ -230,0 +241,0 @@ notificationCategory: { |
Sorry, the diff of this file is not supported yet
35
20.69%46
84%101903
-16.4%8
60%2189
-6.53%+ Added
- Removed
Updated