@powersync/web 0.0.0-dev-20260708104358 → 0.0.0-dev-20260917074240

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