@powersync/web 0.0.0-dev-20260630141119 → 0.0.0-dev-20260708103617

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 (234) hide show
  1. package/bin/powersync.cjs +1 -1
  2. package/dist/index.umd.js +7821 -0
  3. package/dist/index.umd.js.map +1 -0
  4. package/dist/worker/SharedSyncImplementation.umd.js +16139 -0
  5. package/dist/worker/SharedSyncImplementation.umd.js.map +1 -0
  6. package/dist/worker/WASQLiteDB.umd.js +17434 -0
  7. package/dist/worker/WASQLiteDB.umd.js.map +1 -0
  8. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7.umd.js +31 -0
  9. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-9af0a7.umd.js.map +1 -0
  10. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9.umd.js +31 -0
  11. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_mc-wa-s-bbf5a9.umd.js.map +1 -0
  12. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f.umd.js +31 -0
  13. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqli-c26e0f.umd.js.map +1 -0
  14. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js +31 -0
  15. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_dist_wa-sqlite_mjs.umd.js.map +1 -0
  16. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422.umd.js +3562 -0
  17. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-2fb422.umd.js.map +1 -0
  18. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-833585.umd.js +1400 -0
  19. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-833585.umd.js.map +1 -0
  20. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23.umd.js +2478 -0
  21. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-96fb23.umd.js.map +1 -0
  22. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911.umd.js +1681 -0
  23. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-c89911.umd.js.map +1 -0
  24. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1.umd.js +1820 -0
  25. package/dist/worker/node_modules_pnpm_journeyapps_wa-sqlite_1_7_0_node_modules_journeyapps_wa-sqlite_src_examples-ec4eb1.umd.js.map +1 -0
  26. package/lib/package.json +91 -0
  27. package/lib/src/attachments/IndexDBFileSystemAdapter.js.map +1 -0
  28. package/lib/{db → src/db}/NavigatorTriggerClaimManager.d.ts +1 -1
  29. package/lib/src/db/NavigatorTriggerClaimManager.js.map +1 -0
  30. package/lib/src/db/PowerSyncDatabase.d.ts +78 -0
  31. package/lib/{db → src/db}/PowerSyncDatabase.js +61 -47
  32. package/lib/src/db/PowerSyncDatabase.js.map +1 -0
  33. package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.d.ts +23 -0
  34. package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.js +27 -0
  35. package/lib/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.js.map +1 -0
  36. package/lib/src/db/adapters/AsyncWebAdapter.d.ts +50 -0
  37. package/lib/{db → src/db}/adapters/AsyncWebAdapter.js +14 -14
  38. package/lib/src/db/adapters/AsyncWebAdapter.js.map +1 -0
  39. package/lib/src/db/adapters/SSRDBAdapter.d.ts +30 -0
  40. package/lib/src/db/adapters/SSRDBAdapter.js +69 -0
  41. package/lib/src/db/adapters/SSRDBAdapter.js.map +1 -0
  42. package/lib/{db → src/db}/adapters/WebDBAdapter.d.ts +1 -1
  43. package/lib/src/db/adapters/WebDBAdapter.js.map +1 -0
  44. package/lib/{db → src/db}/adapters/wa-sqlite/ConcurrentConnection.d.ts +4 -3
  45. package/lib/{db → src/db}/adapters/wa-sqlite/ConcurrentConnection.js +2 -2
  46. package/lib/src/db/adapters/wa-sqlite/ConcurrentConnection.js.map +1 -0
  47. package/lib/{db → src/db}/adapters/wa-sqlite/DatabaseClient.d.ts +4 -4
  48. package/lib/{db → src/db}/adapters/wa-sqlite/DatabaseClient.js +37 -11
  49. package/lib/src/db/adapters/wa-sqlite/DatabaseClient.js.map +1 -0
  50. package/lib/{db → src/db}/adapters/wa-sqlite/DatabaseServer.d.ts +5 -5
  51. package/lib/{db → src/db}/adapters/wa-sqlite/DatabaseServer.js +7 -11
  52. package/lib/src/db/adapters/wa-sqlite/DatabaseServer.js.map +1 -0
  53. package/lib/{db → src/db}/adapters/wa-sqlite/RawSqliteConnection.d.ts +12 -23
  54. package/lib/{db → src/db}/adapters/wa-sqlite/RawSqliteConnection.js +11 -17
  55. package/lib/src/db/adapters/wa-sqlite/RawSqliteConnection.js.map +1 -0
  56. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +45 -0
  57. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +146 -0
  58. package/lib/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.js.map +1 -0
  59. package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.d.ts +15 -0
  60. package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.js +22 -0
  61. package/lib/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.js.map +1 -0
  62. package/lib/src/db/adapters/wa-sqlite/vfs.d.ts +40 -0
  63. package/lib/src/db/adapters/wa-sqlite/vfs.js +95 -0
  64. package/lib/src/db/adapters/wa-sqlite/vfs.js.map +1 -0
  65. package/lib/src/db/adapters/web-sql-flags.d.ts +92 -0
  66. package/lib/src/db/adapters/web-sql-flags.js +37 -0
  67. package/lib/src/db/adapters/web-sql-flags.js.map +1 -0
  68. package/lib/{db → src/db}/sync/SSRWebStreamingSyncImplementation.d.ts +8 -4
  69. package/lib/{db → src/db}/sync/SSRWebStreamingSyncImplementation.js +11 -4
  70. package/lib/src/db/sync/SSRWebStreamingSyncImplementation.js.map +1 -0
  71. package/lib/{db → src/db}/sync/SharedWebStreamingSyncImplementation.d.ts +14 -13
  72. package/lib/{db → src/db}/sync/SharedWebStreamingSyncImplementation.js +66 -31
  73. package/lib/src/db/sync/SharedWebStreamingSyncImplementation.js.map +1 -0
  74. package/lib/src/db/sync/WebRemote.d.ts +7 -0
  75. package/lib/src/db/sync/WebRemote.js +33 -0
  76. package/lib/src/db/sync/WebRemote.js.map +1 -0
  77. package/lib/{db → src/db}/sync/WebStreamingSyncImplementation.d.ts +4 -2
  78. package/lib/{db → src/db}/sync/WebStreamingSyncImplementation.js +2 -3
  79. package/lib/src/db/sync/WebStreamingSyncImplementation.js.map +1 -0
  80. package/lib/src/db/sync/userAgent.js.map +1 -0
  81. package/lib/{index.d.ts → src/index.d.ts} +3 -1
  82. package/lib/{index.js → src/index.js} +3 -1
  83. package/lib/src/index.js.map +1 -0
  84. package/lib/src/shared/navigator.js.map +1 -0
  85. package/lib/src/shared/tab_close_signal.js.map +1 -0
  86. package/lib/src/worker/db/MultiDatabaseServer.d.ts +17 -0
  87. package/lib/{worker → src/worker}/db/MultiDatabaseServer.js +18 -26
  88. package/lib/src/worker/db/MultiDatabaseServer.js.map +1 -0
  89. package/lib/src/worker/db/WASQLiteDB.worker.d.ts +4 -0
  90. package/lib/src/worker/db/WASQLiteDB.worker.js +31 -0
  91. package/lib/src/worker/db/WASQLiteDB.worker.js.map +1 -0
  92. package/lib/src/worker/db/open-worker-database.d.ts +14 -0
  93. package/lib/src/worker/db/open-worker-database.js +53 -0
  94. package/lib/src/worker/db/open-worker-database.js.map +1 -0
  95. package/lib/src/worker/sync/AbstractSharedSyncClientProvider.d.ts +19 -0
  96. package/lib/src/worker/sync/AbstractSharedSyncClientProvider.js.map +1 -0
  97. package/lib/src/worker/sync/BroadcastLogger.d.ts +47 -0
  98. package/lib/src/worker/sync/BroadcastLogger.js +129 -0
  99. package/lib/src/worker/sync/BroadcastLogger.js.map +1 -0
  100. package/lib/{worker → src/worker}/sync/SharedSyncImplementation.d.ts +15 -11
  101. package/lib/{worker → src/worker}/sync/SharedSyncImplementation.js +43 -42
  102. package/lib/src/worker/sync/SharedSyncImplementation.js.map +1 -0
  103. package/lib/src/worker/sync/SharedSyncImplementation.worker.js +12 -0
  104. package/lib/src/worker/sync/SharedSyncImplementation.worker.js.map +1 -0
  105. package/lib/{worker → src/worker}/sync/WorkerClient.d.ts +3 -3
  106. package/lib/{worker → src/worker}/sync/WorkerClient.js +2 -2
  107. package/lib/src/worker/sync/WorkerClient.js.map +1 -0
  108. package/lib/tsconfig.tsbuildinfo +1 -0
  109. package/package.json +29 -22
  110. package/src/db/NavigatorTriggerClaimManager.ts +1 -1
  111. package/src/db/PowerSyncDatabase.ts +122 -80
  112. package/src/db/adapters/AbstractWebPowerSyncDatabaseOpenFactory.ts +47 -0
  113. package/src/db/adapters/AsyncWebAdapter.ts +26 -17
  114. package/src/db/adapters/SSRDBAdapter.ts +64 -14
  115. package/src/db/adapters/WebDBAdapter.ts +1 -1
  116. package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +5 -4
  117. package/src/db/adapters/wa-sqlite/DatabaseClient.ts +56 -20
  118. package/src/db/adapters/wa-sqlite/DatabaseServer.ts +12 -15
  119. package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +24 -41
  120. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +126 -63
  121. package/src/db/adapters/wa-sqlite/WASQLitePowerSyncDatabaseOpenFactory.ts +24 -0
  122. package/src/db/adapters/wa-sqlite/vfs.ts +67 -54
  123. package/src/db/adapters/web-sql-flags.ts +141 -0
  124. package/src/db/sync/SSRWebStreamingSyncImplementation.ts +22 -4
  125. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +77 -38
  126. package/src/db/sync/WebRemote.ts +26 -23
  127. package/src/db/sync/WebStreamingSyncImplementation.ts +5 -4
  128. package/src/index.ts +3 -1
  129. package/src/worker/db/MultiDatabaseServer.ts +25 -41
  130. package/src/worker/db/WASQLiteDB.worker.ts +35 -0
  131. package/src/worker/db/open-worker-database.ts +62 -0
  132. package/src/worker/sync/AbstractSharedSyncClientProvider.ts +10 -4
  133. package/src/worker/sync/BroadcastLogger.ts +103 -35
  134. package/src/worker/sync/SharedSyncImplementation.ts +63 -62
  135. package/src/worker/sync/SharedSyncImplementation.worker.ts +14 -0
  136. package/src/worker/sync/WorkerClient.ts +4 -4
  137. package/dist/index.react_native_web.js +0 -1879
  138. package/dist/index.react_native_web.js.map +0 -1
  139. package/dist/worker/AccessHandlePoolVFS-BPUHfZME.js +0 -2
  140. package/dist/worker/AccessHandlePoolVFS-BPUHfZME.js.map +0 -1
  141. package/dist/worker/FacadeVFS-d1ZDvud7.js +0 -2
  142. package/dist/worker/FacadeVFS-d1ZDvud7.js.map +0 -1
  143. package/dist/worker/IDBBatchAtomicVFS-DbkDb777.js +0 -2
  144. package/dist/worker/IDBBatchAtomicVFS-DbkDb777.js.map +0 -1
  145. package/dist/worker/OPFSCoopSyncVFS-DRKedN0p.js +0 -2
  146. package/dist/worker/OPFSCoopSyncVFS-DRKedN0p.js.map +0 -1
  147. package/dist/worker/OPFSWriteAheadVFS-BzodSqNq.js +0 -2
  148. package/dist/worker/OPFSWriteAheadVFS-BzodSqNq.js.map +0 -1
  149. package/dist/worker/mc-wa-sqlite-DiBqIVE5.js +0 -2
  150. package/dist/worker/mc-wa-sqlite-DiBqIVE5.js.map +0 -1
  151. package/dist/worker/mc-wa-sqlite-async-DUEhO9ef.js +0 -2
  152. package/dist/worker/mc-wa-sqlite-async-DUEhO9ef.js.map +0 -1
  153. package/dist/worker/wa-sqlite-BlSx7-_P.js +0 -2
  154. package/dist/worker/wa-sqlite-BlSx7-_P.js.map +0 -1
  155. package/dist/worker/wa-sqlite-async-BdR24Ucf.js +0 -2
  156. package/dist/worker/wa-sqlite-async-BdR24Ucf.js.map +0 -1
  157. package/dist/worker/websockets-Q8W_lerF.js +0 -9
  158. package/dist/worker/websockets-Q8W_lerF.js.map +0 -1
  159. package/dist/worker/worker.js +0 -7
  160. package/dist/worker/worker.js.map +0 -1
  161. package/lib/attachments/IndexDBFileSystemAdapter.js.map +0 -1
  162. package/lib/db/NavigatorTriggerClaimManager.js.map +0 -1
  163. package/lib/db/PowerSyncDatabase.d.ts +0 -67
  164. package/lib/db/PowerSyncDatabase.js.map +0 -1
  165. package/lib/db/adapters/AsyncWebAdapter.d.ts +0 -32
  166. package/lib/db/adapters/AsyncWebAdapter.js.map +0 -1
  167. package/lib/db/adapters/SSRDBAdapter.d.ts +0 -17
  168. package/lib/db/adapters/SSRDBAdapter.js +0 -37
  169. package/lib/db/adapters/SSRDBAdapter.js.map +0 -1
  170. package/lib/db/adapters/WebDBAdapter.js.map +0 -1
  171. package/lib/db/adapters/options.d.ts +0 -87
  172. package/lib/db/adapters/options.js +0 -6
  173. package/lib/db/adapters/options.js.map +0 -1
  174. package/lib/db/adapters/resolveAndValidateOptions.d.ts +0 -5
  175. package/lib/db/adapters/resolveAndValidateOptions.js +0 -33
  176. package/lib/db/adapters/resolveAndValidateOptions.js.map +0 -1
  177. package/lib/db/adapters/wa-sqlite/ConcurrentConnection.js.map +0 -1
  178. package/lib/db/adapters/wa-sqlite/DatabaseClient.js.map +0 -1
  179. package/lib/db/adapters/wa-sqlite/DatabaseServer.js.map +0 -1
  180. package/lib/db/adapters/wa-sqlite/RawSqliteConnection.js.map +0 -1
  181. package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +0 -18
  182. package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +0 -131
  183. package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js.map +0 -1
  184. package/lib/db/adapters/wa-sqlite/vfs.d.ts +0 -50
  185. package/lib/db/adapters/wa-sqlite/vfs.js +0 -77
  186. package/lib/db/adapters/wa-sqlite/vfs.js.map +0 -1
  187. package/lib/db/sync/SSRWebStreamingSyncImplementation.js.map +0 -1
  188. package/lib/db/sync/SharedWebStreamingSyncImplementation.js.map +0 -1
  189. package/lib/db/sync/WebRemote.d.ts +0 -10
  190. package/lib/db/sync/WebRemote.js +0 -33
  191. package/lib/db/sync/WebRemote.js.map +0 -1
  192. package/lib/db/sync/WebStreamingSyncImplementation.js.map +0 -1
  193. package/lib/db/sync/userAgent.js.map +0 -1
  194. package/lib/index.js.map +0 -1
  195. package/lib/shared/navigator.js.map +0 -1
  196. package/lib/shared/tab_close_signal.js.map +0 -1
  197. package/lib/worker/SharedWorkerConnectionRequest.d.ts +0 -5
  198. package/lib/worker/SharedWorkerConnectionRequest.js +0 -2
  199. package/lib/worker/SharedWorkerConnectionRequest.js.map +0 -1
  200. package/lib/worker/client.d.ts +0 -15
  201. package/lib/worker/client.js +0 -77
  202. package/lib/worker/client.js.map +0 -1
  203. package/lib/worker/db/MultiDatabaseServer.d.ts +0 -22
  204. package/lib/worker/db/MultiDatabaseServer.js.map +0 -1
  205. package/lib/worker/sync/AbstractSharedSyncClientProvider.d.ts +0 -13
  206. package/lib/worker/sync/AbstractSharedSyncClientProvider.js.map +0 -1
  207. package/lib/worker/sync/BroadcastLogger.d.ts +0 -27
  208. package/lib/worker/sync/BroadcastLogger.js +0 -65
  209. package/lib/worker/sync/BroadcastLogger.js.map +0 -1
  210. package/lib/worker/sync/SharedSyncImplementation.js.map +0 -1
  211. package/lib/worker/sync/WorkerClient.js.map +0 -1
  212. package/lib/worker/worker.js +0 -34
  213. package/lib/worker/worker.js.map +0 -1
  214. package/src/db/adapters/options.ts +0 -100
  215. package/src/db/adapters/resolveAndValidateOptions.ts +0 -40
  216. package/src/worker/SharedWorkerConnectionRequest.ts +0 -6
  217. package/src/worker/client.ts +0 -100
  218. package/src/worker/worker.ts +0 -38
  219. /package/dist/{worker/assets/mc-wa-sqlite-async-D6idQS2r.wasm → 2075a31bb151adbb9767.wasm} +0 -0
  220. /package/dist/{worker/assets/wa-sqlite-XZW__iJk.wasm → 3322bc84de986b63c2cd.wasm} +0 -0
  221. /package/dist/{worker/assets/mc-wa-sqlite-CnHbhWvs.wasm → 8e97452e297be23b5e50.wasm} +0 -0
  222. /package/dist/{worker/assets/wa-sqlite-async-rHzzC98y.wasm → fbc178b70d530e8ce02b.wasm} +0 -0
  223. /package/lib/{attachments → src/attachments}/IndexDBFileSystemAdapter.d.ts +0 -0
  224. /package/lib/{attachments → src/attachments}/IndexDBFileSystemAdapter.js +0 -0
  225. /package/lib/{db → src/db}/NavigatorTriggerClaimManager.js +0 -0
  226. /package/lib/{db → src/db}/adapters/WebDBAdapter.js +0 -0
  227. /package/lib/{db → src/db}/sync/userAgent.d.ts +0 -0
  228. /package/lib/{db → src/db}/sync/userAgent.js +0 -0
  229. /package/lib/{shared → src/shared}/navigator.d.ts +0 -0
  230. /package/lib/{shared → src/shared}/navigator.js +0 -0
  231. /package/lib/{shared → src/shared}/tab_close_signal.d.ts +0 -0
  232. /package/lib/{shared → src/shared}/tab_close_signal.js +0 -0
  233. /package/lib/{worker → src/worker}/sync/AbstractSharedSyncClientProvider.js +0 -0
  234. /package/lib/{worker/worker.d.ts → src/worker/sync/SharedSyncImplementation.worker.d.ts} +0 -0
@@ -1,1879 +0,0 @@
1
- import { DBAdapter, LockContext, LogLevels, queryResultWithoutRows, BaseObserver } from '@powersync/common';
2
- export * from '@powersync/common';
3
- import * as Comlink from 'comlink';
4
- import { Mutex, ConnectionClosedError, Semaphore, LockType, AbstractRemote, AbstractStreamingSyncImplementation, BasePowerSyncDatabase, openDatabase, SqliteBucketStorage } from '@powersync/shared-internals';
5
- import { Factory, SQLITE_ROW } from '@journeyapps/wa-sqlite';
6
-
7
- /**
8
- * IndexDBFileSystemStorageAdapter implements LocalStorageAdapter using IndexedDB.
9
- * Suitable for web browsers and web-based environments.
10
- */
11
- class IndexDBFileSystemStorageAdapter {
12
- databaseName;
13
- dbPromise;
14
- constructor(databaseName = 'PowerSyncFiles') {
15
- this.databaseName = databaseName;
16
- }
17
- async initialize() {
18
- this.dbPromise = new Promise((resolve, reject) => {
19
- const request = indexedDB.open(this.databaseName, 1);
20
- request.onupgradeneeded = () => {
21
- request.result.createObjectStore('files');
22
- };
23
- request.onsuccess = () => resolve(request.result);
24
- request.onerror = () => reject(request.error);
25
- });
26
- }
27
- async clear() {
28
- const db = await this.dbPromise;
29
- return new Promise((resolve, reject) => {
30
- const tx = db.transaction('files', 'readwrite');
31
- const store = tx.objectStore('files');
32
- const req = store.clear();
33
- req.onsuccess = () => resolve();
34
- req.onerror = () => reject(req.error);
35
- });
36
- }
37
- getLocalUri(filename) {
38
- return `indexeddb://${this.databaseName}/files/${filename}`;
39
- }
40
- async getStore(mode = 'readonly') {
41
- const db = await this.dbPromise;
42
- const tx = db.transaction('files', mode);
43
- return tx.objectStore('files');
44
- }
45
- async saveFile(filePath, data) {
46
- const store = await this.getStore('readwrite');
47
- let dataToStore;
48
- let size;
49
- if (typeof data === 'string') {
50
- const binaryString = atob(data);
51
- const bytes = new Uint8Array(binaryString.length);
52
- for (let i = 0; i < binaryString.length; i++) {
53
- bytes[i] = binaryString.charCodeAt(i);
54
- }
55
- dataToStore = bytes.buffer;
56
- size = bytes.byteLength;
57
- }
58
- else {
59
- dataToStore = data;
60
- size = dataToStore.byteLength;
61
- }
62
- return await new Promise((resolve, reject) => {
63
- const req = store.put(dataToStore, filePath);
64
- req.onsuccess = () => resolve(size);
65
- req.onerror = () => reject(req.error);
66
- });
67
- }
68
- async readFile(fileUri, options) {
69
- const store = await this.getStore();
70
- return new Promise((resolve, reject) => {
71
- const req = store.get(fileUri);
72
- req.onsuccess = async () => {
73
- if (!req.result) {
74
- reject(new Error('File not found'));
75
- return;
76
- }
77
- resolve(req.result);
78
- };
79
- req.onerror = () => reject(req.error);
80
- });
81
- }
82
- async deleteFile(uri, options) {
83
- const store = await this.getStore('readwrite');
84
- await new Promise((resolve, reject) => {
85
- const req = store.delete(uri);
86
- req.onsuccess = () => resolve();
87
- req.onerror = () => reject(req.error);
88
- });
89
- }
90
- async fileExists(fileUri) {
91
- const store = await this.getStore();
92
- return new Promise((resolve, reject) => {
93
- const req = store.get(fileUri);
94
- req.onsuccess = () => resolve(!!req.result);
95
- req.onerror = () => reject(req.error);
96
- });
97
- }
98
- async makeDir(path) {
99
- // No-op for IndexedDB as it does not have a directory structure
100
- }
101
- async rmDir(path) {
102
- const store = await this.getStore('readwrite');
103
- const range = IDBKeyRange.bound(path + '/', path + '/\uffff', false, false);
104
- await new Promise((resolve, reject) => {
105
- const req = store.delete(range);
106
- req.onsuccess = () => resolve();
107
- req.onerror = () => reject(req.error);
108
- });
109
- }
110
- }
111
-
112
- /**
113
- * List of currently tested virtual filesystems
114
- */
115
- var WASQLiteVFS;
116
- (function (WASQLiteVFS) {
117
- WASQLiteVFS["IDBBatchAtomicVFS"] = "IDBBatchAtomicVFS";
118
- WASQLiteVFS["OPFSCoopSyncVFS"] = "OPFSCoopSyncVFS";
119
- WASQLiteVFS["AccessHandlePoolVFS"] = "AccessHandlePoolVFS";
120
- WASQLiteVFS["OPFSWriteAheadVFS"] = "OPFSWriteAheadVFS";
121
- })(WASQLiteVFS || (WASQLiteVFS = {}));
122
- function vfsRequiresDedicatedWorkers(vfs) {
123
- return vfs != WASQLiteVFS.IDBBatchAtomicVFS;
124
- }
125
- async function asyncModuleFactory(encryptionKey) {
126
- if (encryptionKey) {
127
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite-async.mjs');
128
- return factory();
129
- }
130
- else {
131
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite-async.mjs');
132
- return factory();
133
- }
134
- }
135
- async function syncModuleFactory(encryptionKey) {
136
- if (encryptionKey) {
137
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/mc-wa-sqlite.mjs');
138
- return factory();
139
- }
140
- else {
141
- const { default: factory } = await import('@journeyapps/wa-sqlite/dist/wa-sqlite.mjs');
142
- return factory();
143
- }
144
- }
145
- /**
146
- * @internal
147
- */
148
- const DEFAULT_MODULE_FACTORIES = {
149
- [WASQLiteVFS.IDBBatchAtomicVFS]: async (options) => {
150
- const module = await asyncModuleFactory(options.encryptionKey);
151
- const { IDBBatchAtomicVFS } = await import('@journeyapps/wa-sqlite/src/examples/IDBBatchAtomicVFS.js');
152
- return {
153
- module,
154
- // @ts-expect-error The types for this static method are missing upstream
155
- vfs: await IDBBatchAtomicVFS.create(options.dbFileName, module, { lockPolicy: 'exclusive' })
156
- };
157
- },
158
- [WASQLiteVFS.AccessHandlePoolVFS]: async (options) => {
159
- const module = await syncModuleFactory(options.encryptionKey);
160
- // @ts-expect-error The types for this static method are missing upstream
161
- const { AccessHandlePoolVFS } = await import('@journeyapps/wa-sqlite/src/examples/AccessHandlePoolVFS.js');
162
- return {
163
- module,
164
- vfs: await AccessHandlePoolVFS.create(options.dbFileName, module)
165
- };
166
- },
167
- [WASQLiteVFS.OPFSCoopSyncVFS]: async (options) => {
168
- const module = await syncModuleFactory(options.encryptionKey);
169
- // @ts-expect-error The types for this static method are missing upstream
170
- const { OPFSCoopSyncVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js');
171
- const vfs = await OPFSCoopSyncVFS.create(options.dbFileName, module);
172
- return {
173
- module,
174
- vfs
175
- };
176
- },
177
- [WASQLiteVFS.OPFSWriteAheadVFS]: async (options) => {
178
- const module = await syncModuleFactory(options.encryptionKey);
179
- // @ts-expect-error The types for this static method are missing upstream
180
- const { OPFSWriteAheadVFS } = await import('@journeyapps/wa-sqlite/src/examples/OPFSWriteAheadVFS.js');
181
- const vfs = await OPFSWriteAheadVFS.create(options.dbFileName, module, {});
182
- return {
183
- module,
184
- vfs
185
- };
186
- }
187
- };
188
-
189
- const MOCK_QUERY_RESPONSE = {
190
- rowsAffected: 0,
191
- columnNames: [],
192
- rawRows: []
193
- };
194
- /**
195
- * Implements a Mock DB adapter for use in Server Side Rendering (SSR).
196
- * This adapter will return empty results for queries, which will allow
197
- * server rendered views to initially generate scaffolding components
198
- */
199
- class SSRDBAdapter extends DBAdapter {
200
- name;
201
- readMutex;
202
- writeMutex;
203
- constructor() {
204
- super();
205
- this.name = 'SSR DB';
206
- this.readMutex = new Mutex();
207
- this.writeMutex = new Mutex();
208
- }
209
- close() { }
210
- async readLock(fn, options) {
211
- return fn(new StubLockContext());
212
- }
213
- async writeLock(fn, options) {
214
- return fn(new StubLockContext());
215
- }
216
- async refreshSchema() { }
217
- }
218
- class StubLockContext extends LockContext {
219
- async executeRaw() {
220
- return MOCK_QUERY_RESPONSE;
221
- }
222
- }
223
-
224
- /**
225
- * Access to a WA-sqlite connection that can be shared with multiple clients sending queries over an RPC protocol built
226
- * with the Comlink package.
227
- */
228
- class DatabaseServer {
229
- #options;
230
- #nextClientId = 0;
231
- #activeClients = new Set();
232
- // TODO: Don't use a broadcast channel for connections managed by a shared worker.
233
- #updateBroadcastChannel;
234
- #clientTableListeners = new Set();
235
- constructor(options) {
236
- this.#options = options;
237
- const inner = options.inner;
238
- this.#updateBroadcastChannel = new BroadcastChannel(`${inner.options.filename}-table-updates`);
239
- this.#updateBroadcastChannel.onmessage = ({ data }) => {
240
- this.#pushTableUpdateToClients(data);
241
- };
242
- }
243
- #pushTableUpdateToClients(changedTables) {
244
- for (const listener of this.#clientTableListeners) {
245
- listener.postMessage(changedTables);
246
- }
247
- }
248
- get #inner() {
249
- return this.#options.inner;
250
- }
251
- get #logger() {
252
- return this.#options.logger;
253
- }
254
- /**
255
- * Called by clients when they wish to connect to this database.
256
- *
257
- * @param lockName A lock that is currently held by the client. When the lock is returned, we know the client is gone
258
- * and that we need to clean up resources.
259
- */
260
- async connect(lockName) {
261
- let isOpen = true;
262
- const clientId = this.#nextClientId++;
263
- this.#activeClients.add(clientId);
264
- let connectionLeases = new Map();
265
- let currentTableListener;
266
- function requireOpen() {
267
- if (!isOpen) {
268
- throw new Error('Client has already been closed');
269
- }
270
- }
271
- function requireOpenAndLease(lease) {
272
- requireOpen();
273
- const token = connectionLeases.get(lease);
274
- if (!token) {
275
- throw new Error('Attempted to use a connection lease that has already been returned.');
276
- }
277
- return token;
278
- }
279
- const close = async () => {
280
- if (isOpen) {
281
- isOpen = false;
282
- if (currentTableListener) {
283
- this.#clientTableListeners.delete(currentTableListener);
284
- }
285
- // If the client holds a connection lease it hasn't returned, return that now.
286
- for (const { lease } of connectionLeases.values()) {
287
- this.#logger.log({ level: LogLevels.debug, message: `Closing connection lease that hasn't been returned.` });
288
- await lease.returnLease();
289
- }
290
- this.#activeClients.delete(clientId);
291
- if (this.#activeClients.size == 0) {
292
- await this.forceClose();
293
- }
294
- else {
295
- this.#logger.log({
296
- level: LogLevels.debug,
297
- message: 'Keeping underlying connection active since its used by other clients.'
298
- });
299
- }
300
- }
301
- };
302
- if (lockName) {
303
- navigator.locks.request(lockName, {}, () => {
304
- close();
305
- });
306
- }
307
- return {
308
- close,
309
- debugIsAutoCommit: async () => {
310
- return this.#inner.unsafeUseInner().isAutoCommit();
311
- },
312
- requestAccess: async (write, timeoutMs) => {
313
- requireOpen();
314
- const lease = await this.#inner.acquireConnection(timeoutMs != null ? AbortSignal.timeout(timeoutMs) : undefined);
315
- if (!isOpen) {
316
- // Race between requestAccess and close(), the connection was closed while we tried to acquire a lease.
317
- await lease.returnLease();
318
- return requireOpen();
319
- }
320
- const token = crypto.randomUUID();
321
- connectionLeases.set(token, { lease, write });
322
- return token;
323
- },
324
- completeAccess: async (token) => {
325
- const lease = requireOpenAndLease(token);
326
- connectionLeases.delete(token);
327
- try {
328
- if (lease.write) {
329
- // Collect update hooks invoked while the client had the write connection.
330
- const { rawRows } = await lease.lease.use((conn) => conn.execute(`SELECT powersync_update_hooks('get')`));
331
- if (rawRows.length) {
332
- const updatedTables = JSON.parse(rawRows[0][0]);
333
- if (updatedTables.length) {
334
- this.#updateBroadcastChannel.postMessage(updatedTables);
335
- this.#pushTableUpdateToClients(updatedTables);
336
- }
337
- }
338
- }
339
- }
340
- finally {
341
- await lease.lease.returnLease();
342
- }
343
- },
344
- execute: async (token, sql, params) => {
345
- const { lease } = requireOpenAndLease(token);
346
- return await lease.use((db) => db.execute(sql, params));
347
- },
348
- executeBatch: async (token, sql, params) => {
349
- const { lease } = requireOpenAndLease(token);
350
- return await lease.use((db) => db.executeBatch(sql, params));
351
- },
352
- setUpdateListener: async (listener) => {
353
- requireOpen();
354
- if (currentTableListener) {
355
- this.#clientTableListeners.delete(currentTableListener);
356
- }
357
- currentTableListener = listener;
358
- if (listener) {
359
- this.#clientTableListeners.add(listener);
360
- }
361
- }
362
- };
363
- }
364
- async forceClose() {
365
- this.#logger.log({ level: LogLevels.debug, message: `Closing connection to ${this.#inner.options}.` });
366
- const connection = this.#inner;
367
- this.#options.onClose();
368
- this.#updateBroadcastChannel.close();
369
- await connection.close();
370
- }
371
- }
372
-
373
- const getNavigatorLocks = () => {
374
- if ('locks' in navigator && navigator.locks) {
375
- return navigator.locks;
376
- }
377
- throw new Error('Navigator locks are not available in an insecure context. Use a secure context such as HTTPS or http://localhost.');
378
- };
379
-
380
- /**
381
- * A small wrapper around WA-sqlite to help with opening databases and running statements by preparing them internally.
382
- *
383
- * This is an internal class, and it must never be used directly. Wrappers are required to ensure raw connections aren't
384
- * used concurrently across tabs.
385
- */
386
- class RawSqliteConnection {
387
- options;
388
- _sqliteAPI = null;
389
- /**
390
- * The `sqlite3*` connection pointer.
391
- */
392
- db = 0;
393
- _moduleFactory;
394
- constructor(options) {
395
- this.options = options;
396
- this._moduleFactory = DEFAULT_MODULE_FACTORIES[this.options.vfs];
397
- }
398
- get isOpen() {
399
- return this.db != 0;
400
- }
401
- async init() {
402
- const api = (this._sqliteAPI = await this.openSQLiteAPI());
403
- this.db = await api.open_v2(this.options.filename, this.options.readonly ? 1 /* SQLITE_OPEN_READONLY */ : 6 /* SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE */);
404
- await this.executeRaw(`PRAGMA temp_store = ${this.options.temporaryStorage};`);
405
- if (this.options.encryptionKey) {
406
- const escapedKey = this.options.encryptionKey.replace("'", "''");
407
- await this.executeRaw(`PRAGMA key = '${escapedKey}'`);
408
- }
409
- await this.executeRaw(`PRAGMA cache_size = -${this.options.cacheSizeKb};`);
410
- await this.executeRaw(`SELECT powersync_update_hooks('install');`);
411
- }
412
- async openSQLiteAPI() {
413
- const { module, vfs } = await this._moduleFactory({
414
- dbFileName: this.options.filename,
415
- encryptionKey: this.options.encryptionKey
416
- });
417
- const sqlite3 = Factory(module);
418
- sqlite3.vfs_register(vfs, true);
419
- /**
420
- * Register the PowerSync core SQLite extension
421
- */
422
- module.ccall('powersync_init_static', 'int', []);
423
- /**
424
- * Create the multiple cipher vfs if an encryption key is provided
425
- */
426
- if (this.options.encryptionKey) {
427
- const createResult = module.ccall('sqlite3mc_vfs_create', 'int', ['string', 'int'], [this.options.filename, 1]);
428
- if (createResult !== 0) {
429
- throw new Error('Failed to create multiple cipher vfs, Database encryption will not work');
430
- }
431
- }
432
- return sqlite3;
433
- }
434
- requireSqlite() {
435
- if (!this._sqliteAPI) {
436
- throw new Error(`Initialization has not completed`);
437
- }
438
- return this._sqliteAPI;
439
- }
440
- /**
441
- * Checks if the database connection is in autocommit mode.
442
- * @returns true if in autocommit mode, false if in a transaction
443
- */
444
- isAutoCommit() {
445
- return this.requireSqlite().get_autocommit(this.db) != 0;
446
- }
447
- async execute(sql, bindings) {
448
- const resultSet = await this.executeSingleStatementRaw(sql, bindings);
449
- return this.wrapQueryResults(this.requireSqlite(), resultSet);
450
- }
451
- async executeBatch(sql, bindings) {
452
- const results = [];
453
- const api = this.requireSqlite();
454
- for await (const stmt of api.statements(this.db, sql)) {
455
- let columns;
456
- for (const parameterSet of bindings) {
457
- const rs = await this.stepThroughStatement(api, stmt, parameterSet, columns, false);
458
- results.push(this.wrapQueryResults(api, rs));
459
- }
460
- // executeBatch can only use a single statement
461
- break;
462
- }
463
- return results;
464
- }
465
- wrapQueryResults(api, { rawRows, columnNames }) {
466
- return {
467
- rowsAffected: api.changes(this.db),
468
- insertId: api.last_insert_id(this.db),
469
- autocommit: api.get_autocommit(this.db) != 0,
470
- rawRows,
471
- columnNames
472
- };
473
- }
474
- /**
475
- * This executes a single statement using SQLite3 and returns the results as a {@link RawResultSet}.
476
- */
477
- async executeSingleStatementRaw(sql, bindings) {
478
- const results = await this.executeRaw(sql, bindings);
479
- return results.length ? results[0] : { columnNames: [], rawRows: [] };
480
- }
481
- async executeRaw(sql, bindings) {
482
- const results = [];
483
- const api = this.requireSqlite();
484
- for await (const stmt of api.statements(this.db, sql)) {
485
- let columns;
486
- const rs = await this.stepThroughStatement(api, stmt, bindings ?? [], columns);
487
- columns = rs.columnNames;
488
- if (columns.length) {
489
- results.push(rs);
490
- }
491
- // When binding parameters, only a single statement is executed.
492
- if (bindings) {
493
- break;
494
- }
495
- }
496
- return results;
497
- }
498
- async stepThroughStatement(api, stmt, bindings, knownColumns, includeResults = true) {
499
- // TODO not sure why this is needed currently, but booleans break
500
- bindings.forEach((b, index, arr) => {
501
- if (typeof b == 'boolean') {
502
- arr[index] = b ? 1 : 0;
503
- }
504
- });
505
- api.reset(stmt);
506
- if (bindings) {
507
- api.bind_collection(stmt, bindings);
508
- }
509
- const rows = [];
510
- while ((await api.step(stmt)) === SQLITE_ROW) {
511
- if (includeResults) {
512
- const row = api.row(stmt);
513
- rows.push(row);
514
- }
515
- }
516
- knownColumns ??= api.column_names(stmt);
517
- return { columnNames: knownColumns, rawRows: rows };
518
- }
519
- async close() {
520
- if (this.isOpen) {
521
- await this.requireSqlite().close(this.db);
522
- this.db = 0;
523
- }
524
- }
525
- }
526
-
527
- /**
528
- * A wrapper around a {@link RawSqliteConnection} allowing multiple tabs to access it.
529
- *
530
- * To allow potentially concurrent accesses from different clients, this requires a local mutex implementation here.
531
- *
532
- * Note that instances of this class are not safe to proxy across context boundaries with comlink! We need to be able to
533
- * rely on mutexes being returned reliably, so additional checks to detect say a client tab closing are required to
534
- * avoid deadlocks.
535
- */
536
- class ConcurrentSqliteConnection {
537
- inner;
538
- /**
539
- * An outer mutex ensuring at most one {@link ConnectionLeaseToken} can exist for this connection at a time.
540
- *
541
- * If null, we'll use navigator locks instead.
542
- */
543
- leaseMutex;
544
- /**
545
- * @param needsNavigatorLocks Whether access to the database needs an additional navigator lock guard.
546
- *
547
- * While {@link ConcurrentSqliteConnection} prevents concurrent access to a database _connection_, it's possible we
548
- * might have multiple connections to the same physical database (e.g. if multiple tabs use dedicated workers).
549
- * In those setups, we use navigator locks instead of an internal mutex to guard access..
550
- */
551
- constructor(inner, needsNavigatorLocks) {
552
- this.inner = inner;
553
- this.leaseMutex = needsNavigatorLocks ? null : new Mutex();
554
- }
555
- get options() {
556
- return this.inner.options;
557
- }
558
- acquireMutex(abort) {
559
- if (this.leaseMutex) {
560
- return this.leaseMutex.acquire(abort);
561
- }
562
- return new Promise((resolve, reject) => {
563
- const options = { signal: abort };
564
- navigator.locks
565
- .request(`db-lock-${this.options.filename}`, options, (_) => {
566
- return new Promise((returnLock) => {
567
- return resolve(() => {
568
- returnLock();
569
- });
570
- });
571
- })
572
- .catch(reject);
573
- });
574
- }
575
- // Unsafe, unguarded access to the SQLite connection.
576
- unsafeUseInner() {
577
- return this.inner;
578
- }
579
- /**
580
- * @returns A {@link ConnectionLeaseToken}. Until that token is returned, no other client can use the database.
581
- */
582
- async acquireConnection(abort) {
583
- const returnMutex = await this.acquireMutex(abort);
584
- const token = new ConnectionLeaseToken(returnMutex, this.inner);
585
- try {
586
- // Assert that the inner connection is initialized at this point, fail early if it's not.
587
- this.inner.requireSqlite();
588
- // If a previous client was interrupted in the middle of a transaction AND this is a shared worker, it's possible
589
- // for the connection to still be in a transaction. To avoid inconsistent state, we roll back connection leases
590
- // that haven't been comitted.
591
- if (!this.inner.isAutoCommit()) {
592
- await this.inner.executeRaw('ROLLBACK');
593
- }
594
- }
595
- catch (e) {
596
- returnMutex();
597
- throw e;
598
- }
599
- return token;
600
- }
601
- async close() {
602
- const returnMutex = await this.acquireMutex();
603
- try {
604
- await this.inner.close();
605
- }
606
- finally {
607
- returnMutex();
608
- }
609
- }
610
- }
611
- /**
612
- * An instance representing temporary exclusive access to a {@link ConcurrentSqliteConnection}.
613
- */
614
- class ConnectionLeaseToken {
615
- returnMutex;
616
- connection;
617
- /** Ensures that the client with access to this token can't run statements concurrently. */
618
- useMutex = new Mutex();
619
- closed = false;
620
- constructor(returnMutex, connection) {
621
- this.returnMutex = returnMutex;
622
- this.connection = connection;
623
- }
624
- /**
625
- * Returns this lease, allowing another client to use the database connection.
626
- */
627
- async returnLease() {
628
- await this.useMutex.runExclusive(async () => {
629
- if (!this.closed) {
630
- this.closed = true;
631
- this.returnMutex();
632
- }
633
- });
634
- }
635
- /**
636
- * This should only be used internally, since the callback must not use the raw connection after resolving.
637
- */
638
- async use(callback) {
639
- return await this.useMutex.runExclusive(async () => {
640
- if (this.closed) {
641
- throw new Error('lease token has already been closed');
642
- }
643
- return await callback(this.connection);
644
- });
645
- }
646
- }
647
-
648
- const OPEN_DB_LOCK = 'open-wasqlite-db';
649
- /**
650
- * Shared state to manage multiple database connections hosted by a worker.
651
- */
652
- class MultiDatabaseServer {
653
- logger;
654
- activeDatabases = new Map();
655
- constructor(logger) {
656
- this.logger = logger;
657
- }
658
- async handleConnection({ logLevel, database, lockName }) {
659
- const logger = {
660
- log: (record) => {
661
- if (record.level >= logLevel)
662
- this.logger.log(record);
663
- }
664
- };
665
- return Comlink.proxy(await this.openConnectionLocally(logger, database, lockName));
666
- }
667
- async connectToExisting(name, lockName) {
668
- return getNavigatorLocks().request(OPEN_DB_LOCK, async () => {
669
- const server = this.activeDatabases.get(name);
670
- if (server == null) {
671
- throw new Error(`connectToExisting(${name}) failed because the worker doesn't own a database with that name.`);
672
- }
673
- return Comlink.proxy(await server.connect(lockName));
674
- });
675
- }
676
- async openConnectionLocally(logger, options, lockName) {
677
- // Especially on Firefox, we're sometimes seeing "NoModificationAllowedError"s when opening OPFS databases we can
678
- // work around by retrying.
679
- const maxAttempts = 3;
680
- let server;
681
- for (let count = 0; count < maxAttempts - 1; count++) {
682
- try {
683
- server = await this.databaseOpenAttempt(logger, options);
684
- }
685
- catch (error) {
686
- this.logger.log({
687
- level: LogLevels.warn,
688
- message: `Attempt ${count + 1} of ${maxAttempts} to open database failed, retrying in 1 second...`,
689
- error
690
- });
691
- await new Promise((resolve) => setTimeout(resolve, 1000));
692
- }
693
- }
694
- // Final attempt if we haven't been able to open the server - rethrow errors if we still can't open.
695
- server ??= await this.databaseOpenAttempt(logger, options);
696
- return server.connect(lockName);
697
- }
698
- async databaseOpenAttempt(logger, options) {
699
- return getNavigatorLocks().request(OPEN_DB_LOCK, async () => {
700
- const { filename } = options;
701
- let server = this.activeDatabases.get(filename);
702
- if (server == null) {
703
- // We don't need navigator locks for shared workers because all queries run in this shared worker exclusively.
704
- // For read-only connections, we use a VFS that supports concurrent reads (so a single lock on the connection is
705
- // fine).
706
- const needsNavigatorLocks = !(isSharedWorker$1 || options.readonly);
707
- const connection = new RawSqliteConnection(options);
708
- const withSafeConcurrency = new ConcurrentSqliteConnection(connection, needsNavigatorLocks);
709
- // Initializing the RawSqliteConnection will run some pragmas that might write to the database file, so we want
710
- // to do that in an exclusive lock. Note that OPEN_DB_LOCK is not enough for that, as another tab might have
711
- // already created a connection (and is thus outside of OPEN_DB_LOCK) while currently writing to it.
712
- const returnLease = await withSafeConcurrency.acquireMutex();
713
- try {
714
- await connection.init();
715
- }
716
- catch (e) {
717
- returnLease();
718
- await connection.close();
719
- throw e;
720
- }
721
- returnLease();
722
- const onClose = () => this.activeDatabases.delete(filename);
723
- server = new DatabaseServer({
724
- inner: withSafeConcurrency,
725
- logger,
726
- onClose
727
- });
728
- this.activeDatabases.set(filename, server);
729
- }
730
- return server;
731
- });
732
- }
733
- closeAll() {
734
- const existingDatabases = [...this.activeDatabases.values()];
735
- return Promise.all(existingDatabases.map((db) => {
736
- db.forceClose();
737
- }));
738
- }
739
- }
740
- const isSharedWorker$1 = 'SharedWorkerGlobalScope' in globalThis;
741
-
742
- /**
743
- * A single-connection {@link ConnectionPool} implementation based on a worker connection.
744
- */
745
- class DatabaseClient extends DBAdapter {
746
- options;
747
- config;
748
- #connection;
749
- #shareConnectionAbortController = new AbortController();
750
- #receiveTableUpdates;
751
- constructor(options, config) {
752
- super();
753
- this.options = options;
754
- this.config = config;
755
- this.#connection = {
756
- connection: options.connection,
757
- notifyRemoteClosed: options.remoteCanCloseUnexpectedly ? new AbortController() : undefined,
758
- traceQueries: config.debugMode === true
759
- };
760
- const { port1, port2 } = new MessageChannel();
761
- options.connection.setUpdateListener(Comlink.transfer(port1, [port1]));
762
- this.#receiveTableUpdates = port2;
763
- port2.onmessage = (event) => {
764
- const tables = event.data;
765
- const notification = {
766
- tables
767
- };
768
- this.iterateListeners((l) => {
769
- l.tablesUpdated && l.tablesUpdated(notification);
770
- });
771
- };
772
- }
773
- get name() {
774
- return this.config.dbFilename;
775
- }
776
- /**
777
- * Marks the remote as closed.
778
- *
779
- * This can sometimes happen outside of our control, e.g. when a shared worker requests a connection from a tab. When
780
- * it happens, all outstanding requests on this pool would never resolve. To avoid livelocks in this scenario, we
781
- * throw on all outstanding promises and forbid new calls.
782
- */
783
- markRemoteClosed() {
784
- // Can non-null assert here because this function is only supposed to be called when remoteCanCloseUnexpectedly was
785
- // set.
786
- this.#connection.notifyRemoteClosed.abort();
787
- }
788
- async close() {
789
- // This connection is no longer shared, so we can close locks held for shareConnection calls.
790
- this.#shareConnectionAbortController.abort();
791
- this.#receiveTableUpdates.close();
792
- await useConnectionState(this.#connection, (c) => c.close(), true);
793
- this.options.onClose?.();
794
- this.options.source?.[Comlink.releaseProxy]();
795
- }
796
- readLock(fn, options) {
797
- return this.#lock(false, fn, options);
798
- }
799
- writeLock(fn, options) {
800
- return this.#lock(true, fn, options);
801
- }
802
- async #lock(write, fn, options) {
803
- const token = await useConnectionState(this.#connection, (c) => c.requestAccess(write, options?.timeoutMs));
804
- try {
805
- return await fn(new ClientLockContext(this.#connection, token));
806
- }
807
- finally {
808
- await useConnectionState(this.#connection, (c) => c.completeAccess(token));
809
- }
810
- }
811
- async refreshSchema() {
812
- // Currently a no-op on the web.
813
- }
814
- async shareConnection() {
815
- /**
816
- * Hold a navigator lock in order to avoid features such as Chrome's frozen tabs,
817
- * or Edge's sleeping tabs from pausing the thread for this connection.
818
- * This promise resolves once a lock is obtained.
819
- * This lock will be held as long as this connection is open.
820
- * The `shareConnection` method should not be called on multiple tabs concurrently.
821
- */
822
- const abort = this.#shareConnectionAbortController;
823
- const source = this.options.source;
824
- if (source == null) {
825
- throw new Error(`shareConnection() is only available for connections based by workers.`);
826
- }
827
- await new Promise((resolve, reject) => navigator.locks
828
- .request(`shared-connection-${this.name}-${Date.now()}-${Math.round(Math.random() * 10000)}`, {
829
- signal: abort.signal
830
- }, async () => {
831
- resolve();
832
- // Free the lock when the connection is already closed.
833
- if (abort.signal.aborted) {
834
- return;
835
- }
836
- // Hold the lock while the shared connection is in use.
837
- await new Promise((releaseLock) => {
838
- abort.signal.addEventListener('abort', () => {
839
- releaseLock();
840
- });
841
- });
842
- })
843
- // We aren't concerned with abort errors here
844
- .catch((ex) => {
845
- if (ex.name == 'AbortError') {
846
- resolve();
847
- }
848
- else {
849
- reject(ex);
850
- }
851
- }));
852
- const newPort = await source[Comlink.createEndpoint]();
853
- return { port: newPort, identifier: this.name };
854
- }
855
- getConfiguration() {
856
- return this.config;
857
- }
858
- }
859
- /**
860
- * A {@link LockContext} implemented by sending commands to a worker.
861
- *
862
- * While an instance is active, it has exclusive access to the underlying database connection (as represented by its
863
- * token).
864
- */
865
- class ClientLockContext extends LockContext {
866
- #connection;
867
- #token;
868
- constructor(connection, token) {
869
- super();
870
- this.#connection = connection;
871
- this.#token = token;
872
- }
873
- /**
874
- * Requests an operation from the worker, potentially tracing it if that option has been enabled.
875
- */
876
- async maybeTrace(fn, describeForTrace) {
877
- if (this.#connection.traceQueries) {
878
- const start = performance.now();
879
- const description = describeForTrace();
880
- try {
881
- const r = await useConnectionState(this.#connection, fn);
882
- performance.measure(`[SQL] ${description}`, { start });
883
- return r;
884
- }
885
- catch (e) {
886
- performance.measure(`[SQL] [ERROR: ${e.message}] ${description}`, { start });
887
- throw e;
888
- }
889
- }
890
- else {
891
- return useConnectionState(this.#connection, fn);
892
- }
893
- }
894
- async executeRaw(query, params) {
895
- return await this.#executeOnWorker(query, params);
896
- }
897
- async #executeOnWorker(query, params) {
898
- return this.maybeTrace((c) => c.execute(this.#token, query, params), () => query);
899
- }
900
- async executeBatch(query, params = []) {
901
- const results = await this.maybeTrace((c) => c.executeBatch(this.#token, query, params), () => `${query} (batch of ${params.length})`);
902
- const result = { insertId: undefined, rowsAffected: 0 };
903
- for (const source of results) {
904
- result.insertId = source.insertId;
905
- result.rowsAffected = (result.rowsAffected ?? 0) + source.rowsAffected;
906
- }
907
- return queryResultWithoutRows(result);
908
- }
909
- }
910
- async function useConnectionState(state, workerPromise, fireActionOnAbort = false) {
911
- const controller = state.notifyRemoteClosed;
912
- if (controller) {
913
- return new Promise((resolve, reject) => {
914
- if (controller.signal.aborted) {
915
- reject(new ConnectionClosedError('Called operation on closed remote'));
916
- if (!fireActionOnAbort) {
917
- // Don't run the operation if we're going to reject
918
- // We might want to fire-and-forget the operation in some cases (like a close operation)
919
- return;
920
- }
921
- }
922
- function handleAbort() {
923
- reject(new ConnectionClosedError('Remote peer closed with request in flight'));
924
- }
925
- function completePromise(action) {
926
- controller.signal.removeEventListener('abort', handleAbort);
927
- action();
928
- }
929
- controller.signal.addEventListener('abort', handleAbort);
930
- workerPromise(state.connection)
931
- .then((data) => completePromise(() => resolve(data)))
932
- .catch((e) => completePromise(() => reject(e)));
933
- });
934
- }
935
- else {
936
- // Can't close, so just return the inner worker promise unguarded.
937
- return workerPromise(state.connection);
938
- }
939
- }
940
-
941
- /**
942
- * Requests a random lock that will be released once the optional signal is aborted (or, if no signal is given, when the
943
- * tab is closed).
944
- *
945
- * This allows sending the name of the lock to another context (e.g. a shared worker), which will also attempt to
946
- * acquire it. Since the lock is returned when the tab is closed, this allows the shared worker to free resources
947
- * assocatiated with this tab.
948
- *
949
- * We take hold of this lock as soon-as-possible in order to cater for potentially closed tabs.
950
- */
951
- function generateTabCloseSignal(abort) {
952
- return new Promise((resolve, reject) => {
953
- const options = { signal: abort };
954
- getNavigatorLocks()
955
- .request(`tab-close-signal-${crypto.randomUUID()}`, options, (lock) => {
956
- resolve(lock.name);
957
- return new Promise((resolve) => {
958
- if (abort) {
959
- abort.addEventListener('abort', () => resolve());
960
- }
961
- });
962
- })
963
- .catch(reject);
964
- });
965
- }
966
-
967
- /**
968
- * A connection pool implementation delegating to another pool opened asynchronnously.
969
- */
970
- class AsyncDbAdapter extends DBAdapter {
971
- name;
972
- state;
973
- resolvedWriter;
974
- pendingListeners = new Set();
975
- constructor(inner, name) {
976
- super();
977
- this.name = name;
978
- this.state = inner.then((client) => {
979
- for (const pending of this.pendingListeners) {
980
- pending.closeAfterRegisteredOnResolvedPool = client.writer.registerListener(pending.listener);
981
- }
982
- this.pendingListeners.clear();
983
- this.resolvedWriter = client.writer;
984
- if (client.additionalReaders.length) {
985
- return readWritePoolState(client.writer, client.additionalReaders);
986
- }
987
- return singleConnectionPoolState(client.writer);
988
- });
989
- }
990
- async init() {
991
- await this.state;
992
- }
993
- async close() {
994
- const state = await this.state;
995
- await state.close();
996
- }
997
- async readLock(fn, options) {
998
- const state = await this.state;
999
- return state.withConnection(true, fn, options);
1000
- }
1001
- async writeLock(fn, options) {
1002
- const state = await this.state;
1003
- return state.withConnection(false, fn, options);
1004
- }
1005
- async refreshSchema() {
1006
- const state = await this.state;
1007
- await state.refreshSchema();
1008
- }
1009
- registerListener(listener) {
1010
- if (this.resolvedWriter) {
1011
- return this.resolvedWriter.registerListener(listener);
1012
- }
1013
- else {
1014
- const pending = { listener };
1015
- this.pendingListeners.add(pending);
1016
- return () => {
1017
- if (pending.closeAfterRegisteredOnResolvedPool) {
1018
- return pending.closeAfterRegisteredOnResolvedPool();
1019
- }
1020
- else {
1021
- // Has not been registered yet, we can just remove the pending listener.
1022
- this.pendingListeners.delete(pending);
1023
- }
1024
- };
1025
- }
1026
- }
1027
- async shareConnection() {
1028
- const state = await this.state;
1029
- return state.writer.shareConnection();
1030
- }
1031
- getConfiguration() {
1032
- if (this.resolvedWriter) {
1033
- return this.resolvedWriter.getConfiguration();
1034
- }
1035
- throw new Error('AsyncDbAdapter.getConfiguration() can only be called after initializing it.');
1036
- }
1037
- }
1038
- function singleConnectionPoolState(connection) {
1039
- return {
1040
- writer: connection,
1041
- withConnection: (allowReadOnly, fn, options) => {
1042
- if (allowReadOnly) {
1043
- return connection.readLock(fn, options);
1044
- }
1045
- else {
1046
- return connection.writeLock(fn, options);
1047
- }
1048
- },
1049
- close: () => connection.close(),
1050
- refreshSchema: () => connection.refreshSchema()
1051
- };
1052
- }
1053
- function readWritePoolState(writer, readers) {
1054
- // DatabaseClients have locks internally, so these aren't necessary for correctness. However, our mutex and semaphore
1055
- // implementations are very cheap to cancel, which we use to dispatch reads to the first available connection (by
1056
- // simply requesting all of them and sticking with the first connection we get).
1057
- const writerMutex = new Mutex();
1058
- const readerSemaphore = new Semaphore(readers);
1059
- return {
1060
- writer,
1061
- async withConnection(allowReadOnly, fn, options) {
1062
- const abortController = new AbortController();
1063
- const abortSignal = abortController.signal;
1064
- let timeout = null;
1065
- let release;
1066
- if (options?.timeoutMs) {
1067
- timeout = setTimeout(() => abortController.abort, options.timeoutMs);
1068
- }
1069
- try {
1070
- if (allowReadOnly) {
1071
- let connection;
1072
- // Even if we have a pool of read connections, it's typically very small and we assume that most queries are
1073
- // reads. So, we want to request any connection from the read pool and the dedicated write connection (which
1074
- // can also serve reads). We race for the first connection we can obtain this way, and then abort the other
1075
- // request.
1076
- [connection, release] = await new Promise((resolve, reject) => {
1077
- let didComplete = false;
1078
- function complete() {
1079
- didComplete = true;
1080
- abortController.abort();
1081
- }
1082
- function completeSuccess(connection, returnFn) {
1083
- if (didComplete) {
1084
- // We're not going to use this connection, so return it immediately.
1085
- returnFn();
1086
- }
1087
- else {
1088
- complete();
1089
- resolve([connection, returnFn]);
1090
- }
1091
- }
1092
- function completeError(error) {
1093
- // We either have a working connection already, or we've rejected the promise. Either way, we don't need
1094
- // to do either thing again.
1095
- if (didComplete)
1096
- return;
1097
- complete();
1098
- reject(error);
1099
- }
1100
- writerMutex.acquire(abortSignal).then((unlock) => completeSuccess(writer, unlock), completeError);
1101
- readerSemaphore
1102
- .requestOne(abortSignal)
1103
- .then(({ item, release }) => completeSuccess(item, release), completeError);
1104
- });
1105
- return await connection.readLock(fn);
1106
- }
1107
- else {
1108
- return await writerMutex.runExclusive(() => writer.writeLock(fn), abortSignal);
1109
- }
1110
- }
1111
- finally {
1112
- if (timeout != null) {
1113
- clearTimeout(timeout);
1114
- }
1115
- release?.();
1116
- }
1117
- },
1118
- async close() {
1119
- await writer.close();
1120
- await Promise.all(readers.map((r) => r.close()));
1121
- },
1122
- async refreshSchema() {
1123
- await writer.refreshSchema();
1124
- await Promise.all(readers.map((r) => r.refreshSchema()));
1125
- }
1126
- };
1127
- }
1128
-
1129
- var TemporaryStorageOption;
1130
- (function (TemporaryStorageOption) {
1131
- TemporaryStorageOption["MEMORY"] = "memory";
1132
- TemporaryStorageOption["FILESYSTEM"] = "file";
1133
- })(TemporaryStorageOption || (TemporaryStorageOption = {}));
1134
-
1135
- /**
1136
- * @internal
1137
- */
1138
- function resolveAndValidateOptions(options) {
1139
- const defaults = {
1140
- disableSSRWarning: false,
1141
- ssrMode: !('window' in globalThis),
1142
- /**
1143
- * Multiple tabs are by default not supported on Android, iOS and Safari.
1144
- * Other platforms will have multiple tabs enabled by default.
1145
- */
1146
- enableMultiTabs: typeof globalThis.navigator !== 'undefined' && // For SSR purposes
1147
- typeof SharedWorker !== 'undefined' &&
1148
- !navigator.userAgent.match(/(Android|iPhone|iPod|iPad)/i) &&
1149
- !window.safari,
1150
- useWebWorker: true,
1151
- databaseWorkerLogLevel: LogLevels.info,
1152
- temporaryStorage: TemporaryStorageOption.MEMORY,
1153
- cacheSizeKb: 50 * 1024,
1154
- encryptionKey: undefined,
1155
- vfs: WASQLiteVFS.IDBBatchAtomicVFS,
1156
- additionalReaders: 1
1157
- };
1158
- const resolved = Object.assign(defaults, options);
1159
- if (vfsRequiresDedicatedWorkers(resolved.vfs) && !resolved.useWebWorker) {
1160
- throw new Error(`Invalid configuration: The 'useWebWorker' flag must be true when using an OPFS-based VFS (${resolved.vfs}).`);
1161
- }
1162
- return resolved;
1163
- }
1164
-
1165
- function connectToWorker({ service, databaseIdentifier, customWorker, shared }) {
1166
- const name = `${shared ? 'shared-' : ''}powersync-${databaseIdentifier}`;
1167
- let worker;
1168
- if (customWorker) {
1169
- worker = shared
1170
- ? new SharedWorker(customWorker, {
1171
- /* @vite-ignore */
1172
- name,
1173
- type: 'module'
1174
- })
1175
- : new Worker(customWorker, {
1176
- /* @vite-ignore */
1177
- name,
1178
- type: 'module'
1179
- });
1180
- }
1181
- else {
1182
- worker = spawnDefaultPowerSyncWorker();
1183
- }
1184
- return connectToExistingWorker(worker, service);
1185
- }
1186
- /**
1187
- * Opens the default PowerSync worker.
1188
- *
1189
- * When users depend on the web SDK, we assume they use their own bundler (either vite or webpack). Both recognize the
1190
- * syntax of worker constructors with a string literal and will rewrite the URL as part of their bundling processes.
1191
- *
1192
- * React Native / Metro users can't rely on this on the web, as their app is not a JavaScript module and import.meta.url
1193
- * is not rewritten by Metro. For those users, we include a pre-bundled worker they can copy into a static assets
1194
- * directory and load with a custom URI. This also means that defaultWorker cannot work with Metro for React Native Web.
1195
- * We have a custom rollup plugin and conditional exports that replaces this function with a throwing stub for that
1196
- * platform. This allows a helpful error message.
1197
- */
1198
- // Note: When changing this function, also update disableDefaultWorkers in rollup.config.ts.
1199
- function spawnDefaultPowerSyncWorker(shared, name) {
1200
- throw new Error('You are using the React Native web build of the PowerSync SDK, which requires custom worker URLs. Please see the documentation at https://docs.powersync.com/client-sdks/frameworks/react-native-web-support for details.');
1201
- }
1202
-
1203
- function connectToExistingWorker(worker, service) {
1204
- const isShared = isSharedWorker(worker);
1205
- if (isShared) {
1206
- const { port1, port2 } = new MessageChannel();
1207
- const mainPort = worker.port;
1208
- mainPort.start();
1209
- mainPort.postMessage({ port: port1, service }, [port1]);
1210
- port2.start();
1211
- return {
1212
- endpoint: port2,
1213
- worker,
1214
- close() {
1215
- port2.close();
1216
- }
1217
- };
1218
- }
1219
- else {
1220
- return {
1221
- endpoint: worker,
1222
- worker,
1223
- close() {
1224
- worker.terminate();
1225
- }
1226
- };
1227
- }
1228
- }
1229
- function isSharedWorker(worker) {
1230
- return 'port' in worker;
1231
- }
1232
-
1233
- /**
1234
- * Opens a SQLite connection using WA-SQLite.
1235
- */
1236
- class WASQLiteOpenFactory {
1237
- options;
1238
- logger;
1239
- constructor(options) {
1240
- this.options = resolveAndValidateOptions(options.open);
1241
- this.logger = options.logger;
1242
- }
1243
- openAdapter() {
1244
- return new AsyncDbAdapter(this.openConnection(), this.options.dbFilename);
1245
- }
1246
- openDB() {
1247
- const { disableSSRWarning, enableMultiTabs, ssrMode } = this.options;
1248
- if (ssrMode) {
1249
- if (!disableSSRWarning) {
1250
- this.logger.log({
1251
- level: LogLevels.warn,
1252
- message: `
1253
- Running PowerSync in SSR mode.
1254
- Only empty query results will be returned.
1255
- Disable this warning by setting 'disableSSRWarning: true' in options.`
1256
- });
1257
- }
1258
- return new SSRDBAdapter();
1259
- }
1260
- if (!enableMultiTabs) {
1261
- this.logger.log({
1262
- level: LogLevels.warn,
1263
- message: 'Multiple tab support is not enabled. Using this site across multiple tabs may not function correctly.'
1264
- });
1265
- }
1266
- return this.openAdapter();
1267
- }
1268
- async openConnection() {
1269
- const { enableMultiTabs, useWebWorker, vfs, dbFilename, encryptionKey, temporaryStorage, cacheSizeKb } = this.options;
1270
- if (!enableMultiTabs) {
1271
- this.logger.log({ level: LogLevels.warn, message: 'Multiple tabs are not enabled in this browser' });
1272
- }
1273
- let client;
1274
- let additionalReaders = [];
1275
- let requiresPersistentTriggers = vfsRequiresDedicatedWorkers(vfs);
1276
- function resolveRawWaSqliteDatabaseOptions(readonly) {
1277
- return {
1278
- filename: dbFilename,
1279
- readonly,
1280
- vfs,
1281
- encryptionKey,
1282
- temporaryStorage,
1283
- cacheSizeKb
1284
- };
1285
- }
1286
- if (useWebWorker) {
1287
- const optionsDbWorker = this.options.worker;
1288
- const openDatabaseWorker = async (readonly) => {
1289
- let workerConnection;
1290
- if (typeof optionsDbWorker == 'function') {
1291
- const worker = optionsDbWorker(this.options);
1292
- workerConnection = connectToExistingWorker(worker, 'database');
1293
- }
1294
- else {
1295
- const needsDedicated = vfsRequiresDedicatedWorkers(vfs);
1296
- const useShared = !needsDedicated && enableMultiTabs;
1297
- workerConnection = connectToWorker({
1298
- service: 'database',
1299
- databaseIdentifier: this.options.dbFilename,
1300
- shared: useShared,
1301
- customWorker: optionsDbWorker
1302
- });
1303
- }
1304
- const source = Comlink.wrap(workerConnection.endpoint);
1305
- const closeSignal = new AbortController();
1306
- const connection = await source.connect({
1307
- database: resolveRawWaSqliteDatabaseOptions(readonly),
1308
- logLevel: this.options.databaseWorkerLogLevel,
1309
- lockName: await generateTabCloseSignal(closeSignal.signal)
1310
- });
1311
- const clientOptions = {
1312
- connection,
1313
- source,
1314
- // This tab owns the worker, so we're guaranteed to outlive it.
1315
- remoteCanCloseUnexpectedly: false,
1316
- onClose: () => {
1317
- closeSignal.abort();
1318
- workerConnection.close();
1319
- }
1320
- };
1321
- return new DatabaseClient(clientOptions, {
1322
- ...this.options,
1323
- requiresPersistentTriggers
1324
- });
1325
- };
1326
- client = await openDatabaseWorker(false);
1327
- if (vfs == WASQLiteVFS.OPFSWriteAheadVFS) {
1328
- // This VFS supports concurrent reads, so we can open additional workers to host read-only connections for
1329
- // concurrent reads / writes.
1330
- const additionalReadersCount = this.options.additionalReaders ?? 1;
1331
- for (let i = 0; i < additionalReadersCount; i++) {
1332
- const reader = await openDatabaseWorker(true);
1333
- additionalReaders.push(reader);
1334
- }
1335
- }
1336
- }
1337
- else {
1338
- // Don't use a web worker. Instead, open the MultiDatabaseServer a worker would use locally.
1339
- const localServer = new MultiDatabaseServer(this.logger);
1340
- requiresPersistentTriggers = true;
1341
- const connection = await localServer.openConnectionLocally(this.logger, resolveRawWaSqliteDatabaseOptions(false));
1342
- client = new DatabaseClient({ connection, source: null, remoteCanCloseUnexpectedly: false }, {
1343
- ...this.options,
1344
- requiresPersistentTriggers
1345
- });
1346
- }
1347
- return {
1348
- writer: client,
1349
- additionalReaders
1350
- };
1351
- }
1352
- }
1353
-
1354
- /**
1355
- * @internal
1356
- * @experimental
1357
- */
1358
- const NAVIGATOR_TRIGGER_CLAIM_MANAGER = {
1359
- async obtainClaim(identifier) {
1360
- return new Promise((resolveReleaser) => {
1361
- getNavigatorLocks().request(identifier, async () => {
1362
- await new Promise((releaseLock) => {
1363
- resolveReleaser(async () => releaseLock());
1364
- });
1365
- });
1366
- });
1367
- },
1368
- async checkClaim(identifier) {
1369
- const currentState = await getNavigatorLocks().query();
1370
- return currentState.held?.find((heldLock) => heldLock.name == identifier) != null;
1371
- }
1372
- };
1373
-
1374
- class SSRStreamingSyncImplementation extends BaseObserver {
1375
- syncMutex;
1376
- crudMutex;
1377
- isConnected;
1378
- lastSyncedAt;
1379
- constructor() {
1380
- super();
1381
- this.syncMutex = new Mutex();
1382
- this.crudMutex = new Mutex();
1383
- this.isConnected = false;
1384
- }
1385
- obtainLock(lockOptions) {
1386
- const mutex = lockOptions.type == LockType.CRUD ? this.crudMutex : this.syncMutex;
1387
- return mutex.runExclusive(lockOptions.callback, lockOptions.signal);
1388
- }
1389
- /**
1390
- * This is a no-op in SSR mode
1391
- */
1392
- async connect() { }
1393
- async dispose() { }
1394
- /**
1395
- * This is a no-op in SSR mode
1396
- */
1397
- async disconnect() { }
1398
- /**
1399
- * This SSR Mode implementation is immediately ready.
1400
- */
1401
- async waitForReady() { }
1402
- /**
1403
- * This will never resolve in SSR Mode.
1404
- */
1405
- waitUntilStatusMatches(_predicate) {
1406
- return new Promise(() => { });
1407
- }
1408
- /**
1409
- * Returns a placeholder checkpoint. This should not be used.
1410
- */
1411
- async getWriteCheckpoint() {
1412
- return '1';
1413
- }
1414
- /**
1415
- * The SSR mode adapter will never complete syncing.
1416
- */
1417
- async hasCompletedSync() {
1418
- return false;
1419
- }
1420
- /**
1421
- * This is a no-op in SSR mode.
1422
- */
1423
- triggerCrudUpload() { }
1424
- /**
1425
- * No-op in SSR mode.
1426
- */
1427
- updateSubscriptions() { }
1428
- /**
1429
- * No-op in SSR mode.
1430
- */
1431
- markConnectionMayHaveChanged() { }
1432
- }
1433
-
1434
- /**
1435
- * The client side port should provide these methods.
1436
- */
1437
- class AbstractSharedSyncClientProvider {
1438
- }
1439
-
1440
- /**
1441
- * Get a minimal representation of browser, version and operating system.
1442
- *
1443
- * The goal is to get enough environemnt info to reproduce issues, but no
1444
- * more.
1445
- */
1446
- function getUserAgentInfo(nav) {
1447
- nav ??= navigator;
1448
- const browser = getBrowserInfo(nav);
1449
- const os = getOsInfo(nav);
1450
- // The cast below is to cater for TypeScript < 5.5.0
1451
- return [browser, os].filter((v) => v != null);
1452
- }
1453
- function getBrowserInfo(nav) {
1454
- const brands = nav.userAgentData?.brands;
1455
- if (brands != null) {
1456
- const tests = [
1457
- { name: 'Google Chrome', value: 'Chrome' },
1458
- { name: 'Opera', value: 'Opera' },
1459
- { name: 'Edge', value: 'Edge' },
1460
- { name: 'Chromium', value: 'Chromium' }
1461
- ];
1462
- for (let { name, value } of tests) {
1463
- const brand = brands.find((b) => b.brand == name);
1464
- if (brand != null) {
1465
- return `${value}/${brand.version}`;
1466
- }
1467
- }
1468
- }
1469
- const ua = nav.userAgent;
1470
- const regexps = [
1471
- { re: /(?:firefox|fxios)\/(\d+)/i, value: 'Firefox' },
1472
- { re: /(?:edg|edge|edga|edgios)\/(\d+)/i, value: 'Edge' },
1473
- { re: /opr\/(\d+)/i, value: 'Opera' },
1474
- { re: /(?:chrome|chromium|crios)\/(\d+)/i, value: 'Chrome' },
1475
- { re: /version\/(\d+).*safari/i, value: 'Safari' }
1476
- ];
1477
- for (let { re, value } of regexps) {
1478
- const match = re.exec(ua);
1479
- if (match != null) {
1480
- return `${value}/${match[1]}`;
1481
- }
1482
- }
1483
- return null;
1484
- }
1485
- function getOsInfo(nav) {
1486
- if (nav.userAgentData?.platform != null) {
1487
- return nav.userAgentData.platform.toLowerCase();
1488
- }
1489
- const ua = nav.userAgent;
1490
- const regexps = [
1491
- { re: /windows/i, value: 'windows' },
1492
- { re: /android/i, value: 'android' },
1493
- { re: /linux/i, value: 'linux' },
1494
- { re: /iphone|ipad|ipod/i, value: 'ios' },
1495
- { re: /macintosh|mac os x/i, value: 'macos' }
1496
- ];
1497
- for (let { re, value } of regexps) {
1498
- if (re.test(ua)) {
1499
- return value;
1500
- }
1501
- }
1502
- return null;
1503
- }
1504
-
1505
- class WebRemote extends AbstractRemote {
1506
- connector;
1507
- constructor(connector, logger) {
1508
- super(connector, logger);
1509
- this.connector = connector;
1510
- }
1511
- fetch({ resource, request }) {
1512
- return fetch(resource, request);
1513
- }
1514
- async loadWebSocketSupport(platform) {
1515
- if (!websockets) {
1516
- // loadWebSocketSupport being called concurrently is safe, the import resolves to the same module in that case.
1517
- const module = await import('@powersync/shared-internals/websockets');
1518
- websockets = new module.WebSocketSupport(platform);
1519
- }
1520
- return websockets;
1521
- }
1522
- getUserAgent() {
1523
- let ua = [super.getUserAgent(), `powersync-web`];
1524
- try {
1525
- ua.push(...getUserAgentInfo());
1526
- }
1527
- catch (error) {
1528
- this.logger.log({ level: LogLevels.warn, message: 'Failed to get user agent info', error });
1529
- }
1530
- return ua.join(' ');
1531
- }
1532
- }
1533
- let websockets;
1534
-
1535
- class WebStreamingSyncImplementation extends AbstractStreamingSyncImplementation {
1536
- constructor(options) {
1537
- // Super will store and provide default values for options
1538
- super(options);
1539
- }
1540
- get webOptions() {
1541
- return this.options;
1542
- }
1543
- async obtainLock(lockOptions) {
1544
- const identifier = `streaming-sync-${lockOptions.type}-${this.webOptions.identifier}`;
1545
- if (lockOptions.type == LockType.SYNC) {
1546
- this.logger.log({ level: LogLevels.debug, message: `requesting lock for ${identifier}` });
1547
- }
1548
- return getNavigatorLocks().request(identifier, { signal: lockOptions.signal }, lockOptions.callback);
1549
- }
1550
- }
1551
-
1552
- /**
1553
- * @internal
1554
- * Manual message events for shared sync clients
1555
- */
1556
- var SharedSyncClientEvent;
1557
- (function (SharedSyncClientEvent) {
1558
- /**
1559
- * This client requests the shared sync manager should
1560
- * close it's connection to the client.
1561
- */
1562
- SharedSyncClientEvent["CLOSE_CLIENT"] = "close-client";
1563
- SharedSyncClientEvent["CLOSE_ACK"] = "close-ack";
1564
- })(SharedSyncClientEvent || (SharedSyncClientEvent = {}));
1565
-
1566
- /**
1567
- * The shared worker will trigger methods on this side of the message port
1568
- * via this client provider.
1569
- */
1570
- class SharedSyncClientProvider extends AbstractSharedSyncClientProvider {
1571
- options;
1572
- statusChanged;
1573
- webDB;
1574
- constructor(options, statusChanged, webDB) {
1575
- super();
1576
- this.options = options;
1577
- this.statusChanged = statusChanged;
1578
- this.webDB = webDB;
1579
- }
1580
- async getDBWorkerPort() {
1581
- const { port } = await this.webDB.shareConnection();
1582
- return Comlink.transfer(port, [port]);
1583
- }
1584
- invalidateCredentials() {
1585
- this.options.remote.invalidateCredentials();
1586
- }
1587
- async fetchCredentials() {
1588
- const credentials = await this.options.remote.getCredentials();
1589
- if (credentials == null) {
1590
- return null;
1591
- }
1592
- /**
1593
- * The credentials need to be serializable.
1594
- * Users might extend [PowerSyncCredentials] to contain
1595
- * items which are not serializable.
1596
- * This returns only the essential fields.
1597
- */
1598
- return {
1599
- endpoint: credentials.endpoint,
1600
- token: credentials.token
1601
- };
1602
- }
1603
- async uploadCrud() {
1604
- /**
1605
- * Don't return anything here, just incase something which is not
1606
- * serializable is returned from the `uploadCrud` function.
1607
- */
1608
- await this.options.uploadCrud();
1609
- }
1610
- get logger() {
1611
- return this.options.logger;
1612
- }
1613
- log(record) {
1614
- this.logger.log(record);
1615
- }
1616
- }
1617
- /**
1618
- * The local part of the sync implementation on the web, which talks to a sync implementation hosted in a shared worker.
1619
- */
1620
- class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplementation {
1621
- syncManager;
1622
- clientProvider;
1623
- worker;
1624
- isInitialized;
1625
- dbAdapter;
1626
- abortOnClose = new AbortController();
1627
- logLevel;
1628
- enableBroadcastLogs;
1629
- constructor(options) {
1630
- super(options);
1631
- this.dbAdapter = options.db;
1632
- this.logLevel = options.logLevel;
1633
- this.enableBroadcastLogs = options.enableBroadcastLogs;
1634
- const syncWorker = options.sync?.worker;
1635
- if (typeof syncWorker === 'function') {
1636
- this.worker = connectToExistingWorker(syncWorker(), 'sync');
1637
- }
1638
- else {
1639
- this.worker = connectToWorker({
1640
- service: 'sync',
1641
- databaseIdentifier: this.webOptions.identifier,
1642
- shared: true,
1643
- customWorker: syncWorker
1644
- });
1645
- }
1646
- /**
1647
- * Pass along any sync status updates to this listener
1648
- */
1649
- this.clientProvider = new SharedSyncClientProvider(this.webOptions, ({ core, dataFlow }) => {
1650
- this.updateSyncStatus(core, dataFlow);
1651
- }, options.db);
1652
- this.syncManager = Comlink.wrap(this.worker.endpoint);
1653
- /**
1654
- * The sync worker will call this client provider when it needs
1655
- * to fetch credentials or upload data.
1656
- * This performs bi-directional method calling.
1657
- */
1658
- Comlink.expose(this.clientProvider, this.worker.endpoint);
1659
- this.syncManager.setLogLevel(this.logLevel);
1660
- this.triggerCrudUpload = this.syncManager.triggerCrudUpload;
1661
- /**
1662
- * Opens MessagePort to the existing shared DB worker.
1663
- * The sync worker cannot initiate connections directly to the
1664
- * DB worker, but a port to the DB worker can be transferred to the
1665
- * sync worker.
1666
- */
1667
- this.isInitialized = this._init();
1668
- }
1669
- async _init() {
1670
- /**
1671
- * The general flow of initialization is:
1672
- * - The client requests a unique navigator lock.
1673
- * - Once the lock is acquired, we register the lock with the shared worker.
1674
- * - The shared worker can then request the same lock. The client has been closed if the shared worker can acquire the lock.
1675
- * - Once the shared worker knows the client's lock, we can guarentee that the shared worker will detect if the client has been closed.
1676
- * - This makes the client safe for the shared worker to use.
1677
- * - The client is only added to the SharedSyncImplementation once the lock has been registered.
1678
- * This ensures we don't ever keep track of dead clients (tabs that closed before the lock was registered).
1679
- * - The client side lock is held until the client is disposed.
1680
- * - We resolve the top-level promise after the lock has been registered with the shared worker.
1681
- * - The client sends the params to the shared worker after locks have been registered.
1682
- */
1683
- const closeSignal = await generateTabCloseSignal(this.abortOnClose.signal);
1684
- // Awaiting here ensures the worker is waiting for the lock
1685
- await this.syncManager.addLockBasedCloseSignal(closeSignal);
1686
- const { identifier } = this.options;
1687
- await this.syncManager.setParams({
1688
- dbParams: this.dbAdapter.getConfiguration(),
1689
- streamOptions: {
1690
- identifier,
1691
- serializedSchema: this.options.serializedSchema
1692
- },
1693
- enableBroadcastLogs: this.enableBroadcastLogs
1694
- }, this.options.subscriptions);
1695
- }
1696
- /**
1697
- * Starts the sync process, this effectively acts as a call to
1698
- * `connect` if not yet connected.
1699
- */
1700
- async connect(options) {
1701
- await this.waitForReady();
1702
- return this.syncManager.connect(options, this.options.serializedSchema);
1703
- }
1704
- async disconnect() {
1705
- await this.waitForReady();
1706
- return this.syncManager.disconnect();
1707
- }
1708
- async getWriteCheckpoint() {
1709
- await this.waitForReady();
1710
- return this.syncManager.getWriteCheckpoint();
1711
- }
1712
- async dispose() {
1713
- await this.waitForReady();
1714
- await new Promise((resolve) => {
1715
- // This will always be a message port since we use shared workers.
1716
- const messagePort = this.worker.endpoint;
1717
- // Listen for the close acknowledgment from the worker
1718
- messagePort.addEventListener('message', (event) => {
1719
- const payload = event.data;
1720
- if (payload?.event === SharedSyncClientEvent.CLOSE_ACK) {
1721
- resolve();
1722
- }
1723
- });
1724
- // Signal the shared worker that this client is closing its connection to the worker
1725
- const closeMessagePayload = {
1726
- event: SharedSyncClientEvent.CLOSE_CLIENT,
1727
- data: {}
1728
- };
1729
- messagePort.postMessage(closeMessagePayload);
1730
- });
1731
- await super.dispose();
1732
- this.abortOnClose.abort();
1733
- // Release the proxy
1734
- this.syncManager[Comlink.releaseProxy]();
1735
- this.worker.close();
1736
- }
1737
- async waitForReady() {
1738
- return this.isInitialized;
1739
- }
1740
- updateSubscriptions(subscriptions) {
1741
- this.syncManager.updateSubscriptions(subscriptions);
1742
- }
1743
- }
1744
-
1745
- /**
1746
- * @internal Use {@link PowerSyncDatabase} instead, this class is only used by other SDKs also needing web support.
1747
- */
1748
- class WebPowerSyncDatabase extends BasePowerSyncDatabase {
1749
- static SHARED_MUTEX = new Mutex();
1750
- resolvedOpenOptions;
1751
- enableBroadcastLogs;
1752
- constructor(options) {
1753
- const resolvedOpenOptions = resolveAndValidateOptions('database' in options ? options.database : {});
1754
- super(options);
1755
- this.resolvedOpenOptions = resolvedOpenOptions;
1756
- this.enableBroadcastLogs = options.broadcastLogs ?? true;
1757
- }
1758
- async _initialize() {
1759
- if (this.database instanceof AsyncDbAdapter) {
1760
- /**
1761
- * While init is done automatically,
1762
- * LockedAsyncDatabaseAdapter only exposes config after init.
1763
- * We can explicitly wait for init here in order to access config.
1764
- */
1765
- await this.database.init();
1766
- }
1767
- // In some cases, like the SQLJs adapter, we don't pass a WebDBAdapter, so we need to check.
1768
- if (typeof this.database.getConfiguration == 'function') {
1769
- const config = this.database.getConfiguration();
1770
- if (config.requiresPersistentTriggers) {
1771
- this.triggersImpl.updateDefaults({
1772
- useStorageByDefault: true
1773
- });
1774
- }
1775
- }
1776
- }
1777
- generateTriggerManagerConfig() {
1778
- return {
1779
- // We need to share hold information between tabs for web
1780
- claimManager: NAVIGATOR_TRIGGER_CLAIM_MANAGER
1781
- };
1782
- }
1783
- openDBAdapter() {
1784
- return openDatabase(this.options, (options) => {
1785
- const defaultFactory = new WASQLiteOpenFactory({
1786
- logger: this.logger,
1787
- open: options
1788
- });
1789
- return defaultFactory.openDB();
1790
- });
1791
- }
1792
- /**
1793
- * Closes the database connection.
1794
- * By default the sync stream client is only disconnected if
1795
- * multiple tabs are not enabled.
1796
- */
1797
- close(options) {
1798
- return super.close({
1799
- // Don't disconnect by default if multiple tabs are enabled
1800
- disconnect: options?.disconnect ?? !this.resolvedOpenOptions.enableMultiTabs
1801
- });
1802
- }
1803
- async loadVersion() {
1804
- if (this.resolvedOpenOptions.ssrMode) {
1805
- return;
1806
- }
1807
- return super.loadVersion();
1808
- }
1809
- async resolveOfflineSyncStatus() {
1810
- if (this.resolvedOpenOptions.ssrMode) {
1811
- return;
1812
- }
1813
- return super.resolveOfflineSyncStatus();
1814
- }
1815
- generateBucketStorageAdapter() {
1816
- return new SqliteBucketStorage(this.database, this.logger);
1817
- }
1818
- async runExclusive(cb) {
1819
- if (this.resolvedOpenOptions.ssrMode) {
1820
- return WebPowerSyncDatabase.SHARED_MUTEX.runExclusive(cb);
1821
- }
1822
- return getNavigatorLocks().request(`lock-${this.database.name}`, cb);
1823
- }
1824
- generateSyncStreamImplementation(connector, options) {
1825
- const remote = new WebRemote(connector, this.logger);
1826
- const syncOptions = {
1827
- ...this.options,
1828
- ...options,
1829
- adapter: this.bucketStorageAdapter,
1830
- remote,
1831
- uploadCrud: async () => {
1832
- await this.waitForReady();
1833
- await connector.uploadData(this);
1834
- },
1835
- identifier: this.database.name,
1836
- logger: this.logger
1837
- };
1838
- switch (true) {
1839
- case this.resolvedOpenOptions.ssrMode:
1840
- return new SSRStreamingSyncImplementation();
1841
- case this.resolvedOpenOptions.enableMultiTabs:
1842
- if (!this.enableBroadcastLogs) {
1843
- const warning = `
1844
- Multiple tabs are enabled, but broadcasting of logs is disabled.
1845
- Logs for shared sync worker will only be available in the shared worker context
1846
- `;
1847
- const logger = this.options.logger;
1848
- logger ? logger.log({ level: LogLevels.warn, message: warning }) : console.warn(warning);
1849
- }
1850
- return new SharedWebStreamingSyncImplementation({
1851
- ...syncOptions,
1852
- db: this.database, // This should always be the case
1853
- logLevel: this.options.sync?.logLevel ?? LogLevels.info,
1854
- enableBroadcastLogs: this.enableBroadcastLogs
1855
- });
1856
- default:
1857
- return new WebStreamingSyncImplementation(syncOptions);
1858
- }
1859
- }
1860
- }
1861
- /**
1862
- * A PowerSync database which provides SQLite functionality
1863
- * which is automatically synced.
1864
- *
1865
- * @example
1866
- * ```typescript
1867
- * export const db = new PowerSyncDatabase({
1868
- * schema: AppSchema,
1869
- * database: {
1870
- * dbFilename: 'example.db'
1871
- * }
1872
- * });
1873
- * ```
1874
- */
1875
- // Typed constructor to avoid leaking AbstractPowerSyncDatabase into the public interface
1876
- const PowerSyncDatabase = WebPowerSyncDatabase;
1877
-
1878
- export { IndexDBFileSystemStorageAdapter, PowerSyncDatabase, SharedWebStreamingSyncImplementation, TemporaryStorageOption, WASQLiteOpenFactory, WASQLiteVFS, WebPowerSyncDatabase, WebRemote, WebStreamingSyncImplementation };
1879
- //# sourceMappingURL=index.react_native_web.js.map