@powersync/web 1.36.0 → 1.37.1

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 +1127 -1235
  2. package/dist/index.umd.js.map +1 -1
  3. package/dist/worker/SharedSyncImplementation.umd.js +550 -3089
  4. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  5. package/dist/worker/WASQLiteDB.umd.js +797 -854
  6. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  7. package/lib/package.json +2 -3
  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 +3 -4
  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 -1881
  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 -404
  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 -489
  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");
2431
-
2432
-
2112
+ /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
2433
2113
 
2434
2114
  /**
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
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.
2473
2122
  */
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();
2123
+ class ConcurrentSqliteConnection {
2124
+ inner;
2125
+ /**
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.
2129
+ */
2130
+ leaseMutex;
2131
+ /**
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..
2137
+ */
2138
+ constructor(inner, needsNavigatorLocks) {
2139
+ this.inner = inner;
2140
+ this.leaseMutex = needsNavigatorLocks ? null : new _powersync_common__WEBPACK_IMPORTED_MODULE_0__.Mutex();
2141
+ }
2142
+ get options() {
2143
+ return this.inner.options;
2144
+ }
2145
+ acquireMutex(abort) {
2146
+ if (this.leaseMutex) {
2147
+ return this.leaseMutex.acquire(abort);
2482
2148
  }
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();
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;
2165
+ }
2166
+ /**
2167
+ * @returns A {@link ConnectionLeaseToken}. Until that token is returned, no other client can use the database.
2168
+ */
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
+ }
2494
2181
  }
2495
- else {
2496
- module = await SyncWASQLiteModuleFactory();
2182
+ catch (e) {
2183
+ returnMutex();
2184
+ throw e;
2497
2185
  }
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();
2186
+ return token;
2187
+ }
2188
+ async close() {
2189
+ const returnMutex = await this.acquireMutex();
2190
+ try {
2191
+ await this.inner.close();
2509
2192
  }
2510
- else {
2511
- module = await SyncWASQLiteModuleFactory();
2193
+ finally {
2194
+ returnMutex();
2512
2195
  }
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
2196
  }
2521
- };
2197
+ }
2522
2198
  /**
2523
- * @internal
2524
- * WA-SQLite connection which directly interfaces with WA-SQLite.
2525
- * This is usually instantiated inside a worker.
2199
+ * An instance representing temporary exclusive access to a {@link ConcurrentSqliteConnection}.
2526
2200
  */
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;
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;
2210
+ }
2536
2211
  /**
2537
- * Unique id for this specific connection. This is used to prevent broadcast table change
2538
- * notification loops.
2212
+ * Returns this lease, allowing another client to use the database connection.
2539
2213
  */
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;
2214
+ async returnLease() {
2215
+ await this.useMutex.runExclusive(async () => {
2216
+ if (!this.closed) {
2217
+ this.closed = true;
2218
+ this.returnMutex();
2219
+ }
2220
+ });
2554
2221
  }
2555
2222
  /**
2556
- * Gets the id for the current hold.
2557
- * This can be used to check for invalid states.
2223
+ * This should only be used internally, since the callback must not use the raw connection after resolving.
2558
2224
  */
2559
- get currentHoldId() {
2560
- return this._holdId;
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
+ });
2561
2232
  }
2562
- get sqliteAPI() {
2563
- if (!this._sqliteAPI) {
2564
- throw new Error(`Initialization has not completed`);
2565
- }
2566
- return this._sqliteAPI;
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
+ };
2567
2266
  }
2568
- get dbP() {
2569
- if (!this._dbP) {
2570
- throw new Error(`Initialization has not completed`);
2267
+ #pushTableUpdateToClients(changedTables) {
2268
+ for (const listener of this.#clientTableListeners) {
2269
+ listener.postMessage(changedTables);
2571
2270
  }
2572
- return this._dbP;
2271
+ }
2272
+ get #inner() {
2273
+ return this.#options.inner;
2274
+ }
2275
+ get #logger() {
2276
+ return this.#options.logger;
2573
2277
  }
2574
2278
  /**
2575
- * Checks if the database connection is in autocommit mode.
2576
- * @returns true if in autocommit mode, false if in a transaction
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.
2577
2283
  */
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));
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
+ }
2586
2294
  }
2587
- return this._holdId;
2588
- }
2589
- async releaseHold(holdId) {
2590
- if (holdId != this._holdId) {
2591
- throw new Error(`Invalid hold state, expected ${this._holdId} but got ${holdId}`);
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;
2592
2302
  }
2593
- this._holdId = null;
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];
2594
2429
  }
2595
- async openDB() {
2596
- this._dbP = await this.sqliteAPI.open_v2(this.options.dbFilename);
2597
- return this._dbP;
2430
+ get isOpen() {
2431
+ return this.db != 0;
2598
2432
  }
2599
- async executeEncryptionPragma() {
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};`);
2600
2437
  if (this.options.encryptionKey) {
2601
- await this.executeSingleStatement(`PRAGMA key = "${this.options.encryptionKey}"`);
2438
+ const escapedKey = this.options.encryptionKey.replace("'", "''");
2439
+ await this.executeRaw(`PRAGMA key = '${escapedKey}'`);
2602
2440
  }
2603
- return;
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
- });
2480
+ const resultSet = await this.executeSingleStatementRaw(sql, bindings);
2481
+ return this.wrapQueryResults(this.requireSqlite(), resultSet);
2753
2482
  }
2754
- async registerOnTableChange(callback) {
2755
- return this.registerListener({
2756
- tablesUpdated: (event) => callback(event)
2757
- });
2758
- }
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,7 +2526,145 @@ 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
+ }
2556
+ }
2557
+
2558
+
2559
+ /***/ },
2560
+
2561
+ /***/ "./lib/src/db/adapters/wa-sqlite/vfs.js"
2562
+ /*!**********************************************!*\
2563
+ !*** ./lib/src/db/adapters/wa-sqlite/vfs.js ***!
2564
+ \**********************************************/
2565
+ (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2566
+
2567
+ __webpack_require__.r(__webpack_exports__);
2568
+ /* harmony export */ __webpack_require__.d(__webpack_exports__, {
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)
2576
+ /* harmony export */ });
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;
2831
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();
2595
+ };
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();
2625
+ }
2626
+ else {
2627
+ module = await AsyncWASQLiteModuleFactory();
2628
+ }
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();
2640
+ }
2641
+ else {
2642
+ module = await SyncWASQLiteModuleFactory();
2643
+ }
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();
2655
+ }
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
+ };
2666
+ }
2667
+ };
2832
2668
 
2833
2669
 
2834
2670
  /***/ },
@@ -2853,134 +2689,108 @@ const getNavigatorLocks = () => {
2853
2689
 
2854
2690
  /***/ },
2855
2691
 
2856
- /***/ "./lib/src/worker/db/SharedWASQLiteConnection.js"
2857
- /*!*******************************************************!*\
2858
- !*** ./lib/src/worker/db/SharedWASQLiteConnection.js ***!
2859
- \*******************************************************/
2692
+ /***/ "./lib/src/worker/db/MultiDatabaseServer.js"
2693
+ /*!**************************************************!*\
2694
+ !*** ./lib/src/worker/db/MultiDatabaseServer.js ***!
2695
+ \**************************************************/
2860
2696
  (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2861
2697
 
2862
2698
  __webpack_require__.r(__webpack_exports__);
2863
2699
  /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2864
- /* harmony export */ SharedWASQLiteConnection: () => (/* binding */ SharedWASQLiteConnection)
2700
+ /* harmony export */ MultiDatabaseServer: () => (/* binding */ MultiDatabaseServer),
2701
+ /* harmony export */ isSharedWorker: () => (/* binding */ isSharedWorker)
2865
2702
  /* 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);
2900
- }
2901
- finally {
2902
- this.activeHoldId = null;
2903
- }
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.`);
2923
- }
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;
2930
- }
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');
2937
- }
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);
2951
- }
2952
- getConfig() {
2953
- return this.connection.getConfig();
2954
- }
2955
- }
2956
-
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");
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");
2957
2708
 
2958
- /***/ },
2959
2709
 
2960
- /***/ "./lib/src/worker/db/WorkerWASQLiteConnection.js"
2961
- /*!*******************************************************!*\
2962
- !*** ./lib/src/worker/db/WorkerWASQLiteConnection.js ***!
2963
- \*******************************************************/
2964
- (__unused_webpack___webpack_module__, __webpack_exports__, __webpack_require__) {
2965
2710
 
2966
- __webpack_require__.r(__webpack_exports__);
2967
- /* harmony export */ __webpack_require__.d(__webpack_exports__, {
2968
- /* harmony export */ WorkerWASQLiteConnection: () => (/* binding */ WorkerWASQLiteConnection)
2969
- /* harmony export */ });
2970
- /* 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");
2972
2711
 
2973
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
  /***/ },
@@ -3052,6 +2862,7 @@ __webpack_require__.r(__webpack_exports__);
3052
2862
  /* harmony export */ MAX_AMOUNT_OF_COLUMNS: () => (/* binding */ MAX_AMOUNT_OF_COLUMNS),
3053
2863
  /* harmony export */ MAX_OP_ID: () => (/* binding */ MAX_OP_ID),
3054
2864
  /* harmony export */ MEMORY_TRIGGER_CLAIM_MANAGER: () => (/* binding */ MEMORY_TRIGGER_CLAIM_MANAGER),
2865
+ /* harmony export */ Mutex: () => (/* binding */ Mutex),
3055
2866
  /* harmony export */ OnChangeQueryProcessor: () => (/* binding */ OnChangeQueryProcessor),
3056
2867
  /* harmony export */ OpType: () => (/* binding */ OpType),
3057
2868
  /* harmony export */ OpTypeEnum: () => (/* binding */ OpTypeEnum),
@@ -3060,6 +2871,7 @@ __webpack_require__.r(__webpack_exports__);
3060
2871
  /* harmony export */ PowerSyncControlCommand: () => (/* binding */ PowerSyncControlCommand),
3061
2872
  /* harmony export */ RowUpdateType: () => (/* binding */ RowUpdateType),
3062
2873
  /* harmony export */ Schema: () => (/* binding */ Schema),
2874
+ /* harmony export */ Semaphore: () => (/* binding */ Semaphore),
3063
2875
  /* harmony export */ SqliteBucketStorage: () => (/* binding */ SqliteBucketStorage),
3064
2876
  /* harmony export */ SyncClientImplementation: () => (/* binding */ SyncClientImplementation),
3065
2877
  /* harmony export */ SyncDataBatch: () => (/* binding */ SyncDataBatch),
@@ -3093,15 +2905,12 @@ __webpack_require__.r(__webpack_exports__);
3093
2905
  /* harmony export */ isStreamingSyncCheckpointPartiallyComplete: () => (/* binding */ isStreamingSyncCheckpointPartiallyComplete),
3094
2906
  /* harmony export */ isStreamingSyncData: () => (/* binding */ isStreamingSyncData),
3095
2907
  /* harmony export */ isSyncNewCheckpointRequest: () => (/* binding */ isSyncNewCheckpointRequest),
3096
- /* harmony export */ mutexRunExclusive: () => (/* binding */ mutexRunExclusive),
3097
2908
  /* harmony export */ parseQuery: () => (/* binding */ parseQuery),
3098
2909
  /* harmony export */ runOnSchemaChange: () => (/* binding */ runOnSchemaChange),
3099
2910
  /* harmony export */ sanitizeSQL: () => (/* binding */ sanitizeSQL),
3100
- /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID)
2911
+ /* harmony export */ sanitizeUUID: () => (/* binding */ sanitizeUUID),
2912
+ /* harmony export */ timeoutSignal: () => (/* binding */ timeoutSignal)
3101
2913
  /* harmony export */ });
3102
- /* 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");
3103
-
3104
-
3105
2914
  // https://www.sqlite.org/lang_expr.html#castexpr
3106
2915
  var ColumnType;
3107
2916
  (function (ColumnType) {
@@ -3759,7 +3568,7 @@ class SyncingService {
3759
3568
  updatedAttachments.push(downloaded);
3760
3569
  break;
3761
3570
  case AttachmentState.QUEUED_DELETE:
3762
- const deleted = await this.deleteAttachment(attachment);
3571
+ const deleted = await this.deleteAttachment(attachment, context);
3763
3572
  updatedAttachments.push(deleted);
3764
3573
  break;
3765
3574
  }
@@ -3837,17 +3646,16 @@ class SyncingService {
3837
3646
  * On failure, defers to error handler or archives.
3838
3647
  *
3839
3648
  * @param attachment - The attachment record to delete
3649
+ * @param context - Attachment context for database operations
3840
3650
  * @returns Updated attachment record
3841
3651
  */
3842
- async deleteAttachment(attachment) {
3652
+ async deleteAttachment(attachment, context) {
3843
3653
  try {
3844
3654
  await this.remoteStorage.deleteFile(attachment);
3845
3655
  if (attachment.localUri) {
3846
3656
  await this.localStorage.deleteFile(attachment.localUri);
3847
3657
  }
3848
- await this.attachmentService.withContext(async (ctx) => {
3849
- await ctx.deleteAttachment(attachment.id);
3850
- });
3658
+ await context.deleteAttachment(attachment.id);
3851
3659
  return {
3852
3660
  ...attachment,
3853
3661
  state: AttachmentState.ARCHIVED
@@ -3885,32 +3693,198 @@ class SyncingService {
3885
3693
  }
3886
3694
 
3887
3695
  /**
3888
- * Wrapper for async-mutex runExclusive, which allows for a timeout on each exclusive lock.
3696
+ * A simple fixed-capacity queue implementation.
3697
+ *
3698
+ * Unlike a naive queue implemented by `array.push()` and `array.shift()`, this avoids moving array elements around
3699
+ * and is `O(1)` for {@link addLast} and {@link removeFirst}.
3700
+ */
3701
+ class Queue {
3702
+ table;
3703
+ // Index of the first element in the table.
3704
+ head;
3705
+ // Amount of items currently in the queue.
3706
+ _length;
3707
+ constructor(initialItems) {
3708
+ this.table = [...initialItems];
3709
+ this.head = 0;
3710
+ this._length = this.table.length;
3711
+ }
3712
+ get isEmpty() {
3713
+ return this.length == 0;
3714
+ }
3715
+ get length() {
3716
+ return this._length;
3717
+ }
3718
+ removeFirst() {
3719
+ if (this.isEmpty) {
3720
+ throw new Error('Queue is empty');
3721
+ }
3722
+ const result = this.table[this.head];
3723
+ this._length--;
3724
+ this.table[this.head] = undefined;
3725
+ this.head = (this.head + 1) % this.table.length;
3726
+ return result;
3727
+ }
3728
+ addLast(element) {
3729
+ if (this.length == this.table.length) {
3730
+ throw new Error('Queue is full');
3731
+ }
3732
+ this.table[(this.head + this._length) % this.table.length] = element;
3733
+ this._length++;
3734
+ }
3735
+ }
3736
+
3737
+ /**
3738
+ * An asynchronous semaphore implementation with associated items per lease.
3739
+ *
3740
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
3889
3741
  */
3890
- async function mutexRunExclusive(mutex, callback, options) {
3891
- return new Promise((resolve, reject) => {
3892
- const timeout = options?.timeoutMs;
3893
- let timedOut = false;
3894
- const timeoutId = timeout
3895
- ? setTimeout(() => {
3896
- timedOut = true;
3897
- reject(new Error('Timeout waiting for lock'));
3898
- }, timeout)
3899
- : undefined;
3900
- mutex.runExclusive(async () => {
3901
- if (timeoutId) {
3902
- clearTimeout(timeoutId);
3742
+ class Semaphore {
3743
+ // Available items that are not currently assigned to a waiter.
3744
+ available;
3745
+ size;
3746
+ // Linked list of waiters. We don't expect the wait list to become particularly large, and this allows removing
3747
+ // aborted waiters from the middle of the list efficiently.
3748
+ firstWaiter;
3749
+ lastWaiter;
3750
+ constructor(elements) {
3751
+ this.available = new Queue(elements);
3752
+ this.size = this.available.length;
3753
+ }
3754
+ addWaiter(requestedItems, onAcquire) {
3755
+ const node = {
3756
+ isActive: true,
3757
+ acquiredItems: [],
3758
+ remainingItems: requestedItems,
3759
+ onAcquire,
3760
+ prev: this.lastWaiter
3761
+ };
3762
+ if (this.lastWaiter) {
3763
+ this.lastWaiter.next = node;
3764
+ this.lastWaiter = node;
3765
+ }
3766
+ else {
3767
+ // First waiter
3768
+ this.lastWaiter = this.firstWaiter = node;
3769
+ }
3770
+ return node;
3771
+ }
3772
+ deactivateWaiter(waiter) {
3773
+ const { prev, next } = waiter;
3774
+ waiter.isActive = false;
3775
+ if (prev)
3776
+ prev.next = next;
3777
+ if (next)
3778
+ next.prev = prev;
3779
+ if (waiter == this.firstWaiter)
3780
+ this.firstWaiter = next;
3781
+ if (waiter == this.lastWaiter)
3782
+ this.lastWaiter = prev;
3783
+ }
3784
+ requestPermits(amount, abort) {
3785
+ if (amount <= 0 || amount > this.size) {
3786
+ throw new Error(`Invalid amount of items requested (${amount}), must be between 1 and ${this.size}`);
3787
+ }
3788
+ return new Promise((resolve, reject) => {
3789
+ function rejectAborted() {
3790
+ reject(abort?.reason ?? new Error('Semaphore acquire aborted'));
3903
3791
  }
3904
- if (timedOut)
3905
- return;
3906
- try {
3907
- resolve(await callback());
3792
+ if (abort?.aborted) {
3793
+ return rejectAborted();
3908
3794
  }
3909
- catch (ex) {
3910
- reject(ex);
3795
+ let waiter;
3796
+ const markCompleted = () => {
3797
+ const items = waiter.acquiredItems;
3798
+ waiter.acquiredItems = []; // Avoid releasing items twice.
3799
+ for (const element of items) {
3800
+ // Give to next waiter, if possible.
3801
+ const nextWaiter = this.firstWaiter;
3802
+ if (nextWaiter) {
3803
+ nextWaiter.acquiredItems.push(element);
3804
+ nextWaiter.remainingItems--;
3805
+ if (nextWaiter.remainingItems == 0) {
3806
+ nextWaiter.onAcquire();
3807
+ }
3808
+ }
3809
+ else {
3810
+ // No pending waiter, return lease into pool.
3811
+ this.available.addLast(element);
3812
+ }
3813
+ }
3814
+ };
3815
+ const onAbort = () => {
3816
+ abort?.removeEventListener('abort', onAbort);
3817
+ if (waiter.isActive) {
3818
+ this.deactivateWaiter(waiter);
3819
+ rejectAborted();
3820
+ }
3821
+ };
3822
+ const resolvePromise = () => {
3823
+ this.deactivateWaiter(waiter);
3824
+ abort?.removeEventListener('abort', onAbort);
3825
+ const items = waiter.acquiredItems;
3826
+ resolve({ items, release: markCompleted });
3827
+ };
3828
+ waiter = this.addWaiter(amount, resolvePromise);
3829
+ // If there are items in the pool that haven't been assigned, we can pull them into this waiter. Note that this is
3830
+ // only the case if we're the first waiter (otherwise, items would have been assigned to an earlier waiter).
3831
+ while (!this.available.isEmpty && waiter.remainingItems > 0) {
3832
+ waiter.acquiredItems.push(this.available.removeFirst());
3833
+ waiter.remainingItems--;
3834
+ }
3835
+ if (waiter.remainingItems == 0) {
3836
+ return resolvePromise();
3911
3837
  }
3838
+ abort?.addEventListener('abort', onAbort);
3912
3839
  });
3913
- });
3840
+ }
3841
+ /**
3842
+ * Requests a single item from the pool.
3843
+ *
3844
+ * The returned `release` callback must be invoked to return the item into the pool.
3845
+ */
3846
+ async requestOne(abort) {
3847
+ const { items, release } = await this.requestPermits(1, abort);
3848
+ return { release, item: items[0] };
3849
+ }
3850
+ /**
3851
+ * Requests access to all items from the pool.
3852
+ *
3853
+ * The returned `release` callback must be invoked to return items into the pool.
3854
+ */
3855
+ requestAll(abort) {
3856
+ return this.requestPermits(this.size, abort);
3857
+ }
3858
+ }
3859
+ /**
3860
+ * An asynchronous mutex implementation.
3861
+ *
3862
+ * @internal This class is meant to be used in PowerSync SDKs only, and is not part of the public API.
3863
+ */
3864
+ class Mutex {
3865
+ inner = new Semaphore([null]);
3866
+ async acquire(abort) {
3867
+ const { release } = await this.inner.requestOne(abort);
3868
+ return release;
3869
+ }
3870
+ async runExclusive(fn, abort) {
3871
+ const returnMutex = await this.acquire(abort);
3872
+ try {
3873
+ return await fn();
3874
+ }
3875
+ finally {
3876
+ returnMutex();
3877
+ }
3878
+ }
3879
+ }
3880
+ function timeoutSignal(timeout) {
3881
+ if (timeout == null)
3882
+ return;
3883
+ if ('timeout' in AbortSignal)
3884
+ return AbortSignal.timeout(timeout);
3885
+ const controller = new AbortController();
3886
+ setTimeout(() => controller.abort(new Error('Timeout waiting for lock')), timeout);
3887
+ return controller.signal;
3914
3888
  }
3915
3889
 
3916
3890
  /**
@@ -3922,7 +3896,7 @@ class AttachmentService {
3922
3896
  db;
3923
3897
  logger;
3924
3898
  tableName;
3925
- mutex = new async_mutex__WEBPACK_IMPORTED_MODULE_0__.Mutex();
3899
+ mutex = new Mutex();
3926
3900
  context;
3927
3901
  constructor(db, logger, tableName = 'attachments', archivedCacheLimit = 100) {
3928
3902
  this.db = db;
@@ -3959,7 +3933,7 @@ class AttachmentService {
3959
3933
  * Executes a callback with exclusive access to the attachment context.
3960
3934
  */
3961
3935
  async withContext(callback) {
3962
- return mutexRunExclusive(this.mutex, async () => {
3936
+ return this.mutex.runExclusive(async () => {
3963
3937
  return callback(this.context);
3964
3938
  });
3965
3939
  }
@@ -3995,9 +3969,15 @@ class AttachmentQueue {
3995
3969
  tableName;
3996
3970
  /** Logger instance for diagnostic information */
3997
3971
  logger;
3998
- /** Interval in milliseconds between periodic sync operations. Default: 30000 (30 seconds) */
3972
+ /** Interval in milliseconds between periodic sync operations. Acts as a polling timer to retry
3973
+ * failed uploads/downloads, especially after the app goes offline. Default: 30000 (30 seconds) */
3999
3974
  syncIntervalMs = 30 * 1000;
4000
- /** Duration in milliseconds to throttle sync operations */
3975
+ /** Throttle duration in milliseconds for the reactive watch query on the attachments table.
3976
+ * When attachment records change, a watch query detects the change and triggers a sync.
3977
+ * This throttle prevents the sync from firing too rapidly when many changes happen in
3978
+ * quick succession (e.g., bulk inserts). This is distinct from syncIntervalMs — it controls
3979
+ * how quickly the queue reacts to changes, while syncIntervalMs controls how often it polls
3980
+ * for retries. Default: 30 (from DEFAULT_WATCH_THROTTLE_MS) */
4001
3981
  syncThrottleDuration;
4002
3982
  /** Whether to automatically download remote attachments. Default: true */
4003
3983
  downloadAttachments = true;
@@ -4021,8 +4001,8 @@ class AttachmentQueue {
4021
4001
  * @param options.watchAttachments - Callback for monitoring attachment changes in your data model
4022
4002
  * @param options.tableName - Name of the table to store attachment records. Default: 'ps_attachment_queue'
4023
4003
  * @param options.logger - Logger instance. Defaults to db.logger
4024
- * @param options.syncIntervalMs - Interval between automatic syncs in milliseconds. Default: 30000
4025
- * @param options.syncThrottleDuration - Throttle duration for sync operations in milliseconds. Default: 1000
4004
+ * @param options.syncIntervalMs - Periodic polling interval in milliseconds for retrying failed uploads/downloads. Default: 30000
4005
+ * @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
4026
4006
  * @param options.downloadAttachments - Whether to automatically download remote attachments. Default: true
4027
4007
  * @param options.archivedCacheLimit - Maximum archived attachments before cleanup. Default: 100
4028
4008
  */
@@ -13683,7 +13663,7 @@ function requireDist () {
13683
13663
 
13684
13664
  var distExports = requireDist();
13685
13665
 
13686
- var version = "1.49.0";
13666
+ var version = "1.51.0";
13687
13667
  var PACKAGE = {
13688
13668
  version: version};
13689
13669
 
@@ -16075,7 +16055,7 @@ class AbstractPowerSyncDatabase extends BaseObserver {
16075
16055
  this._schema = schema;
16076
16056
  this.ready = false;
16077
16057
  this.sdkVersion = '';
16078
- this.runExclusiveMutex = new async_mutex__WEBPACK_IMPORTED_MODULE_0__.Mutex();
16058
+ this.runExclusiveMutex = new Mutex();
16079
16059
  // Start async init
16080
16060
  this.subscriptions = {
16081
16061
  firstStatusMatching: (predicate, abort) => this.waitForStatus(predicate, abort),
@@ -16540,6 +16520,10 @@ SELECT * FROM crud_entries;
16540
16520
  * Execute a SQL write (INSERT/UPDATE/DELETE) query
16541
16521
  * and optionally return results.
16542
16522
  *
16523
+ * When using the default client-side [JSON-based view system](https://docs.powersync.com/architecture/client-architecture#client-side-schema-and-sqlite-database-structure),
16524
+ * the returned result's `rowsAffected` may be `0` for successful `UPDATE` and `DELETE` statements.
16525
+ * Use a `RETURNING` clause and inspect `result.rows` when you need to confirm which rows changed.
16526
+ *
16543
16527
  * @param sql The SQL query to execute
16544
16528
  * @param parameters Optional array of parameters to bind to the query
16545
16529
  * @returns The query result as an object with structured key-value pairs
@@ -16636,7 +16620,7 @@ SELECT * FROM crud_entries;
16636
16620
  async readTransaction(callback, lockTimeout = DEFAULT_LOCK_TIMEOUT_MS) {
16637
16621
  await this.waitForReady();
16638
16622
  return this.database.readTransaction(async (tx) => {
16639
- const res = await callback({ ...tx });
16623
+ const res = await callback(tx);
16640
16624
  await tx.rollback();
16641
16625
  return res;
16642
16626
  }, { timeoutMs: lockTimeout });
@@ -17792,9 +17776,7 @@ __webpack_require__.r(__webpack_exports__);
17792
17776
  /* 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");
17793
17777
  /* harmony import */ var _powersync_common__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! @powersync/common */ "../common/dist/bundle.mjs");
17794
17778
  /* 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");
17795
- /* harmony import */ var _shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ../../shared/navigator.js */ "./lib/src/shared/navigator.js");
17796
- /* harmony import */ var _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__ = __webpack_require__(/*! ./SharedWASQLiteConnection.js */ "./lib/src/worker/db/SharedWASQLiteConnection.js");
17797
- /* harmony import */ var _WorkerWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_5__ = __webpack_require__(/*! ./WorkerWASQLiteConnection.js */ "./lib/src/worker/db/WorkerWASQLiteConnection.js");
17779
+ /* harmony import */ var _MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__ = __webpack_require__(/*! ./MultiDatabaseServer.js */ "./lib/src/worker/db/MultiDatabaseServer.js");
17798
17780
  /**
17799
17781
  * Supports both shared and dedicated workers, based on how the worker is constructed (new SharedWorker vs new Worker()).
17800
17782
  */
@@ -17802,67 +17784,28 @@ __webpack_require__.r(__webpack_exports__);
17802
17784
 
17803
17785
 
17804
17786
 
17805
-
17806
-
17807
17787
  const baseLogger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_1__.createBaseLogger)();
17808
17788
  baseLogger.useDefaults();
17809
17789
  const logger = (0,_powersync_common__WEBPACK_IMPORTED_MODULE_1__.createLogger)('db-worker');
17810
- const DBMap = new Map();
17811
- const OPEN_DB_LOCK = 'open-wasqlite-db';
17812
- let nextClientId = 1;
17813
- const openDBShared = async (options) => {
17814
- // Prevent multiple simultaneous opens from causing race conditions
17815
- return (0,_shared_navigator_js__WEBPACK_IMPORTED_MODULE_3__.getNavigatorLocks)().request(OPEN_DB_LOCK, async () => {
17816
- const clientId = nextClientId++;
17817
- const { dbFilename, logLevel } = options;
17818
- logger.setLevel(logLevel);
17819
- if (!DBMap.has(dbFilename)) {
17820
- const clientIds = new Set();
17821
- // This format returns proxy objects for function callbacks
17822
- const connection = new _WorkerWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_5__.WorkerWASQLiteConnection(options);
17823
- await connection.init();
17824
- connection.registerListener({
17825
- holdOverwritten: async () => {
17826
- /**
17827
- * The previous hold has been overwritten, without being released.
17828
- * we need to cleanup any resources associated with it.
17829
- * We can perform a rollback to release any potential transactions that were started.
17830
- */
17831
- await connection.execute('ROLLBACK').catch(() => { });
17832
- }
17833
- });
17834
- DBMap.set(dbFilename, {
17835
- clientIds,
17836
- db: connection
17837
- });
17838
- }
17839
- // Associates this clientId with the shared connection entry
17840
- const sharedConnection = new _SharedWASQLiteConnection_js__WEBPACK_IMPORTED_MODULE_4__.SharedWASQLiteConnection({
17841
- dbMap: DBMap,
17842
- dbFilename,
17843
- clientId,
17844
- logger
17845
- });
17846
- return comlink__WEBPACK_IMPORTED_MODULE_2__.proxy(sharedConnection);
17847
- });
17790
+ const server = new _MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__.MultiDatabaseServer(logger);
17791
+ const exposedFunctions = {
17792
+ connect: (config) => server.handleConnection(config),
17793
+ connectToExisting: ({ identifier, lockName }) => server.connectToExisting(identifier, lockName)
17848
17794
  };
17849
17795
  // Check if we're in a SharedWorker context
17850
- if (typeof SharedWorkerGlobalScope !== 'undefined') {
17796
+ if (_MultiDatabaseServer_js__WEBPACK_IMPORTED_MODULE_3__.isSharedWorker) {
17851
17797
  const _self = self;
17852
17798
  _self.onconnect = function (event) {
17853
17799
  const port = event.ports[0];
17854
- comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared, port);
17800
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(exposedFunctions, port);
17855
17801
  };
17856
17802
  }
17857
17803
  else {
17858
17804
  // A dedicated worker can be shared externally
17859
- comlink__WEBPACK_IMPORTED_MODULE_2__.expose(openDBShared);
17805
+ comlink__WEBPACK_IMPORTED_MODULE_2__.expose(exposedFunctions);
17860
17806
  }
17861
17807
  addEventListener('unload', () => {
17862
- Array.from(DBMap.values()).forEach(async (dbConnection) => {
17863
- const { db } = dbConnection;
17864
- db.close?.();
17865
- });
17808
+ server.closeAll();
17866
17809
  });
17867
17810
 
17868
17811
  })();