@powersync/web 0.0.0-dev-20260311103504 → 0.0.0-dev-20260414110516

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 (91) hide show
  1. package/dist/index.umd.js +1126 -1231
  2. package/dist/index.umd.js.map +1 -1
  3. package/dist/worker/SharedSyncImplementation.umd.js +1097 -3519
  4. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  5. package/dist/worker/WASQLiteDB.umd.js +1386 -1329
  6. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  7. package/lib/package.json +3 -4
  8. package/lib/src/db/PowerSyncDatabase.d.ts +1 -2
  9. package/lib/src/db/PowerSyncDatabase.js +3 -4
  10. package/lib/src/db/adapters/AsyncWebAdapter.d.ts +40 -0
  11. package/lib/src/db/adapters/AsyncWebAdapter.js +69 -0
  12. package/lib/src/db/adapters/SSRDBAdapter.d.ts +1 -2
  13. package/lib/src/db/adapters/SSRDBAdapter.js +5 -6
  14. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.d.ts +56 -0
  15. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js +121 -0
  16. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.d.ts +54 -0
  17. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.js +227 -0
  18. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.d.ts +47 -0
  19. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.js +146 -0
  20. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +46 -0
  21. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js +147 -0
  22. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +14 -6
  23. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +66 -39
  24. package/lib/src/db/adapters/wa-sqlite/vfs.d.ts +61 -0
  25. package/lib/src/db/adapters/wa-sqlite/vfs.js +91 -0
  26. package/lib/src/db/adapters/web-sql-flags.d.ts +5 -0
  27. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.d.ts +1 -2
  28. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js +2 -3
  29. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +4 -19
  30. package/lib/src/index.d.ts +1 -4
  31. package/lib/src/index.js +1 -4
  32. package/lib/src/shared/tab_close_signal.d.ts +11 -0
  33. package/lib/src/shared/tab_close_signal.js +26 -0
  34. package/lib/src/worker/db/MultiDatabaseServer.d.ts +17 -0
  35. package/lib/src/worker/db/MultiDatabaseServer.js +86 -0
  36. package/lib/src/worker/db/WASQLiteDB.worker.js +9 -48
  37. package/lib/src/worker/db/open-worker-database.d.ts +3 -3
  38. package/lib/src/worker/db/open-worker-database.js +1 -1
  39. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +5 -6
  40. package/lib/src/worker/sync/SharedSyncImplementation.js +92 -54
  41. package/lib/tsconfig.tsbuildinfo +1 -1
  42. package/package.json +4 -5
  43. package/src/db/PowerSyncDatabase.ts +3 -3
  44. package/src/db/adapters/AsyncWebAdapter.ts +91 -0
  45. package/src/db/adapters/SSRDBAdapter.ts +7 -7
  46. package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +137 -0
  47. package/src/db/adapters/wa-sqlite/DatabaseClient.ts +325 -0
  48. package/src/db/adapters/wa-sqlite/DatabaseServer.ts +201 -0
  49. package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +191 -0
  50. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +87 -43
  51. package/src/db/adapters/wa-sqlite/vfs.ts +112 -0
  52. package/src/db/adapters/web-sql-flags.ts +6 -0
  53. package/src/db/sync/SSRWebStreamingSyncImplementation.ts +2 -3
  54. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +4 -20
  55. package/src/index.ts +1 -4
  56. package/src/shared/tab_close_signal.ts +28 -0
  57. package/src/worker/db/MultiDatabaseServer.ts +104 -0
  58. package/src/worker/db/WASQLiteDB.worker.ts +10 -57
  59. package/src/worker/db/open-worker-database.ts +3 -3
  60. package/src/worker/sync/SharedSyncImplementation.ts +118 -58
  61. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js +0 -1878
  62. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js.map +0 -1
  63. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js +0 -555
  64. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-97ebe9.index.umd.js.map +0 -1
  65. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.d.ts +0 -17
  66. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.js +0 -33
  67. package/lib/src/db/adapters/AsyncDatabaseConnection.d.ts +0 -49
  68. package/lib/src/db/adapters/AsyncDatabaseConnection.js +0 -1
  69. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.d.ts +0 -109
  70. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.js +0 -401
  71. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.d.ts +0 -59
  72. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js +0 -147
  73. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.d.ts +0 -12
  74. package/lib/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.js +0 -19
  75. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.d.ts +0 -155
  76. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js +0 -401
  77. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +0 -32
  78. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +0 -49
  79. package/lib/src/worker/db/SharedWASQLiteConnection.d.ts +0 -42
  80. package/lib/src/worker/db/SharedWASQLiteConnection.js +0 -90
  81. package/lib/src/worker/db/WorkerWASQLiteConnection.d.ts +0 -9
  82. package/lib/src/worker/db/WorkerWASQLiteConnection.js +0 -12
  83. package/src/db/adapters/AbstractWebSQLOpenFactory.ts +0 -48
  84. package/src/db/adapters/AsyncDatabaseConnection.ts +0 -55
  85. package/src/db/adapters/LockedAsyncDatabaseAdapter.ts +0 -490
  86. package/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts +0 -201
  87. package/src/db/adapters/wa-sqlite/InternalWASQLiteDBAdapter.ts +0 -23
  88. package/src/db/adapters/wa-sqlite/WASQLiteConnection.ts +0 -497
  89. package/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.ts +0 -86
  90. package/src/worker/db/SharedWASQLiteConnection.ts +0 -131
  91. package/src/worker/db/WorkerWASQLiteConnection.ts +0 -14
@@ -3,317 +3,6 @@ var sdk_web;
3
3
  /******/ "use strict";
4
4
  /******/ var __webpack_modules__ = ({
5
5
 
6
- /***/ "../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs"
7
- /*!*************************************************************************************!*\
8
- !*** ../../node_modules/.pnpm/async-mutex@0.5.0/node_modules/async-mutex/index.mjs ***!
9
- \*************************************************************************************/
10
- (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
11
-
12
- __webpack_require__.r(__webpack_exports__);
13
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
14
- /* harmony export */ E_ALREADY_LOCKED: () => (/* binding */ E_ALREADY_LOCKED),
15
- /* harmony export */ E_CANCELED: () => (/* binding */ E_CANCELED),
16
- /* harmony export */ E_TIMEOUT: () => (/* binding */ E_TIMEOUT),
17
- /* harmony export */ Mutex: () => (/* binding */ Mutex),
18
- /* harmony export */ Semaphore: () => (/* binding */ Semaphore),
19
- /* harmony export */ tryAcquire: () => (/* binding */ tryAcquire),
20
- /* harmony export */ withTimeout: () => (/* binding */ withTimeout)
21
- /* harmony export */ });
22
- const E_TIMEOUT = new Error('timeout while waiting for mutex to become available');
23
- const E_ALREADY_LOCKED = new Error('mutex already locked');
24
- const E_CANCELED = new Error('request for lock canceled');
25
-
26
- var __awaiter$2 = ( false) || function (thisArg, _arguments, P, generator) {
27
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
28
- return new (P || (P = Promise))(function (resolve, reject) {
29
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
30
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
31
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
32
- step((generator = generator.apply(thisArg, _arguments || [])).next());
33
- });
34
- };
35
- class Semaphore {
36
- constructor(_value, _cancelError = E_CANCELED) {
37
- this._value = _value;
38
- this._cancelError = _cancelError;
39
- this._queue = [];
40
- this._weightedWaiters = [];
41
- }
42
- acquire(weight = 1, priority = 0) {
43
- if (weight <= 0)
44
- throw new Error(`invalid weight ${weight}: must be positive`);
45
- return new Promise((resolve, reject) => {
46
- const task = { resolve, reject, weight, priority };
47
- const i = findIndexFromEnd(this._queue, (other) => priority <= other.priority);
48
- if (i === -1 && weight <= this._value) {
49
- // Needs immediate dispatch, skip the queue
50
- this._dispatchItem(task);
51
- }
52
- else {
53
- this._queue.splice(i + 1, 0, task);
54
- }
55
- });
56
- }
57
- runExclusive(callback_1) {
58
- return __awaiter$2(this, arguments, void 0, function* (callback, weight = 1, priority = 0) {
59
- const [value, release] = yield this.acquire(weight, priority);
60
- try {
61
- return yield callback(value);
62
- }
63
- finally {
64
- release();
65
- }
66
- });
67
- }
68
- waitForUnlock(weight = 1, priority = 0) {
69
- if (weight <= 0)
70
- throw new Error(`invalid weight ${weight}: must be positive`);
71
- if (this._couldLockImmediately(weight, priority)) {
72
- return Promise.resolve();
73
- }
74
- else {
75
- return new Promise((resolve) => {
76
- if (!this._weightedWaiters[weight - 1])
77
- this._weightedWaiters[weight - 1] = [];
78
- insertSorted(this._weightedWaiters[weight - 1], { resolve, priority });
79
- });
80
- }
81
- }
82
- isLocked() {
83
- return this._value <= 0;
84
- }
85
- getValue() {
86
- return this._value;
87
- }
88
- setValue(value) {
89
- this._value = value;
90
- this._dispatchQueue();
91
- }
92
- release(weight = 1) {
93
- if (weight <= 0)
94
- throw new Error(`invalid weight ${weight}: must be positive`);
95
- this._value += weight;
96
- this._dispatchQueue();
97
- }
98
- cancel() {
99
- this._queue.forEach((entry) => entry.reject(this._cancelError));
100
- this._queue = [];
101
- }
102
- _dispatchQueue() {
103
- this._drainUnlockWaiters();
104
- while (this._queue.length > 0 && this._queue[0].weight <= this._value) {
105
- this._dispatchItem(this._queue.shift());
106
- this._drainUnlockWaiters();
107
- }
108
- }
109
- _dispatchItem(item) {
110
- const previousValue = this._value;
111
- this._value -= item.weight;
112
- item.resolve([previousValue, this._newReleaser(item.weight)]);
113
- }
114
- _newReleaser(weight) {
115
- let called = false;
116
- return () => {
117
- if (called)
118
- return;
119
- called = true;
120
- this.release(weight);
121
- };
122
- }
123
- _drainUnlockWaiters() {
124
- if (this._queue.length === 0) {
125
- for (let weight = this._value; weight > 0; weight--) {
126
- const waiters = this._weightedWaiters[weight - 1];
127
- if (!waiters)
128
- continue;
129
- waiters.forEach((waiter) => waiter.resolve());
130
- this._weightedWaiters[weight - 1] = [];
131
- }
132
- }
133
- else {
134
- const queuedPriority = this._queue[0].priority;
135
- for (let weight = this._value; weight > 0; weight--) {
136
- const waiters = this._weightedWaiters[weight - 1];
137
- if (!waiters)
138
- continue;
139
- const i = waiters.findIndex((waiter) => waiter.priority <= queuedPriority);
140
- (i === -1 ? waiters : waiters.splice(0, i))
141
- .forEach((waiter => waiter.resolve()));
142
- }
143
- }
144
- }
145
- _couldLockImmediately(weight, priority) {
146
- return (this._queue.length === 0 || this._queue[0].priority < priority) &&
147
- weight <= this._value;
148
- }
149
- }
150
- function insertSorted(a, v) {
151
- const i = findIndexFromEnd(a, (other) => v.priority <= other.priority);
152
- a.splice(i + 1, 0, v);
153
- }
154
- function findIndexFromEnd(a, predicate) {
155
- for (let i = a.length - 1; i >= 0; i--) {
156
- if (predicate(a[i])) {
157
- return i;
158
- }
159
- }
160
- return -1;
161
- }
162
-
163
- var __awaiter$1 = ( false) || function (thisArg, _arguments, P, generator) {
164
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
165
- return new (P || (P = Promise))(function (resolve, reject) {
166
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
167
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
168
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
169
- step((generator = generator.apply(thisArg, _arguments || [])).next());
170
- });
171
- };
172
- class Mutex {
173
- constructor(cancelError) {
174
- this._semaphore = new Semaphore(1, cancelError);
175
- }
176
- acquire() {
177
- return __awaiter$1(this, arguments, void 0, function* (priority = 0) {
178
- const [, releaser] = yield this._semaphore.acquire(1, priority);
179
- return releaser;
180
- });
181
- }
182
- runExclusive(callback, priority = 0) {
183
- return this._semaphore.runExclusive(() => callback(), 1, priority);
184
- }
185
- isLocked() {
186
- return this._semaphore.isLocked();
187
- }
188
- waitForUnlock(priority = 0) {
189
- return this._semaphore.waitForUnlock(1, priority);
190
- }
191
- release() {
192
- if (this._semaphore.isLocked())
193
- this._semaphore.release();
194
- }
195
- cancel() {
196
- return this._semaphore.cancel();
197
- }
198
- }
199
-
200
- var __awaiter = ( false) || function (thisArg, _arguments, P, generator) {
201
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
202
- return new (P || (P = Promise))(function (resolve, reject) {
203
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
204
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
205
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
206
- step((generator = generator.apply(thisArg, _arguments || [])).next());
207
- });
208
- };
209
- function withTimeout(sync, timeout, timeoutError = E_TIMEOUT) {
210
- return {
211
- acquire: (weightOrPriority, priority) => {
212
- let weight;
213
- if (isSemaphore(sync)) {
214
- weight = weightOrPriority;
215
- }
216
- else {
217
- weight = undefined;
218
- priority = weightOrPriority;
219
- }
220
- if (weight !== undefined && weight <= 0) {
221
- throw new Error(`invalid weight ${weight}: must be positive`);
222
- }
223
- return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
224
- let isTimeout = false;
225
- const handle = setTimeout(() => {
226
- isTimeout = true;
227
- reject(timeoutError);
228
- }, timeout);
229
- try {
230
- const ticket = yield (isSemaphore(sync)
231
- ? sync.acquire(weight, priority)
232
- : sync.acquire(priority));
233
- if (isTimeout) {
234
- const release = Array.isArray(ticket) ? ticket[1] : ticket;
235
- release();
236
- }
237
- else {
238
- clearTimeout(handle);
239
- resolve(ticket);
240
- }
241
- }
242
- catch (e) {
243
- if (!isTimeout) {
244
- clearTimeout(handle);
245
- reject(e);
246
- }
247
- }
248
- }));
249
- },
250
- runExclusive(callback, weight, priority) {
251
- return __awaiter(this, void 0, void 0, function* () {
252
- let release = () => undefined;
253
- try {
254
- const ticket = yield this.acquire(weight, priority);
255
- if (Array.isArray(ticket)) {
256
- release = ticket[1];
257
- return yield callback(ticket[0]);
258
- }
259
- else {
260
- release = ticket;
261
- return yield callback();
262
- }
263
- }
264
- finally {
265
- release();
266
- }
267
- });
268
- },
269
- release(weight) {
270
- sync.release(weight);
271
- },
272
- cancel() {
273
- return sync.cancel();
274
- },
275
- waitForUnlock: (weightOrPriority, priority) => {
276
- let weight;
277
- if (isSemaphore(sync)) {
278
- weight = weightOrPriority;
279
- }
280
- else {
281
- weight = undefined;
282
- priority = weightOrPriority;
283
- }
284
- if (weight !== undefined && weight <= 0) {
285
- throw new Error(`invalid weight ${weight}: must be positive`);
286
- }
287
- return new Promise((resolve, reject) => {
288
- const handle = setTimeout(() => reject(timeoutError), timeout);
289
- (isSemaphore(sync)
290
- ? sync.waitForUnlock(weight, priority)
291
- : sync.waitForUnlock(priority)).then(() => {
292
- clearTimeout(handle);
293
- resolve();
294
- });
295
- });
296
- },
297
- isLocked: () => sync.isLocked(),
298
- getValue: () => sync.getValue(),
299
- setValue: (value) => sync.setValue(value),
300
- };
301
- }
302
- function isSemaphore(sync) {
303
- return sync.getValue !== undefined;
304
- }
305
-
306
- // eslint-disable-next-lisne @typescript-eslint/explicit-module-boundary-types
307
- function tryAcquire(sync, alreadyAcquiredError = E_ALREADY_LOCKED) {
308
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
309
- return withTimeout(sync, 0, alreadyAcquiredError);
310
- }
311
-
312
-
313
-
314
-
315
- /***/ },
316
-
317
6
  /***/ "../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs"
318
7
  /*!****************************************************************************************!*\
319
8
  !*** ../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs ***!
@@ -2409,205 +2098,355 @@ const SQLITE_PREPARE_NO_VTAB = 0x04;
2409
2098
 
2410
2099
  /***/ },
2411
2100
 
2412
- /***/ "./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js"
2413
- /*!*************************************************************!*\
2414
- !*** ./lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js ***!
2415
- \*************************************************************/
2101
+ /***/ "./lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js"
2102
+ /*!***************************************************************!*\
2103
+ !*** ./lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js ***!
2104
+ \***************************************************************/
2416
2105
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2417
2106
 
2418
2107
  __webpack_require__.r(__webpack_exports__);
2419
2108
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2420
- /* harmony export */ AsyncWASQLiteModuleFactory: () => (/* binding */ AsyncWASQLiteModuleFactory),
2421
- /* harmony export */ DEFAULT_MODULE_FACTORIES: () => (/* binding */ DEFAULT_MODULE_FACTORIES),
2422
- /* harmony export */ MultiCipherAsyncWASQLiteModuleFactory: () => (/* binding */ MultiCipherAsyncWASQLiteModuleFactory),
2423
- /* harmony export */ MultiCipherSyncWASQLiteModuleFactory: () => (/* binding */ MultiCipherSyncWASQLiteModuleFactory),
2424
- /* harmony export */ SyncWASQLiteModuleFactory: () => (/* binding */ SyncWASQLiteModuleFactory),
2425
- /* harmony export */ WASQLiteVFS: () => (/* binding */ WASQLiteVFS),
2426
- /* harmony export */ WASqliteConnection: () => (/* binding */ WASqliteConnection)
2109
+ /* harmony export */ ConcurrentSqliteConnection: () => (/* binding */ ConcurrentSqliteConnection),
2110
+ /* harmony export */ ConnectionLeaseToken: () => (/* binding */ ConnectionLeaseToken)
2427
2111
  /* harmony export */ });
2428
- /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
2429
- /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
2430
- /* 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");
2112
+ /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
2431
2113
 
2432
-
2433
-
2434
- /**
2435
- * List of currently tested virtual filesystems
2436
- */
2437
- var WASQLiteVFS;
2438
- (function (WASQLiteVFS) {
2439
- WASQLiteVFS["IDBBatchAtomicVFS"] = "IDBBatchAtomicVFS";
2440
- WASQLiteVFS["OPFSCoopSyncVFS"] = "OPFSCoopSyncVFS";
2441
- WASQLiteVFS["AccessHandlePoolVFS"] = "AccessHandlePoolVFS";
2442
- })(WASQLiteVFS || (WASQLiteVFS = {}));
2443
- /**
2444
- * @internal
2445
- */
2446
- const AsyncWASQLiteModuleFactory = async () => {
2447
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs"));
2448
- return factory();
2449
- };
2450
- /**
2451
- * @internal
2452
- */
2453
- const MultiCipherAsyncWASQLiteModuleFactory = async () => {
2454
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs"));
2455
- return factory();
2456
- };
2457
- /**
2458
- * @internal
2459
- */
2460
- const SyncWASQLiteModuleFactory = async () => {
2461
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_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.5.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs"));
2462
- return factory();
2463
- };
2464
- /**
2465
- * @internal
2466
- */
2467
- const MultiCipherSyncWASQLiteModuleFactory = async () => {
2468
- const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs"));
2469
- return factory();
2470
- };
2471
- /**
2472
- * @internal
2473
- */
2474
- const DEFAULT_MODULE_FACTORIES = {
2475
- [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {
2476
- let module;
2477
- if (options.encryptionKey) {
2478
- module = await MultiCipherAsyncWASQLiteModuleFactory();
2479
- }
2480
- else {
2481
- module = await AsyncWASQLiteModuleFactory();
2482
- }
2483
- const { IDBBatchAtomicVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js"));
2484
- return {
2485
- module,
2486
- // @ts-expect-error The types for this static method are missing upstream
2487
- vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })
2488
- };
2489
- },
2490
- [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {
2491
- let module;
2492
- if (options.encryptionKey) {
2493
- module = await MultiCipherSyncWASQLiteModuleFactory();
2494
- }
2495
- else {
2496
- module = await SyncWASQLiteModuleFactory();
2497
- }
2498
- // @ts-expect-error The types for this static method are missing upstream
2499
- const { AccessHandlePoolVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"));
2500
- return {
2501
- module,
2502
- vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
2503
- };
2504
- },
2505
- [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {
2506
- let module;
2507
- if (options.encryptionKey) {
2508
- module = await MultiCipherSyncWASQLiteModuleFactory();
2509
- }
2510
- else {
2511
- module = await SyncWASQLiteModuleFactory();
2512
- }
2513
- // @ts-expect-error The types for this static method are missing upstream
2514
- const { OPFSCoopSyncVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"));
2515
- const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
2516
- return {
2517
- module,
2518
- vfs
2519
- };
2520
- }
2521
- };
2522
2114
  /**
2523
- * @internal
2524
- * WA-SQLite connection which directly interfaces with WA-SQLite.
2525
- * This is usually instantiated inside a worker.
2115
+ * A wrapper around a {@link RawSqliteConnection} allowing multiple tabs to access it.
2116
+ *
2117
+ * To allow potentially concurrent accesses from different clients, this requires a local mutex implementation here.
2118
+ *
2119
+ * Note that instances of this class are not safe to proxy across context boundaries with comlink! We need to be able to
2120
+ * rely on mutexes being returned reliably, so additional checks to detect say a client tab closing are required to
2121
+ * avoid deadlocks.
2526
2122
  */
2527
- class WASqliteConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_1__.BaseObserver {
2528
- options;
2529
- _sqliteAPI = null;
2530
- _dbP = null;
2531
- _moduleFactory;
2532
- updatedTables;
2533
- updateTimer;
2534
- statementMutex;
2535
- broadcastChannel;
2123
+ class ConcurrentSqliteConnection {
2124
+ inner;
2536
2125
  /**
2537
- * Unique id for this specific connection. This is used to prevent broadcast table change
2538
- * notification loops.
2126
+ * An outer mutex ensuring at most one {@link ConnectionLeaseToken} can exist for this connection at a time.
2127
+ *
2128
+ * If null, we'll use navigator locks instead.
2539
2129
  */
2540
- connectionId;
2541
- _holdCounter;
2542
- _holdId;
2543
- constructor(options) {
2544
- super();
2545
- this.options = options;
2546
- this.updatedTables = new Set();
2547
- this.updateTimer = null;
2548
- this.broadcastChannel = null;
2549
- this.connectionId = new Date().valueOf() + Math.random();
2550
- this.statementMutex = new async_mutex__WEBPACK_IMPORTED_MODULE_2__.Mutex();
2551
- this._moduleFactory = DEFAULT_MODULE_FACTORIES[this.options.vfs];
2552
- this._holdCounter = 0;
2553
- this._holdId = null;
2554
- }
2130
+ leaseMutex;
2555
2131
  /**
2556
- * Gets the id for the current hold.
2557
- * This can be used to check for invalid states.
2132
+ * @param needsNavigatorLocks Whether access to the database needs an additional navigator lock guard.
2133
+ *
2134
+ * While {@link ConcurrentSqliteConnection} prevents concurrent access to a database _connection_, it's possible we
2135
+ * might have multiple connections to the same physical database (e.g. if multiple tabs use dedicated workers).
2136
+ * In those setups, we use navigator locks instead of an internal mutex to guard access..
2558
2137
  */
2559
- get currentHoldId() {
2560
- return this._holdId;
2138
+ constructor(inner, needsNavigatorLocks) {
2139
+ this.inner = inner;
2140
+ this.leaseMutex = needsNavigatorLocks ? null : new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.Mutex();
2561
2141
  }
2562
- get sqliteAPI() {
2563
- if (!this._sqliteAPI) {
2564
- throw new Error(`Initialization has not completed`);
2565
- }
2566
- return this._sqliteAPI;
2142
+ get options() {
2143
+ return this.inner.options;
2567
2144
  }
2568
- get dbP() {
2569
- if (!this._dbP) {
2570
- throw new Error(`Initialization has not completed`);
2145
+ acquireMutex(abort) {
2146
+ if (this.leaseMutex) {
2147
+ return this.leaseMutex.acquire(abort);
2571
2148
  }
2572
- return this._dbP;
2149
+ return new Promise((resolve, reject) => {
2150
+ const options = { signal: abort };
2151
+ navigator.locks
2152
+ .request(`db-lock-${this.options.dbFilename}`, options, (_) => {
2153
+ return new Promise((returnLock) => {
2154
+ return resolve(() => {
2155
+ returnLock();
2156
+ });
2157
+ });
2158
+ })
2159
+ .catch(reject);
2160
+ });
2161
+ }
2162
+ // Unsafe, unguarded access to the SQLite connection.
2163
+ unsafeUseInner() {
2164
+ return this.inner;
2573
2165
  }
2574
2166
  /**
2575
- * Checks if the database connection is in autocommit mode.
2576
- * @returns true if in autocommit mode, false if in a transaction
2167
+ * @returns A {@link ConnectionLeaseToken}. Until that token is returned, no other client can use the database.
2577
2168
  */
2578
- async isAutoCommit() {
2579
- return this.sqliteAPI.get_autocommit(this.dbP) != 0;
2580
- }
2581
- async markHold() {
2582
- const previousHoldId = this._holdId;
2583
- this._holdId = `${++this._holdCounter}`;
2584
- if (previousHoldId) {
2585
- await this.iterateAsyncListeners(async (cb) => cb.holdOverwritten?.(previousHoldId));
2169
+ async acquireConnection(abort) {
2170
+ const returnMutex = await this.acquireMutex(abort);
2171
+ const token = new ConnectionLeaseToken(returnMutex, this.inner);
2172
+ try {
2173
+ // Assert that the inner connection is initialized at this point, fail early if it's not.
2174
+ this.inner.requireSqlite();
2175
+ // If a previous client was interrupted in the middle of a transaction AND this is a shared worker, it's possible
2176
+ // for the connection to still be in a transaction. To avoid inconsistent state, we roll back connection leases
2177
+ // that haven't been comitted.
2178
+ if (!this.inner.isAutoCommit()) {
2179
+ await this.inner.executeRaw('ROLLBACK');
2180
+ }
2586
2181
  }
2587
- return this._holdId;
2182
+ catch (e) {
2183
+ returnMutex();
2184
+ throw e;
2185
+ }
2186
+ return token;
2588
2187
  }
2589
- async releaseHold(holdId) {
2590
- if (holdId != this._holdId) {
2591
- throw new Error(`Invalid hold state, expected ${this._holdId} but got ${holdId}`);
2188
+ async close() {
2189
+ const returnMutex = await this.acquireMutex();
2190
+ try {
2191
+ await this.inner.close();
2192
+ }
2193
+ finally {
2194
+ returnMutex();
2592
2195
  }
2593
- this._holdId = null;
2594
2196
  }
2595
- async openDB() {
2596
- this._dbP = await this.sqliteAPI.open_v2(this.options.dbFilename);
2597
- return this._dbP;
2197
+ }
2198
+ /**
2199
+ * An instance representing temporary exclusive access to a {@link ConcurrentSqliteConnection}.
2200
+ */
2201
+ class ConnectionLeaseToken {
2202
+ returnMutex;
2203
+ connection;
2204
+ /** Ensures that the client with access to this token can't run statements concurrently. */
2205
+ useMutex = new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.Mutex();
2206
+ closed = false;
2207
+ constructor(returnMutex, connection) {
2208
+ this.returnMutex = returnMutex;
2209
+ this.connection = connection;
2598
2210
  }
2599
- async executeEncryptionPragma() {
2600
- if (this.options.encryptionKey) {
2601
- await this.executeSingleStatement(`PRAGMA key = "${this.options.encryptionKey}"`);
2602
- }
2603
- return;
2211
+ /**
2212
+ * Returns this lease, allowing another client to use the database connection.
2213
+ */
2214
+ async returnLease() {
2215
+ await this.useMutex.runExclusive(async () => {
2216
+ if (!this.closed) {
2217
+ this.closed = true;
2218
+ this.returnMutex();
2219
+ }
2220
+ });
2221
+ }
2222
+ /**
2223
+ * This should only be used internally, since the callback must not use the raw connection after resolving.
2224
+ */
2225
+ async use(callback) {
2226
+ return await this.useMutex.runExclusive(async () => {
2227
+ if (this.closed) {
2228
+ throw new Error('lease token has already been closed');
2229
+ }
2230
+ return await callback(this.connection);
2231
+ });
2232
+ }
2233
+ }
2234
+
2235
+
2236
+ /***/ },
2237
+
2238
+ /***/ "./lib/src/db/adapters/wa-sqlite/DatabaseServer.js"
2239
+ /*!*********************************************************!*\
2240
+ !*** ./lib/src/db/adapters/wa-sqlite/DatabaseServer.js ***!
2241
+ \*********************************************************/
2242
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2243
+
2244
+ __webpack_require__.r(__webpack_exports__);
2245
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2246
+ /* harmony export */ DatabaseServer: () => (/* binding */ DatabaseServer)
2247
+ /* harmony export */ });
2248
+ /**
2249
+ * Access to a WA-sqlite connection that can be shared with multiple clients sending queries over an RPC protocol built
2250
+ * with the Comlink package.
2251
+ */
2252
+ class DatabaseServer {
2253
+ #options;
2254
+ #nextClientId = 0;
2255
+ #activeClients = new Set();
2256
+ // TODO: Don't use a broadcast channel for connections managed by a shared worker.
2257
+ #updateBroadcastChannel;
2258
+ #clientTableListeners = new Set();
2259
+ constructor(options) {
2260
+ this.#options = options;
2261
+ const inner = options.inner;
2262
+ this.#updateBroadcastChannel = new BroadcastChannel(`${inner.options.dbFilename}-table-updates`);
2263
+ this.#updateBroadcastChannel.onmessage = ({ data }) => {
2264
+ this.#pushTableUpdateToClients(data);
2265
+ };
2266
+ }
2267
+ #pushTableUpdateToClients(changedTables) {
2268
+ for (const listener of this.#clientTableListeners) {
2269
+ listener.postMessage(changedTables);
2270
+ }
2271
+ }
2272
+ get #inner() {
2273
+ return this.#options.inner;
2274
+ }
2275
+ get #logger() {
2276
+ return this.#options.logger;
2277
+ }
2278
+ /**
2279
+ * Called by clients when they wish to connect to this database.
2280
+ *
2281
+ * @param lockName A lock that is currently held by the client. When the lock is returned, we know the client is gone
2282
+ * and that we need to clean up resources.
2283
+ */
2284
+ async connect(lockName) {
2285
+ let isOpen = true;
2286
+ const clientId = this.#nextClientId++;
2287
+ this.#activeClients.add(clientId);
2288
+ let connectionLeases = new Map();
2289
+ let currentTableListener;
2290
+ function requireOpen() {
2291
+ if (!isOpen) {
2292
+ throw new Error('Client has already been closed');
2293
+ }
2294
+ }
2295
+ function requireOpenAndLease(lease) {
2296
+ requireOpen();
2297
+ const token = connectionLeases.get(lease);
2298
+ if (!token) {
2299
+ throw new Error('Attempted to use a connection lease that has already been returned.');
2300
+ }
2301
+ return token;
2302
+ }
2303
+ const close = async () => {
2304
+ if (isOpen) {
2305
+ isOpen = false;
2306
+ if (currentTableListener) {
2307
+ this.#clientTableListeners.delete(currentTableListener);
2308
+ }
2309
+ // If the client holds a connection lease it hasn't returned, return that now.
2310
+ for (const { lease } of connectionLeases.values()) {
2311
+ this.#logger.debug(`Closing connection lease that hasn't been returned.`);
2312
+ await lease.returnLease();
2313
+ }
2314
+ this.#activeClients.delete(clientId);
2315
+ if (this.#activeClients.size == 0) {
2316
+ await this.forceClose();
2317
+ }
2318
+ else {
2319
+ this.#logger.debug('Keeping underlying connection active since its used by other clients.');
2320
+ }
2321
+ }
2322
+ };
2323
+ if (lockName) {
2324
+ navigator.locks.request(lockName, {}, () => {
2325
+ close();
2326
+ });
2327
+ }
2328
+ return {
2329
+ close,
2330
+ debugIsAutoCommit: async () => {
2331
+ return this.#inner.unsafeUseInner().isAutoCommit();
2332
+ },
2333
+ requestAccess: async (write, timeoutMs) => {
2334
+ requireOpen();
2335
+ // TODO: Support timeouts, they don't seem to be supported by the async-mutex package.
2336
+ const lease = await this.#inner.acquireConnection();
2337
+ if (!isOpen) {
2338
+ // Race between requestAccess and close(), the connection was closed while we tried to acquire a lease.
2339
+ await lease.returnLease();
2340
+ return requireOpen();
2341
+ }
2342
+ const token = crypto.randomUUID();
2343
+ connectionLeases.set(token, { lease, write });
2344
+ return token;
2345
+ },
2346
+ completeAccess: async (token) => {
2347
+ const lease = requireOpenAndLease(token);
2348
+ connectionLeases.delete(token);
2349
+ try {
2350
+ if (lease.write) {
2351
+ // Collect update hooks invoked while the client had the write connection.
2352
+ const { resultSet } = await lease.lease.use((conn) => conn.execute(`SELECT powersync_update_hooks('get')`));
2353
+ if (resultSet) {
2354
+ const updatedTables = JSON.parse(resultSet.rows[0][0]);
2355
+ if (updatedTables.length) {
2356
+ this.#updateBroadcastChannel.postMessage(updatedTables);
2357
+ this.#pushTableUpdateToClients(updatedTables);
2358
+ }
2359
+ }
2360
+ }
2361
+ }
2362
+ finally {
2363
+ await lease.lease.returnLease();
2364
+ }
2365
+ },
2366
+ execute: async (token, sql, params) => {
2367
+ const { lease } = requireOpenAndLease(token);
2368
+ return await lease.use((db) => db.execute(sql, params));
2369
+ },
2370
+ executeBatch: async (token, sql, params) => {
2371
+ const { lease } = requireOpenAndLease(token);
2372
+ return await lease.use((db) => db.executeBatch(sql, params));
2373
+ },
2374
+ setUpdateListener: async (listener) => {
2375
+ requireOpen();
2376
+ if (currentTableListener) {
2377
+ this.#clientTableListeners.delete(currentTableListener);
2378
+ }
2379
+ currentTableListener = listener;
2380
+ if (listener) {
2381
+ this.#clientTableListeners.add(listener);
2382
+ }
2383
+ }
2384
+ };
2385
+ }
2386
+ async forceClose() {
2387
+ this.#logger.debug(`Closing connection to ${this.#inner.options}.`);
2388
+ const connection = this.#inner;
2389
+ this.#options.onClose();
2390
+ this.#updateBroadcastChannel.close();
2391
+ await connection.close();
2392
+ }
2393
+ }
2394
+
2395
+
2396
+ /***/ },
2397
+
2398
+ /***/ "./lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js"
2399
+ /*!**************************************************************!*\
2400
+ !*** ./lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js ***!
2401
+ \**************************************************************/
2402
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2403
+
2404
+ __webpack_require__.r(__webpack_exports__);
2405
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2406
+ /* harmony export */ RawSqliteConnection: () => (/* binding */ RawSqliteConnection)
2407
+ /* harmony export */ });
2408
+ /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
2409
+ /* harmony import */ var _vfs_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./vfs.js */ "./lib/src/db/adapters/wa-sqlite/vfs.js");
2410
+
2411
+
2412
+ /**
2413
+ * A small wrapper around WA-sqlite to help with opening databases and running statements by preparing them internally.
2414
+ *
2415
+ * This is an internal class, and it must never be used directly. Wrappers are required to ensure raw connections aren't
2416
+ * used concurrently across tabs.
2417
+ */
2418
+ class RawSqliteConnection {
2419
+ options;
2420
+ _sqliteAPI = null;
2421
+ /**
2422
+ * The `sqlite3*` connection pointer.
2423
+ */
2424
+ db = 0;
2425
+ _moduleFactory;
2426
+ constructor(options) {
2427
+ this.options = options;
2428
+ this._moduleFactory = _vfs_js__WEBPACK_IMPORTED_MODULE_1__.DEFAULT_MODULE_FACTORIES[this.options.vfs];
2429
+ }
2430
+ get isOpen() {
2431
+ return this.db != 0;
2432
+ }
2433
+ async init() {
2434
+ const api = (this._sqliteAPI = await this.openSQLiteAPI());
2435
+ this.db = await api.open_v2(this.options.dbFilename);
2436
+ await this.executeRaw(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
2437
+ if (this.options.encryptionKey) {
2438
+ const escapedKey = this.options.encryptionKey.replace("'", "''");
2439
+ await this.executeRaw(`PRAGMA key = '${escapedKey}'`);
2440
+ }
2441
+ await this.executeRaw(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
2442
+ await this.executeRaw(`SELECT powersync_update_hooks('install');`);
2604
2443
  }
2605
2444
  async openSQLiteAPI() {
2606
2445
  const { module, vfs } = await this._moduleFactory({
2607
2446
  dbFileName: this.options.dbFilename,
2608
2447
  encryptionKey: this.options.encryptionKey
2609
2448
  });
2610
- const sqlite3 = _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.Factory(module);
2449
+ const sqlite3 = (0,_journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.Factory)(module);
2611
2450
  sqlite3.vfs_register(vfs, true);
2612
2451
  /**
2613
2452
  * Register the PowerSync core SQLite extension
@@ -2624,202 +2463,61 @@ class WASqliteConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_1__.
2624
2463
  }
2625
2464
  return sqlite3;
2626
2465
  }
2627
- registerBroadcastListeners() {
2628
- this.broadcastChannel = new BroadcastChannel(`${this.options.dbFilename}-table-updates`);
2629
- this.broadcastChannel.addEventListener('message', (event) => {
2630
- const data = event.data;
2631
- if (this.connectionId == data.connectionId) {
2632
- // Ignore messages from the same connection
2633
- return;
2634
- }
2635
- // Ensuring that we don't rebroadcast the same message
2636
- this.queueTableUpdate(data.changedTables, false);
2637
- });
2638
- }
2639
- queueTableUpdate(tableNames, shouldBroadcast = true) {
2640
- tableNames.forEach((tableName) => this.updatedTables.add(tableName));
2641
- if (this.updateTimer == null) {
2642
- this.updateTimer = setTimeout(() => this.fireUpdates(shouldBroadcast), 0);
2643
- }
2644
- }
2645
- async init() {
2646
- this._sqliteAPI = await this.openSQLiteAPI();
2647
- await this.openDB();
2648
- this.registerBroadcastListeners();
2649
- await this.executeSingleStatement(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
2650
- await this.executeEncryptionPragma();
2651
- await this.executeSingleStatement(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
2652
- this.sqliteAPI.update_hook(this.dbP, (updateType, dbName, tableName) => {
2653
- if (!tableName) {
2654
- return;
2655
- }
2656
- const changedTables = new Set([tableName]);
2657
- this.queueTableUpdate(changedTables);
2658
- });
2659
- }
2660
- async getConfig() {
2661
- return this.options;
2662
- }
2663
- fireUpdates(shouldBroadcast = true) {
2664
- this.updateTimer = null;
2665
- const event = { tables: [...this.updatedTables], groupedUpdates: {}, rawUpdates: [] };
2666
- // Share to other connections
2667
- if (shouldBroadcast) {
2668
- this.broadcastChannel.postMessage({
2669
- changedTables: this.updatedTables,
2670
- connectionId: this.connectionId
2671
- });
2466
+ requireSqlite() {
2467
+ if (!this._sqliteAPI) {
2468
+ throw new Error(`Initialization has not completed`);
2672
2469
  }
2673
- this.updatedTables.clear();
2674
- this.iterateListeners((cb) => cb.tablesUpdated?.(event));
2470
+ return this._sqliteAPI;
2675
2471
  }
2676
2472
  /**
2677
- * This executes SQL statements in a batch.
2473
+ * Checks if the database connection is in autocommit mode.
2474
+ * @returns true if in autocommit mode, false if in a transaction
2678
2475
  */
2679
- async executeBatch(sql, bindings) {
2680
- return this.acquireExecuteLock(async () => {
2681
- let affectedRows = 0;
2682
- try {
2683
- await this.executeSingleStatement('BEGIN TRANSACTION');
2684
- const wrappedBindings = bindings ? bindings : [];
2685
- for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
2686
- if (stmt === null) {
2687
- return {
2688
- rowsAffected: 0,
2689
- rows: { _array: [], length: 0 }
2690
- };
2691
- }
2692
- //Prepare statement once
2693
- for (const binding of wrappedBindings) {
2694
- // TODO not sure why this is needed currently, but booleans break
2695
- for (let i = 0; i < binding.length; i++) {
2696
- const b = binding[i];
2697
- if (typeof b == 'boolean') {
2698
- binding[i] = b ? 1 : 0;
2699
- }
2700
- }
2701
- if (bindings) {
2702
- this.sqliteAPI.bind_collection(stmt, binding);
2703
- }
2704
- const result = await this.sqliteAPI.step(stmt);
2705
- if (result === _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.SQLITE_DONE) {
2706
- //The value returned by sqlite3_changes() immediately after an INSERT, UPDATE or DELETE statement run on a view is always zero.
2707
- affectedRows += this.sqliteAPI.changes(this.dbP);
2708
- }
2709
- this.sqliteAPI.reset(stmt);
2710
- }
2711
- }
2712
- await this.executeSingleStatement('COMMIT');
2713
- }
2714
- catch (err) {
2715
- await this.executeSingleStatement('ROLLBACK');
2716
- return {
2717
- rowsAffected: 0,
2718
- rows: { _array: [], length: 0 }
2719
- };
2720
- }
2721
- const result = {
2722
- rowsAffected: affectedRows,
2723
- rows: { _array: [], length: 0 }
2724
- };
2725
- return result;
2726
- });
2476
+ isAutoCommit() {
2477
+ return this.requireSqlite().get_autocommit(this.db) != 0;
2727
2478
  }
2728
- /**
2729
- * This executes single SQL statements inside a requested lock.
2730
- */
2731
2479
  async execute(sql, bindings) {
2732
- // Running multiple statements on the same connection concurrently should not be allowed
2733
- return this.acquireExecuteLock(async () => {
2734
- return this.executeSingleStatement(sql, bindings);
2735
- });
2736
- }
2737
- async executeRaw(sql, bindings) {
2738
- return this.acquireExecuteLock(async () => {
2739
- return this.executeSingleStatementRaw(sql, bindings);
2740
- });
2741
- }
2742
- async close() {
2743
- this.broadcastChannel?.close();
2744
- await this.acquireExecuteLock(async () => {
2745
- /**
2746
- * Running the close operation inside the same execute mutex prevents errors like:
2747
- * ```
2748
- * unable to close due to unfinalized statements or unfinished backups
2749
- * ```
2750
- */
2751
- await this.sqliteAPI.close(this.dbP);
2752
- });
2753
- }
2754
- async registerOnTableChange(callback) {
2755
- return this.registerListener({
2756
- tablesUpdated: (event) => callback(event)
2757
- });
2480
+ const resultSet = await this.executeSingleStatementRaw(sql, bindings);
2481
+ return this.wrapQueryResults(this.requireSqlite(), resultSet);
2758
2482
  }
2759
- /**
2760
- * This requests a lock for executing statements.
2761
- * Should only be used internally.
2762
- */
2763
- acquireExecuteLock = (callback) => {
2764
- return this.statementMutex.runExclusive(callback);
2765
- };
2766
- /**
2767
- * This executes a single statement using SQLite3.
2768
- */
2769
- async executeSingleStatement(sql, bindings) {
2770
- const results = await this._execute(sql, bindings);
2771
- const rows = [];
2772
- for (const resultSet of results) {
2773
- for (const row of resultSet.rows) {
2774
- const outRow = {};
2775
- resultSet.columns.forEach((key, index) => {
2776
- outRow[key] = row[index];
2777
- });
2778
- rows.push(outRow);
2483
+ async executeBatch(sql, bindings) {
2484
+ const results = [];
2485
+ const api = this.requireSqlite();
2486
+ for await (const stmt of api.statements(this.db, sql)) {
2487
+ let columns;
2488
+ for (const parameterSet of bindings) {
2489
+ const rs = await this.stepThroughStatement(api, stmt, parameterSet, columns, false);
2490
+ results.push(this.wrapQueryResults(api, rs));
2779
2491
  }
2492
+ // executeBatch can only use a single statement
2493
+ break;
2780
2494
  }
2781
- const result = {
2782
- insertId: this.sqliteAPI.last_insert_id(this.dbP),
2783
- rowsAffected: this.sqliteAPI.changes(this.dbP),
2784
- rows: {
2785
- _array: rows,
2786
- length: rows.length
2787
- }
2495
+ return results;
2496
+ }
2497
+ wrapQueryResults(api, rs) {
2498
+ return {
2499
+ changes: api.changes(this.db),
2500
+ lastInsertRowId: api.last_insert_id(this.db),
2501
+ autocommit: api.get_autocommit(this.db) != 0,
2502
+ resultSet: rs
2788
2503
  };
2789
- return result;
2790
2504
  }
2791
2505
  /**
2792
- * This executes a single statement using SQLite3 and returns the results as an array of arrays.
2506
+ * This executes a single statement using SQLite3 and returns the results as a {@link RawResultSet}.
2793
2507
  */
2794
2508
  async executeSingleStatementRaw(sql, bindings) {
2795
- const results = await this._execute(sql, bindings);
2796
- return results.flatMap((resultset) => resultset.rows.map((row) => resultset.columns.map((_, index) => row[index])));
2509
+ const results = await this.executeRaw(sql, bindings);
2510
+ return results.length ? results[0] : undefined;
2797
2511
  }
2798
- async _execute(sql, bindings) {
2512
+ async executeRaw(sql, bindings) {
2799
2513
  const results = [];
2800
- for await (const stmt of this.sqliteAPI.statements(this.dbP, sql)) {
2514
+ const api = this.requireSqlite();
2515
+ for await (const stmt of api.statements(this.db, sql)) {
2801
2516
  let columns;
2802
- const wrappedBindings = bindings ? [bindings] : [[]];
2803
- for (const binding of wrappedBindings) {
2804
- // TODO not sure why this is needed currently, but booleans break
2805
- binding.forEach((b, index, arr) => {
2806
- if (typeof b == 'boolean') {
2807
- arr[index] = b ? 1 : 0;
2808
- }
2809
- });
2810
- this.sqliteAPI.reset(stmt);
2811
- if (bindings) {
2812
- this.sqliteAPI.bind_collection(stmt, binding);
2813
- }
2814
- const rows = [];
2815
- while ((await this.sqliteAPI.step(stmt)) === _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.SQLITE_ROW) {
2816
- const row = this.sqliteAPI.row(stmt);
2817
- rows.push(row);
2818
- }
2819
- columns = columns ?? this.sqliteAPI.column_names(stmt);
2820
- if (columns.length) {
2821
- results.push({ columns, rows });
2822
- }
2517
+ const rs = await this.stepThroughStatement(api, stmt, bindings ?? [], columns);
2518
+ columns = rs.columns;
2519
+ if (columns.length) {
2520
+ results.push(rs);
2823
2521
  }
2824
2522
  // When binding parameters, only a single statement is executed.
2825
2523
  if (bindings) {
@@ -2828,159 +2526,271 @@ class WASqliteConnection extends _powersync_common__WEBPACK_IMPORTED_MODULE_1__.
2828
2526
  }
2829
2527
  return results;
2830
2528
  }
2529
+ async stepThroughStatement(api, stmt, bindings, knownColumns, includeResults = true) {
2530
+ // TODO not sure why this is needed currently, but booleans break
2531
+ bindings.forEach((b, index, arr) => {
2532
+ if (typeof b == 'boolean') {
2533
+ arr[index] = b ? 1 : 0;
2534
+ }
2535
+ });
2536
+ api.reset(stmt);
2537
+ if (bindings) {
2538
+ api.bind_collection(stmt, bindings);
2539
+ }
2540
+ const rows = [];
2541
+ while ((await api.step(stmt)) === _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__.SQLITE_ROW) {
2542
+ if (includeResults) {
2543
+ const row = api.row(stmt);
2544
+ rows.push(row);
2545
+ }
2546
+ }
2547
+ knownColumns ??= api.column_names(stmt);
2548
+ return { columns: knownColumns, rows };
2549
+ }
2550
+ async close() {
2551
+ if (this.isOpen) {
2552
+ await this.requireSqlite().close(this.db);
2553
+ this.db = 0;
2554
+ }
2555
+ }
2831
2556
  }
2832
2557
 
2833
2558
 
2834
2559
  /***/ },
2835
2560
 
2836
- /***/ "./lib/src/shared/navigator.js"
2837
- /*!*************************************!*\
2838
- !*** ./lib/src/shared/navigator.js ***!
2839
- \*************************************/
2561
+ /***/ "./lib/src/db/adapters/wa-sqlite/vfs.js"
2562
+ /*!**********************************************!*\
2563
+ !*** ./lib/src/db/adapters/wa-sqlite/vfs.js ***!
2564
+ \**********************************************/
2840
2565
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2841
2566
 
2842
2567
  __webpack_require__.r(__webpack_exports__);
2843
2568
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2844
- /* harmony export */ getNavigatorLocks: () => (/* binding */ getNavigatorLocks)
2569
+ /* harmony export */ AsyncWASQLiteModuleFactory: () => (/* binding */ AsyncWASQLiteModuleFactory),
2570
+ /* harmony export */ DEFAULT_MODULE_FACTORIES: () => (/* binding */ DEFAULT_MODULE_FACTORIES),
2571
+ /* harmony export */ MultiCipherAsyncWASQLiteModuleFactory: () => (/* binding */ MultiCipherAsyncWASQLiteModuleFactory),
2572
+ /* harmony export */ MultiCipherSyncWASQLiteModuleFactory: () => (/* binding */ MultiCipherSyncWASQLiteModuleFactory),
2573
+ /* harmony export */ SyncWASQLiteModuleFactory: () => (/* binding */ SyncWASQLiteModuleFactory),
2574
+ /* harmony export */ WASQLiteVFS: () => (/* binding */ WASQLiteVFS),
2575
+ /* harmony export */ vfsRequiresDedicatedWorkers: () => (/* binding */ vfsRequiresDedicatedWorkers)
2845
2576
  /* harmony export */ });
2846
- const getNavigatorLocks = () => {
2847
- if ('locks' in navigator && navigator.locks) {
2848
- return navigator.locks;
2849
- }
2850
- throw new Error('Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.');
2577
+ /**
2578
+ * List of currently tested virtual filesystems
2579
+ */
2580
+ var WASQLiteVFS;
2581
+ (function (WASQLiteVFS) {
2582
+ WASQLiteVFS["IDBBatchAtomicVFS"] = "IDBBatchAtomicVFS";
2583
+ WASQLiteVFS["OPFSCoopSyncVFS"] = "OPFSCoopSyncVFS";
2584
+ WASQLiteVFS["AccessHandlePoolVFS"] = "AccessHandlePoolVFS";
2585
+ })(WASQLiteVFS || (WASQLiteVFS = {}));
2586
+ function vfsRequiresDedicatedWorkers(vfs) {
2587
+ return vfs != WASQLiteVFS.IDBBatchAtomicVFS;
2588
+ }
2589
+ /**
2590
+ * @internal
2591
+ */
2592
+ const AsyncWASQLiteModuleFactory = async () => {
2593
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-cc5fcc").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs"));
2594
+ return factory();
2851
2595
  };
2852
-
2853
-
2854
- /***/ },
2855
-
2856
- /***/ "./lib/src/worker/db/SharedWASQLiteConnection.js"
2857
- /*!*******************************************************!*\
2858
- !*** ./lib/src/worker/db/SharedWASQLiteConnection.js ***!
2859
- \*******************************************************/
2860
- (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2861
-
2862
- __webpack_require__.r(__webpack_exports__);
2863
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2864
- /* harmony export */ SharedWASQLiteConnection: () => (/* binding */ SharedWASQLiteConnection)
2865
- /* harmony export */ });
2866
- class SharedWASQLiteConnection {
2867
- options;
2868
- isClosing;
2869
- // Keeps track if this current hold if the shared connection has a hold
2870
- activeHoldId;
2871
- constructor(options) {
2872
- this.options = options;
2873
- // Add this client ID to the set of known clients
2874
- this.clientIds.add(options.clientId);
2875
- this.isClosing = false;
2876
- this.activeHoldId = null;
2877
- }
2878
- get logger() {
2879
- return this.options.logger;
2880
- }
2881
- get dbEntry() {
2882
- return this.options.dbMap.get(this.options.dbFilename);
2883
- }
2884
- get connection() {
2885
- return this.dbEntry.db;
2886
- }
2887
- get clientIds() {
2888
- return this.dbEntry.clientIds;
2889
- }
2890
- async init() {
2891
- // No-op since the connection is already initialized when it was created
2892
- }
2893
- async markHold() {
2894
- this.activeHoldId = await this.connection.markHold();
2895
- return this.activeHoldId;
2896
- }
2897
- async releaseHold(id) {
2898
- try {
2899
- await this.connection.releaseHold(id);
2596
+ /**
2597
+ * @internal
2598
+ */
2599
+ const MultiCipherAsyncWASQLiteModuleFactory = async () => {
2600
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-c99c07").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs"));
2601
+ return factory();
2602
+ };
2603
+ /**
2604
+ * @internal
2605
+ */
2606
+ const SyncWASQLiteModuleFactory = async () => {
2607
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_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.5.0/node_modules/@journeyapps/wa-sqlite/dist/wa-sqlite.mjs"));
2608
+ return factory();
2609
+ };
2610
+ /**
2611
+ * @internal
2612
+ */
2613
+ const MultiCipherSyncWASQLiteModuleFactory = async () => {
2614
+ const { default: factory } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-b9c070").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs"));
2615
+ return factory();
2616
+ };
2617
+ /**
2618
+ * @internal
2619
+ */
2620
+ const DEFAULT_MODULE_FACTORIES = {
2621
+ [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {
2622
+ let module;
2623
+ if (options.encryptionKey) {
2624
+ module = await MultiCipherAsyncWASQLiteModuleFactory();
2900
2625
  }
2901
- finally {
2902
- this.activeHoldId = null;
2626
+ else {
2627
+ module = await AsyncWASQLiteModuleFactory();
2903
2628
  }
2904
- }
2905
- async isAutoCommit() {
2906
- return this.connection.isAutoCommit();
2907
- }
2908
- /**
2909
- * Handles closing of a shared connection.
2910
- * The connection is only closed if there are no active clients using it.
2911
- */
2912
- async close() {
2913
- // This prevents further statements on this connection from being executed
2914
- this.isClosing = true;
2915
- const { clientIds, logger } = this;
2916
- const { clientId, dbFilename, dbMap } = this.options;
2917
- logger.debug(`Close requested from client ${clientId} of ${[...clientIds]}`);
2918
- clientIds.delete(clientId);
2919
- if (this.activeHoldId) {
2920
- // We can't cleanup here since we're not in a lock context.
2921
- // The cleanup will occur once a new hold is acquired.
2922
- this.logger.info(`Hold ${this.activeHoldId} was still active when the connection was closed. Cleanup will occur once a new hold is acquired.`);
2629
+ const { IDBBatchAtomicVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-0df390").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js"));
2630
+ return {
2631
+ module,
2632
+ // @ts-expect-error The types for this static method are missing upstream
2633
+ vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })
2634
+ };
2635
+ },
2636
+ [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {
2637
+ let module;
2638
+ if (options.encryptionKey) {
2639
+ module = await MultiCipherSyncWASQLiteModuleFactory();
2923
2640
  }
2924
- if (clientIds.size == 0) {
2925
- logger.debug(`Closing connection to ${this.options}.`);
2926
- const connection = this.connection;
2927
- dbMap.delete(dbFilename);
2928
- await connection.close();
2929
- return;
2641
+ else {
2642
+ module = await SyncWASQLiteModuleFactory();
2930
2643
  }
2931
- logger.debug(`Connection to ${dbFilename} not closed yet due to active clients.`);
2932
- return;
2933
- }
2934
- async withClosing(action) {
2935
- if (this.isClosing) {
2936
- throw new Error('Connection is closing');
2644
+ // @ts-expect-error The types for this static method are missing upstream
2645
+ const { AccessHandlePoolVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-151024").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js"));
2646
+ return {
2647
+ module,
2648
+ vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
2649
+ };
2650
+ },
2651
+ [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {
2652
+ let module;
2653
+ if (options.encryptionKey) {
2654
+ module = await MultiCipherSyncWASQLiteModuleFactory();
2937
2655
  }
2938
- return action();
2939
- }
2940
- async execute(sql, params) {
2941
- return this.withClosing(() => this.connection.execute(sql, params));
2942
- }
2943
- async executeRaw(sql, params) {
2944
- return this.withClosing(() => this.connection.executeRaw(sql, params));
2945
- }
2946
- executeBatch(sql, params) {
2947
- return this.withClosing(() => this.connection.executeBatch(sql, params));
2948
- }
2949
- registerOnTableChange(callback) {
2950
- return this.connection.registerOnTableChange(callback);
2656
+ else {
2657
+ module = await SyncWASQLiteModuleFactory();
2658
+ }
2659
+ // @ts-expect-error The types for this static method are missing upstream
2660
+ const { OPFSCoopSyncVFS } = await __webpack_require__.e(/*! import() */ "node_modules_pnpm_journeyapps_wa-sqlite_1_5_0_node_modules_journeyapps_wa-sqlite_src_examples-c01ef0").then(__webpack_require__.bind(__webpack_require__, /*! @journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"));
2661
+ const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
2662
+ return {
2663
+ module,
2664
+ vfs
2665
+ };
2951
2666
  }
2952
- getConfig() {
2953
- return this.connection.getConfig();
2667
+ };
2668
+
2669
+
2670
+ /***/ },
2671
+
2672
+ /***/ "./lib/src/shared/navigator.js"
2673
+ /*!*************************************!*\
2674
+ !*** ./lib/src/shared/navigator.js ***!
2675
+ \*************************************/
2676
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2677
+
2678
+ __webpack_require__.r(__webpack_exports__);
2679
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2680
+ /* harmony export */ getNavigatorLocks: () => (/* binding */ getNavigatorLocks)
2681
+ /* harmony export */ });
2682
+ const getNavigatorLocks = () => {
2683
+ if ('locks' in navigator && navigator.locks) {
2684
+ return navigator.locks;
2954
2685
  }
2955
- }
2686
+ throw new Error('Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.');
2687
+ };
2956
2688
 
2957
2689
 
2958
2690
  /***/ },
2959
2691
 
2960
- /***/ "./lib/src/worker/db/WorkerWASQLiteConnection.js"
2961
- /*!*******************************************************!*\
2962
- !*** ./lib/src/worker/db/WorkerWASQLiteConnection.js ***!
2963
- \*******************************************************/
2692
+ /***/ "./lib/src/worker/db/MultiDatabaseServer.js"
2693
+ /*!**************************************************!*\
2694
+ !*** ./lib/src/worker/db/MultiDatabaseServer.js ***!
2695
+ \**************************************************/
2964
2696
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2965
2697
 
2966
2698
  __webpack_require__.r(__webpack_exports__);
2967
2699
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2968
- /* harmony export */ WorkerWASQLiteConnection: () => (/* binding */ WorkerWASQLiteConnection)
2700
+ /* harmony export */ MultiDatabaseServer: () => (/* binding */ MultiDatabaseServer),
2701
+ /* harmony export */ isSharedWorker: () => (/* binding */ isSharedWorker)
2969
2702
  /* harmony export */ });
2970
2703
  /* 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");
2971
- /* 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");
2704
+ /* harmony import */ var _db_adapters_wa_sqlite_DatabaseServer_js__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ../../db/adapters/wa-sqlite/DatabaseServer.js */ "./lib/src/db/adapters/wa-sqlite/DatabaseServer.js");
2705
+ /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
2706
+ /* harmony import */ var _db_adapters_wa_sqlite_RawSqliteConnection_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../db/adapters/wa-sqlite/RawSqliteConnection.js */ "./lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js");
2707
+ /* harmony import */ var _db_adapters_wa_sqlite_ConcurrentConnection_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ../../db/adapters/wa-sqlite/ConcurrentConnection.js */ "./lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js");
2708
+
2709
+
2972
2710
 
2973
2711
 
2712
+
2713
+ const OPEN_DB_LOCK = 'open-wasqlite-db';
2974
2714
  /**
2975
- * A Small proxy wrapper around the WASqliteConnection.
2976
- * This ensures that certain return types are properly proxied.
2715
+ * Shared state to manage multiple database connections hosted by a worker.
2977
2716
  */
2978
- class WorkerWASQLiteConnection extends _db_adapters_wa_sqlite_WASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_1__.WASqliteConnection {
2979
- async registerOnTableChange(callback) {
2980
- // Proxy the callback remove function
2981
- return comlink__WEBPACK_IMPORTED_MODULE_0__.proxy(await super.registerOnTableChange(callback));
2717
+ class MultiDatabaseServer {
2718
+ logger;
2719
+ activeDatabases = new Map();
2720
+ constructor(logger) {
2721
+ this.logger = logger;
2722
+ }
2723
+ async handleConnection(options) {
2724
+ this.logger.setLevel(options.logLevel);
2725
+ return comlink__WEBPACK_IMPORTED_MODULE_0__.proxy(await this.openConnectionLocally(options, options.lockName));
2726
+ }
2727
+ async connectToExisting(name, lockName) {
2728
+ return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_2__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
2729
+ const server = this.activeDatabases.get(name);
2730
+ if (server == null) {
2731
+ throw new Error(`connectToExisting(${name}) failed because the worker doesn't own a database with that name.`);
2732
+ }
2733
+ return comlink__WEBPACK_IMPORTED_MODULE_0__.proxy(await server.connect(lockName));
2734
+ });
2735
+ }
2736
+ async openConnectionLocally(options, lockName) {
2737
+ // Especially on Firefox, we're sometimes seeing "NoModificationAllowedError"s when opening OPFS databases we can
2738
+ // work around by retrying.
2739
+ const maxAttempts = 3;
2740
+ let server;
2741
+ for (let count = 0; count < maxAttempts - 1; count++) {
2742
+ try {
2743
+ server = await this.databaseOpenAttempt(options);
2744
+ }
2745
+ catch (ex) {
2746
+ this.logger.warn(`Attempt ${count + 1} of ${maxAttempts} to open database failed, retrying in 1 second...`, ex);
2747
+ await new Promise((resolve) => setTimeout(resolve, 1000));
2748
+ }
2749
+ }
2750
+ // Final attempt if we haven't been able to open the server - rethrow errors if we still can't open.
2751
+ server ??= await this.databaseOpenAttempt(options);
2752
+ return server.connect(lockName);
2753
+ }
2754
+ async databaseOpenAttempt(options) {
2755
+ return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_2__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
2756
+ const { dbFilename } = options;
2757
+ let server = this.activeDatabases.get(dbFilename);
2758
+ if (server == null) {
2759
+ const needsNavigatorLocks = !isSharedWorker;
2760
+ const connection = new _db_adapters_wa_sqlite_RawSqliteConnection_js__WEBPACK_IMPORTED_MODULE_3__.RawSqliteConnection(options);
2761
+ const withSafeConcurrency = new _db_adapters_wa_sqlite_ConcurrentConnection_js__WEBPACK_IMPORTED_MODULE_4__.ConcurrentSqliteConnection(connection, needsNavigatorLocks);
2762
+ // Initializing the RawSqliteConnection will run some pragmas that might write to the database file, so we want
2763
+ // to do that in an exclusive lock. Note that OPEN_DB_LOCK is not enough for that, as another tab might have
2764
+ // already created a connection (and is thus outside of OPEN_DB_LOCK) while currently writing to it.
2765
+ const returnLease = await withSafeConcurrency.acquireMutex();
2766
+ try {
2767
+ await connection.init();
2768
+ }
2769
+ catch (e) {
2770
+ returnLease();
2771
+ await connection.close();
2772
+ throw e;
2773
+ }
2774
+ returnLease();
2775
+ const onClose = () => this.activeDatabases.delete(dbFilename);
2776
+ server = new _db_adapters_wa_sqlite_DatabaseServer_js__WEBPACK_IMPORTED_MODULE_1__.DatabaseServer({
2777
+ inner: withSafeConcurrency,
2778
+ logger: this.logger,
2779
+ onClose
2780
+ });
2781
+ this.activeDatabases.set(dbFilename, server);
2782
+ }
2783
+ return server;
2784
+ });
2785
+ }
2786
+ closeAll() {
2787
+ const existingDatabases = [...this.activeDatabases.values()];
2788
+ return Promise.all(existingDatabases.map((db) => {
2789
+ db.forceClose();
2790
+ }));
2982
2791
  }
2983
2792
  }
2793
+ const isSharedWorker = 'SharedWorkerGlobalScope' in globalThis;
2984
2794
 
2985
2795
 
2986
2796
  /***/ },
@@ -3015,6 +2825,8 @@ __webpack_require__.r(__webpack_exports__);
3015
2825
  /* harmony export */ CrudBatch: () => (/* binding */ CrudBatch),
3016
2826
  /* harmony export */ CrudEntry: () => (/* binding */ CrudEntry),
3017
2827
  /* harmony export */ CrudTransaction: () => (/* binding */ CrudTransaction),
2828
+ /* harmony export */ DBAdapterDefaultMixin: () => (/* binding */ DBAdapterDefaultMixin),
2829
+ /* harmony export */ DBGetUtilsDefaultMixin: () => (/* binding */ DBGetUtilsDefaultMixin),
3018
2830
  /* harmony export */ DEFAULT_CRUD_BATCH_LIMIT: () => (/* binding */ DEFAULT_CRUD_BATCH_LIMIT),
3019
2831
  /* harmony export */ DEFAULT_CRUD_UPLOAD_THROTTLE_MS: () => (/* binding */ DEFAULT_CRUD_UPLOAD_THROTTLE_MS),
3020
2832
  /* harmony export */ DEFAULT_INDEX_COLUMN_OPTIONS: () => (/* binding */ DEFAULT_INDEX_COLUMN_OPTIONS),
@@ -3022,7 +2834,6 @@ __webpack_require__.r(__webpack_exports__);
3022
2834
  /* harmony export */ DEFAULT_LOCK_TIMEOUT_MS: () => (/* binding */ DEFAULT_LOCK_TIMEOUT_MS),
3023
2835
  /* harmony export */ DEFAULT_POWERSYNC_CLOSE_OPTIONS: () => (/* binding */ DEFAULT_POWERSYNC_CLOSE_OPTIONS),
3024
2836
  /* harmony export */ DEFAULT_POWERSYNC_DB_OPTIONS: () => (/* binding */ DEFAULT_POWERSYNC_DB_OPTIONS),
3025
- /* harmony export */ DEFAULT_PRESSURE_LIMITS: () => (/* binding */ DEFAULT_PRESSURE_LIMITS),
3026
2837
  /* harmony export */ DEFAULT_REMOTE_LOGGER: () => (/* binding */ DEFAULT_REMOTE_LOGGER),
3027
2838
  /* harmony export */ DEFAULT_REMOTE_OPTIONS: () => (/* binding */ DEFAULT_REMOTE_OPTIONS),
3028
2839
  /* harmony export */ DEFAULT_RETRY_DELAY_MS: () => (/* binding */ DEFAULT_RETRY_DELAY_MS),
@@ -3033,7 +2844,6 @@ __webpack_require__.r(__webpack_exports__);
3033
2844
  /* harmony export */ DEFAULT_TABLE_OPTIONS: () => (/* binding */ DEFAULT_TABLE_OPTIONS),
3034
2845
  /* harmony export */ DEFAULT_WATCH_QUERY_OPTIONS: () => (/* binding */ DEFAULT_WATCH_QUERY_OPTIONS),
3035
2846
  /* harmony export */ DEFAULT_WATCH_THROTTLE_MS: () => (/* binding */ DEFAULT_WATCH_THROTTLE_MS),
3036
- /* harmony export */ DataStream: () => (/* binding */ DataStream),
3037
2847
  /* harmony export */ DiffTriggerOperation: () => (/* binding */ DiffTriggerOperation),
3038
2848
  /* harmony export */ DifferentialQueryProcessor: () => (/* binding */ DifferentialQueryProcessor),
3039
2849
  /* harmony export */ EMPTY_DIFFERENTIAL: () => (/* binding */ EMPTY_DIFFERENTIAL),
@@ -3050,6 +2860,7 @@ __webpack_require__.r(__webpack_exports__);
3050
2860
  /* harmony export */ MAX_AMOUNT_OF_COLUMNS: () => (/* binding */ MAX_AMOUNT_OF_COLUMNS),
3051
2861
  /* harmony export */ MAX_OP_ID: () => (/* binding */ MAX_OP_ID),
3052
2862
  /* harmony export */ MEMORY_TRIGGER_CLAIM_MANAGER: () => (/* binding */ MEMORY_TRIGGER_CLAIM_MANAGER),
2863
+ /* harmony export */ Mutex: () => (/* binding */ Mutex),
3053
2864
  /* harmony export */ OnChangeQueryProcessor: () => (/* binding */ OnChangeQueryProcessor),
3054
2865
  /* harmony export */ OpType: () => (/* binding */ OpType),
3055
2866
  /* harmony export */ OpTypeEnum: () => (/* binding */ OpTypeEnum),
@@ -3058,6 +2869,7 @@ __webpack_require__.r(__webpack_exports__);
3058
2869
  /* harmony export */ PowerSyncControlCommand: () => (/* binding */ PowerSyncControlCommand),
3059
2870
  /* harmony export */ RowUpdateType: () => (/* binding */ RowUpdateType),
3060
2871
  /* harmony export */ Schema: () => (/* binding */ Schema),
2872
+ /* harmony export */ Semaphore: () => (/* binding */ Semaphore),
3061
2873
  /* harmony export */ SqliteBucketStorage: () => (/* binding */ SqliteBucketStorage),
3062
2874
  /* harmony export */ SyncClientImplementation: () => (/* binding */ SyncClientImplementation),
3063
2875
  /* harmony export */ SyncDataBatch: () => (/* binding */ SyncDataBatch),
@@ -3091,15 +2903,12 @@ __webpack_require__.r(__webpack_exports__);
3091
2903
  /* harmony export */ isStreamingSyncCheckpointPartiallyComplete: () => (/* binding */ isStreamingSyncCheckpointPartiallyComplete),
3092
2904
  /* harmony export */ isStreamingSyncData: () => (/* binding */ isStreamingSyncData),
3093
2905
  /* harmony export */ isSyncNewCheckpointRequest: () => (/* binding */ isSyncNewCheckpointRequest),
3094
- /* harmony export */ mutexRunExclusive: () => (/* binding */ mutexRunExclusive),
3095
2906
  /* harmony export */ parseQuery: () => (/* binding */ parseQuery),
3096
2907
  /* harmony export */ runOnSchemaChange: () => (/* binding */ runOnSchemaChange),
3097
2908
  /* harmony export */ sanitizeSQL: () => (/* binding */ sanitizeSQL),
3098
- /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID)
2909
+ /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID),
2910
+ /* harmony export */ timeoutSignal: () => (/* binding */ timeoutSignal)
3099
2911
  /* harmony export */ });
3100
- /* 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");
3101
-
3102
-
3103
2912
  // https://www.sqlite.org/lang_expr.html#castexpr
3104
2913
  var ColumnType;
3105
2914
  (function (ColumnType) {
@@ -3757,7 +3566,7 @@ class SyncingService {
3757
3566
  updatedAttachments.push(downloaded);
3758
3567
  break;
3759
3568
  case AttachmentState.QUEUED_DELETE:
3760
- const deleted = await this.deleteAttachment(attachment);
3569
+ const deleted = await this.deleteAttachment(attachment, context);
3761
3570
  updatedAttachments.push(deleted);
3762
3571
  break;
3763
3572
  }
@@ -3835,17 +3644,16 @@ class SyncingService {
3835
3644
  * On failure, defers to error handler or archives.
3836
3645
  *
3837
3646
  * @param attachment - The attachment record to delete
3647
+ * @param context - Attachment context for database operations
3838
3648
  * @returns Updated attachment record
3839
3649
  */
3840
- async deleteAttachment(attachment) {
3650
+ async deleteAttachment(attachment, context) {
3841
3651
  try {
3842
3652
  await this.remoteStorage.deleteFile(attachment);
3843
3653
  if (attachment.localUri) {
3844
3654
  await this.localStorage.deleteFile(attachment.localUri);
3845
3655
  }
3846
- await this.attachmentService.withContext(async (ctx) => {
3847
- await ctx.deleteAttachment(attachment.id);
3848
- });
3656
+ await context.deleteAttachment(attachment.id);
3849
3657
  return {
3850
3658
  ...attachment,
3851
3659
  state: AttachmentState.ARCHIVED
@@ -3883,32 +3691,198 @@ class SyncingService {
3883
3691
  }
3884
3692
 
3885
3693
  /**
3886
- * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
3694
+ * A simple fixed-capacity queue implementation.
3695
+ *
3696
+ * Unlike a naive queue implemented by `array.push()` and `array.shift()`, this avoids moving array elements around
3697
+ * and is `O(1)` for {@link addLast} and {@link removeFirst}.
3698
+ */
3699
+ class Queue {
3700
+ table;
3701
+ // Index of the first element in the table.
3702
+ head;
3703
+ // Amount of items currently in the queue.
3704
+ _length;
3705
+ constructor(initialItems) {
3706
+ this.table = [...initialItems];
3707
+ this.head = 0;
3708
+ this._length = this.table.length;
3709
+ }
3710
+ get isEmpty() {
3711
+ return this.length == 0;
3712
+ }
3713
+ get length() {
3714
+ return this._length;
3715
+ }
3716
+ removeFirst() {
3717
+ if (this.isEmpty) {
3718
+ throw new Error('Queue is empty');
3719
+ }
3720
+ const result = this.table[this.head];
3721
+ this._length--;
3722
+ this.table[this.head] = undefined;
3723
+ this.head = (this.head + 1) % this.table.length;
3724
+ return result;
3725
+ }
3726
+ addLast(element) {
3727
+ if (this.length == this.table.length) {
3728
+ throw new Error('Queue is full');
3729
+ }
3730
+ this.table[(this.head + this._length) % this.table.length] = element;
3731
+ this._length++;
3732
+ }
3733
+ }
3734
+
3735
+ /**
3736
+ * An asynchronous semaphore implementation with associated items per lease.
3737
+ *
3738
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
3887
3739
  */
3888
- async function mutexRunExclusive(mutex, callback, options) {
3889
- return new Promise((resolve, reject) => {
3890
- const timeout = options?.timeoutMs;
3891
- let timedOut = false;
3892
- const timeoutId = timeout
3893
- ? setTimeout(() => {
3894
- timedOut = true;
3895
- reject(new Error('Timeout waiting for lock'));
3896
- }, timeout)
3897
- : undefined;
3898
- mutex.runExclusive(async () => {
3899
- if (timeoutId) {
3900
- clearTimeout(timeoutId);
3740
+ class Semaphore {
3741
+ // Available items that are not currently assigned to a waiter.
3742
+ available;
3743
+ size;
3744
+ // Linked list of waiters. We don't expect the wait list to become particularly large, and this allows removing
3745
+ // aborted waiters from the middle of the list efficiently.
3746
+ firstWaiter;
3747
+ lastWaiter;
3748
+ constructor(elements) {
3749
+ this.available = new Queue(elements);
3750
+ this.size = this.available.length;
3751
+ }
3752
+ addWaiter(requestedItems, onAcquire) {
3753
+ const node = {
3754
+ isActive: true,
3755
+ acquiredItems: [],
3756
+ remainingItems: requestedItems,
3757
+ onAcquire,
3758
+ prev: this.lastWaiter
3759
+ };
3760
+ if (this.lastWaiter) {
3761
+ this.lastWaiter.next = node;
3762
+ this.lastWaiter = node;
3763
+ }
3764
+ else {
3765
+ // First waiter
3766
+ this.lastWaiter = this.firstWaiter = node;
3767
+ }
3768
+ return node;
3769
+ }
3770
+ deactivateWaiter(waiter) {
3771
+ const { prev, next } = waiter;
3772
+ waiter.isActive = false;
3773
+ if (prev)
3774
+ prev.next = next;
3775
+ if (next)
3776
+ next.prev = prev;
3777
+ if (waiter == this.firstWaiter)
3778
+ this.firstWaiter = next;
3779
+ if (waiter == this.lastWaiter)
3780
+ this.lastWaiter = prev;
3781
+ }
3782
+ requestPermits(amount, abort) {
3783
+ if (amount <= 0 || amount > this.size) {
3784
+ throw new Error(`Invalid amount of items requested (${amount}), must be between 1 and ${this.size}`);
3785
+ }
3786
+ return new Promise((resolve, reject) => {
3787
+ function rejectAborted() {
3788
+ reject(abort?.reason ?? new Error('Semaphore acquire aborted'));
3901
3789
  }
3902
- if (timedOut)
3903
- return;
3904
- try {
3905
- resolve(await callback());
3790
+ if (abort?.aborted) {
3791
+ return rejectAborted();
3906
3792
  }
3907
- catch (ex) {
3908
- reject(ex);
3793
+ let waiter;
3794
+ const markCompleted = () => {
3795
+ const items = waiter.acquiredItems;
3796
+ waiter.acquiredItems = []; // Avoid releasing items twice.
3797
+ for (const element of items) {
3798
+ // Give to next waiter, if possible.
3799
+ const nextWaiter = this.firstWaiter;
3800
+ if (nextWaiter) {
3801
+ nextWaiter.acquiredItems.push(element);
3802
+ nextWaiter.remainingItems--;
3803
+ if (nextWaiter.remainingItems == 0) {
3804
+ nextWaiter.onAcquire();
3805
+ }
3806
+ }
3807
+ else {
3808
+ // No pending waiter, return lease into pool.
3809
+ this.available.addLast(element);
3810
+ }
3811
+ }
3812
+ };
3813
+ const onAbort = () => {
3814
+ abort?.removeEventListener('abort', onAbort);
3815
+ if (waiter.isActive) {
3816
+ this.deactivateWaiter(waiter);
3817
+ rejectAborted();
3818
+ }
3819
+ };
3820
+ const resolvePromise = () => {
3821
+ this.deactivateWaiter(waiter);
3822
+ abort?.removeEventListener('abort', onAbort);
3823
+ const items = waiter.acquiredItems;
3824
+ resolve({ items, release: markCompleted });
3825
+ };
3826
+ waiter = this.addWaiter(amount, resolvePromise);
3827
+ // If there are items in the pool that haven't been assigned, we can pull them into this waiter. Note that this is
3828
+ // only the case if we're the first waiter (otherwise, items would have been assigned to an earlier waiter).
3829
+ while (!this.available.isEmpty && waiter.remainingItems > 0) {
3830
+ waiter.acquiredItems.push(this.available.removeFirst());
3831
+ waiter.remainingItems--;
3909
3832
  }
3833
+ if (waiter.remainingItems == 0) {
3834
+ return resolvePromise();
3835
+ }
3836
+ abort?.addEventListener('abort', onAbort);
3910
3837
  });
3911
- });
3838
+ }
3839
+ /**
3840
+ * Requests a single item from the pool.
3841
+ *
3842
+ * The returned `release` callback must be invoked to return the item into the pool.
3843
+ */
3844
+ async requestOne(abort) {
3845
+ const { items, release } = await this.requestPermits(1, abort);
3846
+ return { release, item: items[0] };
3847
+ }
3848
+ /**
3849
+ * Requests access to all items from the pool.
3850
+ *
3851
+ * The returned `release` callback must be invoked to return items into the pool.
3852
+ */
3853
+ requestAll(abort) {
3854
+ return this.requestPermits(this.size, abort);
3855
+ }
3856
+ }
3857
+ /**
3858
+ * An asynchronous mutex implementation.
3859
+ *
3860
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
3861
+ */
3862
+ class Mutex {
3863
+ inner = new Semaphore([null]);
3864
+ async acquire(abort) {
3865
+ const { release } = await this.inner.requestOne(abort);
3866
+ return release;
3867
+ }
3868
+ async runExclusive(fn, abort) {
3869
+ const returnMutex = await this.acquire(abort);
3870
+ try {
3871
+ return await fn();
3872
+ }
3873
+ finally {
3874
+ returnMutex();
3875
+ }
3876
+ }
3877
+ }
3878
+ function timeoutSignal(timeout) {
3879
+ if (timeout == null)
3880
+ return;
3881
+ if ('timeout' in AbortSignal)
3882
+ return AbortSignal.timeout(timeout);
3883
+ const controller = new AbortController();
3884
+ setTimeout(() => controller.abort(new Error('Timeout waiting for lock')), timeout);
3885
+ return controller.signal;
3912
3886
  }
3913
3887
 
3914
3888
  /**
@@ -3920,7 +3894,7 @@ class AttachmentService {
3920
3894
  db;
3921
3895
  logger;
3922
3896
  tableName;
3923
- mutex = new async_mutex__WEBPACK_IMPORTED_MODULE_0__.Mutex();
3897
+ mutex = new Mutex();
3924
3898
  context;
3925
3899
  constructor(db, logger, tableName = 'attachments', archivedCacheLimit = 100) {
3926
3900
  this.db = db;
@@ -3957,7 +3931,7 @@ class AttachmentService {
3957
3931
  * Executes a callback with exclusive access to the attachment context.
3958
3932
  */
3959
3933
  async withContext(callback) {
3960
- return mutexRunExclusive(this.mutex, async () => {
3934
+ return this.mutex.runExclusive(async () => {
3961
3935
  return callback(this.context);
3962
3936
  });
3963
3937
  }
@@ -3993,9 +3967,15 @@ class AttachmentQueue {
3993
3967
  tableName;
3994
3968
  /** Logger instance for diagnostic information */
3995
3969
  logger;
3996
- /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
3970
+ /** Interval in milliseconds between periodic sync operations. Acts as a polling timer to retry
3971
+ * failed uploads/downloads, especially after the app goes offline. Default: 30000 (30 seconds) */
3997
3972
  syncIntervalMs = 30 * 1000;
3998
- /** Duration in milliseconds to throttle sync operations */
3973
+ /** Throttle duration in milliseconds for the reactive watch query on the attachments table.
3974
+ * When attachment records change, a watch query detects the change and triggers a sync.
3975
+ * This throttle prevents the sync from firing too rapidly when many changes happen in
3976
+ * quick succession (e.g., bulk inserts). This is distinct from syncIntervalMs — it controls
3977
+ * how quickly the queue reacts to changes, while syncIntervalMs controls how often it polls
3978
+ * for retries. Default: 30 (from DEFAULT_WATCH_THROTTLE_MS) */
3999
3979
  syncThrottleDuration;
4000
3980
  /** Whether to automatically download remote attachments. Default: true */
4001
3981
  downloadAttachments = true;
@@ -4019,8 +3999,8 @@ class AttachmentQueue {
4019
3999
  * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
4020
4000
  * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
4021
4001
  * @param options.logger - Logger instance. Defaults to db.logger
4022
- * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
4023
- * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000
4002
+ * @param options.syncIntervalMs - Periodic polling interval in milliseconds for retrying failed uploads/downloads. Default: 30000
4003
+ * @param options.syncThrottleDuration - Throttle duration in milliseconds for the reactive watch query that detects attachment changes. Prevents rapid-fire syncs during bulk changes. Default: 30
4024
4004
  * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
4025
4005
  * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
4026
4006
  */
@@ -4327,6 +4307,8 @@ var EncodingType;
4327
4307
  EncodingType["Base64"] = "base64";
4328
4308
  })(EncodingType || (EncodingType = {}));
4329
4309
 
4310
+ const symbolAsyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');
4311
+
4330
4312
  function getDefaultExportFromCjs (x) {
4331
4313
  return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
4332
4314
  }
@@ -4407,7 +4389,7 @@ function requireEventIterator () {
4407
4389
  this.removeCallback();
4408
4390
  });
4409
4391
  }
4410
- [Symbol.asyncIterator]() {
4392
+ [symbolAsyncIterator]() {
4411
4393
  return {
4412
4394
  next: (value) => {
4413
4395
  const result = this.pushQueue.shift();
@@ -4454,7 +4436,7 @@ function requireEventIterator () {
4454
4436
  queue.eventHandlers[event] = fn;
4455
4437
  },
4456
4438
  }) || (() => { });
4457
- this[Symbol.asyncIterator] = () => queue[Symbol.asyncIterator]();
4439
+ this[symbolAsyncIterator] = () => queue[symbolAsyncIterator]();
4458
4440
  Object.freeze(this);
4459
4441
  }
4460
4442
  }
@@ -4781,6 +4763,49 @@ var Logger = /*@__PURE__*/getDefaultExportFromCjs(loggerExports);
4781
4763
  * Set of generic interfaces to allow PowerSync compatibility with
4782
4764
  * different SQLite DB implementations.
4783
4765
  */
4766
+ /**
4767
+ * Implements {@link DBGetUtils} on a {@link SqlRunner}.
4768
+ */
4769
+ function DBGetUtilsDefaultMixin(Base) {
4770
+ return class extends Base {
4771
+ async getAll(sql, parameters) {
4772
+ const res = await this.execute(sql, parameters);
4773
+ return res.rows?._array ?? [];
4774
+ }
4775
+ async getOptional(sql, parameters) {
4776
+ const res = await this.execute(sql, parameters);
4777
+ return res.rows?.item(0) ?? null;
4778
+ }
4779
+ async get(sql, parameters) {
4780
+ const res = await this.execute(sql, parameters);
4781
+ const first = res.rows?.item(0);
4782
+ if (!first) {
4783
+ throw new Error('Result set is empty');
4784
+ }
4785
+ return first;
4786
+ }
4787
+ async executeBatch(query, params = []) {
4788
+ // If this context can run batch statements natively, use that.
4789
+ // @ts-ignore
4790
+ if (super.executeBatch) {
4791
+ // @ts-ignore
4792
+ return super.executeBatch(query, params);
4793
+ }
4794
+ // Emulate executeBatch by running statements individually.
4795
+ let lastInsertId;
4796
+ let rowsAffected = 0;
4797
+ for (const set of params) {
4798
+ const result = await this.execute(query, set);
4799
+ lastInsertId = result.insertId;
4800
+ rowsAffected += result.rowsAffected;
4801
+ }
4802
+ return {
4803
+ rowsAffected,
4804
+ insertId: lastInsertId
4805
+ };
4806
+ }
4807
+ };
4808
+ }
4784
4809
  /**
4785
4810
  * Update table operation numbers from SQLite
4786
4811
  */
@@ -4790,6 +4815,89 @@ var RowUpdateType;
4790
4815
  RowUpdateType[RowUpdateType["SQLITE_DELETE"] = 9] = "SQLITE_DELETE";
4791
4816
  RowUpdateType[RowUpdateType["SQLITE_UPDATE"] = 23] = "SQLITE_UPDATE";
4792
4817
  })(RowUpdateType || (RowUpdateType = {}));
4818
+ /**
4819
+ * A mixin to implement {@link DBAdapter} by delegating to {@link ConnectionPool.readLock} and
4820
+ * {@link ConnectionPool.writeLock}.
4821
+ */
4822
+ function DBAdapterDefaultMixin(Base) {
4823
+ return class extends Base {
4824
+ readTransaction(fn, options) {
4825
+ return this.readLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
4826
+ }
4827
+ writeTransaction(fn, options) {
4828
+ return this.writeLock((ctx) => TransactionImplementation.runWith(ctx, fn), options);
4829
+ }
4830
+ getAll(sql, parameters) {
4831
+ return this.readLock((ctx) => ctx.getAll(sql, parameters));
4832
+ }
4833
+ getOptional(sql, parameters) {
4834
+ return this.readLock((ctx) => ctx.getOptional(sql, parameters));
4835
+ }
4836
+ get(sql, parameters) {
4837
+ return this.readLock((ctx) => ctx.get(sql, parameters));
4838
+ }
4839
+ execute(query, params) {
4840
+ return this.writeLock((ctx) => ctx.execute(query, params));
4841
+ }
4842
+ executeRaw(query, params) {
4843
+ return this.writeLock((ctx) => ctx.executeRaw(query, params));
4844
+ }
4845
+ executeBatch(query, params) {
4846
+ return this.writeTransaction((tx) => tx.executeBatch(query, params));
4847
+ }
4848
+ };
4849
+ }
4850
+ class BaseTransaction {
4851
+ inner;
4852
+ finalized = false;
4853
+ constructor(inner) {
4854
+ this.inner = inner;
4855
+ }
4856
+ async commit() {
4857
+ if (this.finalized) {
4858
+ return { rowsAffected: 0 };
4859
+ }
4860
+ this.finalized = true;
4861
+ return this.inner.execute('COMMIT');
4862
+ }
4863
+ async rollback() {
4864
+ if (this.finalized) {
4865
+ return { rowsAffected: 0 };
4866
+ }
4867
+ this.finalized = true;
4868
+ return this.inner.execute('ROLLBACK');
4869
+ }
4870
+ execute(query, params) {
4871
+ return this.inner.execute(query, params);
4872
+ }
4873
+ executeRaw(query, params) {
4874
+ return this.inner.executeRaw(query, params);
4875
+ }
4876
+ executeBatch(query, params) {
4877
+ return this.inner.executeBatch(query, params);
4878
+ }
4879
+ }
4880
+ class TransactionImplementation extends DBGetUtilsDefaultMixin(BaseTransaction) {
4881
+ static async runWith(ctx, fn) {
4882
+ let tx = new TransactionImplementation(ctx);
4883
+ try {
4884
+ await ctx.execute('BEGIN IMMEDIATE');
4885
+ const result = await fn(tx);
4886
+ await tx.commit();
4887
+ return result;
4888
+ }
4889
+ catch (ex) {
4890
+ try {
4891
+ await tx.rollback();
4892
+ }
4893
+ catch (ex2) {
4894
+ // In rare cases, a rollback may fail.
4895
+ // Safe to ignore.
4896
+ }
4897
+ throw ex;
4898
+ }
4899
+ }
4900
+ }
4793
4901
  function isBatchedUpdateNotification(update) {
4794
4902
  return 'tables' in update;
4795
4903
  }
@@ -5210,15 +5318,6 @@ class ControlledExecutor {
5210
5318
  }
5211
5319
  }
5212
5320
 
5213
- /**
5214
- * A ponyfill for `Symbol.asyncIterator` that is compatible with the
5215
- * [recommended polyfill](https://github.com/Azure/azure-sdk-for-js/blob/%40azure/core-asynciterator-polyfill_1.0.2/sdk/core/core-asynciterator-polyfill/src/index.ts#L4-L6)
5216
- * we recommend for React Native.
5217
- *
5218
- * As long as we use this symbol (instead of `for await` and `async *`) in this package, we can be compatible with async
5219
- * iterators without requiring them.
5220
- */
5221
- const symbolAsyncIterator = Symbol.asyncIterator ?? Symbol.for('Symbol.asyncIterator');
5222
5321
  /**
5223
5322
  * Throttle a function to be called at most once every "wait" milliseconds,
5224
5323
  * on the trailing edge.
@@ -13540,192 +13639,25 @@ function requireDist () {
13540
13639
  };
13541
13640
  Object.defineProperty(exports$1, "__esModule", { value: true });
13542
13641
  __exportStar(requireCodecs(), exports$1);
13543
- __exportStar(requireCommon(), exports$1);
13544
- __exportStar(requireDeferred(), exports$1);
13545
- __exportStar(requireErrors(), exports$1);
13546
- __exportStar(requireFrames(), exports$1);
13547
- __exportStar(requireRSocket(), exports$1);
13548
- __exportStar(requireRSocketConnector(), exports$1);
13549
- __exportStar(requireRSocketServer(), exports$1);
13550
- __exportStar(requireTransport(), exports$1);
13551
-
13552
- } (dist));
13553
- return dist;
13554
- }
13555
-
13556
- var distExports = requireDist();
13557
-
13558
- var version = "1.48.0";
13559
- var PACKAGE = {
13560
- version: version};
13561
-
13562
- const DEFAULT_PRESSURE_LIMITS = {
13563
- highWater: 10,
13564
- lowWater: 0
13565
- };
13566
- /**
13567
- * A very basic implementation of a data stream with backpressure support which does not use
13568
- * native JS streams or async iterators.
13569
- * This is handy for environments such as React Native which need polyfills for the above.
13570
- */
13571
- class DataStream extends BaseObserver {
13572
- options;
13573
- dataQueue;
13574
- isClosed;
13575
- processingPromise;
13576
- notifyDataAdded;
13577
- logger;
13578
- mapLine;
13579
- constructor(options) {
13580
- super();
13581
- this.options = options;
13582
- this.processingPromise = null;
13583
- this.isClosed = false;
13584
- this.dataQueue = [];
13585
- this.mapLine = options?.mapLine ?? ((line) => line);
13586
- this.logger = options?.logger ?? Logger.get('DataStream');
13587
- if (options?.closeOnError) {
13588
- const l = this.registerListener({
13589
- error: (ex) => {
13590
- l?.();
13591
- this.close();
13592
- }
13593
- });
13594
- }
13595
- }
13596
- get highWatermark() {
13597
- return this.options?.pressure?.highWaterMark ?? DEFAULT_PRESSURE_LIMITS.highWater;
13598
- }
13599
- get lowWatermark() {
13600
- return this.options?.pressure?.lowWaterMark ?? DEFAULT_PRESSURE_LIMITS.lowWater;
13601
- }
13602
- get closed() {
13603
- return this.isClosed;
13604
- }
13605
- async close() {
13606
- this.isClosed = true;
13607
- await this.processingPromise;
13608
- this.iterateListeners((l) => l.closed?.());
13609
- // Discard any data in the queue
13610
- this.dataQueue = [];
13611
- this.listeners.clear();
13612
- }
13613
- /**
13614
- * Enqueues data for the consumers to read
13615
- */
13616
- enqueueData(data) {
13617
- if (this.isClosed) {
13618
- throw new Error('Cannot enqueue data into closed stream.');
13619
- }
13620
- this.dataQueue.push(data);
13621
- this.notifyDataAdded?.();
13622
- this.processQueue();
13623
- }
13624
- /**
13625
- * Reads data once from the data stream
13626
- * @returns a Data payload or Null if the stream closed.
13627
- */
13628
- async read() {
13629
- if (this.closed) {
13630
- return null;
13631
- }
13632
- // Wait for any pending processing to complete first.
13633
- // This ensures we register our listener before calling processQueue(),
13634
- // avoiding a race where processQueue() sees no reader and returns early.
13635
- if (this.processingPromise) {
13636
- await this.processingPromise;
13637
- }
13638
- // Re-check after await - stream may have closed while we were waiting
13639
- if (this.closed) {
13640
- return null;
13641
- }
13642
- return new Promise((resolve, reject) => {
13643
- const l = this.registerListener({
13644
- data: async (data) => {
13645
- resolve(data);
13646
- // Remove the listener
13647
- l?.();
13648
- },
13649
- closed: () => {
13650
- resolve(null);
13651
- l?.();
13652
- },
13653
- error: (ex) => {
13654
- reject(ex);
13655
- l?.();
13656
- }
13657
- });
13658
- this.processQueue();
13659
- });
13660
- }
13661
- /**
13662
- * Executes a callback for each data item in the stream
13663
- */
13664
- forEach(callback) {
13665
- if (this.dataQueue.length <= this.lowWatermark) {
13666
- this.iterateAsyncErrored(async (l) => l.lowWater?.());
13667
- }
13668
- return this.registerListener({
13669
- data: callback
13670
- });
13671
- }
13672
- processQueue() {
13673
- if (this.processingPromise) {
13674
- return;
13675
- }
13676
- const promise = (this.processingPromise = this._processQueue());
13677
- promise.finally(() => {
13678
- this.processingPromise = null;
13679
- });
13680
- return promise;
13681
- }
13682
- hasDataReader() {
13683
- return Array.from(this.listeners.values()).some((l) => !!l.data);
13684
- }
13685
- async _processQueue() {
13686
- /**
13687
- * Allow listeners to mutate the queue before processing.
13688
- * This allows for operations such as dropping or compressing data
13689
- * on high water or requesting more data on low water.
13690
- */
13691
- if (this.dataQueue.length >= this.highWatermark) {
13692
- await this.iterateAsyncErrored(async (l) => l.highWater?.());
13693
- }
13694
- if (this.isClosed || !this.hasDataReader()) {
13695
- return;
13696
- }
13697
- if (this.dataQueue.length) {
13698
- const data = this.dataQueue.shift();
13699
- const mapped = this.mapLine(data);
13700
- await this.iterateAsyncErrored(async (l) => l.data?.(mapped));
13701
- }
13702
- if (this.dataQueue.length <= this.lowWatermark) {
13703
- const dataAdded = new Promise((resolve) => {
13704
- this.notifyDataAdded = resolve;
13705
- });
13706
- await Promise.race([this.iterateAsyncErrored(async (l) => l.lowWater?.()), dataAdded]);
13707
- this.notifyDataAdded = null;
13708
- }
13709
- if (this.dataQueue.length > 0) {
13710
- setTimeout(() => this.processQueue());
13711
- }
13712
- }
13713
- async iterateAsyncErrored(cb) {
13714
- // Important: We need to copy the listeners, as calling a listener could result in adding another
13715
- // listener, resulting in infinite loops.
13716
- const listeners = Array.from(this.listeners.values());
13717
- for (let i of listeners) {
13718
- try {
13719
- await cb(i);
13720
- }
13721
- catch (ex) {
13722
- this.logger.error(ex);
13723
- this.iterateListeners((l) => l.error?.(ex));
13724
- }
13725
- }
13726
- }
13642
+ __exportStar(requireCommon(), exports$1);
13643
+ __exportStar(requireDeferred(), exports$1);
13644
+ __exportStar(requireErrors(), exports$1);
13645
+ __exportStar(requireFrames(), exports$1);
13646
+ __exportStar(requireRSocket(), exports$1);
13647
+ __exportStar(requireRSocketConnector(), exports$1);
13648
+ __exportStar(requireRSocketServer(), exports$1);
13649
+ __exportStar(requireTransport(), exports$1);
13650
+
13651
+ } (dist));
13652
+ return dist;
13727
13653
  }
13728
13654
 
13655
+ var distExports = requireDist();
13656
+
13657
+ var version = "1.51.0";
13658
+ var PACKAGE = {
13659
+ version: version};
13660
+
13729
13661
  var WebsocketDuplexConnection = {};
13730
13662
 
13731
13663
  var hasRequiredWebsocketDuplexConnection;
@@ -13888,8 +13820,215 @@ class WebsocketClientTransport {
13888
13820
  }
13889
13821
  }
13890
13822
 
13823
+ const doneResult = { done: true, value: undefined };
13824
+ function valueResult(value) {
13825
+ return { done: false, value };
13826
+ }
13827
+ /**
13828
+ * A variant of {@link Array.map} for async iterators.
13829
+ */
13830
+ function map(source, map) {
13831
+ return {
13832
+ next: async () => {
13833
+ const value = await source.next();
13834
+ if (value.done) {
13835
+ return value;
13836
+ }
13837
+ else {
13838
+ return { value: map(value.value) };
13839
+ }
13840
+ }
13841
+ };
13842
+ }
13843
+ /**
13844
+ * Expands a source async iterator by allowing to inject events asynchronously.
13845
+ *
13846
+ * The resulting iterator will emit all events from its source. Additionally though, events can be injected. These
13847
+ * events are dropped once the main iterator completes, but are otherwise forwarded.
13848
+ *
13849
+ * The iterator completes when its source completes, and it supports backpressure by only calling `next()` on the source
13850
+ * in response to a `next()` call from downstream if no pending injected events can be dispatched.
13851
+ */
13852
+ function injectable(source) {
13853
+ let sourceIsDone = false;
13854
+ let waiter = undefined; // An active, waiting next() call.
13855
+ // A pending upstream event that couldn't be dispatched because inject() has been called before it was resolved.
13856
+ let pendingSourceEvent = null;
13857
+ let pendingInjectedEvents = [];
13858
+ const consumeWaiter = () => {
13859
+ const pending = waiter;
13860
+ waiter = undefined;
13861
+ return pending;
13862
+ };
13863
+ const fetchFromSource = () => {
13864
+ const resolveWaiter = (propagate) => {
13865
+ const active = consumeWaiter();
13866
+ if (active) {
13867
+ propagate(active);
13868
+ }
13869
+ else {
13870
+ pendingSourceEvent = propagate;
13871
+ }
13872
+ };
13873
+ const nextFromSource = source.next();
13874
+ nextFromSource.then((value) => {
13875
+ sourceIsDone = value.done == true;
13876
+ resolveWaiter((w) => w.resolve(value));
13877
+ }, (error) => {
13878
+ resolveWaiter((w) => w.reject(error));
13879
+ });
13880
+ };
13881
+ return {
13882
+ next: () => {
13883
+ return new Promise((resolve, reject) => {
13884
+ // First priority: Dispatch ready upstream events.
13885
+ if (sourceIsDone) {
13886
+ return resolve(doneResult);
13887
+ }
13888
+ if (pendingSourceEvent) {
13889
+ pendingSourceEvent({ resolve, reject });
13890
+ pendingSourceEvent = null;
13891
+ return;
13892
+ }
13893
+ // Second priority: Dispatch injected events
13894
+ if (pendingInjectedEvents.length) {
13895
+ return resolve(valueResult(pendingInjectedEvents.shift()));
13896
+ }
13897
+ // Nothing pending? Fetch from source
13898
+ waiter = { resolve, reject };
13899
+ return fetchFromSource();
13900
+ });
13901
+ },
13902
+ inject: (event) => {
13903
+ const pending = consumeWaiter();
13904
+ if (pending != null) {
13905
+ pending.resolve(valueResult(event));
13906
+ }
13907
+ else {
13908
+ pendingInjectedEvents.push(event);
13909
+ }
13910
+ }
13911
+ };
13912
+ }
13913
+ /**
13914
+ * Splits a byte stream at line endings, emitting each line as a string.
13915
+ */
13916
+ function extractJsonLines(source, decoder) {
13917
+ let buffer = '';
13918
+ const pendingLines = [];
13919
+ let isFinalEvent = false;
13920
+ return {
13921
+ next: async () => {
13922
+ while (true) {
13923
+ if (isFinalEvent) {
13924
+ return doneResult;
13925
+ }
13926
+ {
13927
+ const first = pendingLines.shift();
13928
+ if (first) {
13929
+ return { done: false, value: first };
13930
+ }
13931
+ }
13932
+ const { done, value } = await source.next();
13933
+ if (done) {
13934
+ const remaining = buffer.trim();
13935
+ if (remaining.length != 0) {
13936
+ isFinalEvent = true;
13937
+ return { done: false, value: remaining };
13938
+ }
13939
+ return doneResult;
13940
+ }
13941
+ const data = decoder.decode(value, { stream: true });
13942
+ buffer += data;
13943
+ const lines = buffer.split('\n');
13944
+ for (let i = 0; i < lines.length - 1; i++) {
13945
+ const l = lines[i].trim();
13946
+ if (l.length > 0) {
13947
+ pendingLines.push(l);
13948
+ }
13949
+ }
13950
+ buffer = lines[lines.length - 1];
13951
+ }
13952
+ }
13953
+ };
13954
+ }
13955
+ /**
13956
+ * Splits a concatenated stream of BSON objects by emitting individual objects.
13957
+ */
13958
+ function extractBsonObjects(source) {
13959
+ // Fully read but not emitted yet.
13960
+ const completedObjects = [];
13961
+ // Whether source has returned { done: true }. We do the same once completed objects have been emitted.
13962
+ let isDone = false;
13963
+ const lengthBuffer = new DataView(new ArrayBuffer(4));
13964
+ let objectBody = null;
13965
+ // If we're parsing the length field, a number between 1 and 4 (inclusive) describing remaining bytes in the header.
13966
+ // If we're consuming a document, the bytes remaining.
13967
+ let remainingLength = 4;
13968
+ return {
13969
+ async next() {
13970
+ while (true) {
13971
+ // Before fetching new data from upstream, return completed objects.
13972
+ if (completedObjects.length) {
13973
+ return valueResult(completedObjects.shift());
13974
+ }
13975
+ if (isDone) {
13976
+ return doneResult;
13977
+ }
13978
+ const upstreamEvent = await source.next();
13979
+ if (upstreamEvent.done) {
13980
+ isDone = true;
13981
+ if (objectBody || remainingLength != 4) {
13982
+ throw new Error('illegal end of stream in BSON object');
13983
+ }
13984
+ return doneResult;
13985
+ }
13986
+ const chunk = upstreamEvent.value;
13987
+ for (let i = 0; i < chunk.length;) {
13988
+ const availableInData = chunk.length - i;
13989
+ if (objectBody) {
13990
+ // We're in the middle of reading a BSON document.
13991
+ const bytesToRead = Math.min(availableInData, remainingLength);
13992
+ const copySource = new Uint8Array(chunk.buffer, chunk.byteOffset + i, bytesToRead);
13993
+ objectBody.set(copySource, objectBody.length - remainingLength);
13994
+ i += bytesToRead;
13995
+ remainingLength -= bytesToRead;
13996
+ if (remainingLength == 0) {
13997
+ completedObjects.push(objectBody);
13998
+ // Prepare to read another document, starting with its length
13999
+ objectBody = null;
14000
+ remainingLength = 4;
14001
+ }
14002
+ }
14003
+ else {
14004
+ // Copy up to 4 bytes into lengthBuffer, depending on how many we still need.
14005
+ const bytesToRead = Math.min(availableInData, remainingLength);
14006
+ for (let j = 0; j < bytesToRead; j++) {
14007
+ lengthBuffer.setUint8(4 - remainingLength + j, chunk[i + j]);
14008
+ }
14009
+ i += bytesToRead;
14010
+ remainingLength -= bytesToRead;
14011
+ if (remainingLength == 0) {
14012
+ // Transition from reading length header to reading document. Subtracting 4 because the length of the
14013
+ // header is included in length.
14014
+ const length = lengthBuffer.getInt32(0, true /* little endian */);
14015
+ remainingLength = length - 4;
14016
+ if (remainingLength < 1) {
14017
+ throw new Error(`invalid length for bson: ${length}`);
14018
+ }
14019
+ objectBody = new Uint8Array(length);
14020
+ new DataView(objectBody.buffer).setInt32(0, length, true);
14021
+ }
14022
+ }
14023
+ }
14024
+ }
14025
+ }
14026
+ };
14027
+ }
14028
+
13891
14029
  const POWERSYNC_TRAILING_SLASH_MATCH = /\/+$/;
13892
14030
  const POWERSYNC_JS_VERSION = PACKAGE.version;
14031
+ const SYNC_QUEUE_REQUEST_HIGH_WATER = 10;
13893
14032
  const SYNC_QUEUE_REQUEST_LOW_WATER = 5;
13894
14033
  // Keep alive message is sent every period
13895
14034
  const KEEP_ALIVE_MS = 20_000;
@@ -14069,13 +14208,14 @@ class AbstractRemote {
14069
14208
  return new WebSocket(url);
14070
14209
  }
14071
14210
  /**
14072
- * Returns a data stream of sync line data.
14211
+ * Returns a data stream of sync line data, fetched via RSocket-over-WebSocket.
14212
+ *
14213
+ * The only mechanism to abort the returned stream is to use the abort signal in {@link SocketSyncStreamOptions}.
14073
14214
  *
14074
- * @param map Maps received payload frames to the typed event value.
14075
14215
  * @param bson A BSON encoder and decoder. When set, the data stream will be requested with a BSON payload
14076
14216
  * (required for compatibility with older sync services).
14077
14217
  */
14078
- async socketStreamRaw(options, map, bson) {
14218
+ async socketStreamRaw(options, bson) {
14079
14219
  const { path, fetchStrategy = FetchStrategy.Buffered } = options;
14080
14220
  const mimeType = bson == null ? 'application/json' : 'application/bson';
14081
14221
  function toBuffer(js) {
@@ -14090,52 +14230,55 @@ class AbstractRemote {
14090
14230
  }
14091
14231
  const syncQueueRequestSize = fetchStrategy == FetchStrategy.Buffered ? 10 : 1;
14092
14232
  const request = await this.buildRequest(path);
14233
+ const url = this.options.socketUrlTransformer(request.url);
14093
14234
  // Add the user agent in the setup payload - we can't set custom
14094
14235
  // headers with websockets on web. The browser userAgent is however added
14095
14236
  // automatically as a header.
14096
14237
  const userAgent = this.getUserAgent();
14097
- const stream = new DataStream({
14098
- logger: this.logger,
14099
- pressure: {
14100
- lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER
14101
- },
14102
- mapLine: map
14103
- });
14238
+ // While we're connecting (a process that can't be aborted in RSocket), the WebSocket instance to close if we wanted
14239
+ // to abort the connection.
14240
+ let pendingSocket = null;
14241
+ let keepAliveTimeout;
14242
+ let rsocket = null;
14243
+ let queue = null;
14244
+ let didClose = false;
14245
+ const abortRequest = () => {
14246
+ if (didClose) {
14247
+ return;
14248
+ }
14249
+ didClose = true;
14250
+ clearTimeout(keepAliveTimeout);
14251
+ if (pendingSocket) {
14252
+ pendingSocket.close();
14253
+ }
14254
+ if (rsocket) {
14255
+ rsocket.close();
14256
+ }
14257
+ if (queue) {
14258
+ queue.stop();
14259
+ }
14260
+ };
14104
14261
  // Handle upstream abort
14105
- if (options.abortSignal?.aborted) {
14262
+ if (options.abortSignal.aborted) {
14106
14263
  throw new AbortOperation('Connection request aborted');
14107
14264
  }
14108
14265
  else {
14109
- options.abortSignal?.addEventListener('abort', () => {
14110
- stream.close();
14111
- }, { once: true });
14266
+ options.abortSignal.addEventListener('abort', abortRequest);
14112
14267
  }
14113
- let keepAliveTimeout;
14114
14268
  const resetTimeout = () => {
14115
14269
  clearTimeout(keepAliveTimeout);
14116
14270
  keepAliveTimeout = setTimeout(() => {
14117
14271
  this.logger.error(`No data received on WebSocket in ${SOCKET_TIMEOUT_MS}ms, closing connection.`);
14118
- stream.close();
14272
+ abortRequest();
14119
14273
  }, SOCKET_TIMEOUT_MS);
14120
14274
  };
14121
14275
  resetTimeout();
14122
- // Typescript complains about this being `never` if it's not assigned here.
14123
- // This is assigned in `wsCreator`.
14124
- let disposeSocketConnectionTimeout = () => { };
14125
- const url = this.options.socketUrlTransformer(request.url);
14126
14276
  const connector = new distExports.RSocketConnector({
14127
14277
  transport: new WebsocketClientTransport({
14128
14278
  url,
14129
14279
  wsCreator: (url) => {
14130
- const socket = this.createSocket(url);
14131
- disposeSocketConnectionTimeout = stream.registerListener({
14132
- closed: () => {
14133
- // Allow closing the underlying WebSocket if the stream was closed before the
14134
- // RSocket connect completed. This should effectively abort the request.
14135
- socket.close();
14136
- }
14137
- });
14138
- socket.addEventListener('message', (event) => {
14280
+ const socket = (pendingSocket = this.createSocket(url));
14281
+ socket.addEventListener('message', () => {
14139
14282
  resetTimeout();
14140
14283
  });
14141
14284
  return socket;
@@ -14155,43 +14298,40 @@ class AbstractRemote {
14155
14298
  }
14156
14299
  }
14157
14300
  });
14158
- let rsocket;
14159
14301
  try {
14160
14302
  rsocket = await connector.connect();
14161
14303
  // The connection is established, we no longer need to monitor the initial timeout
14162
- disposeSocketConnectionTimeout();
14304
+ pendingSocket = null;
14163
14305
  }
14164
14306
  catch (ex) {
14165
14307
  this.logger.error(`Failed to connect WebSocket`, ex);
14166
- clearTimeout(keepAliveTimeout);
14167
- if (!stream.closed) {
14168
- await stream.close();
14169
- }
14308
+ abortRequest();
14170
14309
  throw ex;
14171
14310
  }
14172
14311
  resetTimeout();
14173
- let socketIsClosed = false;
14174
- const closeSocket = () => {
14175
- clearTimeout(keepAliveTimeout);
14176
- if (socketIsClosed) {
14177
- return;
14178
- }
14179
- socketIsClosed = true;
14180
- rsocket.close();
14181
- };
14182
14312
  // Helps to prevent double close scenarios
14183
- rsocket.onClose(() => (socketIsClosed = true));
14184
- // We initially request this amount and expect these to arrive eventually
14185
- let pendingEventsCount = syncQueueRequestSize;
14186
- const disposeClosedListener = stream.registerListener({
14187
- closed: () => {
14188
- closeSocket();
14189
- disposeClosedListener();
14190
- }
14191
- });
14192
- const socket = await new Promise((resolve, reject) => {
14313
+ rsocket.onClose(() => (rsocket = null));
14314
+ return await new Promise((resolve, reject) => {
14193
14315
  let connectionEstablished = false;
14194
- const res = rsocket.requestStream({
14316
+ let pendingEventsCount = syncQueueRequestSize;
14317
+ let paused = false;
14318
+ let res = null;
14319
+ function requestMore() {
14320
+ const delta = syncQueueRequestSize - pendingEventsCount;
14321
+ if (!paused && delta > 0) {
14322
+ res?.request(delta);
14323
+ pendingEventsCount = syncQueueRequestSize;
14324
+ }
14325
+ }
14326
+ const events = new domExports.EventIterator((q) => {
14327
+ queue = q;
14328
+ q.on('highWater', () => (paused = true));
14329
+ q.on('lowWater', () => {
14330
+ paused = false;
14331
+ requestMore();
14332
+ });
14333
+ }, { highWaterMark: SYNC_QUEUE_REQUEST_HIGH_WATER, lowWaterMark: SYNC_QUEUE_REQUEST_LOW_WATER })[symbolAsyncIterator]();
14334
+ res = rsocket.requestStream({
14195
14335
  data: toBuffer(options.data),
14196
14336
  metadata: toBuffer({
14197
14337
  path
@@ -14216,7 +14356,7 @@ class AbstractRemote {
14216
14356
  }
14217
14357
  // RSocket will close the RSocket stream automatically
14218
14358
  // Close the downstream stream as well - this will close the RSocket connection and WebSocket
14219
- stream.close();
14359
+ abortRequest();
14220
14360
  // Handles cases where the connection failed e.g. auth error or connection error
14221
14361
  if (!connectionEstablished) {
14222
14362
  reject(e);
@@ -14226,41 +14366,40 @@ class AbstractRemote {
14226
14366
  // The connection is active
14227
14367
  if (!connectionEstablished) {
14228
14368
  connectionEstablished = true;
14229
- resolve(res);
14369
+ resolve(events);
14230
14370
  }
14231
14371
  const { data } = payload;
14372
+ if (data) {
14373
+ queue.push(data);
14374
+ }
14232
14375
  // Less events are now pending
14233
14376
  pendingEventsCount--;
14234
- if (!data) {
14235
- return;
14236
- }
14237
- stream.enqueueData(data);
14377
+ // Request another event (unless the downstream consumer is paused).
14378
+ requestMore();
14238
14379
  },
14239
14380
  onComplete: () => {
14240
- stream.close();
14381
+ abortRequest(); // this will also emit a done event
14241
14382
  },
14242
14383
  onExtension: () => { }
14243
14384
  });
14244
14385
  });
14245
- const l = stream.registerListener({
14246
- lowWater: async () => {
14247
- // Request to fill up the queue
14248
- const required = syncQueueRequestSize - pendingEventsCount;
14249
- if (required > 0) {
14250
- socket.request(syncQueueRequestSize - pendingEventsCount);
14251
- pendingEventsCount = syncQueueRequestSize;
14252
- }
14253
- },
14254
- closed: () => {
14255
- l();
14256
- }
14257
- });
14258
- return stream;
14259
14386
  }
14260
14387
  /**
14261
- * Connects to the sync/stream http endpoint, mapping and emitting each received string line.
14388
+ * @returns Whether the HTTP implementation on this platform can receive streamed binary responses. This is true on
14389
+ * all platforms except React Native (who would have guessed...), where we must not request BSON responses.
14390
+ *
14391
+ * @see https://github.com/react-native-community/fetch?tab=readme-ov-file#motivation
14392
+ */
14393
+ get supportsStreamingBinaryResponses() {
14394
+ return true;
14395
+ }
14396
+ /**
14397
+ * Posts a `/sync/stream` request, asserts that it completes successfully and returns the streaming response as an
14398
+ * async iterator of byte blobs.
14399
+ *
14400
+ * To cancel the async iterator, use the abort signal from {@link SyncStreamOptions} passed to this method.
14262
14401
  */
14263
- async postStreamRaw(options, mapLine) {
14402
+ async fetchStreamRaw(options) {
14264
14403
  const { data, path, headers, abortSignal } = options;
14265
14404
  const request = await this.buildRequest(path);
14266
14405
  /**
@@ -14272,119 +14411,94 @@ class AbstractRemote {
14272
14411
  * Aborting the active fetch request while it is being consumed seems to throw
14273
14412
  * an unhandled exception on the window level.
14274
14413
  */
14275
- if (abortSignal?.aborted) {
14276
- throw new AbortOperation('Abort request received before making postStreamRaw request');
14414
+ if (abortSignal.aborted) {
14415
+ throw new AbortOperation('Abort request received before making fetchStreamRaw request');
14277
14416
  }
14278
14417
  const controller = new AbortController();
14279
- let requestResolved = false;
14280
- abortSignal?.addEventListener('abort', () => {
14281
- if (!requestResolved) {
14418
+ let reader = null;
14419
+ abortSignal.addEventListener('abort', () => {
14420
+ const reason = abortSignal.reason ??
14421
+ new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.');
14422
+ if (reader == null) {
14282
14423
  // Only abort via the abort controller if the request has not resolved yet
14283
- controller.abort(abortSignal.reason ??
14284
- new AbortOperation('Cancelling network request before it resolves. Abort signal has been received.'));
14424
+ controller.abort(reason);
14425
+ }
14426
+ else {
14427
+ reader.cancel(reason).catch(() => {
14428
+ // Cancelling the reader might rethrow an exception we would have handled by throwing in next(). So we can
14429
+ // ignore it here.
14430
+ });
14285
14431
  }
14286
14432
  });
14287
- const res = await this.fetch(request.url, {
14288
- method: 'POST',
14289
- headers: { ...headers, ...request.headers },
14290
- body: JSON.stringify(data),
14291
- signal: controller.signal,
14292
- cache: 'no-store',
14293
- ...(this.options.fetchOptions ?? {}),
14294
- ...options.fetchOptions
14295
- }).catch((ex) => {
14433
+ let res;
14434
+ let responseIsBson = false;
14435
+ try {
14436
+ const ndJson = 'application/x-ndjson';
14437
+ const bson = 'application/vnd.powersync.bson-stream';
14438
+ res = await this.fetch(request.url, {
14439
+ method: 'POST',
14440
+ headers: {
14441
+ ...headers,
14442
+ ...request.headers,
14443
+ accept: this.supportsStreamingBinaryResponses ? `${bson};q=0.9,${ndJson};q=0.8` : ndJson
14444
+ },
14445
+ body: JSON.stringify(data),
14446
+ signal: controller.signal,
14447
+ cache: 'no-store',
14448
+ ...(this.options.fetchOptions ?? {}),
14449
+ ...options.fetchOptions
14450
+ });
14451
+ if (!res.ok || !res.body) {
14452
+ const text = await res.text();
14453
+ this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
14454
+ const error = new Error(`HTTP ${res.statusText}: ${text}`);
14455
+ error.status = res.status;
14456
+ throw error;
14457
+ }
14458
+ const contentType = res.headers.get('content-type');
14459
+ responseIsBson = contentType == bson;
14460
+ }
14461
+ catch (ex) {
14296
14462
  if (ex.name == 'AbortError') {
14297
14463
  throw new AbortOperation(`Pending fetch request to ${request.url} has been aborted.`);
14298
14464
  }
14299
14465
  throw ex;
14300
- });
14301
- if (!res) {
14302
- throw new Error('Fetch request was aborted');
14303
14466
  }
14304
- requestResolved = true;
14305
- if (!res.ok || !res.body) {
14306
- const text = await res.text();
14307
- this.logger.error(`Could not POST streaming to ${path} - ${res.status} - ${res.statusText}: ${text}`);
14308
- const error = new Error(`HTTP ${res.statusText}: ${text}`);
14309
- error.status = res.status;
14310
- throw error;
14311
- }
14312
- // Create a new stream splitting the response at line endings while also handling cancellations
14313
- // by closing the reader.
14314
- const reader = res.body.getReader();
14315
- let readerReleased = false;
14316
- // This will close the network request and read stream
14317
- const closeReader = async () => {
14318
- try {
14319
- readerReleased = true;
14320
- await reader.cancel();
14321
- }
14322
- catch (ex) {
14323
- // an error will throw if the reader hasn't been used yet
14324
- }
14325
- reader.releaseLock();
14326
- };
14327
- const stream = new DataStream({
14328
- logger: this.logger,
14329
- mapLine: mapLine,
14330
- pressure: {
14331
- highWaterMark: 20,
14332
- lowWaterMark: 10
14333
- }
14334
- });
14335
- abortSignal?.addEventListener('abort', () => {
14336
- closeReader();
14337
- stream.close();
14338
- });
14339
- const decoder = this.createTextDecoder();
14340
- let buffer = '';
14341
- const consumeStream = async () => {
14342
- while (!stream.closed && !abortSignal?.aborted && !readerReleased) {
14343
- const { done, value } = await reader.read();
14344
- if (done) {
14345
- const remaining = buffer.trim();
14346
- if (remaining.length != 0) {
14347
- stream.enqueueData(remaining);
14348
- }
14349
- stream.close();
14350
- await closeReader();
14351
- return;
14467
+ reader = res.body.getReader();
14468
+ const stream = {
14469
+ next: async () => {
14470
+ if (controller.signal.aborted) {
14471
+ return doneResult;
14352
14472
  }
14353
- const data = decoder.decode(value, { stream: true });
14354
- buffer += data;
14355
- const lines = buffer.split('\n');
14356
- for (var i = 0; i < lines.length - 1; i++) {
14357
- var l = lines[i].trim();
14358
- if (l.length > 0) {
14359
- stream.enqueueData(l);
14360
- }
14473
+ try {
14474
+ return await reader.read();
14361
14475
  }
14362
- buffer = lines[lines.length - 1];
14363
- // Implement backpressure by waiting for the low water mark to be reached
14364
- if (stream.dataQueue.length > stream.highWatermark) {
14365
- await new Promise((resolve) => {
14366
- const dispose = stream.registerListener({
14367
- lowWater: async () => {
14368
- resolve();
14369
- dispose();
14370
- },
14371
- closed: () => {
14372
- resolve();
14373
- dispose();
14374
- }
14375
- });
14376
- });
14476
+ catch (ex) {
14477
+ if (controller.signal.aborted) {
14478
+ // .read() completes with an error if we cancel the reader, which we do to disconnect. So this is just
14479
+ // things working as intended, we can return a done event and consider the exception handled.
14480
+ return doneResult;
14481
+ }
14482
+ throw ex;
14377
14483
  }
14378
14484
  }
14379
14485
  };
14380
- consumeStream().catch(ex => this.logger.error('Error consuming stream', ex));
14381
- const l = stream.registerListener({
14382
- closed: () => {
14383
- closeReader();
14384
- l?.();
14385
- }
14386
- });
14387
- return stream;
14486
+ return { isBson: responseIsBson, stream };
14487
+ }
14488
+ /**
14489
+ * Posts a `/sync/stream` request.
14490
+ *
14491
+ * Depending on the `Content-Type` of the response, this returns strings for sync lines or encoded BSON documents as
14492
+ * {@link Uint8Array}s.
14493
+ */
14494
+ async fetchStream(options) {
14495
+ const { isBson, stream } = await this.fetchStreamRaw(options);
14496
+ if (isBson) {
14497
+ return extractBsonObjects(stream);
14498
+ }
14499
+ else {
14500
+ return extractJsonLines(stream, this.createTextDecoder());
14501
+ }
14388
14502
  }
14389
14503
  }
14390
14504
 
@@ -14892,6 +15006,19 @@ The next upload iteration will be delayed.`);
14892
15006
  }
14893
15007
  });
14894
15008
  }
15009
+ async receiveSyncLines(data) {
15010
+ const { options, connection, bson } = data;
15011
+ const remote = this.options.remote;
15012
+ if (connection.connectionMethod == SyncStreamConnectionMethod.HTTP) {
15013
+ return await remote.fetchStream(options);
15014
+ }
15015
+ else {
15016
+ return await this.options.remote.socketStreamRaw({
15017
+ ...options,
15018
+ ...{ fetchStrategy: connection.fetchStrategy }
15019
+ }, bson);
15020
+ }
15021
+ }
14895
15022
  async legacyStreamingSyncIteration(signal, resolvedOptions) {
14896
15023
  const rawTables = resolvedOptions.serializedSchema?.raw_tables;
14897
15024
  if (rawTables != null && rawTables.length) {
@@ -14921,42 +15048,27 @@ The next upload iteration will be delayed.`);
14921
15048
  client_id: clientId
14922
15049
  }
14923
15050
  };
14924
- let stream;
14925
- if (resolvedOptions?.connectionMethod == SyncStreamConnectionMethod.HTTP) {
14926
- stream = await this.options.remote.postStreamRaw(syncOptions, (line) => {
14927
- if (typeof line == 'string') {
14928
- return JSON.parse(line);
14929
- }
14930
- else {
14931
- // Directly enqueued by us
14932
- return line;
14933
- }
14934
- });
14935
- }
14936
- else {
14937
- const bson = await this.options.remote.getBSON();
14938
- stream = await this.options.remote.socketStreamRaw({
14939
- ...syncOptions,
14940
- ...{ fetchStrategy: resolvedOptions.fetchStrategy }
14941
- }, (payload) => {
14942
- if (payload instanceof Uint8Array) {
14943
- return bson.deserialize(payload);
14944
- }
14945
- else {
14946
- // Directly enqueued by us
14947
- return payload;
14948
- }
14949
- }, bson);
14950
- }
15051
+ const bson = await this.options.remote.getBSON();
15052
+ const source = await this.receiveSyncLines({
15053
+ options: syncOptions,
15054
+ connection: resolvedOptions,
15055
+ bson
15056
+ });
15057
+ const stream = injectable(map(source, (line) => {
15058
+ if (typeof line == 'string') {
15059
+ return JSON.parse(line);
15060
+ }
15061
+ else {
15062
+ return bson.deserialize(line);
15063
+ }
15064
+ }));
14951
15065
  this.logger.debug('Stream established. Processing events');
14952
15066
  this.notifyCompletedUploads = () => {
14953
- if (!stream.closed) {
14954
- stream.enqueueData({ crud_upload_completed: null });
14955
- }
15067
+ stream.inject({ crud_upload_completed: null });
14956
15068
  };
14957
- while (!stream.closed) {
14958
- const line = await stream.read();
14959
- if (!line) {
15069
+ while (true) {
15070
+ const { value: line, done } = await stream.next();
15071
+ if (done) {
14960
15072
  // The stream has closed while waiting
14961
15073
  return;
14962
15074
  }
@@ -15135,14 +15247,17 @@ The next upload iteration will be delayed.`);
15135
15247
  const syncImplementation = this;
15136
15248
  const adapter = this.options.adapter;
15137
15249
  const remote = this.options.remote;
15250
+ const controller = new AbortController();
15251
+ const abort = () => {
15252
+ return controller.abort(signal.reason);
15253
+ };
15254
+ signal.addEventListener('abort', abort);
15138
15255
  let receivingLines = null;
15139
15256
  let hadSyncLine = false;
15140
15257
  let hideDisconnectOnRestart = false;
15141
15258
  if (signal.aborted) {
15142
15259
  throw new AbortOperation('Connection request has been aborted');
15143
15260
  }
15144
- const abortController = new AbortController();
15145
- signal.addEventListener('abort', () => abortController.abort());
15146
15261
  // Pending sync lines received from the service, as well as local events that trigger a powersync_control
15147
15262
  // invocation (local events include refreshed tokens and completed uploads).
15148
15263
  // This is a single data stream so that we can handle all control calls from a single place.
@@ -15150,49 +15265,36 @@ The next upload iteration will be delayed.`);
15150
15265
  async function connect(instr) {
15151
15266
  const syncOptions = {
15152
15267
  path: '/sync/stream',
15153
- abortSignal: abortController.signal,
15268
+ abortSignal: controller.signal,
15154
15269
  data: instr.request
15155
15270
  };
15156
- if (resolvedOptions.connectionMethod == SyncStreamConnectionMethod.HTTP) {
15157
- controlInvocations = await remote.postStreamRaw(syncOptions, (line) => {
15158
- if (typeof line == 'string') {
15159
- return {
15160
- command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
15161
- payload: line
15162
- };
15163
- }
15164
- else {
15165
- // Directly enqueued by us
15166
- return line;
15167
- }
15168
- });
15169
- }
15170
- else {
15171
- controlInvocations = await remote.socketStreamRaw({
15172
- ...syncOptions,
15173
- fetchStrategy: resolvedOptions.fetchStrategy
15174
- }, (payload) => {
15175
- if (payload instanceof Uint8Array) {
15176
- return {
15177
- command: PowerSyncControlCommand.PROCESS_BSON_LINE,
15178
- payload: payload
15179
- };
15180
- }
15181
- else {
15182
- // Directly enqueued by us
15183
- return payload;
15184
- }
15185
- });
15186
- }
15271
+ controlInvocations = injectable(map(await syncImplementation.receiveSyncLines({
15272
+ options: syncOptions,
15273
+ connection: resolvedOptions
15274
+ }), (line) => {
15275
+ if (typeof line == 'string') {
15276
+ return {
15277
+ command: PowerSyncControlCommand.PROCESS_TEXT_LINE,
15278
+ payload: line
15279
+ };
15280
+ }
15281
+ else {
15282
+ return {
15283
+ command: PowerSyncControlCommand.PROCESS_BSON_LINE,
15284
+ payload: line
15285
+ };
15286
+ }
15287
+ }));
15187
15288
  // The rust client will set connected: true after the first sync line because that's when it gets invoked, but
15188
15289
  // we're already connected here and can report that.
15189
15290
  syncImplementation.updateSyncStatus({ connected: true });
15190
15291
  try {
15191
- while (!controlInvocations.closed) {
15192
- const line = await controlInvocations.read();
15193
- if (line == null) {
15194
- return;
15292
+ while (true) {
15293
+ let event = await controlInvocations.next();
15294
+ if (event.done) {
15295
+ break;
15195
15296
  }
15297
+ const line = event.value;
15196
15298
  await control(line.command, line.payload);
15197
15299
  if (!hadSyncLine) {
15198
15300
  syncImplementation.triggerCrudUpload();
@@ -15201,12 +15303,8 @@ The next upload iteration will be delayed.`);
15201
15303
  }
15202
15304
  }
15203
15305
  finally {
15204
- const activeInstructions = controlInvocations;
15205
- // We concurrently add events to the active data stream when e.g. a CRUD upload is completed or a token is
15206
- // refreshed. That would throw after closing (and we can't handle those events either way), so set this back
15207
- // to null.
15208
- controlInvocations = null;
15209
- await activeInstructions.close();
15306
+ abort();
15307
+ signal.removeEventListener('abort', abort);
15210
15308
  }
15211
15309
  }
15212
15310
  async function stop() {
@@ -15250,14 +15348,14 @@ The next upload iteration will be delayed.`);
15250
15348
  remote.invalidateCredentials();
15251
15349
  // Restart iteration after the credentials have been refreshed.
15252
15350
  remote.fetchCredentials().then((_) => {
15253
- controlInvocations?.enqueueData({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
15351
+ controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_TOKEN_REFRESHED });
15254
15352
  }, (err) => {
15255
15353
  syncImplementation.logger.warn('Could not prefetch credentials', err);
15256
15354
  });
15257
15355
  }
15258
15356
  }
15259
15357
  else if ('CloseSyncStream' in instruction) {
15260
- abortController.abort();
15358
+ controller.abort();
15261
15359
  hideDisconnectOnRestart = instruction.CloseSyncStream.hide_disconnect;
15262
15360
  }
15263
15361
  else if ('FlushFileSystem' in instruction) ;
@@ -15286,17 +15384,13 @@ The next upload iteration will be delayed.`);
15286
15384
  }
15287
15385
  await control(PowerSyncControlCommand.START, JSON.stringify(options));
15288
15386
  this.notifyCompletedUploads = () => {
15289
- if (controlInvocations && !controlInvocations?.closed) {
15290
- controlInvocations.enqueueData({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
15291
- }
15387
+ controlInvocations?.inject({ command: PowerSyncControlCommand.NOTIFY_CRUD_UPLOAD_COMPLETED });
15292
15388
  };
15293
15389
  this.handleActiveStreamsChange = () => {
15294
- if (controlInvocations && !controlInvocations?.closed) {
15295
- controlInvocations.enqueueData({
15296
- command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
15297
- payload: JSON.stringify(this.activeStreams)
15298
- });
15299
- }
15390
+ controlInvocations?.inject({
15391
+ command: PowerSyncControlCommand.UPDATE_SUBSCRIPTIONS,
15392
+ payload: JSON.stringify(this.activeStreams)
15393
+ });
15300
15394
  };
15301
15395
  await receivingLines;
15302
15396
  }
@@ -15947,7 +16041,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
15947
16041
  this._schema = schema;
15948
16042
  this.ready = false;
15949
16043
  this.sdkVersion = '';
15950
- this.runExclusiveMutex = new async_mutex__WEBPACK_IMPORTED_MODULE_0__.Mutex();
16044
+ this.runExclusiveMutex = new Mutex();
15951
16045
  // Start async init
15952
16046
  this.subscriptions = {
15953
16047
  firstStatusMatching: (predicate, abort) => this.waitForStatus(predicate, abort),
@@ -16412,6 +16506,10 @@ SELECT * FROM crud_entries;
16412
16506
  * Execute a SQL write (INSERT/UPDATE/DELETE) query
16413
16507
  * and optionally return results.
16414
16508
  *
16509
+ * When using the default client-side [JSON-based view system](https://docs.powersync.com/architecture/client-architecture#client-side-schema-and-sqlite-database-structure),
16510
+ * the returned result's `rowsAffected` may be `0` for successful `UPDATE` and `DELETE` statements.
16511
+ * Use a `RETURNING` clause and inspect `result.rows` when you need to confirm which rows changed.
16512
+ *
16415
16513
  * @param sql The SQL query to execute
16416
16514
  * @param parameters Optional array of parameters to bind to the query
16417
16515
  * @returns The query result as an object with structured key-value pairs
@@ -16508,7 +16606,7 @@ SELECT * FROM crud_entries;
16508
16606
  async readTransaction(callback, lockTimeout = DEFAULT_LOCK_TIMEOUT_MS) {
16509
16607
  await this.waitForReady();
16510
16608
  return this.database.readTransaction(async (tx) => {
16511
- const res = await callback({ ...tx });
16609
+ const res = await callback(tx);
16512
16610
  await tx.rollback();
16513
16611
  return res;
16514
16612
  }, { timeoutMs: lockTimeout });
@@ -17664,9 +17762,7 @@ __webpack_require__.r(__webpack_exports__);
17664
17762
  /* harmony import */ var _journeyapps_wa_sqlite__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @journeyapps/wa-sqlite */ "../../node_modules/.pnpm/@journeyapps+wa-sqlite@1.5.0/node_modules/@journeyapps/wa-sqlite/src/sqlite-api.js");
17665
17763
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
17666
17764
  /* 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");
17667
- /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
17668
- /* harmony import */ var _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SharedWASQLiteConnection.js */ "./lib/src/worker/db/SharedWASQLiteConnection.js");
17669
- /* harmony import */ var _WorkerWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./WorkerWASQLiteConnection.js */ "./lib/src/worker/db/WorkerWASQLiteConnection.js");
17765
+ /* harmony import */ var _MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./MultiDatabaseServer.js */ "./lib/src/worker/db/MultiDatabaseServer.js");
17670
17766
  /**
17671
17767
  * Supports both shared and dedicated workers, based on how the worker is constructed (new SharedWorker vs new Worker()).
17672
17768
  */
@@ -17674,67 +17770,28 @@ __webpack_require__.r(__webpack_exports__);
17674
17770
 
17675
17771
 
17676
17772
 
17677
-
17678
-
17679
17773
  const baseLogger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_1__.createBaseLogger)();
17680
17774
  baseLogger.useDefaults();
17681
17775
  const logger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_1__.createLogger)('db-worker');
17682
- const DBMap = new Map();
17683
- const OPEN_DB_LOCK = 'open-wasqlite-db';
17684
- let nextClientId = 1;
17685
- const openDBShared = async (options) => {
17686
- // Prevent multiple simultaneous opens from causing race conditions
17687
- return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
17688
- const clientId = nextClientId++;
17689
- const { dbFilename, logLevel } = options;
17690
- logger.setLevel(logLevel);
17691
- if (!DBMap.has(dbFilename)) {
17692
- const clientIds = new Set();
17693
- // This format returns proxy objects for function callbacks
17694
- const connection = new _WorkerWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_5__.WorkerWASQLiteConnection(options);
17695
- await connection.init();
17696
- connection.registerListener({
17697
- holdOverwritten: async () => {
17698
- /**
17699
- * The previous hold has been overwritten, without being released.
17700
- * we need to cleanup any resources associated with it.
17701
- * We can perform a rollback to release any potential transactions that were started.
17702
- */
17703
- await connection.execute('ROLLBACK').catch(() => { });
17704
- }
17705
- });
17706
- DBMap.set(dbFilename, {
17707
- clientIds,
17708
- db: connection
17709
- });
17710
- }
17711
- // Associates this clientId with the shared connection entry
17712
- const sharedConnection = new _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__.SharedWASQLiteConnection({
17713
- dbMap: DBMap,
17714
- dbFilename,
17715
- clientId,
17716
- logger
17717
- });
17718
- return comlink__WEBPACK_IMPORTED_MODULE_2__.proxy(sharedConnection);
17719
- });
17776
+ const server = new _MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__.MultiDatabaseServer(logger);
17777
+ const exposedFunctions = {
17778
+ connect: (config) => server.handleConnection(config),
17779
+ connectToExisting: ({ identifier, lockName }) => server.connectToExisting(identifier, lockName)
17720
17780
  };
17721
17781
  // Check if we're in a SharedWorker context
17722
- if (typeof SharedWorkerGlobalScope !== 'undefined') {
17782
+ if (_MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__.isSharedWorker) {
17723
17783
  const _self = self;
17724
17784
  _self.onconnect = function (event) {
17725
17785
  const port = event.ports[0];
17726
- comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared, port);
17786
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(exposedFunctions, port);
17727
17787
  };
17728
17788
  }
17729
17789
  else {
17730
17790
  // A dedicated worker can be shared externally
17731
- comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared);
17791
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(exposedFunctions);
17732
17792
  }
17733
17793
  addEventListener('unload', () => {
17734
- Array.from(DBMap.values()).forEach(async (dbConnection) => {
17735
- const { db } = dbConnection;
17736
- db.close?.();
17737
- });
17794
+ server.closeAll();
17738
17795
  });
17739
17796
 
17740
17797
  })();