@powersync/web 0.0.0-dev-20251203144301 → 0.0.0-dev-20260112083235

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 (107) hide show
  1. package/README.md +1 -1
  2. package/dist/0b19af1befc07ce338dd.wasm +0 -0
  3. package/dist/2632c3bda9473da74fd5.wasm +0 -0
  4. package/dist/64f5351ba3784bfe2f3e.wasm +0 -0
  5. package/dist/9318ca94aac4d0fe0135.wasm +0 -0
  6. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js +1875 -0
  7. package/dist/_journeyapps_wa-sqlite-_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapp-89f0ba.index.umd.js.map +1 -0
  8. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-685f6c0.index.umd.js +567 -0
  9. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-685f6c0.index.umd.js.map +1 -0
  10. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-685f6c1.index.umd.js +567 -0
  11. package/dist/_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js-_journeyapps_wa-sqlite_src_example-685f6c1.index.umd.js.map +1 -0
  12. package/dist/index.umd.js +7107 -4249
  13. package/dist/index.umd.js.map +1 -1
  14. package/dist/worker/SharedSyncImplementation.umd.js +337 -2101
  15. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -1
  16. package/dist/worker/WASQLiteDB.umd.js +182 -1931
  17. package/dist/worker/WASQLiteDB.umd.js.map +1 -1
  18. package/dist/worker/node_modules_bson_lib_bson_mjs.umd.js +3 -3
  19. package/dist/worker/node_modules_bson_lib_bson_mjs.umd.js.map +1 -1
  20. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite-async_mjs.umd.js +22 -9
  21. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite-async_mjs.umd.js.map +1 -1
  22. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite_mjs.umd.js +22 -9
  23. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_mc-wa-sqlite_mjs.umd.js.map +1 -1
  24. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite-async_mjs.umd.js +22 -9
  25. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite-async_mjs.umd.js.map +1 -1
  26. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +22 -9
  27. package/dist/worker/node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map +1 -1
  28. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js.umd.js +1206 -3
  29. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_AccessHandlePoolVFS_js.umd.js.map +1 -1
  30. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_IDBBatchAtomicVFS_js.umd.js +1209 -6
  31. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_IDBBatchAtomicVFS_js.umd.js.map +1 -1
  32. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_OPFSCoopSyncVFS_js.umd.js +1820 -0
  33. package/dist/worker/node_modules_journeyapps_wa-sqlite_src_examples_OPFSCoopSyncVFS_js.umd.js.map +1 -0
  34. package/lib/package.json +20 -15
  35. package/lib/src/db/PowerSyncDatabase.d.ts +3 -1
  36. package/lib/src/db/PowerSyncDatabase.js +19 -7
  37. package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.d.ts +1 -1
  38. package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.js +1 -1
  39. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.d.ts +2 -2
  40. package/lib/src/db/adapters/AbstractWebSQLOpenFactory.js +2 -2
  41. package/lib/src/db/adapters/AsyncDatabaseConnection.d.ts +1 -9
  42. package/lib/src/db/adapters/AsyncDatabaseConnection.js +1 -11
  43. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.d.ts +3 -3
  44. package/lib/src/db/adapters/LockedAsyncDatabaseAdapter.js +25 -12
  45. package/lib/src/db/adapters/WebDBAdapter.d.ts +1 -1
  46. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.d.ts +2 -2
  47. package/lib/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.js +1 -2
  48. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.d.ts +2 -2
  49. package/lib/src/db/adapters/wa-sqlite/WASQLiteConnection.js +12 -3
  50. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.d.ts +3 -3
  51. package/lib/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.js +5 -5
  52. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +4 -4
  53. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +6 -6
  54. package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.d.ts +1 -1
  55. package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.js +3 -3
  56. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.d.ts +4 -4
  57. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js +5 -5
  58. package/lib/src/db/sync/WebRemote.js +1 -1
  59. package/lib/src/db/sync/WebStreamingSyncImplementation.d.ts +1 -1
  60. package/lib/src/db/sync/WebStreamingSyncImplementation.js +1 -1
  61. package/lib/src/index.d.ts +12 -12
  62. package/lib/src/index.js +12 -12
  63. package/lib/src/worker/db/SharedWASQLiteConnection.d.ts +2 -2
  64. package/lib/src/worker/db/WASQLiteDB.worker.js +4 -3
  65. package/lib/src/worker/db/WorkerWASQLiteConnection.d.ts +2 -2
  66. package/lib/src/worker/db/WorkerWASQLiteConnection.js +1 -1
  67. package/lib/src/worker/db/open-worker-database.d.ts +2 -2
  68. package/lib/src/worker/db/open-worker-database.js +1 -1
  69. package/lib/src/worker/sync/BroadcastLogger.d.ts +1 -1
  70. package/lib/src/worker/sync/SharedSyncImplementation.d.ts +4 -4
  71. package/lib/src/worker/sync/SharedSyncImplementation.js +84 -83
  72. package/lib/src/worker/sync/SharedSyncImplementation.worker.js +2 -2
  73. package/lib/src/worker/sync/WorkerClient.d.ts +1 -1
  74. package/lib/src/worker/sync/WorkerClient.js +2 -2
  75. package/lib/tsconfig.tsbuildinfo +1 -1
  76. package/package.json +21 -16
  77. package/src/db/PowerSyncDatabase.ts +23 -8
  78. package/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.ts +1 -1
  79. package/src/db/adapters/AbstractWebSQLOpenFactory.ts +3 -3
  80. package/src/db/adapters/AsyncDatabaseConnection.ts +1 -13
  81. package/src/db/adapters/LockedAsyncDatabaseAdapter.ts +30 -14
  82. package/src/db/adapters/WebDBAdapter.ts +1 -1
  83. package/src/db/adapters/WorkerWrappedAsyncDatabaseConnection.ts +3 -4
  84. package/src/db/adapters/wa-sqlite/WASQLiteConnection.ts +14 -5
  85. package/src/db/adapters/wa-sqlite/WASQLiteDBAdapter.ts +7 -7
  86. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +7 -7
  87. package/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.ts +3 -3
  88. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +7 -7
  89. package/src/db/sync/WebRemote.ts +1 -1
  90. package/src/db/sync/WebStreamingSyncImplementation.ts +2 -2
  91. package/src/index.ts +12 -12
  92. package/src/worker/db/SharedWASQLiteConnection.ts +2 -2
  93. package/src/worker/db/WASQLiteDB.worker.ts +6 -5
  94. package/src/worker/db/WorkerWASQLiteConnection.ts +2 -2
  95. package/src/worker/db/open-worker-database.ts +2 -2
  96. package/src/worker/sync/BroadcastLogger.ts +1 -1
  97. package/src/worker/sync/SharedSyncImplementation.ts +92 -89
  98. package/src/worker/sync/SharedSyncImplementation.worker.ts +2 -2
  99. package/src/worker/sync/WorkerClient.ts +2 -2
  100. package/dist/1807036ae51c10ee4d23.wasm +0 -0
  101. package/dist/307d8ce2280e3bae09d5.wasm +0 -0
  102. package/dist/cd8b9e8f4c87bf81c169.wasm +0 -0
  103. package/dist/e797080f5ed0b5324166.wasm +0 -0
  104. package/lib/src/worker/db/opfs.d.ts +0 -96
  105. package/lib/src/worker/db/opfs.js +0 -582
  106. package/src/worker/db/opfs.ts +0 -623
  107. /package/bin/{powersync.js → powersync.cjs} +0 -0
@@ -1,582 +0,0 @@
1
- // Copyright 2024 Roy T. Hashimoto. All Rights Reserved.
2
- // @ts-nocheck
3
- import { FacadeVFS } from '@journeyapps/wa-sqlite/src/FacadeVFS.js';
4
- import * as VFS from '@journeyapps/wa-sqlite/src/VFS.js';
5
- const DEFAULT_TEMPORARY_FILES = 10;
6
- const LOCK_NOTIFY_INTERVAL = 1000;
7
- const DB_RELATED_FILE_SUFFIXES = ['', '-journal', '-wal'];
8
- const finalizationRegistry = new FinalizationRegistry((releaser) => releaser());
9
- class File {
10
- /** @type {string} */ path;
11
- /** @type {number} */ flags;
12
- /** @type {FileSystemSyncAccessHandle} */ accessHandle;
13
- /** @type {PersistentFile?} */ persistentFile;
14
- constructor(path, flags) {
15
- this.path = path;
16
- this.flags = flags;
17
- }
18
- }
19
- class PersistentFile {
20
- /** @type {FileSystemFileHandle} */ fileHandle;
21
- /** @type {FileSystemSyncAccessHandle} */ accessHandle = null;
22
- // The following properties are for main database files.
23
- /** @type {boolean} */ isLockBusy = false;
24
- /** @type {boolean} */ isFileLocked = false;
25
- /** @type {boolean} */ isRequestInProgress = false;
26
- /** @type {function} */ handleLockReleaser = null;
27
- /** @type {BroadcastChannel} */ handleRequestChannel;
28
- /** @type {boolean} */ isHandleRequested = false;
29
- constructor(fileHandle) {
30
- this.fileHandle = fileHandle;
31
- }
32
- }
33
- export class OPFSCoopSyncVFS extends FacadeVFS {
34
- /** @type {Map<number, File>} */ mapIdToFile = new Map();
35
- lastError = null;
36
- log = null; //function(...args) { console.log(`[${contextName}]`, ...args) };
37
- /** @type {Map<string, PersistentFile>} */ persistentFiles = new Map();
38
- /** @type {Map<string, FileSystemSyncAccessHandle>} */ boundAccessHandles = new Map();
39
- /** @type {Set<FileSystemSyncAccessHandle>} */ unboundAccessHandles = new Set();
40
- /** @type {Set<string>} */ accessiblePaths = new Set();
41
- releaser = null;
42
- static async create(name, module) {
43
- const vfs = new OPFSCoopSyncVFS(name, module);
44
- await Promise.all([vfs.isReady(), vfs.#initialize(DEFAULT_TEMPORARY_FILES)]);
45
- return vfs;
46
- }
47
- constructor(name, module) {
48
- super(name, module);
49
- }
50
- async #initialize(nTemporaryFiles) {
51
- // Delete temporary directories no longer in use.
52
- const root = await navigator.storage.getDirectory();
53
- // @ts-ignore
54
- for await (const entry of root.values()) {
55
- if (entry.kind === 'directory' && entry.name.startsWith('.ahp-')) {
56
- // A lock with the same name as the directory protects it from
57
- // being deleted.
58
- await navigator.locks.request(entry.name, { ifAvailable: true }, async (lock) => {
59
- if (lock) {
60
- this.log?.(`Deleting temporary directory ${entry.name}`);
61
- await root.removeEntry(entry.name, { recursive: true });
62
- }
63
- else {
64
- this.log?.(`Temporary directory ${entry.name} is in use`);
65
- }
66
- });
67
- }
68
- }
69
- // Create our temporary directory.
70
- const tmpDirName = `.ahp-${Math.random().toString(36).slice(2)}`;
71
- this.releaser = await new Promise((resolve) => {
72
- navigator.locks.request(tmpDirName, () => {
73
- return new Promise((release) => {
74
- resolve(release);
75
- });
76
- });
77
- });
78
- const releaseHandle = async () => {
79
- await Promise.all(this.persistentFiles.values().map(async (file) => {
80
- try {
81
- await this.#releaseAccessHandle(file);
82
- }
83
- catch (e) {
84
- this.log?.('error releasing access handle', e);
85
- }
86
- finally {
87
- release();
88
- }
89
- }));
90
- };
91
- finalizationRegistry.register(this, releaseHandle);
92
- finalizationRegistry.register(this, this.releaser);
93
- const tmpDir = await root.getDirectoryHandle(tmpDirName, { create: true });
94
- // Populate temporary directory.
95
- for (let i = 0; i < nTemporaryFiles; i++) {
96
- const tmpFile = await tmpDir.getFileHandle(`${i}.tmp`, { create: true });
97
- const tmpAccessHandle = await tmpFile.createSyncAccessHandle();
98
- this.unboundAccessHandles.add(tmpAccessHandle);
99
- }
100
- }
101
- /**
102
- * @param {string?} zName
103
- * @param {number} fileId
104
- * @param {number} flags
105
- * @param {DataView} pOutFlags
106
- * @returns {number}
107
- */
108
- jOpen(zName, fileId, flags, pOutFlags) {
109
- try {
110
- const url = new URL(zName || Math.random().toString(36).slice(2), 'file://');
111
- const path = url.pathname;
112
- if (flags & VFS.SQLITE_OPEN_MAIN_DB) {
113
- const persistentFile = this.persistentFiles.get(path);
114
- if (persistentFile?.isRequestInProgress) {
115
- // Should not reach here unless SQLite itself retries an open.
116
- // Otherwise, asynchronous operations started on a previous
117
- // open try should have completed.
118
- return VFS.SQLITE_BUSY;
119
- }
120
- else if (!persistentFile) {
121
- // This is the usual starting point for opening a database.
122
- // Register a Promise that resolves when the database and related
123
- // files are ready to be used.
124
- this.log?.(`creating persistent file for ${path}`);
125
- const create = !!(flags & VFS.SQLITE_OPEN_CREATE);
126
- this._module.retryOps.push((async () => {
127
- try {
128
- // Get the path directory handle.
129
- let dirHandle = await navigator.storage.getDirectory();
130
- const directories = path.split('/').filter((d) => d);
131
- const filename = directories.pop();
132
- for (const directory of directories) {
133
- dirHandle = await dirHandle.getDirectoryHandle(directory, { create });
134
- }
135
- // Get file handles for the database and related files,
136
- // and create persistent file instances.
137
- for (const suffix of DB_RELATED_FILE_SUFFIXES) {
138
- const fileHandle = await dirHandle.getFileHandle(filename + suffix, { create });
139
- await this.#createPersistentFile(fileHandle);
140
- }
141
- // Get access handles for the files.
142
- const file = new File(path, flags);
143
- file.persistentFile = this.persistentFiles.get(path);
144
- await this.#requestAccessHandle(file);
145
- }
146
- catch (e) {
147
- // Use an invalid persistent file to signal this error
148
- // for the retried open.
149
- const persistentFile = new PersistentFile(null);
150
- this.persistentFiles.set(path, persistentFile);
151
- console.error(e);
152
- }
153
- })());
154
- return VFS.SQLITE_BUSY;
155
- }
156
- else if (!persistentFile.fileHandle) {
157
- // The asynchronous open operation failed.
158
- this.persistentFiles.delete(path);
159
- return VFS.SQLITE_CANTOPEN;
160
- }
161
- else if (!persistentFile.accessHandle) {
162
- // This branch is reached if the database was previously opened
163
- // and closed.
164
- this._module.retryOps.push((async () => {
165
- const file = new File(path, flags);
166
- file.persistentFile = this.persistentFiles.get(path);
167
- await this.#requestAccessHandle(file);
168
- })());
169
- return VFS.SQLITE_BUSY;
170
- }
171
- }
172
- if (!this.accessiblePaths.has(path) && !(flags & VFS.SQLITE_OPEN_CREATE)) {
173
- throw new Error(`File ${path} not found`);
174
- }
175
- const file = new File(path, flags);
176
- this.mapIdToFile.set(fileId, file);
177
- if (this.persistentFiles.has(path)) {
178
- file.persistentFile = this.persistentFiles.get(path);
179
- }
180
- else if (this.boundAccessHandles.has(path)) {
181
- // This temporary file was previously created and closed. Reopen
182
- // the same access handle.
183
- file.accessHandle = this.boundAccessHandles.get(path);
184
- }
185
- else if (this.unboundAccessHandles.size) {
186
- // Associate an unbound access handle to this file.
187
- file.accessHandle = this.unboundAccessHandles.values().next().value;
188
- file.accessHandle.truncate(0);
189
- this.unboundAccessHandles.delete(file.accessHandle);
190
- this.boundAccessHandles.set(path, file.accessHandle);
191
- }
192
- this.accessiblePaths.add(path);
193
- pOutFlags.setInt32(0, flags, true);
194
- return VFS.SQLITE_OK;
195
- }
196
- catch (e) {
197
- this.lastError = e;
198
- return VFS.SQLITE_CANTOPEN;
199
- }
200
- }
201
- /**
202
- * @param {string} zName
203
- * @param {number} syncDir
204
- * @returns {number}
205
- */
206
- jDelete(zName, syncDir) {
207
- try {
208
- const url = new URL(zName, 'file://');
209
- const path = url.pathname;
210
- if (this.persistentFiles.has(path)) {
211
- const persistentFile = this.persistentFiles.get(path);
212
- persistentFile.accessHandle.truncate(0);
213
- }
214
- else {
215
- this.boundAccessHandles.get(path)?.truncate(0);
216
- }
217
- this.accessiblePaths.delete(path);
218
- return VFS.SQLITE_OK;
219
- }
220
- catch (e) {
221
- this.lastError = e;
222
- return VFS.SQLITE_IOERR_DELETE;
223
- }
224
- }
225
- /**
226
- * @param {string} zName
227
- * @param {number} flags
228
- * @param {DataView} pResOut
229
- * @returns {number}
230
- */
231
- jAccess(zName, flags, pResOut) {
232
- try {
233
- const url = new URL(zName, 'file://');
234
- const path = url.pathname;
235
- pResOut.setInt32(0, this.accessiblePaths.has(path) ? 1 : 0, true);
236
- return VFS.SQLITE_OK;
237
- }
238
- catch (e) {
239
- this.lastError = e;
240
- return VFS.SQLITE_IOERR_ACCESS;
241
- }
242
- }
243
- /**
244
- * @param {number} fileId
245
- * @returns {number}
246
- */
247
- jClose(fileId) {
248
- try {
249
- const file = this.mapIdToFile.get(fileId);
250
- this.mapIdToFile.delete(fileId);
251
- if (file?.flags & VFS.SQLITE_OPEN_MAIN_DB) {
252
- if (file.persistentFile?.accessHandle) {
253
- this.#releaseAccessHandle(file);
254
- }
255
- }
256
- else if (file?.flags & VFS.SQLITE_OPEN_DELETEONCLOSE) {
257
- file.accessHandle.truncate(0);
258
- this.accessiblePaths.delete(file.path);
259
- if (!this.persistentFiles.has(file.path)) {
260
- this.boundAccessHandles.delete(file.path);
261
- this.unboundAccessHandles.add(file.accessHandle);
262
- }
263
- }
264
- return VFS.SQLITE_OK;
265
- }
266
- catch (e) {
267
- this.lastError = e;
268
- return VFS.SQLITE_IOERR_CLOSE;
269
- }
270
- }
271
- /**
272
- * @param {number} fileId
273
- * @param {Uint8Array} pData
274
- * @param {number} iOffset
275
- * @returns {number}
276
- */
277
- jRead(fileId, pData, iOffset) {
278
- try {
279
- const file = this.mapIdToFile.get(fileId);
280
- // On Chrome (at least), passing pData to accessHandle.read() is
281
- // an error because pData is a Proxy of a Uint8Array. Calling
282
- // subarray() produces a real Uint8Array and that works.
283
- const accessHandle = file.accessHandle || file.persistentFile.accessHandle;
284
- const bytesRead = accessHandle.read(pData.subarray(), { at: iOffset });
285
- // Opening a database file performs one read without a xLock call.
286
- if (file.flags & VFS.SQLITE_OPEN_MAIN_DB && !file.persistentFile.isFileLocked) {
287
- this.#releaseAccessHandle(file);
288
- }
289
- if (bytesRead < pData.byteLength) {
290
- pData.fill(0, bytesRead);
291
- return VFS.SQLITE_IOERR_SHORT_READ;
292
- }
293
- return VFS.SQLITE_OK;
294
- }
295
- catch (e) {
296
- this.lastError = e;
297
- return VFS.SQLITE_IOERR_READ;
298
- }
299
- }
300
- /**
301
- * @param {number} fileId
302
- * @param {Uint8Array} pData
303
- * @param {number} iOffset
304
- * @returns {number}
305
- */
306
- jWrite(fileId, pData, iOffset) {
307
- try {
308
- const file = this.mapIdToFile.get(fileId);
309
- // On Chrome (at least), passing pData to accessHandle.write() is
310
- // an error because pData is a Proxy of a Uint8Array. Calling
311
- // subarray() produces a real Uint8Array and that works.
312
- const accessHandle = file.accessHandle || file.persistentFile.accessHandle;
313
- const nBytes = accessHandle.write(pData.subarray(), { at: iOffset });
314
- if (nBytes !== pData.byteLength)
315
- throw new Error('short write');
316
- return VFS.SQLITE_OK;
317
- }
318
- catch (e) {
319
- this.lastError = e;
320
- return VFS.SQLITE_IOERR_WRITE;
321
- }
322
- }
323
- /**
324
- * @param {number} fileId
325
- * @param {number} iSize
326
- * @returns {number}
327
- */
328
- jTruncate(fileId, iSize) {
329
- try {
330
- const file = this.mapIdToFile.get(fileId);
331
- const accessHandle = file.accessHandle || file.persistentFile.accessHandle;
332
- accessHandle.truncate(iSize);
333
- return VFS.SQLITE_OK;
334
- }
335
- catch (e) {
336
- this.lastError = e;
337
- return VFS.SQLITE_IOERR_TRUNCATE;
338
- }
339
- }
340
- /**
341
- * @param {number} fileId
342
- * @param {number} flags
343
- * @returns {number}
344
- */
345
- jSync(fileId, flags) {
346
- try {
347
- const file = this.mapIdToFile.get(fileId);
348
- const accessHandle = file.accessHandle || file.persistentFile.accessHandle;
349
- accessHandle.flush();
350
- return VFS.SQLITE_OK;
351
- }
352
- catch (e) {
353
- this.lastError = e;
354
- return VFS.SQLITE_IOERR_FSYNC;
355
- }
356
- }
357
- /**
358
- * @param {number} fileId
359
- * @param {DataView} pSize64
360
- * @returns {number}
361
- */
362
- jFileSize(fileId, pSize64) {
363
- try {
364
- const file = this.mapIdToFile.get(fileId);
365
- const accessHandle = file.accessHandle || file.persistentFile.accessHandle;
366
- const size = accessHandle.getSize();
367
- pSize64.setBigInt64(0, BigInt(size), true);
368
- return VFS.SQLITE_OK;
369
- }
370
- catch (e) {
371
- this.lastError = e;
372
- return VFS.SQLITE_IOERR_FSTAT;
373
- }
374
- }
375
- /**
376
- * @param {number} fileId
377
- * @param {number} lockType
378
- * @returns {number}
379
- */
380
- jLock(fileId, lockType) {
381
- const file = this.mapIdToFile.get(fileId);
382
- if (file.persistentFile.isRequestInProgress) {
383
- file.persistentFile.isLockBusy = true;
384
- return VFS.SQLITE_BUSY;
385
- }
386
- file.persistentFile.isFileLocked = true;
387
- if (!file.persistentFile.handleLockReleaser) {
388
- // Start listening for notifications from other connections.
389
- // This is before we actually get access handles, but waiting to
390
- // listen until then allows a race condition where notifications
391
- // are missed.
392
- file.persistentFile.handleRequestChannel.onmessage = () => {
393
- this.log?.(`received notification for ${file.path}`);
394
- if (file.persistentFile.isFileLocked) {
395
- // We're still using the access handle, so mark it to be
396
- // released when we're done.
397
- file.persistentFile.isHandleRequested = true;
398
- }
399
- else {
400
- // Release the access handles immediately.
401
- this.#releaseAccessHandle(file);
402
- }
403
- file.persistentFile.handleRequestChannel.onmessage = null;
404
- };
405
- this.#requestAccessHandle(file);
406
- this.log?.('returning SQLITE_BUSY');
407
- file.persistentFile.isLockBusy = true;
408
- return VFS.SQLITE_BUSY;
409
- }
410
- file.persistentFile.isLockBusy = false;
411
- return VFS.SQLITE_OK;
412
- }
413
- /**
414
- * @param {number} fileId
415
- * @param {number} lockType
416
- * @returns {number}
417
- */
418
- jUnlock(fileId, lockType) {
419
- const file = this.mapIdToFile.get(fileId);
420
- if (lockType === VFS.SQLITE_LOCK_NONE) {
421
- // Don't change any state if this unlock is because xLock returned
422
- // SQLITE_BUSY.
423
- if (!file.persistentFile.isLockBusy) {
424
- if (file.persistentFile.isHandleRequested) {
425
- // Another connection wants the access handle.
426
- this.#releaseAccessHandle(file);
427
- file.persistentFile.isHandleRequested = false;
428
- }
429
- file.persistentFile.isFileLocked = false;
430
- }
431
- }
432
- return VFS.SQLITE_OK;
433
- }
434
- /**
435
- * @param {number} fileId
436
- * @param {number} op
437
- * @param {DataView} pArg
438
- * @returns {number|Promise<number>}
439
- */
440
- jFileControl(fileId, op, pArg) {
441
- try {
442
- const file = this.mapIdToFile.get(fileId);
443
- switch (op) {
444
- case VFS.SQLITE_FCNTL_PRAGMA:
445
- const key = extractString(pArg, 4);
446
- const value = extractString(pArg, 8);
447
- this.log?.('xFileControl', file.path, 'PRAGMA', key, value);
448
- switch (key.toLowerCase()) {
449
- case 'journal_mode':
450
- if (value && !['off', 'memory', 'delete', 'wal'].includes(value.toLowerCase())) {
451
- throw new Error('journal_mode must be "off", "memory", "delete", or "wal"');
452
- }
453
- break;
454
- }
455
- break;
456
- }
457
- }
458
- catch (e) {
459
- this.lastError = e;
460
- return VFS.SQLITE_IOERR;
461
- }
462
- return VFS.SQLITE_NOTFOUND;
463
- }
464
- /**
465
- * @param {Uint8Array} zBuf
466
- * @returns
467
- */
468
- jGetLastError(zBuf) {
469
- if (this.lastError) {
470
- console.error(this.lastError);
471
- const outputArray = zBuf.subarray(0, zBuf.byteLength - 1);
472
- const { written } = new TextEncoder().encodeInto(this.lastError.message, outputArray);
473
- zBuf[written] = 0;
474
- }
475
- return VFS.SQLITE_OK;
476
- }
477
- /**
478
- * @param {FileSystemFileHandle} fileHandle
479
- * @returns {Promise<PersistentFile>}
480
- */
481
- async #createPersistentFile(fileHandle) {
482
- const persistentFile = new PersistentFile(fileHandle);
483
- const root = await navigator.storage.getDirectory();
484
- const relativePath = await root.resolve(fileHandle);
485
- const path = `/${relativePath.join('/')}`;
486
- persistentFile.handleRequestChannel = new BroadcastChannel(`ahp:${path}`);
487
- this.persistentFiles.set(path, persistentFile);
488
- const f = await fileHandle.getFile();
489
- if (f.size) {
490
- this.accessiblePaths.add(path);
491
- }
492
- return persistentFile;
493
- }
494
- /**
495
- * @param {File} file
496
- */
497
- #requestAccessHandle(file) {
498
- console.assert(!file.persistentFile.handleLockReleaser);
499
- if (!file.persistentFile.isRequestInProgress) {
500
- file.persistentFile.isRequestInProgress = true;
501
- this._module.retryOps.push((async () => {
502
- // Acquire the Web Lock.
503
- file.persistentFile.handleLockReleaser = await this.#acquireLock(file.persistentFile);
504
- try {
505
- // Get access handles for the database and releated files in parallel.
506
- this.log?.(`creating access handles for ${file.path}`);
507
- await Promise.all(DB_RELATED_FILE_SUFFIXES.map(async (suffix) => {
508
- const persistentFile = this.persistentFiles.get(file.path + suffix);
509
- if (persistentFile) {
510
- persistentFile.accessHandle = await persistentFile.fileHandle.createSyncAccessHandle();
511
- }
512
- }));
513
- }
514
- catch (e) {
515
- this.log?.(`failed to create access handles for ${file.path}`, e);
516
- // Close any of the potentially opened access handles
517
- DB_RELATED_FILE_SUFFIXES.forEach(async (suffix) => {
518
- const persistentFile = this.persistentFiles.get(file.path + suffix);
519
- if (persistentFile) {
520
- persistentFile.accessHandle?.close();
521
- }
522
- });
523
- // Release the lock, if we failed here, we'd need to obtain the lock later in order to retry
524
- file.persistentFile.handleLockReleaser();
525
- throw e;
526
- }
527
- finally {
528
- file.persistentFile.isRequestInProgress = false;
529
- }
530
- })());
531
- return this._module.retryOps.at(-1);
532
- }
533
- return Promise.resolve();
534
- }
535
- /**
536
- * @param {File} file
537
- */
538
- async #releaseAccessHandle(file) {
539
- DB_RELATED_FILE_SUFFIXES.forEach(async (suffix) => {
540
- const persistentFile = this.persistentFiles.get(file.path + suffix);
541
- if (persistentFile) {
542
- persistentFile.accessHandle?.close();
543
- persistentFile.accessHandle = null;
544
- }
545
- });
546
- this.log?.(`access handles closed for ${file.path}`);
547
- file.persistentFile.handleLockReleaser?.();
548
- file.persistentFile.handleLockReleaser = null;
549
- this.log?.(`lock released for ${file.path}`);
550
- }
551
- /**
552
- * @param {PersistentFile} persistentFile
553
- * @returns {Promise<function>} lock releaser
554
- */
555
- #acquireLock(persistentFile) {
556
- return new Promise((resolve) => {
557
- // Tell other connections we want the access handle.
558
- const lockName = persistentFile.handleRequestChannel.name;
559
- const notify = () => {
560
- this.log?.(`notifying for ${lockName}`);
561
- persistentFile.handleRequestChannel.postMessage(null);
562
- };
563
- const notifyId = setInterval(notify, LOCK_NOTIFY_INTERVAL);
564
- setTimeout(notify);
565
- this.log?.(`lock requested: ${lockName}`);
566
- navigator.locks.request(lockName, (lock) => {
567
- // We have the lock. Stop asking other connections for it.
568
- this.log?.(`lock acquired: ${lockName}`, lock);
569
- clearInterval(notifyId);
570
- return new Promise(resolve);
571
- });
572
- });
573
- }
574
- }
575
- function extractString(dataView, offset) {
576
- const p = dataView.getUint32(offset, true);
577
- if (p) {
578
- const chars = new Uint8Array(dataView.buffer, p);
579
- return new TextDecoder().decode(chars.subarray(0, chars.indexOf(0)));
580
- }
581
- return null;
582
- }