@powersync/web 1.30.0 → 1.32.0

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.
Files changed (112) hide show
  1. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js +1867 -0
  2. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js.map +1 -0
  3. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530150.index.umd.js +555 -0
  4. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530150.index.umd.js.map +1 -0
  5. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530151.index.umd.js +555 -0
  6. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-2530151.index.umd.js.map +1 -0
  7. package/dist/index.umd.js +5022 -38504
  8. package/dist/index.umd.js.map +1 -1
  9. package/dist/worker/SharedSyncImplementation.umd.js +819 -2220
  10. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  11. package/dist/worker/WASQLiteDB.umd.js +524 -2121
  12. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  13. package/dist/worker/{node_modules_bson_lib_bson_mjs.umd.js → node_modules_pnpm_bson_6_10_4_node_modules_bson_lib_bson_mjs.umd.js} +8 -8
  14. package/dist/worker/node_modules_pnpm_bson_6_10_4_node_modules_bson_lib_bson_mjs.umd.js.map +1 -0
  15. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-3a94cf.umd.js +44 -0
  16. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-3a94cf.umd.js.map +1 -0
  17. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-868779.umd.js +44 -0
  18. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-868779.umd.js.map +1 -0
  19. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-f60d0d.umd.js +44 -0
  20. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-f60d0d.umd.js.map +1 -0
  21. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +44 -0
  22. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map +1 -0
  23. package/dist/worker/{node_modules_journeyapps_wa-sqlite_src_examples_IDBBatchAtomicVFS_js.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-0d2437.umd.js} +32 -32
  24. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-0d2437.umd.js.map +1 -0
  25. package/dist/worker/{node_modules_journeyapps_wa-sqlite_src_examples_OPFSCoopSyncVFS_js.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-1d4e74.umd.js} +24 -24
  26. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-1d4e74.umd.js.map +1 -0
  27. package/dist/worker/{node_modules_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js.umd.js → node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-3622cf.umd.js} +24 -24
  28. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-3622cf.umd.js.map +1 -0
  29. package/lib/package.json +27 -23
  30. package/lib/src/db/NavigatorTriggerClaimManager.d.ts +6 -0
  31. package/lib/src/db/NavigatorTriggerClaimManager.js +20 -0
  32. package/lib/src/db/PowerSyncDatabase.d.ts +5 -2
  33. package/lib/src/db/PowerSyncDatabase.js +49 -11
  34. package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.d.ts +1 -1
  35. package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.js +1 -1
  36. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.d.ts +2 -2
  37. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.js +2 -2
  38. package/lib/src/db/adapters/AsyncDatabaseConnection.d.ts +1 -1
  39. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.d.ts +21 -4
  40. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.js +116 -22
  41. package/lib/src/db/adapters/WebDBAdapter.d.ts +5 -2
  42. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.d.ts +7 -3
  43. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js +14 -7
  44. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.d.ts +12 -0
  45. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.js +19 -0
  46. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.d.ts +2 -2
  47. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js +11 -2
  48. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +4 -4
  49. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +6 -6
  50. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +5 -5
  51. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +7 -7
  52. package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.d.ts +1 -1
  53. package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.js +3 -3
  54. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.d.ts +6 -9
  55. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +54 -38
  56. package/lib/src/db/sync/WebRemote.js +1 -1
  57. package/lib/src/db/sync/WebStreamingSyncImplementation.d.ts +1 -1
  58. package/lib/src/db/sync/WebStreamingSyncImplementation.js +1 -1
  59. package/lib/src/index.d.ts +12 -12
  60. package/lib/src/index.js +12 -12
  61. package/lib/src/worker/db/SharedWASQLiteConnection.d.ts +2 -2
  62. package/lib/src/worker/db/WASQLiteDB.worker.js +3 -3
  63. package/lib/src/worker/db/WorkerWASQLiteConnection.d.ts +2 -2
  64. package/lib/src/worker/db/WorkerWASQLiteConnection.js +1 -1
  65. package/lib/src/worker/db/open-worker-database.d.ts +2 -2
  66. package/lib/src/worker/db/open-worker-database.js +1 -1
  67. package/lib/src/worker/sync/BroadcastLogger.d.ts +1 -1
  68. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +21 -11
  69. package/lib/src/worker/sync/SharedSyncImplementation.js +209 -113
  70. package/lib/src/worker/sync/SharedSyncImplementation.worker.js +3 -3
  71. package/lib/src/worker/sync/WorkerClient.d.ts +4 -5
  72. package/lib/src/worker/sync/WorkerClient.js +8 -10
  73. package/lib/tsconfig.tsbuildinfo +1 -1
  74. package/package.json +23 -19
  75. package/src/db/NavigatorTriggerClaimManager.ts +23 -0
  76. package/src/db/PowerSyncDatabase.ts +64 -22
  77. package/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.ts +1 -1
  78. package/src/db/adapters/AbstractWebSQLOpenFactory.ts +3 -3
  79. package/src/db/adapters/AsyncDatabaseConnection.ts +1 -1
  80. package/src/db/adapters/LockedAsyncDatabaseAdapter.ts +138 -33
  81. package/src/db/adapters/WebDBAdapter.ts +6 -2
  82. package/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts +20 -8
  83. package/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.ts +23 -0
  84. package/src/db/adapters/wa-sqlite/WASQLiteConnection.ts +13 -5
  85. package/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.ts +8 -8
  86. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +9 -9
  87. package/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.ts +3 -3
  88. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +69 -51
  89. package/src/db/sync/WebRemote.ts +1 -1
  90. package/src/db/sync/WebStreamingSyncImplementation.ts +2 -2
  91. package/src/index.ts +12 -12
  92. package/src/worker/db/SharedWASQLiteConnection.ts +2 -2
  93. package/src/worker/db/WASQLiteDB.worker.ts +5 -6
  94. package/src/worker/db/WorkerWASQLiteConnection.ts +2 -2
  95. package/src/worker/db/open-worker-database.ts +2 -2
  96. package/src/worker/sync/BroadcastLogger.ts +1 -1
  97. package/src/worker/sync/SharedSyncImplementation.ts +241 -126
  98. package/src/worker/sync/SharedSyncImplementation.worker.ts +3 -3
  99. package/src/worker/sync/WorkerClient.ts +10 -14
  100. package/dist/worker/node_modules_bson_lib_bson_mjs.umd.js.map +0 -1
  101. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite-async_mjs.umd.js +0 -44
  102. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite-async_mjs.umd.js.map +0 -1
  103. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite_mjs.umd.js +0 -44
  104. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite_mjs.umd.js.map +0 -1
  105. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite-async_mjs.umd.js +0 -44
  106. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite-async_mjs.umd.js.map +0 -1
  107. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +0 -44
  108. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map +0 -1
  109. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js.umd.js.map +0 -1
  110. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_IDBBatchAtomicVFS_js.umd.js.map +0 -1
  111. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_OPFSCoopSyncVFS_js.umd.js.map +0 -1
  112. /package/bin/{powersync.js → powersync.cjs} +0 -0
@@ -3,11 +3,11 @@ var sdk_web;
3
3
  /******/ "use strict";
4
4
  /******/ var __webpack_modules__ = ({
5
5
 
6
- /***/ "../../node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js":
7
- /*!*******************************************************************!*\
8
- !*** ../../node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js ***!
9
- \*******************************************************************/
10
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
6
+ /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js"
7
+ /*!*******************************************************************************************************************!*\
8
+ !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js ***!
9
+ \*******************************************************************************************************************/
10
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
11
11
 
12
12
  __webpack_require__.r(__webpack_exports__);
13
13
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -246,7 +246,7 @@ __webpack_require__.r(__webpack_exports__);
246
246
  /* harmony export */ SQLITE_WARNING: () => (/* reexport safe */ _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__.SQLITE_WARNING),
247
247
  /* harmony export */ SQLiteError: () => (/* binding */ SQLiteError)
248
248
  /* harmony export */ });
249
- /* harmony import */ var _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sqlite-constants.js */ "../../node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js");
249
+ /* harmony import */ var _sqlite_constants_js__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./sqlite-constants.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js");
250
250
  // Copyright 2021 Roy T. Hashimoto. All Rights Reserved.
251
251
 
252
252
 
@@ -1147,8 +1147,11 @@ function Factory(Module) {
1147
1147
  // Wait for all pending retry operations to complete. This is
1148
1148
  // normally empty on the first loop iteration.
1149
1149
  if (Module.retryOps.length) {
1150
- await Promise.all(Module.retryOps);
1151
- Module.retryOps = [];
1150
+ try {
1151
+ await Promise.all(Module.retryOps);
1152
+ } finally {
1153
+ Module.retryOps = [];
1154
+ }
1152
1155
  }
1153
1156
 
1154
1157
  rc = await f();
@@ -1193,13 +1196,13 @@ function decl(s) {
1193
1196
  }
1194
1197
 
1195
1198
 
1196
- /***/ }),
1199
+ /***/ },
1197
1200
 
1198
- /***/ "../../node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js":
1199
- /*!*************************************************************************!*\
1200
- !*** ../../node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js ***!
1201
- \*************************************************************************/
1202
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1201
+ /***/ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js"
1202
+ /*!*************************************************************************************************************************!*\
1203
+ !*** ../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-constants.js ***!
1204
+ \*************************************************************************************************************************/
1205
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
1203
1206
 
1204
1207
  __webpack_require__.r(__webpack_exports__);
1205
1208
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -1712,13 +1715,13 @@ const SQLITE_PREPARE_PERSISTENT = 0x01;
1712
1715
  const SQLITE_PREPARE_NORMALIZED = 0x02;
1713
1716
  const SQLITE_PREPARE_NO_VTAB = 0x04;
1714
1717
 
1715
- /***/ }),
1718
+ /***/ },
1716
1719
 
1717
- /***/ "../../node_modules/async-mutex/index.mjs":
1718
- /*!************************************************!*\
1719
- !*** ../../node_modules/async-mutex/index.mjs ***!
1720
- \************************************************/
1721
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
1720
+ /***/ "../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs"
1721
+ /*!*************************************************************************************!*\
1722
+ !*** ../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs ***!
1723
+ \*************************************************************************************/
1724
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
1722
1725
 
1723
1726
  __webpack_require__.r(__webpack_exports__);
1724
1727
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -2023,13 +2026,13 @@ function tryAcquire(sync, alreadyAcquiredError = E_ALREADY_LOCKED) {
2023
2026
 
2024
2027
 
2025
2028
 
2026
- /***/ }),
2029
+ /***/ },
2027
2030
 
2028
- /***/ "../../node_modules/comlink/dist/esm/comlink.mjs":
2029
- /*!*******************************************************!*\
2030
- !*** ../../node_modules/comlink/dist/esm/comlink.mjs ***!
2031
- \*******************************************************/
2032
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2031
+ /***/ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs"
2032
+ /*!****************************************************************************************!*\
2033
+ !*** ../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs ***!
2034
+ \****************************************************************************************/
2035
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2033
2036
 
2034
2037
  __webpack_require__.r(__webpack_exports__);
2035
2038
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -2404,13 +2407,13 @@ function generateUUID() {
2404
2407
  //# sourceMappingURL=comlink.mjs.map
2405
2408
 
2406
2409
 
2407
- /***/ }),
2410
+ /***/ },
2408
2411
 
2409
- /***/ "../common/dist/bundle.mjs":
2412
+ /***/ "../common/dist/bundle.mjs"
2410
2413
  /*!*********************************!*\
2411
2414
  !*** ../common/dist/bundle.mjs ***!
2412
2415
  \*********************************/
2413
- /***/ ((__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) => {
2416
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2414
2417
 
2415
2418
  __webpack_require__.r(__webpack_exports__);
2416
2419
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -2424,6 +2427,7 @@ __webpack_require__.r(__webpack_exports__);
2424
2427
  /* harmony export */ BaseObserver: () => (/* binding */ BaseObserver),
2425
2428
  /* harmony export */ Column: () => (/* binding */ Column),
2426
2429
  /* harmony export */ ColumnType: () => (/* binding */ ColumnType),
2430
+ /* harmony export */ ConnectionClosedError: () => (/* binding */ ConnectionClosedError),
2427
2431
  /* harmony export */ ConnectionManager: () => (/* binding */ ConnectionManager),
2428
2432
  /* harmony export */ ControlledExecutor: () => (/* binding */ ControlledExecutor),
2429
2433
  /* harmony export */ CrudBatch: () => (/* binding */ CrudBatch),
@@ -2462,12 +2466,14 @@ __webpack_require__.r(__webpack_exports__);
2462
2466
  /* harmony export */ LogLevel: () => (/* binding */ LogLevel),
2463
2467
  /* harmony export */ MAX_AMOUNT_OF_COLUMNS: () => (/* binding */ MAX_AMOUNT_OF_COLUMNS),
2464
2468
  /* harmony export */ MAX_OP_ID: () => (/* binding */ MAX_OP_ID),
2469
+ /* harmony export */ MEMORY_TRIGGER_CLAIM_MANAGER: () => (/* binding */ MEMORY_TRIGGER_CLAIM_MANAGER),
2465
2470
  /* harmony export */ OnChangeQueryProcessor: () => (/* binding */ OnChangeQueryProcessor),
2466
2471
  /* harmony export */ OpType: () => (/* binding */ OpType),
2467
2472
  /* harmony export */ OpTypeEnum: () => (/* binding */ OpTypeEnum),
2468
2473
  /* harmony export */ OplogEntry: () => (/* binding */ OplogEntry),
2469
2474
  /* harmony export */ PSInternalTable: () => (/* binding */ PSInternalTable),
2470
2475
  /* harmony export */ PowerSyncControlCommand: () => (/* binding */ PowerSyncControlCommand),
2476
+ /* harmony export */ RawTable: () => (/* binding */ RawTable),
2471
2477
  /* harmony export */ RowUpdateType: () => (/* binding */ RowUpdateType),
2472
2478
  /* harmony export */ Schema: () => (/* binding */ Schema),
2473
2479
  /* harmony export */ SqliteBucketStorage: () => (/* binding */ SqliteBucketStorage),
@@ -2479,6 +2485,7 @@ __webpack_require__.r(__webpack_exports__);
2479
2485
  /* harmony export */ SyncStreamConnectionMethod: () => (/* binding */ SyncStreamConnectionMethod),
2480
2486
  /* harmony export */ Table: () => (/* binding */ Table),
2481
2487
  /* harmony export */ TableV2: () => (/* binding */ TableV2),
2488
+ /* harmony export */ TriggerManagerImpl: () => (/* binding */ TriggerManagerImpl),
2482
2489
  /* harmony export */ UpdateType: () => (/* binding */ UpdateType),
2483
2490
  /* harmony export */ UploadQueueStats: () => (/* binding */ UploadQueueStats),
2484
2491
  /* harmony export */ WatchedQueryListenerEvent: () => (/* binding */ WatchedQueryListenerEvent),
@@ -2505,7 +2512,7 @@ __webpack_require__.r(__webpack_exports__);
2505
2512
  /* harmony export */ sanitizeSQL: () => (/* binding */ sanitizeSQL),
2506
2513
  /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID)
2507
2514
  /* harmony export */ });
2508
- /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! async-mutex */ "../../node_modules/async-mutex/index.mjs");
2515
+ /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! async-mutex */ "../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs");
2509
2516
 
2510
2517
 
2511
2518
  function getDefaultExportFromCjs (x) {
@@ -3228,12 +3235,30 @@ class SyncStatus {
3228
3235
  return {
3229
3236
  connected: this.connected,
3230
3237
  connecting: this.connecting,
3231
- dataFlow: this.dataFlowStatus,
3238
+ dataFlow: {
3239
+ ...this.dataFlowStatus,
3240
+ uploadError: this.serializeError(this.dataFlowStatus.uploadError),
3241
+ downloadError: this.serializeError(this.dataFlowStatus.downloadError)
3242
+ },
3232
3243
  lastSyncedAt: this.lastSyncedAt,
3233
3244
  hasSynced: this.hasSynced,
3234
3245
  priorityStatusEntries: this.priorityStatusEntries
3235
3246
  };
3236
3247
  }
3248
+ /**
3249
+ * Not all errors are serializable over a MessagePort. E.g. some `DomExceptions` fail to be passed across workers.
3250
+ * This explicitly serializes errors in the SyncStatus.
3251
+ */
3252
+ serializeError(error) {
3253
+ if (typeof error == 'undefined') {
3254
+ return undefined;
3255
+ }
3256
+ return {
3257
+ name: error.name,
3258
+ message: error.message,
3259
+ stack: error.stack
3260
+ };
3261
+ }
3237
3262
  static comparePriorities(a, b) {
3238
3263
  return b.priority - a.priority; // Reverse because higher priorities have lower numbers
3239
3264
  }
@@ -4577,7 +4602,7 @@ class SyncDataBucket {
4577
4602
  }
4578
4603
  }
4579
4604
 
4580
- var buffer$1 = {};
4605
+ var buffer = {};
4581
4606
 
4582
4607
  var base64Js = {};
4583
4608
 
@@ -4841,12 +4866,12 @@ function requireIeee754 () {
4841
4866
  * @license MIT
4842
4867
  */
4843
4868
 
4844
- var hasRequiredBuffer$1;
4869
+ var hasRequiredBuffer;
4845
4870
 
4846
- function requireBuffer$1 () {
4847
- if (hasRequiredBuffer$1) return buffer$1;
4848
- hasRequiredBuffer$1 = 1;
4849
- (function (exports) {
4871
+ function requireBuffer () {
4872
+ if (hasRequiredBuffer) return buffer;
4873
+ hasRequiredBuffer = 1;
4874
+ (function (exports$1) {
4850
4875
 
4851
4876
  const base64 = requireBase64Js();
4852
4877
  const ieee754 = requireIeee754();
@@ -4855,12 +4880,12 @@ function requireBuffer$1 () {
4855
4880
  ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
4856
4881
  : null;
4857
4882
 
4858
- exports.Buffer = Buffer;
4859
- exports.SlowBuffer = SlowBuffer;
4860
- exports.INSPECT_MAX_BYTES = 50;
4883
+ exports$1.Buffer = Buffer;
4884
+ exports$1.SlowBuffer = SlowBuffer;
4885
+ exports$1.INSPECT_MAX_BYTES = 50;
4861
4886
 
4862
4887
  const K_MAX_LENGTH = 0x7fffffff;
4863
- exports.kMaxLength = K_MAX_LENGTH;
4888
+ exports$1.kMaxLength = K_MAX_LENGTH;
4864
4889
 
4865
4890
  /**
4866
4891
  * If `Buffer.TYPED_ARRAY_SUPPORT`:
@@ -5456,7 +5481,7 @@ function requireBuffer$1 () {
5456
5481
 
5457
5482
  Buffer.prototype.inspect = function inspect () {
5458
5483
  let str = '';
5459
- const max = exports.INSPECT_MAX_BYTES;
5484
+ const max = exports$1.INSPECT_MAX_BYTES;
5460
5485
  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
5461
5486
  if (this.length > max) str += ' ... ';
5462
5487
  return '<Buffer ' + str + '>'
@@ -6700,1921 +6725,80 @@ function requireBuffer$1 () {
6700
6725
  let msg = `The value of "${str}" is out of range.`;
6701
6726
  let received = input;
6702
6727
  if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {
6703
- received = addNumericalSeparator(String(input));
6704
- } else if (typeof input === 'bigint') {
6705
- received = String(input);
6706
- if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
6707
- received = addNumericalSeparator(received);
6708
- }
6709
- received += 'n';
6710
- }
6711
- msg += ` It must be ${range}. Received ${received}`;
6712
- return msg
6713
- }, RangeError);
6714
-
6715
- function addNumericalSeparator (val) {
6716
- let res = '';
6717
- let i = val.length;
6718
- const start = val[0] === '-' ? 1 : 0;
6719
- for (; i >= start + 4; i -= 3) {
6720
- res = `_${val.slice(i - 3, i)}${res}`;
6721
- }
6722
- return `${val.slice(0, i)}${res}`
6723
- }
6724
-
6725
- // CHECK FUNCTIONS
6726
- // ===============
6727
-
6728
- function checkBounds (buf, offset, byteLength) {
6729
- validateNumber(offset, 'offset');
6730
- if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {
6731
- boundsError(offset, buf.length - (byteLength + 1));
6732
- }
6733
- }
6734
-
6735
- function checkIntBI (value, min, max, buf, offset, byteLength) {
6736
- if (value > max || value < min) {
6737
- const n = typeof min === 'bigint' ? 'n' : '';
6738
- let range;
6739
- {
6740
- if (min === 0 || min === BigInt(0)) {
6741
- range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`;
6742
- } else {
6743
- range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +
6744
- `${(byteLength + 1) * 8 - 1}${n}`;
6745
- }
6746
- }
6747
- throw new errors.ERR_OUT_OF_RANGE('value', range, value)
6748
- }
6749
- checkBounds(buf, offset, byteLength);
6750
- }
6751
-
6752
- function validateNumber (value, name) {
6753
- if (typeof value !== 'number') {
6754
- throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)
6755
- }
6756
- }
6757
-
6758
- function boundsError (value, length, type) {
6759
- if (Math.floor(value) !== value) {
6760
- validateNumber(value, type);
6761
- throw new errors.ERR_OUT_OF_RANGE('offset', 'an integer', value)
6762
- }
6763
-
6764
- if (length < 0) {
6765
- throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()
6766
- }
6767
-
6768
- throw new errors.ERR_OUT_OF_RANGE('offset',
6769
- `>= ${0} and <= ${length}`,
6770
- value)
6771
- }
6772
-
6773
- // HELPER FUNCTIONS
6774
- // ================
6775
-
6776
- const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
6777
-
6778
- function base64clean (str) {
6779
- // Node takes equal signs as end of the Base64 encoding
6780
- str = str.split('=')[0];
6781
- // Node strips out invalid characters like \n and \t from the string, base64-js does not
6782
- str = str.trim().replace(INVALID_BASE64_RE, '');
6783
- // Node converts strings with length < 2 to ''
6784
- if (str.length < 2) return ''
6785
- // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
6786
- while (str.length % 4 !== 0) {
6787
- str = str + '=';
6788
- }
6789
- return str
6790
- }
6791
-
6792
- function utf8ToBytes (string, units) {
6793
- units = units || Infinity;
6794
- let codePoint;
6795
- const length = string.length;
6796
- let leadSurrogate = null;
6797
- const bytes = [];
6798
-
6799
- for (let i = 0; i < length; ++i) {
6800
- codePoint = string.charCodeAt(i);
6801
-
6802
- // is surrogate component
6803
- if (codePoint > 0xD7FF && codePoint < 0xE000) {
6804
- // last char was a lead
6805
- if (!leadSurrogate) {
6806
- // no lead yet
6807
- if (codePoint > 0xDBFF) {
6808
- // unexpected trail
6809
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
6810
- continue
6811
- } else if (i + 1 === length) {
6812
- // unpaired lead
6813
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
6814
- continue
6815
- }
6816
-
6817
- // valid lead
6818
- leadSurrogate = codePoint;
6819
-
6820
- continue
6821
- }
6822
-
6823
- // 2 leads in a row
6824
- if (codePoint < 0xDC00) {
6825
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
6826
- leadSurrogate = codePoint;
6827
- continue
6828
- }
6829
-
6830
- // valid surrogate pair
6831
- codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000;
6832
- } else if (leadSurrogate) {
6833
- // valid bmp char, but last char was a lead
6834
- if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD);
6835
- }
6836
-
6837
- leadSurrogate = null;
6838
-
6839
- // encode utf8
6840
- if (codePoint < 0x80) {
6841
- if ((units -= 1) < 0) break
6842
- bytes.push(codePoint);
6843
- } else if (codePoint < 0x800) {
6844
- if ((units -= 2) < 0) break
6845
- bytes.push(
6846
- codePoint >> 0x6 | 0xC0,
6847
- codePoint & 0x3F | 0x80
6848
- );
6849
- } else if (codePoint < 0x10000) {
6850
- if ((units -= 3) < 0) break
6851
- bytes.push(
6852
- codePoint >> 0xC | 0xE0,
6853
- codePoint >> 0x6 & 0x3F | 0x80,
6854
- codePoint & 0x3F | 0x80
6855
- );
6856
- } else if (codePoint < 0x110000) {
6857
- if ((units -= 4) < 0) break
6858
- bytes.push(
6859
- codePoint >> 0x12 | 0xF0,
6860
- codePoint >> 0xC & 0x3F | 0x80,
6861
- codePoint >> 0x6 & 0x3F | 0x80,
6862
- codePoint & 0x3F | 0x80
6863
- );
6864
- } else {
6865
- throw new Error('Invalid code point')
6866
- }
6867
- }
6868
-
6869
- return bytes
6870
- }
6871
-
6872
- function asciiToBytes (str) {
6873
- const byteArray = [];
6874
- for (let i = 0; i < str.length; ++i) {
6875
- // Node's code seems to be doing this and not & 0x7F..
6876
- byteArray.push(str.charCodeAt(i) & 0xFF);
6877
- }
6878
- return byteArray
6879
- }
6880
-
6881
- function utf16leToBytes (str, units) {
6882
- let c, hi, lo;
6883
- const byteArray = [];
6884
- for (let i = 0; i < str.length; ++i) {
6885
- if ((units -= 2) < 0) break
6886
-
6887
- c = str.charCodeAt(i);
6888
- hi = c >> 8;
6889
- lo = c % 256;
6890
- byteArray.push(lo);
6891
- byteArray.push(hi);
6892
- }
6893
-
6894
- return byteArray
6895
- }
6896
-
6897
- function base64ToBytes (str) {
6898
- return base64.toByteArray(base64clean(str))
6899
- }
6900
-
6901
- function blitBuffer (src, dst, offset, length) {
6902
- let i;
6903
- for (i = 0; i < length; ++i) {
6904
- if ((i + offset >= dst.length) || (i >= src.length)) break
6905
- dst[i + offset] = src[i];
6906
- }
6907
- return i
6908
- }
6909
-
6910
- // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
6911
- // the `instanceof` check but they should be treated as of that type.
6912
- // See: https://github.com/feross/buffer/issues/166
6913
- function isInstance (obj, type) {
6914
- return obj instanceof type ||
6915
- (obj != null && obj.constructor != null && obj.constructor.name != null &&
6916
- obj.constructor.name === type.name)
6917
- }
6918
- function numberIsNaN (obj) {
6919
- // For IE11 support
6920
- return obj !== obj // eslint-disable-line no-self-compare
6921
- }
6922
-
6923
- // Create lookup table for `toString('hex')`
6924
- // See: https://github.com/feross/buffer/issues/219
6925
- const hexSliceLookupTable = (function () {
6926
- const alphabet = '0123456789abcdef';
6927
- const table = new Array(256);
6928
- for (let i = 0; i < 16; ++i) {
6929
- const i16 = i * 16;
6930
- for (let j = 0; j < 16; ++j) {
6931
- table[i16 + j] = alphabet[i] + alphabet[j];
6932
- }
6933
- }
6934
- return table
6935
- })();
6936
-
6937
- // Return not function with Error if BigInt not supported
6938
- function defineBigIntMethod (fn) {
6939
- return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn
6940
- }
6941
-
6942
- function BufferBigIntNotDefined () {
6943
- throw new Error('BigInt not supported')
6944
- }
6945
- } (buffer$1));
6946
- return buffer$1;
6947
- }
6948
-
6949
- var bufferExports$1 = requireBuffer$1();
6950
-
6951
- var dist = {};
6952
-
6953
- var buffer = {};
6954
-
6955
- /*!
6956
- * The buffer module from node.js, for the browser.
6957
- *
6958
- * @author Feross Aboukhadijeh <https://feross.org>
6959
- * @license MIT
6960
- */
6961
-
6962
- var hasRequiredBuffer;
6963
-
6964
- function requireBuffer () {
6965
- if (hasRequiredBuffer) return buffer;
6966
- hasRequiredBuffer = 1;
6967
- (function (exports) {
6968
-
6969
- var base64 = requireBase64Js();
6970
- var ieee754 = requireIeee754();
6971
- var customInspectSymbol =
6972
- (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation
6973
- ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation
6974
- : null;
6975
-
6976
- exports.Buffer = Buffer;
6977
- exports.SlowBuffer = SlowBuffer;
6978
- exports.INSPECT_MAX_BYTES = 50;
6979
-
6980
- var K_MAX_LENGTH = 0x7fffffff;
6981
- exports.kMaxLength = K_MAX_LENGTH;
6982
-
6983
- /**
6984
- * If `Buffer.TYPED_ARRAY_SUPPORT`:
6985
- * === true Use Uint8Array implementation (fastest)
6986
- * === false Print warning and recommend using `buffer` v4.x which has an Object
6987
- * implementation (most compatible, even IE6)
6988
- *
6989
- * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
6990
- * Opera 11.6+, iOS 4.2+.
6991
- *
6992
- * We report that the browser does not support typed arrays if the are not subclassable
6993
- * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
6994
- * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
6995
- * for __proto__ and has a buggy typed array implementation.
6996
- */
6997
- Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport();
6998
-
6999
- if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
7000
- typeof console.error === 'function') {
7001
- console.error(
7002
- 'This browser lacks typed array (Uint8Array) support which is required by ' +
7003
- '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
7004
- );
7005
- }
7006
-
7007
- function typedArraySupport () {
7008
- // Can typed array instances can be augmented?
7009
- try {
7010
- var arr = new Uint8Array(1);
7011
- var proto = { foo: function () { return 42 } };
7012
- Object.setPrototypeOf(proto, Uint8Array.prototype);
7013
- Object.setPrototypeOf(arr, proto);
7014
- return arr.foo() === 42
7015
- } catch (e) {
7016
- return false
7017
- }
7018
- }
7019
-
7020
- Object.defineProperty(Buffer.prototype, 'parent', {
7021
- enumerable: true,
7022
- get: function () {
7023
- if (!Buffer.isBuffer(this)) return undefined
7024
- return this.buffer
7025
- }
7026
- });
7027
-
7028
- Object.defineProperty(Buffer.prototype, 'offset', {
7029
- enumerable: true,
7030
- get: function () {
7031
- if (!Buffer.isBuffer(this)) return undefined
7032
- return this.byteOffset
7033
- }
7034
- });
7035
-
7036
- function createBuffer (length) {
7037
- if (length > K_MAX_LENGTH) {
7038
- throw new RangeError('The value "' + length + '" is invalid for option "size"')
7039
- }
7040
- // Return an augmented `Uint8Array` instance
7041
- var buf = new Uint8Array(length);
7042
- Object.setPrototypeOf(buf, Buffer.prototype);
7043
- return buf
7044
- }
7045
-
7046
- /**
7047
- * The Buffer constructor returns instances of `Uint8Array` that have their
7048
- * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
7049
- * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
7050
- * and the `Uint8Array` methods. Square bracket notation works as expected -- it
7051
- * returns a single octet.
7052
- *
7053
- * The `Uint8Array` prototype remains unmodified.
7054
- */
7055
-
7056
- function Buffer (arg, encodingOrOffset, length) {
7057
- // Common case.
7058
- if (typeof arg === 'number') {
7059
- if (typeof encodingOrOffset === 'string') {
7060
- throw new TypeError(
7061
- 'The "string" argument must be of type string. Received type number'
7062
- )
7063
- }
7064
- return allocUnsafe(arg)
7065
- }
7066
- return from(arg, encodingOrOffset, length)
7067
- }
7068
-
7069
- Buffer.poolSize = 8192; // not used by this implementation
7070
-
7071
- function from (value, encodingOrOffset, length) {
7072
- if (typeof value === 'string') {
7073
- return fromString(value, encodingOrOffset)
7074
- }
7075
-
7076
- if (ArrayBuffer.isView(value)) {
7077
- return fromArrayView(value)
7078
- }
7079
-
7080
- if (value == null) {
7081
- throw new TypeError(
7082
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
7083
- 'or Array-like Object. Received type ' + (typeof value)
7084
- )
7085
- }
7086
-
7087
- if (isInstance(value, ArrayBuffer) ||
7088
- (value && isInstance(value.buffer, ArrayBuffer))) {
7089
- return fromArrayBuffer(value, encodingOrOffset, length)
7090
- }
7091
-
7092
- if (typeof SharedArrayBuffer !== 'undefined' &&
7093
- (isInstance(value, SharedArrayBuffer) ||
7094
- (value && isInstance(value.buffer, SharedArrayBuffer)))) {
7095
- return fromArrayBuffer(value, encodingOrOffset, length)
7096
- }
7097
-
7098
- if (typeof value === 'number') {
7099
- throw new TypeError(
7100
- 'The "value" argument must not be of type number. Received type number'
7101
- )
7102
- }
7103
-
7104
- var valueOf = value.valueOf && value.valueOf();
7105
- if (valueOf != null && valueOf !== value) {
7106
- return Buffer.from(valueOf, encodingOrOffset, length)
7107
- }
7108
-
7109
- var b = fromObject(value);
7110
- if (b) return b
7111
-
7112
- if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
7113
- typeof value[Symbol.toPrimitive] === 'function') {
7114
- return Buffer.from(
7115
- value[Symbol.toPrimitive]('string'), encodingOrOffset, length
7116
- )
7117
- }
7118
-
7119
- throw new TypeError(
7120
- 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
7121
- 'or Array-like Object. Received type ' + (typeof value)
7122
- )
7123
- }
7124
-
7125
- /**
7126
- * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
7127
- * if value is a number.
7128
- * Buffer.from(str[, encoding])
7129
- * Buffer.from(array)
7130
- * Buffer.from(buffer)
7131
- * Buffer.from(arrayBuffer[, byteOffset[, length]])
7132
- **/
7133
- Buffer.from = function (value, encodingOrOffset, length) {
7134
- return from(value, encodingOrOffset, length)
7135
- };
7136
-
7137
- // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
7138
- // https://github.com/feross/buffer/pull/148
7139
- Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype);
7140
- Object.setPrototypeOf(Buffer, Uint8Array);
7141
-
7142
- function assertSize (size) {
7143
- if (typeof size !== 'number') {
7144
- throw new TypeError('"size" argument must be of type number')
7145
- } else if (size < 0) {
7146
- throw new RangeError('The value "' + size + '" is invalid for option "size"')
7147
- }
7148
- }
7149
-
7150
- function alloc (size, fill, encoding) {
7151
- assertSize(size);
7152
- if (size <= 0) {
7153
- return createBuffer(size)
7154
- }
7155
- if (fill !== undefined) {
7156
- // Only pay attention to encoding if it's a string. This
7157
- // prevents accidentally sending in a number that would
7158
- // be interpreted as a start offset.
7159
- return typeof encoding === 'string'
7160
- ? createBuffer(size).fill(fill, encoding)
7161
- : createBuffer(size).fill(fill)
7162
- }
7163
- return createBuffer(size)
7164
- }
7165
-
7166
- /**
7167
- * Creates a new filled Buffer instance.
7168
- * alloc(size[, fill[, encoding]])
7169
- **/
7170
- Buffer.alloc = function (size, fill, encoding) {
7171
- return alloc(size, fill, encoding)
7172
- };
7173
-
7174
- function allocUnsafe (size) {
7175
- assertSize(size);
7176
- return createBuffer(size < 0 ? 0 : checked(size) | 0)
7177
- }
7178
-
7179
- /**
7180
- * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
7181
- * */
7182
- Buffer.allocUnsafe = function (size) {
7183
- return allocUnsafe(size)
7184
- };
7185
- /**
7186
- * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
7187
- */
7188
- Buffer.allocUnsafeSlow = function (size) {
7189
- return allocUnsafe(size)
7190
- };
7191
-
7192
- function fromString (string, encoding) {
7193
- if (typeof encoding !== 'string' || encoding === '') {
7194
- encoding = 'utf8';
7195
- }
7196
-
7197
- if (!Buffer.isEncoding(encoding)) {
7198
- throw new TypeError('Unknown encoding: ' + encoding)
7199
- }
7200
-
7201
- var length = byteLength(string, encoding) | 0;
7202
- var buf = createBuffer(length);
7203
-
7204
- var actual = buf.write(string, encoding);
7205
-
7206
- if (actual !== length) {
7207
- // Writing a hex string, for example, that contains invalid characters will
7208
- // cause everything after the first invalid character to be ignored. (e.g.
7209
- // 'abxxcd' will be treated as 'ab')
7210
- buf = buf.slice(0, actual);
7211
- }
7212
-
7213
- return buf
7214
- }
7215
-
7216
- function fromArrayLike (array) {
7217
- var length = array.length < 0 ? 0 : checked(array.length) | 0;
7218
- var buf = createBuffer(length);
7219
- for (var i = 0; i < length; i += 1) {
7220
- buf[i] = array[i] & 255;
7221
- }
7222
- return buf
7223
- }
7224
-
7225
- function fromArrayView (arrayView) {
7226
- if (isInstance(arrayView, Uint8Array)) {
7227
- var copy = new Uint8Array(arrayView);
7228
- return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)
7229
- }
7230
- return fromArrayLike(arrayView)
7231
- }
7232
-
7233
- function fromArrayBuffer (array, byteOffset, length) {
7234
- if (byteOffset < 0 || array.byteLength < byteOffset) {
7235
- throw new RangeError('"offset" is outside of buffer bounds')
7236
- }
7237
-
7238
- if (array.byteLength < byteOffset + (length || 0)) {
7239
- throw new RangeError('"length" is outside of buffer bounds')
7240
- }
7241
-
7242
- var buf;
7243
- if (byteOffset === undefined && length === undefined) {
7244
- buf = new Uint8Array(array);
7245
- } else if (length === undefined) {
7246
- buf = new Uint8Array(array, byteOffset);
7247
- } else {
7248
- buf = new Uint8Array(array, byteOffset, length);
7249
- }
7250
-
7251
- // Return an augmented `Uint8Array` instance
7252
- Object.setPrototypeOf(buf, Buffer.prototype);
7253
-
7254
- return buf
7255
- }
7256
-
7257
- function fromObject (obj) {
7258
- if (Buffer.isBuffer(obj)) {
7259
- var len = checked(obj.length) | 0;
7260
- var buf = createBuffer(len);
7261
-
7262
- if (buf.length === 0) {
7263
- return buf
7264
- }
7265
-
7266
- obj.copy(buf, 0, 0, len);
7267
- return buf
7268
- }
7269
-
7270
- if (obj.length !== undefined) {
7271
- if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
7272
- return createBuffer(0)
7273
- }
7274
- return fromArrayLike(obj)
7275
- }
7276
-
7277
- if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
7278
- return fromArrayLike(obj.data)
7279
- }
7280
- }
7281
-
7282
- function checked (length) {
7283
- // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
7284
- // length is NaN (which is otherwise coerced to zero.)
7285
- if (length >= K_MAX_LENGTH) {
7286
- throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
7287
- 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
7288
- }
7289
- return length | 0
7290
- }
7291
-
7292
- function SlowBuffer (length) {
7293
- if (+length != length) { // eslint-disable-line eqeqeq
7294
- length = 0;
7295
- }
7296
- return Buffer.alloc(+length)
7297
- }
7298
-
7299
- Buffer.isBuffer = function isBuffer (b) {
7300
- return b != null && b._isBuffer === true &&
7301
- b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
7302
- };
7303
-
7304
- Buffer.compare = function compare (a, b) {
7305
- if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength);
7306
- if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength);
7307
- if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
7308
- throw new TypeError(
7309
- 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
7310
- )
7311
- }
7312
-
7313
- if (a === b) return 0
7314
-
7315
- var x = a.length;
7316
- var y = b.length;
7317
-
7318
- for (var i = 0, len = Math.min(x, y); i < len; ++i) {
7319
- if (a[i] !== b[i]) {
7320
- x = a[i];
7321
- y = b[i];
7322
- break
7323
- }
7324
- }
7325
-
7326
- if (x < y) return -1
7327
- if (y < x) return 1
7328
- return 0
7329
- };
7330
-
7331
- Buffer.isEncoding = function isEncoding (encoding) {
7332
- switch (String(encoding).toLowerCase()) {
7333
- case 'hex':
7334
- case 'utf8':
7335
- case 'utf-8':
7336
- case 'ascii':
7337
- case 'latin1':
7338
- case 'binary':
7339
- case 'base64':
7340
- case 'ucs2':
7341
- case 'ucs-2':
7342
- case 'utf16le':
7343
- case 'utf-16le':
7344
- return true
7345
- default:
7346
- return false
7347
- }
7348
- };
7349
-
7350
- Buffer.concat = function concat (list, length) {
7351
- if (!Array.isArray(list)) {
7352
- throw new TypeError('"list" argument must be an Array of Buffers')
7353
- }
7354
-
7355
- if (list.length === 0) {
7356
- return Buffer.alloc(0)
7357
- }
7358
-
7359
- var i;
7360
- if (length === undefined) {
7361
- length = 0;
7362
- for (i = 0; i < list.length; ++i) {
7363
- length += list[i].length;
7364
- }
7365
- }
7366
-
7367
- var buffer = Buffer.allocUnsafe(length);
7368
- var pos = 0;
7369
- for (i = 0; i < list.length; ++i) {
7370
- var buf = list[i];
7371
- if (isInstance(buf, Uint8Array)) {
7372
- if (pos + buf.length > buffer.length) {
7373
- Buffer.from(buf).copy(buffer, pos);
7374
- } else {
7375
- Uint8Array.prototype.set.call(
7376
- buffer,
7377
- buf,
7378
- pos
7379
- );
7380
- }
7381
- } else if (!Buffer.isBuffer(buf)) {
7382
- throw new TypeError('"list" argument must be an Array of Buffers')
7383
- } else {
7384
- buf.copy(buffer, pos);
7385
- }
7386
- pos += buf.length;
7387
- }
7388
- return buffer
7389
- };
7390
-
7391
- function byteLength (string, encoding) {
7392
- if (Buffer.isBuffer(string)) {
7393
- return string.length
7394
- }
7395
- if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
7396
- return string.byteLength
7397
- }
7398
- if (typeof string !== 'string') {
7399
- throw new TypeError(
7400
- 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
7401
- 'Received type ' + typeof string
7402
- )
7403
- }
7404
-
7405
- var len = string.length;
7406
- var mustMatch = (arguments.length > 2 && arguments[2] === true);
7407
- if (!mustMatch && len === 0) return 0
7408
-
7409
- // Use a for loop to avoid recursion
7410
- var loweredCase = false;
7411
- for (;;) {
7412
- switch (encoding) {
7413
- case 'ascii':
7414
- case 'latin1':
7415
- case 'binary':
7416
- return len
7417
- case 'utf8':
7418
- case 'utf-8':
7419
- return utf8ToBytes(string).length
7420
- case 'ucs2':
7421
- case 'ucs-2':
7422
- case 'utf16le':
7423
- case 'utf-16le':
7424
- return len * 2
7425
- case 'hex':
7426
- return len >>> 1
7427
- case 'base64':
7428
- return base64ToBytes(string).length
7429
- default:
7430
- if (loweredCase) {
7431
- return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
7432
- }
7433
- encoding = ('' + encoding).toLowerCase();
7434
- loweredCase = true;
7435
- }
7436
- }
7437
- }
7438
- Buffer.byteLength = byteLength;
7439
-
7440
- function slowToString (encoding, start, end) {
7441
- var loweredCase = false;
7442
-
7443
- // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
7444
- // property of a typed array.
7445
-
7446
- // This behaves neither like String nor Uint8Array in that we set start/end
7447
- // to their upper/lower bounds if the value passed is out of range.
7448
- // undefined is handled specially as per ECMA-262 6th Edition,
7449
- // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
7450
- if (start === undefined || start < 0) {
7451
- start = 0;
7452
- }
7453
- // Return early if start > this.length. Done here to prevent potential uint32
7454
- // coercion fail below.
7455
- if (start > this.length) {
7456
- return ''
7457
- }
7458
-
7459
- if (end === undefined || end > this.length) {
7460
- end = this.length;
7461
- }
7462
-
7463
- if (end <= 0) {
7464
- return ''
7465
- }
7466
-
7467
- // Force coercion to uint32. This will also coerce falsey/NaN values to 0.
7468
- end >>>= 0;
7469
- start >>>= 0;
7470
-
7471
- if (end <= start) {
7472
- return ''
7473
- }
7474
-
7475
- if (!encoding) encoding = 'utf8';
7476
-
7477
- while (true) {
7478
- switch (encoding) {
7479
- case 'hex':
7480
- return hexSlice(this, start, end)
7481
-
7482
- case 'utf8':
7483
- case 'utf-8':
7484
- return utf8Slice(this, start, end)
7485
-
7486
- case 'ascii':
7487
- return asciiSlice(this, start, end)
7488
-
7489
- case 'latin1':
7490
- case 'binary':
7491
- return latin1Slice(this, start, end)
7492
-
7493
- case 'base64':
7494
- return base64Slice(this, start, end)
7495
-
7496
- case 'ucs2':
7497
- case 'ucs-2':
7498
- case 'utf16le':
7499
- case 'utf-16le':
7500
- return utf16leSlice(this, start, end)
7501
-
7502
- default:
7503
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7504
- encoding = (encoding + '').toLowerCase();
7505
- loweredCase = true;
7506
- }
7507
- }
7508
- }
7509
-
7510
- // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
7511
- // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
7512
- // reliably in a browserify context because there could be multiple different
7513
- // copies of the 'buffer' package in use. This method works even for Buffer
7514
- // instances that were created from another copy of the `buffer` package.
7515
- // See: https://github.com/feross/buffer/issues/154
7516
- Buffer.prototype._isBuffer = true;
7517
-
7518
- function swap (b, n, m) {
7519
- var i = b[n];
7520
- b[n] = b[m];
7521
- b[m] = i;
7522
- }
7523
-
7524
- Buffer.prototype.swap16 = function swap16 () {
7525
- var len = this.length;
7526
- if (len % 2 !== 0) {
7527
- throw new RangeError('Buffer size must be a multiple of 16-bits')
7528
- }
7529
- for (var i = 0; i < len; i += 2) {
7530
- swap(this, i, i + 1);
7531
- }
7532
- return this
7533
- };
7534
-
7535
- Buffer.prototype.swap32 = function swap32 () {
7536
- var len = this.length;
7537
- if (len % 4 !== 0) {
7538
- throw new RangeError('Buffer size must be a multiple of 32-bits')
7539
- }
7540
- for (var i = 0; i < len; i += 4) {
7541
- swap(this, i, i + 3);
7542
- swap(this, i + 1, i + 2);
7543
- }
7544
- return this
7545
- };
7546
-
7547
- Buffer.prototype.swap64 = function swap64 () {
7548
- var len = this.length;
7549
- if (len % 8 !== 0) {
7550
- throw new RangeError('Buffer size must be a multiple of 64-bits')
7551
- }
7552
- for (var i = 0; i < len; i += 8) {
7553
- swap(this, i, i + 7);
7554
- swap(this, i + 1, i + 6);
7555
- swap(this, i + 2, i + 5);
7556
- swap(this, i + 3, i + 4);
7557
- }
7558
- return this
7559
- };
7560
-
7561
- Buffer.prototype.toString = function toString () {
7562
- var length = this.length;
7563
- if (length === 0) return ''
7564
- if (arguments.length === 0) return utf8Slice(this, 0, length)
7565
- return slowToString.apply(this, arguments)
7566
- };
7567
-
7568
- Buffer.prototype.toLocaleString = Buffer.prototype.toString;
7569
-
7570
- Buffer.prototype.equals = function equals (b) {
7571
- if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
7572
- if (this === b) return true
7573
- return Buffer.compare(this, b) === 0
7574
- };
7575
-
7576
- Buffer.prototype.inspect = function inspect () {
7577
- var str = '';
7578
- var max = exports.INSPECT_MAX_BYTES;
7579
- str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim();
7580
- if (this.length > max) str += ' ... ';
7581
- return '<Buffer ' + str + '>'
7582
- };
7583
- if (customInspectSymbol) {
7584
- Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect;
7585
- }
7586
-
7587
- Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
7588
- if (isInstance(target, Uint8Array)) {
7589
- target = Buffer.from(target, target.offset, target.byteLength);
7590
- }
7591
- if (!Buffer.isBuffer(target)) {
7592
- throw new TypeError(
7593
- 'The "target" argument must be one of type Buffer or Uint8Array. ' +
7594
- 'Received type ' + (typeof target)
7595
- )
7596
- }
7597
-
7598
- if (start === undefined) {
7599
- start = 0;
7600
- }
7601
- if (end === undefined) {
7602
- end = target ? target.length : 0;
7603
- }
7604
- if (thisStart === undefined) {
7605
- thisStart = 0;
7606
- }
7607
- if (thisEnd === undefined) {
7608
- thisEnd = this.length;
7609
- }
7610
-
7611
- if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
7612
- throw new RangeError('out of range index')
7613
- }
7614
-
7615
- if (thisStart >= thisEnd && start >= end) {
7616
- return 0
7617
- }
7618
- if (thisStart >= thisEnd) {
7619
- return -1
7620
- }
7621
- if (start >= end) {
7622
- return 1
7623
- }
7624
-
7625
- start >>>= 0;
7626
- end >>>= 0;
7627
- thisStart >>>= 0;
7628
- thisEnd >>>= 0;
7629
-
7630
- if (this === target) return 0
7631
-
7632
- var x = thisEnd - thisStart;
7633
- var y = end - start;
7634
- var len = Math.min(x, y);
7635
-
7636
- var thisCopy = this.slice(thisStart, thisEnd);
7637
- var targetCopy = target.slice(start, end);
7638
-
7639
- for (var i = 0; i < len; ++i) {
7640
- if (thisCopy[i] !== targetCopy[i]) {
7641
- x = thisCopy[i];
7642
- y = targetCopy[i];
7643
- break
7644
- }
7645
- }
7646
-
7647
- if (x < y) return -1
7648
- if (y < x) return 1
7649
- return 0
7650
- };
7651
-
7652
- // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
7653
- // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
7654
- //
7655
- // Arguments:
7656
- // - buffer - a Buffer to search
7657
- // - val - a string, Buffer, or number
7658
- // - byteOffset - an index into `buffer`; will be clamped to an int32
7659
- // - encoding - an optional encoding, relevant is val is a string
7660
- // - dir - true for indexOf, false for lastIndexOf
7661
- function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
7662
- // Empty buffer means no match
7663
- if (buffer.length === 0) return -1
7664
-
7665
- // Normalize byteOffset
7666
- if (typeof byteOffset === 'string') {
7667
- encoding = byteOffset;
7668
- byteOffset = 0;
7669
- } else if (byteOffset > 0x7fffffff) {
7670
- byteOffset = 0x7fffffff;
7671
- } else if (byteOffset < -2147483648) {
7672
- byteOffset = -2147483648;
7673
- }
7674
- byteOffset = +byteOffset; // Coerce to Number.
7675
- if (numberIsNaN(byteOffset)) {
7676
- // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
7677
- byteOffset = dir ? 0 : (buffer.length - 1);
7678
- }
7679
-
7680
- // Normalize byteOffset: negative offsets start from the end of the buffer
7681
- if (byteOffset < 0) byteOffset = buffer.length + byteOffset;
7682
- if (byteOffset >= buffer.length) {
7683
- if (dir) return -1
7684
- else byteOffset = buffer.length - 1;
7685
- } else if (byteOffset < 0) {
7686
- if (dir) byteOffset = 0;
7687
- else return -1
7688
- }
7689
-
7690
- // Normalize val
7691
- if (typeof val === 'string') {
7692
- val = Buffer.from(val, encoding);
7693
- }
7694
-
7695
- // Finally, search either indexOf (if dir is true) or lastIndexOf
7696
- if (Buffer.isBuffer(val)) {
7697
- // Special case: looking for empty string/buffer always fails
7698
- if (val.length === 0) {
7699
- return -1
7700
- }
7701
- return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
7702
- } else if (typeof val === 'number') {
7703
- val = val & 0xFF; // Search for a byte value [0-255]
7704
- if (typeof Uint8Array.prototype.indexOf === 'function') {
7705
- if (dir) {
7706
- return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
7707
- } else {
7708
- return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
7709
- }
7710
- }
7711
- return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)
7712
- }
7713
-
7714
- throw new TypeError('val must be string, number or Buffer')
7715
- }
7716
-
7717
- function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
7718
- var indexSize = 1;
7719
- var arrLength = arr.length;
7720
- var valLength = val.length;
7721
-
7722
- if (encoding !== undefined) {
7723
- encoding = String(encoding).toLowerCase();
7724
- if (encoding === 'ucs2' || encoding === 'ucs-2' ||
7725
- encoding === 'utf16le' || encoding === 'utf-16le') {
7726
- if (arr.length < 2 || val.length < 2) {
7727
- return -1
7728
- }
7729
- indexSize = 2;
7730
- arrLength /= 2;
7731
- valLength /= 2;
7732
- byteOffset /= 2;
7733
- }
7734
- }
7735
-
7736
- function read (buf, i) {
7737
- if (indexSize === 1) {
7738
- return buf[i]
7739
- } else {
7740
- return buf.readUInt16BE(i * indexSize)
7741
- }
7742
- }
7743
-
7744
- var i;
7745
- if (dir) {
7746
- var foundIndex = -1;
7747
- for (i = byteOffset; i < arrLength; i++) {
7748
- if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
7749
- if (foundIndex === -1) foundIndex = i;
7750
- if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
7751
- } else {
7752
- if (foundIndex !== -1) i -= i - foundIndex;
7753
- foundIndex = -1;
7754
- }
7755
- }
7756
- } else {
7757
- if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength;
7758
- for (i = byteOffset; i >= 0; i--) {
7759
- var found = true;
7760
- for (var j = 0; j < valLength; j++) {
7761
- if (read(arr, i + j) !== read(val, j)) {
7762
- found = false;
7763
- break
7764
- }
7765
- }
7766
- if (found) return i
7767
- }
7768
- }
7769
-
7770
- return -1
7771
- }
7772
-
7773
- Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
7774
- return this.indexOf(val, byteOffset, encoding) !== -1
7775
- };
7776
-
7777
- Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
7778
- return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
7779
- };
7780
-
7781
- Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
7782
- return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
7783
- };
7784
-
7785
- function hexWrite (buf, string, offset, length) {
7786
- offset = Number(offset) || 0;
7787
- var remaining = buf.length - offset;
7788
- if (!length) {
7789
- length = remaining;
7790
- } else {
7791
- length = Number(length);
7792
- if (length > remaining) {
7793
- length = remaining;
7794
- }
7795
- }
7796
-
7797
- var strLen = string.length;
7798
-
7799
- if (length > strLen / 2) {
7800
- length = strLen / 2;
7801
- }
7802
- for (var i = 0; i < length; ++i) {
7803
- var parsed = parseInt(string.substr(i * 2, 2), 16);
7804
- if (numberIsNaN(parsed)) return i
7805
- buf[offset + i] = parsed;
7806
- }
7807
- return i
7808
- }
7809
-
7810
- function utf8Write (buf, string, offset, length) {
7811
- return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
7812
- }
7813
-
7814
- function asciiWrite (buf, string, offset, length) {
7815
- return blitBuffer(asciiToBytes(string), buf, offset, length)
7816
- }
7817
-
7818
- function base64Write (buf, string, offset, length) {
7819
- return blitBuffer(base64ToBytes(string), buf, offset, length)
7820
- }
7821
-
7822
- function ucs2Write (buf, string, offset, length) {
7823
- return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
7824
- }
7825
-
7826
- Buffer.prototype.write = function write (string, offset, length, encoding) {
7827
- // Buffer#write(string)
7828
- if (offset === undefined) {
7829
- encoding = 'utf8';
7830
- length = this.length;
7831
- offset = 0;
7832
- // Buffer#write(string, encoding)
7833
- } else if (length === undefined && typeof offset === 'string') {
7834
- encoding = offset;
7835
- length = this.length;
7836
- offset = 0;
7837
- // Buffer#write(string, offset[, length][, encoding])
7838
- } else if (isFinite(offset)) {
7839
- offset = offset >>> 0;
7840
- if (isFinite(length)) {
7841
- length = length >>> 0;
7842
- if (encoding === undefined) encoding = 'utf8';
7843
- } else {
7844
- encoding = length;
7845
- length = undefined;
7846
- }
7847
- } else {
7848
- throw new Error(
7849
- 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
7850
- )
7851
- }
7852
-
7853
- var remaining = this.length - offset;
7854
- if (length === undefined || length > remaining) length = remaining;
7855
-
7856
- if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
7857
- throw new RangeError('Attempt to write outside buffer bounds')
7858
- }
7859
-
7860
- if (!encoding) encoding = 'utf8';
7861
-
7862
- var loweredCase = false;
7863
- for (;;) {
7864
- switch (encoding) {
7865
- case 'hex':
7866
- return hexWrite(this, string, offset, length)
7867
-
7868
- case 'utf8':
7869
- case 'utf-8':
7870
- return utf8Write(this, string, offset, length)
7871
-
7872
- case 'ascii':
7873
- case 'latin1':
7874
- case 'binary':
7875
- return asciiWrite(this, string, offset, length)
7876
-
7877
- case 'base64':
7878
- // Warning: maxLength not taken into account in base64Write
7879
- return base64Write(this, string, offset, length)
7880
-
7881
- case 'ucs2':
7882
- case 'ucs-2':
7883
- case 'utf16le':
7884
- case 'utf-16le':
7885
- return ucs2Write(this, string, offset, length)
7886
-
7887
- default:
7888
- if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
7889
- encoding = ('' + encoding).toLowerCase();
7890
- loweredCase = true;
7891
- }
7892
- }
7893
- };
7894
-
7895
- Buffer.prototype.toJSON = function toJSON () {
7896
- return {
7897
- type: 'Buffer',
7898
- data: Array.prototype.slice.call(this._arr || this, 0)
7899
- }
7900
- };
7901
-
7902
- function base64Slice (buf, start, end) {
7903
- if (start === 0 && end === buf.length) {
7904
- return base64.fromByteArray(buf)
7905
- } else {
7906
- return base64.fromByteArray(buf.slice(start, end))
7907
- }
7908
- }
7909
-
7910
- function utf8Slice (buf, start, end) {
7911
- end = Math.min(buf.length, end);
7912
- var res = [];
7913
-
7914
- var i = start;
7915
- while (i < end) {
7916
- var firstByte = buf[i];
7917
- var codePoint = null;
7918
- var bytesPerSequence = (firstByte > 0xEF)
7919
- ? 4
7920
- : (firstByte > 0xDF)
7921
- ? 3
7922
- : (firstByte > 0xBF)
7923
- ? 2
7924
- : 1;
7925
-
7926
- if (i + bytesPerSequence <= end) {
7927
- var secondByte, thirdByte, fourthByte, tempCodePoint;
7928
-
7929
- switch (bytesPerSequence) {
7930
- case 1:
7931
- if (firstByte < 0x80) {
7932
- codePoint = firstByte;
7933
- }
7934
- break
7935
- case 2:
7936
- secondByte = buf[i + 1];
7937
- if ((secondByte & 0xC0) === 0x80) {
7938
- tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F);
7939
- if (tempCodePoint > 0x7F) {
7940
- codePoint = tempCodePoint;
7941
- }
7942
- }
7943
- break
7944
- case 3:
7945
- secondByte = buf[i + 1];
7946
- thirdByte = buf[i + 2];
7947
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
7948
- tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F);
7949
- if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
7950
- codePoint = tempCodePoint;
7951
- }
7952
- }
7953
- break
7954
- case 4:
7955
- secondByte = buf[i + 1];
7956
- thirdByte = buf[i + 2];
7957
- fourthByte = buf[i + 3];
7958
- if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
7959
- tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F);
7960
- if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
7961
- codePoint = tempCodePoint;
7962
- }
7963
- }
7964
- }
7965
- }
7966
-
7967
- if (codePoint === null) {
7968
- // we did not generate a valid codePoint so insert a
7969
- // replacement char (U+FFFD) and advance only 1 byte
7970
- codePoint = 0xFFFD;
7971
- bytesPerSequence = 1;
7972
- } else if (codePoint > 0xFFFF) {
7973
- // encode to utf16 (surrogate pair dance)
7974
- codePoint -= 0x10000;
7975
- res.push(codePoint >>> 10 & 0x3FF | 0xD800);
7976
- codePoint = 0xDC00 | codePoint & 0x3FF;
7977
- }
7978
-
7979
- res.push(codePoint);
7980
- i += bytesPerSequence;
7981
- }
7982
-
7983
- return decodeCodePointsArray(res)
7984
- }
7985
-
7986
- // Based on http://stackoverflow.com/a/22747272/680742, the browser with
7987
- // the lowest limit is Chrome, with 0x10000 args.
7988
- // We go 1 magnitude less, for safety
7989
- var MAX_ARGUMENTS_LENGTH = 0x1000;
7990
-
7991
- function decodeCodePointsArray (codePoints) {
7992
- var len = codePoints.length;
7993
- if (len <= MAX_ARGUMENTS_LENGTH) {
7994
- return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
7995
- }
7996
-
7997
- // Decode in chunks to avoid "call stack size exceeded".
7998
- var res = '';
7999
- var i = 0;
8000
- while (i < len) {
8001
- res += String.fromCharCode.apply(
8002
- String,
8003
- codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
8004
- );
8005
- }
8006
- return res
8007
- }
8008
-
8009
- function asciiSlice (buf, start, end) {
8010
- var ret = '';
8011
- end = Math.min(buf.length, end);
8012
-
8013
- for (var i = start; i < end; ++i) {
8014
- ret += String.fromCharCode(buf[i] & 0x7F);
8015
- }
8016
- return ret
8017
- }
8018
-
8019
- function latin1Slice (buf, start, end) {
8020
- var ret = '';
8021
- end = Math.min(buf.length, end);
8022
-
8023
- for (var i = start; i < end; ++i) {
8024
- ret += String.fromCharCode(buf[i]);
8025
- }
8026
- return ret
8027
- }
8028
-
8029
- function hexSlice (buf, start, end) {
8030
- var len = buf.length;
8031
-
8032
- if (!start || start < 0) start = 0;
8033
- if (!end || end < 0 || end > len) end = len;
8034
-
8035
- var out = '';
8036
- for (var i = start; i < end; ++i) {
8037
- out += hexSliceLookupTable[buf[i]];
8038
- }
8039
- return out
8040
- }
8041
-
8042
- function utf16leSlice (buf, start, end) {
8043
- var bytes = buf.slice(start, end);
8044
- var res = '';
8045
- // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)
8046
- for (var i = 0; i < bytes.length - 1; i += 2) {
8047
- res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256));
8048
- }
8049
- return res
8050
- }
8051
-
8052
- Buffer.prototype.slice = function slice (start, end) {
8053
- var len = this.length;
8054
- start = ~~start;
8055
- end = end === undefined ? len : ~~end;
8056
-
8057
- if (start < 0) {
8058
- start += len;
8059
- if (start < 0) start = 0;
8060
- } else if (start > len) {
8061
- start = len;
8062
- }
8063
-
8064
- if (end < 0) {
8065
- end += len;
8066
- if (end < 0) end = 0;
8067
- } else if (end > len) {
8068
- end = len;
8069
- }
8070
-
8071
- if (end < start) end = start;
8072
-
8073
- var newBuf = this.subarray(start, end);
8074
- // Return an augmented `Uint8Array` instance
8075
- Object.setPrototypeOf(newBuf, Buffer.prototype);
8076
-
8077
- return newBuf
8078
- };
8079
-
8080
- /*
8081
- * Need to make sure that buffer isn't trying to write out of bounds.
8082
- */
8083
- function checkOffset (offset, ext, length) {
8084
- if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
8085
- if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
8086
- }
8087
-
8088
- Buffer.prototype.readUintLE =
8089
- Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
8090
- offset = offset >>> 0;
8091
- byteLength = byteLength >>> 0;
8092
- if (!noAssert) checkOffset(offset, byteLength, this.length);
8093
-
8094
- var val = this[offset];
8095
- var mul = 1;
8096
- var i = 0;
8097
- while (++i < byteLength && (mul *= 0x100)) {
8098
- val += this[offset + i] * mul;
8099
- }
8100
-
8101
- return val
8102
- };
8103
-
8104
- Buffer.prototype.readUintBE =
8105
- Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
8106
- offset = offset >>> 0;
8107
- byteLength = byteLength >>> 0;
8108
- if (!noAssert) {
8109
- checkOffset(offset, byteLength, this.length);
8110
- }
8111
-
8112
- var val = this[offset + --byteLength];
8113
- var mul = 1;
8114
- while (byteLength > 0 && (mul *= 0x100)) {
8115
- val += this[offset + --byteLength] * mul;
8116
- }
8117
-
8118
- return val
8119
- };
8120
-
8121
- Buffer.prototype.readUint8 =
8122
- Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
8123
- offset = offset >>> 0;
8124
- if (!noAssert) checkOffset(offset, 1, this.length);
8125
- return this[offset]
8126
- };
8127
-
8128
- Buffer.prototype.readUint16LE =
8129
- Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
8130
- offset = offset >>> 0;
8131
- if (!noAssert) checkOffset(offset, 2, this.length);
8132
- return this[offset] | (this[offset + 1] << 8)
8133
- };
8134
-
8135
- Buffer.prototype.readUint16BE =
8136
- Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
8137
- offset = offset >>> 0;
8138
- if (!noAssert) checkOffset(offset, 2, this.length);
8139
- return (this[offset] << 8) | this[offset + 1]
8140
- };
8141
-
8142
- Buffer.prototype.readUint32LE =
8143
- Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
8144
- offset = offset >>> 0;
8145
- if (!noAssert) checkOffset(offset, 4, this.length);
8146
-
8147
- return ((this[offset]) |
8148
- (this[offset + 1] << 8) |
8149
- (this[offset + 2] << 16)) +
8150
- (this[offset + 3] * 0x1000000)
8151
- };
8152
-
8153
- Buffer.prototype.readUint32BE =
8154
- Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
8155
- offset = offset >>> 0;
8156
- if (!noAssert) checkOffset(offset, 4, this.length);
8157
-
8158
- return (this[offset] * 0x1000000) +
8159
- ((this[offset + 1] << 16) |
8160
- (this[offset + 2] << 8) |
8161
- this[offset + 3])
8162
- };
8163
-
8164
- Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
8165
- offset = offset >>> 0;
8166
- byteLength = byteLength >>> 0;
8167
- if (!noAssert) checkOffset(offset, byteLength, this.length);
8168
-
8169
- var val = this[offset];
8170
- var mul = 1;
8171
- var i = 0;
8172
- while (++i < byteLength && (mul *= 0x100)) {
8173
- val += this[offset + i] * mul;
8174
- }
8175
- mul *= 0x80;
8176
-
8177
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
8178
-
8179
- return val
8180
- };
8181
-
8182
- Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
8183
- offset = offset >>> 0;
8184
- byteLength = byteLength >>> 0;
8185
- if (!noAssert) checkOffset(offset, byteLength, this.length);
8186
-
8187
- var i = byteLength;
8188
- var mul = 1;
8189
- var val = this[offset + --i];
8190
- while (i > 0 && (mul *= 0x100)) {
8191
- val += this[offset + --i] * mul;
8192
- }
8193
- mul *= 0x80;
8194
-
8195
- if (val >= mul) val -= Math.pow(2, 8 * byteLength);
8196
-
8197
- return val
8198
- };
8199
-
8200
- Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
8201
- offset = offset >>> 0;
8202
- if (!noAssert) checkOffset(offset, 1, this.length);
8203
- if (!(this[offset] & 0x80)) return (this[offset])
8204
- return ((0xff - this[offset] + 1) * -1)
8205
- };
8206
-
8207
- Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
8208
- offset = offset >>> 0;
8209
- if (!noAssert) checkOffset(offset, 2, this.length);
8210
- var val = this[offset] | (this[offset + 1] << 8);
8211
- return (val & 0x8000) ? val | 0xFFFF0000 : val
8212
- };
8213
-
8214
- Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
8215
- offset = offset >>> 0;
8216
- if (!noAssert) checkOffset(offset, 2, this.length);
8217
- var val = this[offset + 1] | (this[offset] << 8);
8218
- return (val & 0x8000) ? val | 0xFFFF0000 : val
8219
- };
8220
-
8221
- Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
8222
- offset = offset >>> 0;
8223
- if (!noAssert) checkOffset(offset, 4, this.length);
8224
-
8225
- return (this[offset]) |
8226
- (this[offset + 1] << 8) |
8227
- (this[offset + 2] << 16) |
8228
- (this[offset + 3] << 24)
8229
- };
8230
-
8231
- Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
8232
- offset = offset >>> 0;
8233
- if (!noAssert) checkOffset(offset, 4, this.length);
8234
-
8235
- return (this[offset] << 24) |
8236
- (this[offset + 1] << 16) |
8237
- (this[offset + 2] << 8) |
8238
- (this[offset + 3])
8239
- };
8240
-
8241
- Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
8242
- offset = offset >>> 0;
8243
- if (!noAssert) checkOffset(offset, 4, this.length);
8244
- return ieee754.read(this, offset, true, 23, 4)
8245
- };
8246
-
8247
- Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
8248
- offset = offset >>> 0;
8249
- if (!noAssert) checkOffset(offset, 4, this.length);
8250
- return ieee754.read(this, offset, false, 23, 4)
8251
- };
8252
-
8253
- Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
8254
- offset = offset >>> 0;
8255
- if (!noAssert) checkOffset(offset, 8, this.length);
8256
- return ieee754.read(this, offset, true, 52, 8)
8257
- };
8258
-
8259
- Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
8260
- offset = offset >>> 0;
8261
- if (!noAssert) checkOffset(offset, 8, this.length);
8262
- return ieee754.read(this, offset, false, 52, 8)
8263
- };
8264
-
8265
- function checkInt (buf, value, offset, ext, max, min) {
8266
- if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
8267
- if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
8268
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
8269
- }
8270
-
8271
- Buffer.prototype.writeUintLE =
8272
- Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
8273
- value = +value;
8274
- offset = offset >>> 0;
8275
- byteLength = byteLength >>> 0;
8276
- if (!noAssert) {
8277
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
8278
- checkInt(this, value, offset, byteLength, maxBytes, 0);
8279
- }
8280
-
8281
- var mul = 1;
8282
- var i = 0;
8283
- this[offset] = value & 0xFF;
8284
- while (++i < byteLength && (mul *= 0x100)) {
8285
- this[offset + i] = (value / mul) & 0xFF;
8286
- }
8287
-
8288
- return offset + byteLength
8289
- };
8290
-
8291
- Buffer.prototype.writeUintBE =
8292
- Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
8293
- value = +value;
8294
- offset = offset >>> 0;
8295
- byteLength = byteLength >>> 0;
8296
- if (!noAssert) {
8297
- var maxBytes = Math.pow(2, 8 * byteLength) - 1;
8298
- checkInt(this, value, offset, byteLength, maxBytes, 0);
8299
- }
8300
-
8301
- var i = byteLength - 1;
8302
- var mul = 1;
8303
- this[offset + i] = value & 0xFF;
8304
- while (--i >= 0 && (mul *= 0x100)) {
8305
- this[offset + i] = (value / mul) & 0xFF;
8306
- }
8307
-
8308
- return offset + byteLength
8309
- };
8310
-
8311
- Buffer.prototype.writeUint8 =
8312
- Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
8313
- value = +value;
8314
- offset = offset >>> 0;
8315
- if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0);
8316
- this[offset] = (value & 0xff);
8317
- return offset + 1
8318
- };
8319
-
8320
- Buffer.prototype.writeUint16LE =
8321
- Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
8322
- value = +value;
8323
- offset = offset >>> 0;
8324
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
8325
- this[offset] = (value & 0xff);
8326
- this[offset + 1] = (value >>> 8);
8327
- return offset + 2
8328
- };
8329
-
8330
- Buffer.prototype.writeUint16BE =
8331
- Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
8332
- value = +value;
8333
- offset = offset >>> 0;
8334
- if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0);
8335
- this[offset] = (value >>> 8);
8336
- this[offset + 1] = (value & 0xff);
8337
- return offset + 2
8338
- };
8339
-
8340
- Buffer.prototype.writeUint32LE =
8341
- Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
8342
- value = +value;
8343
- offset = offset >>> 0;
8344
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
8345
- this[offset + 3] = (value >>> 24);
8346
- this[offset + 2] = (value >>> 16);
8347
- this[offset + 1] = (value >>> 8);
8348
- this[offset] = (value & 0xff);
8349
- return offset + 4
8350
- };
8351
-
8352
- Buffer.prototype.writeUint32BE =
8353
- Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
8354
- value = +value;
8355
- offset = offset >>> 0;
8356
- if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0);
8357
- this[offset] = (value >>> 24);
8358
- this[offset + 1] = (value >>> 16);
8359
- this[offset + 2] = (value >>> 8);
8360
- this[offset + 3] = (value & 0xff);
8361
- return offset + 4
8362
- };
8363
-
8364
- Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
8365
- value = +value;
8366
- offset = offset >>> 0;
8367
- if (!noAssert) {
8368
- var limit = Math.pow(2, (8 * byteLength) - 1);
8369
-
8370
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
8371
- }
8372
-
8373
- var i = 0;
8374
- var mul = 1;
8375
- var sub = 0;
8376
- this[offset] = value & 0xFF;
8377
- while (++i < byteLength && (mul *= 0x100)) {
8378
- if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
8379
- sub = 1;
8380
- }
8381
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
8382
- }
8383
-
8384
- return offset + byteLength
8385
- };
8386
-
8387
- Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
8388
- value = +value;
8389
- offset = offset >>> 0;
8390
- if (!noAssert) {
8391
- var limit = Math.pow(2, (8 * byteLength) - 1);
8392
-
8393
- checkInt(this, value, offset, byteLength, limit - 1, -limit);
8394
- }
8395
-
8396
- var i = byteLength - 1;
8397
- var mul = 1;
8398
- var sub = 0;
8399
- this[offset + i] = value & 0xFF;
8400
- while (--i >= 0 && (mul *= 0x100)) {
8401
- if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
8402
- sub = 1;
8403
- }
8404
- this[offset + i] = ((value / mul) >> 0) - sub & 0xFF;
8405
- }
8406
-
8407
- return offset + byteLength
8408
- };
8409
-
8410
- Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
8411
- value = +value;
8412
- offset = offset >>> 0;
8413
- if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -128);
8414
- if (value < 0) value = 0xff + value + 1;
8415
- this[offset] = (value & 0xff);
8416
- return offset + 1
8417
- };
8418
-
8419
- Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
8420
- value = +value;
8421
- offset = offset >>> 0;
8422
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
8423
- this[offset] = (value & 0xff);
8424
- this[offset + 1] = (value >>> 8);
8425
- return offset + 2
8426
- };
8427
-
8428
- Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
8429
- value = +value;
8430
- offset = offset >>> 0;
8431
- if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768);
8432
- this[offset] = (value >>> 8);
8433
- this[offset + 1] = (value & 0xff);
8434
- return offset + 2
8435
- };
8436
-
8437
- Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
8438
- value = +value;
8439
- offset = offset >>> 0;
8440
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
8441
- this[offset] = (value & 0xff);
8442
- this[offset + 1] = (value >>> 8);
8443
- this[offset + 2] = (value >>> 16);
8444
- this[offset + 3] = (value >>> 24);
8445
- return offset + 4
8446
- };
8447
-
8448
- Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
8449
- value = +value;
8450
- offset = offset >>> 0;
8451
- if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648);
8452
- if (value < 0) value = 0xffffffff + value + 1;
8453
- this[offset] = (value >>> 24);
8454
- this[offset + 1] = (value >>> 16);
8455
- this[offset + 2] = (value >>> 8);
8456
- this[offset + 3] = (value & 0xff);
8457
- return offset + 4
8458
- };
8459
-
8460
- function checkIEEE754 (buf, value, offset, ext, max, min) {
8461
- if (offset + ext > buf.length) throw new RangeError('Index out of range')
8462
- if (offset < 0) throw new RangeError('Index out of range')
8463
- }
8464
-
8465
- function writeFloat (buf, value, offset, littleEndian, noAssert) {
8466
- value = +value;
8467
- offset = offset >>> 0;
8468
- if (!noAssert) {
8469
- checkIEEE754(buf, value, offset, 4);
8470
- }
8471
- ieee754.write(buf, value, offset, littleEndian, 23, 4);
8472
- return offset + 4
8473
- }
8474
-
8475
- Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
8476
- return writeFloat(this, value, offset, true, noAssert)
8477
- };
8478
-
8479
- Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
8480
- return writeFloat(this, value, offset, false, noAssert)
8481
- };
8482
-
8483
- function writeDouble (buf, value, offset, littleEndian, noAssert) {
8484
- value = +value;
8485
- offset = offset >>> 0;
8486
- if (!noAssert) {
8487
- checkIEEE754(buf, value, offset, 8);
8488
- }
8489
- ieee754.write(buf, value, offset, littleEndian, 52, 8);
8490
- return offset + 8
8491
- }
8492
-
8493
- Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
8494
- return writeDouble(this, value, offset, true, noAssert)
8495
- };
8496
-
8497
- Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
8498
- return writeDouble(this, value, offset, false, noAssert)
8499
- };
8500
-
8501
- // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
8502
- Buffer.prototype.copy = function copy (target, targetStart, start, end) {
8503
- if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
8504
- if (!start) start = 0;
8505
- if (!end && end !== 0) end = this.length;
8506
- if (targetStart >= target.length) targetStart = target.length;
8507
- if (!targetStart) targetStart = 0;
8508
- if (end > 0 && end < start) end = start;
8509
-
8510
- // Copy 0 bytes; we're done
8511
- if (end === start) return 0
8512
- if (target.length === 0 || this.length === 0) return 0
8513
-
8514
- // Fatal error conditions
8515
- if (targetStart < 0) {
8516
- throw new RangeError('targetStart out of bounds')
8517
- }
8518
- if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
8519
- if (end < 0) throw new RangeError('sourceEnd out of bounds')
6728
+ received = addNumericalSeparator(String(input));
6729
+ } else if (typeof input === 'bigint') {
6730
+ received = String(input);
6731
+ if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {
6732
+ received = addNumericalSeparator(received);
6733
+ }
6734
+ received += 'n';
6735
+ }
6736
+ msg += ` It must be ${range}. Received ${received}`;
6737
+ return msg
6738
+ }, RangeError);
8520
6739
 
8521
- // Are we oob?
8522
- if (end > this.length) end = this.length;
8523
- if (target.length - targetStart < end - start) {
8524
- end = target.length - targetStart + start;
6740
+ function addNumericalSeparator (val) {
6741
+ let res = '';
6742
+ let i = val.length;
6743
+ const start = val[0] === '-' ? 1 : 0;
6744
+ for (; i >= start + 4; i -= 3) {
6745
+ res = `_${val.slice(i - 3, i)}${res}`;
8525
6746
  }
6747
+ return `${val.slice(0, i)}${res}`
6748
+ }
8526
6749
 
8527
- var len = end - start;
6750
+ // CHECK FUNCTIONS
6751
+ // ===============
8528
6752
 
8529
- if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
8530
- // Use built-in when available, missing from IE11
8531
- this.copyWithin(targetStart, start, end);
8532
- } else {
8533
- Uint8Array.prototype.set.call(
8534
- target,
8535
- this.subarray(start, end),
8536
- targetStart
8537
- );
6753
+ function checkBounds (buf, offset, byteLength) {
6754
+ validateNumber(offset, 'offset');
6755
+ if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {
6756
+ boundsError(offset, buf.length - (byteLength + 1));
8538
6757
  }
6758
+ }
8539
6759
 
8540
- return len
8541
- };
8542
-
8543
- // Usage:
8544
- // buffer.fill(number[, offset[, end]])
8545
- // buffer.fill(buffer[, offset[, end]])
8546
- // buffer.fill(string[, offset[, end]][, encoding])
8547
- Buffer.prototype.fill = function fill (val, start, end, encoding) {
8548
- // Handle string cases:
8549
- if (typeof val === 'string') {
8550
- if (typeof start === 'string') {
8551
- encoding = start;
8552
- start = 0;
8553
- end = this.length;
8554
- } else if (typeof end === 'string') {
8555
- encoding = end;
8556
- end = this.length;
8557
- }
8558
- if (encoding !== undefined && typeof encoding !== 'string') {
8559
- throw new TypeError('encoding must be a string')
8560
- }
8561
- if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
8562
- throw new TypeError('Unknown encoding: ' + encoding)
8563
- }
8564
- if (val.length === 1) {
8565
- var code = val.charCodeAt(0);
8566
- if ((encoding === 'utf8' && code < 128) ||
8567
- encoding === 'latin1') {
8568
- // Fast path: If `val` fits into a single byte, use that numeric value.
8569
- val = code;
6760
+ function checkIntBI (value, min, max, buf, offset, byteLength) {
6761
+ if (value > max || value < min) {
6762
+ const n = typeof min === 'bigint' ? 'n' : '';
6763
+ let range;
6764
+ {
6765
+ if (min === 0 || min === BigInt(0)) {
6766
+ range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`;
6767
+ } else {
6768
+ range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +
6769
+ `${(byteLength + 1) * 8 - 1}${n}`;
8570
6770
  }
8571
6771
  }
8572
- } else if (typeof val === 'number') {
8573
- val = val & 255;
8574
- } else if (typeof val === 'boolean') {
8575
- val = Number(val);
6772
+ throw new errors.ERR_OUT_OF_RANGE('value', range, value)
8576
6773
  }
6774
+ checkBounds(buf, offset, byteLength);
6775
+ }
8577
6776
 
8578
- // Invalid ranges are not set to a default, so can range check early.
8579
- if (start < 0 || this.length < start || this.length < end) {
8580
- throw new RangeError('Out of range index')
6777
+ function validateNumber (value, name) {
6778
+ if (typeof value !== 'number') {
6779
+ throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)
8581
6780
  }
6781
+ }
8582
6782
 
8583
- if (end <= start) {
8584
- return this
6783
+ function boundsError (value, length, type) {
6784
+ if (Math.floor(value) !== value) {
6785
+ validateNumber(value, type);
6786
+ throw new errors.ERR_OUT_OF_RANGE('offset', 'an integer', value)
8585
6787
  }
8586
6788
 
8587
- start = start >>> 0;
8588
- end = end === undefined ? this.length : end >>> 0;
8589
-
8590
- if (!val) val = 0;
8591
-
8592
- var i;
8593
- if (typeof val === 'number') {
8594
- for (i = start; i < end; ++i) {
8595
- this[i] = val;
8596
- }
8597
- } else {
8598
- var bytes = Buffer.isBuffer(val)
8599
- ? val
8600
- : Buffer.from(val, encoding);
8601
- var len = bytes.length;
8602
- if (len === 0) {
8603
- throw new TypeError('The value "' + val +
8604
- '" is invalid for argument "value"')
8605
- }
8606
- for (i = 0; i < end - start; ++i) {
8607
- this[i + start] = bytes[i % len];
8608
- }
6789
+ if (length < 0) {
6790
+ throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()
8609
6791
  }
8610
6792
 
8611
- return this
8612
- };
6793
+ throw new errors.ERR_OUT_OF_RANGE('offset',
6794
+ `>= ${0} and <= ${length}`,
6795
+ value)
6796
+ }
8613
6797
 
8614
6798
  // HELPER FUNCTIONS
8615
6799
  // ================
8616
6800
 
8617
- var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
6801
+ const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g;
8618
6802
 
8619
6803
  function base64clean (str) {
8620
6804
  // Node takes equal signs as end of the Base64 encoding
@@ -8632,12 +6816,12 @@ function requireBuffer () {
8632
6816
 
8633
6817
  function utf8ToBytes (string, units) {
8634
6818
  units = units || Infinity;
8635
- var codePoint;
8636
- var length = string.length;
8637
- var leadSurrogate = null;
8638
- var bytes = [];
6819
+ let codePoint;
6820
+ const length = string.length;
6821
+ let leadSurrogate = null;
6822
+ const bytes = [];
8639
6823
 
8640
- for (var i = 0; i < length; ++i) {
6824
+ for (let i = 0; i < length; ++i) {
8641
6825
  codePoint = string.charCodeAt(i);
8642
6826
 
8643
6827
  // is surrogate component
@@ -8711,8 +6895,8 @@ function requireBuffer () {
8711
6895
  }
8712
6896
 
8713
6897
  function asciiToBytes (str) {
8714
- var byteArray = [];
8715
- for (var i = 0; i < str.length; ++i) {
6898
+ const byteArray = [];
6899
+ for (let i = 0; i < str.length; ++i) {
8716
6900
  // Node's code seems to be doing this and not & 0x7F..
8717
6901
  byteArray.push(str.charCodeAt(i) & 0xFF);
8718
6902
  }
@@ -8720,9 +6904,9 @@ function requireBuffer () {
8720
6904
  }
8721
6905
 
8722
6906
  function utf16leToBytes (str, units) {
8723
- var c, hi, lo;
8724
- var byteArray = [];
8725
- for (var i = 0; i < str.length; ++i) {
6907
+ let c, hi, lo;
6908
+ const byteArray = [];
6909
+ for (let i = 0; i < str.length; ++i) {
8726
6910
  if ((units -= 2) < 0) break
8727
6911
 
8728
6912
  c = str.charCodeAt(i);
@@ -8740,7 +6924,8 @@ function requireBuffer () {
8740
6924
  }
8741
6925
 
8742
6926
  function blitBuffer (src, dst, offset, length) {
8743
- for (var i = 0; i < length; ++i) {
6927
+ let i;
6928
+ for (i = 0; i < length; ++i) {
8744
6929
  if ((i + offset >= dst.length) || (i >= src.length)) break
8745
6930
  dst[i + offset] = src[i];
8746
6931
  }
@@ -8762,23 +6947,34 @@ function requireBuffer () {
8762
6947
 
8763
6948
  // Create lookup table for `toString('hex')`
8764
6949
  // See: https://github.com/feross/buffer/issues/219
8765
- var hexSliceLookupTable = (function () {
8766
- var alphabet = '0123456789abcdef';
8767
- var table = new Array(256);
8768
- for (var i = 0; i < 16; ++i) {
8769
- var i16 = i * 16;
8770
- for (var j = 0; j < 16; ++j) {
6950
+ const hexSliceLookupTable = (function () {
6951
+ const alphabet = '0123456789abcdef';
6952
+ const table = new Array(256);
6953
+ for (let i = 0; i < 16; ++i) {
6954
+ const i16 = i * 16;
6955
+ for (let j = 0; j < 16; ++j) {
8771
6956
  table[i16 + j] = alphabet[i] + alphabet[j];
8772
6957
  }
8773
6958
  }
8774
6959
  return table
8775
- })();
6960
+ })();
6961
+
6962
+ // Return not function with Error if BigInt not supported
6963
+ function defineBigIntMethod (fn) {
6964
+ return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn
6965
+ }
6966
+
6967
+ function BufferBigIntNotDefined () {
6968
+ throw new Error('BigInt not supported')
6969
+ }
8776
6970
  } (buffer));
8777
6971
  return buffer;
8778
6972
  }
8779
6973
 
8780
6974
  var bufferExports = requireBuffer();
8781
6975
 
6976
+ var dist = {};
6977
+
8782
6978
  var Codecs = {};
8783
6979
 
8784
6980
  var Frames = {};
@@ -8788,7 +6984,7 @@ var hasRequiredFrames;
8788
6984
  function requireFrames () {
8789
6985
  if (hasRequiredFrames) return Frames;
8790
6986
  hasRequiredFrames = 1;
8791
- (function (exports) {
6987
+ (function (exports$1) {
8792
6988
  /*
8793
6989
  * Copyright 2021-2022 the original author or authors.
8794
6990
  *
@@ -8804,8 +7000,8 @@ function requireFrames () {
8804
7000
  * See the License for the specific language governing permissions and
8805
7001
  * limitations under the License.
8806
7002
  */
8807
- Object.defineProperty(exports, "__esModule", { value: true });
8808
- exports.Frame = exports.Lengths = exports.Flags = exports.FrameTypes = void 0;
7003
+ Object.defineProperty(exports$1, "__esModule", { value: true });
7004
+ exports$1.Frame = exports$1.Lengths = exports$1.Flags = exports$1.FrameTypes = void 0;
8809
7005
  var FrameTypes;
8810
7006
  (function (FrameTypes) {
8811
7007
  FrameTypes[FrameTypes["RESERVED"] = 0] = "RESERVED";
@@ -8824,7 +7020,7 @@ function requireFrames () {
8824
7020
  FrameTypes[FrameTypes["RESUME"] = 13] = "RESUME";
8825
7021
  FrameTypes[FrameTypes["RESUME_OK"] = 14] = "RESUME_OK";
8826
7022
  FrameTypes[FrameTypes["EXT"] = 63] = "EXT";
8827
- })(FrameTypes = exports.FrameTypes || (exports.FrameTypes = {}));
7023
+ })(FrameTypes = exports$1.FrameTypes || (exports$1.FrameTypes = {}));
8828
7024
  (function (Flags) {
8829
7025
  Flags[Flags["NONE"] = 0] = "NONE";
8830
7026
  Flags[Flags["COMPLETE"] = 64] = "COMPLETE";
@@ -8835,7 +7031,7 @@ function requireFrames () {
8835
7031
  Flags[Flags["NEXT"] = 32] = "NEXT";
8836
7032
  Flags[Flags["RESPOND"] = 128] = "RESPOND";
8837
7033
  Flags[Flags["RESUME_ENABLE"] = 128] = "RESUME_ENABLE";
8838
- })(exports.Flags || (exports.Flags = {}));
7034
+ })(exports$1.Flags || (exports$1.Flags = {}));
8839
7035
  (function (Flags) {
8840
7036
  function hasMetadata(flags) {
8841
7037
  return (flags & Flags.METADATA) === Flags.METADATA;
@@ -8869,13 +7065,13 @@ function requireFrames () {
8869
7065
  return (flags & Flags.RESUME_ENABLE) === Flags.RESUME_ENABLE;
8870
7066
  }
8871
7067
  Flags.hasResume = hasResume;
8872
- })(exports.Flags || (exports.Flags = {}));
7068
+ })(exports$1.Flags || (exports$1.Flags = {}));
8873
7069
  (function (Lengths) {
8874
7070
  Lengths[Lengths["FRAME"] = 3] = "FRAME";
8875
7071
  Lengths[Lengths["HEADER"] = 6] = "HEADER";
8876
7072
  Lengths[Lengths["METADATA"] = 3] = "METADATA";
8877
7073
  Lengths[Lengths["REQUEST"] = 3] = "REQUEST";
8878
- })(exports.Lengths || (exports.Lengths = {}));
7074
+ })(exports$1.Lengths || (exports$1.Lengths = {}));
8879
7075
  (function (Frame) {
8880
7076
  function isConnection(frame) {
8881
7077
  return frame.streamId === 0;
@@ -8886,7 +7082,7 @@ function requireFrames () {
8886
7082
  frame.type <= FrameTypes.REQUEST_CHANNEL);
8887
7083
  }
8888
7084
  Frame.isRequest = isRequest;
8889
- })(exports.Frame || (exports.Frame = {}));
7085
+ })(exports$1.Frame || (exports$1.Frame = {}));
8890
7086
 
8891
7087
  } (Frames));
8892
7088
  return Frames;
@@ -8897,7 +7093,7 @@ var hasRequiredCodecs;
8897
7093
  function requireCodecs () {
8898
7094
  if (hasRequiredCodecs) return Codecs;
8899
7095
  hasRequiredCodecs = 1;
8900
- (function (exports) {
7096
+ (function (exports$1) {
8901
7097
  var __generator = (Codecs && Codecs.__generator) || function (thisArg, body) {
8902
7098
  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
8903
7099
  return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
@@ -8925,22 +7121,22 @@ function requireCodecs () {
8925
7121
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
8926
7122
  }
8927
7123
  };
8928
- Object.defineProperty(exports, "__esModule", { value: true });
8929
- exports.Deserializer = exports.sizeOfFrame = exports.serializeFrame = exports.deserializeFrame = exports.serializeFrameWithLength = exports.deserializeFrames = exports.deserializeFrameWithLength = exports.writeUInt64BE = exports.readUInt64BE = exports.writeUInt24BE = exports.readUInt24BE = exports.MAX_VERSION = exports.MAX_TTL = exports.MAX_STREAM_ID = exports.MAX_RESUME_LENGTH = exports.MAX_REQUEST_N = exports.MAX_REQUEST_COUNT = exports.MAX_MIME_LENGTH = exports.MAX_METADATA_LENGTH = exports.MAX_LIFETIME = exports.MAX_KEEPALIVE = exports.MAX_CODE = exports.FRAME_TYPE_OFFFSET = exports.FLAGS_MASK = void 0;
7124
+ Object.defineProperty(exports$1, "__esModule", { value: true });
7125
+ exports$1.Deserializer = exports$1.sizeOfFrame = exports$1.serializeFrame = exports$1.deserializeFrame = exports$1.serializeFrameWithLength = exports$1.deserializeFrames = exports$1.deserializeFrameWithLength = exports$1.writeUInt64BE = exports$1.readUInt64BE = exports$1.writeUInt24BE = exports$1.readUInt24BE = exports$1.MAX_VERSION = exports$1.MAX_TTL = exports$1.MAX_STREAM_ID = exports$1.MAX_RESUME_LENGTH = exports$1.MAX_REQUEST_N = exports$1.MAX_REQUEST_COUNT = exports$1.MAX_MIME_LENGTH = exports$1.MAX_METADATA_LENGTH = exports$1.MAX_LIFETIME = exports$1.MAX_KEEPALIVE = exports$1.MAX_CODE = exports$1.FRAME_TYPE_OFFFSET = exports$1.FLAGS_MASK = void 0;
8930
7126
  var Frames_1 = requireFrames();
8931
- exports.FLAGS_MASK = 0x3ff; // low 10 bits
8932
- exports.FRAME_TYPE_OFFFSET = 10; // frame type is offset 10 bytes within the uint16 containing type + flags
8933
- exports.MAX_CODE = 0x7fffffff; // uint31
8934
- exports.MAX_KEEPALIVE = 0x7fffffff; // uint31
8935
- exports.MAX_LIFETIME = 0x7fffffff; // uint31
8936
- exports.MAX_METADATA_LENGTH = 0xffffff; // uint24
8937
- exports.MAX_MIME_LENGTH = 0xff; // int8
8938
- exports.MAX_REQUEST_COUNT = 0x7fffffff; // uint31
8939
- exports.MAX_REQUEST_N = 0x7fffffff; // uint31
8940
- exports.MAX_RESUME_LENGTH = 0xffff; // uint16
8941
- exports.MAX_STREAM_ID = 0x7fffffff; // uint31
8942
- exports.MAX_TTL = 0x7fffffff; // uint31
8943
- exports.MAX_VERSION = 0xffff; // uint16
7127
+ exports$1.FLAGS_MASK = 0x3ff; // low 10 bits
7128
+ exports$1.FRAME_TYPE_OFFFSET = 10; // frame type is offset 10 bytes within the uint16 containing type + flags
7129
+ exports$1.MAX_CODE = 0x7fffffff; // uint31
7130
+ exports$1.MAX_KEEPALIVE = 0x7fffffff; // uint31
7131
+ exports$1.MAX_LIFETIME = 0x7fffffff; // uint31
7132
+ exports$1.MAX_METADATA_LENGTH = 0xffffff; // uint24
7133
+ exports$1.MAX_MIME_LENGTH = 0xff; // int8
7134
+ exports$1.MAX_REQUEST_COUNT = 0x7fffffff; // uint31
7135
+ exports$1.MAX_REQUEST_N = 0x7fffffff; // uint31
7136
+ exports$1.MAX_RESUME_LENGTH = 0xffff; // uint16
7137
+ exports$1.MAX_STREAM_ID = 0x7fffffff; // uint31
7138
+ exports$1.MAX_TTL = 0x7fffffff; // uint31
7139
+ exports$1.MAX_VERSION = 0xffff; // uint16
8944
7140
  /**
8945
7141
  * Mimimum value that would overflow bitwise operators (2^32).
8946
7142
  */
@@ -8954,7 +7150,7 @@ function requireCodecs () {
8954
7150
  var val3 = buffer.readUInt8(offset + 2);
8955
7151
  return val1 | val2 | val3;
8956
7152
  }
8957
- exports.readUInt24BE = readUInt24BE;
7153
+ exports$1.readUInt24BE = readUInt24BE;
8958
7154
  /**
8959
7155
  * Writes a uint24 to a buffer starting at the given offset, returning the
8960
7156
  * offset of the next byte.
@@ -8964,7 +7160,7 @@ function requireCodecs () {
8964
7160
  offset = buffer.writeUInt8((value >>> 8) & 0xff, offset); // 2nd byte
8965
7161
  return buffer.writeUInt8(value & 0xff, offset); // 1st byte
8966
7162
  }
8967
- exports.writeUInt24BE = writeUInt24BE;
7163
+ exports$1.writeUInt24BE = writeUInt24BE;
8968
7164
  /**
8969
7165
  * Read a uint64 (technically supports up to 53 bits per JS number
8970
7166
  * representation).
@@ -8974,7 +7170,7 @@ function requireCodecs () {
8974
7170
  var low = buffer.readUInt32BE(offset + 4);
8975
7171
  return high * BITWISE_OVERFLOW + low;
8976
7172
  }
8977
- exports.readUInt64BE = readUInt64BE;
7173
+ exports$1.readUInt64BE = readUInt64BE;
8978
7174
  /**
8979
7175
  * Write a uint64 (technically supports up to 53 bits per JS number
8980
7176
  * representation).
@@ -8985,7 +7181,7 @@ function requireCodecs () {
8985
7181
  offset = buffer.writeUInt32BE(high, offset); // first half of uint64
8986
7182
  return buffer.writeUInt32BE(low, offset); // second half of uint64
8987
7183
  }
8988
- exports.writeUInt64BE = writeUInt64BE;
7184
+ exports$1.writeUInt64BE = writeUInt64BE;
8989
7185
  /**
8990
7186
  * Frame header is:
8991
7187
  * - stream id (uint32 = 4)
@@ -9003,7 +7199,7 @@ function requireCodecs () {
9003
7199
  var frameLength = readUInt24BE(buffer, 0);
9004
7200
  return deserializeFrame(buffer.slice(UINT24_SIZE, UINT24_SIZE + frameLength));
9005
7201
  }
9006
- exports.deserializeFrameWithLength = deserializeFrameWithLength;
7202
+ exports$1.deserializeFrameWithLength = deserializeFrameWithLength;
9007
7203
  /**
9008
7204
  * Given a buffer that may contain zero or more length-prefixed frames followed
9009
7205
  * by zero or more bytes of a (partial) subsequent frame, returns an array of
@@ -9036,7 +7232,7 @@ function requireCodecs () {
9036
7232
  }
9037
7233
  });
9038
7234
  }
9039
- exports.deserializeFrames = deserializeFrames;
7235
+ exports$1.deserializeFrames = deserializeFrames;
9040
7236
  /**
9041
7237
  * Writes a frame to a buffer with a length prefix.
9042
7238
  */
@@ -9047,7 +7243,7 @@ function requireCodecs () {
9047
7243
  buffer.copy(lengthPrefixed, UINT24_SIZE);
9048
7244
  return lengthPrefixed;
9049
7245
  }
9050
- exports.serializeFrameWithLength = serializeFrameWithLength;
7246
+ exports$1.serializeFrameWithLength = serializeFrameWithLength;
9051
7247
  /**
9052
7248
  * Read a frame from the buffer.
9053
7249
  */
@@ -9062,8 +7258,8 @@ function requireCodecs () {
9062
7258
  // );
9063
7259
  var typeAndFlags = buffer.readUInt16BE(offset);
9064
7260
  offset += 2;
9065
- var type = typeAndFlags >>> exports.FRAME_TYPE_OFFFSET; // keep highest 6 bits
9066
- var flags = typeAndFlags & exports.FLAGS_MASK; // keep lowest 10 bits
7261
+ var type = typeAndFlags >>> exports$1.FRAME_TYPE_OFFFSET; // keep highest 6 bits
7262
+ var flags = typeAndFlags & exports$1.FLAGS_MASK; // keep lowest 10 bits
9067
7263
  switch (type) {
9068
7264
  case Frames_1.FrameTypes.SETUP:
9069
7265
  return deserializeSetupFrame(buffer, streamId, flags);
@@ -9100,7 +7296,7 @@ function requireCodecs () {
9100
7296
  // );
9101
7297
  }
9102
7298
  }
9103
- exports.deserializeFrame = deserializeFrame;
7299
+ exports$1.deserializeFrame = deserializeFrame;
9104
7300
  /**
9105
7301
  * Convert the frame to a (binary) buffer.
9106
7302
  */
@@ -9139,7 +7335,7 @@ function requireCodecs () {
9139
7335
  // );
9140
7336
  }
9141
7337
  }
9142
- exports.serializeFrame = serializeFrame;
7338
+ exports$1.serializeFrame = serializeFrame;
9143
7339
  /**
9144
7340
  * Byte size of frame without size prefix
9145
7341
  */
@@ -9178,7 +7374,7 @@ function requireCodecs () {
9178
7374
  // );
9179
7375
  }
9180
7376
  }
9181
- exports.sizeOfFrame = sizeOfFrame;
7377
+ exports$1.sizeOfFrame = sizeOfFrame;
9182
7378
  /**
9183
7379
  * Writes a SETUP frame into a new buffer and returns it.
9184
7380
  *
@@ -9813,7 +8009,7 @@ function requireCodecs () {
9813
8009
  function writeHeader(frame, buffer) {
9814
8010
  var offset = buffer.writeInt32BE(frame.streamId, 0);
9815
8011
  // shift frame to high 6 bits, extract lowest 10 bits from flags
9816
- return buffer.writeUInt16BE((frame.type << exports.FRAME_TYPE_OFFFSET) | (frame.flags & exports.FLAGS_MASK), offset);
8012
+ return buffer.writeUInt16BE((frame.type << exports$1.FRAME_TYPE_OFFFSET) | (frame.flags & exports$1.FLAGS_MASK), offset);
9817
8013
  }
9818
8014
  /**
9819
8015
  * Determine the length of the payload section of a frame. Only applies to
@@ -9894,7 +8090,7 @@ function requireCodecs () {
9894
8090
  };
9895
8091
  return Deserializer;
9896
8092
  }());
9897
- exports.Deserializer = Deserializer;
8093
+ exports$1.Deserializer = Deserializer;
9898
8094
 
9899
8095
  } (Codecs));
9900
8096
  return Codecs;
@@ -10040,7 +8236,7 @@ var hasRequiredErrors;
10040
8236
  function requireErrors () {
10041
8237
  if (hasRequiredErrors) return Errors;
10042
8238
  hasRequiredErrors = 1;
10043
- (function (exports) {
8239
+ (function (exports$1) {
10044
8240
  /*
10045
8241
  * Copyright 2021-2022 the original author or authors.
10046
8242
  *
@@ -10071,8 +8267,8 @@ function requireErrors () {
10071
8267
  d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10072
8268
  };
10073
8269
  })();
10074
- Object.defineProperty(exports, "__esModule", { value: true });
10075
- exports.ErrorCodes = exports.RSocketError = void 0;
8270
+ Object.defineProperty(exports$1, "__esModule", { value: true });
8271
+ exports$1.ErrorCodes = exports$1.RSocketError = void 0;
10076
8272
  var RSocketError = /** @class */ (function (_super) {
10077
8273
  __extends(RSocketError, _super);
10078
8274
  function RSocketError(code, message) {
@@ -10082,7 +8278,7 @@ function requireErrors () {
10082
8278
  }
10083
8279
  return RSocketError;
10084
8280
  }(Error));
10085
- exports.RSocketError = RSocketError;
8281
+ exports$1.RSocketError = RSocketError;
10086
8282
  (function (ErrorCodes) {
10087
8283
  ErrorCodes[ErrorCodes["RESERVED"] = 0] = "RESERVED";
10088
8284
  ErrorCodes[ErrorCodes["INVALID_SETUP"] = 1] = "INVALID_SETUP";
@@ -10096,7 +8292,7 @@ function requireErrors () {
10096
8292
  ErrorCodes[ErrorCodes["CANCELED"] = 515] = "CANCELED";
10097
8293
  ErrorCodes[ErrorCodes["INVALID"] = 516] = "INVALID";
10098
8294
  ErrorCodes[ErrorCodes["RESERVED_EXTENSION"] = 4294967295] = "RESERVED_EXTENSION";
10099
- })(exports.ErrorCodes || (exports.ErrorCodes = {}));
8295
+ })(exports$1.ErrorCodes || (exports$1.ErrorCodes = {}));
10100
8296
 
10101
8297
  } (Errors));
10102
8298
  return Errors;
@@ -10138,7 +8334,7 @@ var hasRequiredClientServerMultiplexerDemultiplexer;
10138
8334
  function requireClientServerMultiplexerDemultiplexer () {
10139
8335
  if (hasRequiredClientServerMultiplexerDemultiplexer) return ClientServerMultiplexerDemultiplexer;
10140
8336
  hasRequiredClientServerMultiplexerDemultiplexer = 1;
10141
- (function (exports) {
8337
+ (function (exports$1) {
10142
8338
  /*
10143
8339
  * Copyright 2021-2022 the original author or authors.
10144
8340
  *
@@ -10205,8 +8401,8 @@ function requireClientServerMultiplexerDemultiplexer () {
10205
8401
  if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
10206
8402
  }
10207
8403
  };
10208
- Object.defineProperty(exports, "__esModule", { value: true });
10209
- exports.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = exports.ResumableClientServerInputMultiplexerDemultiplexer = exports.ClientServerInputMultiplexerDemultiplexer = exports.StreamIdGenerator = void 0;
8404
+ Object.defineProperty(exports$1, "__esModule", { value: true });
8405
+ exports$1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = exports$1.ResumableClientServerInputMultiplexerDemultiplexer = exports$1.ClientServerInputMultiplexerDemultiplexer = exports$1.StreamIdGenerator = void 0;
10210
8406
  var _1 = requireDist();
10211
8407
  var Deferred_1 = requireDeferred();
10212
8408
  var Errors_1 = requireErrors();
@@ -10229,7 +8425,7 @@ function requireClientServerMultiplexerDemultiplexer () {
10229
8425
  };
10230
8426
  return StreamIdGeneratorImpl;
10231
8427
  }());
10232
- })(exports.StreamIdGenerator || (exports.StreamIdGenerator = {}));
8428
+ })(exports$1.StreamIdGenerator || (exports$1.StreamIdGenerator = {}));
10233
8429
  var ClientServerInputMultiplexerDemultiplexer = /** @class */ (function (_super) {
10234
8430
  __extends(ClientServerInputMultiplexerDemultiplexer, _super);
10235
8431
  function ClientServerInputMultiplexerDemultiplexer(streamIdSupplier, outbound, closeable) {
@@ -10318,7 +8514,7 @@ function requireClientServerMultiplexerDemultiplexer () {
10318
8514
  };
10319
8515
  return ClientServerInputMultiplexerDemultiplexer;
10320
8516
  }(Deferred_1.Deferred));
10321
- exports.ClientServerInputMultiplexerDemultiplexer = ClientServerInputMultiplexerDemultiplexer;
8517
+ exports$1.ClientServerInputMultiplexerDemultiplexer = ClientServerInputMultiplexerDemultiplexer;
10322
8518
  var ResumableClientServerInputMultiplexerDemultiplexer = /** @class */ (function (_super) {
10323
8519
  __extends(ResumableClientServerInputMultiplexerDemultiplexer, _super);
10324
8520
  function ResumableClientServerInputMultiplexerDemultiplexer(streamIdSupplier, outbound, closeable, frameStore, token, sessionStoreOrReconnector, sessionTimeout) {
@@ -10475,7 +8671,7 @@ function requireClientServerMultiplexerDemultiplexer () {
10475
8671
  };
10476
8672
  return ResumableClientServerInputMultiplexerDemultiplexer;
10477
8673
  }(ClientServerInputMultiplexerDemultiplexer));
10478
- exports.ResumableClientServerInputMultiplexerDemultiplexer = ResumableClientServerInputMultiplexerDemultiplexer;
8674
+ exports$1.ResumableClientServerInputMultiplexerDemultiplexer = ResumableClientServerInputMultiplexerDemultiplexer;
10479
8675
  var ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = /** @class */ (function () {
10480
8676
  function ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer(outbound, closeable, delegate) {
10481
8677
  this.outbound = outbound;
@@ -10532,7 +8728,7 @@ function requireClientServerMultiplexerDemultiplexer () {
10532
8728
  };
10533
8729
  return ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;
10534
8730
  }());
10535
- exports.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;
8731
+ exports$1.ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer = ResumeOkAwaitingResumableClientServerInputMultiplexerDemultiplexer;
10536
8732
 
10537
8733
  } (ClientServerMultiplexerDemultiplexer));
10538
8734
  return ClientServerMultiplexerDemultiplexer;
@@ -13518,7 +11714,7 @@ var hasRequiredDist;
13518
11714
  function requireDist () {
13519
11715
  if (hasRequiredDist) return dist;
13520
11716
  hasRequiredDist = 1;
13521
- (function (exports) {
11717
+ (function (exports$1) {
13522
11718
  /*
13523
11719
  * Copyright 2021-2022 the original author or authors.
13524
11720
  *
@@ -13541,19 +11737,19 @@ function requireDist () {
13541
11737
  if (k2 === undefined) k2 = k;
13542
11738
  o[k2] = m[k];
13543
11739
  }));
13544
- var __exportStar = (dist && dist.__exportStar) || function(m, exports) {
13545
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11740
+ var __exportStar = (dist && dist.__exportStar) || function(m, exports$1) {
11741
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports$1, p)) __createBinding(exports$1, m, p);
13546
11742
  };
13547
- Object.defineProperty(exports, "__esModule", { value: true });
13548
- __exportStar(requireCodecs(), exports);
13549
- __exportStar(requireCommon(), exports);
13550
- __exportStar(requireDeferred(), exports);
13551
- __exportStar(requireErrors(), exports);
13552
- __exportStar(requireFrames(), exports);
13553
- __exportStar(requireRSocket(), exports);
13554
- __exportStar(requireRSocketConnector(), exports);
13555
- __exportStar(requireRSocketServer(), exports);
13556
- __exportStar(requireTransport(), exports);
11743
+ Object.defineProperty(exports$1, "__esModule", { value: true });
11744
+ __exportStar(requireCodecs(), exports$1);
11745
+ __exportStar(requireCommon(), exports$1);
11746
+ __exportStar(requireDeferred(), exports$1);
11747
+ __exportStar(requireErrors(), exports$1);
11748
+ __exportStar(requireFrames(), exports$1);
11749
+ __exportStar(requireRSocket(), exports$1);
11750
+ __exportStar(requireRSocketConnector(), exports$1);
11751
+ __exportStar(requireRSocketServer(), exports$1);
11752
+ __exportStar(requireTransport(), exports$1);
13557
11753
 
13558
11754
  } (dist));
13559
11755
  return dist;
@@ -13561,7 +11757,7 @@ function requireDist () {
13561
11757
 
13562
11758
  var distExports = requireDist();
13563
11759
 
13564
- var version = "1.44.0";
11760
+ var version = "1.46.0";
13565
11761
  var PACKAGE = {
13566
11762
  version: version};
13567
11763
 
@@ -13632,6 +11828,16 @@ class DataStream extends BaseObserver {
13632
11828
  * @returns a Data payload or Null if the stream closed.
13633
11829
  */
13634
11830
  async read() {
11831
+ if (this.closed) {
11832
+ return null;
11833
+ }
11834
+ // Wait for any pending processing to complete first.
11835
+ // This ensures we register our listener before calling processQueue(),
11836
+ // avoiding a race where processQueue() sees no reader and returns early.
11837
+ if (this.processingPromise) {
11838
+ await this.processingPromise;
11839
+ }
11840
+ // Re-check after await - stream may have closed while we were waiting
13635
11841
  if (this.closed) {
13636
11842
  return null;
13637
11843
  }
@@ -13671,7 +11877,7 @@ class DataStream extends BaseObserver {
13671
11877
  }
13672
11878
  const promise = (this.processingPromise = this._processQueue());
13673
11879
  promise.finally(() => {
13674
- return (this.processingPromise = null);
11880
+ this.processingPromise = null;
13675
11881
  });
13676
11882
  return promise;
13677
11883
  }
@@ -13703,7 +11909,6 @@ class DataStream extends BaseObserver {
13703
11909
  this.notifyDataAdded = null;
13704
11910
  }
13705
11911
  if (this.dataQueue.length > 0) {
13706
- // Next tick
13707
11912
  setTimeout(() => this.processQueue());
13708
11913
  }
13709
11914
  }
@@ -14083,7 +12288,7 @@ class AbstractRemote {
14083
12288
  else {
14084
12289
  contents = JSON.stringify(js);
14085
12290
  }
14086
- return bufferExports$1.Buffer.from(contents);
12291
+ return bufferExports.Buffer.from(contents);
14087
12292
  }
14088
12293
  const syncQueueRequestSize = fetchStrategy == FetchStrategy.Buffered ? 10 : 1;
14089
12294
  const request = await this.buildRequest(path);
@@ -14323,7 +12528,11 @@ class AbstractRemote {
14323
12528
  };
14324
12529
  const stream = new DataStream({
14325
12530
  logger: this.logger,
14326
- mapLine: mapLine
12531
+ mapLine: mapLine,
12532
+ pressure: {
12533
+ highWaterMark: 20,
12534
+ lowWaterMark: 10
12535
+ }
14327
12536
  });
14328
12537
  abortSignal?.addEventListener('abort', () => {
14329
12538
  closeReader();
@@ -14331,42 +12540,47 @@ class AbstractRemote {
14331
12540
  });
14332
12541
  const decoder = this.createTextDecoder();
14333
12542
  let buffer = '';
14334
- const l = stream.registerListener({
14335
- lowWater: async () => {
14336
- if (stream.closed || abortSignal?.aborted || readerReleased) {
12543
+ const consumeStream = async () => {
12544
+ while (!stream.closed && !abortSignal?.aborted && !readerReleased) {
12545
+ const { done, value } = await reader.read();
12546
+ if (done) {
12547
+ const remaining = buffer.trim();
12548
+ if (remaining.length != 0) {
12549
+ stream.enqueueData(remaining);
12550
+ }
12551
+ stream.close();
12552
+ await closeReader();
14337
12553
  return;
14338
12554
  }
14339
- try {
14340
- let didCompleteLine = false;
14341
- while (!didCompleteLine) {
14342
- const { done, value } = await reader.read();
14343
- if (done) {
14344
- const remaining = buffer.trim();
14345
- if (remaining.length != 0) {
14346
- stream.enqueueData(remaining);
14347
- }
14348
- stream.close();
14349
- await closeReader();
14350
- return;
14351
- }
14352
- const data = decoder.decode(value, { stream: true });
14353
- buffer += data;
14354
- const lines = buffer.split('\n');
14355
- for (var i = 0; i < lines.length - 1; i++) {
14356
- var l = lines[i].trim();
14357
- if (l.length > 0) {
14358
- stream.enqueueData(l);
14359
- didCompleteLine = true;
14360
- }
14361
- }
14362
- buffer = lines[lines.length - 1];
12555
+ const data = decoder.decode(value, { stream: true });
12556
+ buffer += data;
12557
+ const lines = buffer.split('\n');
12558
+ for (var i = 0; i < lines.length - 1; i++) {
12559
+ var l = lines[i].trim();
12560
+ if (l.length > 0) {
12561
+ stream.enqueueData(l);
14363
12562
  }
14364
12563
  }
14365
- catch (ex) {
14366
- stream.close();
14367
- throw ex;
12564
+ buffer = lines[lines.length - 1];
12565
+ // Implement backpressure by waiting for the low water mark to be reached
12566
+ if (stream.dataQueue.length > stream.highWatermark) {
12567
+ await new Promise((resolve) => {
12568
+ const dispose = stream.registerListener({
12569
+ lowWater: async () => {
12570
+ resolve();
12571
+ dispose();
12572
+ },
12573
+ closed: () => {
12574
+ resolve();
12575
+ dispose();
12576
+ }
12577
+ });
12578
+ });
14368
12579
  }
14369
- },
12580
+ }
12581
+ };
12582
+ consumeStream().catch(ex => this.logger.error('Error consuming stream', ex));
12583
+ const l = stream.registerListener({
14370
12584
  closed: () => {
14371
12585
  closeReader();
14372
12586
  l?.();
@@ -14445,18 +12659,17 @@ var SyncClientImplementation;
14445
12659
  *
14446
12660
  * This is the default option.
14447
12661
  *
14448
- * @deprecated Don't use {@link SyncClientImplementation.JAVASCRIPT} directly. Instead, use
14449
- * {@link DEFAULT_SYNC_CLIENT_IMPLEMENTATION} or omit the option. The explicit choice to use
14450
- * the JavaScript-based sync implementation will be removed from a future version of the SDK.
12662
+ * @deprecated We recommend the {@link RUST} client implementation for all apps. If you have issues with
12663
+ * the Rust client, please file an issue or reach out to us. The JavaScript client will be removed in a future
12664
+ * version of the PowerSync SDK.
14451
12665
  */
14452
12666
  SyncClientImplementation["JAVASCRIPT"] = "js";
14453
12667
  /**
14454
12668
  * This implementation offloads the sync line decoding and handling into the PowerSync
14455
12669
  * core extension.
14456
12670
  *
14457
- * @experimental
14458
- * While this implementation is more performant than {@link SyncClientImplementation.JAVASCRIPT},
14459
- * it has seen less real-world testing and is marked as __experimental__ at the moment.
12671
+ * This option is more performant than the {@link JAVASCRIPT} client, enabled by default and the
12672
+ * recommended client implementation for all apps.
14460
12673
  *
14461
12674
  * ## Compatibility warning
14462
12675
  *
@@ -14474,13 +12687,9 @@ var SyncClientImplementation;
14474
12687
  SyncClientImplementation["RUST"] = "rust";
14475
12688
  })(SyncClientImplementation || (SyncClientImplementation = {}));
14476
12689
  /**
14477
- * The default {@link SyncClientImplementation} to use.
14478
- *
14479
- * Please use this field instead of {@link SyncClientImplementation.JAVASCRIPT} directly. A future version
14480
- * of the PowerSync SDK will enable {@link SyncClientImplementation.RUST} by default and remove the JavaScript
14481
- * option.
12690
+ * The default {@link SyncClientImplementation} to use, {@link SyncClientImplementation.RUST}.
14482
12691
  */
14483
- const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.JAVASCRIPT;
12692
+ const DEFAULT_SYNC_CLIENT_IMPLEMENTATION = SyncClientImplementation.RUST;
14484
12693
  const DEFAULT_CRUD_UPLOAD_THROTTLE_MS = 1000;
14485
12694
  const DEFAULT_RETRY_DELAY_MS = 5000;
14486
12695
  const DEFAULT_STREAMING_SYNC_OPTIONS = {
@@ -14890,6 +13099,9 @@ The next upload iteration will be delayed.`);
14890
13099
  if (rawTables != null && rawTables.length) {
14891
13100
  this.logger.warn('Raw tables require the Rust-based sync client. The JS client will ignore them.');
14892
13101
  }
13102
+ if (this.activeStreams.length) {
13103
+ this.logger.error('Sync streams require `clientImplementation: SyncClientImplementation.RUST` when connecting.');
13104
+ }
14893
13105
  this.logger.debug('Streaming sync iteration started');
14894
13106
  this.options.adapter.startSession();
14895
13107
  let [req, bucketMap] = await this.collectLocalBucketState();
@@ -15405,6 +13617,27 @@ The next upload iteration will be delayed.`);
15405
13617
  }
15406
13618
  }
15407
13619
 
13620
+ const CLAIM_STORE = new Map();
13621
+ /**
13622
+ * @internal
13623
+ * @experimental
13624
+ */
13625
+ const MEMORY_TRIGGER_CLAIM_MANAGER = {
13626
+ async obtainClaim(identifier) {
13627
+ if (CLAIM_STORE.has(identifier)) {
13628
+ throw new Error(`A claim is already present for ${identifier}`);
13629
+ }
13630
+ const release = async () => {
13631
+ CLAIM_STORE.delete(identifier);
13632
+ };
13633
+ CLAIM_STORE.set(identifier, release);
13634
+ return release;
13635
+ },
13636
+ async checkClaim(identifier) {
13637
+ return CLAIM_STORE.has(identifier);
13638
+ }
13639
+ };
13640
+
15408
13641
  /**
15409
13642
  * SQLite operations to track changes for with {@link TriggerManager}
15410
13643
  * @experimental
@@ -15416,9 +13649,20 @@ var DiffTriggerOperation;
15416
13649
  DiffTriggerOperation["DELETE"] = "DELETE";
15417
13650
  })(DiffTriggerOperation || (DiffTriggerOperation = {}));
15418
13651
 
13652
+ const DEFAULT_TRIGGER_MANAGER_CONFIGURATION = {
13653
+ useStorageByDefault: false
13654
+ };
13655
+ const TRIGGER_CLEANUP_INTERVAL_MS = 120_000; // 2 minutes
13656
+ /**
13657
+ * @internal
13658
+ * @experimental
13659
+ */
15419
13660
  class TriggerManagerImpl {
15420
13661
  options;
15421
13662
  schema;
13663
+ defaultConfig;
13664
+ cleanupTimeout;
13665
+ isDisposed;
15422
13666
  constructor(options) {
15423
13667
  this.options = options;
15424
13668
  this.schema = options.schema;
@@ -15427,6 +13671,33 @@ class TriggerManagerImpl {
15427
13671
  this.schema = schema;
15428
13672
  }
15429
13673
  });
13674
+ this.isDisposed = false;
13675
+ /**
13676
+ * Configure a cleanup to run on an interval.
13677
+ * The interval is configured using setTimeout to take the async
13678
+ * execution time of the callback into account.
13679
+ */
13680
+ this.defaultConfig = DEFAULT_TRIGGER_MANAGER_CONFIGURATION;
13681
+ const cleanupCallback = async () => {
13682
+ this.cleanupTimeout = null;
13683
+ if (this.isDisposed) {
13684
+ return;
13685
+ }
13686
+ try {
13687
+ await this.cleanupResources();
13688
+ }
13689
+ catch (ex) {
13690
+ this.db.logger.error(`Caught error while attempting to cleanup triggers`, ex);
13691
+ }
13692
+ finally {
13693
+ // if not closed, set another timeout
13694
+ if (this.isDisposed) {
13695
+ return;
13696
+ }
13697
+ this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);
13698
+ }
13699
+ };
13700
+ this.cleanupTimeout = setTimeout(cleanupCallback, TRIGGER_CLEANUP_INTERVAL_MS);
15430
13701
  }
15431
13702
  get db() {
15432
13703
  return this.options.db;
@@ -15444,13 +13715,95 @@ class TriggerManagerImpl {
15444
13715
  await tx.execute(/* sql */ `DROP TRIGGER IF EXISTS ${triggerId}; `);
15445
13716
  }
15446
13717
  }
13718
+ dispose() {
13719
+ this.isDisposed = true;
13720
+ if (this.cleanupTimeout) {
13721
+ clearTimeout(this.cleanupTimeout);
13722
+ }
13723
+ }
13724
+ /**
13725
+ * Updates default config settings for platform specific use-cases.
13726
+ */
13727
+ updateDefaults(config) {
13728
+ this.defaultConfig = {
13729
+ ...this.defaultConfig,
13730
+ ...config
13731
+ };
13732
+ }
13733
+ generateTriggerName(operation, destinationTable, triggerId) {
13734
+ return `__ps_temp_trigger_${operation.toLowerCase()}__${destinationTable}__${triggerId}`;
13735
+ }
13736
+ /**
13737
+ * Cleanup any SQLite triggers or tables that are no longer in use.
13738
+ */
13739
+ async cleanupResources() {
13740
+ // we use the database here since cleanupResources is called during the PowerSyncDatabase initialization
13741
+ await this.db.database.writeLock(async (ctx) => {
13742
+ /**
13743
+ * Note: We only cleanup persisted triggers. These are tracked in the sqlite_master table.
13744
+ * temporary triggers will not be affected by this.
13745
+ * Query all triggers that match our naming pattern
13746
+ */
13747
+ const triggers = await ctx.getAll(/* sql */ `
13748
+ SELECT
13749
+ name
13750
+ FROM
13751
+ sqlite_master
13752
+ WHERE
13753
+ type = 'trigger'
13754
+ AND name LIKE '__ps_temp_trigger_%'
13755
+ `);
13756
+ /** Use regex to extract table names and IDs from trigger names
13757
+ * Trigger naming convention: __ps_temp_trigger_<operation>__<destination_table>__<id>
13758
+ */
13759
+ const triggerPattern = /^__ps_temp_trigger_(?:insert|update|delete)__(.+)__([a-f0-9_]{36})$/i;
13760
+ const trackedItems = new Map();
13761
+ for (const trigger of triggers) {
13762
+ const match = trigger.name.match(triggerPattern);
13763
+ if (match) {
13764
+ const [, table, id] = match;
13765
+ // Collect all trigger names for each id combo
13766
+ const existing = trackedItems.get(id);
13767
+ if (existing) {
13768
+ existing.triggerNames.push(trigger.name);
13769
+ }
13770
+ else {
13771
+ trackedItems.set(id, { table, id, triggerNames: [trigger.name] });
13772
+ }
13773
+ }
13774
+ }
13775
+ for (const trackedItem of trackedItems.values()) {
13776
+ // check if there is anything holding on to this item
13777
+ const hasClaim = await this.options.claimManager.checkClaim(trackedItem.id);
13778
+ if (hasClaim) {
13779
+ // This does not require cleanup
13780
+ continue;
13781
+ }
13782
+ this.db.logger.debug(`Clearing resources for trigger ${trackedItem.id} with table ${trackedItem.table}`);
13783
+ // We need to delete the triggers and table
13784
+ for (const triggerName of trackedItem.triggerNames) {
13785
+ await ctx.execute(`DROP TRIGGER IF EXISTS ${triggerName}`);
13786
+ }
13787
+ await ctx.execute(`DROP TABLE IF EXISTS ${trackedItem.table}`);
13788
+ }
13789
+ });
13790
+ }
15447
13791
  async createDiffTrigger(options) {
15448
13792
  await this.db.waitForReady();
15449
- const { source, destination, columns, when, hooks } = options;
13793
+ const { source, destination, columns, when, hooks,
13794
+ // Fall back to the provided default if not given on this level
13795
+ useStorage = this.defaultConfig.useStorageByDefault } = options;
15450
13796
  const operations = Object.keys(when);
15451
13797
  if (operations.length == 0) {
15452
13798
  throw new Error('At least one WHEN operation must be specified for the trigger.');
15453
13799
  }
13800
+ /**
13801
+ * The clause to use when executing
13802
+ * CREATE ${tableTriggerTypeClause} TABLE
13803
+ * OR
13804
+ * CREATE ${tableTriggerTypeClause} TRIGGER
13805
+ */
13806
+ const tableTriggerTypeClause = !useStorage ? 'TEMP' : '';
15454
13807
  const whenClauses = Object.fromEntries(Object.entries(when).map(([operation, filter]) => [operation, `WHEN ${filter}`]));
15455
13808
  /**
15456
13809
  * Allow specifying the View name as the source.
@@ -15464,6 +13817,7 @@ class TriggerManagerImpl {
15464
13817
  const internalSource = sourceDefinition.internalName;
15465
13818
  const triggerIds = [];
15466
13819
  const id = await this.getUUID();
13820
+ const releaseStorageClaim = useStorage ? await this.options.claimManager.obtainClaim(id) : null;
15467
13821
  /**
15468
13822
  * We default to replicating all columns if no columns array is provided.
15469
13823
  */
@@ -15496,26 +13850,27 @@ class TriggerManagerImpl {
15496
13850
  return this.db.writeLock(async (tx) => {
15497
13851
  await this.removeTriggers(tx, triggerIds);
15498
13852
  await tx.execute(/* sql */ `DROP TABLE IF EXISTS ${destination};`);
13853
+ await releaseStorageClaim?.();
15499
13854
  });
15500
13855
  };
15501
13856
  const setup = async (tx) => {
15502
13857
  // Allow user code to execute in this lock context before the trigger is created.
15503
13858
  await hooks?.beforeCreate?.(tx);
15504
13859
  await tx.execute(/* sql */ `
15505
- CREATE TEMP TABLE ${destination} (
13860
+ CREATE ${tableTriggerTypeClause} TABLE ${destination} (
15506
13861
  operation_id INTEGER PRIMARY KEY AUTOINCREMENT,
15507
13862
  id TEXT,
15508
13863
  operation TEXT,
15509
13864
  timestamp TEXT,
15510
13865
  value TEXT,
15511
13866
  previous_value TEXT
15512
- );
13867
+ )
15513
13868
  `);
15514
13869
  if (operations.includes(DiffTriggerOperation.INSERT)) {
15515
- const insertTriggerId = `ps_temp_trigger_insert_${id}`;
13870
+ const insertTriggerId = this.generateTriggerName(DiffTriggerOperation.INSERT, destination, id);
15516
13871
  triggerIds.push(insertTriggerId);
15517
13872
  await tx.execute(/* sql */ `
15518
- CREATE TEMP TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[DiffTriggerOperation.INSERT]} BEGIN
13873
+ CREATE ${tableTriggerTypeClause} TRIGGER ${insertTriggerId} AFTER INSERT ON ${internalSource} ${whenClauses[DiffTriggerOperation.INSERT]} BEGIN
15519
13874
  INSERT INTO
15520
13875
  ${destination} (id, operation, timestamp, value)
15521
13876
  VALUES
@@ -15526,14 +13881,14 @@ class TriggerManagerImpl {
15526
13881
  ${jsonFragment('NEW')}
15527
13882
  );
15528
13883
 
15529
- END;
13884
+ END
15530
13885
  `);
15531
13886
  }
15532
13887
  if (operations.includes(DiffTriggerOperation.UPDATE)) {
15533
- const updateTriggerId = `ps_temp_trigger_update_${id}`;
13888
+ const updateTriggerId = this.generateTriggerName(DiffTriggerOperation.UPDATE, destination, id);
15534
13889
  triggerIds.push(updateTriggerId);
15535
13890
  await tx.execute(/* sql */ `
15536
- CREATE TEMP TRIGGER ${updateTriggerId} AFTER
13891
+ CREATE ${tableTriggerTypeClause} TRIGGER ${updateTriggerId} AFTER
15537
13892
  UPDATE ON ${internalSource} ${whenClauses[DiffTriggerOperation.UPDATE]} BEGIN
15538
13893
  INSERT INTO
15539
13894
  ${destination} (id, operation, timestamp, value, previous_value)
@@ -15550,11 +13905,11 @@ class TriggerManagerImpl {
15550
13905
  `);
15551
13906
  }
15552
13907
  if (operations.includes(DiffTriggerOperation.DELETE)) {
15553
- const deleteTriggerId = `ps_temp_trigger_delete_${id}`;
13908
+ const deleteTriggerId = this.generateTriggerName(DiffTriggerOperation.DELETE, destination, id);
15554
13909
  triggerIds.push(deleteTriggerId);
15555
13910
  // Create delete trigger for basic JSON
15556
13911
  await tx.execute(/* sql */ `
15557
- CREATE TEMP TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[DiffTriggerOperation.DELETE]} BEGIN
13912
+ CREATE ${tableTriggerTypeClause} TRIGGER ${deleteTriggerId} AFTER DELETE ON ${internalSource} ${whenClauses[DiffTriggerOperation.DELETE]} BEGIN
15558
13913
  INSERT INTO
15559
13914
  ${destination} (id, operation, timestamp, value)
15560
13915
  VALUES
@@ -15598,7 +13953,7 @@ class TriggerManagerImpl {
15598
13953
  // If no array is provided, we use all columns from the source table.
15599
13954
  const contextColumns = columns ?? sourceDefinition.columns.map((col) => col.name);
15600
13955
  const id = await this.getUUID();
15601
- const destination = `ps_temp_track_${source}_${id}`;
13956
+ const destination = `__ps_temp_track_${source}_${id}`;
15602
13957
  // register an onChange before the trigger is created
15603
13958
  const abortController = new AbortController();
15604
13959
  const abortOnChange = () => abortController.abort();
@@ -15753,6 +14108,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
15753
14108
  * Allows creating SQLite triggers which can be used to track various operations on SQLite tables.
15754
14109
  */
15755
14110
  triggers;
14111
+ triggersImpl;
15756
14112
  logger;
15757
14113
  constructor(options) {
15758
14114
  super();
@@ -15816,9 +14172,10 @@ class AbstractPowerSyncDatabase extends BaseObserver {
15816
14172
  logger: this.logger
15817
14173
  });
15818
14174
  this._isReadyPromise = this.initialize();
15819
- this.triggers = new TriggerManagerImpl({
14175
+ this.triggers = this.triggersImpl = new TriggerManagerImpl({
15820
14176
  db: this,
15821
- schema: this.schema
14177
+ schema: this.schema,
14178
+ ...this.generateTriggerManagerConfig()
15822
14179
  });
15823
14180
  }
15824
14181
  /**
@@ -15844,6 +14201,15 @@ class AbstractPowerSyncDatabase extends BaseObserver {
15844
14201
  get connecting() {
15845
14202
  return this.currentStatus?.connecting || false;
15846
14203
  }
14204
+ /**
14205
+ * Generates a base configuration for {@link TriggerManagerImpl}.
14206
+ * Implementations should override this if necessary.
14207
+ */
14208
+ generateTriggerManagerConfig() {
14209
+ return {
14210
+ claimManager: MEMORY_TRIGGER_CLAIM_MANAGER
14211
+ };
14212
+ }
15847
14213
  /**
15848
14214
  * @returns A promise which will resolve once initialization is completed.
15849
14215
  */
@@ -15904,14 +14270,15 @@ class AbstractPowerSyncDatabase extends BaseObserver {
15904
14270
  async initialize() {
15905
14271
  await this._initialize();
15906
14272
  await this.bucketStorageAdapter.init();
15907
- await this._loadVersion();
14273
+ await this.loadVersion();
15908
14274
  await this.updateSchema(this.options.schema);
15909
14275
  await this.resolveOfflineSyncStatus();
15910
14276
  await this.database.execute('PRAGMA RECURSIVE_TRIGGERS=TRUE');
14277
+ await this.triggersImpl.cleanupResources();
15911
14278
  this.ready = true;
15912
14279
  this.iterateListeners((cb) => cb.initialized?.());
15913
14280
  }
15914
- async _loadVersion() {
14281
+ async loadVersion() {
15915
14282
  try {
15916
14283
  const { version } = await this.database.get('SELECT powersync_rs_version() as version');
15917
14284
  this.sdkVersion = version;
@@ -16027,7 +14394,6 @@ class AbstractPowerSyncDatabase extends BaseObserver {
16027
14394
  await this.disconnect();
16028
14395
  await this.waitForReady();
16029
14396
  const { clearLocal } = options;
16030
- // TODO DB name, verify this is necessary with extension
16031
14397
  await this.database.writeTransaction(async (tx) => {
16032
14398
  await tx.execute('SELECT powersync_clear(?)', [clearLocal ? 1 : 0]);
16033
14399
  });
@@ -16059,6 +14425,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
16059
14425
  if (this.closed) {
16060
14426
  return;
16061
14427
  }
14428
+ this.triggersImpl.dispose();
16062
14429
  await this.iterateAsyncListeners(async (cb) => cb.closing?.());
16063
14430
  const { disconnect } = options;
16064
14431
  if (disconnect) {
@@ -17050,6 +15417,27 @@ class SyncDataBatch {
17050
15417
  }
17051
15418
  }
17052
15419
 
15420
+ /**
15421
+ * Thrown when an underlying database connection is closed.
15422
+ * This is particularly relevant when worker connections are marked as closed while
15423
+ * operations are still in progress.
15424
+ */
15425
+ class ConnectionClosedError extends Error {
15426
+ static NAME = 'ConnectionClosedError';
15427
+ static MATCHES(input) {
15428
+ /**
15429
+ * If there are weird package issues which cause multiple versions of classes to be present, the instanceof
15430
+ * check might fail. This also performs a failsafe check.
15431
+ * This might also happen if the Error is serialized and parsed over a bridging channel like a MessagePort.
15432
+ */
15433
+ return (input instanceof ConnectionClosedError || (input instanceof Error && input.name == ConnectionClosedError.NAME));
15434
+ }
15435
+ constructor(message) {
15436
+ super(message);
15437
+ this.name = ConnectionClosedError.NAME;
15438
+ }
15439
+ }
15440
+
17053
15441
  // https://www.sqlite.org/lang_expr.html#castexpr
17054
15442
  var ColumnType;
17055
15443
  (function (ColumnType) {
@@ -17608,13 +15996,13 @@ const parseQuery = (query, parameters) => {
17608
15996
  //# sourceMappingURL=bundle.mjs.map
17609
15997
 
17610
15998
 
17611
- /***/ }),
15999
+ /***/ },
17612
16000
 
17613
- /***/ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js":
16001
+ /***/ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js"
17614
16002
  /*!*************************************************************!*\
17615
16003
  !*** ./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js ***!
17616
16004
  \*************************************************************/
17617
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
16005
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
17618
16006
 
17619
16007
  __webpack_require__.r(__webpack_exports__);
17620
16008
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -17626,9 +16014,9 @@ __webpack_require__.r(__webpack_exports__);
17626
16014
  /* harmony export */ WASQLiteVFS: () => (/* binding */ WASQLiteVFS),
17627
16015
  /* harmony export */ WASqliteConnection: () => (/* binding */ WASqliteConnection)
17628
16016
  /* harmony export */ });
17629
- /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
16017
+ /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
17630
16018
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
17631
- /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! async-mutex */ "../../node_modules/async-mutex/index.mjs");
16019
+ /* harmony import */ var async_mutex__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! async-mutex */ "../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs");
17632
16020
 
17633
16021
 
17634
16022
 
@@ -17645,28 +16033,28 @@ var WASQLiteVFS;
17645
16033
  * @internal
17646
16034
  */
17647
16035
  const AsyncWASQLiteModuleFactory = async () => {
17648
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_dist_wa-sqlite-async_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs */ "../../node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs"));
16036
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-f60d0d").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs"));
17649
16037
  return factory();
17650
16038
  };
17651
16039
  /**
17652
16040
  * @internal
17653
16041
  */
17654
16042
  const MultiCipherAsyncWASQLiteModuleFactory = async () => {
17655
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite-async_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs */ "../../node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs"));
16043
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-3a94cf").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs"));
17656
16044
  return factory();
17657
16045
  };
17658
16046
  /**
17659
16047
  * @internal
17660
16048
  */
17661
16049
  const SyncWASQLiteModuleFactory = async () => {
17662
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite.mjs */ "../../node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs"));
16050
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs"));
17663
16051
  return factory();
17664
16052
  };
17665
16053
  /**
17666
16054
  * @internal
17667
16055
  */
17668
16056
  const MultiCipherSyncWASQLiteModuleFactory = async () => {
17669
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite_mjs").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs */ "../../node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs"));
16057
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-868779").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs"));
17670
16058
  return factory();
17671
16059
  };
17672
16060
  /**
@@ -17681,7 +16069,7 @@ const DEFAULT_MODULE_FACTORIES = {
17681
16069
  else {
17682
16070
  module = await AsyncWASQLiteModuleFactory();
17683
16071
  }
17684
- const { IDBBatchAtomicVFS } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_src_examples_IDBBatchAtomicVFS_js").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js */ "../../node_modules/@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js"));
16072
+ const { IDBBatchAtomicVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-0d2437").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js"));
17685
16073
  return {
17686
16074
  module,
17687
16075
  // @ts-expect-error The types for this static method are missing upstream
@@ -17697,7 +16085,7 @@ const DEFAULT_MODULE_FACTORIES = {
17697
16085
  module = await SyncWASQLiteModuleFactory();
17698
16086
  }
17699
16087
  // @ts-expect-error The types for this static method are missing upstream
17700
- const { AccessHandlePoolVFS } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js */ "../../node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"));
16088
+ const { AccessHandlePoolVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-3622cf").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"));
17701
16089
  return {
17702
16090
  module,
17703
16091
  vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
@@ -17712,10 +16100,11 @@ const DEFAULT_MODULE_FACTORIES = {
17712
16100
  module = await SyncWASQLiteModuleFactory();
17713
16101
  }
17714
16102
  // @ts-expect-error The types for this static method are missing upstream
17715
- const { OPFSCoopSyncVFS } = await __webpack_require__.e(/*! import() */ "node_modules_journeyapps_wa-sqlite_src_examples_OPFSCoopSyncVFS_js").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js */ "../../node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"));
16103
+ const { OPFSCoopSyncVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_4_1_node_modules_journeyapps_wa-sqlite_src_examples-1d4e74").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"));
16104
+ const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
17716
16105
  return {
17717
16106
  module,
17718
- vfs: await OPFSCoopSyncVFS.create(options.dbFileName, module)
16107
+ vfs
17719
16108
  };
17720
16109
  }
17721
16110
  };
@@ -17941,7 +16330,15 @@ class WASqliteConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_1__.
17941
16330
  }
17942
16331
  async close() {
17943
16332
  this.broadcastChannel?.close();
17944
- await this.sqliteAPI.close(this.dbP);
16333
+ await this.acquireExecuteLock(async () => {
16334
+ /**
16335
+ * Running the close operation inside the same execute mutex prevents errors like:
16336
+ * ```
16337
+ * unable to close due to unfinalized statements or unfinished backups
16338
+ * ```
16339
+ */
16340
+ await this.sqliteAPI.close(this.dbP);
16341
+ });
17945
16342
  }
17946
16343
  async registerOnTableChange(callback) {
17947
16344
  return this.registerListener({
@@ -18023,13 +16420,13 @@ class WASqliteConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_1__.
18023
16420
  }
18024
16421
 
18025
16422
 
18026
- /***/ }),
16423
+ /***/ },
18027
16424
 
18028
- /***/ "./lib/src/shared/navigator.js":
16425
+ /***/ "./lib/src/shared/navigator.js"
18029
16426
  /*!*************************************!*\
18030
16427
  !*** ./lib/src/shared/navigator.js ***!
18031
16428
  \*************************************/
18032
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
16429
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
18033
16430
 
18034
16431
  __webpack_require__.r(__webpack_exports__);
18035
16432
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -18043,13 +16440,13 @@ const getNavigatorLocks = () => {
18043
16440
  };
18044
16441
 
18045
16442
 
18046
- /***/ }),
16443
+ /***/ },
18047
16444
 
18048
- /***/ "./lib/src/worker/db/SharedWASQLiteConnection.js":
16445
+ /***/ "./lib/src/worker/db/SharedWASQLiteConnection.js"
18049
16446
  /*!*******************************************************!*\
18050
16447
  !*** ./lib/src/worker/db/SharedWASQLiteConnection.js ***!
18051
16448
  \*******************************************************/
18052
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
16449
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
18053
16450
 
18054
16451
  __webpack_require__.r(__webpack_exports__);
18055
16452
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
@@ -18147,35 +16544,35 @@ class SharedWASQLiteConnection {
18147
16544
  }
18148
16545
 
18149
16546
 
18150
- /***/ }),
16547
+ /***/ },
18151
16548
 
18152
- /***/ "./lib/src/worker/db/WorkerWASQLiteConnection.js":
16549
+ /***/ "./lib/src/worker/db/WorkerWASQLiteConnection.js"
18153
16550
  /*!*******************************************************!*\
18154
16551
  !*** ./lib/src/worker/db/WorkerWASQLiteConnection.js ***!
18155
16552
  \*******************************************************/
18156
- /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => {
16553
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
18157
16554
 
18158
16555
  __webpack_require__.r(__webpack_exports__);
18159
16556
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
18160
16557
  /* harmony export */ WorkerWASQLiteConnection: () => (/* binding */ WorkerWASQLiteConnection)
18161
16558
  /* harmony export */ });
18162
- /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! comlink */ "../../node_modules/comlink/dist/esm/comlink.mjs");
18163
- /* harmony import */ var _db_adapters_wa_sqlite_WASQLiteConnection__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ../../db/adapters/wa-sqlite/WASQLiteConnection */ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js");
16559
+ /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! comlink */ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs");
16560
+ /* harmony import */ var _db_adapters_wa_sqlite_WASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../db/adapters/wa-sqlite/WASQLiteConnection.js */ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js");
18164
16561
 
18165
16562
 
18166
16563
  /**
18167
16564
  * A Small proxy wrapper around the WASqliteConnection.
18168
16565
  * This ensures that certain return types are properly proxied.
18169
16566
  */
18170
- class WorkerWASQLiteConnection extends _db_adapters_wa_sqlite_WASQLiteConnection__WEBPACK_IMPORTED_MODULE_0__.WASqliteConnection {
16567
+ class WorkerWASQLiteConnection extends _db_adapters_wa_sqlite_WASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_1__.WASqliteConnection {
18171
16568
  async registerOnTableChange(callback) {
18172
16569
  // Proxy the callback remove function
18173
- return comlink__WEBPACK_IMPORTED_MODULE_1__.proxy(await super.registerOnTableChange(callback));
16570
+ return comlink__WEBPACK_IMPORTED_MODULE_0__.proxy(await super.registerOnTableChange(callback));
18174
16571
  }
18175
16572
  }
18176
16573
 
18177
16574
 
18178
- /***/ })
16575
+ /***/ }
18179
16576
 
18180
16577
  /******/ });
18181
16578
  /************************************************************************/
@@ -18189,6 +16586,12 @@ class WorkerWASQLiteConnection extends _db_adapters_wa_sqlite_WASQLiteConnection
18189
16586
  /******/ if (cachedModule !== undefined) {
18190
16587
  /******/ return cachedModule.exports;
18191
16588
  /******/ }
16589
+ /******/ // Check if module exists (development only)
16590
+ /******/ if (__webpack_modules__[moduleId] === undefined) {
16591
+ /******/ var e = new Error("Cannot find module '" + moduleId + "'");
16592
+ /******/ e.code = 'MODULE_NOT_FOUND';
16593
+ /******/ throw e;
16594
+ /******/ }
18192
16595
  /******/ // Create a new module (and put it into the cache)
18193
16596
  /******/ var module = __webpack_module_cache__[moduleId] = {
18194
16597
  /******/ // no module.id needed
@@ -18341,12 +16744,12 @@ var __webpack_exports__ = {};
18341
16744
  !*** ./lib/src/worker/db/WASQLiteDB.worker.js ***!
18342
16745
  \************************************************/
18343
16746
  __webpack_require__.r(__webpack_exports__);
18344
- /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
16747
+ /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.4.1/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
18345
16748
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
18346
- /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! comlink */ "../../node_modules/comlink/dist/esm/comlink.mjs");
18347
- /* harmony import */ var _shared_navigator__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../shared/navigator */ "./lib/src/shared/navigator.js");
18348
- /* harmony import */ var _SharedWASQLiteConnection__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./SharedWASQLiteConnection */ "./lib/src/worker/db/SharedWASQLiteConnection.js");
18349
- /* harmony import */ var _WorkerWASQLiteConnection__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./WorkerWASQLiteConnection */ "./lib/src/worker/db/WorkerWASQLiteConnection.js");
16749
+ /* harmony import */ var comlink__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! comlink */ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs");
16750
+ /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
16751
+ /* harmony import */ var _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SharedWASQLiteConnection.js */ "./lib/src/worker/db/SharedWASQLiteConnection.js");
16752
+ /* harmony import */ var _WorkerWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./WorkerWASQLiteConnection.js */ "./lib/src/worker/db/WorkerWASQLiteConnection.js");
18350
16753
  /**
18351
16754
  * Supports both shared and dedicated workers, based on how the worker is constructed (new SharedWorker vs new Worker()).
18352
16755
  */
@@ -18364,14 +16767,14 @@ const OPEN_DB_LOCK = 'open-wasqlite-db';
18364
16767
  let nextClientId = 1;
18365
16768
  const openDBShared = async (options) => {
18366
16769
  // Prevent multiple simultaneous opens from causing race conditions
18367
- return (0,_shared_navigator__WEBPACK_IMPORTED_MODULE_2__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
16770
+ return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
18368
16771
  const clientId = nextClientId++;
18369
16772
  const { dbFilename, logLevel } = options;
18370
16773
  logger.setLevel(logLevel);
18371
16774
  if (!DBMap.has(dbFilename)) {
18372
16775
  const clientIds = new Set();
18373
16776
  // This format returns proxy objects for function callbacks
18374
- const connection = new _WorkerWASQLiteConnection__WEBPACK_IMPORTED_MODULE_4__.WorkerWASQLiteConnection(options);
16777
+ const connection = new _WorkerWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_5__.WorkerWASQLiteConnection(options);
18375
16778
  await connection.init();
18376
16779
  connection.registerListener({
18377
16780
  holdOverwritten: async () => {
@@ -18389,13 +16792,13 @@ const openDBShared = async (options) => {
18389
16792
  });
18390
16793
  }
18391
16794
  // Associates this clientId with the shared connection entry
18392
- const sharedConnection = new _SharedWASQLiteConnection__WEBPACK_IMPORTED_MODULE_3__.SharedWASQLiteConnection({
16795
+ const sharedConnection = new _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__.SharedWASQLiteConnection({
18393
16796
  dbMap: DBMap,
18394
16797
  dbFilename,
18395
16798
  clientId,
18396
16799
  logger
18397
16800
  });
18398
- return comlink__WEBPACK_IMPORTED_MODULE_5__.proxy(sharedConnection);
16801
+ return comlink__WEBPACK_IMPORTED_MODULE_2__.proxy(sharedConnection);
18399
16802
  });
18400
16803
  };
18401
16804
  // Check if we're in a SharedWorker context
@@ -18403,12 +16806,12 @@ if (typeof SharedWorkerGlobalScope !== 'undefined') {
18403
16806
  const _self = self;
18404
16807
  _self.onconnect = function (event) {
18405
16808
  const port = event.ports[0];
18406
- comlink__WEBPACK_IMPORTED_MODULE_5__.expose(openDBShared, port);
16809
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared, port);
18407
16810
  };
18408
16811
  }
18409
16812
  else {
18410
16813
  // A dedicated worker can be shared externally
18411
- comlink__WEBPACK_IMPORTED_MODULE_5__.expose(openDBShared);
16814
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared);
18412
16815
  }
18413
16816
  addEventListener('unload', () => {
18414
16817
  Array.from(DBMap.values()).forEach(async (dbConnection) => {