@sqlitecloud/drivers 1.0.245 → 1.0.255

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -26,7 +26,7 @@ return /******/ (() => { // webpackBootstrap
26
26
  /***/ (function(__unused_webpack_module, exports, __webpack_require__) {
27
27
 
28
28
  "use strict";
29
- eval("\n/**\n * connection-tls.ts - connection via tls socket and sqlitecloud protocol\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.SQLiteCloudTlsConnection = void 0;\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst connection_1 = __webpack_require__(/*! ./connection */ \"./lib/drivers/connection.js\");\nconst utilities_1 = __webpack_require__(/*! ./utilities */ \"./lib/drivers/utilities.js\");\nconst protocol_1 = __webpack_require__(/*! ./protocol */ \"./lib/drivers/protocol.js\");\nconst tls = __importStar(__webpack_require__(/*! tls */ \"?4235\"));\n/**\n * Implementation of SQLiteCloudConnection that connects to the database using specific tls APIs\n * that connect to native sockets or tls sockets and communicates via raw, binary protocol.\n */\nclass SQLiteCloudTlsConnection extends connection_1.SQLiteCloudConnection {\n constructor() {\n super(...arguments);\n // processCommands sets up empty buffers, results callback then send the command to the server via socket.write\n // onData is called when data is received, it will process the data until all data is retrieved for a response\n // when response is complete or there's an error, finish is called to call the results callback set by processCommands...\n // buffer to accumulate incoming data until an whole command is received and can be parsed\n this.buffer = Buffer.alloc(0);\n this.startedOn = new Date();\n this.pendingChunks = [];\n }\n /** True if connection is open */\n get connected() {\n return !!this.socket;\n }\n /* Opens a connection with the server and sends the initialization commands. Will throw in case of errors. */\n /* eslint-disable @typescript-eslint/no-unused-vars */\n connectTransport(config, callback) {\n console.assert(!this.connected, 'SQLiteCloudTlsConnection.connect - connection already established');\n if (this.config.verbose) {\n console.debug(`-> connecting ${config === null || config === void 0 ? void 0 : config.host}:${config === null || config === void 0 ? void 0 : config.port}`);\n }\n this.config = config;\n const initializationCommands = (0, utilities_1.getInitializationCommands)(config);\n // connect to plain socket, without encryption, only if insecure parameter specified\n // this option is mainly for testing purposes and is not available on production nodes\n // which would need to connect using tls and proper certificates as per code below\n const connectionOptions = {\n host: config.host,\n port: config.port,\n rejectUnauthorized: config.host != 'localhost',\n // Server name for the SNI (Server Name Indication) TLS extension.\n // https://r2.nodejs.org/docs/v6.11.4/api/tls.html#tls_class_tls_tlssocket\n servername: config.host\n };\n this.socket = tls.connect(connectionOptions, () => {\n var _a;\n if (this.config.verbose) {\n console.debug(`SQLiteCloudTlsConnection - connected to ${this.config.host}, authorized: ${(_a = this.socket) === null || _a === void 0 ? void 0 : _a.authorized}`);\n }\n this.transportCommands(initializationCommands, error => {\n if (this.config.verbose) {\n console.debug(`SQLiteCloudTlsConnection - initialized connection`);\n }\n callback === null || callback === void 0 ? void 0 : callback.call(this, error);\n });\n });\n this.socket.on('data', data => {\n this.processCommandsData(data);\n });\n this.socket.on('error', error => {\n this.close();\n this.processCommandsFinish(new types_1.SQLiteCloudError('Connection error', { errorCode: 'ERR_CONNECTION_ERROR', cause: error }));\n });\n this.socket.on('end', () => {\n this.close();\n if (this.processCallback)\n this.processCommandsFinish(new types_1.SQLiteCloudError('Server ended the connection', { errorCode: 'ERR_CONNECTION_ENDED' }));\n });\n this.socket.on('close', () => {\n this.close();\n this.processCommandsFinish(new types_1.SQLiteCloudError('Connection closed', { errorCode: 'ERR_CONNECTION_CLOSED' }));\n });\n return this;\n }\n /** Will send a command immediately (no queueing), return the rowset/result or throw an error */\n transportCommands(commands, callback) {\n var _a, _b, _c, _d, _e;\n // connection needs to be established?\n if (!this.socket) {\n callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Connection not established', { errorCode: 'ERR_CONNECTION_NOT_ESTABLISHED' }));\n return this;\n }\n // reset buffer and rowset chunks, define response callback\n this.buffer = Buffer.alloc(0);\n this.startedOn = new Date();\n this.processCallback = callback;\n this.executingCommands = commands;\n // compose commands following SCPC protocol\n const formattedCommands = (0, protocol_1.formatCommand)(commands);\n if ((_a = this.config) === null || _a === void 0 ? void 0 : _a.verbose) {\n console.debug(`-> ${formattedCommands}`);\n }\n const timeoutMs = (_c = (_b = this.config) === null || _b === void 0 ? void 0 : _b.timeout) !== null && _c !== void 0 ? _c : 0;\n if (timeoutMs > 0) {\n const timeout = setTimeout(() => {\n var _a;\n callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Connection timeout out', { errorCode: 'ERR_CONNECTION_TIMEOUT' }));\n (_a = this.socket) === null || _a === void 0 ? void 0 : _a.destroy();\n this.socket = undefined;\n }, timeoutMs);\n (_d = this.socket) === null || _d === void 0 ? void 0 : _d.write(formattedCommands, 'utf-8', () => {\n clearTimeout(timeout); // Clear the timeout on successful write\n });\n }\n else {\n (_e = this.socket) === null || _e === void 0 ? void 0 : _e.write(formattedCommands, 'utf-8');\n }\n return this;\n }\n /** Handles data received in response to an outbound command sent by processCommands */\n processCommandsData(data) {\n var _a, _b, _c, _d, _e, _f, _g;\n try {\n // append data to buffer as it arrives\n if (data.length && data.length > 0) {\n // console.debug(`processCommandsData - received ${data.length} bytes`)\n this.buffer = Buffer.concat([this.buffer, data]);\n }\n let dataType = (_a = this.buffer) === null || _a === void 0 ? void 0 : _a.subarray(0, 1).toString();\n if ((0, protocol_1.hasCommandLength)(dataType)) {\n const commandLength = (0, protocol_1.parseCommandLength)(this.buffer);\n const hasReceivedEntireCommand = this.buffer.length - this.buffer.indexOf(' ') - 1 >= commandLength ? true : false;\n if (hasReceivedEntireCommand) {\n if ((_b = this.config) === null || _b === void 0 ? void 0 : _b.verbose) {\n let bufferString = this.buffer.toString('utf8');\n if (bufferString.length > 1000) {\n bufferString = bufferString.substring(0, 100) + '...' + bufferString.substring(bufferString.length - 40);\n }\n const elapsedMs = new Date().getTime() - this.startedOn.getTime();\n console.debug(`<- ${bufferString} (${bufferString.length} bytes, ${elapsedMs}ms)`);\n }\n // need to decompress this buffer before decoding?\n if (dataType === protocol_1.CMD_COMPRESSED) {\n const decompressResults = (0, protocol_1.decompressBuffer)(this.buffer);\n if (decompressResults.dataType === protocol_1.CMD_ROWSET_CHUNK) {\n this.pendingChunks.push(decompressResults.buffer);\n this.buffer = decompressResults.remainingBuffer;\n this.processCommandsData(Buffer.alloc(0));\n return;\n }\n else {\n const { data } = (0, protocol_1.popData)(decompressResults.buffer);\n (_c = this.processCommandsFinish) === null || _c === void 0 ? void 0 : _c.call(this, null, data);\n }\n }\n else {\n if (dataType !== protocol_1.CMD_ROWSET_CHUNK) {\n const { data } = (0, protocol_1.popData)(this.buffer);\n (_d = this.processCommandsFinish) === null || _d === void 0 ? void 0 : _d.call(this, null, data);\n }\n else {\n const completeChunk = (0, protocol_1.bufferEndsWith)(this.buffer, protocol_1.ROWSET_CHUNKS_END);\n if (completeChunk) {\n const parsedData = (0, protocol_1.parseRowsetChunks)([...this.pendingChunks, this.buffer]);\n (_e = this.processCommandsFinish) === null || _e === void 0 ? void 0 : _e.call(this, null, parsedData);\n }\n }\n }\n }\n }\n else {\n // command with no explicit len so make sure that the final character is a space\n const lastChar = this.buffer.subarray(this.buffer.length - 1, this.buffer.length).toString('utf8');\n if (lastChar == ' ') {\n const { data } = (0, protocol_1.popData)(this.buffer);\n (_f = this.processCommandsFinish) === null || _f === void 0 ? void 0 : _f.call(this, null, data);\n }\n }\n }\n catch (error) {\n console.error(`processCommandsData - error: ${error}`);\n console.assert(error instanceof Error, 'An error occoured while processing data');\n if (error instanceof Error) {\n (_g = this.processCommandsFinish) === null || _g === void 0 ? void 0 : _g.call(this, error);\n }\n }\n }\n /** Completes a transaction initiated by processCommands */\n processCommandsFinish(error, result) {\n if (error) {\n if (this.processCallback) {\n console.error('processCommandsFinish - error', error);\n }\n else {\n console.warn('processCommandsFinish - error with no registered callback', error);\n }\n }\n if (this.processCallback) {\n this.processCallback(error, result);\n }\n this.buffer = Buffer.alloc(0);\n this.pendingChunks = [];\n }\n /** Disconnect immediately, release connection, no events. */\n close() {\n if (this.socket) {\n this.socket.removeAllListeners();\n this.socket.destroy();\n this.socket = undefined;\n }\n this.operations.clear();\n return this;\n }\n}\nexports.SQLiteCloudTlsConnection = SQLiteCloudTlsConnection;\nexports[\"default\"] = SQLiteCloudTlsConnection;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/connection-tls.js?");
29
+ eval("\n/**\n * connection-tls.ts - connection via tls socket and sqlitecloud protocol\n */\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\n}) : function(o, v) {\n o[\"default\"] = v;\n});\nvar __importStar = (this && this.__importStar) || function (mod) {\n if (mod && mod.__esModule) return mod;\n var result = {};\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n __setModuleDefault(result, mod);\n return result;\n};\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.SQLiteCloudTlsConnection = void 0;\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst connection_1 = __webpack_require__(/*! ./connection */ \"./lib/drivers/connection.js\");\nconst utilities_1 = __webpack_require__(/*! ./utilities */ \"./lib/drivers/utilities.js\");\nconst protocol_1 = __webpack_require__(/*! ./protocol */ \"./lib/drivers/protocol.js\");\n// explicitly importing buffer library to allow cross-platform support by replacing it\nconst buffer_1 = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\");\nconst tls = __importStar(__webpack_require__(/*! tls */ \"?4235\"));\n/**\n * Implementation of SQLiteCloudConnection that connects to the database using specific tls APIs\n * that connect to native sockets or tls sockets and communicates via raw, binary protocol.\n */\nclass SQLiteCloudTlsConnection extends connection_1.SQLiteCloudConnection {\n constructor() {\n super(...arguments);\n // processCommands sets up empty buffers, results callback then send the command to the server via socket.write\n // onData is called when data is received, it will process the data until all data is retrieved for a response\n // when response is complete or there's an error, finish is called to call the results callback set by processCommands...\n // buffer to accumulate incoming data until an whole command is received and can be parsed\n this.buffer = buffer_1.Buffer.alloc(0);\n this.startedOn = new Date();\n this.pendingChunks = [];\n }\n /** True if connection is open */\n get connected() {\n return !!this.socket;\n }\n /* Opens a connection with the server and sends the initialization commands. Will throw in case of errors. */\n /* eslint-disable @typescript-eslint/no-unused-vars */\n connectTransport(config, callback) {\n console.assert(!this.connected, 'SQLiteCloudTlsConnection.connect - connection already established');\n if (this.config.verbose) {\n console.debug(`-> connecting ${config === null || config === void 0 ? void 0 : config.host}:${config === null || config === void 0 ? void 0 : config.port}`);\n }\n this.config = config;\n const initializationCommands = (0, utilities_1.getInitializationCommands)(config);\n // connect to plain socket, without encryption, only if insecure parameter specified\n // this option is mainly for testing purposes and is not available on production nodes\n // which would need to connect using tls and proper certificates as per code below\n const connectionOptions = {\n host: config.host,\n port: config.port,\n rejectUnauthorized: config.host != 'localhost',\n // Server name for the SNI (Server Name Indication) TLS extension.\n // https://r2.nodejs.org/docs/v6.11.4/api/tls.html#tls_class_tls_tlssocket\n servername: config.host\n };\n // tls.connect in the react-native-tcp-socket library is tls.connectTLS\n let connector = tls.connect;\n // @ts-ignore\n if (typeof tls.connectTLS !== 'undefined') {\n // @ts-ignore\n connector = tls.connectTLS;\n }\n this.socket = connector(connectionOptions, () => {\n var _a;\n if (this.config.verbose) {\n console.debug(`SQLiteCloudTlsConnection - connected to ${this.config.host}, authorized: ${(_a = this.socket) === null || _a === void 0 ? void 0 : _a.authorized}`);\n }\n this.transportCommands(initializationCommands, error => {\n if (this.config.verbose) {\n console.debug(`SQLiteCloudTlsConnection - initialized connection`);\n }\n callback === null || callback === void 0 ? void 0 : callback.call(this, error);\n });\n });\n this.socket.on('data', data => {\n this.processCommandsData(data);\n });\n this.socket.on('error', error => {\n this.close();\n this.processCommandsFinish(new types_1.SQLiteCloudError('Connection error', { errorCode: 'ERR_CONNECTION_ERROR', cause: error }));\n });\n this.socket.on('end', () => {\n this.close();\n if (this.processCallback)\n this.processCommandsFinish(new types_1.SQLiteCloudError('Server ended the connection', { errorCode: 'ERR_CONNECTION_ENDED' }));\n });\n this.socket.on('close', () => {\n this.close();\n this.processCommandsFinish(new types_1.SQLiteCloudError('Connection closed', { errorCode: 'ERR_CONNECTION_CLOSED' }));\n });\n return this;\n }\n /** Will send a command immediately (no queueing), return the rowset/result or throw an error */\n transportCommands(commands, callback) {\n var _a, _b, _c, _d, _e;\n // connection needs to be established?\n if (!this.socket) {\n callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Connection not established', { errorCode: 'ERR_CONNECTION_NOT_ESTABLISHED' }));\n return this;\n }\n // reset buffer and rowset chunks, define response callback\n this.buffer = buffer_1.Buffer.alloc(0);\n this.startedOn = new Date();\n this.processCallback = callback;\n this.executingCommands = commands;\n // compose commands following SCPC protocol\n const formattedCommands = (0, protocol_1.formatCommand)(commands);\n if ((_a = this.config) === null || _a === void 0 ? void 0 : _a.verbose) {\n console.debug(`-> ${formattedCommands}`);\n }\n const timeoutMs = (_c = (_b = this.config) === null || _b === void 0 ? void 0 : _b.timeout) !== null && _c !== void 0 ? _c : 0;\n if (timeoutMs > 0) {\n const timeout = setTimeout(() => {\n var _a;\n callback === null || callback === void 0 ? void 0 : callback.call(this, new types_1.SQLiteCloudError('Connection timeout out', { errorCode: 'ERR_CONNECTION_TIMEOUT' }));\n (_a = this.socket) === null || _a === void 0 ? void 0 : _a.destroy();\n this.socket = undefined;\n }, timeoutMs);\n (_d = this.socket) === null || _d === void 0 ? void 0 : _d.write(formattedCommands, 'utf-8', () => {\n clearTimeout(timeout); // Clear the timeout on successful write\n });\n }\n else {\n (_e = this.socket) === null || _e === void 0 ? void 0 : _e.write(formattedCommands, 'utf-8');\n }\n return this;\n }\n /** Handles data received in response to an outbound command sent by processCommands */\n processCommandsData(data) {\n var _a, _b, _c, _d, _e, _f, _g;\n try {\n // append data to buffer as it arrives\n if (data.length && data.length > 0) {\n // console.debug(`processCommandsData - received ${data.length} bytes`)\n this.buffer = buffer_1.Buffer.concat([this.buffer, data]);\n }\n let dataType = (_a = this.buffer) === null || _a === void 0 ? void 0 : _a.subarray(0, 1).toString();\n if ((0, protocol_1.hasCommandLength)(dataType)) {\n const commandLength = (0, protocol_1.parseCommandLength)(this.buffer);\n const hasReceivedEntireCommand = this.buffer.length - this.buffer.indexOf(' ') - 1 >= commandLength ? true : false;\n if (hasReceivedEntireCommand) {\n if ((_b = this.config) === null || _b === void 0 ? void 0 : _b.verbose) {\n let bufferString = this.buffer.toString('utf8');\n if (bufferString.length > 1000) {\n bufferString = bufferString.substring(0, 100) + '...' + bufferString.substring(bufferString.length - 40);\n }\n const elapsedMs = new Date().getTime() - this.startedOn.getTime();\n console.debug(`<- ${bufferString} (${bufferString.length} bytes, ${elapsedMs}ms)`);\n }\n // need to decompress this buffer before decoding?\n if (dataType === protocol_1.CMD_COMPRESSED) {\n const decompressResults = (0, protocol_1.decompressBuffer)(this.buffer);\n if (decompressResults.dataType === protocol_1.CMD_ROWSET_CHUNK) {\n this.pendingChunks.push(decompressResults.buffer);\n this.buffer = decompressResults.remainingBuffer;\n this.processCommandsData(buffer_1.Buffer.alloc(0));\n return;\n }\n else {\n const { data } = (0, protocol_1.popData)(decompressResults.buffer);\n (_c = this.processCommandsFinish) === null || _c === void 0 ? void 0 : _c.call(this, null, data);\n }\n }\n else {\n if (dataType !== protocol_1.CMD_ROWSET_CHUNK) {\n const { data } = (0, protocol_1.popData)(this.buffer);\n (_d = this.processCommandsFinish) === null || _d === void 0 ? void 0 : _d.call(this, null, data);\n }\n else {\n const completeChunk = (0, protocol_1.bufferEndsWith)(this.buffer, protocol_1.ROWSET_CHUNKS_END);\n if (completeChunk) {\n const parsedData = (0, protocol_1.parseRowsetChunks)([...this.pendingChunks, this.buffer]);\n (_e = this.processCommandsFinish) === null || _e === void 0 ? void 0 : _e.call(this, null, parsedData);\n }\n }\n }\n }\n }\n else {\n // command with no explicit len so make sure that the final character is a space\n const lastChar = this.buffer.subarray(this.buffer.length - 1, this.buffer.length).toString('utf8');\n if (lastChar == ' ') {\n const { data } = (0, protocol_1.popData)(this.buffer);\n (_f = this.processCommandsFinish) === null || _f === void 0 ? void 0 : _f.call(this, null, data);\n }\n }\n }\n catch (error) {\n console.error(`processCommandsData - error: ${error}`);\n console.assert(error instanceof Error, 'An error occoured while processing data');\n if (error instanceof Error) {\n (_g = this.processCommandsFinish) === null || _g === void 0 ? void 0 : _g.call(this, error);\n }\n }\n }\n /** Completes a transaction initiated by processCommands */\n processCommandsFinish(error, result) {\n if (error) {\n if (this.processCallback) {\n console.error('processCommandsFinish - error', error);\n }\n else {\n console.warn('processCommandsFinish - error with no registered callback', error);\n }\n }\n if (this.processCallback) {\n this.processCallback(error, result);\n }\n this.buffer = buffer_1.Buffer.alloc(0);\n this.pendingChunks = [];\n }\n /** Disconnect immediately, release connection, no events. */\n close() {\n if (this.socket) {\n this.socket.removeAllListeners();\n this.socket.destroy();\n this.socket = undefined;\n }\n this.operations.clear();\n return this;\n }\n}\nexports.SQLiteCloudTlsConnection = SQLiteCloudTlsConnection;\nexports[\"default\"] = SQLiteCloudTlsConnection;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/connection-tls.js?");
30
30
 
31
31
  /***/ }),
32
32
 
@@ -70,7 +70,7 @@ eval("\n//\n// database.ts - database driver api, implements and extends sqlite3
70
70
  /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
71
71
 
72
72
  "use strict";
73
- eval("\n//\n// protocol.ts - low level protocol handling for SQLiteCloud transport\n//\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.formatCommand = exports.popData = exports.parseRowsetChunks = exports.bufferEndsWith = exports.bufferStartsWith = exports.parseRowsetHeader = exports.parseArray = exports.parseError = exports.decompressBuffer = exports.parseCommandLength = exports.hasCommandLength = exports.ROWSET_CHUNKS_END = exports.CMD_PUBSUB = exports.CMD_ARRAY = exports.CMD_COMMAND = exports.CMD_COMPRESSED = exports.CMD_BLOB = exports.CMD_NULL = exports.CMD_JSON = exports.CMD_ROWSET_CHUNK = exports.CMD_ROWSET = exports.CMD_FLOAT = exports.CMD_INT = exports.CMD_ERROR = exports.CMD_ZEROSTRING = exports.CMD_STRING = void 0;\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst rowset_1 = __webpack_require__(/*! ./rowset */ \"./lib/drivers/rowset.js\");\n// https://www.npmjs.com/package/lz4js\nconst lz4 = __webpack_require__(/*! lz4js */ \"./node_modules/lz4js/lz4.js\");\n// The server communicates with clients via commands defined in\n// SQLiteCloud Server Protocol (SCSP), see more at:\n// https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md\nexports.CMD_STRING = '+';\nexports.CMD_ZEROSTRING = '!';\nexports.CMD_ERROR = '-';\nexports.CMD_INT = ':';\nexports.CMD_FLOAT = ',';\nexports.CMD_ROWSET = '*';\nexports.CMD_ROWSET_CHUNK = '/';\nexports.CMD_JSON = '#';\nexports.CMD_NULL = '_';\nexports.CMD_BLOB = '$';\nexports.CMD_COMPRESSED = '%';\nexports.CMD_COMMAND = '^';\nexports.CMD_ARRAY = '=';\n// const CMD_RAWJSON = '{'\nexports.CMD_PUBSUB = '|';\n// const CMD_RECONNECT = '@'\n// To mark the end of the Rowset, the special string /LEN 0 0 0 is sent (LEN is always 6 in this case)\n// https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md#scsp-rowset-chunk\nexports.ROWSET_CHUNKS_END = '/6 0 0 0 ';\n//\n// utility functions\n//\n/** Analyze first character to check if corresponding data type has LEN */\nfunction hasCommandLength(firstCharacter) {\n return firstCharacter == exports.CMD_INT || firstCharacter == exports.CMD_FLOAT || firstCharacter == exports.CMD_NULL ? false : true;\n}\nexports.hasCommandLength = hasCommandLength;\n/** Analyze a command with explict LEN and extract it */\nfunction parseCommandLength(data) {\n return parseInt(data.subarray(1, data.indexOf(' ')).toString('utf8'));\n}\nexports.parseCommandLength = parseCommandLength;\n/** Receive a compressed buffer, decompress with lz4, return buffer and datatype */\nfunction decompressBuffer(buffer) {\n // https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md#scsp-compression\n // jest test/database.test.ts -t \"select large result set\"\n // starts with %<commandLength> <compressed> <uncompressed>\n const spaceIndex = buffer.indexOf(' ');\n const commandLength = parseInt(buffer.subarray(1, spaceIndex).toString('utf8'));\n let commandBuffer = buffer.subarray(spaceIndex + 1, spaceIndex + 1 + commandLength);\n const remainingBuffer = buffer.subarray(spaceIndex + 1 + commandLength);\n // extract compressed + decompressed size\n const compressedSize = parseInt(commandBuffer.subarray(0, commandBuffer.indexOf(' ') + 1).toString('utf8'));\n commandBuffer = commandBuffer.subarray(commandBuffer.indexOf(' ') + 1);\n const decompressedSize = parseInt(commandBuffer.subarray(0, commandBuffer.indexOf(' ') + 1).toString('utf8'));\n commandBuffer = commandBuffer.subarray(commandBuffer.indexOf(' ') + 1);\n // extract compressed dataType\n const dataType = commandBuffer.subarray(0, 1).toString('utf8');\n let decompressedBuffer = Buffer.alloc(decompressedSize);\n const compressedBuffer = commandBuffer.subarray(commandBuffer.length - compressedSize);\n // lz4js library is javascript and doesn't have types so we silence the type check\n // eslint-disable-next-line\n const decompressionResult = lz4.decompressBlock(compressedBuffer, decompressedBuffer, 0, compressedSize, 0);\n // the entire command is composed of the header (which is not compressed) + the decompressed block\n decompressedBuffer = Buffer.concat([commandBuffer.subarray(0, commandBuffer.length - compressedSize), decompressedBuffer]);\n if (decompressionResult <= 0 || decompressionResult !== decompressedSize) {\n throw new Error(`lz4 decompression error at offset ${decompressionResult}`);\n }\n return { buffer: decompressedBuffer, dataType, remainingBuffer };\n}\nexports.decompressBuffer = decompressBuffer;\n/** Parse error message or extended error message */\nfunction parseError(buffer, spaceIndex) {\n const errorBuffer = buffer.subarray(spaceIndex + 1);\n const errorString = errorBuffer.toString('utf8');\n const parts = errorString.split(' ');\n let errorCodeStr = parts.shift() || '0'; // Default errorCode is '0' if not present\n let extErrCodeStr = '0'; // Default extended error code\n let offsetCodeStr = '-1'; // Default offset code\n // Split the errorCode by ':' to check for extended error codes\n const errorCodeParts = errorCodeStr.split(':');\n errorCodeStr = errorCodeParts[0];\n if (errorCodeParts.length > 1) {\n extErrCodeStr = errorCodeParts[1];\n if (errorCodeParts.length > 2) {\n offsetCodeStr = errorCodeParts[2];\n }\n }\n // Rest of the error string is the error message\n const errorMessage = parts.join(' ');\n // Parse error codes to integers safely, defaulting to 0 if NaN\n const errorCode = parseInt(errorCodeStr);\n const extErrCode = parseInt(extErrCodeStr);\n const offsetCode = parseInt(offsetCodeStr);\n // create an Error object and add the custom properties\n throw new types_1.SQLiteCloudError(errorMessage, {\n errorCode: errorCode.toString(),\n externalErrorCode: extErrCode.toString(),\n offsetCode\n });\n}\nexports.parseError = parseError;\n/** Parse an array of items (each of which will be parsed by type separately) */\nfunction parseArray(buffer, spaceIndex) {\n const parsedData = [];\n const array = buffer.subarray(spaceIndex + 1, buffer.length);\n const numberOfItems = parseInt(array.subarray(0, spaceIndex - 2).toString('utf8'));\n let arrayItems = array.subarray(array.indexOf(' ') + 1, array.length);\n for (let i = 0; i < numberOfItems; i++) {\n const { data, fwdBuffer: buffer } = popData(arrayItems);\n parsedData.push(data);\n arrayItems = buffer;\n }\n return parsedData;\n}\nexports.parseArray = parseArray;\n/** Parse header in a rowset or chunk of a chunked rowset */\nfunction parseRowsetHeader(buffer) {\n const index = parseInt(buffer.subarray(0, buffer.indexOf(':') + 1).toString());\n buffer = buffer.subarray(buffer.indexOf(':') + 1);\n // extract rowset header\n const { data, fwdBuffer } = popIntegers(buffer, 3);\n const result = {\n index,\n metadata: {\n version: data[0],\n numberOfRows: data[1],\n numberOfColumns: data[2],\n columns: []\n },\n fwdBuffer\n };\n // console.debug(`parseRowsetHeader`, result)\n return result;\n}\nexports.parseRowsetHeader = parseRowsetHeader;\n/** Extract column names and, optionally, more metadata out of a rowset's header */\nfunction parseRowsetColumnsMetadata(buffer, metadata) {\n function popForward() {\n const { data, fwdBuffer: fwdBuffer } = popData(buffer); // buffer in parent scope\n buffer = fwdBuffer;\n return data;\n }\n for (let i = 0; i < metadata.numberOfColumns; i++) {\n metadata.columns.push({ name: popForward() });\n }\n // extract additional metadata if rowset has version 2\n if (metadata.version == 2) {\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].type = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].database = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].table = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].column = popForward(); // original column name\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].notNull = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].primaryKey = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].autoIncrement = popForward();\n }\n return buffer;\n}\n/** Parse a regular rowset (no chunks) */\nfunction parseRowset(buffer, spaceIndex) {\n buffer = buffer.subarray(spaceIndex + 1, buffer.length);\n const { metadata, fwdBuffer } = parseRowsetHeader(buffer);\n buffer = parseRowsetColumnsMetadata(fwdBuffer, metadata);\n // decode each rowset item\n const data = [];\n for (let j = 0; j < metadata.numberOfRows * metadata.numberOfColumns; j++) {\n const { data: rowData, fwdBuffer } = popData(buffer);\n data.push(rowData);\n buffer = fwdBuffer;\n }\n console.assert(data && data.length === metadata.numberOfRows * metadata.numberOfColumns, 'SQLiteCloudConnection.parseRowset - invalid rowset data');\n return new rowset_1.SQLiteCloudRowset(metadata, data);\n}\nfunction bufferStartsWith(buffer, prefix) {\n return buffer.length >= prefix.length && buffer.subarray(0, prefix.length).toString('utf8') === prefix;\n}\nexports.bufferStartsWith = bufferStartsWith;\nfunction bufferEndsWith(buffer, suffix) {\n return buffer.length >= suffix.length && buffer.subarray(buffer.length - suffix.length, buffer.length).toString('utf8') === suffix;\n}\nexports.bufferEndsWith = bufferEndsWith;\n/**\n * Parse a chunk of a chunked rowset command, eg:\n * *LEN 0:VERS NROWS NCOLS DATA\n * @see https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md#scsp-rowset-chunk\n */\nfunction parseRowsetChunks(buffers) {\n let buffer = Buffer.concat(buffers);\n if (!bufferStartsWith(buffer, exports.CMD_ROWSET_CHUNK) || !bufferEndsWith(buffer, exports.ROWSET_CHUNKS_END)) {\n throw new Error('SQLiteCloudConnection.parseRowsetChunks - invalid chunks buffer');\n }\n let metadata = { version: 1, numberOfColumns: 0, numberOfRows: 0, columns: [] };\n const data = [];\n // validate and skip data type\n const dataType = buffer.subarray(0, 1).toString();\n if (dataType !== exports.CMD_ROWSET_CHUNK)\n throw new Error(`parseRowsetChunks - dataType: ${dataType} should be CMD_ROWSET_CHUNK`);\n buffer = buffer.subarray(buffer.indexOf(' ') + 1);\n while (buffer.length > 0 && !bufferStartsWith(buffer, exports.ROWSET_CHUNKS_END)) {\n // chunk header, eg: 0:VERS NROWS NCOLS\n const { index: chunkIndex, metadata: chunkMetadata, fwdBuffer } = parseRowsetHeader(buffer);\n buffer = fwdBuffer;\n // first chunk? extract columns metadata\n if (chunkIndex === 1) {\n metadata = chunkMetadata;\n buffer = parseRowsetColumnsMetadata(buffer, metadata);\n }\n else {\n metadata.numberOfRows += chunkMetadata.numberOfRows;\n }\n // extract single rowset row\n for (let k = 0; k < chunkMetadata.numberOfRows * metadata.numberOfColumns; k++) {\n const { data: itemData, fwdBuffer } = popData(buffer);\n data.push(itemData);\n buffer = fwdBuffer;\n }\n }\n console.assert(data && data.length === metadata.numberOfRows * metadata.numberOfColumns, 'parseRowsetChunks - invalid rowset data');\n const rowset = new rowset_1.SQLiteCloudRowset(metadata, data);\n // console.debug(`parseRowsetChunks - ${rowset.numberOfRows} rows, ${rowset.numberOfColumns} columns`)\n return rowset;\n}\nexports.parseRowsetChunks = parseRowsetChunks;\n/** Pop one or more space separated integers from beginning of buffer, move buffer forward */\nfunction popIntegers(buffer, numberOfIntegers = 1) {\n const data = [];\n for (let i = 0; i < numberOfIntegers; i++) {\n const spaceIndex = buffer.indexOf(' ');\n data[i] = parseInt(buffer.subarray(0, spaceIndex).toString());\n buffer = buffer.subarray(spaceIndex + 1);\n }\n return { data, fwdBuffer: buffer };\n}\n/** Parse command, extract its data, return the data and the buffer moved to the first byte after the command */\nfunction popData(buffer) {\n function popResults(data) {\n const fwdBuffer = buffer.subarray(commandEnd);\n return { data, fwdBuffer };\n }\n // first character is the data type\n console.assert(buffer && buffer instanceof Buffer);\n let dataType = buffer.subarray(0, 1).toString('utf8');\n if (dataType == exports.CMD_COMPRESSED)\n throw new Error('Compressed data should be decompressed before parsing');\n if (dataType == exports.CMD_ROWSET_CHUNK)\n throw new Error('Chunked data should be parsed by parseRowsetChunks');\n let spaceIndex = buffer.indexOf(' ');\n if (spaceIndex === -1) {\n spaceIndex = buffer.length - 1;\n }\n let commandEnd = -1, commandLength = -1;\n if (dataType === exports.CMD_INT || dataType === exports.CMD_FLOAT || dataType === exports.CMD_NULL) {\n commandEnd = spaceIndex + 1;\n }\n else {\n commandLength = parseInt(buffer.subarray(1, spaceIndex).toString());\n commandEnd = spaceIndex + 1 + commandLength;\n }\n // console.debug(`popData - dataType: ${dataType}, spaceIndex: ${spaceIndex}, commandLength: ${commandLength}, commandEnd: ${commandEnd}`)\n switch (dataType) {\n case exports.CMD_INT:\n return popResults(parseInt(buffer.subarray(1, spaceIndex).toString()));\n case exports.CMD_FLOAT:\n return popResults(parseFloat(buffer.subarray(1, spaceIndex).toString()));\n case exports.CMD_NULL:\n return popResults(null);\n case exports.CMD_STRING:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));\n case exports.CMD_ZEROSTRING:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd - 1).toString('utf8'));\n case exports.CMD_COMMAND:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));\n case exports.CMD_PUBSUB:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));\n case exports.CMD_JSON:\n return popResults(JSON.parse(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8')));\n case exports.CMD_BLOB:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd));\n case exports.CMD_ARRAY:\n return popResults(parseArray(buffer, spaceIndex));\n case exports.CMD_ROWSET:\n return popResults(parseRowset(buffer, spaceIndex));\n case exports.CMD_ERROR:\n parseError(buffer, spaceIndex); // throws custom error\n break;\n }\n const msg = `popData - Data type: ${Number(dataType)} '${dataType}' is not defined in SCSP, spaceIndex: ${spaceIndex}, commandLength: ${commandLength}, commandEnd: ${commandEnd}`;\n console.error(msg);\n throw new TypeError(msg);\n}\nexports.popData = popData;\n/** Format a command to be sent via SCSP protocol */\nfunction formatCommand(command) {\n const commandLength = Buffer.byteLength(command, 'utf-8');\n return `+${commandLength} ${command}`;\n}\nexports.formatCommand = formatCommand;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/protocol.js?");
73
+ eval("\n//\n// protocol.ts - low level protocol handling for SQLiteCloud transport\n//\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.formatCommand = exports.popData = exports.parseRowsetChunks = exports.bufferEndsWith = exports.bufferStartsWith = exports.parseRowsetHeader = exports.parseArray = exports.parseError = exports.decompressBuffer = exports.parseCommandLength = exports.hasCommandLength = exports.ROWSET_CHUNKS_END = exports.CMD_PUBSUB = exports.CMD_ARRAY = exports.CMD_COMMAND = exports.CMD_COMPRESSED = exports.CMD_BLOB = exports.CMD_NULL = exports.CMD_JSON = exports.CMD_ROWSET_CHUNK = exports.CMD_ROWSET = exports.CMD_FLOAT = exports.CMD_INT = exports.CMD_ERROR = exports.CMD_ZEROSTRING = exports.CMD_STRING = void 0;\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst rowset_1 = __webpack_require__(/*! ./rowset */ \"./lib/drivers/rowset.js\");\n// explicitly importing buffer library to allow cross-platform support by replacing it\nconst buffer_1 = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\");\n// https://www.npmjs.com/package/lz4js\nconst lz4 = __webpack_require__(/*! lz4js */ \"./node_modules/lz4js/lz4.js\");\n// The server communicates with clients via commands defined in\n// SQLiteCloud Server Protocol (SCSP), see more at:\n// https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md\nexports.CMD_STRING = '+';\nexports.CMD_ZEROSTRING = '!';\nexports.CMD_ERROR = '-';\nexports.CMD_INT = ':';\nexports.CMD_FLOAT = ',';\nexports.CMD_ROWSET = '*';\nexports.CMD_ROWSET_CHUNK = '/';\nexports.CMD_JSON = '#';\nexports.CMD_NULL = '_';\nexports.CMD_BLOB = '$';\nexports.CMD_COMPRESSED = '%';\nexports.CMD_COMMAND = '^';\nexports.CMD_ARRAY = '=';\n// const CMD_RAWJSON = '{'\nexports.CMD_PUBSUB = '|';\n// const CMD_RECONNECT = '@'\n// To mark the end of the Rowset, the special string /LEN 0 0 0 is sent (LEN is always 6 in this case)\n// https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md#scsp-rowset-chunk\nexports.ROWSET_CHUNKS_END = '/6 0 0 0 ';\n//\n// utility functions\n//\n/** Analyze first character to check if corresponding data type has LEN */\nfunction hasCommandLength(firstCharacter) {\n return firstCharacter == exports.CMD_INT || firstCharacter == exports.CMD_FLOAT || firstCharacter == exports.CMD_NULL ? false : true;\n}\nexports.hasCommandLength = hasCommandLength;\n/** Analyze a command with explict LEN and extract it */\nfunction parseCommandLength(data) {\n return parseInt(data.subarray(1, data.indexOf(' ')).toString('utf8'));\n}\nexports.parseCommandLength = parseCommandLength;\n/** Receive a compressed buffer, decompress with lz4, return buffer and datatype */\nfunction decompressBuffer(buffer) {\n // https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md#scsp-compression\n // jest test/database.test.ts -t \"select large result set\"\n // starts with %<commandLength> <compressed> <uncompressed>\n const spaceIndex = buffer.indexOf(' ');\n const commandLength = parseInt(buffer.subarray(1, spaceIndex).toString('utf8'));\n let commandBuffer = buffer.subarray(spaceIndex + 1, spaceIndex + 1 + commandLength);\n const remainingBuffer = buffer.subarray(spaceIndex + 1 + commandLength);\n // extract compressed + decompressed size\n const compressedSize = parseInt(commandBuffer.subarray(0, commandBuffer.indexOf(' ') + 1).toString('utf8'));\n commandBuffer = commandBuffer.subarray(commandBuffer.indexOf(' ') + 1);\n const decompressedSize = parseInt(commandBuffer.subarray(0, commandBuffer.indexOf(' ') + 1).toString('utf8'));\n commandBuffer = commandBuffer.subarray(commandBuffer.indexOf(' ') + 1);\n // extract compressed dataType\n const dataType = commandBuffer.subarray(0, 1).toString('utf8');\n let decompressedBuffer = buffer_1.Buffer.alloc(decompressedSize);\n const compressedBuffer = commandBuffer.subarray(commandBuffer.length - compressedSize);\n // lz4js library is javascript and doesn't have types so we silence the type check\n // eslint-disable-next-line\n const decompressionResult = lz4.decompressBlock(compressedBuffer, decompressedBuffer, 0, compressedSize, 0);\n // the entire command is composed of the header (which is not compressed) + the decompressed block\n decompressedBuffer = buffer_1.Buffer.concat([commandBuffer.subarray(0, commandBuffer.length - compressedSize), decompressedBuffer]);\n if (decompressionResult <= 0 || decompressionResult !== decompressedSize) {\n throw new Error(`lz4 decompression error at offset ${decompressionResult}`);\n }\n return { buffer: decompressedBuffer, dataType, remainingBuffer };\n}\nexports.decompressBuffer = decompressBuffer;\n/** Parse error message or extended error message */\nfunction parseError(buffer, spaceIndex) {\n const errorBuffer = buffer.subarray(spaceIndex + 1);\n const errorString = errorBuffer.toString('utf8');\n const parts = errorString.split(' ');\n let errorCodeStr = parts.shift() || '0'; // Default errorCode is '0' if not present\n let extErrCodeStr = '0'; // Default extended error code\n let offsetCodeStr = '-1'; // Default offset code\n // Split the errorCode by ':' to check for extended error codes\n const errorCodeParts = errorCodeStr.split(':');\n errorCodeStr = errorCodeParts[0];\n if (errorCodeParts.length > 1) {\n extErrCodeStr = errorCodeParts[1];\n if (errorCodeParts.length > 2) {\n offsetCodeStr = errorCodeParts[2];\n }\n }\n // Rest of the error string is the error message\n const errorMessage = parts.join(' ');\n // Parse error codes to integers safely, defaulting to 0 if NaN\n const errorCode = parseInt(errorCodeStr);\n const extErrCode = parseInt(extErrCodeStr);\n const offsetCode = parseInt(offsetCodeStr);\n // create an Error object and add the custom properties\n throw new types_1.SQLiteCloudError(errorMessage, {\n errorCode: errorCode.toString(),\n externalErrorCode: extErrCode.toString(),\n offsetCode\n });\n}\nexports.parseError = parseError;\n/** Parse an array of items (each of which will be parsed by type separately) */\nfunction parseArray(buffer, spaceIndex) {\n const parsedData = [];\n const array = buffer.subarray(spaceIndex + 1, buffer.length);\n const numberOfItems = parseInt(array.subarray(0, spaceIndex - 2).toString('utf8'));\n let arrayItems = array.subarray(array.indexOf(' ') + 1, array.length);\n for (let i = 0; i < numberOfItems; i++) {\n const { data, fwdBuffer: buffer } = popData(arrayItems);\n parsedData.push(data);\n arrayItems = buffer;\n }\n return parsedData;\n}\nexports.parseArray = parseArray;\n/** Parse header in a rowset or chunk of a chunked rowset */\nfunction parseRowsetHeader(buffer) {\n const index = parseInt(buffer.subarray(0, buffer.indexOf(':') + 1).toString());\n buffer = buffer.subarray(buffer.indexOf(':') + 1);\n // extract rowset header\n const { data, fwdBuffer } = popIntegers(buffer, 3);\n const result = {\n index,\n metadata: {\n version: data[0],\n numberOfRows: data[1],\n numberOfColumns: data[2],\n columns: []\n },\n fwdBuffer\n };\n // console.debug(`parseRowsetHeader`, result)\n return result;\n}\nexports.parseRowsetHeader = parseRowsetHeader;\n/** Extract column names and, optionally, more metadata out of a rowset's header */\nfunction parseRowsetColumnsMetadata(buffer, metadata) {\n function popForward() {\n const { data, fwdBuffer: fwdBuffer } = popData(buffer); // buffer in parent scope\n buffer = fwdBuffer;\n return data;\n }\n for (let i = 0; i < metadata.numberOfColumns; i++) {\n metadata.columns.push({ name: popForward() });\n }\n // extract additional metadata if rowset has version 2\n if (metadata.version == 2) {\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].type = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].database = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].table = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].column = popForward(); // original column name\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].notNull = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].primaryKey = popForward();\n for (let i = 0; i < metadata.numberOfColumns; i++)\n metadata.columns[i].autoIncrement = popForward();\n }\n return buffer;\n}\n/** Parse a regular rowset (no chunks) */\nfunction parseRowset(buffer, spaceIndex) {\n buffer = buffer.subarray(spaceIndex + 1, buffer.length);\n const { metadata, fwdBuffer } = parseRowsetHeader(buffer);\n buffer = parseRowsetColumnsMetadata(fwdBuffer, metadata);\n // decode each rowset item\n const data = [];\n for (let j = 0; j < metadata.numberOfRows * metadata.numberOfColumns; j++) {\n const { data: rowData, fwdBuffer } = popData(buffer);\n data.push(rowData);\n buffer = fwdBuffer;\n }\n console.assert(data && data.length === metadata.numberOfRows * metadata.numberOfColumns, 'SQLiteCloudConnection.parseRowset - invalid rowset data');\n return new rowset_1.SQLiteCloudRowset(metadata, data);\n}\nfunction bufferStartsWith(buffer, prefix) {\n return buffer.length >= prefix.length && buffer.subarray(0, prefix.length).toString('utf8') === prefix;\n}\nexports.bufferStartsWith = bufferStartsWith;\nfunction bufferEndsWith(buffer, suffix) {\n return buffer.length >= suffix.length && buffer.subarray(buffer.length - suffix.length, buffer.length).toString('utf8') === suffix;\n}\nexports.bufferEndsWith = bufferEndsWith;\n/**\n * Parse a chunk of a chunked rowset command, eg:\n * *LEN 0:VERS NROWS NCOLS DATA\n * @see https://github.com/sqlitecloud/sdk/blob/master/PROTOCOL.md#scsp-rowset-chunk\n */\nfunction parseRowsetChunks(buffers) {\n let buffer = buffer_1.Buffer.concat(buffers);\n if (!bufferStartsWith(buffer, exports.CMD_ROWSET_CHUNK) || !bufferEndsWith(buffer, exports.ROWSET_CHUNKS_END)) {\n throw new Error('SQLiteCloudConnection.parseRowsetChunks - invalid chunks buffer');\n }\n let metadata = { version: 1, numberOfColumns: 0, numberOfRows: 0, columns: [] };\n const data = [];\n // validate and skip data type\n const dataType = buffer.subarray(0, 1).toString();\n if (dataType !== exports.CMD_ROWSET_CHUNK)\n throw new Error(`parseRowsetChunks - dataType: ${dataType} should be CMD_ROWSET_CHUNK`);\n buffer = buffer.subarray(buffer.indexOf(' ') + 1);\n while (buffer.length > 0 && !bufferStartsWith(buffer, exports.ROWSET_CHUNKS_END)) {\n // chunk header, eg: 0:VERS NROWS NCOLS\n const { index: chunkIndex, metadata: chunkMetadata, fwdBuffer } = parseRowsetHeader(buffer);\n buffer = fwdBuffer;\n // first chunk? extract columns metadata\n if (chunkIndex === 1) {\n metadata = chunkMetadata;\n buffer = parseRowsetColumnsMetadata(buffer, metadata);\n }\n else {\n metadata.numberOfRows += chunkMetadata.numberOfRows;\n }\n // extract single rowset row\n for (let k = 0; k < chunkMetadata.numberOfRows * metadata.numberOfColumns; k++) {\n const { data: itemData, fwdBuffer } = popData(buffer);\n data.push(itemData);\n buffer = fwdBuffer;\n }\n }\n console.assert(data && data.length === metadata.numberOfRows * metadata.numberOfColumns, 'parseRowsetChunks - invalid rowset data');\n const rowset = new rowset_1.SQLiteCloudRowset(metadata, data);\n // console.debug(`parseRowsetChunks - ${rowset.numberOfRows} rows, ${rowset.numberOfColumns} columns`)\n return rowset;\n}\nexports.parseRowsetChunks = parseRowsetChunks;\n/** Pop one or more space separated integers from beginning of buffer, move buffer forward */\nfunction popIntegers(buffer, numberOfIntegers = 1) {\n const data = [];\n for (let i = 0; i < numberOfIntegers; i++) {\n const spaceIndex = buffer.indexOf(' ');\n data[i] = parseInt(buffer.subarray(0, spaceIndex).toString());\n buffer = buffer.subarray(spaceIndex + 1);\n }\n return { data, fwdBuffer: buffer };\n}\n/** Parse command, extract its data, return the data and the buffer moved to the first byte after the command */\nfunction popData(buffer) {\n function popResults(data) {\n const fwdBuffer = buffer.subarray(commandEnd);\n return { data, fwdBuffer };\n }\n // first character is the data type\n console.assert(buffer && buffer instanceof buffer_1.Buffer);\n let dataType = buffer.subarray(0, 1).toString('utf8');\n if (dataType == exports.CMD_COMPRESSED)\n throw new Error('Compressed data should be decompressed before parsing');\n if (dataType == exports.CMD_ROWSET_CHUNK)\n throw new Error('Chunked data should be parsed by parseRowsetChunks');\n let spaceIndex = buffer.indexOf(' ');\n if (spaceIndex === -1) {\n spaceIndex = buffer.length - 1;\n }\n let commandEnd = -1, commandLength = -1;\n if (dataType === exports.CMD_INT || dataType === exports.CMD_FLOAT || dataType === exports.CMD_NULL) {\n commandEnd = spaceIndex + 1;\n }\n else {\n commandLength = parseInt(buffer.subarray(1, spaceIndex).toString());\n commandEnd = spaceIndex + 1 + commandLength;\n }\n // console.debug(`popData - dataType: ${dataType}, spaceIndex: ${spaceIndex}, commandLength: ${commandLength}, commandEnd: ${commandEnd}`)\n switch (dataType) {\n case exports.CMD_INT:\n return popResults(parseInt(buffer.subarray(1, spaceIndex).toString()));\n case exports.CMD_FLOAT:\n return popResults(parseFloat(buffer.subarray(1, spaceIndex).toString()));\n case exports.CMD_NULL:\n return popResults(null);\n case exports.CMD_STRING:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));\n case exports.CMD_ZEROSTRING:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd - 1).toString('utf8'));\n case exports.CMD_COMMAND:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));\n case exports.CMD_PUBSUB:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8'));\n case exports.CMD_JSON:\n return popResults(JSON.parse(buffer.subarray(spaceIndex + 1, commandEnd).toString('utf8')));\n case exports.CMD_BLOB:\n return popResults(buffer.subarray(spaceIndex + 1, commandEnd));\n case exports.CMD_ARRAY:\n return popResults(parseArray(buffer, spaceIndex));\n case exports.CMD_ROWSET:\n return popResults(parseRowset(buffer, spaceIndex));\n case exports.CMD_ERROR:\n parseError(buffer, spaceIndex); // throws custom error\n break;\n }\n const msg = `popData - Data type: ${Number(dataType)} '${dataType}' is not defined in SCSP, spaceIndex: ${spaceIndex}, commandLength: ${commandLength}, commandEnd: ${commandEnd}`;\n console.error(msg);\n throw new TypeError(msg);\n}\nexports.popData = popData;\n/** Format a command to be sent via SCSP protocol */\nfunction formatCommand(command) {\n const commandLength = buffer_1.Buffer.byteLength(command, 'utf-8');\n return `+${commandLength} ${command}`;\n}\nexports.formatCommand = formatCommand;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/protocol.js?");
74
74
 
75
75
  /***/ }),
76
76
 
@@ -136,7 +136,7 @@ eval("\n/**\n * types.ts - shared types and interfaces\n */\nObject.defineProper
136
136
  /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
137
137
 
138
138
  "use strict";
139
- eval("\n//\n// utilities.ts - utility methods to manipulate SQL statements\n//\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.parseBooleanToZeroOne = exports.parseBoolean = exports.parseconnectionstring = exports.validateConfiguration = exports.popCallback = exports.getUpdateResults = exports.prepareSql = exports.escapeSqlParameter = exports.getInitializationCommands = exports.anonimizeError = exports.anonimizeCommand = exports.isNode = exports.isBrowser = void 0;\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst types_2 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst whatwg_url_1 = __webpack_require__(/*! whatwg-url */ \"./node_modules/whatwg-url/index.js\");\n//\n// determining running environment, thanks to browser-or-node\n// https://www.npmjs.com/package/browser-or-node\n//\nexports.isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';\nexports.isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;\n//\n// utility methods\n//\n/** Messages going to the server are sometimes logged when error conditions occour and need to be stripped of user credentials */\nfunction anonimizeCommand(message) {\n // hide password in AUTH command if needed\n message = message.replace(/USER \\S+/, 'USER ******');\n message = message.replace(/PASSWORD \\S+?(?=;)/, 'PASSWORD ******');\n message = message.replace(/HASH \\S+?(?=;)/, 'HASH ******');\n return message;\n}\nexports.anonimizeCommand = anonimizeCommand;\n/** Strip message code in error of user credentials */\nfunction anonimizeError(error) {\n if (error === null || error === void 0 ? void 0 : error.message) {\n error.message = anonimizeCommand(error.message);\n }\n return error;\n}\nexports.anonimizeError = anonimizeError;\n/** Initialization commands sent to database when connection is established */\nfunction getInitializationCommands(config) {\n // we check the credentials using non linearizable so we're quicker\n // then we bring back linearizability unless specified otherwise\n let commands = 'SET CLIENT KEY NONLINEARIZABLE TO 1; ';\n // first user authentication, then all other commands\n if (config.apikey) {\n commands += `AUTH APIKEY ${config.apikey}; `;\n }\n else {\n commands += `AUTH USER ${config.username || ''} ${config.password_hashed ? 'HASH' : 'PASSWORD'} ${config.password || ''}; `;\n }\n if (config.compression) {\n commands += 'SET CLIENT KEY COMPRESSION TO 1; ';\n }\n if (config.zerotext) {\n commands += 'SET CLIENT KEY ZEROTEXT TO 1; ';\n }\n if (config.noblob) {\n commands += 'SET CLIENT KEY NOBLOB TO 1; ';\n }\n if (config.maxdata) {\n commands += `SET CLIENT KEY MAXDATA TO ${config.maxdata}; `;\n }\n if (config.maxrows) {\n commands += `SET CLIENT KEY MAXROWS TO ${config.maxrows}; `;\n }\n if (config.maxrowset) {\n commands += `SET CLIENT KEY MAXROWSET TO ${config.maxrowset}; `;\n }\n // we ALWAYS set non linearizable to 1 when we start so we can be quicker on login\n // but then we need to put it back to its default value if \"linearizable\" unless set\n if (!config.non_linearizable) {\n commands += 'SET CLIENT KEY NONLINEARIZABLE TO 0; ';\n }\n if (config.database) {\n if (config.create && !config.memory) {\n commands += `CREATE DATABASE ${config.database} IF NOT EXISTS; `;\n }\n commands += `USE DATABASE ${config.database}; `;\n }\n return commands;\n}\nexports.getInitializationCommands = getInitializationCommands;\n/** Takes a generic value and escapes it so it can replace ? as a binding in a prepared SQL statement */\nfunction escapeSqlParameter(param) {\n if (param === null || param === undefined) {\n return 'NULL';\n }\n if (typeof param === 'string') {\n // replace single quote with two single quotes\n param = param.replace(/'/g, \"''\");\n return `'${param}'`;\n }\n if (typeof param === 'number' || typeof param === 'bigint') {\n return param.toString();\n }\n if (typeof param === 'boolean') {\n return param ? '1' : '0';\n }\n // serialize buffer as X'...' hex encoded string\n if (Buffer.isBuffer(param)) {\n return `X'${param.toString('hex')}'`;\n }\n if (typeof param === 'object') {\n // serialize json then escape single quotes\n let json = JSON.stringify(param);\n json = json.replace(/'/g, \"''\");\n return `'${json}'`;\n }\n throw new types_1.SQLiteCloudError(`Unsupported parameter type: ${typeof param}`);\n}\nexports.escapeSqlParameter = escapeSqlParameter;\n/** Take a sql statement and replaces ? or $named parameters that are properly serialized and escaped. */\nfunction prepareSql(sql, ...params) {\n // parameters where passed as an array of parameters?\n if ((params === null || params === void 0 ? void 0 : params.length) === 1 && Array.isArray(params[0])) {\n params = params[0];\n }\n // replace ? or ?idx parameters passed as args or as an array\n let parameterIndex = 1;\n let preparedSql = sql.replace(/\\?(\\d+)?/g, (match, matchIndex) => {\n const index = matchIndex ? parseInt(matchIndex) : parameterIndex;\n parameterIndex++;\n let sqlParameter;\n if (params[0] && typeof params[0] === 'object' && !(params[0] instanceof Buffer)) {\n sqlParameter = params[0][index];\n }\n if (!sqlParameter) {\n if (index > params.length) {\n throw new types_1.SQLiteCloudError('Not enough parameters');\n }\n sqlParameter = params[index - 1];\n }\n return sqlParameter !== null && sqlParameter !== undefined ? escapeSqlParameter(sqlParameter) : 'NULL';\n });\n // replace $named or :named parameters passed as an object\n if ((params === null || params === void 0 ? void 0 : params.length) === 1 && params[0] && typeof params[0] === 'object') {\n const namedParams = params[0];\n for (const [paramKey, param] of Object.entries(namedParams)) {\n const firstChar = paramKey.charAt(0);\n if (firstChar == '$' || firstChar == ':' || firstChar == '@') {\n const escapedParam = escapeSqlParameter(param);\n preparedSql = preparedSql.replace(new RegExp(`\\\\${paramKey}`, 'g'), escapedParam);\n }\n }\n }\n return preparedSql;\n}\nexports.prepareSql = prepareSql;\n/** Converts results of an update or insert call into a more meaning full result set */\nfunction getUpdateResults(results) {\n if (results) {\n if (Array.isArray(results) && results.length > 0) {\n switch (results[0]) {\n case types_2.SQLiteCloudArrayType.ARRAY_TYPE_SQLITE_EXEC:\n return {\n type: results[0],\n index: results[1],\n lastID: results[2],\n changes: results[3],\n totalChanges: results[4],\n finalized: results[5],\n //\n rowId: results[2] // same as lastId\n };\n }\n }\n }\n return undefined;\n}\nexports.getUpdateResults = getUpdateResults;\n/**\n * Many of the methods in our API may contain a callback as their last argument.\n * This method will take the arguments array passed to the method and return an object\n * containing the arguments array with the callbacks removed (if any), and the callback itself.\n * If there are multiple callbacks, the first one is returned as 'callback' and the last one\n * as 'completeCallback'.\n */\nfunction popCallback(args) {\n const remaining = args;\n // at least 1 callback?\n if (args && args.length > 0 && typeof args[args.length - 1] === 'function') {\n // at least 2 callbacks?\n if (args.length > 1 && typeof args[args.length - 2] === 'function') {\n return { args: remaining.slice(0, -2), callback: args[args.length - 2], complete: args[args.length - 1] };\n }\n return { args: remaining.slice(0, -1), callback: args[args.length - 1] };\n }\n return { args: remaining };\n}\nexports.popCallback = popCallback;\n//\n// configuration validation\n//\n/** Validate configuration, apply defaults, throw if something is missing or misconfigured */\nfunction validateConfiguration(config) {\n console.assert(config, 'SQLiteCloudConnection.validateConfiguration - missing config');\n if (config.connectionstring) {\n config = Object.assign(Object.assign(Object.assign({}, config), parseconnectionstring(config.connectionstring)), { connectionstring: config.connectionstring // keep original connection string\n });\n }\n // apply defaults where needed\n config.port || (config.port = types_1.DEFAULT_PORT);\n config.timeout = config.timeout && config.timeout > 0 ? config.timeout : types_1.DEFAULT_TIMEOUT;\n config.clientid || (config.clientid = 'SQLiteCloud');\n config.verbose = parseBoolean(config.verbose);\n config.noblob = parseBoolean(config.noblob);\n config.compression = config.compression != undefined && config.compression != null ? parseBoolean(config.compression) : true; // default: true\n config.create = parseBoolean(config.create);\n config.non_linearizable = parseBoolean(config.non_linearizable);\n config.insecure = parseBoolean(config.insecure);\n const hasCredentials = (config.username && config.password) || config.apikey;\n if (!config.host || !hasCredentials) {\n console.error('SQLiteCloudConnection.validateConfiguration - missing arguments', config);\n throw new types_1.SQLiteCloudError('The user, password and host arguments or the ?apikey= must be specified.', { errorCode: 'ERR_MISSING_ARGS' });\n }\n if (!config.connectionstring) {\n // build connection string from configuration, values are already validated\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n if (config.apikey) {\n config.connectionstring = `sqlitecloud://${config.host}:${config.port}/${config.database || ''}?apikey=${config.apikey}`;\n }\n else {\n config.connectionstring = `sqlitecloud://${encodeURIComponent(config.username || '')}:${encodeURIComponent(config.password || '')}@${config.host}:${config.port}/${config.database}`;\n }\n }\n return config;\n}\nexports.validateConfiguration = validateConfiguration;\n/**\n * Parse connectionstring like sqlitecloud://username:password@host:port/database?option1=xxx&option2=xxx\n * or sqlitecloud://host.sqlite.cloud:8860/chinook.sqlite?apikey=mIiLARzKm9XBVllbAzkB1wqrgijJ3Gx0X5z1Agm3xBo\n * into its basic components.\n */\nfunction parseconnectionstring(connectionstring) {\n try {\n // The URL constructor throws a TypeError if the URL is not valid.\n // in spite of having the same structure as a regular url\n // protocol://username:password@host:port/database?option1=xxx&option2=xxx)\n // the sqlitecloud: protocol is not recognized by the URL constructor in browsers\n // so we need to replace it with https: to make it work\n const knownProtocolUrl = connectionstring.replace('sqlitecloud:', 'https:');\n const url = new whatwg_url_1.URL(knownProtocolUrl);\n // all lowecase options\n const options = {};\n url.searchParams.forEach((value, key) => {\n options[key.toLowerCase().replaceAll('-', '_')] = value;\n });\n const config = Object.assign({ username: decodeURIComponent(url.username), password: decodeURIComponent(url.password), host: url.hostname, port: url.port ? parseInt(url.port) : undefined }, options);\n // either you use an apikey or username and password\n if (config.apikey) {\n if (config.username || config.password) {\n console.warn('SQLiteCloudConnection.parseconnectionstring - apikey and username/password are both specified, using apikey');\n }\n delete config.username;\n delete config.password;\n }\n const database = url.pathname.replace('/', ''); // pathname is database name, remove the leading slash\n if (database) {\n config.database = database;\n }\n return config;\n }\n catch (error) {\n throw new types_1.SQLiteCloudError(`Invalid connection string: ${connectionstring}`);\n }\n}\nexports.parseconnectionstring = parseconnectionstring;\n/** Returns true if value is 1 or true */\nfunction parseBoolean(value) {\n if (typeof value === 'string') {\n return value.toLowerCase() === 'true' || value === '1';\n }\n return value ? true : false;\n}\nexports.parseBoolean = parseBoolean;\n/** Returns true if value is 1 or true */\nfunction parseBooleanToZeroOne(value) {\n if (typeof value === 'string') {\n return value.toLowerCase() === 'true' || value === '1' ? 1 : 0;\n }\n return value ? 1 : 0;\n}\nexports.parseBooleanToZeroOne = parseBooleanToZeroOne;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/utilities.js?");
139
+ eval("\n//\n// utilities.ts - utility methods to manipulate SQL statements\n//\nObject.defineProperty(exports, \"__esModule\", ({ value: true }));\nexports.parseBooleanToZeroOne = exports.parseBoolean = exports.parseconnectionstring = exports.validateConfiguration = exports.popCallback = exports.getUpdateResults = exports.prepareSql = exports.escapeSqlParameter = exports.getInitializationCommands = exports.anonimizeError = exports.anonimizeCommand = exports.isNode = exports.isBrowser = void 0;\nconst types_1 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\nconst types_2 = __webpack_require__(/*! ./types */ \"./lib/drivers/types.js\");\n// explicitly importing these libraries to allow cross-platform support by replacing them\nconst whatwg_url_1 = __webpack_require__(/*! whatwg-url */ \"./node_modules/whatwg-url/index.js\");\nconst buffer_1 = __webpack_require__(/*! buffer */ \"./node_modules/buffer/index.js\");\n//\n// determining running environment, thanks to browser-or-node\n// https://www.npmjs.com/package/browser-or-node\n//\nexports.isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';\nexports.isNode = typeof process !== 'undefined' && process.versions != null && process.versions.node != null;\n//\n// utility methods\n//\n/** Messages going to the server are sometimes logged when error conditions occour and need to be stripped of user credentials */\nfunction anonimizeCommand(message) {\n // hide password in AUTH command if needed\n message = message.replace(/USER \\S+/, 'USER ******');\n message = message.replace(/PASSWORD \\S+?(?=;)/, 'PASSWORD ******');\n message = message.replace(/HASH \\S+?(?=;)/, 'HASH ******');\n return message;\n}\nexports.anonimizeCommand = anonimizeCommand;\n/** Strip message code in error of user credentials */\nfunction anonimizeError(error) {\n if (error === null || error === void 0 ? void 0 : error.message) {\n error.message = anonimizeCommand(error.message);\n }\n return error;\n}\nexports.anonimizeError = anonimizeError;\n/** Initialization commands sent to database when connection is established */\nfunction getInitializationCommands(config) {\n // we check the credentials using non linearizable so we're quicker\n // then we bring back linearizability unless specified otherwise\n let commands = 'SET CLIENT KEY NONLINEARIZABLE TO 1; ';\n // first user authentication, then all other commands\n if (config.apikey) {\n commands += `AUTH APIKEY ${config.apikey}; `;\n }\n else {\n commands += `AUTH USER ${config.username || ''} ${config.password_hashed ? 'HASH' : 'PASSWORD'} ${config.password || ''}; `;\n }\n if (config.compression) {\n commands += 'SET CLIENT KEY COMPRESSION TO 1; ';\n }\n if (config.zerotext) {\n commands += 'SET CLIENT KEY ZEROTEXT TO 1; ';\n }\n if (config.noblob) {\n commands += 'SET CLIENT KEY NOBLOB TO 1; ';\n }\n if (config.maxdata) {\n commands += `SET CLIENT KEY MAXDATA TO ${config.maxdata}; `;\n }\n if (config.maxrows) {\n commands += `SET CLIENT KEY MAXROWS TO ${config.maxrows}; `;\n }\n if (config.maxrowset) {\n commands += `SET CLIENT KEY MAXROWSET TO ${config.maxrowset}; `;\n }\n // we ALWAYS set non linearizable to 1 when we start so we can be quicker on login\n // but then we need to put it back to its default value if \"linearizable\" unless set\n if (!config.non_linearizable) {\n commands += 'SET CLIENT KEY NONLINEARIZABLE TO 0; ';\n }\n if (config.database) {\n if (config.create && !config.memory) {\n commands += `CREATE DATABASE ${config.database} IF NOT EXISTS; `;\n }\n commands += `USE DATABASE ${config.database}; `;\n }\n return commands;\n}\nexports.getInitializationCommands = getInitializationCommands;\n/** Takes a generic value and escapes it so it can replace ? as a binding in a prepared SQL statement */\nfunction escapeSqlParameter(param) {\n if (param === null || param === undefined) {\n return 'NULL';\n }\n if (typeof param === 'string') {\n // replace single quote with two single quotes\n param = param.replace(/'/g, \"''\");\n return `'${param}'`;\n }\n if (typeof param === 'number' || typeof param === 'bigint') {\n return param.toString();\n }\n if (typeof param === 'boolean') {\n return param ? '1' : '0';\n }\n // serialize buffer as X'...' hex encoded string\n if (buffer_1.Buffer.isBuffer(param)) {\n return `X'${param.toString('hex')}'`;\n }\n if (typeof param === 'object') {\n // serialize json then escape single quotes\n let json = JSON.stringify(param);\n json = json.replace(/'/g, \"''\");\n return `'${json}'`;\n }\n throw new types_1.SQLiteCloudError(`Unsupported parameter type: ${typeof param}`);\n}\nexports.escapeSqlParameter = escapeSqlParameter;\n/** Take a sql statement and replaces ? or $named parameters that are properly serialized and escaped. */\nfunction prepareSql(sql, ...params) {\n // parameters where passed as an array of parameters?\n if ((params === null || params === void 0 ? void 0 : params.length) === 1 && Array.isArray(params[0])) {\n params = params[0];\n }\n // replace ? or ?idx parameters passed as args or as an array\n let parameterIndex = 1;\n let preparedSql = sql.replace(/\\?(\\d+)?/g, (match, matchIndex) => {\n const index = matchIndex ? parseInt(matchIndex) : parameterIndex;\n parameterIndex++;\n let sqlParameter;\n if (params[0] && typeof params[0] === 'object' && !(params[0] instanceof buffer_1.Buffer)) {\n sqlParameter = params[0][index];\n }\n if (!sqlParameter) {\n if (index > params.length) {\n throw new types_1.SQLiteCloudError('Not enough parameters');\n }\n sqlParameter = params[index - 1];\n }\n return sqlParameter !== null && sqlParameter !== undefined ? escapeSqlParameter(sqlParameter) : 'NULL';\n });\n // replace $named or :named parameters passed as an object\n if ((params === null || params === void 0 ? void 0 : params.length) === 1 && params[0] && typeof params[0] === 'object') {\n const namedParams = params[0];\n for (const [paramKey, param] of Object.entries(namedParams)) {\n const firstChar = paramKey.charAt(0);\n if (firstChar == '$' || firstChar == ':' || firstChar == '@') {\n const escapedParam = escapeSqlParameter(param);\n preparedSql = preparedSql.replace(new RegExp(`\\\\${paramKey}`, 'g'), escapedParam);\n }\n }\n }\n return preparedSql;\n}\nexports.prepareSql = prepareSql;\n/** Converts results of an update or insert call into a more meaning full result set */\nfunction getUpdateResults(results) {\n if (results) {\n if (Array.isArray(results) && results.length > 0) {\n switch (results[0]) {\n case types_2.SQLiteCloudArrayType.ARRAY_TYPE_SQLITE_EXEC:\n return {\n type: results[0],\n index: results[1],\n lastID: results[2],\n changes: results[3],\n totalChanges: results[4],\n finalized: results[5],\n //\n rowId: results[2] // same as lastId\n };\n }\n }\n }\n return undefined;\n}\nexports.getUpdateResults = getUpdateResults;\n/**\n * Many of the methods in our API may contain a callback as their last argument.\n * This method will take the arguments array passed to the method and return an object\n * containing the arguments array with the callbacks removed (if any), and the callback itself.\n * If there are multiple callbacks, the first one is returned as 'callback' and the last one\n * as 'completeCallback'.\n */\nfunction popCallback(args) {\n const remaining = args;\n // at least 1 callback?\n if (args && args.length > 0 && typeof args[args.length - 1] === 'function') {\n // at least 2 callbacks?\n if (args.length > 1 && typeof args[args.length - 2] === 'function') {\n return { args: remaining.slice(0, -2), callback: args[args.length - 2], complete: args[args.length - 1] };\n }\n return { args: remaining.slice(0, -1), callback: args[args.length - 1] };\n }\n return { args: remaining };\n}\nexports.popCallback = popCallback;\n//\n// configuration validation\n//\n/** Validate configuration, apply defaults, throw if something is missing or misconfigured */\nfunction validateConfiguration(config) {\n console.assert(config, 'SQLiteCloudConnection.validateConfiguration - missing config');\n if (config.connectionstring) {\n config = Object.assign(Object.assign(Object.assign({}, config), parseconnectionstring(config.connectionstring)), { connectionstring: config.connectionstring // keep original connection string\n });\n }\n // apply defaults where needed\n config.port || (config.port = types_1.DEFAULT_PORT);\n config.timeout = config.timeout && config.timeout > 0 ? config.timeout : types_1.DEFAULT_TIMEOUT;\n config.clientid || (config.clientid = 'SQLiteCloud');\n config.verbose = parseBoolean(config.verbose);\n config.noblob = parseBoolean(config.noblob);\n config.compression = config.compression != undefined && config.compression != null ? parseBoolean(config.compression) : true; // default: true\n config.create = parseBoolean(config.create);\n config.non_linearizable = parseBoolean(config.non_linearizable);\n config.insecure = parseBoolean(config.insecure);\n const hasCredentials = (config.username && config.password) || config.apikey;\n if (!config.host || !hasCredentials) {\n console.error('SQLiteCloudConnection.validateConfiguration - missing arguments', config);\n throw new types_1.SQLiteCloudError('The user, password and host arguments or the ?apikey= must be specified.', { errorCode: 'ERR_MISSING_ARGS' });\n }\n if (!config.connectionstring) {\n // build connection string from configuration, values are already validated\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n if (config.apikey) {\n config.connectionstring = `sqlitecloud://${config.host}:${config.port}/${config.database || ''}?apikey=${config.apikey}`;\n }\n else {\n config.connectionstring = `sqlitecloud://${encodeURIComponent(config.username || '')}:${encodeURIComponent(config.password || '')}@${config.host}:${config.port}/${config.database}`;\n }\n }\n return config;\n}\nexports.validateConfiguration = validateConfiguration;\n/**\n * Parse connectionstring like sqlitecloud://username:password@host:port/database?option1=xxx&option2=xxx\n * or sqlitecloud://host.sqlite.cloud:8860/chinook.sqlite?apikey=mIiLARzKm9XBVllbAzkB1wqrgijJ3Gx0X5z1Agm3xBo\n * into its basic components.\n */\nfunction parseconnectionstring(connectionstring) {\n try {\n // The URL constructor throws a TypeError if the URL is not valid.\n // in spite of having the same structure as a regular url\n // protocol://username:password@host:port/database?option1=xxx&option2=xxx)\n // the sqlitecloud: protocol is not recognized by the URL constructor in browsers\n // so we need to replace it with https: to make it work\n const knownProtocolUrl = connectionstring.replace('sqlitecloud:', 'https:');\n const url = new whatwg_url_1.URL(knownProtocolUrl);\n // all lowecase options\n const options = {};\n url.searchParams.forEach((value, key) => {\n options[key.toLowerCase().replaceAll('-', '_')] = value;\n });\n const config = Object.assign({ username: decodeURIComponent(url.username), password: decodeURIComponent(url.password), host: url.hostname, port: url.port ? parseInt(url.port) : undefined }, options);\n // either you use an apikey or username and password\n if (config.apikey) {\n if (config.username || config.password) {\n console.warn('SQLiteCloudConnection.parseconnectionstring - apikey and username/password are both specified, using apikey');\n }\n delete config.username;\n delete config.password;\n }\n const database = url.pathname.replace('/', ''); // pathname is database name, remove the leading slash\n if (database) {\n config.database = database;\n }\n return config;\n }\n catch (error) {\n throw new types_1.SQLiteCloudError(`Invalid connection string: ${connectionstring}`);\n }\n}\nexports.parseconnectionstring = parseconnectionstring;\n/** Returns true if value is 1 or true */\nfunction parseBoolean(value) {\n if (typeof value === 'string') {\n return value.toLowerCase() === 'true' || value === '1';\n }\n return value ? true : false;\n}\nexports.parseBoolean = parseBoolean;\n/** Returns true if value is 1 or true */\nfunction parseBooleanToZeroOne(value) {\n if (typeof value === 'string') {\n return value.toLowerCase() === 'true' || value === '1' ? 1 : 0;\n }\n return value ? 1 : 0;\n}\nexports.parseBooleanToZeroOne = parseBooleanToZeroOne;\n\n\n//# sourceURL=webpack://sqlitecloud/./lib/drivers/utilities.js?");
140
140
 
141
141
  /***/ }),
142
142
 
@@ -151,6 +151,28 @@ eval("\n//\n// index.ts - export drivers classes, utilities, types\n//\nObject.d
151
151
 
152
152
  /***/ }),
153
153
 
154
+ /***/ "./node_modules/base64-js/index.js":
155
+ /*!*****************************************!*\
156
+ !*** ./node_modules/base64-js/index.js ***!
157
+ \*****************************************/
158
+ /***/ ((__unused_webpack_module, exports) => {
159
+
160
+ "use strict";
161
+ eval("\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n\n\n//# sourceURL=webpack://sqlitecloud/./node_modules/base64-js/index.js?");
162
+
163
+ /***/ }),
164
+
165
+ /***/ "./node_modules/buffer/index.js":
166
+ /*!**************************************!*\
167
+ !*** ./node_modules/buffer/index.js ***!
168
+ \**************************************/
169
+ /***/ ((__unused_webpack_module, exports, __webpack_require__) => {
170
+
171
+ "use strict";
172
+ eval("/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh <https://feross.org>\n * @license MIT\n */\n/* eslint-disable no-proto */\n\n\n\nconst base64 = __webpack_require__(/*! base64-js */ \"./node_modules/base64-js/index.js\")\nconst ieee754 = __webpack_require__(/*! ieee754 */ \"./node_modules/ieee754/index.js\")\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return '<Buffer ' + str + '>'\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction decodeCodePointsArray (codePoints) {\n const len = codePoints.length\n if (len <= MAX_ARGUMENTS_LENGTH) {\n return String.fromCharCode.apply(String, codePoints) // avoid extra slice()\n }\n\n // Decode in chunks to avoid \"call stack size exceeded\".\n let res = ''\n let i = 0\n while (i < len) {\n res += String.fromCharCode.apply(\n String,\n codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)\n )\n }\n return res\n}\n\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n\n\n//# sourceURL=webpack://sqlitecloud/./node_modules/buffer/index.js?");
173
+
174
+ /***/ }),
175
+
154
176
  /***/ "./node_modules/debug/src/browser.js":
155
177
  /*!*******************************************!*\
156
178
  !*** ./node_modules/debug/src/browser.js ***!
@@ -182,6 +204,16 @@ eval("\n\nvar has = Object.prototype.hasOwnProperty\n , prefix = '~';\n\n/**\n
182
204
 
183
205
  /***/ }),
184
206
 
207
+ /***/ "./node_modules/ieee754/index.js":
208
+ /*!***************************************!*\
209
+ !*** ./node_modules/ieee754/index.js ***!
210
+ \***************************************/
211
+ /***/ ((__unused_webpack_module, exports) => {
212
+
213
+ eval("/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n\n\n//# sourceURL=webpack://sqlitecloud/./node_modules/ieee754/index.js?");
214
+
215
+ /***/ }),
216
+
185
217
  /***/ "./node_modules/lz4js/lz4.js":
186
218
  /*!***********************************!*\
187
219
  !*** ./node_modules/lz4js/lz4.js ***!