@powersync/react-native 0.0.0-dev-20240701142654 → 0.0.0-dev-20240702142750

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.
package/dist/main.js CHANGED
@@ -2,9 +2,10 @@
2
2
 
3
3
  var require$$0$1 = require('node-fetch');
4
4
  var reactNative = require('react-native');
5
- var buffer = require('buffer');
6
5
  var react = require('@powersync/react');
7
6
  var bson = require('bson');
7
+ var BlobManager = require('react-native/Libraries/Blob/BlobManager');
8
+ var reactNativeQuickSqlite = require('@journeyapps/react-native-quick-sqlite');
8
9
 
9
10
  const E_CANCELED = new Error('request for lock canceled');
10
11
 
@@ -1327,7 +1328,7 @@ class UploadQueueStats {
1327
1328
  }
1328
1329
  }
1329
1330
 
1330
- let BaseObserver$1 = class BaseObserver {
1331
+ class BaseObserver {
1331
1332
  listeners = new Set();
1332
1333
  constructor() { }
1333
1334
  /**
@@ -1349,7 +1350,7 @@ let BaseObserver$1 = class BaseObserver {
1349
1350
  await cb(i);
1350
1351
  }
1351
1352
  }
1352
- };
1353
+ }
1353
1354
 
1354
1355
  /**
1355
1356
  * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
@@ -1689,9 +1690,10 @@ const DEFAULT_STREAMING_SYNC_OPTIONS = {
1689
1690
  crudUploadThrottleMs: DEFAULT_CRUD_UPLOAD_THROTTLE_MS
1690
1691
  };
1691
1692
  const DEFAULT_STREAM_CONNECTION_OPTIONS = {
1692
- connectionMethod: exports.SyncStreamConnectionMethod.HTTP
1693
+ connectionMethod: exports.SyncStreamConnectionMethod.HTTP,
1694
+ params: {}
1693
1695
  };
1694
- class AbstractStreamingSyncImplementation extends BaseObserver$1 {
1696
+ class AbstractStreamingSyncImplementation extends BaseObserver {
1695
1697
  _lastSyncedAt;
1696
1698
  options;
1697
1699
  abortController;
@@ -1783,13 +1785,16 @@ class AbstractStreamingSyncImplementation extends BaseObserver$1 {
1783
1785
  }
1784
1786
  catch (ex) {
1785
1787
  this.updateSyncStatus({
1786
- connected: false,
1787
1788
  dataFlow: {
1788
1789
  uploading: false
1789
1790
  }
1790
1791
  });
1791
1792
  await this.delayRetry();
1792
- break;
1793
+ if (!this.isConnected) {
1794
+ // Exit the upload loop if the sync stream is no longer connected
1795
+ break;
1796
+ }
1797
+ this.logger.debug(`Caught exception when uploading. Upload will retry after a delay. Exception: ${ex.message}`);
1793
1798
  }
1794
1799
  finally {
1795
1800
  this.updateSyncStatus({
@@ -1979,7 +1984,8 @@ class AbstractStreamingSyncImplementation extends BaseObserver$1 {
1979
1984
  data: {
1980
1985
  buckets: req,
1981
1986
  include_checksum: true,
1982
- raw_data: true
1987
+ raw_data: true,
1988
+ parameters: resolvedOptions.params
1983
1989
  }
1984
1990
  };
1985
1991
  const stream = resolvedOptions?.connectionMethod == exports.SyncStreamConnectionMethod.HTTP
@@ -2200,6 +2206,25 @@ class ControlledExecutor {
2200
2206
  }
2201
2207
  }
2202
2208
 
2209
+ /**
2210
+ * Tests if the input is a {@link SQLOpenOptions}
2211
+ */
2212
+ const isSQLOpenOptions = (test) => {
2213
+ return typeof test == 'object' && 'dbFilename' in test;
2214
+ };
2215
+ /**
2216
+ * Tests if input is a {@link SQLOpenFactory}
2217
+ */
2218
+ const isSQLOpenFactory = (test) => {
2219
+ return typeof test?.openDB == 'function';
2220
+ };
2221
+ /**
2222
+ * Tests if input is a {@link DBAdapter}
2223
+ */
2224
+ const isDBAdapter = (test) => {
2225
+ return typeof test?.writeTransaction == 'function';
2226
+ };
2227
+
2203
2228
  const POWERSYNC_TABLE_MATCH = /(^ps_data__|^ps_data_local__)/;
2204
2229
  const DEFAULT_DISCONNECT_CLEAR_OPTIONS = {
2205
2230
  clearLocal: true
@@ -2219,7 +2244,7 @@ const DEFAULT_POWERSYNC_DB_OPTIONS = {
2219
2244
  * be obtained.
2220
2245
  */
2221
2246
  const DEFAULT_LOCK_TIMEOUT_MS = 120_000; // 2 mins
2222
- class AbstractPowerSyncDatabase extends BaseObserver$1 {
2247
+ class AbstractPowerSyncDatabase extends BaseObserver {
2223
2248
  options;
2224
2249
  /**
2225
2250
  * Transactions should be queued in the DBAdapter, but we also want to prevent
@@ -2242,9 +2267,20 @@ class AbstractPowerSyncDatabase extends BaseObserver$1 {
2242
2267
  _isReadyPromise;
2243
2268
  hasSyncedWatchDisposer;
2244
2269
  _schema;
2270
+ _database;
2245
2271
  constructor(options) {
2246
2272
  super();
2247
2273
  this.options = options;
2274
+ const { database } = options;
2275
+ if (isDBAdapter(database)) {
2276
+ this._database = database;
2277
+ }
2278
+ else if (isSQLOpenFactory(database)) {
2279
+ this._database = database.openDB();
2280
+ }
2281
+ else if (isSQLOpenOptions(database)) {
2282
+ this._database = this.openDBAdapter(database);
2283
+ }
2248
2284
  this.bucketStorageAdapter = this.generateBucketStorageAdapter();
2249
2285
  this.closed = false;
2250
2286
  this.currentStatus = new SyncStatus({});
@@ -2267,7 +2303,7 @@ class AbstractPowerSyncDatabase extends BaseObserver$1 {
2267
2303
  * For the most part, behavior is the same whether querying on the underlying database, or on {@link AbstractPowerSyncDatabase}.
2268
2304
  */
2269
2305
  get database() {
2270
- return this.options.database;
2306
+ return this._database;
2271
2307
  }
2272
2308
  /**
2273
2309
  * Whether a connection to the PowerSync service is currently open.
@@ -2313,7 +2349,7 @@ class AbstractPowerSyncDatabase extends BaseObserver$1 {
2313
2349
  async initialize() {
2314
2350
  await this._initialize();
2315
2351
  await this.bucketStorageAdapter.init();
2316
- const version = await this.options.database.execute('SELECT powersync_rs_version()');
2352
+ const version = await this.database.execute('SELECT powersync_rs_version()');
2317
2353
  this.sdkVersion = version.rows?.item(0)['powersync_rs_version()'] ?? '';
2318
2354
  await this.updateSchema(this.options.schema);
2319
2355
  this.updateHasSynced();
@@ -2863,7 +2899,7 @@ class AbstractPowerSyncDatabaseOpenFactory {
2863
2899
  }
2864
2900
 
2865
2901
  const COMPACT_OPERATION_INTERVAL = 1_000;
2866
- class SqliteBucketStorage extends BaseObserver$1 {
2902
+ class SqliteBucketStorage extends BaseObserver {
2867
2903
  db;
2868
2904
  mutex;
2869
2905
  logger;
@@ -8192,7 +8228,7 @@ const DEFAULT_PRESSURE_LIMITS = {
8192
8228
  * native JS streams or async iterators.
8193
8229
  * This is handy for environments such as React Native which need polyfills for the above.
8194
8230
  */
8195
- class DataStream extends BaseObserver$1 {
8231
+ class DataStream extends BaseObserver {
8196
8232
  options;
8197
8233
  dataQueue;
8198
8234
  isClosed;
@@ -11782,7 +11818,7 @@ var reactNativeBuffer = {};
11782
11818
  var base64Js = {};
11783
11819
 
11784
11820
  base64Js.byteLength = byteLength$1;
11785
- base64Js.toByteArray = toByteArray$1;
11821
+ var toByteArray_1 = base64Js.toByteArray = toByteArray$1;
11786
11822
  base64Js.fromByteArray = fromByteArray$1;
11787
11823
 
11788
11824
  var lookup = [];
@@ -19050,246 +19086,2373 @@ WebsocketClientTransport$1.WebsocketClientTransport = WebsocketClientTransport;
19050
19086
 
19051
19087
  } (dist));
19052
19088
 
19053
- // Refresh at least 30 sec before it expires
19054
- const REFRESH_CREDENTIALS_SAFETY_PERIOD_MS = 30_000;
19055
- const SYNC_QUEUE_REQUEST_N = 10;
19056
- const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
19057
- // Keep alive message is sent every period
19058
- const KEEP_ALIVE_MS = 20_000;
19059
- // The ACK must be received in this period
19060
- const KEEP_ALIVE_LIFETIME_MS = 30_000;
19061
- const DEFAULT_REMOTE_LOGGER = Logger.get('PowerSyncRemote');
19062
- const DEFAULT_REMOTE_OPTIONS = {
19063
- socketUrlTransformer: (url) => url.replace(/^https?:\/\//, function (match) {
19064
- return match === 'https://' ? 'wss://' : 'ws://';
19065
- }),
19066
- fetchImplementation: nodePonyfillExports.fetch.bind(globalThis)
19067
- };
19068
- class AbstractRemote {
19069
- connector;
19070
- logger;
19071
- credentials = null;
19072
- options;
19073
- constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {
19074
- this.connector = connector;
19075
- this.logger = logger;
19076
- this.options = {
19077
- ...DEFAULT_REMOTE_OPTIONS,
19078
- ...(options ?? {})
19079
- };
19080
- }
19081
- get fetch() {
19082
- return this.options.fetchImplementation;
19083
- }
19084
- async getCredentials() {
19085
- const { expiresAt } = this.credentials ?? {};
19086
- if (expiresAt && expiresAt > new Date(new Date().valueOf() + REFRESH_CREDENTIALS_SAFETY_PERIOD_MS)) {
19087
- return this.credentials;
19088
- }
19089
- this.credentials = await this.connector.fetchCredentials();
19090
- return this.credentials;
19091
- }
19092
- async buildRequest(path) {
19093
- const credentials = await this.getCredentials();
19094
- if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {
19095
- throw new Error('PowerSync endpoint not configured');
19096
- }
19097
- else if (credentials?.token == null || credentials?.token == '') {
19098
- const error = new Error(`Not signed in`);
19099
- error.status = 401;
19100
- throw error;
19101
- }
19102
- return {
19103
- url: credentials.endpoint + path,
19104
- headers: {
19105
- 'content-type': 'application/json',
19106
- Authorization: `Token ${credentials.token}`
19107
- }
19108
- };
19109
- }
19110
- async post(path, data, headers = {}) {
19111
- const request = await this.buildRequest(path);
19112
- const res = await nodePonyfillExports.fetch(request.url, {
19113
- method: 'POST',
19114
- headers: {
19115
- ...headers,
19116
- ...request.headers
19117
- },
19118
- body: JSON.stringify(data)
19119
- });
19120
- if (!res.ok) {
19121
- throw new Error(`Received ${res.status} - ${res.statusText} when posting to ${path}: ${await res.text()}}`);
19122
- }
19123
- return res.json();
19124
- }
19125
- async get(path, headers) {
19126
- const request = await this.buildRequest(path);
19127
- const res = await this.fetch(request.url, {
19128
- method: 'GET',
19129
- headers: {
19130
- ...headers,
19131
- ...request.headers
19132
- }
19133
- });
19134
- if (!res.ok) {
19135
- throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);
19136
- }
19137
- return res.json();
19138
- }
19139
- async postStreaming(path, data, headers = {}, signal) {
19140
- const request = await this.buildRequest(path);
19141
- const res = await this.fetch(request.url, {
19142
- method: 'POST',
19143
- headers: { ...headers, ...request.headers },
19144
- body: JSON.stringify(data),
19145
- signal,
19146
- cache: 'no-store'
19147
- }).catch((ex) => {
19148
- this.logger.error(`Caught ex when POST streaming to ${path}`, ex);
19149
- throw ex;
19150
- });
19151
- if (!res.ok) {
19152
- const text = await res.text();
19153
- this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
19154
- const error = new Error(`HTTP ${res.statusText}: ${text}`);
19155
- error.status = res.status;
19156
- throw error;
19157
- }
19158
- return res;
19159
- }
19160
- /**
19161
- * Connects to the sync/stream websocket endpoint
19162
- */
19163
- async socketStream(options) {
19164
- const { path } = options;
19165
- const request = await this.buildRequest(path);
19166
- const bson = await this.getBSON();
19167
- const connector = new distExports.RSocketConnector({
19168
- transport: new dist.WebsocketClientTransport({
19169
- url: this.options.socketUrlTransformer(request.url)
19170
- }),
19171
- setup: {
19172
- keepAlive: KEEP_ALIVE_MS,
19173
- lifetime: KEEP_ALIVE_LIFETIME_MS,
19174
- dataMimeType: 'application/bson',
19175
- metadataMimeType: 'application/bson',
19176
- payload: {
19177
- data: null,
19178
- metadata: buffer.Buffer.from(bson.serialize({
19179
- token: request.headers.Authorization
19180
- }))
19181
- }
19182
- }
19183
- });
19184
- let rsocket;
19185
- try {
19186
- rsocket = await connector.connect();
19187
- }
19188
- catch (ex) {
19189
- /**
19190
- * On React native the connection exception can be `undefined` this causes issues
19191
- * with detecting the exception inside async-mutex
19192
- */
19193
- throw new Error(`Could not connect to PowerSync instance: ${JSON.stringify(ex)}`);
19194
- }
19195
- const stream = new DataStream({
19196
- logger: this.logger,
19197
- pressure: {
19198
- lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER
19199
- }
19200
- });
19201
- let socketIsClosed = false;
19202
- const closeSocket = () => {
19203
- if (socketIsClosed) {
19204
- return;
19205
- }
19206
- socketIsClosed = true;
19207
- rsocket.close();
19208
- };
19209
- // We initially request this amount and expect these to arrive eventually
19210
- let pendingEventsCount = SYNC_QUEUE_REQUEST_N;
19211
- const socket = await new Promise((resolve, reject) => {
19212
- let connectionEstablished = false;
19213
- const res = rsocket.requestStream({
19214
- data: buffer.Buffer.from(bson.serialize(options.data)),
19215
- metadata: buffer.Buffer.from(bson.serialize({
19216
- path
19217
- }))
19218
- }, SYNC_QUEUE_REQUEST_N, // The initial N amount
19219
- {
19220
- onError: (e) => {
19221
- // Don't log closed as an error
19222
- if (e.message !== 'Closed. ') {
19223
- this.logger.error(e);
19224
- }
19225
- // RSocket will close this automatically
19226
- // Attempting to close multiple times causes a console warning
19227
- socketIsClosed = true;
19228
- stream.close();
19229
- // Handles cases where the connection failed e.g. auth error or connection error
19230
- if (!connectionEstablished) {
19231
- reject(e);
19232
- }
19233
- },
19234
- onNext: (payload) => {
19235
- // The connection is active
19236
- if (!connectionEstablished) {
19237
- connectionEstablished = true;
19238
- resolve(res);
19239
- }
19240
- const { data } = payload;
19241
- // Less events are now pending
19242
- pendingEventsCount--;
19243
- if (!data) {
19244
- return;
19245
- }
19246
- const deserializedData = bson.deserialize(data);
19247
- stream.enqueueData(deserializedData);
19248
- },
19249
- onComplete: () => {
19250
- stream.close();
19251
- },
19252
- onExtension: () => { }
19253
- });
19254
- });
19255
- const l = stream.registerListener({
19256
- lowWater: async () => {
19257
- // Request to fill up the queue
19258
- const required = SYNC_QUEUE_REQUEST_N - pendingEventsCount;
19259
- if (required > 0) {
19260
- socket.request(SYNC_QUEUE_REQUEST_N - pendingEventsCount);
19261
- pendingEventsCount = SYNC_QUEUE_REQUEST_N;
19262
- }
19263
- },
19264
- closed: () => {
19265
- closeSocket();
19266
- l?.();
19267
- }
19268
- });
19269
- /**
19270
- * Handle abort operations here.
19271
- * Unfortunately cannot insert them into the connection.
19272
- */
19273
- if (options.abortSignal?.aborted) {
19274
- stream.close();
19275
- }
19276
- else {
19277
- options.abortSignal?.addEventListener('abort', () => {
19278
- stream.close();
19279
- });
19280
- }
19281
- return stream;
19282
- }
19283
- /**
19284
- * Connects to the sync/stream http endpoint
19285
- */
19286
- async postStream(options) {
19287
- const { data, path, headers, abortSignal } = options;
19288
- const request = await this.buildRequest(path);
19289
- /**
19290
- * This abort controller will abort pending fetch requests.
19291
- * If the request has resolved, it will be used to close the readable stream.
19292
- * Which will cancel the network request.
19089
+ var buffer = {};
19090
+
19091
+ /*!
19092
+ * The buffer module from node.js, for the browser.
19093
+ *
19094
+ * @author Feross Aboukhadijeh <https://feross.org>
19095
+ * @license MIT
19096
+ */
19097
+
19098
+ (function (exports) {
19099
+
19100
+ const base64 = base64Js;
19101
+ const ieee754$1 = ieee754;
19102
+ const customInspectSymbol =
19103
+ (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
19104
+ ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
19105
+ : null;
19106
+
19107
+ exports.Buffer = Buffer;
19108
+ exports.SlowBuffer = SlowBuffer;
19109
+ exports.INSPECT_MAX_BYTES = 50;
19110
+
19111
+ const K_MAX_LENGTH = 0x7fffffff;
19112
+ exports.kMaxLength = K_MAX_LENGTH;
19113
+
19114
+ /**
19115
+ * If `Buffer.TYPED_ARRAY_SUPPORT`:
19116
+ * === true Use Uint8Array implementation (fastest)
19117
+ * === false Print warning and recommend using `buffer` v4.x which has an Object
19118
+ * implementation (most compatible, even IE6)
19119
+ *
19120
+ * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
19121
+ * Opera 11.6+, iOS 4.2+.
19122
+ *
19123
+ * We report that the browser does not support typed arrays if the are not subclassable
19124
+ * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
19125
+ * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
19126
+ * for __proto__ and has a buggy typed array implementation.
19127
+ */
19128
+ Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
19129
+
19130
+ if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
19131
+ typeof console.error === 'function') {
19132
+ console.error(
19133
+ 'This browser lacks typed array (Uint8Array) support which is required by ' +
19134
+ '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
19135
+ );
19136
+ }
19137
+
19138
+ function typedArraySupport () {
19139
+ // Can typed array instances can be augmented?
19140
+ try {
19141
+ const arr = new Uint8Array(1);
19142
+ const proto = { foo: function () { return 42 } };
19143
+ Object.setPrototypeOf(proto, Uint8Array.prototype);
19144
+ Object.setPrototypeOf(arr, proto);
19145
+ return arr.foo() === 42
19146
+ } catch (e) {
19147
+ return false
19148
+ }
19149
+ }
19150
+
19151
+ Object.defineProperty(Buffer.prototype, 'parent', {
19152
+ enumerable: true,
19153
+ get: function () {
19154
+ if (!Buffer.isBuffer(this)) return undefined
19155
+ return this.buffer
19156
+ }
19157
+ });
19158
+
19159
+ Object.defineProperty(Buffer.prototype, 'offset', {
19160
+ enumerable: true,
19161
+ get: function () {
19162
+ if (!Buffer.isBuffer(this)) return undefined
19163
+ return this.byteOffset
19164
+ }
19165
+ });
19166
+
19167
+ function createBuffer (length) {
19168
+ if (length > K_MAX_LENGTH) {
19169
+ throw new RangeError('The value "' + length + '" is invalid for option "size"')
19170
+ }
19171
+ // Return an augmented `Uint8Array` instance
19172
+ const buf = new Uint8Array(length);
19173
+ Object.setPrototypeOf(buf, Buffer.prototype);
19174
+ return buf
19175
+ }
19176
+
19177
+ /**
19178
+ * The Buffer constructor returns instances of `Uint8Array` that have their
19179
+ * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
19180
+ * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
19181
+ * and the `Uint8Array` methods. Square bracket notation works as expected -- it
19182
+ * returns a single octet.
19183
+ *
19184
+ * The `Uint8Array` prototype remains unmodified.
19185
+ */
19186
+
19187
+ function Buffer (arg, encodingOrOffset, length) {
19188
+ // Common case.
19189
+ if (typeof arg === 'number') {
19190
+ if (typeof encodingOrOffset === 'string') {
19191
+ throw new TypeError(
19192
+ 'The "string" argument must be of type string. Received type number'
19193
+ )
19194
+ }
19195
+ return allocUnsafe(arg)
19196
+ }
19197
+ return from(arg, encodingOrOffset, length)
19198
+ }
19199
+
19200
+ Buffer.poolSize = 8192; // not used by this implementation
19201
+
19202
+ function from (value, encodingOrOffset, length) {
19203
+ if (typeof value === 'string') {
19204
+ return fromString(value, encodingOrOffset)
19205
+ }
19206
+
19207
+ if (ArrayBuffer.isView(value)) {
19208
+ return fromArrayView(value)
19209
+ }
19210
+
19211
+ if (value == null) {
19212
+ throw new TypeError(
19213
+ 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
19214
+ 'or Array-like Object. Received type ' + (typeof value)
19215
+ )
19216
+ }
19217
+
19218
+ if (isInstance(value, ArrayBuffer) ||
19219
+ (value && isInstance(value.buffer, ArrayBuffer))) {
19220
+ return fromArrayBuffer(value, encodingOrOffset, length)
19221
+ }
19222
+
19223
+ if (typeof SharedArrayBuffer !== 'undefined' &&
19224
+ (isInstance(value, SharedArrayBuffer) ||
19225
+ (value && isInstance(value.buffer, SharedArrayBuffer)))) {
19226
+ return fromArrayBuffer(value, encodingOrOffset, length)
19227
+ }
19228
+
19229
+ if (typeof value === 'number') {
19230
+ throw new TypeError(
19231
+ 'The "value" argument must not be of type number. Received type number'
19232
+ )
19233
+ }
19234
+
19235
+ const valueOf = value.valueOf && value.valueOf();
19236
+ if (valueOf != null && valueOf !== value) {
19237
+ return Buffer.from(valueOf, encodingOrOffset, length)
19238
+ }
19239
+
19240
+ const b = fromObject(value);
19241
+ if (b) return b
19242
+
19243
+ if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
19244
+ typeof value[Symbol.toPrimitive] === 'function') {
19245
+ return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)
19246
+ }
19247
+
19248
+ throw new TypeError(
19249
+ 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
19250
+ 'or Array-like Object. Received type ' + (typeof value)
19251
+ )
19252
+ }
19253
+
19254
+ /**
19255
+ * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
19256
+ * if value is a number.
19257
+ * Buffer.from(str[, encoding])
19258
+ * Buffer.from(array)
19259
+ * Buffer.from(buffer)
19260
+ * Buffer.from(arrayBuffer[, byteOffset[, length]])
19261
+ **/
19262
+ Buffer.from = function (value, encodingOrOffset, length) {
19263
+ return from(value, encodingOrOffset, length)
19264
+ };
19265
+
19266
+ // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
19267
+ // https://github.com/feross/buffer/pull/148
19268
+ Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
19269
+ Object.setPrototypeOf(Buffer, Uint8Array);
19270
+
19271
+ function assertSize (size) {
19272
+ if (typeof size !== 'number') {
19273
+ throw new TypeError('"size" argument must be of type number')
19274
+ } else if (size < 0) {
19275
+ throw new RangeError('The value "' + size + '" is invalid for option "size"')
19276
+ }
19277
+ }
19278
+
19279
+ function alloc (size, fill, encoding) {
19280
+ assertSize(size);
19281
+ if (size <= 0) {
19282
+ return createBuffer(size)
19283
+ }
19284
+ if (fill !== undefined) {
19285
+ // Only pay attention to encoding if it's a string. This
19286
+ // prevents accidentally sending in a number that would
19287
+ // be interpreted as a start offset.
19288
+ return typeof encoding === 'string'
19289
+ ? createBuffer(size).fill(fill, encoding)
19290
+ : createBuffer(size).fill(fill)
19291
+ }
19292
+ return createBuffer(size)
19293
+ }
19294
+
19295
+ /**
19296
+ * Creates a new filled Buffer instance.
19297
+ * alloc(size[, fill[, encoding]])
19298
+ **/
19299
+ Buffer.alloc = function (size, fill, encoding) {
19300
+ return alloc(size, fill, encoding)
19301
+ };
19302
+
19303
+ function allocUnsafe (size) {
19304
+ assertSize(size);
19305
+ return createBuffer(size < 0 ? 0 : checked(size) | 0)
19306
+ }
19307
+
19308
+ /**
19309
+ * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
19310
+ * */
19311
+ Buffer.allocUnsafe = function (size) {
19312
+ return allocUnsafe(size)
19313
+ };
19314
+ /**
19315
+ * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
19316
+ */
19317
+ Buffer.allocUnsafeSlow = function (size) {
19318
+ return allocUnsafe(size)
19319
+ };
19320
+
19321
+ function fromString (string, encoding) {
19322
+ if (typeof encoding !== 'string' || encoding === '') {
19323
+ encoding = 'utf8';
19324
+ }
19325
+
19326
+ if (!Buffer.isEncoding(encoding)) {
19327
+ throw new TypeError('Unknown encoding: ' + encoding)
19328
+ }
19329
+
19330
+ const length = byteLength(string, encoding) | 0;
19331
+ let buf = createBuffer(length);
19332
+
19333
+ const actual = buf.write(string, encoding);
19334
+
19335
+ if (actual !== length) {
19336
+ // Writing a hex string, for example, that contains invalid characters will
19337
+ // cause everything after the first invalid character to be ignored. (e.g.
19338
+ // 'abxxcd' will be treated as 'ab')
19339
+ buf = buf.slice(0, actual);
19340
+ }
19341
+
19342
+ return buf
19343
+ }
19344
+
19345
+ function fromArrayLike (array) {
19346
+ const length = array.length < 0 ? 0 : checked(array.length) | 0;
19347
+ const buf = createBuffer(length);
19348
+ for (let i = 0; i < length; i += 1) {
19349
+ buf[i] = array[i] & 255;
19350
+ }
19351
+ return buf
19352
+ }
19353
+
19354
+ function fromArrayView (arrayView) {
19355
+ if (isInstance(arrayView, Uint8Array)) {
19356
+ const copy = new Uint8Array(arrayView);
19357
+ return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
19358
+ }
19359
+ return fromArrayLike(arrayView)
19360
+ }
19361
+
19362
+ function fromArrayBuffer (array, byteOffset, length) {
19363
+ if (byteOffset < 0 || array.byteLength < byteOffset) {
19364
+ throw new RangeError('"offset" is outside of buffer bounds')
19365
+ }
19366
+
19367
+ if (array.byteLength < byteOffset + (length || 0)) {
19368
+ throw new RangeError('"length" is outside of buffer bounds')
19369
+ }
19370
+
19371
+ let buf;
19372
+ if (byteOffset === undefined && length === undefined) {
19373
+ buf = new Uint8Array(array);
19374
+ } else if (length === undefined) {
19375
+ buf = new Uint8Array(array, byteOffset);
19376
+ } else {
19377
+ buf = new Uint8Array(array, byteOffset, length);
19378
+ }
19379
+
19380
+ // Return an augmented `Uint8Array` instance
19381
+ Object.setPrototypeOf(buf, Buffer.prototype);
19382
+
19383
+ return buf
19384
+ }
19385
+
19386
+ function fromObject (obj) {
19387
+ if (Buffer.isBuffer(obj)) {
19388
+ const len = checked(obj.length) | 0;
19389
+ const buf = createBuffer(len);
19390
+
19391
+ if (buf.length === 0) {
19392
+ return buf
19393
+ }
19394
+
19395
+ obj.copy(buf, 0, 0, len);
19396
+ return buf
19397
+ }
19398
+
19399
+ if (obj.length !== undefined) {
19400
+ if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
19401
+ return createBuffer(0)
19402
+ }
19403
+ return fromArrayLike(obj)
19404
+ }
19405
+
19406
+ if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
19407
+ return fromArrayLike(obj.data)
19408
+ }
19409
+ }
19410
+
19411
+ function checked (length) {
19412
+ // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
19413
+ // length is NaN (which is otherwise coerced to zero.)
19414
+ if (length >= K_MAX_LENGTH) {
19415
+ throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
19416
+ 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
19417
+ }
19418
+ return length | 0
19419
+ }
19420
+
19421
+ function SlowBuffer (length) {
19422
+ if (+length != length) { // eslint-disable-line eqeqeq
19423
+ length = 0;
19424
+ }
19425
+ return Buffer.alloc(+length)
19426
+ }
19427
+
19428
+ Buffer.isBuffer = function isBuffer (b) {
19429
+ return b != null && b._isBuffer === true &&
19430
+ b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
19431
+ };
19432
+
19433
+ Buffer.compare = function compare (a, b) {
19434
+ if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
19435
+ if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
19436
+ if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
19437
+ throw new TypeError(
19438
+ 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
19439
+ )
19440
+ }
19441
+
19442
+ if (a === b) return 0
19443
+
19444
+ let x = a.length;
19445
+ let y = b.length;
19446
+
19447
+ for (let i = 0, len = Math.min(x, y); i < len; ++i) {
19448
+ if (a[i] !== b[i]) {
19449
+ x = a[i];
19450
+ y = b[i];
19451
+ break
19452
+ }
19453
+ }
19454
+
19455
+ if (x < y) return -1
19456
+ if (y < x) return 1
19457
+ return 0
19458
+ };
19459
+
19460
+ Buffer.isEncoding = function isEncoding (encoding) {
19461
+ switch (String(encoding).toLowerCase()) {
19462
+ case 'hex':
19463
+ case 'utf8':
19464
+ case 'utf-8':
19465
+ case 'ascii':
19466
+ case 'latin1':
19467
+ case 'binary':
19468
+ case 'base64':
19469
+ case 'ucs2':
19470
+ case 'ucs-2':
19471
+ case 'utf16le':
19472
+ case 'utf-16le':
19473
+ return true
19474
+ default:
19475
+ return false
19476
+ }
19477
+ };
19478
+
19479
+ Buffer.concat = function concat (list, length) {
19480
+ if (!Array.isArray(list)) {
19481
+ throw new TypeError('"list" argument must be an Array of Buffers')
19482
+ }
19483
+
19484
+ if (list.length === 0) {
19485
+ return Buffer.alloc(0)
19486
+ }
19487
+
19488
+ let i;
19489
+ if (length === undefined) {
19490
+ length = 0;
19491
+ for (i = 0; i < list.length; ++i) {
19492
+ length += list[i].length;
19493
+ }
19494
+ }
19495
+
19496
+ const buffer = Buffer.allocUnsafe(length);
19497
+ let pos = 0;
19498
+ for (i = 0; i < list.length; ++i) {
19499
+ let buf = list[i];
19500
+ if (isInstance(buf, Uint8Array)) {
19501
+ if (pos + buf.length > buffer.length) {
19502
+ if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf);
19503
+ buf.copy(buffer, pos);
19504
+ } else {
19505
+ Uint8Array.prototype.set.call(
19506
+ buffer,
19507
+ buf,
19508
+ pos
19509
+ );
19510
+ }
19511
+ } else if (!Buffer.isBuffer(buf)) {
19512
+ throw new TypeError('"list" argument must be an Array of Buffers')
19513
+ } else {
19514
+ buf.copy(buffer, pos);
19515
+ }
19516
+ pos += buf.length;
19517
+ }
19518
+ return buffer
19519
+ };
19520
+
19521
+ function byteLength (string, encoding) {
19522
+ if (Buffer.isBuffer(string)) {
19523
+ return string.length
19524
+ }
19525
+ if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
19526
+ return string.byteLength
19527
+ }
19528
+ if (typeof string !== 'string') {
19529
+ throw new TypeError(
19530
+ 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
19531
+ 'Received type ' + typeof string
19532
+ )
19533
+ }
19534
+
19535
+ const len = string.length;
19536
+ const mustMatch = (arguments.length > 2 && arguments[2] === true);
19537
+ if (!mustMatch && len === 0) return 0
19538
+
19539
+ // Use a for loop to avoid recursion
19540
+ let loweredCase = false;
19541
+ for (;;) {
19542
+ switch (encoding) {
19543
+ case 'ascii':
19544
+ case 'latin1':
19545
+ case 'binary':
19546
+ return len
19547
+ case 'utf8':
19548
+ case 'utf-8':
19549
+ return utf8ToBytes(string).length
19550
+ case 'ucs2':
19551
+ case 'ucs-2':
19552
+ case 'utf16le':
19553
+ case 'utf-16le':
19554
+ return len * 2
19555
+ case 'hex':
19556
+ return len >>> 1
19557
+ case 'base64':
19558
+ return base64ToBytes(string).length
19559
+ default:
19560
+ if (loweredCase) {
19561
+ return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
19562
+ }
19563
+ encoding = ('' + encoding).toLowerCase();
19564
+ loweredCase = true;
19565
+ }
19566
+ }
19567
+ }
19568
+ Buffer.byteLength = byteLength;
19569
+
19570
+ function slowToString (encoding, start, end) {
19571
+ let loweredCase = false;
19572
+
19573
+ // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
19574
+ // property of a typed array.
19575
+
19576
+ // This behaves neither like String nor Uint8Array in that we set start/end
19577
+ // to their upper/lower bounds if the value passed is out of range.
19578
+ // undefined is handled specially as per ECMA-262 6th Edition,
19579
+ // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
19580
+ if (start === undefined || start < 0) {
19581
+ start = 0;
19582
+ }
19583
+ // Return early if start > this.length. Done here to prevent potential uint32
19584
+ // coercion fail below.
19585
+ if (start > this.length) {
19586
+ return ''
19587
+ }
19588
+
19589
+ if (end === undefined || end > this.length) {
19590
+ end = this.length;
19591
+ }
19592
+
19593
+ if (end <= 0) {
19594
+ return ''
19595
+ }
19596
+
19597
+ // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
19598
+ end >>>= 0;
19599
+ start >>>= 0;
19600
+
19601
+ if (end <= start) {
19602
+ return ''
19603
+ }
19604
+
19605
+ if (!encoding) encoding = 'utf8';
19606
+
19607
+ while (true) {
19608
+ switch (encoding) {
19609
+ case 'hex':
19610
+ return hexSlice(this, start, end)
19611
+
19612
+ case 'utf8':
19613
+ case 'utf-8':
19614
+ return utf8Slice(this, start, end)
19615
+
19616
+ case 'ascii':
19617
+ return asciiSlice(this, start, end)
19618
+
19619
+ case 'latin1':
19620
+ case 'binary':
19621
+ return latin1Slice(this, start, end)
19622
+
19623
+ case 'base64':
19624
+ return base64Slice(this, start, end)
19625
+
19626
+ case 'ucs2':
19627
+ case 'ucs-2':
19628
+ case 'utf16le':
19629
+ case 'utf-16le':
19630
+ return utf16leSlice(this, start, end)
19631
+
19632
+ default:
19633
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
19634
+ encoding = (encoding + '').toLowerCase();
19635
+ loweredCase = true;
19636
+ }
19637
+ }
19638
+ }
19639
+
19640
+ // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
19641
+ // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
19642
+ // reliably in a browserify context because there could be multiple different
19643
+ // copies of the 'buffer' package in use. This method works even for Buffer
19644
+ // instances that were created from another copy of the `buffer` package.
19645
+ // See: https://github.com/feross/buffer/issues/154
19646
+ Buffer.prototype._isBuffer = true;
19647
+
19648
+ function swap (b, n, m) {
19649
+ const i = b[n];
19650
+ b[n] = b[m];
19651
+ b[m] = i;
19652
+ }
19653
+
19654
+ Buffer.prototype.swap16 = function swap16 () {
19655
+ const len = this.length;
19656
+ if (len % 2 !== 0) {
19657
+ throw new RangeError('Buffer size must be a multiple of 16-bits')
19658
+ }
19659
+ for (let i = 0; i < len; i += 2) {
19660
+ swap(this, i, i + 1);
19661
+ }
19662
+ return this
19663
+ };
19664
+
19665
+ Buffer.prototype.swap32 = function swap32 () {
19666
+ const len = this.length;
19667
+ if (len % 4 !== 0) {
19668
+ throw new RangeError('Buffer size must be a multiple of 32-bits')
19669
+ }
19670
+ for (let i = 0; i < len; i += 4) {
19671
+ swap(this, i, i + 3);
19672
+ swap(this, i + 1, i + 2);
19673
+ }
19674
+ return this
19675
+ };
19676
+
19677
+ Buffer.prototype.swap64 = function swap64 () {
19678
+ const len = this.length;
19679
+ if (len % 8 !== 0) {
19680
+ throw new RangeError('Buffer size must be a multiple of 64-bits')
19681
+ }
19682
+ for (let i = 0; i < len; i += 8) {
19683
+ swap(this, i, i + 7);
19684
+ swap(this, i + 1, i + 6);
19685
+ swap(this, i + 2, i + 5);
19686
+ swap(this, i + 3, i + 4);
19687
+ }
19688
+ return this
19689
+ };
19690
+
19691
+ Buffer.prototype.toString = function toString () {
19692
+ const length = this.length;
19693
+ if (length === 0) return ''
19694
+ if (arguments.length === 0) return utf8Slice(this, 0, length)
19695
+ return slowToString.apply(this, arguments)
19696
+ };
19697
+
19698
+ Buffer.prototype.toLocaleString = Buffer.prototype.toString;
19699
+
19700
+ Buffer.prototype.equals = function equals (b) {
19701
+ if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
19702
+ if (this === b) return true
19703
+ return Buffer.compare(this, b) === 0
19704
+ };
19705
+
19706
+ Buffer.prototype.inspect = function inspect () {
19707
+ let str = '';
19708
+ const max = exports.INSPECT_MAX_BYTES;
19709
+ str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
19710
+ if (this.length > max) str += ' ... ';
19711
+ return '<Buffer ' + str + '>'
19712
+ };
19713
+ if (customInspectSymbol) {
19714
+ Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
19715
+ }
19716
+
19717
+ Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
19718
+ if (isInstance(target, Uint8Array)) {
19719
+ target = Buffer.from(target, target.offset, target.byteLength);
19720
+ }
19721
+ if (!Buffer.isBuffer(target)) {
19722
+ throw new TypeError(
19723
+ 'The "target" argument must be one of type Buffer or Uint8Array. ' +
19724
+ 'Received type ' + (typeof target)
19725
+ )
19726
+ }
19727
+
19728
+ if (start === undefined) {
19729
+ start = 0;
19730
+ }
19731
+ if (end === undefined) {
19732
+ end = target ? target.length : 0;
19733
+ }
19734
+ if (thisStart === undefined) {
19735
+ thisStart = 0;
19736
+ }
19737
+ if (thisEnd === undefined) {
19738
+ thisEnd = this.length;
19739
+ }
19740
+
19741
+ if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
19742
+ throw new RangeError('out of range index')
19743
+ }
19744
+
19745
+ if (thisStart >= thisEnd && start >= end) {
19746
+ return 0
19747
+ }
19748
+ if (thisStart >= thisEnd) {
19749
+ return -1
19750
+ }
19751
+ if (start >= end) {
19752
+ return 1
19753
+ }
19754
+
19755
+ start >>>= 0;
19756
+ end >>>= 0;
19757
+ thisStart >>>= 0;
19758
+ thisEnd >>>= 0;
19759
+
19760
+ if (this === target) return 0
19761
+
19762
+ let x = thisEnd - thisStart;
19763
+ let y = end - start;
19764
+ const len = Math.min(x, y);
19765
+
19766
+ const thisCopy = this.slice(thisStart, thisEnd);
19767
+ const targetCopy = target.slice(start, end);
19768
+
19769
+ for (let i = 0; i < len; ++i) {
19770
+ if (thisCopy[i] !== targetCopy[i]) {
19771
+ x = thisCopy[i];
19772
+ y = targetCopy[i];
19773
+ break
19774
+ }
19775
+ }
19776
+
19777
+ if (x < y) return -1
19778
+ if (y < x) return 1
19779
+ return 0
19780
+ };
19781
+
19782
+ // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
19783
+ // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
19784
+ //
19785
+ // Arguments:
19786
+ // - buffer - a Buffer to search
19787
+ // - val - a string, Buffer, or number
19788
+ // - byteOffset - an index into `buffer`; will be clamped to an int32
19789
+ // - encoding - an optional encoding, relevant is val is a string
19790
+ // - dir - true for indexOf, false for lastIndexOf
19791
+ function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
19792
+ // Empty buffer means no match
19793
+ if (buffer.length === 0) return -1
19794
+
19795
+ // Normalize byteOffset
19796
+ if (typeof byteOffset === 'string') {
19797
+ encoding = byteOffset;
19798
+ byteOffset = 0;
19799
+ } else if (byteOffset > 0x7fffffff) {
19800
+ byteOffset = 0x7fffffff;
19801
+ } else if (byteOffset < -0x80000000) {
19802
+ byteOffset = -0x80000000;
19803
+ }
19804
+ byteOffset = +byteOffset; // Coerce to Number.
19805
+ if (numberIsNaN(byteOffset)) {
19806
+ // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
19807
+ byteOffset = dir ? 0 : (buffer.length - 1);
19808
+ }
19809
+
19810
+ // Normalize byteOffset: negative offsets start from the end of the buffer
19811
+ if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
19812
+ if (byteOffset >= buffer.length) {
19813
+ if (dir) return -1
19814
+ else byteOffset = buffer.length - 1;
19815
+ } else if (byteOffset < 0) {
19816
+ if (dir) byteOffset = 0;
19817
+ else return -1
19818
+ }
19819
+
19820
+ // Normalize val
19821
+ if (typeof val === 'string') {
19822
+ val = Buffer.from(val, encoding);
19823
+ }
19824
+
19825
+ // Finally, search either indexOf (if dir is true) or lastIndexOf
19826
+ if (Buffer.isBuffer(val)) {
19827
+ // Special case: looking for empty string/buffer always fails
19828
+ if (val.length === 0) {
19829
+ return -1
19830
+ }
19831
+ return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
19832
+ } else if (typeof val === 'number') {
19833
+ val = val & 0xFF; // Search for a byte value [0-255]
19834
+ if (typeof Uint8Array.prototype.indexOf === 'function') {
19835
+ if (dir) {
19836
+ return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
19837
+ } else {
19838
+ return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
19839
+ }
19840
+ }
19841
+ return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
19842
+ }
19843
+
19844
+ throw new TypeError('val must be string, number or Buffer')
19845
+ }
19846
+
19847
+ function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
19848
+ let indexSize = 1;
19849
+ let arrLength = arr.length;
19850
+ let valLength = val.length;
19851
+
19852
+ if (encoding !== undefined) {
19853
+ encoding = String(encoding).toLowerCase();
19854
+ if (encoding === 'ucs2' || encoding === 'ucs-2' ||
19855
+ encoding === 'utf16le' || encoding === 'utf-16le') {
19856
+ if (arr.length < 2 || val.length < 2) {
19857
+ return -1
19858
+ }
19859
+ indexSize = 2;
19860
+ arrLength /= 2;
19861
+ valLength /= 2;
19862
+ byteOffset /= 2;
19863
+ }
19864
+ }
19865
+
19866
+ function read (buf, i) {
19867
+ if (indexSize === 1) {
19868
+ return buf[i]
19869
+ } else {
19870
+ return buf.readUInt16BE(i * indexSize)
19871
+ }
19872
+ }
19873
+
19874
+ let i;
19875
+ if (dir) {
19876
+ let foundIndex = -1;
19877
+ for (i = byteOffset; i < arrLength; i++) {
19878
+ if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
19879
+ if (foundIndex === -1) foundIndex = i;
19880
+ if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
19881
+ } else {
19882
+ if (foundIndex !== -1) i -= i - foundIndex;
19883
+ foundIndex = -1;
19884
+ }
19885
+ }
19886
+ } else {
19887
+ if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
19888
+ for (i = byteOffset; i >= 0; i--) {
19889
+ let found = true;
19890
+ for (let j = 0; j < valLength; j++) {
19891
+ if (read(arr, i + j) !== read(val, j)) {
19892
+ found = false;
19893
+ break
19894
+ }
19895
+ }
19896
+ if (found) return i
19897
+ }
19898
+ }
19899
+
19900
+ return -1
19901
+ }
19902
+
19903
+ Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
19904
+ return this.indexOf(val, byteOffset, encoding) !== -1
19905
+ };
19906
+
19907
+ Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
19908
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
19909
+ };
19910
+
19911
+ Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
19912
+ return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
19913
+ };
19914
+
19915
+ function hexWrite (buf, string, offset, length) {
19916
+ offset = Number(offset) || 0;
19917
+ const remaining = buf.length - offset;
19918
+ if (!length) {
19919
+ length = remaining;
19920
+ } else {
19921
+ length = Number(length);
19922
+ if (length > remaining) {
19923
+ length = remaining;
19924
+ }
19925
+ }
19926
+
19927
+ const strLen = string.length;
19928
+
19929
+ if (length > strLen / 2) {
19930
+ length = strLen / 2;
19931
+ }
19932
+ let i;
19933
+ for (i = 0; i < length; ++i) {
19934
+ const parsed = parseInt(string.substr(i * 2, 2), 16);
19935
+ if (numberIsNaN(parsed)) return i
19936
+ buf[offset + i] = parsed;
19937
+ }
19938
+ return i
19939
+ }
19940
+
19941
+ function utf8Write (buf, string, offset, length) {
19942
+ return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
19943
+ }
19944
+
19945
+ function asciiWrite (buf, string, offset, length) {
19946
+ return blitBuffer(asciiToBytes(string), buf, offset, length)
19947
+ }
19948
+
19949
+ function base64Write (buf, string, offset, length) {
19950
+ return blitBuffer(base64ToBytes(string), buf, offset, length)
19951
+ }
19952
+
19953
+ function ucs2Write (buf, string, offset, length) {
19954
+ return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
19955
+ }
19956
+
19957
+ Buffer.prototype.write = function write (string, offset, length, encoding) {
19958
+ // Buffer#write(string)
19959
+ if (offset === undefined) {
19960
+ encoding = 'utf8';
19961
+ length = this.length;
19962
+ offset = 0;
19963
+ // Buffer#write(string, encoding)
19964
+ } else if (length === undefined && typeof offset === 'string') {
19965
+ encoding = offset;
19966
+ length = this.length;
19967
+ offset = 0;
19968
+ // Buffer#write(string, offset[, length][, encoding])
19969
+ } else if (isFinite(offset)) {
19970
+ offset = offset >>> 0;
19971
+ if (isFinite(length)) {
19972
+ length = length >>> 0;
19973
+ if (encoding === undefined) encoding = 'utf8';
19974
+ } else {
19975
+ encoding = length;
19976
+ length = undefined;
19977
+ }
19978
+ } else {
19979
+ throw new Error(
19980
+ 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
19981
+ )
19982
+ }
19983
+
19984
+ const remaining = this.length - offset;
19985
+ if (length === undefined || length > remaining) length = remaining;
19986
+
19987
+ if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
19988
+ throw new RangeError('Attempt to write outside buffer bounds')
19989
+ }
19990
+
19991
+ if (!encoding) encoding = 'utf8';
19992
+
19993
+ let loweredCase = false;
19994
+ for (;;) {
19995
+ switch (encoding) {
19996
+ case 'hex':
19997
+ return hexWrite(this, string, offset, length)
19998
+
19999
+ case 'utf8':
20000
+ case 'utf-8':
20001
+ return utf8Write(this, string, offset, length)
20002
+
20003
+ case 'ascii':
20004
+ case 'latin1':
20005
+ case 'binary':
20006
+ return asciiWrite(this, string, offset, length)
20007
+
20008
+ case 'base64':
20009
+ // Warning: maxLength not taken into account in base64Write
20010
+ return base64Write(this, string, offset, length)
20011
+
20012
+ case 'ucs2':
20013
+ case 'ucs-2':
20014
+ case 'utf16le':
20015
+ case 'utf-16le':
20016
+ return ucs2Write(this, string, offset, length)
20017
+
20018
+ default:
20019
+ if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
20020
+ encoding = ('' + encoding).toLowerCase();
20021
+ loweredCase = true;
20022
+ }
20023
+ }
20024
+ };
20025
+
20026
+ Buffer.prototype.toJSON = function toJSON () {
20027
+ return {
20028
+ type: 'Buffer',
20029
+ data: Array.prototype.slice.call(this._arr || this, 0)
20030
+ }
20031
+ };
20032
+
20033
+ function base64Slice (buf, start, end) {
20034
+ if (start === 0 && end === buf.length) {
20035
+ return base64.fromByteArray(buf)
20036
+ } else {
20037
+ return base64.fromByteArray(buf.slice(start, end))
20038
+ }
20039
+ }
20040
+
20041
+ function utf8Slice (buf, start, end) {
20042
+ end = Math.min(buf.length, end);
20043
+ const res = [];
20044
+
20045
+ let i = start;
20046
+ while (i < end) {
20047
+ const firstByte = buf[i];
20048
+ let codePoint = null;
20049
+ let bytesPerSequence = (firstByte > 0xEF)
20050
+ ? 4
20051
+ : (firstByte > 0xDF)
20052
+ ? 3
20053
+ : (firstByte > 0xBF)
20054
+ ? 2
20055
+ : 1;
20056
+
20057
+ if (i + bytesPerSequence <= end) {
20058
+ let secondByte, thirdByte, fourthByte, tempCodePoint;
20059
+
20060
+ switch (bytesPerSequence) {
20061
+ case 1:
20062
+ if (firstByte < 0x80) {
20063
+ codePoint = firstByte;
20064
+ }
20065
+ break
20066
+ case 2:
20067
+ secondByte = buf[i + 1];
20068
+ if ((secondByte & 0xC0) === 0x80) {
20069
+ tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
20070
+ if (tempCodePoint > 0x7F) {
20071
+ codePoint = tempCodePoint;
20072
+ }
20073
+ }
20074
+ break
20075
+ case 3:
20076
+ secondByte = buf[i + 1];
20077
+ thirdByte = buf[i + 2];
20078
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
20079
+ tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
20080
+ if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
20081
+ codePoint = tempCodePoint;
20082
+ }
20083
+ }
20084
+ break
20085
+ case 4:
20086
+ secondByte = buf[i + 1];
20087
+ thirdByte = buf[i + 2];
20088
+ fourthByte = buf[i + 3];
20089
+ if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
20090
+ tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
20091
+ if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
20092
+ codePoint = tempCodePoint;
20093
+ }
20094
+ }
20095
+ }
20096
+ }
20097
+
20098
+ if (codePoint === null) {
20099
+ // we did not generate a valid codePoint so insert a
20100
+ // replacement char (U+FFFD) and advance only 1 byte
20101
+ codePoint = 0xFFFD;
20102
+ bytesPerSequence = 1;
20103
+ } else if (codePoint > 0xFFFF) {
20104
+ // encode to utf16 (surrogate pair dance)
20105
+ codePoint -= 0x10000;
20106
+ res.push(codePoint >>> 10 & 0x3FF | 0xD800);
20107
+ codePoint = 0xDC00 | codePoint & 0x3FF;
20108
+ }
20109
+
20110
+ res.push(codePoint);
20111
+ i += bytesPerSequence;
20112
+ }
20113
+
20114
+ return decodeCodePointsArray(res)
20115
+ }
20116
+
20117
+ // Based on http://stackoverflow.com/a/22747272/680742, the browser with
20118
+ // the lowest limit is Chrome, with 0x10000 args.
20119
+ // We go 1 magnitude less, for safety
20120
+ const MAX_ARGUMENTS_LENGTH = 0x1000;
20121
+
20122
+ function decodeCodePointsArray (codePoints) {
20123
+ const len = codePoints.length;
20124
+ if (len <= MAX_ARGUMENTS_LENGTH) {
20125
+ return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
20126
+ }
20127
+
20128
+ // Decode in chunks to avoid "call stack size exceeded".
20129
+ let res = '';
20130
+ let i = 0;
20131
+ while (i < len) {
20132
+ res += String.fromCharCode.apply(
20133
+ String,
20134
+ codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
20135
+ );
20136
+ }
20137
+ return res
20138
+ }
20139
+
20140
+ function asciiSlice (buf, start, end) {
20141
+ let ret = '';
20142
+ end = Math.min(buf.length, end);
20143
+
20144
+ for (let i = start; i < end; ++i) {
20145
+ ret += String.fromCharCode(buf[i] & 0x7F);
20146
+ }
20147
+ return ret
20148
+ }
20149
+
20150
+ function latin1Slice (buf, start, end) {
20151
+ let ret = '';
20152
+ end = Math.min(buf.length, end);
20153
+
20154
+ for (let i = start; i < end; ++i) {
20155
+ ret += String.fromCharCode(buf[i]);
20156
+ }
20157
+ return ret
20158
+ }
20159
+
20160
+ function hexSlice (buf, start, end) {
20161
+ const len = buf.length;
20162
+
20163
+ if (!start || start < 0) start = 0;
20164
+ if (!end || end < 0 || end > len) end = len;
20165
+
20166
+ let out = '';
20167
+ for (let i = start; i < end; ++i) {
20168
+ out += hexSliceLookupTable[buf[i]];
20169
+ }
20170
+ return out
20171
+ }
20172
+
20173
+ function utf16leSlice (buf, start, end) {
20174
+ const bytes = buf.slice(start, end);
20175
+ let res = '';
20176
+ // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
20177
+ for (let i = 0; i < bytes.length - 1; i += 2) {
20178
+ res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256));
20179
+ }
20180
+ return res
20181
+ }
20182
+
20183
+ Buffer.prototype.slice = function slice (start, end) {
20184
+ const len = this.length;
20185
+ start = ~~start;
20186
+ end = end === undefined ? len : ~~end;
20187
+
20188
+ if (start < 0) {
20189
+ start += len;
20190
+ if (start < 0) start = 0;
20191
+ } else if (start > len) {
20192
+ start = len;
20193
+ }
20194
+
20195
+ if (end < 0) {
20196
+ end += len;
20197
+ if (end < 0) end = 0;
20198
+ } else if (end > len) {
20199
+ end = len;
20200
+ }
20201
+
20202
+ if (end < start) end = start;
20203
+
20204
+ const newBuf = this.subarray(start, end);
20205
+ // Return an augmented `Uint8Array` instance
20206
+ Object.setPrototypeOf(newBuf, Buffer.prototype);
20207
+
20208
+ return newBuf
20209
+ };
20210
+
20211
+ /*
20212
+ * Need to make sure that buffer isn't trying to write out of bounds.
20213
+ */
20214
+ function checkOffset (offset, ext, length) {
20215
+ if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
20216
+ if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
20217
+ }
20218
+
20219
+ Buffer.prototype.readUintLE =
20220
+ Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
20221
+ offset = offset >>> 0;
20222
+ byteLength = byteLength >>> 0;
20223
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
20224
+
20225
+ let val = this[offset];
20226
+ let mul = 1;
20227
+ let i = 0;
20228
+ while (++i < byteLength && (mul *= 0x100)) {
20229
+ val += this[offset + i] * mul;
20230
+ }
20231
+
20232
+ return val
20233
+ };
20234
+
20235
+ Buffer.prototype.readUintBE =
20236
+ Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
20237
+ offset = offset >>> 0;
20238
+ byteLength = byteLength >>> 0;
20239
+ if (!noAssert) {
20240
+ checkOffset(offset, byteLength, this.length);
20241
+ }
20242
+
20243
+ let val = this[offset + --byteLength];
20244
+ let mul = 1;
20245
+ while (byteLength > 0 && (mul *= 0x100)) {
20246
+ val += this[offset + --byteLength] * mul;
20247
+ }
20248
+
20249
+ return val
20250
+ };
20251
+
20252
+ Buffer.prototype.readUint8 =
20253
+ Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
20254
+ offset = offset >>> 0;
20255
+ if (!noAssert) checkOffset(offset, 1, this.length);
20256
+ return this[offset]
20257
+ };
20258
+
20259
+ Buffer.prototype.readUint16LE =
20260
+ Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
20261
+ offset = offset >>> 0;
20262
+ if (!noAssert) checkOffset(offset, 2, this.length);
20263
+ return this[offset] | (this[offset + 1] << 8)
20264
+ };
20265
+
20266
+ Buffer.prototype.readUint16BE =
20267
+ Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
20268
+ offset = offset >>> 0;
20269
+ if (!noAssert) checkOffset(offset, 2, this.length);
20270
+ return (this[offset] << 8) | this[offset + 1]
20271
+ };
20272
+
20273
+ Buffer.prototype.readUint32LE =
20274
+ Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
20275
+ offset = offset >>> 0;
20276
+ if (!noAssert) checkOffset(offset, 4, this.length);
20277
+
20278
+ return ((this[offset]) |
20279
+ (this[offset + 1] << 8) |
20280
+ (this[offset + 2] << 16)) +
20281
+ (this[offset + 3] * 0x1000000)
20282
+ };
20283
+
20284
+ Buffer.prototype.readUint32BE =
20285
+ Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
20286
+ offset = offset >>> 0;
20287
+ if (!noAssert) checkOffset(offset, 4, this.length);
20288
+
20289
+ return (this[offset] * 0x1000000) +
20290
+ ((this[offset + 1] << 16) |
20291
+ (this[offset + 2] << 8) |
20292
+ this[offset + 3])
20293
+ };
20294
+
20295
+ Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {
20296
+ offset = offset >>> 0;
20297
+ validateNumber(offset, 'offset');
20298
+ const first = this[offset];
20299
+ const last = this[offset + 7];
20300
+ if (first === undefined || last === undefined) {
20301
+ boundsError(offset, this.length - 8);
20302
+ }
20303
+
20304
+ const lo = first +
20305
+ this[++offset] * 2 ** 8 +
20306
+ this[++offset] * 2 ** 16 +
20307
+ this[++offset] * 2 ** 24;
20308
+
20309
+ const hi = this[++offset] +
20310
+ this[++offset] * 2 ** 8 +
20311
+ this[++offset] * 2 ** 16 +
20312
+ last * 2 ** 24;
20313
+
20314
+ return BigInt(lo) + (BigInt(hi) << BigInt(32))
20315
+ });
20316
+
20317
+ Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {
20318
+ offset = offset >>> 0;
20319
+ validateNumber(offset, 'offset');
20320
+ const first = this[offset];
20321
+ const last = this[offset + 7];
20322
+ if (first === undefined || last === undefined) {
20323
+ boundsError(offset, this.length - 8);
20324
+ }
20325
+
20326
+ const hi = first * 2 ** 24 +
20327
+ this[++offset] * 2 ** 16 +
20328
+ this[++offset] * 2 ** 8 +
20329
+ this[++offset];
20330
+
20331
+ const lo = this[++offset] * 2 ** 24 +
20332
+ this[++offset] * 2 ** 16 +
20333
+ this[++offset] * 2 ** 8 +
20334
+ last;
20335
+
20336
+ return (BigInt(hi) << BigInt(32)) + BigInt(lo)
20337
+ });
20338
+
20339
+ Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
20340
+ offset = offset >>> 0;
20341
+ byteLength = byteLength >>> 0;
20342
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
20343
+
20344
+ let val = this[offset];
20345
+ let mul = 1;
20346
+ let i = 0;
20347
+ while (++i < byteLength && (mul *= 0x100)) {
20348
+ val += this[offset + i] * mul;
20349
+ }
20350
+ mul *= 0x80;
20351
+
20352
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
20353
+
20354
+ return val
20355
+ };
20356
+
20357
+ Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
20358
+ offset = offset >>> 0;
20359
+ byteLength = byteLength >>> 0;
20360
+ if (!noAssert) checkOffset(offset, byteLength, this.length);
20361
+
20362
+ let i = byteLength;
20363
+ let mul = 1;
20364
+ let val = this[offset + --i];
20365
+ while (i > 0 && (mul *= 0x100)) {
20366
+ val += this[offset + --i] * mul;
20367
+ }
20368
+ mul *= 0x80;
20369
+
20370
+ if (val >= mul) val -= Math.pow(2, 8 * byteLength);
20371
+
20372
+ return val
20373
+ };
20374
+
20375
+ Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
20376
+ offset = offset >>> 0;
20377
+ if (!noAssert) checkOffset(offset, 1, this.length);
20378
+ if (!(this[offset] & 0x80)) return (this[offset])
20379
+ return ((0xff - this[offset] + 1) * -1)
20380
+ };
20381
+
20382
+ Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
20383
+ offset = offset >>> 0;
20384
+ if (!noAssert) checkOffset(offset, 2, this.length);
20385
+ const val = this[offset] | (this[offset + 1] << 8);
20386
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
20387
+ };
20388
+
20389
+ Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
20390
+ offset = offset >>> 0;
20391
+ if (!noAssert) checkOffset(offset, 2, this.length);
20392
+ const val = this[offset + 1] | (this[offset] << 8);
20393
+ return (val & 0x8000) ? val | 0xFFFF0000 : val
20394
+ };
20395
+
20396
+ Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
20397
+ offset = offset >>> 0;
20398
+ if (!noAssert) checkOffset(offset, 4, this.length);
20399
+
20400
+ return (this[offset]) |
20401
+ (this[offset + 1] << 8) |
20402
+ (this[offset + 2] << 16) |
20403
+ (this[offset + 3] << 24)
20404
+ };
20405
+
20406
+ Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
20407
+ offset = offset >>> 0;
20408
+ if (!noAssert) checkOffset(offset, 4, this.length);
20409
+
20410
+ return (this[offset] << 24) |
20411
+ (this[offset + 1] << 16) |
20412
+ (this[offset + 2] << 8) |
20413
+ (this[offset + 3])
20414
+ };
20415
+
20416
+ Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {
20417
+ offset = offset >>> 0;
20418
+ validateNumber(offset, 'offset');
20419
+ const first = this[offset];
20420
+ const last = this[offset + 7];
20421
+ if (first === undefined || last === undefined) {
20422
+ boundsError(offset, this.length - 8);
20423
+ }
20424
+
20425
+ const val = this[offset + 4] +
20426
+ this[offset + 5] * 2 ** 8 +
20427
+ this[offset + 6] * 2 ** 16 +
20428
+ (last << 24); // Overflow
20429
+
20430
+ return (BigInt(val) << BigInt(32)) +
20431
+ BigInt(first +
20432
+ this[++offset] * 2 ** 8 +
20433
+ this[++offset] * 2 ** 16 +
20434
+ this[++offset] * 2 ** 24)
20435
+ });
20436
+
20437
+ Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {
20438
+ offset = offset >>> 0;
20439
+ validateNumber(offset, 'offset');
20440
+ const first = this[offset];
20441
+ const last = this[offset + 7];
20442
+ if (first === undefined || last === undefined) {
20443
+ boundsError(offset, this.length - 8);
20444
+ }
20445
+
20446
+ const val = (first << 24) + // Overflow
20447
+ this[++offset] * 2 ** 16 +
20448
+ this[++offset] * 2 ** 8 +
20449
+ this[++offset];
20450
+
20451
+ return (BigInt(val) << BigInt(32)) +
20452
+ BigInt(this[++offset] * 2 ** 24 +
20453
+ this[++offset] * 2 ** 16 +
20454
+ this[++offset] * 2 ** 8 +
20455
+ last)
20456
+ });
20457
+
20458
+ Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
20459
+ offset = offset >>> 0;
20460
+ if (!noAssert) checkOffset(offset, 4, this.length);
20461
+ return ieee754$1.read(this, offset, true, 23, 4)
20462
+ };
20463
+
20464
+ Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
20465
+ offset = offset >>> 0;
20466
+ if (!noAssert) checkOffset(offset, 4, this.length);
20467
+ return ieee754$1.read(this, offset, false, 23, 4)
20468
+ };
20469
+
20470
+ Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
20471
+ offset = offset >>> 0;
20472
+ if (!noAssert) checkOffset(offset, 8, this.length);
20473
+ return ieee754$1.read(this, offset, true, 52, 8)
20474
+ };
20475
+
20476
+ Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
20477
+ offset = offset >>> 0;
20478
+ if (!noAssert) checkOffset(offset, 8, this.length);
20479
+ return ieee754$1.read(this, offset, false, 52, 8)
20480
+ };
20481
+
20482
+ function checkInt (buf, value, offset, ext, max, min) {
20483
+ if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
20484
+ if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
20485
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
20486
+ }
20487
+
20488
+ Buffer.prototype.writeUintLE =
20489
+ Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
20490
+ value = +value;
20491
+ offset = offset >>> 0;
20492
+ byteLength = byteLength >>> 0;
20493
+ if (!noAssert) {
20494
+ const maxBytes = Math.pow(2, 8 * byteLength) - 1;
20495
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
20496
+ }
20497
+
20498
+ let mul = 1;
20499
+ let i = 0;
20500
+ this[offset] = value & 0xFF;
20501
+ while (++i < byteLength && (mul *= 0x100)) {
20502
+ this[offset + i] = (value / mul) & 0xFF;
20503
+ }
20504
+
20505
+ return offset + byteLength
20506
+ };
20507
+
20508
+ Buffer.prototype.writeUintBE =
20509
+ Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
20510
+ value = +value;
20511
+ offset = offset >>> 0;
20512
+ byteLength = byteLength >>> 0;
20513
+ if (!noAssert) {
20514
+ const maxBytes = Math.pow(2, 8 * byteLength) - 1;
20515
+ checkInt(this, value, offset, byteLength, maxBytes, 0);
20516
+ }
20517
+
20518
+ let i = byteLength - 1;
20519
+ let mul = 1;
20520
+ this[offset + i] = value & 0xFF;
20521
+ while (--i >= 0 && (mul *= 0x100)) {
20522
+ this[offset + i] = (value / mul) & 0xFF;
20523
+ }
20524
+
20525
+ return offset + byteLength
20526
+ };
20527
+
20528
+ Buffer.prototype.writeUint8 =
20529
+ Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
20530
+ value = +value;
20531
+ offset = offset >>> 0;
20532
+ if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
20533
+ this[offset] = (value & 0xff);
20534
+ return offset + 1
20535
+ };
20536
+
20537
+ Buffer.prototype.writeUint16LE =
20538
+ Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
20539
+ value = +value;
20540
+ offset = offset >>> 0;
20541
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
20542
+ this[offset] = (value & 0xff);
20543
+ this[offset + 1] = (value >>> 8);
20544
+ return offset + 2
20545
+ };
20546
+
20547
+ Buffer.prototype.writeUint16BE =
20548
+ Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
20549
+ value = +value;
20550
+ offset = offset >>> 0;
20551
+ if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
20552
+ this[offset] = (value >>> 8);
20553
+ this[offset + 1] = (value & 0xff);
20554
+ return offset + 2
20555
+ };
20556
+
20557
+ Buffer.prototype.writeUint32LE =
20558
+ Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
20559
+ value = +value;
20560
+ offset = offset >>> 0;
20561
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
20562
+ this[offset + 3] = (value >>> 24);
20563
+ this[offset + 2] = (value >>> 16);
20564
+ this[offset + 1] = (value >>> 8);
20565
+ this[offset] = (value & 0xff);
20566
+ return offset + 4
20567
+ };
20568
+
20569
+ Buffer.prototype.writeUint32BE =
20570
+ Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
20571
+ value = +value;
20572
+ offset = offset >>> 0;
20573
+ if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
20574
+ this[offset] = (value >>> 24);
20575
+ this[offset + 1] = (value >>> 16);
20576
+ this[offset + 2] = (value >>> 8);
20577
+ this[offset + 3] = (value & 0xff);
20578
+ return offset + 4
20579
+ };
20580
+
20581
+ function wrtBigUInt64LE (buf, value, offset, min, max) {
20582
+ checkIntBI(value, min, max, buf, offset, 7);
20583
+
20584
+ let lo = Number(value & BigInt(0xffffffff));
20585
+ buf[offset++] = lo;
20586
+ lo = lo >> 8;
20587
+ buf[offset++] = lo;
20588
+ lo = lo >> 8;
20589
+ buf[offset++] = lo;
20590
+ lo = lo >> 8;
20591
+ buf[offset++] = lo;
20592
+ let hi = Number(value >> BigInt(32) & BigInt(0xffffffff));
20593
+ buf[offset++] = hi;
20594
+ hi = hi >> 8;
20595
+ buf[offset++] = hi;
20596
+ hi = hi >> 8;
20597
+ buf[offset++] = hi;
20598
+ hi = hi >> 8;
20599
+ buf[offset++] = hi;
20600
+ return offset
20601
+ }
20602
+
20603
+ function wrtBigUInt64BE (buf, value, offset, min, max) {
20604
+ checkIntBI(value, min, max, buf, offset, 7);
20605
+
20606
+ let lo = Number(value & BigInt(0xffffffff));
20607
+ buf[offset + 7] = lo;
20608
+ lo = lo >> 8;
20609
+ buf[offset + 6] = lo;
20610
+ lo = lo >> 8;
20611
+ buf[offset + 5] = lo;
20612
+ lo = lo >> 8;
20613
+ buf[offset + 4] = lo;
20614
+ let hi = Number(value >> BigInt(32) & BigInt(0xffffffff));
20615
+ buf[offset + 3] = hi;
20616
+ hi = hi >> 8;
20617
+ buf[offset + 2] = hi;
20618
+ hi = hi >> 8;
20619
+ buf[offset + 1] = hi;
20620
+ hi = hi >> 8;
20621
+ buf[offset] = hi;
20622
+ return offset + 8
20623
+ }
20624
+
20625
+ Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {
20626
+ return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))
20627
+ });
20628
+
20629
+ Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {
20630
+ return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))
20631
+ });
20632
+
20633
+ Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
20634
+ value = +value;
20635
+ offset = offset >>> 0;
20636
+ if (!noAssert) {
20637
+ const limit = Math.pow(2, (8 * byteLength) - 1);
20638
+
20639
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
20640
+ }
20641
+
20642
+ let i = 0;
20643
+ let mul = 1;
20644
+ let sub = 0;
20645
+ this[offset] = value & 0xFF;
20646
+ while (++i < byteLength && (mul *= 0x100)) {
20647
+ if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
20648
+ sub = 1;
20649
+ }
20650
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
20651
+ }
20652
+
20653
+ return offset + byteLength
20654
+ };
20655
+
20656
+ Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
20657
+ value = +value;
20658
+ offset = offset >>> 0;
20659
+ if (!noAssert) {
20660
+ const limit = Math.pow(2, (8 * byteLength) - 1);
20661
+
20662
+ checkInt(this, value, offset, byteLength, limit - 1, -limit);
20663
+ }
20664
+
20665
+ let i = byteLength - 1;
20666
+ let mul = 1;
20667
+ let sub = 0;
20668
+ this[offset + i] = value & 0xFF;
20669
+ while (--i >= 0 && (mul *= 0x100)) {
20670
+ if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
20671
+ sub = 1;
20672
+ }
20673
+ this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
20674
+ }
20675
+
20676
+ return offset + byteLength
20677
+ };
20678
+
20679
+ Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
20680
+ value = +value;
20681
+ offset = offset >>> 0;
20682
+ if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80);
20683
+ if (value < 0) value = 0xff + value + 1;
20684
+ this[offset] = (value & 0xff);
20685
+ return offset + 1
20686
+ };
20687
+
20688
+ Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
20689
+ value = +value;
20690
+ offset = offset >>> 0;
20691
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
20692
+ this[offset] = (value & 0xff);
20693
+ this[offset + 1] = (value >>> 8);
20694
+ return offset + 2
20695
+ };
20696
+
20697
+ Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
20698
+ value = +value;
20699
+ offset = offset >>> 0;
20700
+ if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000);
20701
+ this[offset] = (value >>> 8);
20702
+ this[offset + 1] = (value & 0xff);
20703
+ return offset + 2
20704
+ };
20705
+
20706
+ Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
20707
+ value = +value;
20708
+ offset = offset >>> 0;
20709
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
20710
+ this[offset] = (value & 0xff);
20711
+ this[offset + 1] = (value >>> 8);
20712
+ this[offset + 2] = (value >>> 16);
20713
+ this[offset + 3] = (value >>> 24);
20714
+ return offset + 4
20715
+ };
20716
+
20717
+ Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
20718
+ value = +value;
20719
+ offset = offset >>> 0;
20720
+ if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
20721
+ if (value < 0) value = 0xffffffff + value + 1;
20722
+ this[offset] = (value >>> 24);
20723
+ this[offset + 1] = (value >>> 16);
20724
+ this[offset + 2] = (value >>> 8);
20725
+ this[offset + 3] = (value & 0xff);
20726
+ return offset + 4
20727
+ };
20728
+
20729
+ Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {
20730
+ return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
20731
+ });
20732
+
20733
+ Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {
20734
+ return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))
20735
+ });
20736
+
20737
+ function checkIEEE754 (buf, value, offset, ext, max, min) {
20738
+ if (offset + ext > buf.length) throw new RangeError('Index out of range')
20739
+ if (offset < 0) throw new RangeError('Index out of range')
20740
+ }
20741
+
20742
+ function writeFloat (buf, value, offset, littleEndian, noAssert) {
20743
+ value = +value;
20744
+ offset = offset >>> 0;
20745
+ if (!noAssert) {
20746
+ checkIEEE754(buf, value, offset, 4);
20747
+ }
20748
+ ieee754$1.write(buf, value, offset, littleEndian, 23, 4);
20749
+ return offset + 4
20750
+ }
20751
+
20752
+ Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
20753
+ return writeFloat(this, value, offset, true, noAssert)
20754
+ };
20755
+
20756
+ Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
20757
+ return writeFloat(this, value, offset, false, noAssert)
20758
+ };
20759
+
20760
+ function writeDouble (buf, value, offset, littleEndian, noAssert) {
20761
+ value = +value;
20762
+ offset = offset >>> 0;
20763
+ if (!noAssert) {
20764
+ checkIEEE754(buf, value, offset, 8);
20765
+ }
20766
+ ieee754$1.write(buf, value, offset, littleEndian, 52, 8);
20767
+ return offset + 8
20768
+ }
20769
+
20770
+ Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
20771
+ return writeDouble(this, value, offset, true, noAssert)
20772
+ };
20773
+
20774
+ Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
20775
+ return writeDouble(this, value, offset, false, noAssert)
20776
+ };
20777
+
20778
+ // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
20779
+ Buffer.prototype.copy = function copy (target, targetStart, start, end) {
20780
+ if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
20781
+ if (!start) start = 0;
20782
+ if (!end && end !== 0) end = this.length;
20783
+ if (targetStart >= target.length) targetStart = target.length;
20784
+ if (!targetStart) targetStart = 0;
20785
+ if (end > 0 && end < start) end = start;
20786
+
20787
+ // Copy 0 bytes; we're done
20788
+ if (end === start) return 0
20789
+ if (target.length === 0 || this.length === 0) return 0
20790
+
20791
+ // Fatal error conditions
20792
+ if (targetStart < 0) {
20793
+ throw new RangeError('targetStart out of bounds')
20794
+ }
20795
+ if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
20796
+ if (end < 0) throw new RangeError('sourceEnd out of bounds')
20797
+
20798
+ // Are we oob?
20799
+ if (end > this.length) end = this.length;
20800
+ if (target.length - targetStart < end - start) {
20801
+ end = target.length - targetStart + start;
20802
+ }
20803
+
20804
+ const len = end - start;
20805
+
20806
+ if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
20807
+ // Use built-in when available, missing from IE11
20808
+ this.copyWithin(targetStart, start, end);
20809
+ } else {
20810
+ Uint8Array.prototype.set.call(
20811
+ target,
20812
+ this.subarray(start, end),
20813
+ targetStart
20814
+ );
20815
+ }
20816
+
20817
+ return len
20818
+ };
20819
+
20820
+ // Usage:
20821
+ // buffer.fill(number[, offset[, end]])
20822
+ // buffer.fill(buffer[, offset[, end]])
20823
+ // buffer.fill(string[, offset[, end]][, encoding])
20824
+ Buffer.prototype.fill = function fill (val, start, end, encoding) {
20825
+ // Handle string cases:
20826
+ if (typeof val === 'string') {
20827
+ if (typeof start === 'string') {
20828
+ encoding = start;
20829
+ start = 0;
20830
+ end = this.length;
20831
+ } else if (typeof end === 'string') {
20832
+ encoding = end;
20833
+ end = this.length;
20834
+ }
20835
+ if (encoding !== undefined && typeof encoding !== 'string') {
20836
+ throw new TypeError('encoding must be a string')
20837
+ }
20838
+ if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
20839
+ throw new TypeError('Unknown encoding: ' + encoding)
20840
+ }
20841
+ if (val.length === 1) {
20842
+ const code = val.charCodeAt(0);
20843
+ if ((encoding === 'utf8' && code < 128) ||
20844
+ encoding === 'latin1') {
20845
+ // Fast path: If `val` fits into a single byte, use that numeric value.
20846
+ val = code;
20847
+ }
20848
+ }
20849
+ } else if (typeof val === 'number') {
20850
+ val = val & 255;
20851
+ } else if (typeof val === 'boolean') {
20852
+ val = Number(val);
20853
+ }
20854
+
20855
+ // Invalid ranges are not set to a default, so can range check early.
20856
+ if (start < 0 || this.length < start || this.length < end) {
20857
+ throw new RangeError('Out of range index')
20858
+ }
20859
+
20860
+ if (end <= start) {
20861
+ return this
20862
+ }
20863
+
20864
+ start = start >>> 0;
20865
+ end = end === undefined ? this.length : end >>> 0;
20866
+
20867
+ if (!val) val = 0;
20868
+
20869
+ let i;
20870
+ if (typeof val === 'number') {
20871
+ for (i = start; i < end; ++i) {
20872
+ this[i] = val;
20873
+ }
20874
+ } else {
20875
+ const bytes = Buffer.isBuffer(val)
20876
+ ? val
20877
+ : Buffer.from(val, encoding);
20878
+ const len = bytes.length;
20879
+ if (len === 0) {
20880
+ throw new TypeError('The value "' + val +
20881
+ '" is invalid for argument "value"')
20882
+ }
20883
+ for (i = 0; i < end - start; ++i) {
20884
+ this[i + start] = bytes[i % len];
20885
+ }
20886
+ }
20887
+
20888
+ return this
20889
+ };
20890
+
20891
+ // CUSTOM ERRORS
20892
+ // =============
20893
+
20894
+ // Simplified versions from Node, changed for Buffer-only usage
20895
+ const errors = {};
20896
+ function E (sym, getMessage, Base) {
20897
+ errors[sym] = class NodeError extends Base {
20898
+ constructor () {
20899
+ super();
20900
+
20901
+ Object.defineProperty(this, 'message', {
20902
+ value: getMessage.apply(this, arguments),
20903
+ writable: true,
20904
+ configurable: true
20905
+ });
20906
+
20907
+ // Add the error code to the name to include it in the stack trace.
20908
+ this.name = `${this.name} [${sym}]`;
20909
+ // Access the stack to generate the error message including the error code
20910
+ // from the name.
20911
+ this.stack; // eslint-disable-line no-unused-expressions
20912
+ // Reset the name to the actual name.
20913
+ delete this.name;
20914
+ }
20915
+
20916
+ get code () {
20917
+ return sym
20918
+ }
20919
+
20920
+ set code (value) {
20921
+ Object.defineProperty(this, 'code', {
20922
+ configurable: true,
20923
+ enumerable: true,
20924
+ value,
20925
+ writable: true
20926
+ });
20927
+ }
20928
+
20929
+ toString () {
20930
+ return `${this.name} [${sym}]: ${this.message}`
20931
+ }
20932
+ };
20933
+ }
20934
+
20935
+ E('ERR_BUFFER_OUT_OF_BOUNDS',
20936
+ function (name) {
20937
+ if (name) {
20938
+ return `${name} is outside of buffer bounds`
20939
+ }
20940
+
20941
+ return 'Attempt to access memory outside buffer bounds'
20942
+ }, RangeError);
20943
+ E('ERR_INVALID_ARG_TYPE',
20944
+ function (name, actual) {
20945
+ return `The "${name}" argument must be of type number. Received type ${typeof actual}`
20946
+ }, TypeError);
20947
+ E('ERR_OUT_OF_RANGE',
20948
+ function (str, range, input) {
20949
+ let msg = `The value of "${str}" is out of range.`;
20950
+ let received = input;
20951
+ if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
20952
+ received = addNumericalSeparator(String(input));
20953
+ } else if (typeof input === 'bigint') {
20954
+ received = String(input);
20955
+ if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
20956
+ received = addNumericalSeparator(received);
20957
+ }
20958
+ received += 'n';
20959
+ }
20960
+ msg += ` It must be ${range}. Received ${received}`;
20961
+ return msg
20962
+ }, RangeError);
20963
+
20964
+ function addNumericalSeparator (val) {
20965
+ let res = '';
20966
+ let i = val.length;
20967
+ const start = val[0] === '-' ? 1 : 0;
20968
+ for (; i >= start + 4; i -= 3) {
20969
+ res = `_${val.slice(i - 3, i)}${res}`;
20970
+ }
20971
+ return `${val.slice(0, i)}${res}`
20972
+ }
20973
+
20974
+ // CHECK FUNCTIONS
20975
+ // ===============
20976
+
20977
+ function checkBounds (buf, offset, byteLength) {
20978
+ validateNumber(offset, 'offset');
20979
+ if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {
20980
+ boundsError(offset, buf.length - (byteLength + 1));
20981
+ }
20982
+ }
20983
+
20984
+ function checkIntBI (value, min, max, buf, offset, byteLength) {
20985
+ if (value > max || value < min) {
20986
+ const n = typeof min === 'bigint' ? 'n' : '';
20987
+ let range;
20988
+ if (byteLength > 3) {
20989
+ if (min === 0 || min === BigInt(0)) {
20990
+ range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`;
20991
+ } else {
20992
+ range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +
20993
+ `${(byteLength + 1) * 8 - 1}${n}`;
20994
+ }
20995
+ } else {
20996
+ range = `>= ${min}${n} and <= ${max}${n}`;
20997
+ }
20998
+ throw new errors.ERR_OUT_OF_RANGE('value', range, value)
20999
+ }
21000
+ checkBounds(buf, offset, byteLength);
21001
+ }
21002
+
21003
+ function validateNumber (value, name) {
21004
+ if (typeof value !== 'number') {
21005
+ throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)
21006
+ }
21007
+ }
21008
+
21009
+ function boundsError (value, length, type) {
21010
+ if (Math.floor(value) !== value) {
21011
+ validateNumber(value, type);
21012
+ throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)
21013
+ }
21014
+
21015
+ if (length < 0) {
21016
+ throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()
21017
+ }
21018
+
21019
+ throw new errors.ERR_OUT_OF_RANGE(type || 'offset',
21020
+ `>= ${type ? 1 : 0} and <= ${length}`,
21021
+ value)
21022
+ }
21023
+
21024
+ // HELPER FUNCTIONS
21025
+ // ================
21026
+
21027
+ const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
21028
+
21029
+ function base64clean (str) {
21030
+ // Node takes equal signs as end of the Base64 encoding
21031
+ str = str.split('=')[0];
21032
+ // Node strips out invalid characters like \n and \t from the string, base64-js does not
21033
+ str = str.trim().replace(INVALID_BASE64_RE, '');
21034
+ // Node converts strings with length < 2 to ''
21035
+ if (str.length < 2) return ''
21036
+ // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
21037
+ while (str.length % 4 !== 0) {
21038
+ str = str + '=';
21039
+ }
21040
+ return str
21041
+ }
21042
+
21043
+ function utf8ToBytes (string, units) {
21044
+ units = units || Infinity;
21045
+ let codePoint;
21046
+ const length = string.length;
21047
+ let leadSurrogate = null;
21048
+ const bytes = [];
21049
+
21050
+ for (let i = 0; i < length; ++i) {
21051
+ codePoint = string.charCodeAt(i);
21052
+
21053
+ // is surrogate component
21054
+ if (codePoint > 0xD7FF && codePoint < 0xE000) {
21055
+ // last char was a lead
21056
+ if (!leadSurrogate) {
21057
+ // no lead yet
21058
+ if (codePoint > 0xDBFF) {
21059
+ // unexpected trail
21060
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
21061
+ continue
21062
+ } else if (i + 1 === length) {
21063
+ // unpaired lead
21064
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
21065
+ continue
21066
+ }
21067
+
21068
+ // valid lead
21069
+ leadSurrogate = codePoint;
21070
+
21071
+ continue
21072
+ }
21073
+
21074
+ // 2 leads in a row
21075
+ if (codePoint < 0xDC00) {
21076
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
21077
+ leadSurrogate = codePoint;
21078
+ continue
21079
+ }
21080
+
21081
+ // valid surrogate pair
21082
+ codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
21083
+ } else if (leadSurrogate) {
21084
+ // valid bmp char, but last char was a lead
21085
+ if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
21086
+ }
21087
+
21088
+ leadSurrogate = null;
21089
+
21090
+ // encode utf8
21091
+ if (codePoint < 0x80) {
21092
+ if ((units -= 1) < 0) break
21093
+ bytes.push(codePoint);
21094
+ } else if (codePoint < 0x800) {
21095
+ if ((units -= 2) < 0) break
21096
+ bytes.push(
21097
+ codePoint >> 0x6 | 0xC0,
21098
+ codePoint & 0x3F | 0x80
21099
+ );
21100
+ } else if (codePoint < 0x10000) {
21101
+ if ((units -= 3) < 0) break
21102
+ bytes.push(
21103
+ codePoint >> 0xC | 0xE0,
21104
+ codePoint >> 0x6 & 0x3F | 0x80,
21105
+ codePoint & 0x3F | 0x80
21106
+ );
21107
+ } else if (codePoint < 0x110000) {
21108
+ if ((units -= 4) < 0) break
21109
+ bytes.push(
21110
+ codePoint >> 0x12 | 0xF0,
21111
+ codePoint >> 0xC & 0x3F | 0x80,
21112
+ codePoint >> 0x6 & 0x3F | 0x80,
21113
+ codePoint & 0x3F | 0x80
21114
+ );
21115
+ } else {
21116
+ throw new Error('Invalid code point')
21117
+ }
21118
+ }
21119
+
21120
+ return bytes
21121
+ }
21122
+
21123
+ function asciiToBytes (str) {
21124
+ const byteArray = [];
21125
+ for (let i = 0; i < str.length; ++i) {
21126
+ // Node's code seems to be doing this and not & 0x7F..
21127
+ byteArray.push(str.charCodeAt(i) & 0xFF);
21128
+ }
21129
+ return byteArray
21130
+ }
21131
+
21132
+ function utf16leToBytes (str, units) {
21133
+ let c, hi, lo;
21134
+ const byteArray = [];
21135
+ for (let i = 0; i < str.length; ++i) {
21136
+ if ((units -= 2) < 0) break
21137
+
21138
+ c = str.charCodeAt(i);
21139
+ hi = c >> 8;
21140
+ lo = c % 256;
21141
+ byteArray.push(lo);
21142
+ byteArray.push(hi);
21143
+ }
21144
+
21145
+ return byteArray
21146
+ }
21147
+
21148
+ function base64ToBytes (str) {
21149
+ return base64.toByteArray(base64clean(str))
21150
+ }
21151
+
21152
+ function blitBuffer (src, dst, offset, length) {
21153
+ let i;
21154
+ for (i = 0; i < length; ++i) {
21155
+ if ((i + offset >= dst.length) || (i >= src.length)) break
21156
+ dst[i + offset] = src[i];
21157
+ }
21158
+ return i
21159
+ }
21160
+
21161
+ // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
21162
+ // the `instanceof` check but they should be treated as of that type.
21163
+ // See: https://github.com/feross/buffer/issues/166
21164
+ function isInstance (obj, type) {
21165
+ return obj instanceof type ||
21166
+ (obj != null && obj.constructor != null && obj.constructor.name != null &&
21167
+ obj.constructor.name === type.name)
21168
+ }
21169
+ function numberIsNaN (obj) {
21170
+ // For IE11 support
21171
+ return obj !== obj // eslint-disable-line no-self-compare
21172
+ }
21173
+
21174
+ // Create lookup table for `toString('hex')`
21175
+ // See: https://github.com/feross/buffer/issues/219
21176
+ const hexSliceLookupTable = (function () {
21177
+ const alphabet = '0123456789abcdef';
21178
+ const table = new Array(256);
21179
+ for (let i = 0; i < 16; ++i) {
21180
+ const i16 = i * 16;
21181
+ for (let j = 0; j < 16; ++j) {
21182
+ table[i16 + j] = alphabet[i] + alphabet[j];
21183
+ }
21184
+ }
21185
+ return table
21186
+ })();
21187
+
21188
+ // Return not function with Error if BigInt not supported
21189
+ function defineBigIntMethod (fn) {
21190
+ return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn
21191
+ }
21192
+
21193
+ function BufferBigIntNotDefined () {
21194
+ throw new Error('BigInt not supported')
21195
+ }
21196
+ } (buffer));
21197
+
21198
+ // Refresh at least 30 sec before it expires
21199
+ const REFRESH_CREDENTIALS_SAFETY_PERIOD_MS = 30_000;
21200
+ const SYNC_QUEUE_REQUEST_N = 10;
21201
+ const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
21202
+ // Keep alive message is sent every period
21203
+ const KEEP_ALIVE_MS = 20_000;
21204
+ // The ACK must be received in this period
21205
+ const KEEP_ALIVE_LIFETIME_MS = 30_000;
21206
+ const DEFAULT_REMOTE_LOGGER = Logger.get('PowerSyncRemote');
21207
+ /**
21208
+ * Class wrapper for providing a fetch implementation.
21209
+ * The class wrapper is used to distinguish the fetchImplementation
21210
+ * option in [AbstractRemoteOptions] from the general fetch method
21211
+ * which is typeof "function"
21212
+ */
21213
+ class FetchImplementationProvider {
21214
+ getFetch() {
21215
+ return nodePonyfillExports.fetch.bind(globalThis);
21216
+ }
21217
+ }
21218
+ const DEFAULT_REMOTE_OPTIONS = {
21219
+ socketUrlTransformer: (url) => url.replace(/^https?:\/\//, function (match) {
21220
+ return match === 'https://' ? 'wss://' : 'ws://';
21221
+ }),
21222
+ fetchImplementation: new FetchImplementationProvider()
21223
+ };
21224
+ class AbstractRemote {
21225
+ connector;
21226
+ logger;
21227
+ credentials = null;
21228
+ options;
21229
+ constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {
21230
+ this.connector = connector;
21231
+ this.logger = logger;
21232
+ this.options = {
21233
+ ...DEFAULT_REMOTE_OPTIONS,
21234
+ ...(options ?? {})
21235
+ };
21236
+ }
21237
+ /**
21238
+ * @returns a fetch implementation (function)
21239
+ * which can be called to perform fetch requests
21240
+ */
21241
+ get fetch() {
21242
+ const { fetchImplementation } = this.options;
21243
+ return fetchImplementation instanceof FetchImplementationProvider
21244
+ ? fetchImplementation.getFetch()
21245
+ : fetchImplementation;
21246
+ }
21247
+ async getCredentials() {
21248
+ const { expiresAt } = this.credentials ?? {};
21249
+ if (expiresAt && expiresAt > new Date(new Date().valueOf() + REFRESH_CREDENTIALS_SAFETY_PERIOD_MS)) {
21250
+ return this.credentials;
21251
+ }
21252
+ this.credentials = await this.connector.fetchCredentials();
21253
+ return this.credentials;
21254
+ }
21255
+ async buildRequest(path) {
21256
+ const credentials = await this.getCredentials();
21257
+ if (credentials != null && (credentials.endpoint == null || credentials.endpoint == '')) {
21258
+ throw new Error('PowerSync endpoint not configured');
21259
+ }
21260
+ else if (credentials?.token == null || credentials?.token == '') {
21261
+ const error = new Error(`Not signed in`);
21262
+ error.status = 401;
21263
+ throw error;
21264
+ }
21265
+ return {
21266
+ url: credentials.endpoint + path,
21267
+ headers: {
21268
+ 'content-type': 'application/json',
21269
+ Authorization: `Token ${credentials.token}`
21270
+ }
21271
+ };
21272
+ }
21273
+ async post(path, data, headers = {}) {
21274
+ const request = await this.buildRequest(path);
21275
+ const res = await nodePonyfillExports.fetch(request.url, {
21276
+ method: 'POST',
21277
+ headers: {
21278
+ ...headers,
21279
+ ...request.headers
21280
+ },
21281
+ body: JSON.stringify(data)
21282
+ });
21283
+ if (!res.ok) {
21284
+ throw new Error(`Received ${res.status} - ${res.statusText} when posting to ${path}: ${await res.text()}}`);
21285
+ }
21286
+ return res.json();
21287
+ }
21288
+ async get(path, headers) {
21289
+ const request = await this.buildRequest(path);
21290
+ const res = await this.fetch(request.url, {
21291
+ method: 'GET',
21292
+ headers: {
21293
+ ...headers,
21294
+ ...request.headers
21295
+ }
21296
+ });
21297
+ if (!res.ok) {
21298
+ throw new Error(`Received ${res.status} - ${res.statusText} when getting from ${path}: ${await res.text()}}`);
21299
+ }
21300
+ return res.json();
21301
+ }
21302
+ async postStreaming(path, data, headers = {}, signal) {
21303
+ const request = await this.buildRequest(path);
21304
+ const res = await this.fetch(request.url, {
21305
+ method: 'POST',
21306
+ headers: { ...headers, ...request.headers },
21307
+ body: JSON.stringify(data),
21308
+ signal,
21309
+ cache: 'no-store'
21310
+ }).catch((ex) => {
21311
+ this.logger.error(`Caught ex when POST streaming to ${path}`, ex);
21312
+ throw ex;
21313
+ });
21314
+ if (!res.ok) {
21315
+ const text = await res.text();
21316
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
21317
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
21318
+ error.status = res.status;
21319
+ throw error;
21320
+ }
21321
+ return res;
21322
+ }
21323
+ /**
21324
+ * Connects to the sync/stream websocket endpoint
21325
+ */
21326
+ async socketStream(options) {
21327
+ const { path } = options;
21328
+ const request = await this.buildRequest(path);
21329
+ const bson = await this.getBSON();
21330
+ const connector = new distExports.RSocketConnector({
21331
+ transport: new dist.WebsocketClientTransport({
21332
+ url: this.options.socketUrlTransformer(request.url)
21333
+ }),
21334
+ setup: {
21335
+ keepAlive: KEEP_ALIVE_MS,
21336
+ lifetime: KEEP_ALIVE_LIFETIME_MS,
21337
+ dataMimeType: 'application/bson',
21338
+ metadataMimeType: 'application/bson',
21339
+ payload: {
21340
+ data: null,
21341
+ metadata: buffer.Buffer.from(bson.serialize({
21342
+ token: request.headers.Authorization
21343
+ }))
21344
+ }
21345
+ }
21346
+ });
21347
+ let rsocket;
21348
+ try {
21349
+ rsocket = await connector.connect();
21350
+ }
21351
+ catch (ex) {
21352
+ /**
21353
+ * On React native the connection exception can be `undefined` this causes issues
21354
+ * with detecting the exception inside async-mutex
21355
+ */
21356
+ throw new Error(`Could not connect to PowerSync instance: ${JSON.stringify(ex)}`);
21357
+ }
21358
+ const stream = new DataStream({
21359
+ logger: this.logger,
21360
+ pressure: {
21361
+ lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER
21362
+ }
21363
+ });
21364
+ let socketIsClosed = false;
21365
+ const closeSocket = () => {
21366
+ if (socketIsClosed) {
21367
+ return;
21368
+ }
21369
+ socketIsClosed = true;
21370
+ rsocket.close();
21371
+ };
21372
+ // We initially request this amount and expect these to arrive eventually
21373
+ let pendingEventsCount = SYNC_QUEUE_REQUEST_N;
21374
+ const socket = await new Promise((resolve, reject) => {
21375
+ let connectionEstablished = false;
21376
+ const res = rsocket.requestStream({
21377
+ data: buffer.Buffer.from(bson.serialize(options.data)),
21378
+ metadata: buffer.Buffer.from(bson.serialize({
21379
+ path
21380
+ }))
21381
+ }, SYNC_QUEUE_REQUEST_N, // The initial N amount
21382
+ {
21383
+ onError: (e) => {
21384
+ // Don't log closed as an error
21385
+ if (e.message !== 'Closed. ') {
21386
+ this.logger.error(e);
21387
+ }
21388
+ // RSocket will close this automatically
21389
+ // Attempting to close multiple times causes a console warning
21390
+ socketIsClosed = true;
21391
+ stream.close();
21392
+ // Handles cases where the connection failed e.g. auth error or connection error
21393
+ if (!connectionEstablished) {
21394
+ reject(e);
21395
+ }
21396
+ },
21397
+ onNext: (payload) => {
21398
+ // The connection is active
21399
+ if (!connectionEstablished) {
21400
+ connectionEstablished = true;
21401
+ resolve(res);
21402
+ }
21403
+ const { data } = payload;
21404
+ // Less events are now pending
21405
+ pendingEventsCount--;
21406
+ if (!data) {
21407
+ return;
21408
+ }
21409
+ const deserializedData = bson.deserialize(data);
21410
+ stream.enqueueData(deserializedData);
21411
+ },
21412
+ onComplete: () => {
21413
+ stream.close();
21414
+ },
21415
+ onExtension: () => { }
21416
+ });
21417
+ });
21418
+ const l = stream.registerListener({
21419
+ lowWater: async () => {
21420
+ // Request to fill up the queue
21421
+ const required = SYNC_QUEUE_REQUEST_N - pendingEventsCount;
21422
+ if (required > 0) {
21423
+ socket.request(SYNC_QUEUE_REQUEST_N - pendingEventsCount);
21424
+ pendingEventsCount = SYNC_QUEUE_REQUEST_N;
21425
+ }
21426
+ },
21427
+ closed: () => {
21428
+ closeSocket();
21429
+ l?.();
21430
+ }
21431
+ });
21432
+ /**
21433
+ * Handle abort operations here.
21434
+ * Unfortunately cannot insert them into the connection.
21435
+ */
21436
+ if (options.abortSignal?.aborted) {
21437
+ stream.close();
21438
+ }
21439
+ else {
21440
+ options.abortSignal?.addEventListener('abort', () => {
21441
+ stream.close();
21442
+ });
21443
+ }
21444
+ return stream;
21445
+ }
21446
+ /**
21447
+ * Connects to the sync/stream http endpoint
21448
+ */
21449
+ async postStream(options) {
21450
+ const { data, path, headers, abortSignal } = options;
21451
+ const request = await this.buildRequest(path);
21452
+ /**
21453
+ * This abort controller will abort pending fetch requests.
21454
+ * If the request has resolved, it will be used to close the readable stream.
21455
+ * Which will cancel the network request.
19293
21456
  *
19294
21457
  * This nested controller is required since:
19295
21458
  * Aborting the active fetch request while it is being consumed seems to throw
@@ -19304,399 +21467,1272 @@ class AbstractRemote {
19304
21467
  new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.'));
19305
21468
  }
19306
21469
  });
19307
- const res = await this.fetch(request.url, {
19308
- method: 'POST',
19309
- headers: { ...headers, ...request.headers },
19310
- body: JSON.stringify(data),
19311
- signal: controller.signal,
19312
- cache: 'no-store',
19313
- ...options.fetchOptions
19314
- }).catch((ex) => {
19315
- if (ex.name == 'AbortError') {
19316
- throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
21470
+ const res = await this.fetch(request.url, {
21471
+ method: 'POST',
21472
+ headers: { ...headers, ...request.headers },
21473
+ body: JSON.stringify(data),
21474
+ signal: controller.signal,
21475
+ cache: 'no-store',
21476
+ ...options.fetchOptions
21477
+ }).catch((ex) => {
21478
+ if (ex.name == 'AbortError') {
21479
+ throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
21480
+ }
21481
+ throw ex;
21482
+ });
21483
+ if (!res) {
21484
+ throw new Error('Fetch request was aborted');
21485
+ }
21486
+ requestResolved = true;
21487
+ if (!res.ok || !res.body) {
21488
+ const text = await res.text();
21489
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
21490
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
21491
+ error.status = res.status;
21492
+ throw error;
21493
+ }
21494
+ /**
21495
+ * The can-ndjson-stream does not handle aborted streams well.
21496
+ * This will intercept the readable stream and close the stream if
21497
+ * aborted.
21498
+ */
21499
+ const reader = res.body.getReader();
21500
+ // This will close the network request and read stream
21501
+ const closeReader = async () => {
21502
+ try {
21503
+ await reader.cancel();
21504
+ }
21505
+ catch (ex) {
21506
+ // an error will throw if the reader hasn't been used yet
21507
+ }
21508
+ reader.releaseLock();
21509
+ };
21510
+ abortSignal?.addEventListener('abort', () => {
21511
+ closeReader();
21512
+ });
21513
+ const outputStream = new ReadableStream({
21514
+ start: (controller) => {
21515
+ const processStream = async () => {
21516
+ while (!abortSignal?.aborted) {
21517
+ try {
21518
+ const { done, value } = await reader.read();
21519
+ // When no more data needs to be consumed, close the stream
21520
+ if (done) {
21521
+ break;
21522
+ }
21523
+ // Enqueue the next data chunk into our target stream
21524
+ controller.enqueue(value);
21525
+ }
21526
+ catch (ex) {
21527
+ this.logger.error('Caught exception when reading sync stream', ex);
21528
+ break;
21529
+ }
21530
+ }
21531
+ if (!abortSignal?.aborted) {
21532
+ // Close the downstream readable stream
21533
+ await closeReader();
21534
+ }
21535
+ controller.close();
21536
+ };
21537
+ processStream();
21538
+ }
21539
+ });
21540
+ const jsonS = ndjsonStream$1(new Response(outputStream).body);
21541
+ const stream = new DataStream({
21542
+ logger: this.logger
21543
+ });
21544
+ const r = jsonS.getReader();
21545
+ const l = stream.registerListener({
21546
+ lowWater: async () => {
21547
+ try {
21548
+ const { done, value } = await r.read();
21549
+ // Exit if we're done
21550
+ if (done) {
21551
+ stream.close();
21552
+ l?.();
21553
+ return;
21554
+ }
21555
+ stream.enqueueData(value);
21556
+ }
21557
+ catch (ex) {
21558
+ stream.close();
21559
+ throw ex;
21560
+ }
21561
+ },
21562
+ closed: () => {
21563
+ closeReader();
21564
+ l?.();
21565
+ }
21566
+ });
21567
+ return stream;
21568
+ }
21569
+ }
21570
+
21571
+ // https://www.sqlite.org/lang_expr.html#castexpr
21572
+ exports.ColumnType = void 0;
21573
+ (function (ColumnType) {
21574
+ ColumnType["TEXT"] = "TEXT";
21575
+ ColumnType["INTEGER"] = "INTEGER";
21576
+ ColumnType["REAL"] = "REAL";
21577
+ })(exports.ColumnType || (exports.ColumnType = {}));
21578
+ class Column {
21579
+ options;
21580
+ constructor(options) {
21581
+ this.options = options;
21582
+ }
21583
+ get name() {
21584
+ return this.options.name;
21585
+ }
21586
+ get type() {
21587
+ return this.options.type;
21588
+ }
21589
+ toJSON() {
21590
+ return {
21591
+ name: this.name,
21592
+ type: this.type
21593
+ };
21594
+ }
21595
+ }
21596
+
21597
+ const DEFAULT_TABLE_OPTIONS = {
21598
+ indexes: [],
21599
+ insertOnly: false,
21600
+ localOnly: false
21601
+ };
21602
+ const InvalidSQLCharacters = /["'%,.#\s[\]]/;
21603
+ class Table {
21604
+ options;
21605
+ static createLocalOnly(options) {
21606
+ return new Table({ ...options, localOnly: true, insertOnly: false });
21607
+ }
21608
+ static createInsertOnly(options) {
21609
+ return new Table({ ...options, localOnly: false, insertOnly: true });
21610
+ }
21611
+ static createTable(name, table) {
21612
+ return new Table({
21613
+ name,
21614
+ columns: Object.entries(table.columns).map(([name, col]) => new Column({ name, type: col.type })),
21615
+ indexes: table.indexes,
21616
+ localOnly: table.options.localOnly,
21617
+ insertOnly: table.options.insertOnly,
21618
+ viewName: table.options.viewName
21619
+ });
21620
+ }
21621
+ constructor(options) {
21622
+ this.options = { ...DEFAULT_TABLE_OPTIONS, ...options };
21623
+ }
21624
+ get name() {
21625
+ return this.options.name;
21626
+ }
21627
+ get viewNameOverride() {
21628
+ return this.options.viewName;
21629
+ }
21630
+ get viewName() {
21631
+ return this.viewNameOverride ?? this.name;
21632
+ }
21633
+ get columns() {
21634
+ return this.options.columns;
21635
+ }
21636
+ get indexes() {
21637
+ return this.options.indexes ?? [];
21638
+ }
21639
+ get localOnly() {
21640
+ return this.options.localOnly ?? false;
21641
+ }
21642
+ get insertOnly() {
21643
+ return this.options.insertOnly ?? false;
21644
+ }
21645
+ get internalName() {
21646
+ if (this.options.localOnly) {
21647
+ return `ps_data_local__${this.name}`;
21648
+ }
21649
+ return `ps_data__${this.name}`;
21650
+ }
21651
+ get validName() {
21652
+ if (InvalidSQLCharacters.test(this.name)) {
21653
+ return false;
21654
+ }
21655
+ if (this.viewNameOverride != null && InvalidSQLCharacters.test(this.viewNameOverride)) {
21656
+ return false;
21657
+ }
21658
+ return true;
21659
+ }
21660
+ validate() {
21661
+ if (InvalidSQLCharacters.test(this.name)) {
21662
+ throw new Error(`Invalid characters in table name: ${this.name}`);
21663
+ }
21664
+ if (this.viewNameOverride && InvalidSQLCharacters.test(this.viewNameOverride)) {
21665
+ throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);
21666
+ }
21667
+ const columnNames = new Set();
21668
+ columnNames.add('id');
21669
+ for (const column of this.columns) {
21670
+ const { name: columnName } = column;
21671
+ if (column.name == 'id') {
21672
+ throw new Error(`${this.name}: id column is automatically added, custom id columns are not supported`);
21673
+ }
21674
+ if (columnNames.has(columnName)) {
21675
+ throw new Error(`Duplicate column ${columnName}`);
21676
+ }
21677
+ if (InvalidSQLCharacters.test(columnName)) {
21678
+ throw new Error(`Invalid characters in column name: $name.${column}`);
21679
+ }
21680
+ columnNames.add(columnName);
21681
+ }
21682
+ const indexNames = new Set();
21683
+ for (const index of this.indexes) {
21684
+ if (indexNames.has(index.name)) {
21685
+ throw new Error(`Duplicate index $name.${index}`);
21686
+ }
21687
+ if (InvalidSQLCharacters.test(index.name)) {
21688
+ throw new Error(`Invalid characters in index name: $name.${index}`);
21689
+ }
21690
+ for (const column of index.columns) {
21691
+ if (!columnNames.has(column.name)) {
21692
+ throw new Error(`Column ${column.name} not found for index ${index.name}`);
21693
+ }
21694
+ }
21695
+ indexNames.add(index.name);
21696
+ }
21697
+ }
21698
+ toJSON() {
21699
+ return {
21700
+ name: this.name,
21701
+ view_name: this.viewName,
21702
+ local_only: this.localOnly,
21703
+ insert_only: this.insertOnly,
21704
+ columns: this.columns.map((c) => c.toJSON()),
21705
+ indexes: this.indexes.map((e) => e.toJSON(this))
21706
+ };
21707
+ }
21708
+ }
21709
+
21710
+ /**
21711
+ * A schema is a collection of tables. It is used to define the structure of a database.
21712
+ */
21713
+ class Schema {
21714
+ /*
21715
+ Only available when constructing with mapped typed definition columns
21716
+ */
21717
+ types;
21718
+ props;
21719
+ tables;
21720
+ constructor(tables) {
21721
+ if (Array.isArray(tables)) {
21722
+ this.tables = tables;
21723
+ }
21724
+ else {
21725
+ this.props = tables;
21726
+ this.tables = this.convertToClassicTables(this.props);
21727
+ }
21728
+ }
21729
+ validate() {
21730
+ for (const table of this.tables) {
21731
+ table.validate();
21732
+ }
21733
+ }
21734
+ toJSON() {
21735
+ return {
21736
+ tables: this.tables.map((t) => t.toJSON())
21737
+ };
21738
+ }
21739
+ convertToClassicTables(props) {
21740
+ return Object.entries(props).map(([name, table]) => {
21741
+ return Table.createTable(name, table);
21742
+ });
21743
+ }
21744
+ }
21745
+
21746
+ const DEFAULT_INDEX_COLUMN_OPTIONS = {
21747
+ ascending: true
21748
+ };
21749
+ class IndexedColumn {
21750
+ options;
21751
+ static createAscending(column) {
21752
+ return new IndexedColumn({
21753
+ name: column,
21754
+ ascending: true
21755
+ });
21756
+ }
21757
+ constructor(options) {
21758
+ this.options = { ...DEFAULT_INDEX_COLUMN_OPTIONS, ...options };
21759
+ }
21760
+ get name() {
21761
+ return this.options.name;
21762
+ }
21763
+ get ascending() {
21764
+ return this.options.ascending;
21765
+ }
21766
+ toJSON(table) {
21767
+ return {
21768
+ name: this.name,
21769
+ ascending: this.ascending,
21770
+ type: table.columns.find((column) => column.name === this.name)?.type ?? exports.ColumnType.TEXT
21771
+ };
21772
+ }
21773
+ }
21774
+
21775
+ const DEFAULT_INDEX_OPTIONS = {
21776
+ columns: []
21777
+ };
21778
+ class Index {
21779
+ options;
21780
+ static createAscending(options, columnNames) {
21781
+ return new Index({
21782
+ ...options,
21783
+ columns: columnNames.map((name) => IndexedColumn.createAscending(name))
21784
+ });
21785
+ }
21786
+ constructor(options) {
21787
+ this.options = options;
21788
+ this.options = { ...DEFAULT_INDEX_OPTIONS, ...options };
21789
+ }
21790
+ get name() {
21791
+ return this.options.name;
21792
+ }
21793
+ get columns() {
21794
+ return this.options.columns ?? [];
21795
+ }
21796
+ toJSON(table) {
21797
+ return {
21798
+ name: this.name,
21799
+ columns: this.columns.map((c) => c.toJSON(table))
21800
+ };
21801
+ }
21802
+ }
21803
+
21804
+ const text = {
21805
+ type: exports.ColumnType.TEXT
21806
+ };
21807
+ const integer = {
21808
+ type: exports.ColumnType.INTEGER
21809
+ };
21810
+ const real = {
21811
+ type: exports.ColumnType.REAL
21812
+ };
21813
+ const column = {
21814
+ text,
21815
+ integer,
21816
+ real
21817
+ };
21818
+ /*
21819
+ Generate a new table from the columns and indexes
21820
+ */
21821
+ class TableV2 {
21822
+ columns;
21823
+ options;
21824
+ indexes;
21825
+ constructor(columns, options = {}) {
21826
+ this.columns = columns;
21827
+ this.options = options;
21828
+ if (options?.indexes) {
21829
+ this.indexes = Object.entries(options.indexes).map(([name, columns]) => {
21830
+ if (name.startsWith('-')) {
21831
+ return new Index({
21832
+ name: name.substring(1),
21833
+ columns: columns.map((c) => new IndexedColumn({ name: c, ascending: false }))
21834
+ });
21835
+ }
21836
+ return new Index({
21837
+ name: name,
21838
+ columns: columns.map((c) => new IndexedColumn({ name: c, ascending: true }))
21839
+ });
21840
+ });
21841
+ }
21842
+ }
21843
+ }
21844
+
21845
+ const parseQuery = (query, parameters) => {
21846
+ let sqlStatement;
21847
+ if (typeof query == 'string') {
21848
+ sqlStatement = query;
21849
+ }
21850
+ else {
21851
+ const hasAdditionalParameters = parameters.length > 0;
21852
+ if (hasAdditionalParameters) {
21853
+ throw new Error('You cannot pass parameters to a compiled query.');
21854
+ }
21855
+ const compiled = query.compile();
21856
+ sqlStatement = compiled.sql;
21857
+ parameters = compiled.parameters;
21858
+ }
21859
+ return { sqlStatement, parameters: parameters };
21860
+ };
21861
+
21862
+ function normalizeName(name) {
21863
+ if (typeof name !== "string") {
21864
+ name = String(name);
21865
+ }
21866
+
21867
+ name = name.trim();
21868
+
21869
+ if (name.length === 0) {
21870
+ throw new TypeError("Header field name is empty");
21871
+ }
21872
+
21873
+ if (/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(name)) {
21874
+ throw new TypeError(`Invalid character in header field name: ${name}`);
21875
+ }
21876
+
21877
+ return name.toLowerCase();
21878
+ }
21879
+
21880
+ function normalizeValue(value) {
21881
+ if (typeof value !== "string") {
21882
+ value = String(value);
21883
+ }
21884
+ return value;
21885
+ }
21886
+
21887
+ let Headers$1 = class Headers {
21888
+ map = new Map();
21889
+
21890
+ constructor(init = {}) {
21891
+ if (init instanceof Headers) {
21892
+ init.forEach(function (value, name) {
21893
+ this.append(name, value);
21894
+ }, this);
21895
+
21896
+ return this;
21897
+ }
21898
+
21899
+ if (Array.isArray(init)) {
21900
+ init.forEach(function ([name, value]) {
21901
+ this.append(name, value);
21902
+ }, this);
21903
+
21904
+ return this;
21905
+ }
21906
+
21907
+ Object.getOwnPropertyNames(init).forEach((name) =>
21908
+ this.append(name, init[name])
21909
+ );
21910
+ }
21911
+
21912
+ append(name, value) {
21913
+ name = normalizeName(name);
21914
+ value = normalizeValue(value);
21915
+ const oldValue = this.get(name);
21916
+ // From MDN: If the specified header already exists and accepts multiple values, append() will append the new value to the end of the value set.
21917
+ // However, we're a missing a check on whether the header does indeed accept multiple values
21918
+ this.map.set(name, oldValue ? oldValue + ", " + value : value);
21919
+ }
21920
+
21921
+ delete(name) {
21922
+ this.map.delete(normalizeName(name));
21923
+ }
21924
+
21925
+ get(name) {
21926
+ name = normalizeName(name);
21927
+ return this.has(name) ? this.map.get(name) : null;
21928
+ }
21929
+
21930
+ has(name) {
21931
+ return this.map.has(normalizeName(name));
21932
+ }
21933
+
21934
+ set(name, value) {
21935
+ this.map.set(normalizeName(name), normalizeValue(value));
21936
+ }
21937
+
21938
+ forEach(callback, thisArg) {
21939
+ this.map.forEach(function (value, name) {
21940
+ callback.call(thisArg, value, name, this);
21941
+ }, this);
21942
+ }
21943
+
21944
+ keys() {
21945
+ return this.map.keys();
21946
+ }
21947
+
21948
+ values() {
21949
+ return this.map.values();
21950
+ }
21951
+
21952
+ entries() {
21953
+ return this.map.entries();
21954
+ }
21955
+
21956
+ [Symbol.iterator]() {
21957
+ return this.entries();
21958
+ }
21959
+ };
21960
+
21961
+ function createBlobReader(blob) {
21962
+ const reader = new FileReader();
21963
+ const fileReaderReady = new Promise((resolve, reject) => {
21964
+ reader.onload = function () {
21965
+ resolve(reader.result);
21966
+ };
21967
+ reader.onerror = function () {
21968
+ reject(reader.error);
21969
+ };
21970
+ });
21971
+
21972
+ return {
21973
+ readAsArrayBuffer: async () => {
21974
+ reader.readAsArrayBuffer(blob);
21975
+ return fileReaderReady;
21976
+ },
21977
+ readAsText: async () => {
21978
+ reader.readAsText(blob);
21979
+ return fileReaderReady;
21980
+ },
21981
+ };
21982
+ }
21983
+
21984
+ async function drainStream(stream) {
21985
+ const chunks = [];
21986
+ const reader = stream.getReader();
21987
+
21988
+ function readNextChunk() {
21989
+ return reader.read().then(({ done, value }) => {
21990
+ if (done) {
21991
+ return chunks.reduce(
21992
+ (bytes, chunk) => [...bytes, ...chunk],
21993
+ []
21994
+ );
19317
21995
  }
19318
- throw ex;
21996
+
21997
+ chunks.push(value);
21998
+
21999
+ return readNextChunk();
19319
22000
  });
19320
- if (!res) {
19321
- throw new Error('Fetch request was aborted');
22001
+ }
22002
+
22003
+ const bytes = await readNextChunk();
22004
+
22005
+ return new Uint8Array(bytes);
22006
+ }
22007
+
22008
+ function readArrayBufferAsText(array) {
22009
+ const decoder = new textEncoding.TextDecoder();
22010
+
22011
+ return decoder.decode(array);
22012
+ }
22013
+
22014
+ class Body {
22015
+ constructor(body) {
22016
+ this.bodyUsed = false;
22017
+ this._bodyInit = body;
22018
+
22019
+ if (!body) {
22020
+ this._bodyText = "";
22021
+ return this;
19322
22022
  }
19323
- requestResolved = true;
19324
- if (!res.ok || !res.body) {
19325
- const text = await res.text();
19326
- this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
19327
- const error = new Error(`HTTP ${res.statusText}: ${text}`);
19328
- error.status = res.status;
19329
- throw error;
22023
+
22024
+ if (body instanceof Blob) {
22025
+ this._bodyBlob = body;
22026
+ this._mimeType = body.type;
22027
+ return this;
19330
22028
  }
19331
- /**
19332
- * The can-ndjson-stream does not handle aborted streams well.
19333
- * This will intercept the readable stream and close the stream if
19334
- * aborted.
19335
- */
19336
- const reader = res.body.getReader();
19337
- // This will close the network request and read stream
19338
- const closeReader = async () => {
19339
- try {
19340
- await reader.cancel();
19341
- }
19342
- catch (ex) {
19343
- // an error will throw if the reader hasn't been used yet
22029
+
22030
+ if (body instanceof FormData) {
22031
+ this._bodyFormData = body;
22032
+ this._mimeType = "multipart/form-data";
22033
+ return this;
22034
+ }
22035
+
22036
+ if (body instanceof URLSearchParams) {
22037
+ // URLSearchParams is not handled natively so we reassign bodyInit for fetch to send it as text
22038
+ this._bodyText = this._bodyInit = body.toString();
22039
+ this._mimeType = "application/x-www-form-urlencoded;charset=UTF-8";
22040
+ return this;
22041
+ }
22042
+
22043
+ if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
22044
+ this._bodyArrayBuffer = body.slice?.(0) ?? body.buffer;
22045
+ this._mimeType = "application/octet-stream";
22046
+ return this;
22047
+ }
22048
+
22049
+ if (body instanceof ReadableStream) {
22050
+ this._bodyReadableStream = body;
22051
+ this._mimeType = "application/octet-stream";
22052
+ return this;
22053
+ }
22054
+
22055
+ this._bodyText = body.toString();
22056
+ this._mimeType = "text/plain;charset=UTF-8";
22057
+ }
22058
+
22059
+ __consumed() {
22060
+ if (this.bodyUsed) {
22061
+ return Promise.reject(new TypeError("Already read"));
22062
+ }
22063
+ this.bodyUsed = true;
22064
+ }
22065
+
22066
+ async blob() {
22067
+ const alreadyConsumed = this.__consumed();
22068
+ if (alreadyConsumed) {
22069
+ return alreadyConsumed;
22070
+ }
22071
+
22072
+ if (this._bodyBlob) {
22073
+ return this._bodyBlob;
22074
+ }
22075
+
22076
+ // Currently not supported by React Native. It will throw.
22077
+ // Blobs cannot be constructed from ArrayBuffers or ArrayBufferViews.
22078
+ if (this._bodyReadableStream) {
22079
+ const typedArray = await drainStream(this._bodyReadableStream);
22080
+
22081
+ return new Blob([typedArray]);
22082
+ }
22083
+
22084
+ // Currently not supported by React Native. It will throw.
22085
+ // Blobs cannot be constructed from ArrayBuffers or ArrayBufferViews.
22086
+ if (this._bodyArrayBuffer) {
22087
+ if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
22088
+ return new Blob([this._bodyArrayBuffer.buffer]);
19344
22089
  }
19345
- reader.releaseLock();
19346
- };
19347
- abortSignal?.addEventListener('abort', () => {
19348
- closeReader();
19349
- });
19350
- const outputStream = new ReadableStream({
19351
- start: (controller) => {
19352
- const processStream = async () => {
19353
- while (!abortSignal?.aborted) {
19354
- try {
19355
- const { done, value } = await reader.read();
19356
- // When no more data needs to be consumed, close the stream
19357
- if (done) {
19358
- break;
19359
- }
19360
- // Enqueue the next data chunk into our target stream
19361
- controller.enqueue(value);
19362
- }
19363
- catch (ex) {
19364
- this.logger.error('Caught exception when reading sync stream', ex);
19365
- break;
19366
- }
19367
- }
19368
- if (!abortSignal?.aborted) {
19369
- // Close the downstream readable stream
19370
- await closeReader();
19371
- }
19372
- controller.close();
19373
- };
19374
- processStream();
22090
+
22091
+ return new Blob([this._bodyArrayBuffer]);
22092
+ }
22093
+
22094
+ if (this._bodyFormData) {
22095
+ throw new Error("Could not read FormData body as blob");
22096
+ }
22097
+
22098
+ return new Blob([this._bodyText]);
22099
+ }
22100
+
22101
+ async arrayBuffer() {
22102
+ if (this._bodyText) {
22103
+ const blob = await this.blob();
22104
+
22105
+ return createBlobReader(blob).readAsArrayBuffer();
22106
+ }
22107
+
22108
+ const alreadyConsumed = this.__consumed();
22109
+ if (alreadyConsumed) {
22110
+ return alreadyConsumed;
22111
+ }
22112
+
22113
+ if (this._bodyReadableStream) {
22114
+ const typedArray = await drainStream(this._bodyReadableStream);
22115
+
22116
+ return typedArray.buffer;
22117
+ }
22118
+
22119
+ if (this._bodyArrayBuffer) {
22120
+ if (ArrayBuffer.isView(this._bodyArrayBuffer)) {
22121
+ const {
22122
+ buffer,
22123
+ byteOffset,
22124
+ byteLength,
22125
+ } = this._bodyArrayBuffer;
22126
+
22127
+ return Promise.resolve(
22128
+ buffer.slice(byteOffset, byteOffset + byteLength)
22129
+ );
19375
22130
  }
19376
- });
19377
- const jsonS = ndjsonStream$1(new Response(outputStream).body);
19378
- const stream = new DataStream({
19379
- logger: this.logger
19380
- });
19381
- const r = jsonS.getReader();
19382
- const l = stream.registerListener({
19383
- lowWater: async () => {
19384
- try {
19385
- const { done, value } = await r.read();
19386
- // Exit if we're done
19387
- if (done) {
19388
- stream.close();
19389
- l?.();
19390
- return;
19391
- }
19392
- stream.enqueueData(value);
19393
- }
19394
- catch (ex) {
19395
- stream.close();
19396
- throw ex;
22131
+
22132
+ return Promise.resolve(this._bodyArrayBuffer);
22133
+ }
22134
+ }
22135
+
22136
+ async text() {
22137
+ const alreadyConsumed = this.__consumed();
22138
+ if (alreadyConsumed) {
22139
+ return alreadyConsumed;
22140
+ }
22141
+
22142
+ if (this._bodyReadableStream) {
22143
+ const typedArray = await drainStream(this._bodyReadableStream);
22144
+
22145
+ return readArrayBufferAsText(typedArray);
22146
+ }
22147
+
22148
+ if (this._bodyBlob) {
22149
+ return createBlobReader(this._bodyBlob).readAsText();
22150
+ }
22151
+
22152
+ if (this._bodyArrayBuffer) {
22153
+ return readArrayBufferAsText(this._bodyArrayBuffer);
22154
+ }
22155
+
22156
+ if (this._bodyFormData) {
22157
+ throw new Error("Could not read FormData body as text");
22158
+ }
22159
+
22160
+ return this._bodyText;
22161
+ }
22162
+
22163
+ async json() {
22164
+ const text = await this.text();
22165
+
22166
+ return JSON.parse(text);
22167
+ }
22168
+
22169
+ async formData() {
22170
+ const text = await this.text();
22171
+ const formData = new FormData();
22172
+
22173
+ text.trim()
22174
+ .split("&")
22175
+ .forEach((pairs) => {
22176
+ if (!pairs) {
22177
+ return;
19397
22178
  }
22179
+
22180
+ const split = pairs.split("=");
22181
+ const name = split.shift().replace(/\+/g, " ");
22182
+ const value = split.join("=").replace(/\+/g, " ");
22183
+ formData.append(
22184
+ decodeURIComponent(name),
22185
+ decodeURIComponent(value)
22186
+ );
22187
+ });
22188
+
22189
+ return formData;
22190
+ }
22191
+
22192
+ get body() {
22193
+ if (this._bodyReadableStream) {
22194
+ return this._bodyReadableStream;
22195
+ }
22196
+
22197
+ if (this._bodyArrayBuffer) {
22198
+ const typedArray = new Uint8Array(this._bodyArrayBuffer);
22199
+
22200
+ return new ReadableStream({
22201
+ start(controller) {
22202
+ typedArray.forEach((chunk) => {
22203
+ controller.enqueue(chunk);
22204
+ });
22205
+
22206
+ controller.close();
22207
+ },
22208
+ });
22209
+ }
22210
+
22211
+ if (this._bodyBlob) {
22212
+ return new ReadableStream({
22213
+ start: async (controller) => {
22214
+ const arrayBuffer = await createBlobReader(
22215
+ this._bodyBlob
22216
+ ).readAsArrayBuffer();
22217
+ const typedArray = new Uint8Array(arrayBuffer);
22218
+
22219
+ typedArray.forEach((chunk) => {
22220
+ controller.enqueue(chunk);
22221
+ });
22222
+
22223
+ controller.close();
22224
+ },
22225
+ });
22226
+ }
22227
+
22228
+ const text = this._bodyFormData?.toString() ?? this._bodyText;
22229
+
22230
+ return new ReadableStream({
22231
+ start: async (controller) => {
22232
+ const typedArray = new Uint8Array(text);
22233
+
22234
+ typedArray.forEach((chunk) => {
22235
+ controller.enqueue(chunk);
22236
+ });
22237
+
22238
+ controller.close();
19398
22239
  },
19399
- closed: () => {
19400
- closeReader();
19401
- l?.();
19402
- }
19403
22240
  });
19404
- return stream;
19405
22241
  }
19406
22242
  }
19407
22243
 
19408
- // https://www.sqlite.org/lang_expr.html#castexpr
19409
- exports.ColumnType = void 0;
19410
- (function (ColumnType) {
19411
- ColumnType["TEXT"] = "TEXT";
19412
- ColumnType["INTEGER"] = "INTEGER";
19413
- ColumnType["REAL"] = "REAL";
19414
- })(exports.ColumnType || (exports.ColumnType = {}));
19415
- class Column {
19416
- options;
19417
- constructor(options) {
19418
- this.options = options;
22244
+ class Request {
22245
+ credentials = "same-origin";
22246
+ method = "GET";
22247
+
22248
+ constructor(input, options = {}) {
22249
+ this.url = input;
22250
+
22251
+ if (input instanceof Request) {
22252
+ if (input._body.bodyUsed) {
22253
+ throw new TypeError("Already read");
22254
+ }
22255
+
22256
+ this.__handleRequestInput(input, options);
22257
+ }
22258
+
22259
+ this._body = this._body ?? new Body(options.body);
22260
+ this.method = options.method ?? this.method;
22261
+ this.method = this.method.toUpperCase();
22262
+
22263
+ if (this._body._bodyInit && ["GET", "HEAD"].includes(this.method)) {
22264
+ throw new TypeError("Body not allowed for GET or HEAD requests");
22265
+ }
22266
+
22267
+ if (this._body._bodyReadableStream) {
22268
+ throw new TypeError("Streaming request bodies is not supported");
22269
+ }
22270
+
22271
+ this.credentials = options.credentials ?? this.credentials;
22272
+ this.headers = this.headers ?? new Headers$1(options.headers);
22273
+ this.signal = options.signal ?? this.signal;
22274
+
22275
+ if (!this.headers.has("content-type") && this._body._mimeType) {
22276
+ this.headers.set("content-type", this._body._mimeType);
22277
+ }
22278
+
22279
+ this.__handleCacheOption(options.cache);
22280
+ }
22281
+
22282
+ __handleRequestInput(request, options) {
22283
+ this.url = request.url;
22284
+ this.credentials = request.credentials;
22285
+ this.method = request.method;
22286
+ this.signal = request.signal;
22287
+ this.headers = new Headers$1(options.headers ?? request.headers);
22288
+
22289
+ if (!options.body && request._body._bodyInit) {
22290
+ this._body = new Body(request._body._bodyInit);
22291
+ request._body.bodyUsed = true;
22292
+ }
22293
+ }
22294
+
22295
+ __handleCacheOption(cache) {
22296
+ if (!["GET", "HEAD"].includes(this.method)) {
22297
+ return;
22298
+ }
22299
+
22300
+ if (!["no-store", "no-cache"].includes(cache)) {
22301
+ return;
22302
+ }
22303
+
22304
+ const currentTime = Date.now();
22305
+ // Search for a '_' parameter in the query string
22306
+ const querySearchRegExp = /([?&])_=[^&]*/;
22307
+
22308
+ if (querySearchRegExp.test(this.url)) {
22309
+ this.url = this.url.replace(
22310
+ querySearchRegExp,
22311
+ `$1_=${currentTime}`
22312
+ );
22313
+
22314
+ return;
22315
+ }
22316
+
22317
+ const hasQueryRegExp = /\?/;
22318
+ const querySeparator = hasQueryRegExp.test(this.url) ? "&" : "?";
22319
+
22320
+ this.url += `${querySeparator}_=${currentTime}`;
22321
+ }
22322
+
22323
+ get bodyUsed() {
22324
+ return this._body.bodyUsed;
19419
22325
  }
19420
- get name() {
19421
- return this.options.name;
22326
+
22327
+ clone() {
22328
+ return new Request(this, { body: this._body._bodyInit });
19422
22329
  }
19423
- get type() {
19424
- return this.options.type;
22330
+
22331
+ blob() {
22332
+ return this._body.blob();
19425
22333
  }
19426
- toJSON() {
19427
- return {
19428
- name: this.name,
19429
- type: this.type
19430
- };
22334
+
22335
+ arrayBuffer() {
22336
+ return this._body.arrayBuffer();
22337
+ }
22338
+
22339
+ text() {
22340
+ return this._body.text();
22341
+ }
22342
+
22343
+ json() {
22344
+ return this._body.json();
22345
+ }
22346
+
22347
+ formData() {
22348
+ return this._body.formData();
19431
22349
  }
19432
22350
  }
19433
22351
 
19434
- const DEFAULT_TABLE_OPTIONS = {
19435
- indexes: [],
19436
- insertOnly: false,
19437
- localOnly: false
19438
- };
19439
- const InvalidSQLCharacters = /["'%,.#\s[\]]/;
19440
- class Table {
19441
- options;
19442
- static createLocalOnly(options) {
19443
- return new Table({ ...options, localOnly: true, insertOnly: false });
22352
+ let Response$1 = class Response {
22353
+ constructor(body, options = {}) {
22354
+ this.type = "basic";
22355
+ this.status = options.status ?? 200;
22356
+ this.ok = this.status >= 200 && this.status < 300;
22357
+ this.statusText = options.statusText ?? "";
22358
+ this.headers = new Headers$1(options.headers);
22359
+ this.url = options.url ?? "";
22360
+ this._body = new Body(body);
22361
+
22362
+ if (!this.headers.has("content-type") && this._body._mimeType) {
22363
+ this.headers.set("content-type", this._body._mimeType);
22364
+ }
19444
22365
  }
19445
- static createInsertOnly(options) {
19446
- return new Table({ ...options, localOnly: false, insertOnly: true });
22366
+
22367
+ get bodyUsed() {
22368
+ return this._body.bodyUsed;
19447
22369
  }
19448
- static createTable(name, table) {
19449
- return new Table({
19450
- name,
19451
- columns: Object.entries(table.columns).map(([name, col]) => new Column({ name, type: col.type })),
19452
- indexes: table.indexes,
19453
- localOnly: table.options.localOnly,
19454
- insertOnly: table.options.insertOnly,
19455
- viewName: table.options.viewName
22370
+
22371
+ clone() {
22372
+ return new Response(this._body._bodyInit, {
22373
+ status: this.status,
22374
+ statusText: this.statusText,
22375
+ headers: new Headers$1(this.headers),
22376
+ url: this.url,
19456
22377
  });
19457
22378
  }
19458
- constructor(options) {
19459
- this.options = { ...DEFAULT_TABLE_OPTIONS, ...options };
22379
+
22380
+ blob() {
22381
+ return this._body.blob();
19460
22382
  }
19461
- get name() {
19462
- return this.options.name;
22383
+
22384
+ arrayBuffer() {
22385
+ return this._body.arrayBuffer();
19463
22386
  }
19464
- get viewNameOverride() {
19465
- return this.options.viewName;
22387
+
22388
+ text() {
22389
+ return this._body.text();
19466
22390
  }
19467
- get viewName() {
19468
- return this.viewNameOverride ?? this.name;
22391
+
22392
+ json() {
22393
+ return this._body.json();
19469
22394
  }
19470
- get columns() {
19471
- return this.options.columns;
22395
+
22396
+ formData() {
22397
+ return this._body.formData();
19472
22398
  }
19473
- get indexes() {
19474
- return this.options.indexes ?? [];
22399
+
22400
+ get body() {
22401
+ return this._body.body;
19475
22402
  }
19476
- get localOnly() {
19477
- return this.options.localOnly ?? false;
22403
+ };
22404
+
22405
+ Response$1.error = () => {
22406
+ const response = new Response$1(null, { status: 0, statusText: "" });
22407
+ response.type = "error";
22408
+ return response;
22409
+ };
22410
+
22411
+ Response$1.redirect = (url, status) => {
22412
+ const redirectStatuses = [301, 302, 303, 307, 308];
22413
+
22414
+ if (!redirectStatuses.includes(status)) {
22415
+ throw new RangeError(`Invalid status code: ${status}`);
19478
22416
  }
19479
- get insertOnly() {
19480
- return this.options.insertOnly ?? false;
22417
+
22418
+ return new Response$1(null, { status: status, headers: { location: url } });
22419
+ };
22420
+
22421
+ const pDefer = () => {
22422
+ const deferred = {};
22423
+
22424
+ deferred.promise = new Promise((resolve, reject) => {
22425
+ deferred.resolve = resolve;
22426
+ deferred.reject = reject;
22427
+ });
22428
+
22429
+ return deferred;
22430
+ };
22431
+
22432
+ var pDefer_1 = pDefer;
22433
+
22434
+ var pDefer$1 = /*@__PURE__*/getDefaultExportFromCjs(pDefer_1);
22435
+
22436
+ class BlobResponse extends Response$1 {
22437
+ constructor(blobData, options) {
22438
+ const blob = BlobManager.createFromOptions(blobData);
22439
+ super(blob, options);
22440
+ this._blobData = blobData;
19481
22441
  }
19482
- get internalName() {
19483
- if (this.options.localOnly) {
19484
- return `ps_data_local__${this.name}`;
19485
- }
19486
- return `ps_data__${this.name}`;
22442
+
22443
+ clone() {
22444
+ return new BlobResponse(this._blobData, {
22445
+ status: this.status,
22446
+ statusText: this.statusText,
22447
+ headers: new Headers(this.headers),
22448
+ url: this.url,
22449
+ });
19487
22450
  }
19488
- get validName() {
19489
- if (InvalidSQLCharacters.test(this.name)) {
19490
- return false;
19491
- }
19492
- if (this.viewNameOverride != null && InvalidSQLCharacters.test(this.viewNameOverride)) {
19493
- return false;
19494
- }
19495
- return true;
22451
+ }
22452
+
22453
+ class ArrayBufferResponse extends Response$1 {
22454
+ constructor(base64, options) {
22455
+ const buffer = toByteArray_1(base64);
22456
+ super(buffer, options);
22457
+ this._base64 = base64;
19496
22458
  }
19497
- validate() {
19498
- if (InvalidSQLCharacters.test(this.name)) {
19499
- throw new Error(`Invalid characters in table name: ${this.name}`);
19500
- }
19501
- if (this.viewNameOverride && InvalidSQLCharacters.test(this.viewNameOverride)) {
19502
- throw new Error(`Invalid characters in view name: ${this.viewNameOverride}`);
19503
- }
19504
- const columnNames = new Set();
19505
- columnNames.add('id');
19506
- for (const column of this.columns) {
19507
- const { name: columnName } = column;
19508
- if (column.name == 'id') {
19509
- throw new Error(`${this.name}: id column is automatically added, custom id columns are not supported`);
19510
- }
19511
- if (columnNames.has(columnName)) {
19512
- throw new Error(`Duplicate column ${columnName}`);
19513
- }
19514
- if (InvalidSQLCharacters.test(columnName)) {
19515
- throw new Error(`Invalid characters in column name: $name.${column}`);
19516
- }
19517
- columnNames.add(columnName);
19518
- }
19519
- const indexNames = new Set();
19520
- for (const index of this.indexes) {
19521
- if (indexNames.has(index.name)) {
19522
- throw new Error(`Duplicate index $name.${index}`);
19523
- }
19524
- if (InvalidSQLCharacters.test(index.name)) {
19525
- throw new Error(`Invalid characters in index name: $name.${index}`);
19526
- }
19527
- for (const column of index.columns) {
19528
- if (!columnNames.has(column.name)) {
19529
- throw new Error(`Column ${column.name} not found for index ${index.name}`);
19530
- }
19531
- }
19532
- indexNames.add(index.name);
19533
- }
22459
+
22460
+ clone() {
22461
+ return new ArrayBufferResponse(this._base64, {
22462
+ status: this.status,
22463
+ statusText: this.statusText,
22464
+ headers: new Headers(this.headers),
22465
+ url: this.url,
22466
+ });
19534
22467
  }
19535
- toJSON() {
19536
- return {
19537
- name: this.name,
19538
- view_name: this.viewName,
19539
- local_only: this.localOnly,
19540
- insert_only: this.insertOnly,
19541
- columns: this.columns.map((c) => c.toJSON()),
19542
- indexes: this.indexes.map((e) => e.toJSON(this))
19543
- };
22468
+ }
22469
+
22470
+ class AbortError extends Error {
22471
+ constructor() {
22472
+ super("Aborted");
22473
+ this.name = "AbortError";
22474
+ Error.captureStackTrace?.(this, this.constructor);
19544
22475
  }
19545
22476
  }
19546
22477
 
19547
- /**
19548
- * A schema is a collection of tables. It is used to define the structure of a database.
19549
- */
19550
- class Schema {
19551
- /*
19552
- Only available when constructing with mapped typed definition columns
19553
- */
19554
- types;
19555
- props;
19556
- tables;
19557
- constructor(tables) {
19558
- if (Array.isArray(tables)) {
19559
- this.tables = tables;
22478
+ function createStream(cancel) {
22479
+ let streamController;
22480
+
22481
+ const stream = new ReadableStream({
22482
+ start(controller) {
22483
+ streamController = controller;
22484
+ },
22485
+ cancel,
22486
+ });
22487
+
22488
+ return {
22489
+ stream,
22490
+ streamController,
22491
+ };
22492
+ }
22493
+
22494
+ class Fetch {
22495
+ _nativeNetworkSubscriptions = new Set();
22496
+ _nativeResponseType = "blob";
22497
+ _nativeRequestHeaders = {};
22498
+ _nativeResponseHeaders = {};
22499
+ _nativeRequestTimeout = 0;
22500
+ _nativeResponse;
22501
+ _textEncoder = new textEncoding.TextEncoder();
22502
+ _requestId;
22503
+ _response;
22504
+ _streamController;
22505
+ _deferredPromise;
22506
+ _responseStatus = 0; // requests shall not time out
22507
+ _responseUrl = "";
22508
+
22509
+ constructor(resource, options = {}) {
22510
+ this._request = new Request(resource, options);
22511
+
22512
+ if (this._request.signal?.aborted) {
22513
+ throw new AbortError();
19560
22514
  }
19561
- else {
19562
- this.props = tables;
19563
- this.tables = this.convertToClassicTables(this.props);
22515
+
22516
+ this._abortFn = this.__abort.bind(this);
22517
+ this._deferredPromise = pDefer$1();
22518
+ this._request.signal?.addEventListener("abort", this._abortFn);
22519
+
22520
+ for (const [name, value] of this._request.headers.entries()) {
22521
+ this._nativeRequestHeaders[name] = value;
19564
22522
  }
22523
+
22524
+ this.__setNativeResponseType(options);
22525
+ this.__doFetch();
22526
+
22527
+ return this._deferredPromise.promise;
19565
22528
  }
19566
- validate() {
19567
- for (const table of this.tables) {
19568
- table.validate();
22529
+
22530
+ __setNativeResponseType({ reactNative }) {
22531
+ if (reactNative?.textStreaming) {
22532
+ this._nativeResponseType = "text";
22533
+
22534
+ return;
19569
22535
  }
22536
+
22537
+ this._nativeResponseType =
22538
+ reactNative?.__nativeResponseType ?? this._nativeResponseType;
19570
22539
  }
19571
- toJSON() {
19572
- return {
19573
- tables: this.tables.map((t) => t.toJSON())
19574
- };
19575
- }
19576
- convertToClassicTables(props) {
19577
- return Object.entries(props).map(([name, table]) => {
19578
- return Table.createTable(name, table);
19579
- });
19580
- }
19581
- }
19582
22540
 
19583
- const DEFAULT_INDEX_COLUMN_OPTIONS = {
19584
- ascending: true
19585
- };
19586
- class IndexedColumn {
19587
- options;
19588
- static createAscending(column) {
19589
- return new IndexedColumn({
19590
- name: column,
19591
- ascending: true
22541
+ __subscribeToNetworkEvents() {
22542
+ [
22543
+ "didReceiveNetworkResponse",
22544
+ "didReceiveNetworkData",
22545
+ "didReceiveNetworkIncrementalData",
22546
+ // "didReceiveNetworkDataProgress",
22547
+ "didCompleteNetworkResponse",
22548
+ ].forEach((eventName) => {
22549
+ const subscription = reactNative.Networking.addListener(eventName, (args) => {
22550
+ this[`__${eventName}`](...args);
22551
+ });
22552
+ this._nativeNetworkSubscriptions.add(subscription);
19592
22553
  });
19593
22554
  }
19594
- constructor(options) {
19595
- this.options = { ...DEFAULT_INDEX_COLUMN_OPTIONS, ...options };
22555
+
22556
+ __clearNetworkSubscriptions() {
22557
+ this._nativeNetworkSubscriptions.forEach((subscription) =>
22558
+ subscription.remove()
22559
+ );
22560
+ this._nativeNetworkSubscriptions.clear();
19596
22561
  }
19597
- get name() {
19598
- return this.options.name;
22562
+
22563
+ __abort() {
22564
+ this._requestId && reactNative.Networking.abortRequest(this._requestId);
22565
+ this._streamController?.error(new AbortError());
22566
+ this._deferredPromise.reject(new AbortError());
22567
+ this.__clearNetworkSubscriptions();
19599
22568
  }
19600
- get ascending() {
19601
- return this.options.ascending;
22569
+
22570
+ __doFetch() {
22571
+ this.__subscribeToNetworkEvents();
22572
+
22573
+ reactNative.Networking.sendRequest(
22574
+ this._request.method,
22575
+ this._request.url.toString(), // request tracking name
22576
+ this._request.url.toString(),
22577
+ this._nativeRequestHeaders,
22578
+ this._request._body._bodyInit ?? null,
22579
+ this._nativeResponseType,
22580
+ this._nativeResponseType === "text", // send incremental events only when response type is text
22581
+ this._nativeRequestTimeout,
22582
+ this.__didCreateRequest.bind(this),
22583
+ ["include", "same-origin"].includes(this._request.credentials) // with credentials
22584
+ );
19602
22585
  }
19603
- toJSON(table) {
19604
- return {
19605
- name: this.name,
19606
- ascending: this.ascending,
19607
- type: table.columns.find((column) => column.name === this.name)?.type ?? exports.ColumnType.TEXT
19608
- };
22586
+
22587
+ __didCreateRequest(requestId) {
22588
+ // console.log("fetch __didCreateRequest", { requestId });
22589
+ this._requestId = requestId;
19609
22590
  }
19610
- }
19611
22591
 
19612
- const DEFAULT_INDEX_OPTIONS = {
19613
- columns: []
19614
- };
19615
- class Index {
19616
- options;
19617
- static createAscending(options, columnNames) {
19618
- return new Index({
19619
- ...options,
19620
- columns: columnNames.map((name) => IndexedColumn.createAscending(name))
22592
+ __didReceiveNetworkResponse(requestId, status, headers, url) {
22593
+ // console.log("fetch __didReceiveNetworkResponse", {
22594
+ // requestId,
22595
+ // status,
22596
+ // headers,
22597
+ // url,
22598
+ // });
22599
+
22600
+ if (requestId !== this._requestId) {
22601
+ return;
22602
+ }
22603
+
22604
+ const { stream, streamController } = createStream(() => {
22605
+ this.__clearNetworkSubscriptions();
22606
+ reactNative.Networking.abortRequest(this._requestId);
19621
22607
  });
22608
+
22609
+ this._streamController = streamController;
22610
+ this._stream = stream;
22611
+ this._responseStatus = status;
22612
+ this._nativeResponseHeaders = headers;
22613
+ this._responseUrl = url;
22614
+
22615
+ if (this._nativeResponseType === "text") {
22616
+ this._response = new Response$1(stream, { status, headers, url });
22617
+ this._deferredPromise.resolve(this._response);
22618
+ }
19622
22619
  }
19623
- constructor(options) {
19624
- this.options = options;
19625
- this.options = { ...DEFAULT_INDEX_OPTIONS, ...options };
19626
- }
19627
- get name() {
19628
- return this.options.name;
19629
- }
19630
- get columns() {
19631
- return this.options.columns ?? [];
19632
- }
19633
- toJSON(table) {
19634
- return {
19635
- name: this.name,
19636
- columns: this.columns.map((c) => c.toJSON(table))
19637
- };
19638
- }
19639
- }
19640
22620
 
19641
- const text = {
19642
- type: exports.ColumnType.TEXT
19643
- };
19644
- const integer = {
19645
- type: exports.ColumnType.INTEGER
19646
- };
19647
- const real = {
19648
- type: exports.ColumnType.REAL
19649
- };
19650
- const column = {
19651
- text,
19652
- integer,
19653
- real
19654
- };
19655
- /*
19656
- Generate a new table from the columns and indexes
19657
- */
19658
- class TableV2 {
19659
- columns;
19660
- options;
19661
- indexes;
19662
- constructor(columns, options = {}) {
19663
- this.columns = columns;
19664
- this.options = options;
19665
- if (options?.indexes) {
19666
- this.indexes = Object.entries(options.indexes).map(([name, columns]) => {
19667
- if (name.startsWith('-')) {
19668
- return new Index({
19669
- name: name.substring(1),
19670
- columns: columns.map((c) => new IndexedColumn({ name: c, ascending: false }))
19671
- });
19672
- }
19673
- return new Index({
19674
- name: name,
19675
- columns: columns.map((c) => new IndexedColumn({ name: c, ascending: true }))
19676
- });
19677
- });
22621
+ __didReceiveNetworkData(requestId, response) {
22622
+ // console.log("fetch __didReceiveNetworkData", { requestId, response });
22623
+ if (requestId !== this._requestId) {
22624
+ return;
19678
22625
  }
22626
+
22627
+ this._nativeResponse = response;
19679
22628
  }
19680
- }
19681
22629
 
19682
- const parseQuery = (query, parameters) => {
19683
- let sqlStatement;
19684
- if (typeof query == 'string') {
19685
- sqlStatement = query;
22630
+ __didReceiveNetworkIncrementalData(
22631
+ requestId,
22632
+ responseText,
22633
+ progress,
22634
+ total
22635
+ ) {
22636
+ // console.log("fetch __didReceiveNetworkIncrementalData", {
22637
+ // requestId,
22638
+ // responseText,
22639
+ // progress,
22640
+ // total,
22641
+ // });
22642
+ if (requestId !== this._requestId) {
22643
+ return;
22644
+ }
22645
+
22646
+ const typedArray = this._textEncoder.encode(responseText, {
22647
+ stream: true,
22648
+ });
22649
+ this._streamController.enqueue(typedArray);
19686
22650
  }
19687
- else {
19688
- const hasAdditionalParameters = parameters.length > 0;
19689
- if (hasAdditionalParameters) {
19690
- throw new Error('You cannot pass parameters to a compiled query.');
22651
+
22652
+ // __didReceiveNetworkDataProgress(requestId, loaded, total) {
22653
+ // console.log('fetch __didReceiveNetworkDataProgress', { requestId, loaded, total });
22654
+ // if (requestId !== this._requestId) {
22655
+ // return;
22656
+ // }
22657
+ // }
22658
+
22659
+ async __didCompleteNetworkResponse(requestId, errorMessage, didTimeOut) {
22660
+ // console.log("fetch __didCompleteNetworkResponse", {
22661
+ // requestId,
22662
+ // errorMessage,
22663
+ // didTimeOut,
22664
+ // });
22665
+
22666
+ if (requestId !== this._requestId) {
22667
+ return;
22668
+ }
22669
+
22670
+ this.__clearNetworkSubscriptions();
22671
+ this._request.signal?.removeEventListener("abort", this._abortFn);
22672
+
22673
+ if (didTimeOut) {
22674
+ this.__closeStream();
22675
+
22676
+ return this._deferredPromise.reject(
22677
+ new TypeError("Network request timed out")
22678
+ );
22679
+ }
22680
+
22681
+ if (errorMessage) {
22682
+ this.__closeStream();
22683
+
22684
+ return this._deferredPromise.reject(
22685
+ new TypeError(`Network request failed: ${errorMessage}`)
22686
+ );
22687
+ }
22688
+
22689
+ if (this._nativeResponseType === "text") {
22690
+ this.__closeStream();
22691
+ return;
22692
+ }
22693
+
22694
+ let ResponseClass;
22695
+
22696
+ if (this._nativeResponseType === "blob") {
22697
+ ResponseClass = BlobResponse;
22698
+ }
22699
+
22700
+ if (this._nativeResponseType === "base64") {
22701
+ ResponseClass = ArrayBufferResponse;
22702
+ }
22703
+
22704
+ try {
22705
+ this._response = new ResponseClass(this._nativeResponse, {
22706
+ status: this._responseStatus,
22707
+ url: this._responseUrl,
22708
+ headers: this._nativeResponseHeaders,
22709
+ });
22710
+ this._deferredPromise.resolve(this._response);
22711
+ } catch (error) {
22712
+ this._deferredPromise.reject(error);
22713
+ } finally {
22714
+ this.__closeStream();
19691
22715
  }
19692
- const compiled = query.compile();
19693
- sqlStatement = compiled.sql;
19694
- parameters = compiled.parameters;
19695
22716
  }
19696
- return { sqlStatement, parameters: parameters };
19697
- };
22717
+
22718
+ __closeStream() {
22719
+ this._streamController?.close();
22720
+ }
22721
+ }
22722
+
22723
+ const fetch = (resource, options) => new Fetch(resource, options);
19698
22724
 
19699
22725
  const STREAMING_POST_TIMEOUT_MS = 30_000;
22726
+ /**
22727
+ * Directly imports fetch implementation from react-native-fetch-api.
22728
+ * This removes the requirement for the global `fetch` to be overridden by
22729
+ * a polyfill.
22730
+ */
22731
+ class ReactNativeFetchProvider extends FetchImplementationProvider {
22732
+ getFetch() {
22733
+ return fetch.bind(globalThis);
22734
+ }
22735
+ }
19700
22736
  const CommonPolyfills = [
19701
22737
  // {
19702
22738
  // name: 'TextEncoder',
@@ -19736,6 +22772,16 @@ ${missingPolyfills.join('\n')}`);
19736
22772
  }
19737
22773
  };
19738
22774
  class ReactNativeRemote extends AbstractRemote {
22775
+ connector;
22776
+ logger;
22777
+ constructor(connector, logger = DEFAULT_REMOTE_LOGGER, options) {
22778
+ super(connector, logger, {
22779
+ ...(options ?? {}),
22780
+ fetchImplementation: options?.fetchImplementation ?? new ReactNativeFetchProvider()
22781
+ });
22782
+ this.connector = connector;
22783
+ this.logger = logger;
22784
+ }
19739
22785
  async getBSON() {
19740
22786
  return bson.BSON;
19741
22787
  }
@@ -20126,31 +23172,10 @@ class ReactNativeStreamingSyncImplementation extends AbstractStreamingSyncImplem
20126
23172
  }
20127
23173
  }
20128
23174
 
20129
- class PowerSyncDatabase extends AbstractPowerSyncDatabase {
20130
- async _initialize() { }
20131
- generateBucketStorageAdapter() {
20132
- return new SqliteBucketStorage(this.database, AbstractPowerSyncDatabase.transactionMutex);
20133
- }
20134
- generateSyncStreamImplementation(connector) {
20135
- const remote = new ReactNativeRemote(connector);
20136
- return new ReactNativeStreamingSyncImplementation({
20137
- adapter: this.bucketStorageAdapter,
20138
- remote,
20139
- uploadCrud: async () => {
20140
- await this.waitForReady();
20141
- await connector.uploadData(this);
20142
- },
20143
- retryDelayMs: this.options.retryDelay,
20144
- crudUploadThrottleMs: this.options.crudUploadThrottleMs,
20145
- identifier: this.options.database.name
20146
- });
20147
- }
20148
- }
20149
-
20150
23175
  /**
20151
23176
  * Adapter for React Native Quick SQLite
20152
23177
  */
20153
- class RNQSDBAdapter extends BaseObserver$1 {
23178
+ class RNQSDBAdapter extends BaseObserver {
20154
23179
  baseDB;
20155
23180
  name;
20156
23181
  getAll;
@@ -20248,396 +23273,12 @@ class RNQSDBAdapter extends BaseObserver$1 {
20248
23273
  }
20249
23274
 
20250
23275
  /**
20251
- * Object returned by SQL Query executions {
20252
- * insertId: Represent the auto-generated row id if applicable
20253
- * rowsAffected: Number of affected rows if result of a update query
20254
- * message: if status === 1, here you will find error description
20255
- * rows: if status is undefined or 0 this object will contain the query results
20256
- * }
20257
- *
20258
- * @interface QueryResult
20259
- */
20260
-
20261
- let TransactionEvent = /*#__PURE__*/function (TransactionEvent) {
20262
- TransactionEvent[TransactionEvent["COMMIT"] = 0] = "COMMIT";
20263
- TransactionEvent[TransactionEvent["ROLLBACK"] = 1] = "ROLLBACK";
20264
- return TransactionEvent;
20265
- }({});
20266
- let ConcurrentLockType = /*#__PURE__*/function (ConcurrentLockType) {
20267
- ConcurrentLockType[ConcurrentLockType["READ"] = 0] = "READ";
20268
- ConcurrentLockType[ConcurrentLockType["WRITE"] = 1] = "WRITE";
20269
- return ConcurrentLockType;
20270
- }({});
20271
-
20272
- // Add 'item' function to result object to allow the sqlite-storage typeorm driver to work
20273
- const enhanceQueryResult = result => {
20274
- // Add 'item' function to result object to allow the sqlite-storage typeorm driver to work
20275
- if (result.rows == null) {
20276
- result.rows = {
20277
- _array: [],
20278
- length: 0,
20279
- item: idx => result.rows._array[idx]
20280
- };
20281
- } else {
20282
- result.rows.item = idx => result.rows._array[idx];
20283
- }
20284
- };
20285
-
20286
- const updateCallbacks = {};
20287
- const transactionCallbacks = {};
20288
-
20289
- /**
20290
- * Entry point for update callbacks. This is triggered from C++ with params.
20291
- */
20292
- global.triggerUpdateHook = function (dbName, table, opType, rowId) {
20293
- const callback = updateCallbacks[dbName];
20294
- if (!callback) {
20295
- return;
20296
- }
20297
- callback({
20298
- opType,
20299
- table,
20300
- rowId
20301
- });
20302
- return null;
20303
- };
20304
- const registerUpdateHook = (dbName, callback) => {
20305
- updateCallbacks[dbName] = callback;
20306
- };
20307
-
20308
- /**
20309
- * Entry point for transaction callbacks. This is triggered from C++ with params.
20310
- */
20311
- global.triggerTransactionFinalizerHook = function (dbName, eventType) {
20312
- const callback = transactionCallbacks[dbName];
20313
- if (!callback) {
20314
- return;
20315
- }
20316
- callback(eventType);
20317
- return null;
20318
- };
20319
- const registerTransactionHook = (dbName, callback) => {
20320
- transactionCallbacks[dbName] = callback;
20321
- };
20322
-
20323
- function _defineProperty$1(obj, key, value) { key = _toPropertyKey$1(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
20324
- function _toPropertyKey$1(t) { var i = _toPrimitive$1(t, "string"); return "symbol" == typeof i ? i : String(i); }
20325
- function _toPrimitive$1(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
20326
- class BaseObserver {
20327
- constructor() {
20328
- _defineProperty$1(this, "listeners", void 0);
20329
- this.listeners = new Set();
20330
- }
20331
- registerListener(listener) {
20332
- this.listeners.add(listener);
20333
- return () => {
20334
- this.listeners.delete(listener);
20335
- };
20336
- }
20337
- iterateListeners(cb) {
20338
- for (const listener of this.listeners) {
20339
- cb(listener);
20340
- }
20341
- }
20342
- }
20343
-
20344
- function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
20345
- function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : String(i); }
20346
- function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
20347
- class DBListenerManager extends BaseObserver {}
20348
- class DBListenerManagerInternal extends DBListenerManager {
20349
- constructor(options) {
20350
- super();
20351
- this.options = options;
20352
- _defineProperty(this, "updateBuffer", void 0);
20353
- this.updateBuffer = [];
20354
- registerUpdateHook(this.options.dbName, update => this.handleTableUpdates(update));
20355
- registerTransactionHook(this.options.dbName, eventType => {
20356
- switch (eventType) {
20357
- /**
20358
- * COMMIT hooks occur before the commit is completed. This leads to race conditions.
20359
- * Only use the rollback event to clear updates.
20360
- */
20361
- case TransactionEvent.ROLLBACK:
20362
- this.transactionReverted();
20363
- break;
20364
- }
20365
- this.iterateListeners(l => {
20366
- var _l$writeTransaction;
20367
- return (_l$writeTransaction = l.writeTransaction) === null || _l$writeTransaction === void 0 ? void 0 : _l$writeTransaction.call(l, {
20368
- type: eventType
20369
- });
20370
- });
20371
- });
20372
- }
20373
- flushUpdates() {
20374
- if (!this.updateBuffer.length) {
20375
- return;
20376
- }
20377
- const groupedUpdates = this.updateBuffer.reduce((grouping, update) => {
20378
- const {
20379
- table
20380
- } = update;
20381
- const updateGroup = grouping[table] || (grouping[table] = []);
20382
- updateGroup.push(update);
20383
- return grouping;
20384
- }, {});
20385
- const batchedUpdate = {
20386
- groupedUpdates,
20387
- rawUpdates: this.updateBuffer,
20388
- tables: Object.keys(groupedUpdates)
20389
- };
20390
- this.updateBuffer = [];
20391
- this.iterateListeners(l => {
20392
- var _l$tablesUpdated;
20393
- return (_l$tablesUpdated = l.tablesUpdated) === null || _l$tablesUpdated === void 0 ? void 0 : _l$tablesUpdated.call(l, batchedUpdate);
20394
- });
20395
- }
20396
- transactionReverted() {
20397
- // clear updates
20398
- this.updateBuffer = [];
20399
- }
20400
- handleTableUpdates(notification) {
20401
- // Fire updates for any change
20402
- this.iterateListeners(l => {
20403
- var _l$rawTableChange;
20404
- return (_l$rawTableChange = l.rawTableChange) === null || _l$rawTableChange === void 0 ? void 0 : _l$rawTableChange.call(l, {
20405
- ...notification
20406
- });
20407
- });
20408
-
20409
- // Queue changes until they are flushed
20410
- this.updateBuffer.push(notification);
20411
- }
20412
- }
20413
-
20414
- var TransactionFinalizer = /*#__PURE__*/function (TransactionFinalizer) {
20415
- TransactionFinalizer["COMMIT"] = "commit";
20416
- TransactionFinalizer["ROLLBACK"] = "rollback";
20417
- return TransactionFinalizer;
20418
- }(TransactionFinalizer || {});
20419
- const DEFAULT_READ_CONNECTIONS = 4;
20420
-
20421
- // A incrementing integer ID for tracking lock requests
20422
- let requestIdCounter = 1;
20423
- const getRequestId = () => {
20424
- requestIdCounter++;
20425
- return `${requestIdCounter}`;
20426
- };
20427
- const LockCallbacks = {};
20428
- let proxy$1;
20429
-
20430
- /**
20431
- * Closes the context in JS and C++
20432
- */
20433
- function closeContextLock(dbName, id) {
20434
- delete LockCallbacks[id];
20435
-
20436
- // This is configured by the setupOpen function
20437
- proxy$1.releaseLock(dbName, id);
20438
- }
20439
-
20440
- /**
20441
- * JS callback to trigger queued callbacks when a lock context is available.
20442
- * Declared on the global scope so that C++ can call it.
20443
- * @param lockId
20444
- * @returns
20445
- */
20446
- global.onLockContextIsAvailable = async (dbName, lockId) => {
20447
- // Don't hold C++ bridge side up waiting to complete
20448
- setImmediate(async () => {
20449
- try {
20450
- const record = LockCallbacks[lockId];
20451
- if (record !== null && record !== void 0 && record.timeout) {
20452
- clearTimeout(record.timeout);
20453
- }
20454
- await (record === null || record === void 0 ? void 0 : record.callback({
20455
- // @ts-expect-error This is not part of the public interface, but is used internally
20456
- _contextId: lockId,
20457
- execute: async (sql, args) => {
20458
- const result = await proxy$1.executeInContext(dbName, lockId, sql, args);
20459
- enhanceQueryResult(result);
20460
- return result;
20461
- }
20462
- }));
20463
- } catch (ex) {
20464
- console.error(ex);
20465
- }
20466
- });
20467
- };
20468
-
20469
- /**
20470
- * Generates the entry point for opening concurrent connections
20471
- * @param proxy
20472
- * @returns
23276
+ * Opens a SQLite connection using React Native Quick SQLite
20473
23277
  */
20474
- function setupOpen(QuickSQLite) {
20475
- // Allow the Global callbacks to close lock contexts
20476
- proxy$1 = QuickSQLite;
20477
- return {
20478
- /**
20479
- * Opens a SQLite DB connection.
20480
- * By default opens DB in WAL mode with 4 Read connections and a single
20481
- * write connection
20482
- */
20483
- open: (dbName, options = {}) => {
20484
- // Opens the connection
20485
- QuickSQLite.open(dbName, {
20486
- ...options,
20487
- numReadConnections: (options === null || options === void 0 ? void 0 : options.numReadConnections) ?? DEFAULT_READ_CONNECTIONS
20488
- });
20489
- const listenerManager = new DBListenerManagerInternal({
20490
- dbName
20491
- });
20492
-
20493
- /**
20494
- * Wraps lock requests and their callbacks in order to resolve the lock
20495
- * request with the callback result once triggered from the connection pool.
20496
- */
20497
- const requestLock = (type, callback, options, hooks) => {
20498
- const id = getRequestId();
20499
- // Wrap the callback in a promise that will resolve to the callback result
20500
- return new Promise((resolve, reject) => {
20501
- // Add callback to the queue for timing
20502
- const record = LockCallbacks[id] = {
20503
- callback: async context => {
20504
- try {
20505
- var _hooks$lockAcquired;
20506
- await (hooks === null || hooks === void 0 || (_hooks$lockAcquired = hooks.lockAcquired) === null || _hooks$lockAcquired === void 0 ? void 0 : _hooks$lockAcquired.call(hooks));
20507
- const res = await callback(context);
20508
- closeContextLock(dbName, id);
20509
- resolve(res);
20510
- } catch (ex) {
20511
- closeContextLock(dbName, id);
20512
- reject(ex);
20513
- } finally {
20514
- var _hooks$lockReleased;
20515
- hooks === null || hooks === void 0 || (_hooks$lockReleased = hooks.lockReleased) === null || _hooks$lockReleased === void 0 || _hooks$lockReleased.call(hooks);
20516
- }
20517
- }
20518
- };
20519
- try {
20520
- QuickSQLite.requestLock(dbName, id, type);
20521
- const timeout = options === null || options === void 0 ? void 0 : options.timeoutMs;
20522
- if (timeout) {
20523
- record.timeout = setTimeout(() => {
20524
- // The callback won't be executed
20525
- delete LockCallbacks[id];
20526
- reject(new Error(`Lock request timed out after ${timeout}ms`));
20527
- }, timeout);
20528
- }
20529
- } catch (ex) {
20530
- // Remove callback from the queue
20531
- delete LockCallbacks[id];
20532
- reject(ex);
20533
- }
20534
- });
20535
- };
20536
- const readLock = (callback, options) => requestLock(ConcurrentLockType.READ, callback, options);
20537
- const writeLock = (callback, options) => requestLock(ConcurrentLockType.WRITE, callback, options, {
20538
- lockReleased: async () => {
20539
- // flush updates once a write lock has been released
20540
- listenerManager.flushUpdates();
20541
- }
20542
- });
20543
- const wrapTransaction = async (context, callback, defaultFinalizer = TransactionFinalizer.COMMIT) => {
20544
- await context.execute('BEGIN TRANSACTION');
20545
- let finalized = false;
20546
- const finalizedStatement = action => () => {
20547
- if (finalized) {
20548
- return;
20549
- }
20550
- finalized = true;
20551
- return action();
20552
- };
20553
- const commit = finalizedStatement(async () => context.execute('COMMIT'));
20554
- const rollback = finalizedStatement(async () => context.execute('ROLLBACK'));
20555
- const wrapExecute = method => async (sql, params) => {
20556
- if (finalized) {
20557
- throw new Error(`Cannot execute in transaction after it has been finalized with commit/rollback.`);
20558
- }
20559
- return method(sql, params);
20560
- };
20561
- try {
20562
- const res = await callback({
20563
- ...context,
20564
- commit,
20565
- rollback,
20566
- execute: wrapExecute(context.execute)
20567
- });
20568
- switch (defaultFinalizer) {
20569
- case TransactionFinalizer.COMMIT:
20570
- await commit();
20571
- break;
20572
- case TransactionFinalizer.ROLLBACK:
20573
- await rollback();
20574
- break;
20575
- }
20576
- return res;
20577
- } catch (ex) {
20578
- await rollback();
20579
- throw ex;
20580
- }
20581
- };
20582
-
20583
- // Return the concurrent connection object
20584
- return {
20585
- close: () => QuickSQLite.close(dbName),
20586
- execute: (sql, args) => writeLock(context => context.execute(sql, args)),
20587
- readLock,
20588
- readTransaction: async (callback, options) => readLock(context => wrapTransaction(context, callback)),
20589
- writeLock,
20590
- writeTransaction: async (callback, options) => writeLock(context => wrapTransaction(context, callback, TransactionFinalizer.COMMIT), options),
20591
- delete: () => QuickSQLite.delete(dbName, options === null || options === void 0 ? void 0 : options.location),
20592
- executeBatch: commands => writeLock(context => QuickSQLite.executeBatch(dbName, commands, context._contextId)),
20593
- attach: (dbNameToAttach, alias, location) => QuickSQLite.attach(dbName, dbNameToAttach, alias, location),
20594
- detach: alias => QuickSQLite.detach(dbName, alias),
20595
- loadFile: location => writeLock(context => QuickSQLite.loadFile(dbName, location, context._contextId)),
20596
- listenerManager,
20597
- registerUpdateHook: callback => listenerManager.registerListener({
20598
- rawTableChange: callback
20599
- }),
20600
- registerTablesChangedHook: callback => listenerManager.registerListener({
20601
- tablesUpdated: callback
20602
- })
20603
- };
20604
- }
20605
- };
20606
- }
20607
-
20608
- if (global.__QuickSQLiteProxy == null) {
20609
- const QuickSQLiteModule = reactNative.NativeModules.QuickSQLite;
20610
- if (QuickSQLiteModule == null) {
20611
- throw new Error('Base quick-sqlite module not found. Maybe try rebuilding the app.');
20612
- }
20613
-
20614
- // Check if we are running on-device (JSI)
20615
- if (global.nativeCallSyncHook == null || QuickSQLiteModule.install == null) {
20616
- throw new Error('Failed to install react-native-quick-sqlite: React Native is not running on-device. QuickSQLite can only be used when synchronous method invocations (JSI) are possible. If you are using a remote debugger (e.g. Chrome), switch to an on-device debugger (e.g. Flipper) instead.');
20617
- }
20618
-
20619
- // Call the synchronous blocking install() function
20620
- const result = QuickSQLiteModule.install();
20621
- if (result !== true) {
20622
- throw new Error(`Failed to install react-native-quick-sqlite: The native QuickSQLite Module could not be installed! Looks like something went wrong when installing JSI bindings: ${result}`);
20623
- }
20624
-
20625
- // Check again if the constructor now exists. If not, throw an error.
20626
- if (global.__QuickSQLiteProxy == null) {
20627
- throw new Error('Failed to install react-native-quick-sqlite, the native initializer function does not exist. Are you trying to use QuickSQLite from different JS Runtimes?');
20628
- }
20629
- }
20630
- const proxy = global.__QuickSQLiteProxy;
20631
- const QuickSQLite = proxy;
20632
- const {
20633
- open
20634
- } = setupOpen(QuickSQLite);
20635
-
20636
- class RNQSPowerSyncDatabaseOpenFactory extends AbstractPowerSyncDatabaseOpenFactory {
20637
- instanceGenerated;
23278
+ class ReactNativeQuickSqliteOpenFactory {
23279
+ options;
20638
23280
  constructor(options) {
20639
- super(options);
20640
- this.instanceGenerated = false;
23281
+ this.options = options;
20641
23282
  }
20642
23283
  openDB() {
20643
23284
  /**
@@ -20653,12 +23294,12 @@ class RNQSPowerSyncDatabaseOpenFactory extends AbstractPowerSyncDatabaseOpenFact
20653
23294
  let DB;
20654
23295
  try {
20655
23296
  // Hot reloads can sometimes clear global JS state, but not close DB on native side
20656
- DB = open(dbFilename, openOptions);
23297
+ DB = reactNativeQuickSqlite.open(dbFilename, openOptions);
20657
23298
  }
20658
23299
  catch (ex) {
20659
23300
  if (ex.message.includes('already open')) {
20660
- QuickSQLite.close(dbFilename);
20661
- DB = open(dbFilename, openOptions);
23301
+ reactNativeQuickSqlite.QuickSQLite.close(dbFilename);
23302
+ DB = reactNativeQuickSqlite.open(dbFilename, openOptions);
20662
23303
  }
20663
23304
  else {
20664
23305
  throw ex;
@@ -20666,6 +23307,73 @@ class RNQSPowerSyncDatabaseOpenFactory extends AbstractPowerSyncDatabaseOpenFact
20666
23307
  }
20667
23308
  return new RNQSDBAdapter(DB, this.options.dbFilename);
20668
23309
  }
23310
+ }
23311
+
23312
+ /**
23313
+ * A PowerSync database which provides SQLite functionality
23314
+ * which is automatically synced.
23315
+ *
23316
+ * @example
23317
+ * ```typescript
23318
+ * export const db = new PowerSyncDatabase({
23319
+ * schema: AppSchema,
23320
+ * database: {
23321
+ * dbFilename: 'example.db'
23322
+ * }
23323
+ * });
23324
+ * ```
23325
+ */
23326
+ class PowerSyncDatabase extends AbstractPowerSyncDatabase {
23327
+ async _initialize() { }
23328
+ /**
23329
+ * Opens a DBAdapter using React Native Quick SQLite as the
23330
+ * default SQLite open factory.
23331
+ */
23332
+ openDBAdapter(options) {
23333
+ const defaultFactory = new ReactNativeQuickSqliteOpenFactory(options);
23334
+ return defaultFactory.openDB();
23335
+ }
23336
+ generateBucketStorageAdapter() {
23337
+ return new SqliteBucketStorage(this.database, AbstractPowerSyncDatabase.transactionMutex);
23338
+ }
23339
+ generateSyncStreamImplementation(connector) {
23340
+ const remote = new ReactNativeRemote(connector);
23341
+ return new ReactNativeStreamingSyncImplementation({
23342
+ adapter: this.bucketStorageAdapter,
23343
+ remote,
23344
+ uploadCrud: async () => {
23345
+ await this.waitForReady();
23346
+ await connector.uploadData(this);
23347
+ },
23348
+ retryDelayMs: this.options.retryDelay,
23349
+ crudUploadThrottleMs: this.options.crudUploadThrottleMs,
23350
+ identifier: this.database.name
23351
+ });
23352
+ }
23353
+ }
23354
+
23355
+ /**
23356
+ * @deprecated {@link PowerSyncDatabase} can now be constructed directly
23357
+ * @example
23358
+ * ```typescript
23359
+ * const powersync = new PowerSyncDatabase({
23360
+ * database: {
23361
+ * dbFileName: 'powersync.db'
23362
+ * }
23363
+ * });
23364
+ * ```
23365
+ */
23366
+ class RNQSPowerSyncDatabaseOpenFactory extends AbstractPowerSyncDatabaseOpenFactory {
23367
+ instanceGenerated;
23368
+ sqlOpenFactory;
23369
+ constructor(options) {
23370
+ super(options);
23371
+ this.instanceGenerated = false;
23372
+ this.sqlOpenFactory = new ReactNativeQuickSqliteOpenFactory(options);
23373
+ }
23374
+ openDB() {
23375
+ return this.sqlOpenFactory.openDB();
23376
+ }
20669
23377
  generateInstance(options) {
20670
23378
  if (this.instanceGenerated) {
20671
23379
  this.options.logger?.warn('Generating multiple PowerSync instances can sometimes cause unexpected results.');
@@ -20680,7 +23388,7 @@ exports.AbstractPowerSyncDatabase = AbstractPowerSyncDatabase;
20680
23388
  exports.AbstractPowerSyncDatabaseOpenFactory = AbstractPowerSyncDatabaseOpenFactory;
20681
23389
  exports.AbstractRemote = AbstractRemote;
20682
23390
  exports.AbstractStreamingSyncImplementation = AbstractStreamingSyncImplementation;
20683
- exports.BaseObserver = BaseObserver$1;
23391
+ exports.BaseObserver = BaseObserver;
20684
23392
  exports.Column = Column;
20685
23393
  exports.CrudBatch = CrudBatch;
20686
23394
  exports.CrudEntry = CrudEntry;
@@ -20699,6 +23407,7 @@ exports.DEFAULT_STREAM_CONNECTION_OPTIONS = DEFAULT_STREAM_CONNECTION_OPTIONS;
20699
23407
  exports.DEFAULT_TABLE_OPTIONS = DEFAULT_TABLE_OPTIONS;
20700
23408
  exports.DEFAULT_WATCH_THROTTLE_MS = DEFAULT_WATCH_THROTTLE_MS;
20701
23409
  exports.DataStream = DataStream;
23410
+ exports.FetchImplementationProvider = FetchImplementationProvider;
20702
23411
  exports.Index = Index;
20703
23412
  exports.IndexedColumn = IndexedColumn;
20704
23413
  exports.InvalidSQLCharacters = InvalidSQLCharacters;
@@ -20708,6 +23417,7 @@ exports.OplogEntry = OplogEntry;
20708
23417
  exports.PowerSyncDatabase = PowerSyncDatabase;
20709
23418
  exports.RNQSDBAdapter = RNQSDBAdapter;
20710
23419
  exports.RNQSPowerSyncDatabaseOpenFactory = RNQSPowerSyncDatabaseOpenFactory;
23420
+ exports.ReactNativeQuickSqliteOpenFactory = ReactNativeQuickSqliteOpenFactory;
20711
23421
  exports.ReactNativeRemote = ReactNativeRemote;
20712
23422
  exports.ReactNativeStreamingSyncImplementation = ReactNativeStreamingSyncImplementation;
20713
23423
  exports.STREAMING_POST_TIMEOUT_MS = STREAMING_POST_TIMEOUT_MS;
@@ -20723,6 +23433,9 @@ exports.column = column;
20723
23433
  exports.extractTableUpdates = extractTableUpdates;
20724
23434
  exports.isBatchedUpdateNotification = isBatchedUpdateNotification;
20725
23435
  exports.isContinueCheckpointRequest = isContinueCheckpointRequest;
23436
+ exports.isDBAdapter = isDBAdapter;
23437
+ exports.isSQLOpenFactory = isSQLOpenFactory;
23438
+ exports.isSQLOpenOptions = isSQLOpenOptions;
20726
23439
  exports.isStreamingKeepalive = isStreamingKeepalive;
20727
23440
  exports.isStreamingSyncCheckpoint = isStreamingSyncCheckpoint;
20728
23441
  exports.isStreamingSyncCheckpointComplete = isStreamingSyncCheckpointComplete;