jazz-tools 2.0.0-alpha.6 → 2.0.0-alpha.61

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 (1647) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +179 -3
  3. package/bin/jazz-tools.js +94 -45
  4. package/dist/_dev/inspector-cache-runtime.d.ts +8 -0
  5. package/dist/_dev/inspector-cache-runtime.d.ts.map +1 -0
  6. package/dist/_dev/inspector-cache-runtime.js +237 -0
  7. package/dist/_dev/inspector-cache-runtime.js.map +1 -0
  8. package/dist/_dev/inspector-client.d.ts +15 -0
  9. package/dist/_dev/inspector-client.d.ts.map +1 -0
  10. package/dist/_dev/inspector-client.js +134 -0
  11. package/dist/_dev/inspector-client.js.map +1 -0
  12. package/dist/_dev/native-account-session.d.ts +23 -0
  13. package/dist/_dev/native-account-session.d.ts.map +1 -0
  14. package/dist/_dev/native-account-session.js +61 -0
  15. package/dist/_dev/native-account-session.js.map +1 -0
  16. package/dist/_dev/native-binding-codec.d.ts +9 -0
  17. package/dist/_dev/native-binding-codec.d.ts.map +1 -0
  18. package/dist/_dev/native-binding-codec.js +9 -0
  19. package/dist/_dev/native-binding-codec.js.map +1 -0
  20. package/dist/accounts/account-manager-core.d.ts +34 -0
  21. package/dist/accounts/account-manager-core.d.ts.map +1 -0
  22. package/dist/accounts/account-manager-core.js +203 -0
  23. package/dist/accounts/account-manager-core.js.map +1 -0
  24. package/dist/accounts/browser-host.d.ts +8 -0
  25. package/dist/accounts/browser-host.d.ts.map +1 -0
  26. package/dist/accounts/browser-host.js +16 -0
  27. package/dist/accounts/browser-host.js.map +1 -0
  28. package/dist/accounts/config-capability.d.ts +26 -0
  29. package/dist/accounts/config-capability.d.ts.map +1 -0
  30. package/dist/accounts/config-capability.js +58 -0
  31. package/dist/accounts/config-capability.js.map +1 -0
  32. package/dist/accounts/context.d.ts +14 -0
  33. package/dist/accounts/context.d.ts.map +1 -0
  34. package/dist/accounts/context.js +214 -0
  35. package/dist/accounts/context.js.map +1 -0
  36. package/dist/accounts/create-account-manager.d.ts +52 -0
  37. package/dist/accounts/create-account-manager.d.ts.map +1 -0
  38. package/dist/accounts/create-account-manager.js +17 -0
  39. package/dist/accounts/create-account-manager.js.map +1 -0
  40. package/dist/accounts/enrollment.d.ts +87 -0
  41. package/dist/accounts/enrollment.d.ts.map +1 -0
  42. package/dist/accounts/enrollment.js +312 -0
  43. package/dist/accounts/enrollment.js.map +1 -0
  44. package/dist/accounts/exports.d.ts +3 -0
  45. package/dist/accounts/exports.d.ts.map +1 -0
  46. package/dist/accounts/exports.js +5 -0
  47. package/dist/accounts/exports.js.map +1 -0
  48. package/dist/accounts/local-first.d.ts +14 -0
  49. package/dist/accounts/local-first.d.ts.map +1 -0
  50. package/dist/accounts/local-first.js +62 -0
  51. package/dist/accounts/local-first.js.map +1 -0
  52. package/dist/accounts/persistence.d.ts +42 -0
  53. package/dist/accounts/persistence.d.ts.map +1 -0
  54. package/dist/accounts/persistence.js +311 -0
  55. package/dist/accounts/persistence.js.map +1 -0
  56. package/dist/accounts/registry-client.d.ts +70 -0
  57. package/dist/accounts/registry-client.d.ts.map +1 -0
  58. package/dist/accounts/registry-client.js +142 -0
  59. package/dist/accounts/registry-client.js.map +1 -0
  60. package/dist/accounts/state.d.ts +76 -0
  61. package/dist/accounts/state.d.ts.map +1 -0
  62. package/dist/accounts/state.js +172 -0
  63. package/dist/accounts/state.js.map +1 -0
  64. package/dist/backend/admission.d.ts +18 -0
  65. package/dist/backend/admission.d.ts.map +1 -0
  66. package/dist/backend/admission.js +139 -0
  67. package/dist/backend/admission.js.map +1 -0
  68. package/dist/backend/backend-clients.d.ts +76 -0
  69. package/dist/backend/backend-clients.d.ts.map +1 -0
  70. package/dist/backend/backend-clients.js +237 -0
  71. package/dist/backend/backend-clients.js.map +1 -0
  72. package/dist/backend/backend-issuer.d.ts +6 -0
  73. package/dist/backend/backend-issuer.d.ts.map +1 -0
  74. package/dist/backend/backend-issuer.js +6 -0
  75. package/dist/backend/backend-issuer.js.map +1 -0
  76. package/dist/backend/blobs.d.ts +121 -0
  77. package/dist/backend/blobs.d.ts.map +1 -0
  78. package/dist/backend/blobs.js +123 -0
  79. package/dist/backend/blobs.js.map +1 -0
  80. package/dist/backend/create-jazz-context.d.ts +116 -0
  81. package/dist/backend/create-jazz-context.d.ts.map +1 -0
  82. package/dist/backend/create-jazz-context.js +607 -0
  83. package/dist/backend/create-jazz-context.js.map +1 -0
  84. package/dist/backend/create-jazz-session.d.ts +107 -0
  85. package/dist/backend/create-jazz-session.d.ts.map +1 -0
  86. package/dist/backend/create-jazz-session.js +505 -0
  87. package/dist/backend/create-jazz-session.js.map +1 -0
  88. package/dist/backend/create-jazz.d.ts +493 -0
  89. package/dist/backend/create-jazz.d.ts.map +1 -0
  90. package/dist/backend/create-jazz.js +3026 -0
  91. package/dist/backend/create-jazz.js.map +1 -0
  92. package/dist/backend/early-db.d.ts +29 -0
  93. package/dist/backend/early-db.d.ts.map +1 -0
  94. package/dist/backend/early-db.js +203 -0
  95. package/dist/backend/early-db.js.map +1 -0
  96. package/dist/backend/external-jwt.d.ts +27 -0
  97. package/dist/backend/external-jwt.d.ts.map +1 -0
  98. package/dist/backend/external-jwt.js +380 -0
  99. package/dist/backend/external-jwt.js.map +1 -0
  100. package/dist/backend/from-jwt.d.ts +62 -0
  101. package/dist/backend/from-jwt.d.ts.map +1 -0
  102. package/dist/backend/from-jwt.js +102 -0
  103. package/dist/backend/from-jwt.js.map +1 -0
  104. package/dist/backend/index.d.ts +12 -1
  105. package/dist/backend/index.d.ts.map +1 -1
  106. package/dist/backend/index.js +10 -1
  107. package/dist/backend/index.js.map +1 -1
  108. package/dist/backend/inspect-ui.d.ts +14 -0
  109. package/dist/backend/inspect-ui.d.ts.map +1 -0
  110. package/dist/backend/inspect-ui.js +156 -0
  111. package/dist/backend/inspect-ui.js.map +1 -0
  112. package/dist/backend/inspect.d.ts +129 -0
  113. package/dist/backend/inspect.d.ts.map +1 -0
  114. package/dist/backend/inspect.js +763 -0
  115. package/dist/backend/inspect.js.map +1 -0
  116. package/dist/backend/inspector-ui/0.js +2 -0
  117. package/dist/backend/inspector-ui/1.js +2 -0
  118. package/dist/backend/inspector-ui/10.js +2 -0
  119. package/dist/backend/inspector-ui/11.js +2 -0
  120. package/dist/backend/inspector-ui/12.js +2 -0
  121. package/dist/backend/inspector-ui/13.js +2 -0
  122. package/dist/backend/inspector-ui/14.js +2 -0
  123. package/dist/backend/inspector-ui/15.js +2 -0
  124. package/dist/backend/inspector-ui/16.js +2 -0
  125. package/dist/backend/inspector-ui/17.js +2 -0
  126. package/dist/backend/inspector-ui/18.js +2 -0
  127. package/dist/backend/inspector-ui/19.js +2 -0
  128. package/dist/backend/inspector-ui/2.js +2 -0
  129. package/dist/backend/inspector-ui/20.js +2 -0
  130. package/dist/backend/inspector-ui/3.js +2 -0
  131. package/dist/backend/inspector-ui/4.js +2 -0
  132. package/dist/backend/inspector-ui/5.js +2 -0
  133. package/dist/backend/inspector-ui/6.js +2 -0
  134. package/dist/backend/inspector-ui/7.js +2 -0
  135. package/dist/backend/inspector-ui/8.js +2 -0
  136. package/dist/backend/inspector-ui/9.js +2 -0
  137. package/dist/backend/inspector-ui-files.d.ts +4 -0
  138. package/dist/backend/inspector-ui-files.d.ts.map +1 -0
  139. package/dist/backend/inspector-ui-files.js +25 -0
  140. package/dist/backend/no-account-error.d.ts +23 -0
  141. package/dist/backend/no-account-error.d.ts.map +1 -0
  142. package/dist/backend/no-account-error.js +30 -0
  143. package/dist/backend/no-account-error.js.map +1 -0
  144. package/dist/backend/optional-peer.d.ts +9 -0
  145. package/dist/backend/optional-peer.d.ts.map +1 -0
  146. package/dist/backend/optional-peer.js +24 -0
  147. package/dist/backend/optional-peer.js.map +1 -0
  148. package/dist/backend/request-auth.d.ts +39 -0
  149. package/dist/backend/request-auth.d.ts.map +1 -0
  150. package/dist/backend/request-auth.js +77 -0
  151. package/dist/backend/request-auth.js.map +1 -0
  152. package/dist/backend/session-expiry.d.ts +61 -0
  153. package/dist/backend/session-expiry.d.ts.map +1 -0
  154. package/dist/backend/session-expiry.js +102 -0
  155. package/dist/backend/session-expiry.js.map +1 -0
  156. package/dist/backend/socket-deadline.d.ts +23 -0
  157. package/dist/backend/socket-deadline.d.ts.map +1 -0
  158. package/dist/backend/socket-deadline.js +70 -0
  159. package/dist/backend/socket-deadline.js.map +1 -0
  160. package/dist/backend/upgrade-status.d.ts +19 -0
  161. package/dist/backend/upgrade-status.d.ts.map +1 -0
  162. package/dist/backend/upgrade-status.js +55 -0
  163. package/dist/backend/upgrade-status.js.map +1 -0
  164. package/dist/backend/vercel-sockets.d.ts +16 -0
  165. package/dist/backend/vercel-sockets.d.ts.map +1 -0
  166. package/dist/backend/vercel-sockets.js +24 -0
  167. package/dist/backend/vercel-sockets.js.map +1 -0
  168. package/dist/backend/vercel-store.d.ts +223 -0
  169. package/dist/backend/vercel-store.d.ts.map +1 -0
  170. package/dist/backend/vercel-store.js +999 -0
  171. package/dist/backend/vercel-store.js.map +1 -0
  172. package/dist/better-auth-adapter/fixtures/permissions.d.ts +2 -0
  173. package/dist/better-auth-adapter/fixtures/permissions.d.ts.map +1 -0
  174. package/dist/better-auth-adapter/fixtures/permissions.js +2 -0
  175. package/dist/better-auth-adapter/fixtures/permissions.js.map +1 -0
  176. package/dist/better-auth-adapter/fixtures/schema.d.ts +69 -0
  177. package/dist/better-auth-adapter/fixtures/schema.d.ts.map +1 -0
  178. package/dist/better-auth-adapter/fixtures/schema.js +84 -0
  179. package/dist/better-auth-adapter/fixtures/schema.js.map +1 -0
  180. package/dist/better-auth-adapter/index.d.ts +13 -0
  181. package/dist/better-auth-adapter/index.d.ts.map +1 -0
  182. package/dist/better-auth-adapter/index.js +366 -0
  183. package/dist/better-auth-adapter/index.js.map +1 -0
  184. package/dist/better-auth-adapter/indexes.d.ts +9 -0
  185. package/dist/better-auth-adapter/indexes.d.ts.map +1 -0
  186. package/dist/better-auth-adapter/indexes.js +40 -0
  187. package/dist/better-auth-adapter/indexes.js.map +1 -0
  188. package/dist/better-auth-adapter/schema.d.ts +49 -0
  189. package/dist/better-auth-adapter/schema.d.ts.map +1 -0
  190. package/dist/better-auth-adapter/schema.js +300 -0
  191. package/dist/better-auth-adapter/schema.js.map +1 -0
  192. package/dist/better-auth-adapter/types.d.ts +13 -0
  193. package/dist/better-auth-adapter/types.d.ts.map +1 -0
  194. package/dist/better-auth-adapter/types.js +2 -0
  195. package/dist/better-auth-adapter/types.js.map +1 -0
  196. package/dist/better-auth-adapter/utils.d.ts +27 -0
  197. package/dist/better-auth-adapter/utils.d.ts.map +1 -0
  198. package/dist/better-auth-adapter/utils.js +189 -0
  199. package/dist/better-auth-adapter/utils.js.map +1 -0
  200. package/dist/browser-benchmark-mode.d.ts +6 -0
  201. package/dist/browser-benchmark-mode.d.ts.map +1 -0
  202. package/dist/browser-benchmark-mode.js +13 -0
  203. package/dist/browser-benchmark-mode.js.map +1 -0
  204. package/dist/classic-api.d.ts +59 -0
  205. package/dist/classic-api.d.ts.map +1 -0
  206. package/dist/classic-api.js +122 -0
  207. package/dist/classic-api.js.map +1 -0
  208. package/dist/cli.d.ts +29 -2
  209. package/dist/cli.d.ts.map +1 -1
  210. package/dist/cli.js +385 -267
  211. package/dist/cli.js.map +1 -1
  212. package/dist/client/index.d.ts +10 -0
  213. package/dist/client/index.d.ts.map +1 -0
  214. package/dist/client/index.js +7 -0
  215. package/dist/client/index.js.map +1 -0
  216. package/dist/cloud/api.d.ts +11 -0
  217. package/dist/cloud/api.d.ts.map +1 -0
  218. package/dist/cloud/api.js +46 -0
  219. package/dist/cloud/api.js.map +1 -0
  220. package/dist/cloud/commands.d.ts +13 -0
  221. package/dist/cloud/commands.d.ts.map +1 -0
  222. package/dist/cloud/commands.js +413 -0
  223. package/dist/cloud/commands.js.map +1 -0
  224. package/dist/cloud/credentials.d.ts +49 -0
  225. package/dist/cloud/credentials.d.ts.map +1 -0
  226. package/dist/cloud/credentials.js +219 -0
  227. package/dist/cloud/credentials.js.map +1 -0
  228. package/dist/cloud/session.d.ts +57 -0
  229. package/dist/cloud/session.d.ts.map +1 -0
  230. package/dist/cloud/session.js +269 -0
  231. package/dist/cloud/session.js.map +1 -0
  232. package/dist/codegen/relation-analyzer.d.ts +5 -12
  233. package/dist/codegen/relation-analyzer.d.ts.map +1 -1
  234. package/dist/codegen/relation-analyzer.js +54 -65
  235. package/dist/codegen/relation-analyzer.js.map +1 -1
  236. package/dist/codegen/schema-reader.d.ts +6 -2
  237. package/dist/codegen/schema-reader.d.ts.map +1 -1
  238. package/dist/codegen/schema-reader.js +129 -98
  239. package/dist/codegen/schema-reader.js.map +1 -1
  240. package/dist/dev/catalogue-api.d.ts +157 -0
  241. package/dist/dev/catalogue-api.d.ts.map +1 -0
  242. package/dist/dev/catalogue-api.js +145 -0
  243. package/dist/dev/catalogue-api.js.map +1 -0
  244. package/dist/dev/catalogue-project.d.ts +150 -0
  245. package/dist/dev/catalogue-project.d.ts.map +1 -0
  246. package/dist/dev/catalogue-project.js +1466 -0
  247. package/dist/dev/catalogue-project.js.map +1 -0
  248. package/dist/dev/catalogue.d.ts +84 -0
  249. package/dist/dev/catalogue.d.ts.map +1 -0
  250. package/dist/dev/catalogue.js +310 -0
  251. package/dist/dev/catalogue.js.map +1 -0
  252. package/dist/dev/dev-server.d.ts +57 -0
  253. package/dist/dev/dev-server.d.ts.map +1 -0
  254. package/dist/dev/dev-server.js +122 -0
  255. package/dist/dev/dev-server.js.map +1 -0
  256. package/dist/dev/index.d.ts +3 -0
  257. package/dist/dev/index.d.ts.map +1 -0
  258. package/dist/dev/index.js +3 -0
  259. package/dist/dev/index.js.map +1 -0
  260. package/dist/dev/inspector-overlay/browser-control-registry.d.ts +10 -0
  261. package/dist/dev/inspector-overlay/browser-control-registry.d.ts.map +1 -0
  262. package/dist/dev/inspector-overlay/browser-control-registry.js +188 -0
  263. package/dist/dev/inspector-overlay/browser-control-registry.js.map +1 -0
  264. package/dist/dev/inspector-overlay/embedded/assets/backend-DHeT1LCS.css +1 -0
  265. package/dist/dev/inspector-overlay/embedded/assets/backend-Dt5FYVfX.js +1 -0
  266. package/dist/dev/inspector-overlay/embedded/assets/create-legacy-browser-delegate-Bf58kV5i.js +1 -0
  267. package/dist/dev/inspector-overlay/embedded/assets/esm-BQhYkCKN.js +1 -0
  268. package/dist/dev/inspector-overlay/embedded/assets/esm-CI6IodCN.js +1 -0
  269. package/dist/dev/inspector-overlay/embedded/assets/esm-D5aLlEYl.js +1 -0
  270. package/dist/dev/inspector-overlay/embedded/assets/esm-D_R-EGgt.js +1 -0
  271. package/dist/dev/inspector-overlay/embedded/assets/esm-WihpI9g6.js +1 -0
  272. package/dist/dev/inspector-overlay/embedded/assets/esm-xNe3wI_B.js +1 -0
  273. package/dist/dev/inspector-overlay/embedded/assets/index-CjhxdwQ7.js +1 -0
  274. package/dist/dev/inspector-overlay/embedded/assets/jazz-broker-worker-CaVlHITU.js +3 -0
  275. package/dist/dev/inspector-overlay/embedded/assets/jazz-broker-worker-D-HQuhdu.js +23600 -0
  276. package/dist/dev/inspector-overlay/embedded/assets/jazz_wasm-t1Mm3faf.js +1 -0
  277. package/dist/dev/inspector-overlay/embedded/assets/jazz_wasm_bg-BazWJnU4.wasm +0 -0
  278. package/dist/dev/inspector-overlay/embedded/assets/node-foreground-node-lease.browser-CH8w-D6S.js +1 -0
  279. package/dist/dev/inspector-overlay/embedded/assets/src-Cq8gSOLx.css +1 -0
  280. package/dist/dev/inspector-overlay/embedded/assets/src-Dg6641Mj.js +22 -0
  281. package/dist/dev/inspector-overlay/embedded/assets/trace-api-BctnwbUf.js +1 -0
  282. package/dist/dev/inspector-overlay/embedded/backend.html +16 -0
  283. package/dist/dev/inspector-overlay/embedded/embedded.html +14 -0
  284. package/dist/dev/inspector-overlay/embedded/favicon.ico +0 -0
  285. package/dist/dev/inspector-overlay/host-bridge.d.ts +8 -0
  286. package/dist/dev/inspector-overlay/host-bridge.d.ts.map +1 -0
  287. package/dist/dev/inspector-overlay/host-bridge.js +139 -0
  288. package/dist/dev/inspector-overlay/host-bridge.js.map +1 -0
  289. package/dist/dev/inspector-overlay/inspector-host-types.d.ts +35 -0
  290. package/dist/dev/inspector-overlay/inspector-host-types.d.ts.map +1 -0
  291. package/dist/dev/inspector-overlay/inspector-host-types.js +10 -0
  292. package/dist/dev/inspector-overlay/inspector-host-types.js.map +1 -0
  293. package/dist/dev/inspector-overlay/loader.d.ts +24 -0
  294. package/dist/dev/inspector-overlay/loader.d.ts.map +1 -0
  295. package/dist/dev/inspector-overlay/loader.js +533 -0
  296. package/dist/dev/inspector-overlay/loader.js.map +1 -0
  297. package/dist/dev/legacy-schema-hash.d.ts +4 -0
  298. package/dist/dev/legacy-schema-hash.d.ts.map +1 -0
  299. package/dist/dev/legacy-schema-hash.js +12 -0
  300. package/dist/dev/legacy-schema-hash.js.map +1 -0
  301. package/dist/dev/migration-graph.d.ts +32 -0
  302. package/dist/dev/migration-graph.d.ts.map +1 -0
  303. package/dist/dev/migration-graph.js +136 -0
  304. package/dist/dev/migration-graph.js.map +1 -0
  305. package/dist/dev/migrations.d.ts +14 -0
  306. package/dist/dev/migrations.d.ts.map +1 -0
  307. package/dist/dev/migrations.js +441 -0
  308. package/dist/dev/migrations.js.map +1 -0
  309. package/dist/dev/schema-utils.d.ts +18 -0
  310. package/dist/dev/schema-utils.d.ts.map +1 -0
  311. package/dist/dev/schema-utils.js +365 -0
  312. package/dist/dev/schema-utils.js.map +1 -0
  313. package/dist/dev/schema-validation.d.ts +5 -0
  314. package/dist/dev/schema-validation.d.ts.map +1 -0
  315. package/dist/dev/schema-validation.js +11 -0
  316. package/dist/dev/schema-validation.js.map +1 -0
  317. package/dist/drivers/index.d.ts +1 -1
  318. package/dist/drivers/index.d.ts.map +1 -1
  319. package/dist/drivers/index.js.map +1 -1
  320. package/dist/drivers/schema-wire.d.ts +22 -0
  321. package/dist/drivers/schema-wire.d.ts.map +1 -0
  322. package/dist/drivers/schema-wire.js +70 -0
  323. package/dist/drivers/schema-wire.js.map +1 -0
  324. package/dist/drivers/types.d.ts +322 -45
  325. package/dist/drivers/types.d.ts.map +1 -1
  326. package/dist/drivers/types.js +5 -4
  327. package/dist/drivers/types.js.map +1 -1
  328. package/dist/dsl.d.ts +291 -101
  329. package/dist/dsl.d.ts.map +1 -1
  330. package/dist/dsl.js +244 -113
  331. package/dist/dsl.js.map +1 -1
  332. package/dist/e2ee/SODIUM-LICENSE.txt +36 -0
  333. package/dist/e2ee/SODIUM-SOURCES.json +4 -0
  334. package/dist/e2ee/browser.d.ts +18 -0
  335. package/dist/e2ee/browser.d.ts.map +1 -0
  336. package/dist/e2ee/browser.js +111 -0
  337. package/dist/e2ee/browser.js.map +1 -0
  338. package/dist/e2ee/context.d.ts +23 -0
  339. package/dist/e2ee/context.d.ts.map +1 -0
  340. package/dist/e2ee/context.js +49 -0
  341. package/dist/e2ee/context.js.map +1 -0
  342. package/dist/e2ee/crypto.d.ts +10 -0
  343. package/dist/e2ee/crypto.d.ts.map +1 -0
  344. package/dist/e2ee/crypto.js +22 -0
  345. package/dist/e2ee/crypto.js.map +1 -0
  346. package/dist/e2ee/envelope.d.ts +22 -0
  347. package/dist/e2ee/envelope.d.ts.map +1 -0
  348. package/dist/e2ee/envelope.js +52 -0
  349. package/dist/e2ee/envelope.js.map +1 -0
  350. package/dist/e2ee/index.d.ts +14 -0
  351. package/dist/e2ee/index.d.ts.map +1 -0
  352. package/dist/e2ee/index.js +3 -0
  353. package/dist/e2ee/index.js.map +1 -0
  354. package/dist/e2ee/large-value.d.ts +20 -0
  355. package/dist/e2ee/large-value.d.ts.map +1 -0
  356. package/dist/e2ee/large-value.js +204 -0
  357. package/dist/e2ee/large-value.js.map +1 -0
  358. package/dist/e2ee/native.d.ts +18 -0
  359. package/dist/e2ee/native.d.ts.map +1 -0
  360. package/dist/e2ee/native.js +91 -0
  361. package/dist/e2ee/native.js.map +1 -0
  362. package/dist/e2ee/record-frame.d.ts +3 -0
  363. package/dist/e2ee/record-frame.d.ts.map +1 -0
  364. package/dist/e2ee/record-frame.js +18 -0
  365. package/dist/e2ee/record-frame.js.map +1 -0
  366. package/dist/e2ee/signer.d.ts +10 -0
  367. package/dist/e2ee/signer.d.ts.map +1 -0
  368. package/dist/e2ee/signer.js +54 -0
  369. package/dist/e2ee/signer.js.map +1 -0
  370. package/dist/e2ee/sodium-browser.d.ts +2 -0
  371. package/dist/e2ee/sodium-browser.d.ts.map +1 -0
  372. package/dist/e2ee/sodium-browser.js +3432 -0
  373. package/dist/e2ee/sodium.d.ts +20 -0
  374. package/dist/e2ee/sodium.d.ts.map +1 -0
  375. package/dist/e2ee/sodium.js +165 -0
  376. package/dist/e2ee/sodium.js.map +1 -0
  377. package/dist/e2ee/types.d.ts +92 -0
  378. package/dist/e2ee/types.d.ts.map +1 -0
  379. package/dist/e2ee/types.js +2 -0
  380. package/dist/e2ee/types.js.map +1 -0
  381. package/dist/effect/backend/index.d.ts +8 -0
  382. package/dist/effect/backend/index.d.ts.map +1 -0
  383. package/dist/effect/backend/index.js +8 -0
  384. package/dist/effect/backend/index.js.map +1 -0
  385. package/dist/effect/errors.d.ts +53 -0
  386. package/dist/effect/errors.d.ts.map +1 -0
  387. package/dist/effect/errors.js +61 -0
  388. package/dist/effect/errors.js.map +1 -0
  389. package/dist/effect/index.d.ts +9 -0
  390. package/dist/effect/index.d.ts.map +1 -0
  391. package/dist/effect/index.js +9 -0
  392. package/dist/effect/index.js.map +1 -0
  393. package/dist/effect/jazz-backend.d.ts +69 -0
  394. package/dist/effect/jazz-backend.d.ts.map +1 -0
  395. package/dist/effect/jazz-backend.js +92 -0
  396. package/dist/effect/jazz-backend.js.map +1 -0
  397. package/dist/effect/jazz.d.ts +129 -0
  398. package/dist/effect/jazz.d.ts.map +1 -0
  399. package/dist/effect/jazz.js +182 -0
  400. package/dist/effect/jazz.js.map +1 -0
  401. package/dist/expo/create-account-manager.d.ts +28 -0
  402. package/dist/expo/create-account-manager.d.ts.map +1 -0
  403. package/dist/expo/create-account-manager.js +35 -0
  404. package/dist/expo/create-account-manager.js.map +1 -0
  405. package/dist/expo/create-jazz-session.d.ts +55 -0
  406. package/dist/expo/create-jazz-session.d.ts.map +1 -0
  407. package/dist/expo/create-jazz-session.js +78 -0
  408. package/dist/expo/create-jazz-session.js.map +1 -0
  409. package/dist/expo/index.d.ts +13 -0
  410. package/dist/expo/index.d.ts.map +1 -0
  411. package/dist/expo/index.js +12 -0
  412. package/dist/expo/index.js.map +1 -0
  413. package/dist/expo/polyfills.d.ts +2 -0
  414. package/dist/expo/polyfills.d.ts.map +1 -0
  415. package/dist/expo/polyfills.js +5 -0
  416. package/dist/expo/polyfills.js.map +1 -0
  417. package/dist/expo/provider.d.ts +10 -0
  418. package/dist/expo/provider.d.ts.map +1 -0
  419. package/dist/expo/provider.js +11 -0
  420. package/dist/expo/provider.js.map +1 -0
  421. package/dist/index.d.ts +24 -7
  422. package/dist/index.d.ts.map +1 -1
  423. package/dist/index.js +20 -8
  424. package/dist/index.js.map +1 -1
  425. package/dist/inspect/cli.d.ts +12 -0
  426. package/dist/inspect/cli.d.ts.map +1 -0
  427. package/dist/inspect/cli.js +292 -0
  428. package/dist/inspect/cli.js.map +1 -0
  429. package/dist/inspect/client.d.ts +60 -0
  430. package/dist/inspect/client.d.ts.map +1 -0
  431. package/dist/inspect/client.js +241 -0
  432. package/dist/inspect/client.js.map +1 -0
  433. package/dist/inspect/mcp.d.ts +17 -0
  434. package/dist/inspect/mcp.d.ts.map +1 -0
  435. package/dist/inspect/mcp.js +308 -0
  436. package/dist/inspect/mcp.js.map +1 -0
  437. package/dist/inspect/protocol.d.ts +218 -0
  438. package/dist/inspect/protocol.d.ts.map +1 -0
  439. package/dist/inspect/protocol.js +357 -0
  440. package/dist/inspect/protocol.js.map +1 -0
  441. package/dist/inspector/index.d.ts +10 -0
  442. package/dist/inspector/index.d.ts.map +1 -0
  443. package/dist/inspector/index.js +27 -0
  444. package/dist/inspector/index.js.map +1 -0
  445. package/dist/internal/inspector-query.d.ts +6 -0
  446. package/dist/internal/inspector-query.d.ts.map +1 -0
  447. package/dist/internal/inspector-query.js +20 -0
  448. package/dist/internal/inspector-query.js.map +1 -0
  449. package/dist/ir.d.ts +139 -115
  450. package/dist/ir.d.ts.map +1 -1
  451. package/dist/ir.js +496 -1
  452. package/dist/ir.js.map +1 -1
  453. package/dist/local-first/index.d.ts +16 -0
  454. package/dist/local-first/index.d.ts.map +1 -0
  455. package/dist/local-first/index.js +15 -0
  456. package/dist/local-first/index.js.map +1 -0
  457. package/dist/local-first-auth/browser.d.ts +18 -0
  458. package/dist/local-first-auth/browser.d.ts.map +1 -0
  459. package/dist/local-first-auth/browser.js +26 -0
  460. package/dist/local-first-auth/browser.js.map +1 -0
  461. package/dist/local-first-auth/encoding.d.ts +10 -0
  462. package/dist/local-first-auth/encoding.d.ts.map +1 -0
  463. package/dist/local-first-auth/encoding.js +38 -0
  464. package/dist/local-first-auth/encoding.js.map +1 -0
  465. package/dist/local-first-auth/identity.d.ts +73 -0
  466. package/dist/local-first-auth/identity.d.ts.map +1 -0
  467. package/dist/local-first-auth/identity.js +258 -0
  468. package/dist/local-first-auth/identity.js.map +1 -0
  469. package/dist/local-first-auth/index.d.ts +6 -0
  470. package/dist/local-first-auth/index.d.ts.map +1 -0
  471. package/dist/local-first-auth/index.js +4 -0
  472. package/dist/local-first-auth/index.js.map +1 -0
  473. package/dist/local-first-auth/passkey.d.ts +22 -0
  474. package/dist/local-first-auth/passkey.d.ts.map +1 -0
  475. package/dist/local-first-auth/passkey.js +116 -0
  476. package/dist/local-first-auth/passkey.js.map +1 -0
  477. package/dist/local-first-auth/recovery-phrase.d.ts +10 -0
  478. package/dist/local-first-auth/recovery-phrase.d.ts.map +1 -0
  479. package/dist/local-first-auth/recovery-phrase.js +59 -0
  480. package/dist/local-first-auth/recovery-phrase.js.map +1 -0
  481. package/dist/local-first-auth/secret.d.ts +25 -0
  482. package/dist/local-first-auth/secret.d.ts.map +1 -0
  483. package/dist/local-first-auth/secret.js +68 -0
  484. package/dist/local-first-auth/secret.js.map +1 -0
  485. package/dist/local-first-auth/server.d.ts +13 -0
  486. package/dist/local-first-auth/server.d.ts.map +1 -0
  487. package/dist/local-first-auth/server.js +32 -0
  488. package/dist/local-first-auth/server.js.map +1 -0
  489. package/dist/local-first-auth/store.d.ts +51 -0
  490. package/dist/local-first-auth/store.d.ts.map +1 -0
  491. package/dist/local-first-auth/store.js +112 -0
  492. package/dist/local-first-auth/store.js.map +1 -0
  493. package/dist/magic-columns.d.ts +34 -0
  494. package/dist/magic-columns.d.ts.map +1 -0
  495. package/dist/magic-columns.js +86 -0
  496. package/dist/magic-columns.js.map +1 -0
  497. package/dist/migration-namespace.d.ts +8 -0
  498. package/dist/migration-namespace.d.ts.map +1 -0
  499. package/dist/migration-namespace.js +9 -0
  500. package/dist/migration-namespace.js.map +1 -0
  501. package/dist/migrations.d.ts +229 -0
  502. package/dist/migrations.d.ts.map +1 -0
  503. package/dist/migrations.js +383 -0
  504. package/dist/migrations.js.map +1 -0
  505. package/dist/observed-jazz-client.d.ts +15 -0
  506. package/dist/observed-jazz-client.d.ts.map +1 -0
  507. package/dist/observed-jazz-client.js +38 -0
  508. package/dist/observed-jazz-client.js.map +1 -0
  509. package/dist/passkey-backup.d.ts +3 -0
  510. package/dist/passkey-backup.d.ts.map +1 -0
  511. package/dist/passkey-backup.js +2 -0
  512. package/dist/passkey-backup.js.map +1 -0
  513. package/dist/passphrase.d.ts +2 -0
  514. package/dist/passphrase.d.ts.map +1 -0
  515. package/dist/passphrase.js +2 -0
  516. package/dist/passphrase.js.map +1 -0
  517. package/dist/permissions/index.d.ts +149 -41
  518. package/dist/permissions/index.d.ts.map +1 -1
  519. package/dist/permissions/index.js +1209 -423
  520. package/dist/permissions/index.js.map +1 -1
  521. package/dist/policy-expr-map.d.ts +15 -0
  522. package/dist/policy-expr-map.d.ts.map +1 -0
  523. package/dist/policy-expr-map.js +45 -0
  524. package/dist/policy-expr-map.js.map +1 -0
  525. package/dist/prosemirror/anchors.d.ts +30 -0
  526. package/dist/prosemirror/anchors.d.ts.map +1 -0
  527. package/dist/prosemirror/anchors.js +28 -0
  528. package/dist/prosemirror/anchors.js.map +1 -0
  529. package/dist/prosemirror/index.d.ts +7 -0
  530. package/dist/prosemirror/index.d.ts.map +1 -0
  531. package/dist/prosemirror/index.js +7 -0
  532. package/dist/prosemirror/index.js.map +1 -0
  533. package/dist/prosemirror/markdown.d.ts +95 -0
  534. package/dist/prosemirror/markdown.d.ts.map +1 -0
  535. package/dist/prosemirror/markdown.js +428 -0
  536. package/dist/prosemirror/markdown.js.map +1 -0
  537. package/dist/prosemirror/overlays.d.ts +69 -0
  538. package/dist/prosemirror/overlays.d.ts.map +1 -0
  539. package/dist/prosemirror/overlays.js +143 -0
  540. package/dist/prosemirror/overlays.js.map +1 -0
  541. package/dist/prosemirror/presence.d.ts +39 -0
  542. package/dist/prosemirror/presence.d.ts.map +1 -0
  543. package/dist/prosemirror/presence.js +88 -0
  544. package/dist/prosemirror/presence.js.map +1 -0
  545. package/dist/prosemirror/sync.d.ts +60 -0
  546. package/dist/prosemirror/sync.d.ts.map +1 -0
  547. package/dist/prosemirror/sync.js +174 -0
  548. package/dist/prosemirror/sync.js.map +1 -0
  549. package/dist/prosemirror/text-map.d.ts +21 -0
  550. package/dist/prosemirror/text-map.d.ts.map +1 -0
  551. package/dist/prosemirror/text-map.js +85 -0
  552. package/dist/prosemirror/text-map.js.map +1 -0
  553. package/dist/provenance-guidance.d.ts +3 -0
  554. package/dist/provenance-guidance.d.ts.map +1 -0
  555. package/dist/provenance-guidance.js +19 -0
  556. package/dist/provenance-guidance.js.map +1 -0
  557. package/dist/react/create-jazz-client.d.ts +2 -10
  558. package/dist/react/create-jazz-client.d.ts.map +1 -1
  559. package/dist/react/create-jazz-client.js +1 -25
  560. package/dist/react/create-jazz-client.js.map +1 -1
  561. package/dist/react/index.d.ts +15 -6
  562. package/dist/react/index.d.ts.map +1 -1
  563. package/dist/react/index.js +10 -5
  564. package/dist/react/index.js.map +1 -1
  565. package/dist/react/provider-props.d.ts +7 -0
  566. package/dist/react/provider-props.d.ts.map +1 -0
  567. package/dist/react/provider-props.js +15 -0
  568. package/dist/react/provider-props.js.map +1 -0
  569. package/dist/react/provider.d.ts +19 -13
  570. package/dist/react/provider.d.ts.map +1 -1
  571. package/dist/react/provider.js +25 -4
  572. package/dist/react/provider.js.map +1 -1
  573. package/dist/react/use-all.d.ts +1 -1
  574. package/dist/react/use-all.d.ts.map +1 -1
  575. package/dist/react/use-all.js +1 -1
  576. package/dist/react/use-all.js.map +1 -1
  577. package/dist/react/use-one.d.ts +2 -0
  578. package/dist/react/use-one.d.ts.map +1 -0
  579. package/dist/react/use-one.js +2 -0
  580. package/dist/react/use-one.js.map +1 -0
  581. package/dist/react-core/index.d.ts +10 -4
  582. package/dist/react-core/index.d.ts.map +1 -1
  583. package/dist/react-core/index.js +12 -2
  584. package/dist/react-core/index.js.map +1 -1
  585. package/dist/react-core/provider.d.ts +44 -12
  586. package/dist/react-core/provider.d.ts.map +1 -1
  587. package/dist/react-core/provider.js +110 -11
  588. package/dist/react-core/provider.js.map +1 -1
  589. package/dist/react-core/session.d.ts +53 -0
  590. package/dist/react-core/session.d.ts.map +1 -0
  591. package/dist/react-core/session.js +82 -0
  592. package/dist/react-core/session.js.map +1 -0
  593. package/dist/react-core/use-all.d.ts +95 -3
  594. package/dist/react-core/use-all.d.ts.map +1 -1
  595. package/dist/react-core/use-all.js +126 -52
  596. package/dist/react-core/use-all.js.map +1 -1
  597. package/dist/react-core/use-auth-state.d.ts +13 -0
  598. package/dist/react-core/use-auth-state.d.ts.map +1 -0
  599. package/dist/react-core/use-auth-state.js +15 -0
  600. package/dist/react-core/use-auth-state.js.map +1 -0
  601. package/dist/react-core/use-one.d.ts +58 -0
  602. package/dist/react-core/use-one.d.ts.map +1 -0
  603. package/dist/react-core/use-one.js +19 -0
  604. package/dist/react-core/use-one.js.map +1 -0
  605. package/dist/react-core/use-sync-status.d.ts +8 -0
  606. package/dist/react-core/use-sync-status.d.ts.map +1 -0
  607. package/dist/react-core/use-sync-status.js +12 -0
  608. package/dist/react-core/use-sync-status.js.map +1 -0
  609. package/dist/react-native/abort-signal.d.ts +9 -0
  610. package/dist/react-native/abort-signal.d.ts.map +1 -0
  611. package/dist/react-native/abort-signal.js +51 -0
  612. package/dist/react-native/abort-signal.js.map +1 -0
  613. package/dist/react-native/account-session.d.ts +11 -0
  614. package/dist/react-native/account-session.d.ts.map +1 -0
  615. package/dist/react-native/account-session.js +59 -0
  616. package/dist/react-native/account-session.js.map +1 -0
  617. package/dist/react-native/create-account-manager.d.ts +28 -0
  618. package/dist/react-native/create-account-manager.d.ts.map +1 -0
  619. package/dist/react-native/create-account-manager.js +30 -0
  620. package/dist/react-native/create-account-manager.js.map +1 -0
  621. package/dist/react-native/create-db.d.ts +8 -0
  622. package/dist/react-native/create-db.d.ts.map +1 -0
  623. package/dist/react-native/create-db.js +9 -0
  624. package/dist/react-native/create-db.js.map +1 -0
  625. package/dist/react-native/create-jazz-client.d.ts +12 -10
  626. package/dist/react-native/create-jazz-client.d.ts.map +1 -1
  627. package/dist/react-native/create-jazz-client.js +6 -21
  628. package/dist/react-native/create-jazz-client.js.map +1 -1
  629. package/dist/react-native/create-jazz-session.d.ts +55 -0
  630. package/dist/react-native/create-jazz-session.d.ts.map +1 -0
  631. package/dist/react-native/create-jazz-session.js +78 -0
  632. package/dist/react-native/create-jazz-session.js.map +1 -0
  633. package/dist/react-native/errors.d.ts +6 -0
  634. package/dist/react-native/errors.d.ts.map +1 -0
  635. package/dist/react-native/errors.js +6 -0
  636. package/dist/react-native/errors.js.map +1 -0
  637. package/dist/react-native/index.d.ts +20 -9
  638. package/dist/react-native/index.d.ts.map +1 -1
  639. package/dist/react-native/index.js +15 -7
  640. package/dist/react-native/index.js.map +1 -1
  641. package/dist/react-native/native-foreground-db.d.ts +199 -0
  642. package/dist/react-native/native-foreground-db.d.ts.map +1 -0
  643. package/dist/react-native/native-foreground-db.js +830 -0
  644. package/dist/react-native/native-foreground-db.js.map +1 -0
  645. package/dist/react-native/native-relay.d.ts +7 -0
  646. package/dist/react-native/native-relay.d.ts.map +1 -0
  647. package/dist/react-native/native-relay.js +14 -0
  648. package/dist/react-native/native-relay.js.map +1 -0
  649. package/dist/react-native/provider.d.ts +20 -12
  650. package/dist/react-native/provider.d.ts.map +1 -1
  651. package/dist/react-native/provider.js +25 -4
  652. package/dist/react-native/provider.js.map +1 -1
  653. package/dist/react-native/runtime-source.d.ts +40 -0
  654. package/dist/react-native/runtime-source.d.ts.map +1 -0
  655. package/dist/react-native/runtime-source.js +250 -0
  656. package/dist/react-native/runtime-source.js.map +1 -0
  657. package/dist/react-native/use-all.d.ts +1 -1
  658. package/dist/react-native/use-all.d.ts.map +1 -1
  659. package/dist/react-native/use-all.js +1 -1
  660. package/dist/react-native/use-all.js.map +1 -1
  661. package/dist/react-native/use-one.d.ts +2 -0
  662. package/dist/react-native/use-one.d.ts.map +1 -0
  663. package/dist/react-native/use-one.js +2 -0
  664. package/dist/react-native/use-one.js.map +1 -0
  665. package/dist/reconcile-array.d.ts +45 -0
  666. package/dist/reconcile-array.d.ts.map +1 -0
  667. package/dist/reconcile-array.js +252 -0
  668. package/dist/reconcile-array.js.map +1 -0
  669. package/dist/relationships.d.ts +18 -0
  670. package/dist/relationships.d.ts.map +1 -0
  671. package/dist/relationships.js +28 -0
  672. package/dist/relationships.js.map +1 -0
  673. package/dist/removed-api.d.ts +87 -0
  674. package/dist/removed-api.d.ts.map +1 -0
  675. package/dist/removed-api.js +95 -0
  676. package/dist/removed-api.js.map +1 -0
  677. package/dist/runtime/anonymous-write-denied-error.d.ts +13 -0
  678. package/dist/runtime/anonymous-write-denied-error.d.ts.map +1 -0
  679. package/dist/runtime/anonymous-write-denied-error.js +58 -0
  680. package/dist/runtime/anonymous-write-denied-error.js.map +1 -0
  681. package/dist/runtime/auth-renewal-backoff.d.ts +14 -0
  682. package/dist/runtime/auth-renewal-backoff.d.ts.map +1 -0
  683. package/dist/runtime/auth-renewal-backoff.js +23 -0
  684. package/dist/runtime/auth-renewal-backoff.js.map +1 -0
  685. package/dist/runtime/auth-request-deadline.d.ts +3 -0
  686. package/dist/runtime/auth-request-deadline.d.ts.map +1 -0
  687. package/dist/runtime/auth-request-deadline.js +24 -0
  688. package/dist/runtime/auth-request-deadline.js.map +1 -0
  689. package/dist/runtime/auth-secret-codec.d.ts +21 -0
  690. package/dist/runtime/auth-secret-codec.d.ts.map +1 -0
  691. package/dist/runtime/auth-secret-codec.js +32 -0
  692. package/dist/runtime/auth-secret-codec.js.map +1 -0
  693. package/dist/runtime/auth-secret-store.d.ts +7 -0
  694. package/dist/runtime/auth-secret-store.d.ts.map +1 -0
  695. package/dist/runtime/auth-secret-store.js +12 -0
  696. package/dist/runtime/auth-secret-store.js.map +1 -0
  697. package/dist/runtime/auth-state.d.ts +40 -0
  698. package/dist/runtime/auth-state.d.ts.map +1 -0
  699. package/dist/runtime/auth-state.js +145 -0
  700. package/dist/runtime/auth-state.js.map +1 -0
  701. package/dist/runtime/author-id.d.ts +42 -0
  702. package/dist/runtime/author-id.d.ts.map +1 -0
  703. package/dist/runtime/author-id.js +172 -0
  704. package/dist/runtime/author-id.js.map +1 -0
  705. package/dist/runtime/authority-changed-error.d.ts +54 -0
  706. package/dist/runtime/authority-changed-error.d.ts.map +1 -0
  707. package/dist/runtime/authority-changed-error.js +72 -0
  708. package/dist/runtime/authority-changed-error.js.map +1 -0
  709. package/dist/runtime/browser-physical-database-epoch.d.ts +37 -0
  710. package/dist/runtime/browser-physical-database-epoch.d.ts.map +1 -0
  711. package/dist/runtime/browser-physical-database-epoch.js +89 -0
  712. package/dist/runtime/browser-physical-database-epoch.js.map +1 -0
  713. package/dist/runtime/browser-storage-invalidation.d.ts +8 -0
  714. package/dist/runtime/browser-storage-invalidation.d.ts.map +1 -0
  715. package/dist/runtime/browser-storage-invalidation.js +20 -0
  716. package/dist/runtime/browser-storage-invalidation.js.map +1 -0
  717. package/dist/runtime/browser-worker-assets.d.ts +4 -0
  718. package/dist/runtime/browser-worker-assets.d.ts.map +1 -0
  719. package/dist/runtime/browser-worker-assets.js +8 -0
  720. package/dist/runtime/browser-worker-assets.js.map +1 -0
  721. package/dist/runtime/browser-worker-assets.native.d.ts +5 -0
  722. package/dist/runtime/browser-worker-assets.native.d.ts.map +1 -0
  723. package/dist/runtime/browser-worker-assets.native.js +6 -0
  724. package/dist/runtime/browser-worker-assets.native.js.map +1 -0
  725. package/dist/runtime/browser-worker-config.d.ts +55 -0
  726. package/dist/runtime/browser-worker-config.d.ts.map +1 -0
  727. package/dist/runtime/browser-worker-config.js +222 -0
  728. package/dist/runtime/browser-worker-config.js.map +1 -0
  729. package/dist/runtime/client-config-key.d.ts +6 -0
  730. package/dist/runtime/client-config-key.d.ts.map +1 -0
  731. package/dist/runtime/client-config-key.js +83 -0
  732. package/dist/runtime/client-config-key.js.map +1 -0
  733. package/dist/runtime/client-migrations.d.ts +33 -0
  734. package/dist/runtime/client-migrations.d.ts.map +1 -0
  735. package/dist/runtime/client-migrations.js +30 -0
  736. package/dist/runtime/client-migrations.js.map +1 -0
  737. package/dist/runtime/client-registry.d.ts +21 -0
  738. package/dist/runtime/client-registry.d.ts.map +1 -0
  739. package/dist/runtime/client-registry.js +169 -0
  740. package/dist/runtime/client-registry.js.map +1 -0
  741. package/dist/runtime/client-scope.d.ts +38 -0
  742. package/dist/runtime/client-scope.d.ts.map +1 -0
  743. package/dist/runtime/client-scope.js +64 -0
  744. package/dist/runtime/client-scope.js.map +1 -0
  745. package/dist/runtime/client-session.d.ts +56 -13
  746. package/dist/runtime/client-session.d.ts.map +1 -1
  747. package/dist/runtime/client-session.js +212 -196
  748. package/dist/runtime/client-session.js.map +1 -1
  749. package/dist/runtime/client.d.ts +630 -191
  750. package/dist/runtime/client.d.ts.map +1 -1
  751. package/dist/runtime/client.js +1105 -425
  752. package/dist/runtime/client.js.map +1 -1
  753. package/dist/runtime/column-transforms.d.ts +40 -0
  754. package/dist/runtime/column-transforms.d.ts.map +1 -0
  755. package/dist/runtime/column-transforms.js +279 -0
  756. package/dist/runtime/column-transforms.js.map +1 -0
  757. package/dist/runtime/connection-manager/browser-connection-manager.d.ts +122 -0
  758. package/dist/runtime/connection-manager/browser-connection-manager.d.ts.map +1 -0
  759. package/dist/runtime/connection-manager/browser-connection-manager.js +867 -0
  760. package/dist/runtime/connection-manager/browser-connection-manager.js.map +1 -0
  761. package/dist/runtime/connection-manager/direct-connection-manager.d.ts +26 -0
  762. package/dist/runtime/connection-manager/direct-connection-manager.d.ts.map +1 -0
  763. package/dist/runtime/connection-manager/direct-connection-manager.js +198 -0
  764. package/dist/runtime/connection-manager/direct-connection-manager.js.map +1 -0
  765. package/dist/runtime/connection-manager/index.d.ts +5 -0
  766. package/dist/runtime/connection-manager/index.d.ts.map +1 -0
  767. package/dist/runtime/connection-manager/index.js +4 -0
  768. package/dist/runtime/connection-manager/index.js.map +1 -0
  769. package/dist/runtime/connection-manager/types.d.ts +151 -0
  770. package/dist/runtime/connection-manager/types.d.ts.map +1 -0
  771. package/dist/runtime/connection-manager/types.js +354 -0
  772. package/dist/runtime/connection-manager/types.js.map +1 -0
  773. package/dist/runtime/context.d.ts +90 -30
  774. package/dist/runtime/context.d.ts.map +1 -1
  775. package/dist/runtime/context.js.map +1 -1
  776. package/dist/runtime/credentialed-transport.d.ts +30 -0
  777. package/dist/runtime/credentialed-transport.d.ts.map +1 -0
  778. package/dist/runtime/credentialed-transport.js +164 -0
  779. package/dist/runtime/credentialed-transport.js.map +1 -0
  780. package/dist/runtime/db-access-context.d.ts +14 -0
  781. package/dist/runtime/db-access-context.d.ts.map +1 -0
  782. package/dist/runtime/db-access-context.js +26 -0
  783. package/dist/runtime/db-access-context.js.map +1 -0
  784. package/dist/runtime/db-internal-session.d.ts +7 -0
  785. package/dist/runtime/db-internal-session.d.ts.map +1 -0
  786. package/dist/runtime/db-internal-session.js +21 -0
  787. package/dist/runtime/db-internal-session.js.map +1 -0
  788. package/dist/runtime/db-replaced-error.d.ts +21 -0
  789. package/dist/runtime/db-replaced-error.d.ts.map +1 -0
  790. package/dist/runtime/db-replaced-error.js +22 -0
  791. package/dist/runtime/db-replaced-error.js.map +1 -0
  792. package/dist/runtime/db.d.ts +763 -201
  793. package/dist/runtime/db.d.ts.map +1 -1
  794. package/dist/runtime/db.js +3341 -725
  795. package/dist/runtime/db.js.map +1 -1
  796. package/dist/runtime/default-create-db.d.ts +5 -0
  797. package/dist/runtime/default-create-db.d.ts.map +1 -0
  798. package/dist/runtime/default-create-db.js +7 -0
  799. package/dist/runtime/default-create-db.js.map +1 -0
  800. package/dist/runtime/default-runtime-source.d.ts +41 -0
  801. package/dist/runtime/default-runtime-source.d.ts.map +1 -0
  802. package/dist/runtime/default-runtime-source.js +315 -0
  803. package/dist/runtime/default-runtime-source.js.map +1 -0
  804. package/dist/runtime/deterministic-bytes.d.ts +6 -0
  805. package/dist/runtime/deterministic-bytes.d.ts.map +1 -0
  806. package/dist/runtime/deterministic-bytes.js +18 -0
  807. package/dist/runtime/deterministic-bytes.js.map +1 -0
  808. package/dist/runtime/graceful-shutdown-error.d.ts +9 -0
  809. package/dist/runtime/graceful-shutdown-error.d.ts.map +1 -0
  810. package/dist/runtime/graceful-shutdown-error.js +17 -0
  811. package/dist/runtime/graceful-shutdown-error.js.map +1 -0
  812. package/dist/runtime/hex.d.ts +17 -0
  813. package/dist/runtime/hex.d.ts.map +1 -0
  814. package/dist/runtime/hex.js +56 -0
  815. package/dist/runtime/hex.js.map +1 -0
  816. package/dist/runtime/history-relation.d.ts +8 -0
  817. package/dist/runtime/history-relation.d.ts.map +1 -0
  818. package/dist/runtime/history-relation.js +44 -0
  819. package/dist/runtime/history-relation.js.map +1 -0
  820. package/dist/runtime/in-process-transport.d.ts +18 -0
  821. package/dist/runtime/in-process-transport.d.ts.map +1 -0
  822. package/dist/runtime/in-process-transport.js +32 -0
  823. package/dist/runtime/in-process-transport.js.map +1 -0
  824. package/dist/runtime/index.d.ts +21 -11
  825. package/dist/runtime/index.d.ts.map +1 -1
  826. package/dist/runtime/index.js +13 -10
  827. package/dist/runtime/index.js.map +1 -1
  828. package/dist/runtime/indexeddb-page-store.d.ts +214 -0
  829. package/dist/runtime/indexeddb-page-store.d.ts.map +1 -0
  830. package/dist/runtime/indexeddb-page-store.js +848 -0
  831. package/dist/runtime/indexeddb-page-store.js.map +1 -0
  832. package/dist/runtime/introspection-fetch.d.ts +18 -0
  833. package/dist/runtime/introspection-fetch.d.ts.map +1 -0
  834. package/dist/runtime/introspection-fetch.js +12 -0
  835. package/dist/runtime/introspection-fetch.js.map +1 -0
  836. package/dist/runtime/json-schema-evaluate.d.ts +55 -0
  837. package/dist/runtime/json-schema-evaluate.d.ts.map +1 -0
  838. package/dist/runtime/json-schema-evaluate.js +946 -0
  839. package/dist/runtime/json-schema-evaluate.js.map +1 -0
  840. package/dist/runtime/json-schema-formats.d.ts +14 -0
  841. package/dist/runtime/json-schema-formats.d.ts.map +1 -0
  842. package/dist/runtime/json-schema-formats.js +555 -0
  843. package/dist/runtime/json-schema-formats.js.map +1 -0
  844. package/dist/runtime/json-schema-json.d.ts +41 -0
  845. package/dist/runtime/json-schema-json.d.ts.map +1 -0
  846. package/dist/runtime/json-schema-json.js +309 -0
  847. package/dist/runtime/json-schema-json.js.map +1 -0
  848. package/dist/runtime/json-schema-metaschemas.d.ts +1403 -0
  849. package/dist/runtime/json-schema-metaschemas.d.ts.map +1 -0
  850. package/dist/runtime/json-schema-metaschemas.js +64 -0
  851. package/dist/runtime/json-schema-metaschemas.js.map +1 -0
  852. package/dist/runtime/json-schema-regex.d.ts +32 -0
  853. package/dist/runtime/json-schema-regex.d.ts.map +1 -0
  854. package/dist/runtime/json-schema-regex.js +895 -0
  855. package/dist/runtime/json-schema-regex.js.map +1 -0
  856. package/dist/runtime/json-schema-validator.d.ts +47 -0
  857. package/dist/runtime/json-schema-validator.d.ts.map +1 -0
  858. package/dist/runtime/json-schema-validator.js +404 -0
  859. package/dist/runtime/json-schema-validator.js.map +1 -0
  860. package/dist/runtime/json-text.d.ts +2 -0
  861. package/dist/runtime/json-text.d.ts.map +1 -0
  862. package/dist/runtime/json-text.js +17 -0
  863. package/dist/runtime/json-text.js.map +1 -0
  864. package/dist/runtime/local-first-token.d.ts +11 -0
  865. package/dist/runtime/local-first-token.d.ts.map +1 -0
  866. package/dist/runtime/local-first-token.js +20 -0
  867. package/dist/runtime/local-first-token.js.map +1 -0
  868. package/dist/runtime/local-first-upgrade.d.ts +27 -0
  869. package/dist/runtime/local-first-upgrade.d.ts.map +1 -0
  870. package/dist/runtime/local-first-upgrade.js +31 -0
  871. package/dist/runtime/local-first-upgrade.js.map +1 -0
  872. package/dist/runtime/local-write-observer.d.ts +5 -0
  873. package/dist/runtime/local-write-observer.d.ts.map +1 -0
  874. package/dist/runtime/local-write-observer.js +31 -0
  875. package/dist/runtime/local-write-observer.js.map +1 -0
  876. package/dist/runtime/native-artifact-compatibility.d.ts +12 -0
  877. package/dist/runtime/native-artifact-compatibility.d.ts.map +1 -0
  878. package/dist/runtime/native-artifact-compatibility.js +24 -0
  879. package/dist/runtime/native-artifact-compatibility.js.map +1 -0
  880. package/dist/runtime/native-artifact-fingerprint-napi.d.ts +2 -0
  881. package/dist/runtime/native-artifact-fingerprint-napi.d.ts.map +1 -0
  882. package/dist/runtime/native-artifact-fingerprint-napi.js +3 -0
  883. package/dist/runtime/native-artifact-fingerprint-napi.js.map +1 -0
  884. package/dist/runtime/native-artifact-fingerprint-wasm.d.ts +2 -0
  885. package/dist/runtime/native-artifact-fingerprint-wasm.d.ts.map +1 -0
  886. package/dist/runtime/native-artifact-fingerprint-wasm.js +3 -0
  887. package/dist/runtime/native-artifact-fingerprint-wasm.js.map +1 -0
  888. package/dist/runtime/native-artifact-fingerprints.d.ts +5 -0
  889. package/dist/runtime/native-artifact-fingerprints.d.ts.map +1 -0
  890. package/dist/runtime/native-artifact-fingerprints.js +7 -0
  891. package/dist/runtime/native-artifact-fingerprints.js.map +1 -0
  892. package/dist/runtime/native-runtime/attached-browser-worker-connection.d.ts +22 -0
  893. package/dist/runtime/native-runtime/attached-browser-worker-connection.d.ts.map +1 -0
  894. package/dist/runtime/native-runtime/attached-browser-worker-connection.js +42 -0
  895. package/dist/runtime/native-runtime/attached-browser-worker-connection.js.map +1 -0
  896. package/dist/runtime/native-runtime/auxiliary-receive-deadline.d.ts +15 -0
  897. package/dist/runtime/native-runtime/auxiliary-receive-deadline.d.ts.map +1 -0
  898. package/dist/runtime/native-runtime/auxiliary-receive-deadline.js +64 -0
  899. package/dist/runtime/native-runtime/auxiliary-receive-deadline.js.map +1 -0
  900. package/dist/runtime/native-runtime/broker-worker-load-failure.d.ts +31 -0
  901. package/dist/runtime/native-runtime/broker-worker-load-failure.d.ts.map +1 -0
  902. package/dist/runtime/native-runtime/broker-worker-load-failure.js +66 -0
  903. package/dist/runtime/native-runtime/broker-worker-load-failure.js.map +1 -0
  904. package/dist/runtime/native-runtime/browser-follower-connection.d.ts +82 -0
  905. package/dist/runtime/native-runtime/browser-follower-connection.d.ts.map +1 -0
  906. package/dist/runtime/native-runtime/browser-follower-connection.js +495 -0
  907. package/dist/runtime/native-runtime/browser-follower-connection.js.map +1 -0
  908. package/dist/runtime/native-runtime/browser-shared-worker-connection.d.ts +98 -0
  909. package/dist/runtime/native-runtime/browser-shared-worker-connection.d.ts.map +1 -0
  910. package/dist/runtime/native-runtime/browser-shared-worker-connection.js +831 -0
  911. package/dist/runtime/native-runtime/browser-shared-worker-connection.js.map +1 -0
  912. package/dist/runtime/native-runtime/browser-worker-protocol.d.ts +460 -0
  913. package/dist/runtime/native-runtime/browser-worker-protocol.d.ts.map +1 -0
  914. package/dist/runtime/native-runtime/browser-worker-protocol.js +281 -0
  915. package/dist/runtime/native-runtime/browser-worker-protocol.js.map +1 -0
  916. package/dist/runtime/native-runtime/browser-worker-transport.d.ts +53 -0
  917. package/dist/runtime/native-runtime/browser-worker-transport.d.ts.map +1 -0
  918. package/dist/runtime/native-runtime/browser-worker-transport.js +252 -0
  919. package/dist/runtime/native-runtime/browser-worker-transport.js.map +1 -0
  920. package/dist/runtime/native-runtime/exact-integer.d.ts +7 -0
  921. package/dist/runtime/native-runtime/exact-integer.d.ts.map +1 -0
  922. package/dist/runtime/native-runtime/exact-integer.js +18 -0
  923. package/dist/runtime/native-runtime/exact-integer.js.map +1 -0
  924. package/dist/runtime/native-runtime/http-stream-socket.d.ts +103 -0
  925. package/dist/runtime/native-runtime/http-stream-socket.d.ts.map +1 -0
  926. package/dist/runtime/native-runtime/http-stream-socket.js +460 -0
  927. package/dist/runtime/native-runtime/http-stream-socket.js.map +1 -0
  928. package/dist/runtime/native-runtime/inspector-control-lifecycle.d.ts +4 -0
  929. package/dist/runtime/native-runtime/inspector-control-lifecycle.d.ts.map +1 -0
  930. package/dist/runtime/native-runtime/inspector-control-lifecycle.js +33 -0
  931. package/dist/runtime/native-runtime/inspector-control-lifecycle.js.map +1 -0
  932. package/dist/runtime/native-runtime/native-codec.d.ts +177 -0
  933. package/dist/runtime/native-runtime/native-codec.d.ts.map +1 -0
  934. package/dist/runtime/native-runtime/native-codec.js +627 -0
  935. package/dist/runtime/native-runtime/native-codec.js.map +1 -0
  936. package/dist/runtime/native-runtime/native-error-code.d.ts +39 -0
  937. package/dist/runtime/native-runtime/native-error-code.d.ts.map +1 -0
  938. package/dist/runtime/native-runtime/native-error-code.js +62 -0
  939. package/dist/runtime/native-runtime/native-error-code.js.map +1 -0
  940. package/dist/runtime/native-runtime/native-row-codec.d.ts +161 -0
  941. package/dist/runtime/native-runtime/native-row-codec.d.ts.map +1 -0
  942. package/dist/runtime/native-runtime/native-row-codec.js +942 -0
  943. package/dist/runtime/native-runtime/native-row-codec.js.map +1 -0
  944. package/dist/runtime/native-runtime/native-row-descriptor-key.d.ts +15 -0
  945. package/dist/runtime/native-runtime/native-row-descriptor-key.d.ts.map +1 -0
  946. package/dist/runtime/native-runtime/native-row-descriptor-key.js +25 -0
  947. package/dist/runtime/native-runtime/native-row-descriptor-key.js.map +1 -0
  948. package/dist/runtime/native-runtime/native-runtime-adapter.d.ts +736 -0
  949. package/dist/runtime/native-runtime/native-runtime-adapter.d.ts.map +1 -0
  950. package/dist/runtime/native-runtime/native-runtime-adapter.js +5733 -0
  951. package/dist/runtime/native-runtime/native-runtime-adapter.js.map +1 -0
  952. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.d.ts +17 -0
  953. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.d.ts.map +1 -0
  954. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.js +4 -0
  955. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.js.map +1 -0
  956. package/dist/runtime/native-runtime/node-foreground-node-lease.d.ts +19 -0
  957. package/dist/runtime/native-runtime/node-foreground-node-lease.d.ts.map +1 -0
  958. package/dist/runtime/native-runtime/node-foreground-node-lease.js +297 -0
  959. package/dist/runtime/native-runtime/node-foreground-node-lease.js.map +1 -0
  960. package/dist/runtime/native-runtime/row-values-transport.d.ts +2 -0
  961. package/dist/runtime/native-runtime/row-values-transport.d.ts.map +1 -0
  962. package/dist/runtime/native-runtime/row-values-transport.js +21 -0
  963. package/dist/runtime/native-runtime/row-values-transport.js.map +1 -0
  964. package/dist/runtime/native-runtime/schema-codec.d.ts +10 -0
  965. package/dist/runtime/native-runtime/schema-codec.d.ts.map +1 -0
  966. package/dist/runtime/native-runtime/schema-codec.js +13 -0
  967. package/dist/runtime/native-runtime/schema-codec.js.map +1 -0
  968. package/dist/runtime/native-runtime/websocket.d.ts +178 -0
  969. package/dist/runtime/native-runtime/websocket.d.ts.map +1 -0
  970. package/dist/runtime/native-runtime/websocket.js +732 -0
  971. package/dist/runtime/native-runtime/websocket.js.map +1 -0
  972. package/dist/runtime/page-handle.d.ts +87 -0
  973. package/dist/runtime/page-handle.d.ts.map +1 -0
  974. package/dist/runtime/page-handle.js +144 -0
  975. package/dist/runtime/page-handle.js.map +1 -0
  976. package/dist/runtime/passkey-backup.d.ts +3 -0
  977. package/dist/runtime/passkey-backup.d.ts.map +1 -0
  978. package/dist/runtime/passkey-backup.js +2 -0
  979. package/dist/runtime/passkey-backup.js.map +1 -0
  980. package/dist/runtime/platform-url.d.ts +10 -0
  981. package/dist/runtime/platform-url.d.ts.map +1 -0
  982. package/dist/runtime/platform-url.js +3 -0
  983. package/dist/runtime/platform-url.js.map +1 -0
  984. package/dist/runtime/platform-url.native.d.ts +6 -0
  985. package/dist/runtime/platform-url.native.d.ts.map +1 -0
  986. package/dist/runtime/platform-url.native.js +37 -0
  987. package/dist/runtime/platform-url.native.js.map +1 -0
  988. package/dist/runtime/query-adapter.d.ts +7 -15
  989. package/dist/runtime/query-adapter.d.ts.map +1 -1
  990. package/dist/runtime/query-adapter.js +554 -167
  991. package/dist/runtime/query-adapter.js.map +1 -1
  992. package/dist/runtime/query-builder-shape.d.ts +75 -0
  993. package/dist/runtime/query-builder-shape.d.ts.map +1 -0
  994. package/dist/runtime/query-builder-shape.js +225 -0
  995. package/dist/runtime/query-builder-shape.js.map +1 -0
  996. package/dist/runtime/query-column-name.d.ts +3 -0
  997. package/dist/runtime/query-column-name.d.ts.map +1 -0
  998. package/dist/runtime/query-column-name.js +10 -0
  999. package/dist/runtime/query-column-name.js.map +1 -0
  1000. package/dist/runtime/query-output-table.d.ts +5 -0
  1001. package/dist/runtime/query-output-table.d.ts.map +1 -0
  1002. package/dist/runtime/query-output-table.js +30 -0
  1003. package/dist/runtime/query-output-table.js.map +1 -0
  1004. package/dist/runtime/recovery-phrase.d.ts +3 -0
  1005. package/dist/runtime/recovery-phrase.d.ts.map +1 -0
  1006. package/dist/runtime/recovery-phrase.js +2 -0
  1007. package/dist/runtime/recovery-phrase.js.map +1 -0
  1008. package/dist/runtime/remote-link-state.d.ts +20 -0
  1009. package/dist/runtime/remote-link-state.d.ts.map +1 -0
  1010. package/dist/runtime/remote-link-state.js +5 -0
  1011. package/dist/runtime/remote-link-state.js.map +1 -0
  1012. package/dist/runtime/removed-provider-props.d.ts +17 -0
  1013. package/dist/runtime/removed-provider-props.d.ts.map +1 -0
  1014. package/dist/runtime/removed-provider-props.js +16 -0
  1015. package/dist/runtime/removed-provider-props.js.map +1 -0
  1016. package/dist/runtime/row-transformer.d.ts +18 -6
  1017. package/dist/runtime/row-transformer.d.ts.map +1 -1
  1018. package/dist/runtime/row-transformer.js +195 -41
  1019. package/dist/runtime/row-transformer.js.map +1 -1
  1020. package/dist/runtime/run-cleanup-steps.d.ts +5 -0
  1021. package/dist/runtime/run-cleanup-steps.d.ts.map +1 -0
  1022. package/dist/runtime/run-cleanup-steps.js +19 -0
  1023. package/dist/runtime/run-cleanup-steps.js.map +1 -0
  1024. package/dist/runtime/runtime-closed-error.d.ts +9 -0
  1025. package/dist/runtime/runtime-closed-error.d.ts.map +1 -0
  1026. package/dist/runtime/runtime-closed-error.js +12 -0
  1027. package/dist/runtime/runtime-closed-error.js.map +1 -0
  1028. package/dist/runtime/runtime-config.d.ts +9 -0
  1029. package/dist/runtime/runtime-config.d.ts.map +1 -0
  1030. package/dist/runtime/runtime-config.js +111 -0
  1031. package/dist/runtime/runtime-config.js.map +1 -0
  1032. package/dist/runtime/runtime-entropy.d.ts +14 -0
  1033. package/dist/runtime/runtime-entropy.d.ts.map +1 -0
  1034. package/dist/runtime/runtime-entropy.js +43 -0
  1035. package/dist/runtime/runtime-entropy.js.map +1 -0
  1036. package/dist/runtime/runtime-source.d.ts +170 -0
  1037. package/dist/runtime/runtime-source.d.ts.map +1 -0
  1038. package/dist/runtime/runtime-source.js +64 -0
  1039. package/dist/runtime/runtime-source.js.map +1 -0
  1040. package/dist/runtime/schema-metadata.d.ts +5 -0
  1041. package/dist/runtime/schema-metadata.d.ts.map +1 -0
  1042. package/dist/runtime/schema-metadata.js +34 -0
  1043. package/dist/runtime/schema-metadata.js.map +1 -0
  1044. package/dist/runtime/select-projection.d.ts +5 -0
  1045. package/dist/runtime/select-projection.d.ts.map +1 -0
  1046. package/dist/runtime/select-projection.js +47 -0
  1047. package/dist/runtime/select-projection.js.map +1 -0
  1048. package/dist/runtime/snapshot-ref.d.ts +24 -0
  1049. package/dist/runtime/snapshot-ref.d.ts.map +1 -0
  1050. package/dist/runtime/snapshot-ref.js +43 -0
  1051. package/dist/runtime/snapshot-ref.js.map +1 -0
  1052. package/dist/runtime/store-held-by-another-tab-error.d.ts +47 -0
  1053. package/dist/runtime/store-held-by-another-tab-error.d.ts.map +1 -0
  1054. package/dist/runtime/store-held-by-another-tab-error.js +49 -0
  1055. package/dist/runtime/store-held-by-another-tab-error.js.map +1 -0
  1056. package/dist/runtime/streaming-source.d.ts +4 -0
  1057. package/dist/runtime/streaming-source.d.ts.map +1 -0
  1058. package/dist/runtime/streaming-source.js +53 -0
  1059. package/dist/runtime/streaming-source.js.map +1 -0
  1060. package/dist/runtime/structural-values.d.ts +6 -0
  1061. package/dist/runtime/structural-values.d.ts.map +1 -0
  1062. package/dist/runtime/structural-values.js +55 -0
  1063. package/dist/runtime/structural-values.js.map +1 -0
  1064. package/dist/runtime/subscription-manager.d.ts +98 -14
  1065. package/dist/runtime/subscription-manager.d.ts.map +1 -1
  1066. package/dist/runtime/subscription-manager.js +1049 -25
  1067. package/dist/runtime/subscription-manager.js.map +1 -1
  1068. package/dist/runtime/sync-status.d.ts +157 -0
  1069. package/dist/runtime/sync-status.d.ts.map +1 -0
  1070. package/dist/runtime/sync-status.js +153 -0
  1071. package/dist/runtime/sync-status.js.map +1 -0
  1072. package/dist/runtime/sync-telemetry.d.ts +35 -0
  1073. package/dist/runtime/sync-telemetry.d.ts.map +1 -0
  1074. package/dist/runtime/sync-telemetry.js +354 -0
  1075. package/dist/runtime/sync-telemetry.js.map +1 -0
  1076. package/dist/runtime/system-identity.d.ts +5 -0
  1077. package/dist/runtime/system-identity.d.ts.map +1 -0
  1078. package/dist/runtime/system-identity.js +10 -0
  1079. package/dist/runtime/system-identity.js.map +1 -0
  1080. package/dist/runtime/telemetry-env.d.ts +2 -0
  1081. package/dist/runtime/telemetry-env.d.ts.map +1 -0
  1082. package/dist/runtime/telemetry-env.js +16 -0
  1083. package/dist/runtime/telemetry-env.js.map +1 -0
  1084. package/dist/runtime/telemetry-env.native.d.ts +3 -0
  1085. package/dist/runtime/telemetry-env.native.d.ts.map +1 -0
  1086. package/dist/runtime/telemetry-env.native.js +7 -0
  1087. package/dist/runtime/telemetry-env.native.js.map +1 -0
  1088. package/dist/runtime/text-anchors.d.ts +58 -0
  1089. package/dist/runtime/text-anchors.d.ts.map +1 -0
  1090. package/dist/runtime/text-anchors.js +9 -0
  1091. package/dist/runtime/text-anchors.js.map +1 -0
  1092. package/dist/runtime/unsupported-storage-codecs-error.d.ts +53 -0
  1093. package/dist/runtime/unsupported-storage-codecs-error.d.ts.map +1 -0
  1094. package/dist/runtime/unsupported-storage-codecs-error.js +74 -0
  1095. package/dist/runtime/unsupported-storage-codecs-error.js.map +1 -0
  1096. package/dist/runtime/url.d.ts +32 -0
  1097. package/dist/runtime/url.d.ts.map +1 -0
  1098. package/dist/runtime/url.js +96 -0
  1099. package/dist/runtime/url.js.map +1 -0
  1100. package/dist/runtime/utf8.d.ts +10 -0
  1101. package/dist/runtime/utf8.d.ts.map +1 -0
  1102. package/dist/runtime/utf8.js +93 -0
  1103. package/dist/runtime/utf8.js.map +1 -0
  1104. package/dist/runtime/util.d.ts +18 -0
  1105. package/dist/runtime/util.d.ts.map +1 -0
  1106. package/dist/runtime/util.js +59 -0
  1107. package/dist/runtime/util.js.map +1 -0
  1108. package/dist/runtime/value-converter.d.ts +9 -17
  1109. package/dist/runtime/value-converter.d.ts.map +1 -1
  1110. package/dist/runtime/value-converter.js +196 -43
  1111. package/dist/runtime/value-converter.js.map +1 -1
  1112. package/dist/runtime/wasm-loader.d.ts +6 -0
  1113. package/dist/runtime/wasm-loader.d.ts.map +1 -0
  1114. package/dist/runtime/wasm-loader.js +120 -0
  1115. package/dist/runtime/wasm-loader.js.map +1 -0
  1116. package/dist/runtime/write-preparation.d.ts +24 -0
  1117. package/dist/runtime/write-preparation.d.ts.map +1 -0
  1118. package/dist/runtime/write-preparation.js +63 -0
  1119. package/dist/runtime/write-preparation.js.map +1 -0
  1120. package/dist/runtime/write-row.d.ts +8 -0
  1121. package/dist/runtime/write-row.d.ts.map +1 -0
  1122. package/dist/runtime/write-row.js +17 -0
  1123. package/dist/runtime/write-row.js.map +1 -0
  1124. package/dist/schema-hash.d.ts +3 -0
  1125. package/dist/schema-hash.d.ts.map +1 -0
  1126. package/dist/schema-hash.js +5 -0
  1127. package/dist/schema-hash.js.map +1 -0
  1128. package/dist/schema-loader.d.ts +31 -0
  1129. package/dist/schema-loader.d.ts.map +1 -0
  1130. package/dist/schema-loader.js +501 -0
  1131. package/dist/schema-loader.js.map +1 -0
  1132. package/dist/schema-name.d.ts +2 -0
  1133. package/dist/schema-name.d.ts.map +1 -0
  1134. package/dist/schema-name.js +19 -0
  1135. package/dist/schema-name.js.map +1 -0
  1136. package/dist/schema-namespace.d.ts +35 -0
  1137. package/dist/schema-namespace.d.ts.map +1 -0
  1138. package/dist/schema-namespace.js +17 -0
  1139. package/dist/schema-namespace.js.map +1 -0
  1140. package/dist/schema-permissions.d.ts +16 -0
  1141. package/dist/schema-permissions.d.ts.map +1 -0
  1142. package/dist/schema-permissions.js +405 -0
  1143. package/dist/schema-permissions.js.map +1 -0
  1144. package/dist/schema-source.d.ts +11 -0
  1145. package/dist/schema-source.d.ts.map +1 -0
  1146. package/dist/schema-source.js +39 -0
  1147. package/dist/schema-source.js.map +1 -0
  1148. package/dist/schema.d.ts +108 -36
  1149. package/dist/schema.d.ts.map +1 -1
  1150. package/dist/schema.js +1 -10
  1151. package/dist/schema.js.map +1 -1
  1152. package/dist/session/backend-watch.d.ts +177 -0
  1153. package/dist/session/backend-watch.d.ts.map +1 -0
  1154. package/dist/session/backend-watch.js +653 -0
  1155. package/dist/session/backend-watch.js.map +1 -0
  1156. package/dist/session/config-options.d.ts +15 -0
  1157. package/dist/session/config-options.d.ts.map +1 -0
  1158. package/dist/session/config-options.js +55 -0
  1159. package/dist/session/config-options.js.map +1 -0
  1160. package/dist/session/consumer.d.ts +3 -0
  1161. package/dist/session/consumer.d.ts.map +1 -0
  1162. package/dist/session/consumer.js +3 -0
  1163. package/dist/session/consumer.js.map +1 -0
  1164. package/dist/session/create-jazz-session.d.ts +104 -0
  1165. package/dist/session/create-jazz-session.d.ts.map +1 -0
  1166. package/dist/session/create-jazz-session.js +647 -0
  1167. package/dist/session/create-jazz-session.js.map +1 -0
  1168. package/dist/session/follow-user.d.ts +63 -0
  1169. package/dist/session/follow-user.d.ts.map +1 -0
  1170. package/dist/session/follow-user.js +128 -0
  1171. package/dist/session/follow-user.js.map +1 -0
  1172. package/dist/session/jazz-session.d.ts +164 -0
  1173. package/dist/session/jazz-session.d.ts.map +1 -0
  1174. package/dist/session/jazz-session.js +432 -0
  1175. package/dist/session/jazz-session.js.map +1 -0
  1176. package/dist/session/left-behind-replicas.d.ts +69 -0
  1177. package/dist/session/left-behind-replicas.d.ts.map +1 -0
  1178. package/dist/session/left-behind-replicas.js +163 -0
  1179. package/dist/session/left-behind-replicas.js.map +1 -0
  1180. package/dist/session/native-backend-watch.d.ts +4 -0
  1181. package/dist/session/native-backend-watch.d.ts.map +1 -0
  1182. package/dist/session/native-backend-watch.js +14 -0
  1183. package/dist/session/native-backend-watch.js.map +1 -0
  1184. package/dist/session/state.d.ts +100 -0
  1185. package/dist/session/state.d.ts.map +1 -0
  1186. package/dist/session/state.js +428 -0
  1187. package/dist/session/state.js.map +1 -0
  1188. package/dist/shared/index.d.ts +20 -0
  1189. package/dist/shared/index.d.ts.map +1 -0
  1190. package/dist/shared/index.js +17 -0
  1191. package/dist/shared/index.js.map +1 -0
  1192. package/dist/solid/create-solid-jazz-client-internal.d.ts +13 -0
  1193. package/dist/solid/create-solid-jazz-client-internal.d.ts.map +1 -0
  1194. package/dist/solid/create-solid-jazz-client-internal.js +83 -0
  1195. package/dist/solid/create-solid-jazz-client-internal.js.map +1 -0
  1196. package/dist/solid/create-solid-jazz-client-internal.ssr.js +101 -0
  1197. package/dist/solid/create-solid-jazz-client-internal.ssr.js.map +1 -0
  1198. package/dist/solid/create-solid-jazz-client.d.ts +24 -0
  1199. package/dist/solid/create-solid-jazz-client.d.ts.map +1 -0
  1200. package/dist/solid/create-solid-jazz-client.js +43 -0
  1201. package/dist/solid/create-solid-jazz-client.js.map +1 -0
  1202. package/dist/solid/create-solid-jazz-client.ssr.js +46 -0
  1203. package/dist/solid/create-solid-jazz-client.ssr.js.map +1 -0
  1204. package/dist/solid/index.d.ts +14 -0
  1205. package/dist/solid/index.d.ts.map +1 -0
  1206. package/dist/solid/index.js +10 -0
  1207. package/dist/solid/index.ssr.js +10 -0
  1208. package/dist/solid/provider.d.ts +32 -0
  1209. package/dist/solid/provider.d.ts.map +1 -0
  1210. package/dist/solid/provider.js +47 -0
  1211. package/dist/solid/provider.js.map +1 -0
  1212. package/dist/solid/provider.ssr.js +47 -0
  1213. package/dist/solid/provider.ssr.js.map +1 -0
  1214. package/dist/solid/session.d.ts +52 -0
  1215. package/dist/solid/session.d.ts.map +1 -0
  1216. package/dist/solid/session.js +123 -0
  1217. package/dist/solid/session.js.map +1 -0
  1218. package/dist/solid/session.ssr.js +148 -0
  1219. package/dist/solid/session.ssr.js.map +1 -0
  1220. package/dist/solid/solid-jazz-client-store.d.ts +11 -0
  1221. package/dist/solid/solid-jazz-client-store.d.ts.map +1 -0
  1222. package/dist/solid/solid-jazz-client-store.js +37 -0
  1223. package/dist/solid/solid-jazz-client-store.js.map +1 -0
  1224. package/dist/solid/solid-jazz-client-store.ssr.js +39 -0
  1225. package/dist/solid/solid-jazz-client-store.ssr.js.map +1 -0
  1226. package/dist/solid/use-all.d.ts +18 -0
  1227. package/dist/solid/use-all.d.ts.map +1 -0
  1228. package/dist/solid/use-all.js +73 -0
  1229. package/dist/solid/use-all.js.map +1 -0
  1230. package/dist/solid/use-all.ssr.js +84 -0
  1231. package/dist/solid/use-all.ssr.js.map +1 -0
  1232. package/dist/solid/use-one.d.ts +18 -0
  1233. package/dist/solid/use-one.d.ts.map +1 -0
  1234. package/dist/solid/use-one.js +28 -0
  1235. package/dist/solid/use-one.js.map +1 -0
  1236. package/dist/solid/use-one.ssr.js +28 -0
  1237. package/dist/solid/use-one.ssr.js.map +1 -0
  1238. package/dist/solid/use-sync-status.d.ts +8 -0
  1239. package/dist/solid/use-sync-status.d.ts.map +1 -0
  1240. package/dist/solid/use-sync-status.js +14 -0
  1241. package/dist/solid/use-sync-status.js.map +1 -0
  1242. package/dist/solid/use-sync-status.ssr.js +21 -0
  1243. package/dist/solid/use-sync-status.ssr.js.map +1 -0
  1244. package/dist/subscription-store-internal.d.ts +11 -0
  1245. package/dist/subscription-store-internal.d.ts.map +1 -0
  1246. package/dist/subscription-store-internal.js +18 -0
  1247. package/dist/subscription-store-internal.js.map +1 -0
  1248. package/dist/subscriptions-orchestrator.d.ts +53 -13
  1249. package/dist/subscriptions-orchestrator.d.ts.map +1 -1
  1250. package/dist/subscriptions-orchestrator.js +295 -74
  1251. package/dist/subscriptions-orchestrator.js.map +1 -1
  1252. package/dist/svelte/JazzProvider.svelte +96 -0
  1253. package/dist/svelte/JazzProvider.svelte.d.ts +23 -0
  1254. package/dist/svelte/JazzProvider.svelte.d.ts.map +1 -0
  1255. package/dist/svelte/JazzSvelteClientProvider.svelte +73 -0
  1256. package/dist/svelte/JazzSvelteClientProvider.svelte.d.ts +13 -0
  1257. package/dist/svelte/JazzSvelteClientProvider.svelte.d.ts.map +1 -0
  1258. package/dist/svelte/JazzSvelteProvider.svelte +160 -28
  1259. package/dist/svelte/JazzSvelteProvider.svelte.d.ts +4 -3
  1260. package/dist/svelte/JazzSvelteProvider.svelte.d.ts.map +1 -1
  1261. package/dist/svelte/context.svelte.d.ts +23 -3
  1262. package/dist/svelte/context.svelte.d.ts.map +1 -1
  1263. package/dist/svelte/context.svelte.js +23 -3
  1264. package/dist/svelte/create-jazz-client.d.ts +2 -8
  1265. package/dist/svelte/create-jazz-client.d.ts.map +1 -1
  1266. package/dist/svelte/create-jazz-client.js +1 -17
  1267. package/dist/svelte/index.d.ts +14 -6
  1268. package/dist/svelte/index.d.ts.map +1 -1
  1269. package/dist/svelte/index.js +11 -6
  1270. package/dist/svelte/query-subscription.svelte.d.ts +60 -0
  1271. package/dist/svelte/query-subscription.svelte.d.ts.map +1 -0
  1272. package/dist/svelte/query-subscription.svelte.js +135 -0
  1273. package/dist/svelte/session-state.d.ts +21 -0
  1274. package/dist/svelte/session-state.d.ts.map +1 -0
  1275. package/dist/svelte/session-state.js +29 -0
  1276. package/dist/svelte/sync-status.d.ts +11 -0
  1277. package/dist/svelte/sync-status.d.ts.map +1 -0
  1278. package/dist/svelte/sync-status.js +15 -0
  1279. package/dist/testing/client-migrations.d.ts +29 -0
  1280. package/dist/testing/client-migrations.d.ts.map +1 -0
  1281. package/dist/testing/client-migrations.js +34 -0
  1282. package/dist/testing/client-migrations.js.map +1 -0
  1283. package/dist/testing/fixtures/basic/schema.d.ts +11 -0
  1284. package/dist/testing/fixtures/basic/schema.d.ts.map +1 -0
  1285. package/dist/testing/fixtures/basic/schema.js +10 -0
  1286. package/dist/testing/fixtures/basic/schema.js.map +1 -0
  1287. package/dist/testing/fixtures/with-bigint/schema.d.ts +18 -0
  1288. package/dist/testing/fixtures/with-bigint/schema.d.ts.map +1 -0
  1289. package/dist/testing/fixtures/with-bigint/schema.js +15 -0
  1290. package/dist/testing/fixtures/with-bigint/schema.js.map +1 -0
  1291. package/dist/testing/fixtures/with-defaults/schema.d.ts +385 -0
  1292. package/dist/testing/fixtures/with-defaults/schema.d.ts.map +1 -0
  1293. package/dist/testing/fixtures/with-defaults/schema.js +15 -0
  1294. package/dist/testing/fixtures/with-defaults/schema.js.map +1 -0
  1295. package/dist/testing/fixtures/with-enum-payload-defaults/schema.d.ts +4 -0
  1296. package/dist/testing/fixtures/with-enum-payload-defaults/schema.d.ts.map +1 -0
  1297. package/dist/testing/fixtures/with-enum-payload-defaults/schema.js +22 -0
  1298. package/dist/testing/fixtures/with-enum-payload-defaults/schema.js.map +1 -0
  1299. package/dist/testing/fixtures/with-enum-payload-required-null/schema.d.ts +4 -0
  1300. package/dist/testing/fixtures/with-enum-payload-required-null/schema.d.ts.map +1 -0
  1301. package/dist/testing/fixtures/with-enum-payload-required-null/schema.js +14 -0
  1302. package/dist/testing/fixtures/with-enum-payload-required-null/schema.js.map +1 -0
  1303. package/dist/testing/fixtures/with-enum-payload-wrong-tag/schema.d.ts +4 -0
  1304. package/dist/testing/fixtures/with-enum-payload-wrong-tag/schema.d.ts.map +1 -0
  1305. package/dist/testing/fixtures/with-enum-payload-wrong-tag/schema.js +14 -0
  1306. package/dist/testing/fixtures/with-enum-payload-wrong-tag/schema.js.map +1 -0
  1307. package/dist/testing/index.d.ts +6 -1
  1308. package/dist/testing/index.d.ts.map +1 -1
  1309. package/dist/testing/index.js +5 -1
  1310. package/dist/testing/index.js.map +1 -1
  1311. package/dist/testing/policy-test-app.d.ts +123 -0
  1312. package/dist/testing/policy-test-app.d.ts.map +1 -0
  1313. package/dist/testing/policy-test-app.js +216 -0
  1314. package/dist/testing/policy-test-app.js.map +1 -0
  1315. package/dist/testing/test-jazz.d.ts +106 -0
  1316. package/dist/testing/test-jazz.d.ts.map +1 -0
  1317. package/dist/testing/test-jazz.js +157 -0
  1318. package/dist/testing/test-jazz.js.map +1 -0
  1319. package/dist/testing/test-jwt-issuer.d.ts +19 -0
  1320. package/dist/testing/test-jwt-issuer.d.ts.map +1 -0
  1321. package/dist/testing/test-jwt-issuer.js +40 -0
  1322. package/dist/testing/test-jwt-issuer.js.map +1 -0
  1323. package/dist/text-field/index.d.ts +40 -0
  1324. package/dist/text-field/index.d.ts.map +1 -0
  1325. package/dist/text-field/index.js +129 -0
  1326. package/dist/text-field/index.js.map +1 -0
  1327. package/dist/thin/index.d.ts +81 -0
  1328. package/dist/thin/index.d.ts.map +1 -0
  1329. package/dist/thin/index.js +221 -0
  1330. package/dist/thin/index.js.map +1 -0
  1331. package/dist/thin/self-signed-token.d.ts +13 -0
  1332. package/dist/thin/self-signed-token.d.ts.map +1 -0
  1333. package/dist/thin/self-signed-token.js +84 -0
  1334. package/dist/thin/self-signed-token.js.map +1 -0
  1335. package/dist/thin/thin-runtime-source.d.ts +19 -0
  1336. package/dist/thin/thin-runtime-source.d.ts.map +1 -0
  1337. package/dist/thin/thin-runtime-source.js +66 -0
  1338. package/dist/thin/thin-runtime-source.js.map +1 -0
  1339. package/dist/thin/thin-runtime.d.ts +244 -0
  1340. package/dist/thin/thin-runtime.d.ts.map +1 -0
  1341. package/dist/thin/thin-runtime.js +1323 -0
  1342. package/dist/thin/thin-runtime.js.map +1 -0
  1343. package/dist/thin/wire.d.ts +160 -0
  1344. package/dist/thin/wire.d.ts.map +1 -0
  1345. package/dist/thin/wire.js +304 -0
  1346. package/dist/thin/wire.js.map +1 -0
  1347. package/dist/typed-app.d.ts +729 -0
  1348. package/dist/typed-app.d.ts.map +1 -0
  1349. package/dist/typed-app.js +789 -0
  1350. package/dist/typed-app.js.map +1 -0
  1351. package/dist/vue/create-jazz-client.d.ts +3 -0
  1352. package/dist/vue/create-jazz-client.d.ts.map +1 -0
  1353. package/dist/vue/create-jazz-client.js +2 -0
  1354. package/dist/vue/create-jazz-client.js.map +1 -0
  1355. package/dist/vue/index.d.ts +14 -0
  1356. package/dist/vue/index.d.ts.map +1 -0
  1357. package/dist/vue/index.js +11 -0
  1358. package/dist/vue/index.js.map +1 -0
  1359. package/dist/vue/provider.d.ts +66 -0
  1360. package/dist/vue/provider.d.ts.map +1 -0
  1361. package/dist/vue/provider.js +216 -0
  1362. package/dist/vue/provider.js.map +1 -0
  1363. package/dist/vue/session.d.ts +40 -0
  1364. package/dist/vue/session.d.ts.map +1 -0
  1365. package/dist/vue/session.js +99 -0
  1366. package/dist/vue/session.js.map +1 -0
  1367. package/dist/vue/use-all.d.ts +61 -0
  1368. package/dist/vue/use-all.d.ts.map +1 -0
  1369. package/dist/vue/use-all.js +104 -0
  1370. package/dist/vue/use-all.js.map +1 -0
  1371. package/dist/vue/use-one.d.ts +24 -0
  1372. package/dist/vue/use-one.d.ts.map +1 -0
  1373. package/dist/vue/use-one.js +17 -0
  1374. package/dist/vue/use-one.js.map +1 -0
  1375. package/dist/vue/use-sync-status.d.ts +9 -0
  1376. package/dist/vue/use-sync-status.d.ts.map +1 -0
  1377. package/dist/vue/use-sync-status.js +16 -0
  1378. package/dist/vue/use-sync-status.js.map +1 -0
  1379. package/dist/web/create-jazz-client.d.ts +8 -0
  1380. package/dist/web/create-jazz-client.d.ts.map +1 -0
  1381. package/dist/web/create-jazz-client.js +8 -0
  1382. package/dist/web/create-jazz-client.js.map +1 -0
  1383. package/dist/web/lazy-local-first.d.ts +8 -0
  1384. package/dist/web/lazy-local-first.d.ts.map +1 -0
  1385. package/dist/web/lazy-local-first.js +13 -0
  1386. package/dist/web/lazy-local-first.js.map +1 -0
  1387. package/dist/web/registered-jazz-client.d.ts +15 -0
  1388. package/dist/web/registered-jazz-client.d.ts.map +1 -0
  1389. package/dist/web/registered-jazz-client.js +35 -0
  1390. package/dist/web/registered-jazz-client.js.map +1 -0
  1391. package/dist/where-operators.d.ts +13 -0
  1392. package/dist/where-operators.d.ts.map +1 -0
  1393. package/dist/where-operators.js +70 -0
  1394. package/dist/where-operators.js.map +1 -0
  1395. package/dist/window-client-storage.d.ts +7 -0
  1396. package/dist/window-client-storage.d.ts.map +1 -0
  1397. package/dist/window-client-storage.js +27 -0
  1398. package/dist/window-client-storage.js.map +1 -0
  1399. package/dist/worker/jazz-broker-worker-core.d.ts +34 -0
  1400. package/dist/worker/jazz-broker-worker-core.d.ts.map +1 -0
  1401. package/dist/worker/jazz-broker-worker-core.js +2030 -0
  1402. package/dist/worker/jazz-broker-worker-core.js.map +1 -0
  1403. package/dist/worker/jazz-broker-worker.d.ts +2 -0
  1404. package/dist/worker/jazz-broker-worker.d.ts.map +1 -0
  1405. package/dist/worker/jazz-broker-worker.js +23600 -0
  1406. package/dist/worker/jazz_wasm_bg.wasm +0 -0
  1407. package/dist/worker/mutation-error-delivery.d.ts +8 -0
  1408. package/dist/worker/mutation-error-delivery.d.ts.map +1 -0
  1409. package/dist/worker/mutation-error-delivery.js +10 -0
  1410. package/dist/worker/mutation-error-delivery.js.map +1 -0
  1411. package/dist/worker/runtime-admission.d.ts +19 -0
  1412. package/dist/worker/runtime-admission.d.ts.map +1 -0
  1413. package/dist/worker/runtime-admission.js +34 -0
  1414. package/dist/worker/runtime-admission.js.map +1 -0
  1415. package/package.json +262 -31
  1416. package/bin/native/.gitkeep +0 -0
  1417. package/bin/native/jazz-tools-darwin-arm64 +0 -0
  1418. package/bin/native/jazz-tools-darwin-x64 +0 -0
  1419. package/bin/native/jazz-tools-linux-arm64 +0 -0
  1420. package/bin/native/jazz-tools-linux-x64 +0 -0
  1421. package/bin/native/jazz-tools-windows-x64.exe +0 -0
  1422. package/dist/cli.test.d.ts +0 -2
  1423. package/dist/cli.test.d.ts.map +0 -1
  1424. package/dist/cli.test.js +0 -154
  1425. package/dist/cli.test.js.map +0 -1
  1426. package/dist/codegen/codegen.test.d.ts +0 -2
  1427. package/dist/codegen/codegen.test.d.ts.map +0 -1
  1428. package/dist/codegen/codegen.test.js +0 -844
  1429. package/dist/codegen/codegen.test.js.map +0 -1
  1430. package/dist/codegen/index.d.ts +0 -18
  1431. package/dist/codegen/index.d.ts.map +0 -1
  1432. package/dist/codegen/index.js +0 -22
  1433. package/dist/codegen/index.js.map +0 -1
  1434. package/dist/codegen/query-builder-generator.d.ts +0 -23
  1435. package/dist/codegen/query-builder-generator.d.ts.map +0 -1
  1436. package/dist/codegen/query-builder-generator.js +0 -325
  1437. package/dist/codegen/query-builder-generator.js.map +0 -1
  1438. package/dist/codegen/type-generator.d.ts +0 -29
  1439. package/dist/codegen/type-generator.d.ts.map +0 -1
  1440. package/dist/codegen/type-generator.js +0 -226
  1441. package/dist/codegen/type-generator.js.map +0 -1
  1442. package/dist/dsl.test.d.ts +0 -2
  1443. package/dist/dsl.test.d.ts.map +0 -1
  1444. package/dist/dsl.test.js +0 -51
  1445. package/dist/dsl.test.js.map +0 -1
  1446. package/dist/permissions/index.test.d.ts +0 -2
  1447. package/dist/permissions/index.test.d.ts.map +0 -1
  1448. package/dist/permissions/index.test.js +0 -830
  1449. package/dist/permissions/index.test.js.map +0 -1
  1450. package/dist/permissions/type-inference.test.d.ts +0 -2
  1451. package/dist/permissions/type-inference.test.d.ts.map +0 -1
  1452. package/dist/permissions/type-inference.test.js +0 -151
  1453. package/dist/permissions/type-inference.test.js.map +0 -1
  1454. package/dist/react/create-jazz-client.integration.test.d.ts +0 -2
  1455. package/dist/react/create-jazz-client.integration.test.d.ts.map +0 -1
  1456. package/dist/react/create-jazz-client.integration.test.js +0 -84
  1457. package/dist/react/create-jazz-client.integration.test.js.map +0 -1
  1458. package/dist/react/create-jazz-client.test.d.ts +0 -2
  1459. package/dist/react/create-jazz-client.test.d.ts.map +0 -1
  1460. package/dist/react/create-jazz-client.test.js +0 -133
  1461. package/dist/react/create-jazz-client.test.js.map +0 -1
  1462. package/dist/react/synthetic-user-switcher.d.ts +0 -9
  1463. package/dist/react/synthetic-user-switcher.d.ts.map +0 -1
  1464. package/dist/react/synthetic-user-switcher.js +0 -65
  1465. package/dist/react/synthetic-user-switcher.js.map +0 -1
  1466. package/dist/react/synthetic-users.d.ts +0 -2
  1467. package/dist/react/synthetic-users.d.ts.map +0 -1
  1468. package/dist/react/synthetic-users.js +0 -2
  1469. package/dist/react/synthetic-users.js.map +0 -1
  1470. package/dist/react/synthetic-users.test.d.ts +0 -2
  1471. package/dist/react/synthetic-users.test.d.ts.map +0 -1
  1472. package/dist/react/synthetic-users.test.js +0 -43
  1473. package/dist/react/synthetic-users.test.js.map +0 -1
  1474. package/dist/react/use-link-external-identity.d.ts +0 -25
  1475. package/dist/react/use-link-external-identity.d.ts.map +0 -1
  1476. package/dist/react/use-link-external-identity.js +0 -45
  1477. package/dist/react/use-link-external-identity.js.map +0 -1
  1478. package/dist/react-native/create-jazz-client.test.d.ts +0 -2
  1479. package/dist/react-native/create-jazz-client.test.d.ts.map +0 -1
  1480. package/dist/react-native/create-jazz-client.test.js +0 -162
  1481. package/dist/react-native/create-jazz-client.test.js.map +0 -1
  1482. package/dist/react-native/create-jazz-rn-runtime.d.ts +0 -13
  1483. package/dist/react-native/create-jazz-rn-runtime.d.ts.map +0 -1
  1484. package/dist/react-native/create-jazz-rn-runtime.js +0 -7
  1485. package/dist/react-native/create-jazz-rn-runtime.js.map +0 -1
  1486. package/dist/react-native/db.d.ts +0 -16
  1487. package/dist/react-native/db.d.ts.map +0 -1
  1488. package/dist/react-native/db.js +0 -50
  1489. package/dist/react-native/db.js.map +0 -1
  1490. package/dist/react-native/db.test.d.ts +0 -2
  1491. package/dist/react-native/db.test.d.ts.map +0 -1
  1492. package/dist/react-native/db.test.js +0 -150
  1493. package/dist/react-native/db.test.js.map +0 -1
  1494. package/dist/react-native/jazz-rn-runtime-adapter.d.ts +0 -56
  1495. package/dist/react-native/jazz-rn-runtime-adapter.d.ts.map +0 -1
  1496. package/dist/react-native/jazz-rn-runtime-adapter.js +0 -192
  1497. package/dist/react-native/jazz-rn-runtime-adapter.js.map +0 -1
  1498. package/dist/react-native/jazz-rn-runtime-adapter.test.d.ts +0 -2
  1499. package/dist/react-native/jazz-rn-runtime-adapter.test.d.ts.map +0 -1
  1500. package/dist/react-native/jazz-rn-runtime-adapter.test.js +0 -165
  1501. package/dist/react-native/jazz-rn-runtime-adapter.test.js.map +0 -1
  1502. package/dist/runtime/client-session.test.d.ts +0 -2
  1503. package/dist/runtime/client-session.test.d.ts.map +0 -1
  1504. package/dist/runtime/client-session.test.js +0 -84
  1505. package/dist/runtime/client-session.test.js.map +0 -1
  1506. package/dist/runtime/client.for-request.test.d.ts +0 -2
  1507. package/dist/runtime/client.for-request.test.d.ts.map +0 -1
  1508. package/dist/runtime/client.for-request.test.js +0 -171
  1509. package/dist/runtime/client.for-request.test.js.map +0 -1
  1510. package/dist/runtime/cloud-server.integration.test.d.ts +0 -2
  1511. package/dist/runtime/cloud-server.integration.test.d.ts.map +0 -1
  1512. package/dist/runtime/cloud-server.integration.test.js +0 -985
  1513. package/dist/runtime/cloud-server.integration.test.js.map +0 -1
  1514. package/dist/runtime/leader-lock.d.ts +0 -15
  1515. package/dist/runtime/leader-lock.d.ts.map +0 -1
  1516. package/dist/runtime/leader-lock.js +0 -49
  1517. package/dist/runtime/leader-lock.js.map +0 -1
  1518. package/dist/runtime/local-auth.d.ts +0 -32
  1519. package/dist/runtime/local-auth.d.ts.map +0 -1
  1520. package/dist/runtime/local-auth.js +0 -93
  1521. package/dist/runtime/local-auth.js.map +0 -1
  1522. package/dist/runtime/local-auth.test.d.ts +0 -2
  1523. package/dist/runtime/local-auth.test.d.ts.map +0 -1
  1524. package/dist/runtime/local-auth.test.js +0 -50
  1525. package/dist/runtime/local-auth.test.js.map +0 -1
  1526. package/dist/runtime/query-adapter.test.d.ts +0 -5
  1527. package/dist/runtime/query-adapter.test.d.ts.map +0 -1
  1528. package/dist/runtime/query-adapter.test.js +0 -1209
  1529. package/dist/runtime/query-adapter.test.js.map +0 -1
  1530. package/dist/runtime/row-transformer.test.d.ts +0 -5
  1531. package/dist/runtime/row-transformer.test.d.ts.map +0 -1
  1532. package/dist/runtime/row-transformer.test.js +0 -364
  1533. package/dist/runtime/row-transformer.test.js.map +0 -1
  1534. package/dist/runtime/subscription-manager.test.d.ts +0 -5
  1535. package/dist/runtime/subscription-manager.test.d.ts.map +0 -1
  1536. package/dist/runtime/subscription-manager.test.js +0 -120
  1537. package/dist/runtime/subscription-manager.test.js.map +0 -1
  1538. package/dist/runtime/sync-transport.d.ts +0 -163
  1539. package/dist/runtime/sync-transport.d.ts.map +0 -1
  1540. package/dist/runtime/sync-transport.js +0 -477
  1541. package/dist/runtime/sync-transport.js.map +0 -1
  1542. package/dist/runtime/sync-transport.test.d.ts +0 -2
  1543. package/dist/runtime/sync-transport.test.d.ts.map +0 -1
  1544. package/dist/runtime/sync-transport.test.js +0 -310
  1545. package/dist/runtime/sync-transport.test.js.map +0 -1
  1546. package/dist/runtime/tab-leader-election.d.ts +0 -97
  1547. package/dist/runtime/tab-leader-election.d.ts.map +0 -1
  1548. package/dist/runtime/tab-leader-election.js +0 -339
  1549. package/dist/runtime/tab-leader-election.js.map +0 -1
  1550. package/dist/runtime/tab-leader-election.test.d.ts +0 -2
  1551. package/dist/runtime/tab-leader-election.test.d.ts.map +0 -1
  1552. package/dist/runtime/tab-leader-election.test.js +0 -278
  1553. package/dist/runtime/tab-leader-election.test.js.map +0 -1
  1554. package/dist/runtime/testing/wasm-runtime-test-utils.d.ts +0 -13
  1555. package/dist/runtime/testing/wasm-runtime-test-utils.d.ts.map +0 -1
  1556. package/dist/runtime/testing/wasm-runtime-test-utils.js +0 -75
  1557. package/dist/runtime/testing/wasm-runtime-test-utils.js.map +0 -1
  1558. package/dist/runtime/utils.d.ts +0 -2
  1559. package/dist/runtime/utils.d.ts.map +0 -1
  1560. package/dist/runtime/utils.js +0 -16
  1561. package/dist/runtime/utils.js.map +0 -1
  1562. package/dist/runtime/value-converter.test.d.ts +0 -5
  1563. package/dist/runtime/value-converter.test.d.ts.map +0 -1
  1564. package/dist/runtime/value-converter.test.js +0 -212
  1565. package/dist/runtime/value-converter.test.js.map +0 -1
  1566. package/dist/runtime/worker-bridge.d.ts +0 -86
  1567. package/dist/runtime/worker-bridge.d.ts.map +0 -1
  1568. package/dist/runtime/worker-bridge.js +0 -250
  1569. package/dist/runtime/worker-bridge.js.map +0 -1
  1570. package/dist/runtime/worker-bridge.race-harness.test.d.ts +0 -2
  1571. package/dist/runtime/worker-bridge.race-harness.test.d.ts.map +0 -1
  1572. package/dist/runtime/worker-bridge.race-harness.test.js +0 -265
  1573. package/dist/runtime/worker-bridge.race-harness.test.js.map +0 -1
  1574. package/dist/runtime/worker-bridge.test.d.ts +0 -2
  1575. package/dist/runtime/worker-bridge.test.d.ts.map +0 -1
  1576. package/dist/runtime/worker-bridge.test.js +0 -233
  1577. package/dist/runtime/worker-bridge.test.js.map +0 -1
  1578. package/dist/sql-gen.d.ts +0 -4
  1579. package/dist/sql-gen.d.ts.map +0 -1
  1580. package/dist/sql-gen.js +0 -163
  1581. package/dist/sql-gen.js.map +0 -1
  1582. package/dist/sql-gen.test.d.ts +0 -2
  1583. package/dist/sql-gen.test.d.ts.map +0 -1
  1584. package/dist/sql-gen.test.js +0 -412
  1585. package/dist/sql-gen.test.js.map +0 -1
  1586. package/dist/subscriptions-orchestrator.integration.test.d.ts +0 -2
  1587. package/dist/subscriptions-orchestrator.integration.test.d.ts.map +0 -1
  1588. package/dist/subscriptions-orchestrator.integration.test.js +0 -194
  1589. package/dist/subscriptions-orchestrator.integration.test.js.map +0 -1
  1590. package/dist/subscriptions-orchestrator.test.d.ts +0 -2
  1591. package/dist/subscriptions-orchestrator.test.d.ts.map +0 -1
  1592. package/dist/subscriptions-orchestrator.test.js +0 -367
  1593. package/dist/subscriptions-orchestrator.test.js.map +0 -1
  1594. package/dist/svelte/SyntheticUserSwitcher.svelte +0 -121
  1595. package/dist/svelte/SyntheticUserSwitcher.svelte.d.ts +0 -11
  1596. package/dist/svelte/SyntheticUserSwitcher.svelte.d.ts.map +0 -1
  1597. package/dist/svelte/context.test.d.ts +0 -2
  1598. package/dist/svelte/context.test.d.ts.map +0 -1
  1599. package/dist/svelte/context.test.js +0 -51
  1600. package/dist/svelte/create-jazz-client.test.d.ts +0 -2
  1601. package/dist/svelte/create-jazz-client.test.d.ts.map +0 -1
  1602. package/dist/svelte/create-jazz-client.test.js +0 -50
  1603. package/dist/svelte/use-all.svelte.d.ts +0 -32
  1604. package/dist/svelte/use-all.svelte.d.ts.map +0 -1
  1605. package/dist/svelte/use-all.svelte.js +0 -61
  1606. package/dist/svelte/use-all.test.d.ts +0 -2
  1607. package/dist/svelte/use-all.test.d.ts.map +0 -1
  1608. package/dist/svelte/use-all.test.js +0 -154
  1609. package/dist/svelte/use-link-external-identity.d.ts +0 -25
  1610. package/dist/svelte/use-link-external-identity.d.ts.map +0 -1
  1611. package/dist/svelte/use-link-external-identity.js +0 -33
  1612. package/dist/svelte/use-link-external-identity.test.d.ts +0 -2
  1613. package/dist/svelte/use-link-external-identity.test.d.ts.map +0 -1
  1614. package/dist/svelte/use-link-external-identity.test.js +0 -97
  1615. package/dist/synthetic-user-switcher.d.ts +0 -16
  1616. package/dist/synthetic-user-switcher.d.ts.map +0 -1
  1617. package/dist/synthetic-user-switcher.js +0 -134
  1618. package/dist/synthetic-user-switcher.js.map +0 -1
  1619. package/dist/synthetic-users.d.ts +0 -32
  1620. package/dist/synthetic-users.d.ts.map +0 -1
  1621. package/dist/synthetic-users.js +0 -124
  1622. package/dist/synthetic-users.js.map +0 -1
  1623. package/dist/testing/fixtures/basic/app.d.ts +0 -55
  1624. package/dist/testing/fixtures/basic/app.d.ts.map +0 -1
  1625. package/dist/testing/fixtures/basic/app.js +0 -176
  1626. package/dist/testing/fixtures/basic/app.js.map +0 -1
  1627. package/dist/testing/fixtures/basic/current.d.ts +0 -2
  1628. package/dist/testing/fixtures/basic/current.d.ts.map +0 -1
  1629. package/dist/testing/fixtures/basic/current.js +0 -6
  1630. package/dist/testing/fixtures/basic/current.js.map +0 -1
  1631. package/dist/testing/index.test.d.ts +0 -2
  1632. package/dist/testing/index.test.d.ts.map +0 -1
  1633. package/dist/testing/index.test.js +0 -234
  1634. package/dist/testing/index.test.js.map +0 -1
  1635. package/dist/testing/local-jazz-server.d.ts +0 -34
  1636. package/dist/testing/local-jazz-server.d.ts.map +0 -1
  1637. package/dist/testing/local-jazz-server.js +0 -313
  1638. package/dist/testing/local-jazz-server.js.map +0 -1
  1639. package/dist/worker/jazz-worker.d.ts +0 -9
  1640. package/dist/worker/jazz-worker.d.ts.map +0 -1
  1641. package/dist/worker/jazz-worker.js +0 -516
  1642. package/dist/worker/jazz-worker.js.map +0 -1
  1643. package/dist/worker/jazz-worker.ts +0 -581
  1644. package/dist/worker/worker-protocol.d.ts +0 -136
  1645. package/dist/worker/worker-protocol.d.ts.map +0 -1
  1646. package/dist/worker/worker-protocol.js +0 -7
  1647. package/dist/worker/worker-protocol.js.map +0 -1
@@ -1,776 +1,2520 @@
1
- /**
2
- * High-level database class for typed queries and mutations.
3
- *
4
- * Connects QueryBuilder to JazzClient for actual query execution.
5
- * Handles query translation, execution, and result transformation.
6
- *
7
- * Key design: Mutations are SYNC after WASM pre-loading.
8
- * - createDb() is async (pre-loads WASM module)
9
- * - insert/update/deleteFrom are sync (operate on in-memory WASM runtime)
10
- * - all/one are async (need storage I/O for queries)
11
- */
12
- import { JazzClient, loadWasmModule } from "./client.js";
13
- import { WorkerBridge } from "./worker-bridge.js";
1
+ import { clientScope } from "./client-scope.js";
2
+ import { registerPageDb } from "./page-handle.js";
3
+ import { isHistoryTable, resolveQueryTable } from "./history-relation.js";
4
+ import { Utf8Decoder } from "./utf8.js";
5
+ import { parseSnapshotRef } from "./snapshot-ref.js";
6
+ import { runtimeRandomBytes } from "./runtime-entropy.js";
7
+ import { GracefulShutdownSyncError } from "./graceful-shutdown-error.js";
8
+ import { accountToken, accountRegistry } from "../accounts/enrollment.js";
9
+ import { assertAccountConfig, copyAccountConfigAdmission } from "../accounts/config-capability.js";
10
+ import { SerializableWriteHandle, SerializableWriteResult, WriteResult, beginClientTransactionAfter, WriteHandle, createOpenTransactionId, setWriteWaitReadiness, isPublicQueryReadTier, rejectRemovedReadTier, normalizeFirstLoadRemoteWaitMs, resolveEffectiveQueryExecutionOptions, validateWriteWaitTimeout, WriteWaitTimeoutError, } from "./client.js";
11
+ import { sameSyncStatus } from "./sync-status.js";
14
12
  import { translateQuery } from "./query-adapter.js";
15
- import { transformRows } from "./row-transformer.js";
16
- import { toValueArray, toUpdateRecord } from "./value-converter.js";
17
- import { SubscriptionManager } from "./subscription-manager.js";
18
- import { resolveLocalAuthDefaults } from "./local-auth.js";
13
+ import { resolveQueryOutputTable } from "./query-output-table.js";
14
+ import { applyColumnTransforms, createRowTransformer, transformRow, unwrapValue, } from "./row-transformer.js";
15
+ import { getOwnerPreparation, runAfterPreparation, WritePreparation } from "./write-preparation.js";
16
+ import { nativeCoreErrorCode, unreadableTargetError } from "./native-runtime/native-error-code.js";
17
+ import { writeRow } from "./write-row.js";
18
+ import { ComputedReadState, MissingComputedDependency, columnTransformDependencies, computedColumnValues, dependencyContext, storedDependencyValues, } from "./column-transforms.js";
19
+ import { toValue, toWriteRecord } from "./value-converter.js";
20
+ import { RowChangeKind, SubscriptionManager, } from "./subscription-manager.js";
21
+ import { createAuthStateStore } from "./auth-state.js";
22
+ import { AuthRenewalBackoff } from "./auth-renewal-backoff.js";
23
+ import { parseJwtPayload, internalSessionFromVerifiedReservedJwtPayload, resolveClientInternalSessionSync, } from "./client-session.js";
24
+ import { createBrowserPhysicalDatabaseName, createBrowserStorageOwner, } from "./browser-worker-config.js";
25
+ import { createInspectorLocalQueryOptions, isInspectorLocalQueryOptions, } from "../internal/inspector-query.js";
26
+ import { authSecretSeedForMinting } from "./auth-secret-codec.js";
27
+ import { getDbInternalSession, getTrustedReservedSession, setDbInternalSession, setTrustedReservedSession, } from "./db-internal-session.js";
28
+ import { notifyLocalWrite } from "./local-write-observer.js";
19
29
  import { analyzeRelations } from "../codegen/relation-analyzer.js";
20
- import { TabLeaderElection } from "./tab-leader-election.js";
21
- function isPlainObject(value) {
22
- return typeof value === "object" && value !== null && !Array.isArray(value);
23
- }
24
- function normalizeBuiltQuery(raw, fallbackTable) {
25
- const table = typeof raw.table === "string" ? raw.table : fallbackTable;
26
- const conditions = Array.isArray(raw.conditions)
27
- ? raw.conditions.filter((condition) => isPlainObject(condition) &&
28
- typeof condition.column === "string" &&
29
- typeof condition.op === "string")
30
- : [];
31
- const includes = isPlainObject(raw.includes) ? raw.includes : {};
32
- const orderBy = Array.isArray(raw.orderBy)
33
- ? raw.orderBy.filter((entry) => Array.isArray(entry) &&
34
- entry.length === 2 &&
35
- typeof entry[0] === "string" &&
36
- (entry[1] === "asc" || entry[1] === "desc"))
37
- : [];
38
- const hops = Array.isArray(raw.hops)
39
- ? raw.hops.filter((hop) => typeof hop === "string")
40
- : [];
41
- const gather = isPlainObject(raw.gather) &&
42
- Number.isInteger(raw.gather.max_depth) &&
43
- raw.gather.max_depth > 0 &&
44
- typeof raw.gather.step_table === "string" &&
45
- typeof raw.gather.step_current_column === "string" &&
46
- Array.isArray(raw.gather.step_conditions) &&
47
- Array.isArray(raw.gather.step_hops)
48
- ? {
49
- max_depth: raw.gather.max_depth,
50
- step_table: raw.gather.step_table,
51
- step_current_column: raw.gather.step_current_column,
52
- step_conditions: raw.gather.step_conditions.filter((condition) => isPlainObject(condition) &&
53
- typeof condition.column === "string" &&
54
- typeof condition.op === "string"),
55
- step_hops: raw.gather.step_hops.filter((hop) => typeof hop === "string"),
30
+ import { normalizeBuiltQuery, } from "./query-builder-shape.js";
31
+ import { BrowserConnectionManager, DirectConnectionManager, } from "./connection-manager/index.js";
32
+ import { toError } from "./util.js";
33
+ import { isThinDb, upgradeDbToLocalFirst } from "./local-first-upgrade.js";
34
+ import { DbReplacedError } from "./db-replaced-error.js";
35
+ import { RuntimeClosedError } from "./runtime-closed-error.js";
36
+ function resolveStorageDriver(driver) {
37
+ return driver ?? { type: "persistent" };
38
+ }
39
+ function trimOptionalString(value) {
40
+ if (typeof value !== "string") {
41
+ return null;
42
+ }
43
+ const trimmed = value.trim();
44
+ return trimmed.length > 0 ? trimmed : null;
45
+ }
46
+ /** @internal Resolve the caller-selected logical base for browser persistence. */
47
+ export function resolvePersistentDbBaseName(config) {
48
+ const driver = resolveStorageDriver(config.driver);
49
+ const explicitDbName = trimOptionalString((driver.type === "persistent" ? driver.dbName : undefined) ?? config.dbName);
50
+ return explicitDbName ?? clientScope(config);
51
+ }
52
+ /** @internal Derive the physical browser persistence namespace for this Db config. */
53
+ export function resolveDefaultPersistentDbName(config) {
54
+ return createBrowserPhysicalDatabaseName(config, resolvePersistentDbBaseName(config));
55
+ }
56
+ /**
57
+ * Lower product options to the internal native-read controls. This is a
58
+ * runtime boundary, rather than merely a TypeScript one: JavaScript callers
59
+ * must not be able to select local-only propagation or a deferred own-write
60
+ * overlay by adding private fields to an options object.
61
+ */
62
+ function lowerPublicDbQueryOptions(options) {
63
+ if (!options)
64
+ return undefined;
65
+ const candidate = options;
66
+ rejectRemovedReadTier(candidate.tier);
67
+ const lowered = {};
68
+ if (isPublicQueryReadTier(candidate.tier))
69
+ lowered.tier = candidate.tier;
70
+ const firstLoadRemoteWaitMs = normalizeFirstLoadRemoteWaitMs(candidate.firstLoadRemoteWaitMs);
71
+ if (firstLoadRemoteWaitMs !== undefined)
72
+ lowered.firstLoadRemoteWaitMs = firstLoadRemoteWaitMs;
73
+ if (candidate.branch !== undefined)
74
+ lowered.branch = candidate.branch;
75
+ if (candidate.base !== undefined)
76
+ lowered.base = candidate.base;
77
+ const splices = candidate.splices;
78
+ if (splices !== undefined) {
79
+ if (!Array.isArray(splices) || !splices.every((column) => typeof column === "string")) {
80
+ throw new Error("splices must be an array of column names.");
56
81
  }
57
- : undefined;
82
+ if (splices.length > 0)
83
+ lowered.splices = [...splices];
84
+ }
85
+ if (isInspectorLocalQueryOptions(options))
86
+ lowered.tier = "local-only";
87
+ return lowered;
88
+ }
89
+ const dbSubscriptionSources = new WeakMap();
90
+ /**
91
+ * What a Db hands to its successor after the local-first upgrade: everything
92
+ * an app or framework calls. Its shutdown, and the internals its own runtime
93
+ * needs to finish uploading, stay with it.
94
+ */
95
+ const FORWARDED_TO_SUCCESSOR = [
96
+ "allFromInspectorAttachment",
97
+ "subscribeFromInspectorAttachment",
98
+ "currentRuntime",
99
+ "prefetchRuntimeQueries",
100
+ "refreshAccountAuth",
101
+ "updateAuthToken",
102
+ "updateCookieSession",
103
+ "getAuthState",
104
+ "getLocalFirstIdentityProof",
105
+ "onAuthChanged",
106
+ "onMutationError",
107
+ "textAnchors",
108
+ "getSyncStatus",
109
+ "waitForSync",
110
+ "getConfig",
111
+ "setDevMode",
112
+ "disconnect",
113
+ "reconnect",
114
+ "getActiveQuerySubscriptions",
115
+ "onActiveQuerySubscriptionsChange",
116
+ "getRuntimeSchema",
117
+ "openInspectorControlPort",
118
+ "insert",
119
+ "insertStreaming",
120
+ "updateStreaming",
121
+ "upsertStreaming",
122
+ "restore",
123
+ "upsert",
124
+ "update",
125
+ "delete",
126
+ "canInsert",
127
+ "canRead",
128
+ "canUpdate",
129
+ "canDelete",
130
+ "createTransaction",
131
+ "captureSnapshot",
132
+ "beginTransaction",
133
+ "beginSerializableTransaction",
134
+ "transaction",
135
+ "serializableTransaction",
136
+ "upgradeToLocalFirst",
137
+ "deleteClientStorage",
138
+ "wipeClientStorage",
139
+ "logout",
140
+ "all",
141
+ "allInternal",
142
+ "one",
143
+ "subscribe",
144
+ "subscribeDelta",
145
+ ];
146
+ /** @internal Retrieve the incremental source associated with a public Db. */
147
+ export function getDbSubscriptionSource(db) {
148
+ const source = dbSubscriptionSources.get(db);
149
+ if (!source)
150
+ throw new Error("Jazz Db is missing its internal subscription source.");
151
+ return source;
152
+ }
153
+ function branchColumn(schema, name) {
154
+ const matches = Object.values(schema)
155
+ .flatMap((table) => table.columns)
156
+ .filter((column) => column.name === name);
157
+ const column = matches[0];
158
+ if (!column)
159
+ throw new Error(`Unknown branch column "${name}".`);
160
+ return column;
161
+ }
162
+ function normalizeBranchSelector(schema, tableName, input, scope) {
163
+ const table = resolveQueryTable(schema, tableName);
164
+ if (!table)
165
+ throw new Error(`Unknown table "${tableName}".`);
166
+ const tableColumns = table.branchBy ?? [];
167
+ const expected = scope === "table"
168
+ ? new Set(tableColumns)
169
+ : new Set(Object.values(schema).flatMap((candidate) => candidate.branchBy ?? []));
170
+ const qualified = typeof input === "object" && input !== null && !Array.isArray(input)
171
+ ? input
172
+ : expected.size === 1
173
+ ? { [[...expected][0]]: input }
174
+ : (() => {
175
+ throw new Error(`A scalar branch selector requires exactly one ${scope === "table" ? "table" : "schema"} branch column.`);
176
+ })();
177
+ const actual = Object.keys(qualified);
178
+ if (actual.length !== expected.size || actual.some((name) => !expected.has(name))) {
179
+ throw new Error(`Branch selector must provide exactly: ${[...expected].sort().join(", ") || "no columns"}.`);
180
+ }
181
+ return {
182
+ values: Object.fromEntries(actual.map((name) => [
183
+ name,
184
+ toValue(qualified[name], branchColumn(schema, name).column_type),
185
+ ])),
186
+ };
187
+ }
188
+ function normalizeBranchView(schema, tableName, branch, base) {
189
+ const head = normalizeBranchSelector(schema, tableName, branch, "schema");
190
+ if (base === undefined)
191
+ return { head };
192
+ if (Array.isArray(base)) {
193
+ return {
194
+ head,
195
+ base: {
196
+ kind: "snapshot",
197
+ branch: normalizeBranchSelector(schema, tableName, base[0], "schema"),
198
+ snapshot: parseSnapshotRef(base[1]),
199
+ },
200
+ };
201
+ }
202
+ return {
203
+ head,
204
+ base: {
205
+ kind: "current",
206
+ branch: normalizeBranchSelector(schema, tableName, base, "schema"),
207
+ },
208
+ };
209
+ }
210
+ function normalizeSelectorOptions(schema, tableName, options) {
211
+ if (!options)
212
+ return undefined;
213
+ const { branch, ...rest } = options;
214
+ return branch === undefined
215
+ ? rest
216
+ : {
217
+ ...rest,
218
+ branch: normalizeBranchSelector(schema, tableName, branch, "table"),
219
+ };
220
+ }
221
+ function normalizeViewOptions(schema, tableName, options) {
222
+ if (!options)
223
+ return undefined;
224
+ const { branch, base, ...rest } = options;
225
+ if (branch === undefined) {
226
+ if (base !== undefined)
227
+ throw new Error("A branch base requires a branch head.");
228
+ return rest;
229
+ }
58
230
  return {
59
- table,
60
- conditions,
61
- includes,
62
- orderBy,
63
- limit: typeof raw.limit === "number" ? raw.limit : undefined,
64
- offset: typeof raw.offset === "number" ? raw.offset : undefined,
65
- hops,
66
- gather,
231
+ ...rest,
232
+ branch: normalizeBranchView(schema, tableName, branch, base),
67
233
  };
68
234
  }
69
- function resolveHopOutputTable(schema, startTable, hops) {
70
- if (hops.length === 0) {
71
- return startTable;
235
+ export function limitQueryToOne(query) {
236
+ return {
237
+ get _table() {
238
+ return query._table;
239
+ },
240
+ get _schema() {
241
+ return query._schema;
242
+ },
243
+ get _columnTransforms() {
244
+ return query._columnTransforms;
245
+ },
246
+ get _columnTransformsByTable() {
247
+ return query._columnTransformsByTable;
248
+ },
249
+ get _rowType() {
250
+ return query._rowType;
251
+ },
252
+ _build() {
253
+ const builtQuery = JSON.parse(query._build());
254
+ builtQuery.limit = 1;
255
+ return JSON.stringify(builtQuery);
256
+ },
257
+ };
258
+ }
259
+ function queryUsesRelationTraversal(builtQuery) {
260
+ return (builtQuery.hops.length > 0 ||
261
+ builtQuery.gather !== undefined ||
262
+ Object.keys(builtQuery.includes).length > 0);
263
+ }
264
+ function trimSubscriptionTraceStack(stack) {
265
+ if (!stack) {
266
+ return stack;
267
+ }
268
+ const lines = stack.split("\n");
269
+ if (lines.length <= 1) {
270
+ return stack;
271
+ }
272
+ const isInternalFrame = (line) => {
273
+ return (line.includes("Db.registerActiveQuerySubscriptionTrace") ||
274
+ line.includes("Db.subscribe") ||
275
+ line.includes("SubscriptionsOrchestrator.ensureEntryForKey") ||
276
+ line.includes("SubscriptionsOrchestrator.getCacheEntry") ||
277
+ line.includes("/node_modules/") ||
278
+ line.includes("react-dom") ||
279
+ line.includes("react_stack_bottom_frame"));
280
+ };
281
+ const firstOriginIndex = lines.findIndex((line, index) => index > 0 && !isInternalFrame(line));
282
+ if (firstOriginIndex <= 0) {
283
+ return stack;
284
+ }
285
+ return [lines[0], ...lines.slice(firstOriginIndex)].join("\n");
286
+ }
287
+ function cloneActiveQuerySubscriptionTrace(trace) {
288
+ return {
289
+ ...trace,
290
+ branches: [...trace.branches],
291
+ };
292
+ }
293
+ function requireSchemaWithTable(preferredSchema, tableName) {
294
+ if (resolveQueryTable(preferredSchema, tableName)) {
295
+ return preferredSchema;
72
296
  }
73
- const relations = analyzeRelations(schema);
74
- let currentTable = startTable;
75
- for (const hopName of hops) {
76
- const candidates = relations.get(currentTable) ?? [];
77
- const relation = candidates.find((candidate) => candidate.name === hopName);
78
- if (!relation) {
79
- throw new Error(`Unknown relation "${hopName}" on table "${currentTable}"`);
297
+ throw new Error(`Query schema is missing table "${tableName}".`);
298
+ }
299
+ function normalizeQueryOptions(schema, table, options) {
300
+ return normalizeViewOptions(schema, table, options) ?? {};
301
+ }
302
+ /** Splices are only defined for plain TEXT and BYTEA columns of the result table. */
303
+ function assertSpliceableColumns(schema, table, query, columns) {
304
+ const descriptors = resolveQueryTable(schema, table)?.columns ?? [];
305
+ for (const column of columns) {
306
+ const descriptor = descriptors.find((candidate) => candidate.name === column);
307
+ if (!descriptor)
308
+ throw new Error(`splices: "${column}" is not a column of "${table}".`);
309
+ const type = descriptor.column_type.type;
310
+ if (type !== "Text" && type !== "Bytea") {
311
+ throw new Error(`splices: column "${column}" is ${type}; splices are not supported yet for columns other than TEXT and BYTEA.`);
312
+ }
313
+ if (query._columnTransforms?.[column]) {
314
+ throw new Error(`splices: column "${column}" has a column transform; splices are not supported yet for transformed columns.`);
80
315
  }
81
- currentTable = relation.toTable;
82
316
  }
83
- return currentTable;
84
317
  }
85
- function resolveBroadcastChannelCtor() {
86
- const ctor = globalThis.BroadcastChannel;
87
- if (typeof ctor !== "function")
88
- return null;
89
- return ctor;
318
+ /**
319
+ * A range-selected splice column must be read in part: a computed or
320
+ * transformed column that depends on it makes the engine read it whole and
321
+ * TypeScript cut the window, so the engine's splices would be in whole-value
322
+ * coordinates while the rows show the window.
323
+ */
324
+ function assertSplicesReadInPart(built, physical, columns) {
325
+ for (const column of columns) {
326
+ if (Object.hasOwn(built.partialSelect, column) &&
327
+ !Object.hasOwn(physical.partialSelect, column))
328
+ throw new Error(`splices: column "${column}" is selected in part, but a computed or transformed column depends on it, so it is read whole; splices are not supported yet for such columns.`);
329
+ }
330
+ }
331
+ function assertWritableTable(table) {
332
+ if (isHistoryTable(table._table)) {
333
+ throw new Error(`History table "${table._table}" is read-only`);
334
+ }
90
335
  }
91
- function isStringArray(value) {
92
- return Array.isArray(value) && value.every((entry) => typeof entry === "string");
336
+ /** Apply the table's input transforms, then encode `data` as the write record for `operation`. */
337
+ function writeRecord(operation, table, data) {
338
+ return toWriteRecordForOperation(operation, transformInputColumns(table, data), table._schema, table._table);
93
339
  }
94
- function isTabSyncMessage(value) {
95
- if (typeof value !== "object" || value === null)
96
- return false;
97
- const message = value;
98
- if (message.type === "follower-sync") {
99
- return (typeof message.fromTabId === "string" &&
100
- typeof message.toLeaderTabId === "string" &&
101
- typeof message.term === "number" &&
102
- isStringArray(message.payload));
103
- }
104
- if (message.type === "leader-sync") {
105
- return (typeof message.fromLeaderTabId === "string" &&
106
- typeof message.toTabId === "string" &&
107
- typeof message.term === "number" &&
108
- isStringArray(message.payload));
109
- }
110
- if (message.type === "follower-close") {
111
- return (typeof message.fromTabId === "string" &&
112
- typeof message.toLeaderTabId === "string" &&
113
- typeof message.term === "number");
340
+ function toWriteRecordForOperation(operation, data, schema, tableName) {
341
+ try {
342
+ return toWriteRecord(data, schema, tableName);
114
343
  }
115
- return false;
344
+ catch (error) {
345
+ const message = error instanceof Error ? error.message : String(error);
346
+ throw new Error(`${operation} failed: WriteError("${escapeWriteErrorReason(message)}")`);
347
+ }
348
+ }
349
+ function isPartialLargeValueUpdate(value) {
350
+ return typeof value === "object" && value !== null && ("splices" in value || "edits" in value);
351
+ }
352
+ function requireRecord(value, message) {
353
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
354
+ throw new Error(message);
355
+ }
356
+ return value;
357
+ }
358
+ function requireNonNegativeCoordinate(value, label, column) {
359
+ const coordinate = Number(value);
360
+ if (!Number.isSafeInteger(coordinate) || coordinate < 0) {
361
+ throw new Error(`${label} for "${column}" must be a non-negative safe integer.`);
362
+ }
363
+ return coordinate;
116
364
  }
117
- function isLeaderDebugEnabled() {
118
- const globalFlag = globalThis.__JAZZ_LEADER_DEBUG__;
119
- if (globalFlag === true)
365
+ function requirePageRange(from, to, column) {
366
+ if (from > to) {
367
+ throw new Error(`Large-value page for "${column}" must have from <= to.`);
368
+ }
369
+ }
370
+ /**
371
+ * An `update` call's replacements and wire descriptors: its `applyDiffs`,
372
+ * and each `editedFrom` column's replacement as a text edit of that value.
373
+ */
374
+ function lowerUpdate(table, data, options) {
375
+ const descriptors = lowerApplyDiffs(table, data, options?.applyDiffs);
376
+ const editedFrom = options?.editedFrom;
377
+ if (editedFrom === undefined) {
378
+ rejectIncompleteDependencies(table, data, Object.keys(options?.applyDiffs ?? {}));
379
+ return { replacements: data, descriptors };
380
+ }
381
+ if (typeof editedFrom !== "object" || editedFrom === null || Array.isArray(editedFrom)) {
382
+ throw new Error("update option editedFrom must be an object keyed by column name.");
383
+ }
384
+ const replacements = { ...data };
385
+ const edited = [];
386
+ for (const [column, from] of Object.entries(editedFrom)) {
387
+ if (from === undefined)
388
+ continue;
389
+ const transform = table._columnTransforms?.[column];
390
+ if (transform && !transform.computed) {
391
+ throw new Error(`update option editedFrom is not supported yet on "${column}", which has a transform.`);
392
+ }
393
+ const text = replacements[column];
394
+ if (typeof text !== "string" || typeof from !== "string") {
395
+ throw new Error(`update option editedFrom.${column} needs a string, and a string replacement for "${column}".`);
396
+ }
397
+ delete replacements[column];
398
+ edited.push(column);
399
+ descriptors.push({ kind: "text_edit", column, text, edited_from: from });
400
+ }
401
+ rejectIncompleteDependencies(table, replacements, [
402
+ ...Object.keys(options?.applyDiffs ?? {}),
403
+ ...edited,
404
+ ]);
405
+ return { replacements, descriptors };
406
+ }
407
+ /** `options` without `editedFrom`, which {@link lowerUpdate} turned into descriptors. */
408
+ function withoutEditedFrom(options) {
409
+ if (options?.editedFrom === undefined)
410
+ return options;
411
+ const { editedFrom: _, ...rest } = options;
412
+ return rest;
413
+ }
414
+ /** Validate an `update` call's `applyDiffs` option and lower it to wire descriptors. */
415
+ function lowerApplyDiffs(table, data, diffs) {
416
+ if (diffs === undefined)
417
+ return [];
418
+ if (typeof diffs !== "object" || diffs === null || Array.isArray(diffs)) {
419
+ throw new Error("update option applyDiffs must be an object keyed by column name.");
420
+ }
421
+ if (Object.keys(data).some((column) => Object.hasOwn(diffs, column))) {
422
+ throw new Error("update replacements and applyDiffs must not both specify the same column.");
423
+ }
424
+ const { ordinary, descriptors } = splitLargeValueUpdate(diffs, table._schema, table._table);
425
+ if (Object.keys(ordinary).length > 0) {
426
+ throw new Error("update option applyDiffs accepts only field diff descriptors, not whole-column values.");
427
+ }
428
+ return descriptors;
429
+ }
430
+ function splitLargeValueUpdate(data, schema, table) {
431
+ const ordinary = {};
432
+ const descriptors = [];
433
+ const columns = schema[table]?.columns;
434
+ if (!columns)
435
+ throw new Error(`Unknown table "${table}"`);
436
+ for (const [column, value] of Object.entries(data)) {
437
+ if (!isPartialLargeValueUpdate(value)) {
438
+ ordinary[column] = value;
439
+ continue;
440
+ }
441
+ const type = columns.find((candidate) => candidate.name === column)?.column_type;
442
+ if (!type)
443
+ throw new Error(`Unknown column "${column}" in table "${table}"`);
444
+ if ("splices" in value && "within" in value) {
445
+ const within = requireRecord(value.within, `Large-value update "${column}" has an invalid page.`);
446
+ const splices = value.splices;
447
+ if (!Array.isArray(splices))
448
+ throw new Error(`Large-value update "${column}" has invalid splices.`);
449
+ let page;
450
+ if ("fromUtf8" in within || "toUtf8" in within) {
451
+ if (type.type !== "Text")
452
+ throw new Error(`UTF-8 splice requires a Text column, got "${column}".`);
453
+ const from = requireNonNegativeCoordinate(within.fromUtf8, "fromUtf8", column);
454
+ const to = requireNonNegativeCoordinate(within.toUtf8, "toUtf8", column);
455
+ requirePageRange(from, to, column);
456
+ page = { kind: "text_utf8", from, to };
457
+ }
458
+ else if (type.type === "Bytea") {
459
+ const from = requireNonNegativeCoordinate(within.from, "from", column);
460
+ const to = requireNonNegativeCoordinate(within.to, "to", column);
461
+ requirePageRange(from, to, column);
462
+ page = { kind: "bytes", from, to };
463
+ }
464
+ else if (type.type === "Text") {
465
+ const from = requireNonNegativeCoordinate(within.from, "from", column);
466
+ const to = requireNonNegativeCoordinate(within.to, "to", column);
467
+ requirePageRange(from, to, column);
468
+ page = { kind: "text_utf16", from, to };
469
+ }
470
+ else {
471
+ throw new Error(`Splice requires a Text or Bytea column, got "${column}".`);
472
+ }
473
+ descriptors.push({
474
+ kind: "splice",
475
+ column,
476
+ within: page,
477
+ splices: splices.map((splice) => {
478
+ const item = requireRecord(splice, `Large-value splice for "${column}" is invalid.`);
479
+ const utf8 = page.kind === "text_utf8";
480
+ const at = requireNonNegativeCoordinate(utf8 ? item.atUtf8 : item.at, "at", column);
481
+ const deleted = requireNonNegativeCoordinate(utf8 ? item.deleteUtf8 : item.delete, "delete", column);
482
+ const insert = item.insert;
483
+ let bytes;
484
+ if (page.kind === "bytes") {
485
+ if (!(insert instanceof Uint8Array)) {
486
+ throw new Error(`Byte splice insert for "${column}" must be a Uint8Array.`);
487
+ }
488
+ bytes = [...insert];
489
+ }
490
+ else {
491
+ if (typeof insert !== "string") {
492
+ throw new Error(`Text splice insert for "${column}" must be a string.`);
493
+ }
494
+ bytes = [...new TextEncoder().encode(insert)];
495
+ }
496
+ return { at, delete: deleted, insert: bytes };
497
+ }),
498
+ });
499
+ continue;
500
+ }
501
+ if ("edits" in value) {
502
+ if (type.type !== "Json")
503
+ throw new Error(`JSON set requires a JSON column, got "${column}".`);
504
+ if (!Array.isArray(value.edits))
505
+ throw new Error(`JSON update "${column}" has invalid edits.`);
506
+ descriptors.push({
507
+ kind: "json_set",
508
+ column,
509
+ edits: value.edits.map((edit) => {
510
+ const item = requireRecord(edit, `JSON update edit for "${column}" is invalid.`);
511
+ if (item.op !== "set" || typeof item.at !== "string") {
512
+ throw new Error(`JSON update "${column}" supports only { op: "set", at, value } edits.`);
513
+ }
514
+ return { at: item.at, value: item.value };
515
+ }),
516
+ });
517
+ continue;
518
+ }
519
+ ordinary[column] = value;
520
+ }
521
+ return { ordinary, descriptors };
522
+ }
523
+ function utf16Boundary(text, offset) {
524
+ if (offset < 0 || offset > text.length)
525
+ return false;
526
+ if (offset === 0 || offset === text.length)
120
527
  return true;
121
- try {
122
- if (typeof localStorage !== "undefined") {
123
- return localStorage.getItem("jazz:leader-debug") === "1";
528
+ const before = text.charCodeAt(offset - 1);
529
+ const after = text.charCodeAt(offset);
530
+ return !(before >= 0xd800 && before <= 0xdbff && after >= 0xdc00 && after <= 0xdfff);
531
+ }
532
+ function jsonPointerToken(token) {
533
+ let decoded = "";
534
+ for (let index = 0; index < token.length; index += 1) {
535
+ const character = token[index];
536
+ if (character !== "~") {
537
+ decoded += character;
538
+ continue;
124
539
  }
540
+ const escape = token[++index];
541
+ if (escape === "0")
542
+ decoded += "~";
543
+ else if (escape === "1")
544
+ decoded += "/";
545
+ else
546
+ throw new Error("JSON pointer has an invalid escape.");
125
547
  }
126
- catch {
127
- // Ignore storage access errors (e.g. privacy mode / unavailable storage).
548
+ return decoded;
549
+ }
550
+ function jsonPointerValue(value, pointer) {
551
+ if (pointer === "")
552
+ return value;
553
+ if (!pointer.startsWith("/"))
554
+ throw new Error("JSON pointer must be empty or begin with '/'.");
555
+ let current = value;
556
+ for (const rawToken of pointer.slice(1).split("/")) {
557
+ const token = jsonPointerToken(rawToken);
558
+ if (Array.isArray(current)) {
559
+ if (!/^(0|[1-9]\d*)$/.test(token)) {
560
+ throw new Error("JSON array pointer token is not an index.");
561
+ }
562
+ const index = Number(token);
563
+ if (!Number.isSafeInteger(index) || index >= current.length) {
564
+ throw new Error("JSON pointer path does not exist.");
565
+ }
566
+ current = current[index];
567
+ }
568
+ else if (typeof current === "object" && current !== null && Object.hasOwn(current, token)) {
569
+ current = current[token];
570
+ }
571
+ else {
572
+ throw new Error("JSON pointer path does not exist.");
573
+ }
128
574
  }
129
- return false;
575
+ return current;
130
576
  }
131
577
  /**
132
- * High-level database interface for typed queries and mutations.
133
- *
134
- * Usage:
135
- * ```typescript
136
- * const db = await createDb({ appId: "my-app", driver });
137
- *
138
- * // Sync mutations (after WASM is pre-loaded)
139
- * const id = db.insert(app.todos, { title: "Buy milk", done: false });
140
- * db.update(app.todos, id, { done: true });
141
- * db.deleteFrom(app.todos, id);
142
- *
143
- * // Async queries (need storage I/O)
144
- * const todos = await db.all(app.todos.where({ done: false }));
145
- * const todo = await db.one(app.todos.where({ id }));
146
- *
147
- * // Subscriptions
148
- * const unsubscribe = db.subscribeAll(app.todos, (delta) => {
149
- * console.log("All todos:", delta.all);
150
- * console.log("Changes:", delta.delta);
151
- * });
152
- * ```
578
+ * The engine reads each partial selection of the physical query only in part
579
+ * (SPEC 19.12). A column a transform also depends on is read whole instead,
580
+ * and its visible selection is taken here from the whole value.
153
581
  */
154
- export class Db {
155
- clients = new Map();
156
- config;
157
- wasmModule;
158
- workerBridge = null;
159
- worker = null;
160
- bridgeReady = null;
161
- primaryDbName = null;
162
- workerDbName = null;
163
- leaderElection = null;
164
- leaderElectionUnsubscribe = null;
165
- tabRole = "follower";
166
- tabId = null;
167
- currentLeaderTabId = null;
168
- currentLeaderTerm = 0;
169
- syncChannel = null;
170
- leaderPeerIds = new Set();
171
- activeRemoteLeaderTabId = null;
172
- workerReconfigure = Promise.resolve();
173
- isShuttingDown = false;
174
- lifecycleHooksAttached = false;
175
- onSyncChannelMessage = (event) => {
176
- this.handleSyncChannelMessage(event.data);
177
- };
178
- onVisibilityChange = () => {
179
- if (typeof document === "undefined")
180
- return;
181
- const hidden = document.visibilityState === "hidden";
182
- this.sendLifecycleHint(hidden ? "visibility-hidden" : "visibility-visible");
183
- };
184
- onPageHide = () => {
185
- this.sendLifecycleHint("pagehide");
582
+ function applyPartialValueSelections(row, selections) {
583
+ if (Object.keys(selections).length === 0 || typeof row !== "object" || row === null)
584
+ return row;
585
+ const projected = { ...row };
586
+ for (const [column, selection] of Object.entries(selections)) {
587
+ const value = projected[column];
588
+ if ("at" in selection) {
589
+ projected[column] = jsonPointerValue(value, selection.at);
590
+ continue;
591
+ }
592
+ if (value instanceof Uint8Array) {
593
+ if ("fromUtf8" in selection || selection.from > selection.to || selection.to > value.length) {
594
+ throw new Error(`Byte range for "${column}" is out of bounds.`);
595
+ }
596
+ projected[column] = value.slice(selection.from, selection.to);
597
+ continue;
598
+ }
599
+ if (typeof value !== "string") {
600
+ throw new Error(`Large-value selection for "${column}" has an incompatible column type.`);
601
+ }
602
+ if ("fromUtf8" in selection) {
603
+ const bytes = new TextEncoder().encode(value);
604
+ if (selection.fromUtf8 > selection.toUtf8 ||
605
+ selection.toUtf8 > bytes.length ||
606
+ (selection.fromUtf8 < bytes.length &&
607
+ (bytes[selection.fromUtf8] & 0b1100_0000) === 0b1000_0000) ||
608
+ (selection.toUtf8 < bytes.length &&
609
+ (bytes[selection.toUtf8] & 0b1100_0000) === 0b1000_0000)) {
610
+ throw new Error(`UTF-8 range for "${column}" splits a code point or is out of bounds.`);
611
+ }
612
+ projected[column] = new Utf8Decoder({ fatal: true }).decode(bytes.slice(selection.fromUtf8, selection.toUtf8));
613
+ continue;
614
+ }
615
+ if (selection.from > selection.to ||
616
+ !utf16Boundary(value, selection.from) ||
617
+ !utf16Boundary(value, selection.to)) {
618
+ throw new Error(`UTF-16 range for "${column}" splits a surrogate pair or is out of bounds.`);
619
+ }
620
+ projected[column] = value.slice(selection.from, selection.to);
621
+ }
622
+ return projected;
623
+ }
624
+ function escapeWriteErrorReason(message) {
625
+ return message.replaceAll('"', '\\"');
626
+ }
627
+ function resolveOutputColumnTransforms(query, inputTable, outputTable) {
628
+ return (query._columnTransformsByTable?.[outputTable] ??
629
+ (inputTable === outputTable ? query._columnTransforms : undefined));
630
+ }
631
+ function prepareTransformRead(query, built, outputTable, computedState) {
632
+ const outputTransforms = resolveOutputColumnTransforms(query, built.table, outputTable);
633
+ const outputIncludes = outputTable === built.table || !Object.keys(built.includes).length ? built.includes : {};
634
+ const hasIncludes = Object.keys(outputIncludes).length > 0;
635
+ if (!outputTransforms && (!query._columnTransformsByTable || !hasIncludes)) {
636
+ const decode = createRowTransformer(query._schema, outputTable, outputIncludes, built.select);
637
+ return {
638
+ computedState: undefined,
639
+ version: 0,
640
+ physical: outputIncludes === built.includes ? built : { ...built, includes: outputIncludes },
641
+ // The engine applies every partial selection of this physical query.
642
+ transform: decode,
643
+ };
644
+ }
645
+ const relations = hasIncludes ? analyzeRelations(query._schema) : undefined;
646
+ const prepare = (table, select, includes, partialSelect) => {
647
+ const transforms = query._columnTransformsByTable?.[table] ??
648
+ (table === outputTable ? outputTransforms : undefined);
649
+ let physical = select;
650
+ let partial = partialSelect;
651
+ const selectAll = !select.length || select.includes("*");
652
+ let visibleTransforms;
653
+ let dependencies;
654
+ let hidden;
655
+ let computed;
656
+ const addDependency = (dependency) => {
657
+ if (transforms?.[dependency]?.computed)
658
+ return;
659
+ (dependencies ??= new Set()).add(dependency);
660
+ if (!selectAll && dependency !== "id" && !physical.includes(dependency)) {
661
+ if (physical === select)
662
+ physical = [...select];
663
+ physical.push(dependency);
664
+ (hidden ??= []).push(dependency);
665
+ }
666
+ if (Object.hasOwn(partial, dependency)) {
667
+ if (partial === partialSelect)
668
+ partial = { ...partialSelect };
669
+ delete partial[dependency];
670
+ }
671
+ };
672
+ if (transforms && select.some((column) => transforms[column]?.computed))
673
+ physical = select.filter((column) => !transforms[column]?.computed);
674
+ if (transforms)
675
+ for (const column of selectAll ? Object.keys(transforms) : select) {
676
+ if (!Object.hasOwn(transforms, column))
677
+ continue;
678
+ (visibleTransforms ??= {})[column] = transforms[column];
679
+ if (transforms[column].computed) {
680
+ computedState ??= new ComputedReadState();
681
+ (computed ??= []).push(column);
682
+ for (const dependency of computedState.storedColumns(transforms, column))
683
+ addDependency(dependency);
684
+ }
685
+ else {
686
+ for (const dependency of transforms[column].dependsOn ?? [])
687
+ addDependency(dependency);
688
+ }
689
+ }
690
+ if (!selectAll && !physical.length)
691
+ physical = ["id"];
692
+ let preparedIncludes = includes;
693
+ const finishIncludes = [];
694
+ for (const [name, include] of Object.entries(includes)) {
695
+ const target = relations?.get(table)?.find((relation) => relation.name === name)?.toTable;
696
+ if (!target)
697
+ continue;
698
+ const prepared = prepare(target, include.select, include.includes, include.partialSelect);
699
+ if (prepared.select !== include.select ||
700
+ prepared.includes !== include.includes ||
701
+ prepared.partialSelect !== include.partialSelect) {
702
+ if (preparedIncludes === includes)
703
+ preparedIncludes = { ...includes };
704
+ preparedIncludes[name] = {
705
+ ...include,
706
+ select: prepared.select,
707
+ includes: prepared.includes,
708
+ partialSelect: prepared.partialSelect,
709
+ };
710
+ }
711
+ if (prepared.finish)
712
+ finishIncludes.push([name, prepared.finish]);
713
+ }
714
+ const dependencyColumns = dependencies ? [...dependencies] : noWriteDependencies;
715
+ const hasPartial = Object.keys(partialSelect).length > 0;
716
+ // Selections the engine did not apply: those whose column it read whole.
717
+ const wholeRead = Object.fromEntries(Object.entries(partialSelect).filter(([column]) => !Object.hasOwn(partial, column)));
718
+ const sliceWhole = Object.keys(wholeRead).length > 0;
719
+ const excluded = Object.keys(includes);
720
+ return {
721
+ select: physical,
722
+ includes: preparedIncludes,
723
+ partialSelect: partial,
724
+ finish: visibleTransforms || hasPartial || finishIncludes.length
725
+ ? (row) => {
726
+ const stored = computed
727
+ ? { ...row }
728
+ : visibleTransforms
729
+ ? storedDependencyValues(dependencyColumns, row)
730
+ : undefined;
731
+ const appValues = computed
732
+ ? computedColumnValues(transforms, computed, stored, computedState, partial)
733
+ : undefined;
734
+ const result = sliceWhole ? applyPartialValueSelections(row, wholeRead) : row;
735
+ if (visibleTransforms)
736
+ applyColumnTransforms(result, visibleTransforms, excluded, stored, appValues, hasPartial ? partialSelect : undefined);
737
+ if (computed)
738
+ for (const column of computed)
739
+ result[column] = appValues.get(column);
740
+ for (const [name, finish] of finishIncludes) {
741
+ const value = result[name];
742
+ if (Array.isArray(value))
743
+ for (let i = 0; i < value.length; i++)
744
+ value[i] = finish(value[i]);
745
+ else if (value && typeof value === "object")
746
+ result[name] = finish(value);
747
+ }
748
+ if (hidden)
749
+ for (const column of hidden)
750
+ delete result[column];
751
+ return result;
752
+ }
753
+ : undefined,
754
+ };
186
755
  };
187
- onPageFreeze = () => {
188
- this.sendLifecycleHint("freeze");
756
+ const prepared = prepare(outputTable, built.select, outputIncludes, built.partialSelect);
757
+ const decode = createRowTransformer(query._schema, outputTable, prepared.includes, prepared.select, undefined, false, relations);
758
+ return {
759
+ computedState,
760
+ version: computedState?.version ?? 0,
761
+ physical: prepared.select === built.select &&
762
+ prepared.partialSelect === built.partialSelect &&
763
+ prepared.includes === built.includes
764
+ ? built
765
+ : {
766
+ ...built,
767
+ select: prepared.select,
768
+ partialSelect: prepared.partialSelect,
769
+ includes: prepared.includes,
770
+ },
771
+ transform: prepared.finish
772
+ ? (row) => prepared.finish(decode(row))
773
+ : decode,
189
774
  };
190
- onPageResume = () => {
191
- this.sendLifecycleHint("resume");
775
+ }
776
+ /** Retry only computations that discovered a missing field, preserving the caller's read scope. */
777
+ async function finishComputedRead(query, built, outputTable, prepared, rows, read) {
778
+ for (;;) {
779
+ const results = [];
780
+ let missing;
781
+ // Visit every root before retrying so different rows' branches share a lookup.
782
+ for (const row of rows) {
783
+ try {
784
+ results.push(prepared.transform(row));
785
+ }
786
+ catch (error) {
787
+ if (!(error instanceof MissingComputedDependency))
788
+ throw error;
789
+ missing = error;
790
+ }
791
+ }
792
+ if (!missing)
793
+ return results;
794
+ if (!prepared.computedState || prepared.computedState.version === prepared.version)
795
+ throw missing;
796
+ prepared = prepareTransformRead(query, built, outputTable, prepared.computedState);
797
+ rows = await read(prepared.physical);
798
+ }
799
+ }
800
+ const dbTxHandleBindings = new WeakMap();
801
+ function getDbTxHandleBinding(handle, operation) {
802
+ const binding = dbTxHandleBindings.get(handle);
803
+ if (!binding) {
804
+ throw new Error(`DbTransaction.${operation}() requires at least one table operation first`);
805
+ }
806
+ return binding;
807
+ }
808
+ function transformOutputRow(source, row) {
809
+ return transformOutputColumns(source, row);
810
+ }
811
+ function transformOutputColumns(source, row) {
812
+ if (!source._columnTransforms || typeof row !== "object" || row === null) {
813
+ return row;
814
+ }
815
+ const record = row;
816
+ const computed = columnTransformDependencies(source._columnTransforms).computedColumns;
817
+ const appValues = computed.length
818
+ ? computedColumnValues(source._columnTransforms, computed, record)
819
+ : undefined;
820
+ applyColumnTransforms(record, source._columnTransforms, [], undefined, appValues);
821
+ for (const column of computed)
822
+ record[column] = appValues.get(column);
823
+ return record;
824
+ }
825
+ function transformInputColumns(table, data, storedValues, creation = false) {
826
+ const record = data;
827
+ if (!table._columnTransforms) {
828
+ return record;
829
+ }
830
+ const transforms = table._columnTransforms;
831
+ let hasTransform = false;
832
+ let hasDependencies = false;
833
+ for (const column in record) {
834
+ if (Object.hasOwn(record, column) && transforms[column]?.computed)
835
+ throw new TypeError(`Computed field "${column}" is read-only.`);
836
+ if (!Object.hasOwn(record, column) || record[column] === undefined)
837
+ continue;
838
+ const transform = transforms[column];
839
+ if (transform) {
840
+ hasTransform = true;
841
+ if (transform.dependsOn?.length)
842
+ hasDependencies = true;
843
+ }
844
+ }
845
+ if (!hasTransform)
846
+ return record;
847
+ if (!hasDependencies) {
848
+ const result = { ...record };
849
+ for (const column in record) {
850
+ if (!Object.hasOwn(record, column) || record[column] === undefined)
851
+ continue;
852
+ const transform = transforms[column];
853
+ if (transform)
854
+ result[column] = transform.to(record[column], dependencyContext(transform, record));
855
+ }
856
+ return result;
857
+ }
858
+ const stored = { ...storedValues };
859
+ const app = {};
860
+ const resolved = new Set();
861
+ const resolve = (column) => {
862
+ if (resolved.has(column))
863
+ return;
864
+ const transform = table._columnTransforms?.[column];
865
+ for (const dependency of transform?.dependsOn ?? [])
866
+ resolve(dependency);
867
+ if (Object.hasOwn(record, column) && record[column] !== undefined) {
868
+ app[column] = record[column];
869
+ stored[column] = transform
870
+ ? transform.to(record[column], dependencyContext(transform, app))
871
+ : record[column];
872
+ }
873
+ else {
874
+ if (creation && !Object.hasOwn(stored, column)) {
875
+ const descriptor = table._schema[table._table].columns.find((item) => item.name === column);
876
+ if (descriptor?.default !== undefined)
877
+ stored[column] = unwrapValue(descriptor.default, descriptor.column_type);
878
+ else if (descriptor?.nullable)
879
+ stored[column] = null;
880
+ }
881
+ if (!Object.hasOwn(stored, column))
882
+ throw new Error(`Transform dependency "${column}" is unavailable.`);
883
+ app[column] = transform
884
+ ? transform.from(stored[column], dependencyContext(transform, stored))
885
+ : stored[column];
886
+ }
887
+ resolved.add(column);
192
888
  };
889
+ const result = { ...record };
890
+ for (const column of Object.keys(record)) {
891
+ if (record[column] === undefined)
892
+ continue;
893
+ resolve(column);
894
+ result[column] = stored[column];
895
+ }
896
+ return result;
897
+ }
898
+ const noWriteDependencies = [];
899
+ /**
900
+ * How long an update of a row this replica hasn't loaded waits for the
901
+ * server to send it, before it is refused as a row the session can't find.
902
+ */
903
+ const LOAD_ROW_WAIT_MS = 10_000;
904
+ /**
905
+ * Read one row by id from the server through the caller's session, so this
906
+ * replica holds it before a write stages against it. The read waits for the
907
+ * server at most {@link LOAD_ROW_WAIT_MS}: offline, it finds no row and the
908
+ * update fails instead of hanging, with the writes queued behind it.
909
+ */
910
+ function loadRow(client, table, id, session, branch) {
911
+ const built = JSON.stringify({
912
+ table: table._table,
913
+ conditions: [{ column: "id", op: "eq", value: id }],
914
+ limit: 1,
915
+ });
916
+ const read = client.queryInternal(translateQuery(built, table._schema), branch ? { tier: "remote", branch } : { tier: "remote" }, session);
917
+ let timer;
918
+ const timeout = new Promise((resolve) => {
919
+ timer = setTimeout(() => resolve([]), LOAD_ROW_WAIT_MS);
920
+ });
921
+ return Promise.race([read, timeout]).finally(() => clearTimeout(timer));
922
+ }
923
+ function missingWriteDependencies(table, data, id) {
924
+ if (!table._columnTransforms)
925
+ return noWriteDependencies;
926
+ const { byColumn } = columnTransformDependencies(table._columnTransforms);
927
+ let missing;
928
+ for (const column of Object.keys(data)) {
929
+ if (table._columnTransforms[column]?.computed)
930
+ throw new TypeError(`Computed field "${column}" is read-only.`);
931
+ if (data[column] === undefined)
932
+ continue;
933
+ for (const dependency of byColumn.get(column) ?? noWriteDependencies) {
934
+ if (dependency !== "id" || id === undefined) {
935
+ if (!Object.hasOwn(data, dependency) || data[dependency] === undefined)
936
+ (missing ??= new Set()).add(dependency);
937
+ }
938
+ }
939
+ }
940
+ return missing ? [...missing] : noWriteDependencies;
941
+ }
942
+ function prepareInputColumns(table, data, operation, id, client, session, openTransactionId, options, missing) {
943
+ if (!table._columnTransforms)
944
+ return data;
945
+ missing ??= missingWriteDependencies(table, data, id);
946
+ const stored = id === undefined ? {} : { id };
947
+ if (operation === "Insert" || operation === "Restore" || missing.length === 0)
948
+ return transformInputColumns(table, data, stored, operation === "Insert" || operation === "Restore");
949
+ const built = JSON.stringify({
950
+ table: table._table,
951
+ conditions: [{ column: "id", op: "eq", value: id }],
952
+ select: missing.filter((column) => column !== "id"),
953
+ limit: 1,
954
+ includeDeleted: operation === "Upsert",
955
+ });
956
+ return client
957
+ .queryInternal(translateQuery(built, table._schema), {
958
+ ...(options?.branch ? { branch: options.branch } : {}),
959
+ ...(openTransactionId ? { openTransactionId, localUpdates: "deferred" } : {}),
960
+ }, session)
961
+ .then((rows) => {
962
+ const row = rows[0];
963
+ if (!row && operation !== "Upsert")
964
+ throw new Error("Transform dependency row is unavailable.");
965
+ if (!row && !client.readCanEstablishAbsence(session, openTransactionId))
966
+ throw new Error("Transform dependencies are unavailable: a scoped read cannot establish that the upsert row is absent.");
967
+ const existing = row
968
+ ? transformRow(row, table._schema, table._table, {}, missing)
969
+ : stored;
970
+ return transformInputColumns(table, data, existing, !row && operation === "Upsert");
971
+ });
972
+ }
973
+ function rejectIncompleteDependencies(table, data, incomplete) {
974
+ if (!table._columnTransforms || !incomplete.length)
975
+ return;
976
+ const { byColumn } = columnTransformDependencies(table._columnTransforms);
977
+ for (const column of Object.keys(data)) {
978
+ for (const dependency of byColumn.get(column) ?? noWriteDependencies) {
979
+ if (incomplete.includes(dependency))
980
+ throw new Error(`Transform dependency "${dependency}" requires a whole-value replacement in this write.`);
981
+ }
982
+ }
983
+ }
984
+ /**
985
+ * @internal The row an insert or restore of `data` as row `id` writes, as
986
+ * the table's schema alone decides it: for writes made before a client
987
+ * exists (`createJazz`'s `db` while its store opens).
988
+ */
989
+ export function previewWrittenRow(table, operation, id, data) {
990
+ assertWritableTable(table);
991
+ const transformedData = table._columnTransforms
992
+ ? transformInputColumns(table, data, { id }, true)
993
+ : data;
994
+ return immediateWriteRow(table, id, toWriteRecordForOperation(operation, transformedData, table._schema, table._table));
995
+ }
996
+ /** @internal A fresh row id, as an insert without one would get. */
997
+ export function reserveRowId() {
998
+ const hex = createOpenTransactionId();
999
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
1000
+ }
1001
+ function hasDependentTransforms(table) {
1002
+ return (!!table._columnTransforms &&
1003
+ columnTransformDependencies(table._columnTransforms).hasWriteDependencies);
1004
+ }
1005
+ function immediateWriteRow(table, id, values) {
1006
+ return transformOutputRow(table, transformRow(writeRow(table._table, id, table._schema[table._table].columns, values), table._schema, table._table));
1007
+ }
1008
+ function splitStreamingMutation(table, data) {
1009
+ if (typeof data !== "object" || data === null) {
1010
+ throw new Error("Streaming insert data must be an object");
1011
+ }
1012
+ const record = data;
1013
+ const streamableColumns = table._schema[table._table]?.columns.filter((column) => ["Text", "Json", "Bytea"].includes(column.column_type.type));
1014
+ const streamed = streamableColumns?.filter((column) => Object.hasOwn(record, column.name) && isStreamingValueSource(record[column.name]));
1015
+ if (streamed?.length !== 1) {
1016
+ throw new Error("Streaming insert requires exactly one streamed Text, Json, or Bytea column");
1017
+ }
1018
+ const column = streamed[0].name;
1019
+ if (table._schema[table._table]?.branchBy?.includes(column)) {
1020
+ throw new Error(`Streaming a branchBy column is not supported: ${table._table}.${column}`);
1021
+ }
1022
+ const source = record[column];
1023
+ const values = { ...record };
1024
+ delete values[column];
1025
+ return { column, source, values };
1026
+ }
1027
+ function isStreamingValueSource(value) {
1028
+ if (typeof value !== "object" || value === null)
1029
+ return false;
1030
+ const candidate = value;
1031
+ return (typeof candidate.getReader === "function" ||
1032
+ typeof candidate[Symbol.asyncIterator] === "function");
1033
+ }
1034
+ function deriveStreamingInsertBranch(table, values) {
1035
+ const branchColumns = table._schema[table._table]?.branchBy ?? [];
1036
+ if (branchColumns.length === 0)
1037
+ return undefined;
1038
+ const branch = {};
1039
+ for (const column of branchColumns) {
1040
+ const value = values[column];
1041
+ if (isStreamingValueSource(value)) {
1042
+ throw new Error(`Streaming a branchBy column is not supported: ${table._table}.${column}`);
1043
+ }
1044
+ if (typeof value !== "string" && typeof value !== "number" && typeof value !== "bigint") {
1045
+ throw new Error(`Streaming insert requires branch column ${table._table}.${column}`);
1046
+ }
1047
+ branch[column] = value;
1048
+ }
1049
+ return branch;
1050
+ }
1051
+ function createTransactionScope(transaction) {
1052
+ return new Proxy(transaction, {
1053
+ get(target, property) {
1054
+ if (property === "commit" || property === "rollback") {
1055
+ return undefined;
1056
+ }
1057
+ const value = Reflect.get(target, property, target);
1058
+ return typeof value === "function" ? value.bind(target) : value;
1059
+ },
1060
+ has(target, property) {
1061
+ if (property === "commit" || property === "rollback") {
1062
+ return false;
1063
+ }
1064
+ return Reflect.has(target, property);
1065
+ },
1066
+ set(target, property, value) {
1067
+ return Reflect.set(target, property, value, target);
1068
+ },
1069
+ });
1070
+ }
1071
+ function createTransactionWriteResult(transaction, value, txId, client) {
1072
+ if (transaction.kind === "serializable") {
1073
+ return new SerializableWriteResult(value, txId, client);
1074
+ }
1075
+ return new WriteResult(value, txId, client);
1076
+ }
1077
+ export async function runInTransaction(transaction, callback, client) {
1078
+ let value;
1079
+ try {
1080
+ const scope = createTransactionScope(transaction);
1081
+ value = callback(scope);
1082
+ }
1083
+ catch (error) {
1084
+ try {
1085
+ await transaction.rollback();
1086
+ }
1087
+ catch {
1088
+ // Preserve the original callback error.
1089
+ }
1090
+ throw error;
1091
+ }
1092
+ const resultClient = typeof client === "function" ? client : () => client;
1093
+ let resolvedValue;
1094
+ try {
1095
+ resolvedValue = await value;
1096
+ }
1097
+ catch (error) {
1098
+ try {
1099
+ await transaction.rollback();
1100
+ }
1101
+ catch {
1102
+ // Preserve the original callback error.
1103
+ }
1104
+ throw error;
1105
+ }
1106
+ let committed;
1107
+ try {
1108
+ committed = await transaction.commit();
1109
+ }
1110
+ catch (error) {
1111
+ try {
1112
+ await transaction.rollback();
1113
+ }
1114
+ catch {
1115
+ // Preserve the commit error while ensuring an empty mergeable transaction is
1116
+ // consumed when the callback helper has no handle to return to callers.
1117
+ }
1118
+ throw error;
1119
+ }
1120
+ const txId = committed.txId.catch(async (error) => {
1121
+ try {
1122
+ await transaction.rollback();
1123
+ }
1124
+ catch {
1125
+ // Preserve the deferred commit error, just as for synchronous commit failure.
1126
+ }
1127
+ throw error;
1128
+ });
1129
+ return createTransactionWriteResult(transaction, resolvedValue, txId, resultClient());
1130
+ }
1131
+ /**
1132
+ * Groups a set of writes as either a mergeable or serializable transaction (see {@link TransactionKind}).
1133
+ */
1134
+ export class Transaction {
1135
+ kind;
1136
+ resolveClient;
1137
+ context;
1138
+ /** @internal Install the prerequisite before binding the owner. */
1139
+ static createWithAdmission(kind, resolveClient, context, ownerClient, prerequisite) {
1140
+ const transaction = new Transaction(kind, resolveClient, context);
1141
+ transaction.openingPrerequisite = prerequisite;
1142
+ if (ownerClient)
1143
+ transaction.bindOwnerClient(ownerClient);
1144
+ return transaction;
1145
+ }
1146
+ openingPrerequisite;
1147
+ pendingReads = new Set();
1148
+ committing = false;
1149
+ constructor(kind, resolveClient, context = null, ownerClient) {
1150
+ this.kind = kind;
1151
+ this.resolveClient = resolveClient;
1152
+ this.context = context;
1153
+ if (ownerClient)
1154
+ this.bindOwnerClient(ownerClient);
1155
+ }
1156
+ bindTable(table) {
1157
+ const client = this.resolveClient(table._schema);
1158
+ if (!dbTxHandleBindings.has(this))
1159
+ this.bindOwnerClient(client);
1160
+ if (this.requireBinding("table operation").committing)
1161
+ throw new Error("Transaction commit has already been requested.");
1162
+ return this.requireBinding("table operation");
1163
+ }
1164
+ bindQuery(query) {
1165
+ return this.bindTable(query);
1166
+ }
1167
+ requireBinding(operation) {
1168
+ if (this.committing) {
1169
+ throw new Error(`DbTransaction.${operation}() cannot run after commit has been requested`);
1170
+ }
1171
+ return getDbTxHandleBinding(this, operation);
1172
+ }
1173
+ bindOwnerClient(ownerClient) {
1174
+ const { writeSession: session, attribution } = this.context ?? {};
1175
+ const preparation = new WritePreparation(true);
1176
+ const owner = getOwnerPreparation(ownerClient);
1177
+ const openTransactionId = owner?.pending
1178
+ ? createOpenTransactionId()
1179
+ : this.openingPrerequisite
1180
+ ? beginClientTransactionAfter(ownerClient, this.kind, session, attribution, undefined, this.openingPrerequisite)
1181
+ : ownerClient.beginTransaction(this.kind, session, attribution);
1182
+ const binding = {
1183
+ ownerClient,
1184
+ openTransactionId,
1185
+ session: session,
1186
+ attribution: attribution,
1187
+ preparation,
1188
+ begun: !owner?.pending,
1189
+ };
1190
+ dbTxHandleBindings.set(this, binding);
1191
+ if (!binding.begun)
1192
+ preparation.run(() => owner.run(() => {
1193
+ if (preparation.cancelled)
1194
+ return;
1195
+ if (this.openingPrerequisite)
1196
+ beginClientTransactionAfter(ownerClient, this.kind, session, attribution, openTransactionId, this.openingPrerequisite);
1197
+ else
1198
+ ownerClient.beginTransaction(this.kind, session, attribution, openTransactionId);
1199
+ binding.begun = true;
1200
+ }));
1201
+ }
1202
+ openTransactionId() {
1203
+ return this.requireBinding("openTransactionId").openTransactionId;
1204
+ }
193
1205
  /**
194
- * Protected constructor - use createDb() in regular app code.
1206
+ * Commit this transaction.
195
1207
  */
196
- constructor(config, wasmModule) {
197
- this.config = config;
198
- this.wasmModule = wasmModule;
1208
+ commit() {
1209
+ const binding = this.requireBinding("commit");
1210
+ const { ownerClient, openTransactionId, preparation } = binding;
1211
+ if (binding.committing)
1212
+ throw new Error("Transaction commit has already been requested.");
1213
+ if (preparation.pending || preparation.failed)
1214
+ binding.committing = true;
1215
+ const txId = preparation.pending || preparation.failed || this.pendingReads.size > 0
1216
+ ? Promise.all([preparation.drain(), ...this.pendingReads]).then(() => ownerClient.commitTransaction(openTransactionId).txId)
1217
+ : ownerClient.commitTransaction(openTransactionId).txId;
1218
+ this.committing = true;
1219
+ const finishCommit = () => {
1220
+ this.committing = false;
1221
+ };
1222
+ txId.then(finishCommit, finishCommit);
1223
+ if (this.kind === "serializable") {
1224
+ return new SerializableWriteHandle(txId, ownerClient);
1225
+ }
1226
+ return new WriteHandle(txId, ownerClient);
199
1227
  }
200
1228
  /**
201
- * Create a Db instance with pre-loaded WASM module.
202
- * @internal Use createDb() instead.
1229
+ * Roll back this transaction locally.
1230
+ *
1231
+ * Pending rows remain pending, but this transaction can no longer be committed.
1232
+ *
1233
+ * Only available on transactions created with {@link Db.beginTransaction}.
1234
+ * When using {@link Db.transaction}, throw an error inside the callback to roll back.
203
1235
  */
204
- static async create(config) {
205
- const wasmModule = await loadWasmModule();
206
- return new Db(config, wasmModule);
1236
+ rollback() {
1237
+ const { ownerClient, openTransactionId, preparation, begun } = this.requireBinding("rollback");
1238
+ if (!begun) {
1239
+ preparation.cancelled = true;
1240
+ return Promise.resolve(true);
1241
+ }
1242
+ const result = ownerClient.rollbackTransaction(openTransactionId);
1243
+ preparation.cancelled = true;
1244
+ return result;
207
1245
  }
208
1246
  /**
209
- * Create a Db instance backed by a dedicated worker with OPFS persistence.
1247
+ * Stream one Text, Json, or Bytea column into a new row, staged in this
1248
+ * transaction. Resolves with the row id once the stream is consumed; the
1249
+ * commit waits for it and fails if the stream did.
210
1250
  *
211
- * The main thread runs an in-memory WASM runtime.
212
- * The worker runs a persistent WASM runtime (OPFS).
213
- * WorkerBridge wires them together via postMessage.
1251
+ * The streamed value is held for the transaction for at most the store's
1252
+ * staging max age (10 minutes by default) after the stream finishes. A
1253
+ * transaction left open longer than that is refused at commit, with
1254
+ * `streaming upload expired`, so its storage is never held indefinitely;
1255
+ * start it again. The same applies to `updateStreaming` and
1256
+ * `upsertStreaming`.
1257
+ */
1258
+ insertStreaming(table, data, options) {
1259
+ return this.streamingMutation("insert", table, options?.id, data, options);
1260
+ }
1261
+ /** Stream one large column of an existing row, staged in this transaction. */
1262
+ updateStreaming(table, id, data, options) {
1263
+ return this.streamingMutation("update", table, id, data, options);
1264
+ }
1265
+ /** Stream one large column of a row, creating it if absent, staged in this transaction. */
1266
+ upsertStreaming(table, id, data, options) {
1267
+ return this.streamingMutation("upsert", table, id, data, options);
1268
+ }
1269
+ streamingMutation(mutation, table, id, data, options) {
1270
+ assertWritableTable(table);
1271
+ this.bindTable(table);
1272
+ const client = this.resolveClient(table._schema);
1273
+ const operation = mutation === "insert" ? "Insert" : mutation === "update" ? "Update" : "Upsert";
1274
+ const { openTransactionId, session, attribution, preparation } = this.requireBinding(`${mutation}Streaming`);
1275
+ const { column, source, values: ordinaryData } = splitStreamingMutation(table, data);
1276
+ rejectIncompleteDependencies(table, ordinaryData, [column]);
1277
+ const rowId = id ??
1278
+ (missingWriteDependencies(table, ordinaryData).includes("id") ? reserveRowId() : undefined);
1279
+ const stage = async () => {
1280
+ const record = mutation === "insert"
1281
+ ? transformInputColumns(table, ordinaryData, rowId ? { id: rowId } : {}, true)
1282
+ : await prepareInputColumns(table, ordinaryData, operation, rowId, client, session, undefined, normalizeViewOptions(table._schema, table._table, options));
1283
+ const values = toWriteRecordForOperation(operation, record, table._schema, table._table);
1284
+ const branch = mutation === "insert" ? deriveStreamingInsertBranch(table, ordinaryData) : undefined;
1285
+ const normalized = mutation === "insert"
1286
+ ? normalizeSelectorOptions(table._schema, table._table, {
1287
+ ...options,
1288
+ ...(rowId ? { id: rowId } : {}),
1289
+ ...(branch ? { branch } : {}),
1290
+ })
1291
+ : normalizeViewOptions(table._schema, table._table, options);
1292
+ return client.streamingMutationInTransaction(mutation, table._table, values, column, source, openTransactionId, normalized, session, attribution, rowId);
1293
+ };
1294
+ return Promise.resolve(preparation.run(() => runAfterPreparation(client, () => (preparation.cancelled ? undefined : stage())))).then((staged) => {
1295
+ if (!staged)
1296
+ throw new Error("Transaction was rolled back before the stream was staged");
1297
+ return staged;
1298
+ });
1299
+ }
1300
+ /**
1301
+ * Insert a new row into a table.
214
1302
  *
215
- * @internal Use createDb() instead — it auto-detects browser.
1303
+ * The insert is scoped to this transaction, and will only be globally visible
1304
+ * once it's committed.
216
1305
  */
217
- static async createWithWorker(config) {
218
- const wasmModule = await loadWasmModule();
219
- const db = new Db(config, wasmModule);
220
- db.primaryDbName = config.dbName ?? config.appId;
221
- db.workerDbName = db.primaryDbName;
1306
+ insert(table, data, options) {
1307
+ assertWritableTable(table);
1308
+ this.bindTable(table);
1309
+ const client = this.resolveClient(table._schema);
1310
+ const { openTransactionId, session, attribution, preparation } = this.requireBinding("insert");
1311
+ let id = options?.id ?? (hasDependentTransforms(table) ? reserveRowId() : undefined);
1312
+ const { values, value } = this.prepareCreation(table, data, id, "Insert");
1313
+ if (!id && (preparation.pending || getOwnerPreparation(client)?.pending))
1314
+ id = reserveRowId();
1315
+ let row;
1316
+ const stage = () => {
1317
+ row = client.insertInternal(table._table, values, normalizeSelectorOptions(table._schema, table._table, id ? { ...options, id } : options), session, attribution, openTransactionId);
1318
+ };
1319
+ if (preparation.cancelled)
1320
+ stage();
1321
+ else
1322
+ preparation.run(() => runAfterPreparation(client, () => {
1323
+ if (!preparation.cancelled)
1324
+ stage();
1325
+ }));
222
1326
  try {
223
- const election = new TabLeaderElection({
224
- appId: config.appId,
225
- dbName: db.primaryDbName,
226
- });
227
- db.leaderElection = election;
228
- election.start();
229
- let initialLeader = null;
230
- try {
231
- // Allow at least one startup election window with default heartbeat settings.
232
- initialLeader = await election.waitForInitialLeader(1600);
233
- }
234
- catch {
235
- // Fall back to whatever state election has reached so far.
236
- initialLeader = election.snapshot();
237
- }
238
- db.adoptLeaderSnapshot(initialLeader);
239
- db.workerDbName = Db.resolveWorkerDbNameForSnapshot(db.primaryDbName, initialLeader);
240
- db.logLeaderDebug("initial-election");
241
- db.openSyncChannel();
242
- db.attachLifecycleHooks();
243
- db.leaderElectionUnsubscribe = election.onChange((snapshot) => {
244
- db.onLeaderElectionChange(snapshot);
245
- });
246
- db.worker = await Db.spawnWorker();
247
- return db;
1327
+ return (value ??
1328
+ (row
1329
+ ? transformOutputRow(table, transformRow(row, table._schema, table._table))
1330
+ : immediateWriteRow(table, id, values)));
248
1331
  }
249
1332
  catch (error) {
250
- db.closeSyncChannel();
251
- db.detachLifecycleHooks();
252
- if (db.leaderElectionUnsubscribe) {
253
- db.leaderElectionUnsubscribe();
254
- db.leaderElectionUnsubscribe = null;
255
- }
256
- if (db.leaderElection) {
257
- db.leaderElection.stop();
258
- db.leaderElection = null;
259
- }
1333
+ preparation.failure = error;
260
1334
  throw error;
261
1335
  }
262
1336
  }
263
1337
  /**
264
- * Get or create a JazzClient for the given schema.
265
- * Synchronous because WASM module is pre-loaded.
1338
+ * Restore a soft-deleted row.
266
1339
  *
267
- * In worker mode, the first call per schema also initializes the
268
- * WorkerBridge (async). Subsequent calls are sync.
1340
+ * The restore is scoped to this transaction, and will only be globally visible
1341
+ * once it's committed.
269
1342
  */
270
- getClient(schema) {
271
- if (!this.wasmModule) {
272
- throw new Error("Db runtime module is not initialized for this Db implementation");
273
- }
274
- // Use stringified schema as cache key
275
- const key = JSON.stringify(schema);
276
- if (!this.clients.has(key)) {
277
- // Create in-memory runtime (works for both direct and worker mode)
278
- const client = JazzClient.connectSync(this.wasmModule, {
279
- appId: this.config.appId,
280
- schema,
281
- driver: this.config.driver,
282
- // In worker mode, don't connect to server directly — worker handles it
283
- serverUrl: this.worker ? undefined : this.config.serverUrl,
284
- serverPathPrefix: this.worker ? undefined : this.config.serverPathPrefix,
285
- env: this.config.env,
286
- userBranch: this.config.userBranch,
287
- jwtToken: this.config.jwtToken,
288
- localAuthMode: this.config.localAuthMode,
289
- localAuthToken: this.config.localAuthToken,
290
- adminSecret: this.config.adminSecret,
291
- });
292
- // In worker mode, set up the bridge for this client
293
- if (this.worker && !this.workerBridge) {
294
- this.attachWorkerBridge(key, client);
295
- }
296
- this.clients.set(key, client);
1343
+ restore(table, id, data, options) {
1344
+ assertWritableTable(table);
1345
+ this.bindTable(table);
1346
+ const { values, value } = this.prepareCreation(table, data, id, "Restore");
1347
+ const client = this.resolveClient(table._schema);
1348
+ const { openTransactionId, session, attribution, preparation } = this.requireBinding("restore");
1349
+ const stage = () => {
1350
+ client.restoreInternal(table._table, id, values, normalizeSelectorOptions(table._schema, table._table, options), session, attribution, openTransactionId);
1351
+ };
1352
+ if (preparation.cancelled)
1353
+ stage();
1354
+ else
1355
+ preparation.run(() => runAfterPreparation(client, () => {
1356
+ if (!preparation.cancelled)
1357
+ stage();
1358
+ }));
1359
+ return value;
1360
+ }
1361
+ prepareCreation(table, data, id, operation) {
1362
+ let record;
1363
+ try {
1364
+ record = table._columnTransforms
1365
+ ? transformInputColumns(table, data, id === undefined ? undefined : { id }, true)
1366
+ : data;
1367
+ }
1368
+ catch (error) {
1369
+ this.requireBinding(operation).preparation.failure = error;
1370
+ throw error;
1371
+ }
1372
+ const values = toWriteRecordForOperation(operation, record, table._schema, table._table);
1373
+ try {
1374
+ return {
1375
+ values,
1376
+ value: id === undefined ? undefined : immediateWriteRow(table, id, values),
1377
+ };
1378
+ }
1379
+ catch (error) {
1380
+ this.requireBinding(operation).preparation.failure = error;
1381
+ throw error;
297
1382
  }
298
- return this.clients.get(key);
299
1383
  }
300
1384
  /**
301
- * Wait for the worker bridge to be initialized (if in worker mode).
302
- * No-op if not using a worker.
1385
+ * Create or update a row with a caller-supplied id.
1386
+ *
1387
+ * The upsert is scoped to this transaction, and will only be globally visible
1388
+ * once it's committed.
303
1389
  */
304
- async ensureBridgeReady() {
305
- await this.workerReconfigure;
306
- if (this.bridgeReady) {
307
- await this.bridgeReady;
308
- }
1390
+ upsert(table, id, data, options) {
1391
+ assertWritableTable(table);
1392
+ this.bindTable(table);
1393
+ const client = this.resolveClient(table._schema);
1394
+ const { openTransactionId, session, attribution } = this.requireBinding("upsert");
1395
+ this.prepareMutation(table, id, data, "Upsert", options, (values) => {
1396
+ client.upsertInternal(table._table, id, values, normalizeViewOptions(table._schema, table._table, options), session, attribution, openTransactionId);
1397
+ });
309
1398
  }
310
- attachWorkerBridge(schemaJson, client) {
311
- if (!this.worker) {
312
- throw new Error("Cannot attach worker bridge without an active worker");
313
- }
314
- const bridge = new WorkerBridge(this.worker, client.getRuntime());
315
- this.leaderPeerIds.clear();
316
- bridge.onPeerSync((batch) => {
317
- this.handleWorkerPeerSync(batch);
1399
+ update(table, id, data, options) {
1400
+ assertWritableTable(table);
1401
+ this.bindTable(table);
1402
+ const { replacements, descriptors } = lowerUpdate(table, data, options);
1403
+ options = withoutEditedFrom(options);
1404
+ const client = this.resolveClient(table._schema);
1405
+ const { openTransactionId, session, attribution } = this.requireBinding("update");
1406
+ const normalizedOptions = normalizeViewOptions(table._schema, table._table, options);
1407
+ this.prepareMutation(table, id, replacements, "Update", options, (updates) => {
1408
+ if (descriptors.length > 0) {
1409
+ client.updateLargeValuesInternal(table._table, id, updates, descriptors, normalizedOptions?.updatedAt, session, attribution, openTransactionId, normalizedOptions?.branch);
1410
+ return;
1411
+ }
1412
+ client.updateInternal(table._table, id, updates, normalizedOptions?.updatedAt, session, attribution, openTransactionId, normalizedOptions?.branch);
318
1413
  });
319
- this.applyBridgeRoutingForCurrentLeader(bridge, false);
320
- this.workerBridge = bridge;
321
- this.bridgeReady = bridge.init(this.buildWorkerBridgeOptions(schemaJson)).then(() => undefined);
322
1414
  }
323
- buildWorkerBridgeOptions(schemaJson) {
324
- return {
325
- schemaJson,
326
- appId: this.config.appId,
327
- env: this.config.env ?? "dev",
328
- userBranch: this.config.userBranch ?? "main",
329
- dbName: this.workerDbName ?? this.config.dbName ?? this.config.appId,
330
- serverUrl: this.config.serverUrl,
331
- serverPathPrefix: this.config.serverPathPrefix,
332
- jwtToken: this.config.jwtToken,
333
- localAuthMode: this.config.localAuthMode,
334
- localAuthToken: this.config.localAuthToken,
335
- adminSecret: this.config.adminSecret,
336
- };
337
- }
338
- adoptLeaderSnapshot(snapshot) {
339
- this.tabRole = snapshot.role;
340
- this.tabId = snapshot.tabId;
341
- this.currentLeaderTabId = snapshot.leaderTabId;
342
- this.currentLeaderTerm = snapshot.term;
343
- }
344
- openSyncChannel() {
345
- if (this.syncChannel || !this.primaryDbName)
346
- return;
347
- const ChannelCtor = resolveBroadcastChannelCtor();
348
- if (!ChannelCtor) {
349
- this.logLeaderDebug("sync-channel-unavailable");
1415
+ prepareMutation(table, id, data, operation, options, stage) {
1416
+ const { ownerClient, openTransactionId, preparation } = this.requireBinding(operation);
1417
+ if (preparation.pending ||
1418
+ getOwnerPreparation(ownerClient)?.pending ||
1419
+ missingWriteDependencies(table, data, id).length)
1420
+ data = { ...data };
1421
+ if (preparation.cancelled) {
1422
+ stage({});
350
1423
  return;
351
1424
  }
352
- const channelName = `jazz-tab-sync:${this.config.appId}:${this.primaryDbName}`;
353
- this.syncChannel = new ChannelCtor(channelName);
354
- this.syncChannel.addEventListener("message", this.onSyncChannelMessage);
355
- this.logLeaderDebug("sync-channel-open", {
356
- channelName,
357
- });
1425
+ preparation.run(() => runAfterPreparation(ownerClient, () => {
1426
+ if (preparation.cancelled)
1427
+ return;
1428
+ let prepared;
1429
+ try {
1430
+ prepared = prepareInputColumns(table, data, operation, id, ownerClient, this.context?.readSession, openTransactionId, normalizeViewOptions(table._schema, table._table, options));
1431
+ }
1432
+ catch (error) {
1433
+ preparation.failure = error;
1434
+ throw error;
1435
+ }
1436
+ const finish = (record) => {
1437
+ if (preparation.cancelled)
1438
+ return;
1439
+ if (preparation.failed)
1440
+ throw preparation.failure;
1441
+ const values = toWriteRecordForOperation(operation, record, table._schema, table._table);
1442
+ stage(values);
1443
+ };
1444
+ return prepared instanceof Promise ? prepared.then(finish) : finish(prepared);
1445
+ }));
358
1446
  }
359
- closeSyncChannel() {
360
- if (!this.syncChannel)
361
- return;
362
- this.syncChannel.removeEventListener("message", this.onSyncChannelMessage);
363
- this.syncChannel.close();
364
- this.syncChannel = null;
365
- this.logLeaderDebug("sync-channel-close");
1447
+ /**
1448
+ * Delete an existing row from a table.
1449
+ *
1450
+ * The delete is scoped to this transaction, and will only be globally visible
1451
+ * once it's committed.
1452
+ */
1453
+ delete(table, id, options) {
1454
+ assertWritableTable(table);
1455
+ this.bindTable(table);
1456
+ const client = this.resolveClient(table._schema);
1457
+ const { openTransactionId, session, attribution, preparation } = this.requireBinding("delete");
1458
+ const normalizedOptions = normalizeViewOptions(table._schema, table._table, options);
1459
+ const stage = () => {
1460
+ client.deleteInternal(table._table, id, normalizedOptions?.updatedAt, session, attribution, openTransactionId, normalizedOptions?.branch);
1461
+ };
1462
+ if (preparation.cancelled)
1463
+ stage();
1464
+ else
1465
+ preparation.run(() => runAfterPreparation(client, () => {
1466
+ if (!preparation.cancelled)
1467
+ stage();
1468
+ }));
1469
+ }
1470
+ /**
1471
+ * Execute a query and return all matching rows.
1472
+ *
1473
+ * Read data is scoped to this transaction.
1474
+ */
1475
+ all(query, options) {
1476
+ const reading = this.readAll(query, options);
1477
+ this.pendingReads.add(reading);
1478
+ const settled = () => this.pendingReads.delete(reading);
1479
+ reading.then(settled, settled);
1480
+ return reading;
366
1481
  }
367
- postSyncChannelMessage(message) {
368
- this.syncChannel?.postMessage(message);
1482
+ async readAll(query, options) {
1483
+ this.bindQuery(query);
1484
+ const { preparation, openTransactionId } = this.requireBinding("query");
1485
+ if (preparation.pending || preparation.failed)
1486
+ await preparation.drain();
1487
+ const client = this.resolveClient(query._schema);
1488
+ const builderJson = query._build();
1489
+ const builtQuery = normalizeBuiltQuery(JSON.parse(builderJson));
1490
+ const planningSchema = requireSchemaWithTable(query._schema, builtQuery.table);
1491
+ const outputTable = resolveQueryOutputTable(planningSchema, builtQuery);
1492
+ const prepared = prepareTransformRead(query, builtQuery, outputTable);
1493
+ // Transactions accept the same public options surface as Db. Lower before
1494
+ // reaching native options so JavaScript callers cannot smuggle runtime
1495
+ // controls (for example `localUpdates` or `openTransactionId`) through this
1496
+ // otherwise separate execution path.
1497
+ const queryOptions = normalizeViewOptions(query._schema, builtQuery.table, lowerPublicDbQueryOptions(options)) ??
1498
+ {};
1499
+ const rows = await client.queryInternal(translateQuery(builderJson, planningSchema, prepared.physical), {
1500
+ ...queryOptions,
1501
+ openTransactionId,
1502
+ }, this.context?.readSession);
1503
+ if (!prepared.computedState)
1504
+ return rows.map(prepared.transform);
1505
+ return finishComputedRead(query, builtQuery, outputTable, prepared, rows, (physical) => client.queryInternal(translateQuery(builderJson, planningSchema, physical), { ...queryOptions, openTransactionId }, this.context?.readSession));
369
1506
  }
370
- attachLifecycleHooks() {
371
- if (this.lifecycleHooksAttached)
372
- return;
373
- if (typeof window === "undefined" || typeof document === "undefined")
374
- return;
375
- document.addEventListener("visibilitychange", this.onVisibilityChange);
376
- window.addEventListener("pagehide", this.onPageHide);
377
- // "freeze"/"resume" are non-standard but available in Chromium lifecycle APIs.
378
- document.addEventListener("freeze", this.onPageFreeze);
379
- document.addEventListener("resume", this.onPageResume);
380
- this.lifecycleHooksAttached = true;
381
- }
382
- detachLifecycleHooks() {
383
- if (!this.lifecycleHooksAttached)
384
- return;
385
- if (typeof window === "undefined" || typeof document === "undefined")
386
- return;
387
- document.removeEventListener("visibilitychange", this.onVisibilityChange);
388
- window.removeEventListener("pagehide", this.onPageHide);
389
- document.removeEventListener("freeze", this.onPageFreeze);
390
- document.removeEventListener("resume", this.onPageResume);
391
- this.lifecycleHooksAttached = false;
392
- }
393
- sendLifecycleHint(event) {
394
- if (this.isShuttingDown || !this.worker)
395
- return;
396
- this.logLeaderDebug("lifecycle-hint", { event });
397
- if (this.workerBridge) {
398
- this.workerBridge.sendLifecycleHint(event);
399
- return;
1507
+ /**
1508
+ * Execute a query with a limit of one and return the first matching row, or null.
1509
+ *
1510
+ * Read data is scoped to this transaction.
1511
+ */
1512
+ async one(query, options) {
1513
+ const results = await this.all(limitQueryToOne(query), options);
1514
+ return results[0] ?? null;
1515
+ }
1516
+ }
1517
+ /** @internal The compiler opts in before staging any operations. */
1518
+ export function beginDbTransactionAfter(db, prepare) {
1519
+ return db.createTransaction("serializable", prepare);
1520
+ }
1521
+ export class Db {
1522
+ config;
1523
+ runtimeSource;
1524
+ authStateStore;
1525
+ connection;
1526
+ _localFirstSecret = null;
1527
+ localFirstRefreshOwned = false;
1528
+ localFirstRenewals = new AuthRenewalBackoff();
1529
+ localFirstRefreshTimer = null;
1530
+ shutdownPromise = null;
1531
+ /** Set once the session that owned this Db moved on to another one. */
1532
+ replaced = null;
1533
+ /** Ends each live subscription with a terminal error. */
1534
+ liveSubscriptionEnders = new Set();
1535
+ /** The Db this one hands its work to after the local-first upgrade. */
1536
+ successor = null;
1537
+ /** Queries and listeners that move to the successor with the upgrade. */
1538
+ movable = new Set();
1539
+ shutdownAbort = new AbortController();
1540
+ syncStatusSnapshot = null;
1541
+ activeQuerySubscriptionTraces = new Map();
1542
+ activeQuerySubscriptionTraceListeners = new Set();
1543
+ mutationErrorListeners = new Set();
1544
+ pendingMutationErrorEvents = [];
1545
+ nextActiveQuerySubscriptionTraceId = 1;
1546
+ #authenticatedInspectorPhysicalDbName = null;
1547
+ /**
1548
+ * Protected constructor - use {@link createDb} in regular app code.
1549
+ */
1550
+ constructor(config, runtimeSource, authStateOptions) {
1551
+ assertAccountConfig(config);
1552
+ this.config = config;
1553
+ this.runtimeSource = runtimeSource;
1554
+ const sessionInput = {
1555
+ ...config,
1556
+ trustedReservedSession: getTrustedReservedSession(config),
1557
+ };
1558
+ setDbInternalSession(this, resolveClientInternalSessionSync(sessionInput));
1559
+ this.authStateStore = createAuthStateStore(sessionInput, authStateOptions);
1560
+ this.connection = new DirectConnectionManager(this.dbForConnection());
1561
+ // An overlay peer gets its port only through the authenticated Inspector
1562
+ // control handoff. Keep the resulting read policy inside this source: the
1563
+ // Inspector UI uses ordinary `useAll`, while no application-facing option
1564
+ // or package export can manufacture local-only reads.
1565
+ const inspectorAttachmentRequested = config.runtimeSources?.browserWorkerPort !== undefined &&
1566
+ config.runtimeSources.inspectorHostPhysicalDbName !== undefined;
1567
+ // The Inspector's own Db reads the page's data; it is not one of the page's Dbs.
1568
+ if (!inspectorAttachmentRequested) {
1569
+ const unregister = registerPageDb(this, config.appId ?? null);
1570
+ this.shutdownAbort.signal.addEventListener("abort", unregister, { once: true });
400
1571
  }
401
- this.worker.postMessage({
402
- type: "lifecycle-hint",
403
- event,
404
- sentAtMs: Date.now(),
1572
+ dbSubscriptionSources.set(this, {
1573
+ // Cache identity is reserved before the async worker receipt arrives so
1574
+ // an Inspector entry can never share a host application's query cache.
1575
+ // This marker is not authority: execution below strips it unless the
1576
+ // worker subsequently authenticates this attachment.
1577
+ ...(inspectorAttachmentRequested
1578
+ ? {
1579
+ prepareQueryOptions: (options) => createInspectorLocalQueryOptions(options),
1580
+ }
1581
+ : {}),
1582
+ all: (query, options) => inspectorAttachmentRequested
1583
+ ? this.allFromInspectorAttachment(query, options)
1584
+ : this.allInternal(query, lowerPublicDbQueryOptions(options)),
1585
+ subscribeDelta: (query, callback, options) => inspectorAttachmentRequested
1586
+ ? this.subscribeFromInspectorAttachment(query, callback, options)
1587
+ : this.subscribeDelta(query, callback, lowerPublicDbQueryOptions(options)),
405
1588
  });
406
1589
  }
407
- logLeaderDebug(event, extra) {
408
- if (!isLeaderDebugEnabled())
409
- return;
410
- console.info("[db:leader]", event, {
411
- tabId: this.tabId,
412
- role: this.tabRole,
413
- term: this.currentLeaderTerm,
414
- leaderTabId: this.currentLeaderTabId,
415
- workerDbName: this.workerDbName,
416
- ...extra,
417
- });
1590
+ dbForConnection() {
1591
+ // oxlint-disable-next-line typescript/no-this-alias
1592
+ const thisDb = this;
1593
+ return {
1594
+ get config() {
1595
+ return thisDb.config;
1596
+ },
1597
+ get runtimeSource() {
1598
+ return thisDb.runtimeSource;
1599
+ },
1600
+ get isShuttingDown() {
1601
+ return thisDb.shutdownPromise !== null;
1602
+ },
1603
+ markUnauthenticated: (reason) => this.markUnauthenticated(reason),
1604
+ renewsCredential: (reason) => (credentialRenewers.get(this) ?? 0) > 0 ||
1605
+ (reason === "expired" && this.localFirstRefreshOwned),
1606
+ clearAuthError: () => this.authStateStore.clearError(),
1607
+ onMutationError: (event) => this.handleMutationError(event),
1608
+ enableAuthenticatedInspectorLocalReads: (physicalDbName) => this.#enableAuthenticatedInspectorLocalReads(physicalDbName),
1609
+ clearAuthenticatedInspectorLocalReads: () => this.#clearAuthenticatedInspectorLocalReads(),
1610
+ };
418
1611
  }
419
- handleSyncChannelMessage(raw) {
420
- if (this.isShuttingDown || !this.tabId)
1612
+ #enableAuthenticatedInspectorLocalReads(physicalDbName) {
1613
+ // The configured coordinate is only selection metadata. It becomes
1614
+ // authority only when the worker returns this exact root in the init
1615
+ // receipt for a peer it created through Inspector control.
1616
+ if (this.config.runtimeSources?.inspectorHostPhysicalDbName !== physicalDbName)
421
1617
  return;
422
- if (!isTabSyncMessage(raw))
423
- return;
424
- switch (raw.type) {
425
- case "follower-sync":
426
- this.handleFollowerSync(raw);
427
- return;
428
- case "leader-sync":
429
- this.handleLeaderSync(raw);
430
- return;
431
- case "follower-close":
432
- this.handleFollowerClose(raw);
1618
+ this.#authenticatedInspectorPhysicalDbName = physicalDbName;
1619
+ }
1620
+ #clearAuthenticatedInspectorLocalReads() {
1621
+ this.#authenticatedInspectorPhysicalDbName = null;
1622
+ }
1623
+ async inspectorAttachmentOptions(query, options) {
1624
+ // Client construction starts the follower's init handshake. Do not decide
1625
+ // the read tier from config/MessagePort shape: wait for the worker receipt.
1626
+ this.getClient(query._schema);
1627
+ await this.connection.ensureReady("runtime");
1628
+ const selectedOptions = this.#authenticatedInspectorPhysicalDbName
1629
+ ? createInspectorLocalQueryOptions(options)
1630
+ : // Drop a source's cache-only marker when the worker did not issue an
1631
+ // Inspector receipt. Symbols are deliberately non-enumerable.
1632
+ options && { ...options };
1633
+ return lowerPublicDbQueryOptions(selectedOptions) ?? {};
1634
+ }
1635
+ async allFromInspectorAttachment(query, options) {
1636
+ return this.allInternal(query, await this.inspectorAttachmentOptions(query, options));
1637
+ }
1638
+ subscribeFromInspectorAttachment(query, callback, options) {
1639
+ let inner = null;
1640
+ let cancelled = false;
1641
+ const ready = this.inspectorAttachmentOptions(query, options).then((prepared) => {
1642
+ if (cancelled)
433
1643
  return;
1644
+ inner = this.subscribeDelta(query, callback, prepared);
1645
+ return inner.ready;
1646
+ });
1647
+ const handle = (() => {
1648
+ cancelled = true;
1649
+ inner?.();
1650
+ });
1651
+ Object.defineProperty(handle, "ready", { value: ready });
1652
+ return handle;
1653
+ }
1654
+ /** @internal Store the seed used for local-first auth and optionally schedule token refresh. */
1655
+ initLocalFirstAuth(seed, ttlSeconds, refresh = true) {
1656
+ this._localFirstSecret = seed;
1657
+ this.localFirstRefreshOwned = refresh;
1658
+ if (refresh) {
1659
+ this.scheduleLocalFirstRefresh(ttlSeconds);
434
1660
  }
435
1661
  }
436
- handleFollowerSync(message) {
437
- if (this.tabRole !== "leader")
438
- return;
439
- if (!this.workerBridge)
440
- return;
441
- if (!this.tabId || message.toLeaderTabId !== this.tabId)
442
- return;
443
- if (message.term !== this.currentLeaderTerm)
444
- return;
445
- if (!this.leaderPeerIds.has(message.fromTabId)) {
446
- this.leaderPeerIds.add(message.fromTabId);
447
- this.workerBridge.openPeer(message.fromTabId);
448
- this.logLeaderDebug("peer-open", {
449
- peerId: message.fromTabId,
450
- });
1662
+ scheduleLocalFirstRefresh(ttlSeconds) {
1663
+ if (this.localFirstRefreshTimer) {
1664
+ clearTimeout(this.localFirstRefreshTimer);
451
1665
  }
452
- this.workerBridge.sendPeerSync(message.fromTabId, message.term, message.payload);
1666
+ // Refresh at 80% of TTL
1667
+ const refreshMs = ttlSeconds * 800; // 80% of TTL in ms
1668
+ this.localFirstRefreshTimer = setTimeout(() => {
1669
+ // The token lived to its scheduled refresh, so earlier renewals took.
1670
+ this.localFirstRenewals.reset();
1671
+ this.refreshLocalFirstToken();
1672
+ }, refreshMs);
453
1673
  }
454
- handleLeaderSync(message) {
455
- if (this.tabRole !== "follower")
456
- return;
457
- if (!this.workerBridge)
458
- return;
459
- if (!this.tabId || message.toTabId !== this.tabId)
460
- return;
461
- if (!this.currentLeaderTabId || message.fromLeaderTabId !== this.currentLeaderTabId)
1674
+ refreshLocalFirstToken() {
1675
+ if (!this._localFirstSecret || this.shutdownPromise)
462
1676
  return;
463
- if (message.term !== this.currentLeaderTerm)
464
- return;
465
- for (const payload of message.payload) {
466
- this.workerBridge.applyIncomingServerPayload(payload);
1677
+ try {
1678
+ const ttlSeconds = 3600;
1679
+ const newToken = this.mintLocalFirstToken(this._localFirstSecret, clientScope(this.config), ttlSeconds);
1680
+ const trustedReservedSession = internalSessionFromVerifiedReservedJwtPayload(parseJwtPayload(newToken) ?? {}, "local-first");
1681
+ if (!trustedReservedSession) {
1682
+ throw new Error("Minted local-first token is missing its reserved session identity");
1683
+ }
1684
+ this.applyAuthUpdate(newToken, trustedReservedSession);
1685
+ this.scheduleLocalFirstRefresh(ttlSeconds);
1686
+ }
1687
+ catch (e) {
1688
+ console.error("Failed to refresh local-first token:", e);
467
1689
  }
468
1690
  }
469
- handleFollowerClose(message) {
470
- if (this.tabRole !== "leader")
471
- return;
472
- if (!this.workerBridge)
473
- return;
474
- if (!this.tabId || message.toLeaderTabId !== this.tabId)
475
- return;
476
- if (message.term !== this.currentLeaderTerm)
477
- return;
478
- if (!this.leaderPeerIds.has(message.fromTabId))
479
- return;
480
- this.leaderPeerIds.delete(message.fromTabId);
481
- this.workerBridge.closePeer(message.fromTabId);
482
- this.logLeaderDebug("peer-close", {
483
- peerId: message.fromTabId,
1691
+ mintLocalFirstToken(secret, audience, ttlSeconds) {
1692
+ return this.runtimeSource.mintLocalFirstToken({
1693
+ secret,
1694
+ audience,
1695
+ ttlSeconds,
1696
+ nowSeconds: BigInt(Math.floor(Date.now() / 1000)),
484
1697
  });
485
1698
  }
486
- handleWorkerPeerSync(batch) {
487
- if (this.isShuttingDown)
488
- return;
489
- if (this.tabRole !== "leader")
490
- return;
491
- if (!this.tabId)
492
- return;
493
- if (batch.term !== this.currentLeaderTerm)
1699
+ markUnauthenticated(reason) {
1700
+ try {
1701
+ this.authStateStore.markUnauthenticated(reason);
1702
+ }
1703
+ finally {
1704
+ // Observer failures must not skip renewal of an owned local-first token.
1705
+ if (reason === "expired" && this.localFirstRefreshOwned)
1706
+ this.renewExpiredLocalFirstToken();
1707
+ }
1708
+ }
1709
+ renewExpiredLocalFirstToken() {
1710
+ const delay = this.localFirstRenewals.next();
1711
+ if (delay === 0) {
1712
+ this.refreshLocalFirstToken();
494
1713
  return;
495
- this.postSyncChannelMessage({
496
- type: "leader-sync",
497
- fromLeaderTabId: this.tabId,
498
- toTabId: batch.peerId,
499
- term: batch.term,
500
- payload: batch.payload,
1714
+ }
1715
+ if (this.localFirstRefreshTimer)
1716
+ clearTimeout(this.localFirstRefreshTimer);
1717
+ this.localFirstRefreshTimer = setTimeout(() => this.refreshLocalFirstToken(), delay);
1718
+ }
1719
+ publishAuthStateWithInternalSession(nextSession, publish) {
1720
+ // Commit every snapshot before notifying observers. Observer failures are
1721
+ // reported to the caller without rolling back into a split snapshot.
1722
+ setDbInternalSession(this, nextSession);
1723
+ publish();
1724
+ }
1725
+ applyAuthUpdate(token, trustedReservedSession) {
1726
+ this.runtimeSource.assertAuthUpdateAllowed();
1727
+ const jwtToken = token ?? undefined;
1728
+ const previousToken = this.config.jwtToken;
1729
+ const previousCookieSession = this.config.cookieSession;
1730
+ const previousTrustedReservedSession = getTrustedReservedSession(this.config);
1731
+ const credentialsChanged = previousToken !== jwtToken ||
1732
+ previousCookieSession !== undefined ||
1733
+ JSON.stringify(previousTrustedReservedSession) !== JSON.stringify(trustedReservedSession);
1734
+ if (!credentialsChanged && this.authStateStore.getState().error === undefined)
1735
+ return false;
1736
+ if (!this.authStateStore.validateJwtToken(jwtToken, trustedReservedSession))
1737
+ return false;
1738
+ this.connection.updateAuth({
1739
+ mode: "bearer",
1740
+ jwtToken,
1741
+ trustedReservedSession,
501
1742
  });
1743
+ this.publishAuthUpdate(jwtToken, trustedReservedSession);
1744
+ return true;
502
1745
  }
503
- sendFollowerClose(leaderTabId, term) {
504
- if (!leaderTabId || !this.tabId)
505
- return;
506
- if (leaderTabId === this.tabId)
507
- return;
508
- this.logLeaderDebug("follower-close", {
509
- toLeaderTabId: leaderTabId,
510
- closeTerm: term,
1746
+ publishAuthUpdate(jwtToken, trustedReservedSession) {
1747
+ const nextConfig = {
1748
+ ...this.config,
1749
+ jwtToken,
1750
+ cookieSession: undefined,
1751
+ };
1752
+ setTrustedReservedSession(nextConfig, trustedReservedSession);
1753
+ const nextInternalSession = resolveClientInternalSessionSync(nextConfig);
1754
+ this.config.jwtToken = jwtToken;
1755
+ this.config.cookieSession = undefined;
1756
+ setTrustedReservedSession(this.config, trustedReservedSession);
1757
+ this.publishAuthStateWithInternalSession(nextInternalSession, () => {
1758
+ this.authStateStore.applyJwtToken(jwtToken, trustedReservedSession);
511
1759
  });
512
- this.postSyncChannelMessage({
513
- type: "follower-close",
514
- fromTabId: this.tabId,
515
- toLeaderTabId: leaderTabId,
516
- term,
1760
+ }
1761
+ applyCookieSessionUpdate(session) {
1762
+ this.runtimeSource.assertAuthUpdateAllowed();
1763
+ const cookieSession = session ?? undefined;
1764
+ const previousCookieSession = this.config.cookieSession;
1765
+ const previousToken = this.config.jwtToken;
1766
+ const previousTrustedReservedSession = getTrustedReservedSession(this.config);
1767
+ const sessionChanged = JSON.stringify(previousCookieSession) !== JSON.stringify(cookieSession);
1768
+ const credentialsChanged = previousToken !== undefined || sessionChanged || previousTrustedReservedSession !== undefined;
1769
+ if (!credentialsChanged && this.authStateStore.getState().error === undefined)
1770
+ return false;
1771
+ if (!this.authStateStore.validateCookieSession(cookieSession))
1772
+ return false;
1773
+ this.connection.updateAuth({ mode: "cookie", cookieSession });
1774
+ const nextConfig = {
1775
+ ...this.config,
1776
+ jwtToken: undefined,
1777
+ cookieSession,
1778
+ };
1779
+ const nextInternalSession = resolveClientInternalSessionSync(nextConfig);
1780
+ this.config.jwtToken = undefined;
1781
+ this.config.cookieSession = cookieSession;
1782
+ setTrustedReservedSession(this.config, undefined);
1783
+ this.publishAuthStateWithInternalSession(nextInternalSession, () => {
1784
+ this.authStateStore.applyCookieSession(cookieSession);
517
1785
  });
1786
+ return true;
518
1787
  }
519
- applyBridgeRoutingForCurrentLeader(bridge, replayConnection) {
520
- if (this.tabRole === "leader") {
521
- bridge.setServerPayloadForwarder(null);
522
- this.activeRemoteLeaderTabId = null;
523
- this.logLeaderDebug("upstream-mode", {
524
- mode: "leader-direct",
525
- });
1788
+ /**
1789
+ * Create a Db instance with a loaded runtime source.
1790
+ * @internal Use {@link createDb()} instead.
1791
+ */
1792
+ static create(config, runtimeSource) {
1793
+ return new Db(config, runtimeSource);
1794
+ }
1795
+ /** @internal Create a direct Db after its pre-runtime identity bootstrap. */
1796
+ static async createWithDirectConnection(config, runtimeSource) {
1797
+ const db = new Db(config, runtimeSource);
1798
+ await db.connection.start();
1799
+ return db;
1800
+ }
1801
+ /** @internal Create a Db whose durable peer lives in a dedicated browser worker. */
1802
+ static async createWithBrowserWorker(config, runtimeSource, earlyLease) {
1803
+ const db = new Db(config, runtimeSource);
1804
+ const connection = new BrowserConnectionManager(db.dbForConnection(), earlyLease);
1805
+ db.connection = connection;
1806
+ await connection.start();
1807
+ return db;
1808
+ }
1809
+ /**
1810
+ * Get or create a JazzClient for the given schema.
1811
+ * Synchronous because the runtime source is loaded before Db is created.
1812
+ *
1813
+ */
1814
+ getClient(schema) {
1815
+ this.assertOpen();
1816
+ return this.connection.getClient(schema);
1817
+ }
1818
+ getCurrentClient() {
1819
+ return this.connection.getCurrentClient();
1820
+ }
1821
+ /** @internal The runtime behind this Db's client, once it exists. */
1822
+ currentRuntime() {
1823
+ return this.getCurrentClient()?.getRuntime() ?? null;
1824
+ }
1825
+ /**
1826
+ * @internal Read each runtime query at the remote tier, so that this Db's
1827
+ * store holds what the server holds for it before anything subscribes.
1828
+ */
1829
+ async prefetchRuntimeQueries(schema, queryJsons) {
1830
+ const client = this.getClient(schema);
1831
+ await this.ensureReady("server");
1832
+ await Promise.all(queryJsons.map((queryJson) => client.query(queryJson, { tier: "remote" })));
1833
+ }
1834
+ async ensureReady(requirement, signal) {
1835
+ await this.connection.ensureReady(requirement, signal ?? this.shutdownAbort.signal);
1836
+ this.assertOpen();
1837
+ }
1838
+ wrapWriteWait(handle) {
1839
+ notifyLocalWrite(this);
1840
+ return setWriteWaitReadiness(handle, async (tier) => {
1841
+ // A write made before this Db handed over to a successor waits on its
1842
+ // own runtime's last uploads, which the drain keeps going.
1843
+ if (this.drain)
1844
+ return;
1845
+ await this.ensureReady(tier === "global" ? "upload" : "runtime");
1846
+ });
1847
+ }
1848
+ getAccessContext() {
1849
+ // Ordinary Dbs use the client's session. BackendDb overrides this to supply
1850
+ // per-Db session and attribution without changing the shared client's identity.
1851
+ return null;
1852
+ }
1853
+ handleMutationError(event, logged = false) {
1854
+ // A write this Db took before the upgrade, rejected while it uploads:
1855
+ // the app's listeners are on the successor now.
1856
+ if (this.successor)
1857
+ return this.successor.handleMutationError(event, logged);
1858
+ if (this.mutationErrorListeners.size === 0) {
1859
+ if (!logged)
1860
+ console.error("Unhandled Jazz mutation error", event);
1861
+ this.pendingMutationErrorEvents.push(event);
1862
+ return;
526
1863
  }
527
- else {
528
- bridge.setServerPayloadForwarder((payload) => {
529
- if (!this.tabId || !this.currentLeaderTabId)
530
- return;
531
- if (this.currentLeaderTabId === this.tabId)
532
- return;
533
- this.postSyncChannelMessage({
534
- type: "follower-sync",
535
- fromTabId: this.tabId,
536
- toLeaderTabId: this.currentLeaderTabId,
537
- term: this.currentLeaderTerm,
538
- payload: [payload],
539
- });
540
- });
541
- this.activeRemoteLeaderTabId = this.currentLeaderTabId;
542
- this.logLeaderDebug("upstream-mode", {
543
- mode: "follower-via-leader",
544
- upstreamLeaderTabId: this.currentLeaderTabId,
545
- });
1864
+ for (const listener of this.mutationErrorListeners) {
1865
+ listener(event);
1866
+ }
1867
+ }
1868
+ /** @internal Refresh only through the immutable handle that owns this context. */
1869
+ async refreshAccountAuth(account) {
1870
+ return this.refreshOwnAccountAuth(account);
1871
+ }
1872
+ /**
1873
+ * @internal Renew this Db's own runtime's credential. Its account context
1874
+ * calls this rather than {@link refreshAccountAuth}, which after the
1875
+ * local-first upgrade renews the successor: the thin runtime still needs
1876
+ * its own credential to finish uploading.
1877
+ */
1878
+ async refreshOwnAccountAuth(account) {
1879
+ assertAccountConfig(this.config);
1880
+ const current = getDbInternalSession(this);
1881
+ if (account.id !== this.config.accountId ||
1882
+ accountRegistry(account) !== this.config.accountRegistryAuthority ||
1883
+ account.identity.issuer !== current?.issuer ||
1884
+ account.identity.subject !== current?.user_id)
1885
+ throw new Error("Account context mismatch");
1886
+ try {
1887
+ const token = await accountToken(account, accountRegistry(account));
1888
+ if (this.shutdownAbort.signal.aborted)
1889
+ throw new Error("Account context closed");
1890
+ const reserved = account.identity.issuer === "urn:jazz:local-first"
1891
+ ? internalSessionFromVerifiedReservedJwtPayload(parseJwtPayload(token) ?? {}, "local-first")
1892
+ : undefined;
1893
+ if (!this.authStateStore.validateJwtToken(token, reserved ?? undefined))
1894
+ return token;
1895
+ this.connection.refreshAccountAuth(token, reserved ?? undefined);
1896
+ this.publishAuthUpdate(token, reserved ?? undefined);
1897
+ return token;
546
1898
  }
547
- if (replayConnection) {
548
- bridge.replayServerConnection();
549
- this.logLeaderDebug("upstream-replay");
1899
+ catch (error) {
1900
+ this.markUnauthenticated("invalid");
1901
+ throw error;
550
1902
  }
551
1903
  }
552
- onLeaderElectionChange(snapshot) {
553
- if (this.isShuttingDown || !this.primaryDbName)
554
- return;
555
- const previousRole = this.tabRole;
556
- const previousLeaderTabId = this.currentLeaderTabId;
557
- const previousTerm = this.currentLeaderTerm;
558
- this.adoptLeaderSnapshot(snapshot);
559
- this.logLeaderDebug("leader-change", {
560
- previousRole,
561
- previousLeaderTabId,
562
- previousTerm,
1904
+ updateAuthToken(jwtToken) {
1905
+ this.applyAuthUpdate(jwtToken);
1906
+ }
1907
+ updateCookieSession(cookieSession) {
1908
+ this.applyCookieSessionUpdate(cookieSession);
1909
+ }
1910
+ getAuthState() {
1911
+ return this.authStateStore.getState();
1912
+ }
1913
+ /**
1914
+ * Mint a short-lived local-first JWT proving possession of the current identity.
1915
+ * Returns `null` if the current session is not local-first.
1916
+ */
1917
+ getLocalFirstIdentityProof(options) {
1918
+ if (!this._localFirstSecret) {
1919
+ return null;
1920
+ }
1921
+ const ttl = options?.ttlSeconds ?? 60;
1922
+ const audience = options?.audience ?? clientScope(this.config);
1923
+ return this.mintLocalFirstToken(this._localFirstSecret, audience, ttl);
1924
+ }
1925
+ /** @internal This Db's own runtime's auth state changes, which never move to a successor. */
1926
+ onOwnAuthChanged(listener) {
1927
+ return this.authStateStore.onChange((state) => listener(state));
1928
+ }
1929
+ onAuthChanged(listener) {
1930
+ return this.registerMovable((db) => db.authStateStore.onChange((state) => {
1931
+ listener(state);
1932
+ }));
1933
+ }
1934
+ /**
1935
+ * Register something on this Db that moves to its successor when the
1936
+ * session upgrades it to the local-first client, so code holding the
1937
+ * returned handle keeps hearing from whichever Db does the work.
1938
+ */
1939
+ registerMovable(register,
1940
+ // Register again on this Db rather than on its successor: for what this
1941
+ // Db answers itself after the upgrade (its sync status covers the writes
1942
+ // its own runtime is still uploading).
1943
+ reregisterHere = false) {
1944
+ let detach = register(this);
1945
+ let closed = false;
1946
+ const entry = {
1947
+ move: (next) => {
1948
+ if (closed)
1949
+ return;
1950
+ detach();
1951
+ detach = reregisterHere ? register(this) : next.registerMovable(register);
1952
+ },
1953
+ };
1954
+ this.movable.add(entry);
1955
+ return () => {
1956
+ if (closed)
1957
+ return;
1958
+ closed = true;
1959
+ this.movable.delete(entry);
1960
+ detach();
1961
+ };
1962
+ }
1963
+ /**
1964
+ * Attach a fallback listener for write rejections that are not handled by an
1965
+ * active {@link WriteHandle.wait} call.
1966
+ *
1967
+ * @returns an unsubscribe callback
1968
+ */
1969
+ onMutationError(listener) {
1970
+ if (this.replaced)
1971
+ throw this.replaced;
1972
+ return this.registerMovable((db) => {
1973
+ db.mutationErrorListeners.add(listener);
1974
+ while (db.pendingMutationErrorEvents.length > 0) {
1975
+ listener(db.pendingMutationErrorEvents.shift());
1976
+ }
1977
+ return () => {
1978
+ db.mutationErrorListeners.delete(listener);
1979
+ };
563
1980
  });
564
- if (previousRole === "follower" && previousLeaderTabId !== this.currentLeaderTabId) {
565
- this.sendFollowerClose(previousLeaderTabId, previousTerm);
566
- }
567
- const nextDbName = Db.resolveWorkerDbNameForSnapshot(this.primaryDbName, snapshot);
568
- const dbNameChanged = nextDbName !== this.workerDbName;
569
- this.workerDbName = nextDbName;
570
- // No bridge means no runtime server edge exists yet.
571
- if (!this.workerBridge)
572
- return;
573
- this.enqueueWorkerReconfigure(async () => {
574
- if (this.isShuttingDown)
1981
+ }
1982
+ /**
1983
+ * Stateless anchors and ranges into text values, such as cursors,
1984
+ * selections and comments on a text column: captured from one value and
1985
+ * found again in later ones by the text around them.
1986
+ */
1987
+ textAnchors() {
1988
+ return this.runtimeSource.textAnchors();
1989
+ }
1990
+ /**
1991
+ * Whether this Db's writes have reached the server: the upstream
1992
+ * connection, and how many committed transactions the server has not
1993
+ * accepted or rejected yet. The same object is returned until the status
1994
+ * changes, so it can back `useSyncExternalStore` directly. In a browser,
1995
+ * agents and tests read the same through `window.__jazz.status()`.
1996
+ */
1997
+ getSyncStatus() {
1998
+ const next = this.connection.syncStatus();
1999
+ if (this.syncStatusSnapshot && sameSyncStatus(next, this.syncStatusSnapshot)) {
2000
+ return this.syncStatusSnapshot;
2001
+ }
2002
+ this.syncStatusSnapshot = next;
2003
+ return next;
2004
+ }
2005
+ /**
2006
+ * Call `listener` whenever {@link getSyncStatus} changes.
2007
+ *
2008
+ * @returns an unsubscribe callback
2009
+ */
2010
+ onSyncStatusChange(listener) {
2011
+ let last = this.getSyncStatus();
2012
+ const deliver = (status) => {
2013
+ if (status === last || sameSyncStatus(status, last))
575
2014
  return;
576
- if (dbNameChanged) {
577
- this.logLeaderDebug("worker-restart", {
578
- reason: "db-name-change",
579
- });
580
- await this.restartWorkerWithCurrentDbName();
2015
+ last = status;
2016
+ listener(status);
2017
+ };
2018
+ return this.registerMovable((db) => {
2019
+ const stop = db.syncStatusChangeRegistration(deliver);
2020
+ // Moved at the upgrade: the status now covers both runtimes.
2021
+ if (db.successor)
2022
+ deliver(db.getSyncStatus());
2023
+ return stop;
2024
+ }, true);
2025
+ }
2026
+ /** How this Db reports sync status changes: its own, or combined with its successor's. */
2027
+ syncStatusChangeRegistration(listener) {
2028
+ return this.onSyncStatusChangeHere(listener);
2029
+ }
2030
+ onSyncStatusChangeHere(listener) {
2031
+ const subscription = new AbortController();
2032
+ const end = () => subscription.abort();
2033
+ this.shutdownAbort.signal.addEventListener("abort", end, { once: true });
2034
+ subscription.signal.addEventListener("abort", () => this.shutdownAbort.signal.removeEventListener("abort", end), { once: true });
2035
+ let published = this.getSyncStatus();
2036
+ this.connection.onSyncStatusChange(() => {
2037
+ const status = this.getSyncStatus();
2038
+ if (status === published)
581
2039
  return;
582
- }
583
- if (this.workerBridge) {
584
- this.applyBridgeRoutingForCurrentLeader(this.workerBridge, true);
585
- }
2040
+ published = status;
2041
+ listener(status);
2042
+ }, subscription.signal);
2043
+ return end;
2044
+ }
2045
+ /**
2046
+ * Resolve once every write committed on this Db before the call has been
2047
+ * accepted by the server.
2048
+ *
2049
+ * Like `write.wait({ tier: "global" })`, the wait lasts through network
2050
+ * outages, reconnects and credential renewal. It rejects with the
2051
+ * server's error for the first of those writes it rejected, when the link
2052
+ * stops for good, with a {@link WriteWaitTimeoutError} once `timeoutMs`
2053
+ * passes, or with `signal.reason` when `signal` aborts. Ending the wait
2054
+ * never cancels the writes: they stay queued. In a browser tab it covers
2055
+ * that tab's own writes, not ones the shared worker recovered from storage.
2056
+ */
2057
+ async waitForSync(options = {}) {
2058
+ const { timeoutMs, signal } = options;
2059
+ validateWriteWaitTimeout(timeoutMs);
2060
+ this.assertOpen();
2061
+ signal?.throwIfAborted();
2062
+ const control = new AbortController();
2063
+ const forward = () => control.abort(signal.reason);
2064
+ signal?.addEventListener("abort", forward, { once: true });
2065
+ // Shutdown ends the wait instead of leaving it parked on a closed runtime.
2066
+ const shutdown = () => control.abort(new Error("Db was shut down"));
2067
+ this.shutdownAbort.signal.addEventListener("abort", shutdown, {
2068
+ once: true,
586
2069
  });
2070
+ const timer = timeoutMs === undefined
2071
+ ? undefined
2072
+ : setTimeout(() => control.abort(new WriteWaitTimeoutError("global", timeoutMs)), timeoutMs);
2073
+ try {
2074
+ await this.connection.waitForSync(control.signal);
2075
+ }
2076
+ finally {
2077
+ if (timer !== undefined)
2078
+ clearTimeout(timer);
2079
+ signal?.removeEventListener("abort", forward);
2080
+ this.shutdownAbort.signal.removeEventListener("abort", shutdown);
2081
+ }
587
2082
  }
588
- enqueueWorkerReconfigure(task) {
589
- this.workerReconfigure = this.workerReconfigure.then(task).catch((error) => {
590
- console.error("[db] Worker reconfigure failed:", error);
2083
+ getConfig() {
2084
+ // Return a copy without internal live transport handles. MessagePorts are
2085
+ // neither configuration nor cloneable unless transferred.
2086
+ const { browserWorkerPort: _browserWorkerPort, browserWorkerSession: _browserWorkerSession, ...runtimeSources } = this.config.runtimeSources ?? {};
2087
+ return structuredClone({
2088
+ ...this.config,
2089
+ runtimeSources: Object.keys(runtimeSources).length > 0 ? runtimeSources : undefined,
591
2090
  });
592
2091
  }
593
- async restartWorkerWithCurrentDbName() {
594
- const currentWorker = this.worker;
595
- if (!currentWorker)
596
- return;
597
- // If bridge init is in flight, wait before tearing down.
598
- if (this.bridgeReady) {
599
- await this.bridgeReady;
600
- }
601
- if (this.workerBridge) {
602
- try {
603
- await this.workerBridge.shutdown(currentWorker);
604
- }
605
- catch {
606
- // Best effort
607
- }
608
- this.workerBridge = null;
2092
+ setDevMode(enabled) {
2093
+ this.config.devMode = enabled;
2094
+ }
2095
+ /**
2096
+ * Temporarily disconnect this Db from its configured Jazz sync server.
2097
+ *
2098
+ * Local reads and writes can continue while disconnected. Call
2099
+ * {@link reconnect} to resume sync using the same Db instance.
2100
+ */
2101
+ async disconnect() {
2102
+ if (this.shutdownPromise) {
2103
+ throw new Error("Cannot disconnect a Db that is shutting down.");
609
2104
  }
610
- this.bridgeReady = null;
611
- currentWorker.terminate();
612
- this.worker = await Db.spawnWorker();
613
- // Re-attach immediately for existing client runtime(s) so subscriptions replay.
614
- const first = this.clients.entries().next();
615
- if (!first.done) {
616
- const [schemaJson, client] = first.value;
617
- this.attachWorkerBridge(schemaJson, client);
618
- if (this.bridgeReady) {
619
- await this.bridgeReady;
620
- }
2105
+ this.offlineRequested = true;
2106
+ await this.connection.disconnect();
2107
+ }
2108
+ /**
2109
+ * Reconnect this Db to its configured Jazz sync server after
2110
+ * {@link disconnect}.
2111
+ */
2112
+ async reconnect() {
2113
+ // Sync recovery is safe before teardown starts; it must remain available
2114
+ // while a graceful transition waits for previously committed writes.
2115
+ if (this.shutdownPromise && !this.cancelSyncShutdown) {
2116
+ throw new Error("Cannot reconnect a Db that is shutting down.");
621
2117
  }
2118
+ this.offlineRequested = false;
2119
+ await this.connection.reconnect();
622
2120
  }
623
- static resolveWorkerDbNameForSnapshot(primaryDbName, snapshot) {
624
- if (snapshot.role === "leader")
625
- return primaryDbName;
626
- return `${primaryDbName}__fallback__${snapshot.tabId}`;
2121
+ /**
2122
+ * @internal
2123
+ */
2124
+ getActiveQuerySubscriptions() {
2125
+ return Array.from(this.activeQuerySubscriptionTraces.values())
2126
+ .filter((trace) => trace.visibility === "public")
2127
+ .map(({ visibility: _visibility, ...trace }) => cloneActiveQuerySubscriptionTrace(trace));
627
2128
  }
628
- static async spawnWorker() {
629
- const worker = new Worker(new URL("../worker/jazz-worker.js", import.meta.url), {
630
- type: "module",
2129
+ /**
2130
+ * @internal
2131
+ */
2132
+ onActiveQuerySubscriptionsChange(listener) {
2133
+ return this.registerMovable((db) => {
2134
+ db.activeQuerySubscriptionTraceListeners.add(listener);
2135
+ listener(db.getActiveQuerySubscriptions());
2136
+ return () => {
2137
+ db.activeQuerySubscriptionTraceListeners.delete(listener);
2138
+ };
631
2139
  });
632
- await new Promise((resolve, reject) => {
633
- const timeout = setTimeout(() => reject(new Error("Worker WASM load timeout")), 15000);
634
- const handler = (event) => {
635
- if (event.data.type === "ready") {
636
- clearTimeout(timeout);
637
- worker.removeEventListener("message", handler);
638
- resolve();
2140
+ }
2141
+ /**
2142
+ * The engine-normalized runtime schema of this Db's live client, or null
2143
+ * before the client exists. This is a dev-introspection accessor (inspector
2144
+ * host handle, devtools bridge), not a general schema API.
2145
+ */
2146
+ getRuntimeSchema() {
2147
+ return this.connection.getRuntimeSchema();
2148
+ }
2149
+ /** @internal Open a control channel for the same-origin embedded inspector. */
2150
+ openInspectorControlPort(signal) {
2151
+ return this.connection.openInspectorControlPort(signal);
2152
+ }
2153
+ /**
2154
+ * Insert a new row into a table without waiting for durability.
2155
+ *
2156
+ * Use {@link WriteResult.wait} to wait for durable confirmation.
2157
+ *
2158
+ * @param table Table proxy from generated app module
2159
+ * @param data Init object with column values
2160
+ * @returns Write result containing the inserted row
2161
+ */
2162
+ insert(table, data, options) {
2163
+ assertWritableTable(table);
2164
+ const client = this.getClient(table._schema);
2165
+ let id = options?.id ?? (hasDependentTransforms(table) ? reserveRowId() : undefined);
2166
+ const transformedData = table._columnTransforms
2167
+ ? transformInputColumns(table, data, id ? { id } : undefined, true)
2168
+ : data;
2169
+ const values = toWriteRecordForOperation("Insert", transformedData, table._schema, table._table);
2170
+ const context = this.getAccessContext();
2171
+ const deferred = !!getOwnerPreparation(client)?.pending;
2172
+ if (deferred && !id)
2173
+ id = reserveRowId();
2174
+ const value = deferred ? immediateWriteRow(table, id, values) : undefined;
2175
+ const inserted = runAfterPreparation(client, () => client.insert(table._table, values, normalizeSelectorOptions(table._schema, table._table, id ? { ...options, id } : options), context?.writeSession, context?.attribution));
2176
+ return this.wrapWriteWait(inserted instanceof Promise
2177
+ ? new WriteResult(value, inserted.then((result) => result.txId), client)
2178
+ : inserted.mapValue((row) => value !== undefined
2179
+ ? value
2180
+ : transformOutputRow(table, transformRow(row, table._schema, table._table))));
2181
+ }
2182
+ /**
2183
+ * Stream one Text, Json, or Bytea column into a new row. The column's runtime
2184
+ * schema determines encoding; callers never pass a large-value kind.
2185
+ *
2186
+ * Unlike {@link insert}, this is asynchronous because it consumes the source
2187
+ * before publishing. Its handle returns only the generated id so the complete
2188
+ * streamed value is not copied back into JavaScript memory.
2189
+ */
2190
+ async insertStreaming(table, data, options) {
2191
+ assertWritableTable(table);
2192
+ const client = this.getClient(table._schema);
2193
+ const { column, source, values: ordinaryData } = splitStreamingMutation(table, data);
2194
+ rejectIncompleteDependencies(table, ordinaryData, [column]);
2195
+ notifyLocalWrite(this);
2196
+ const id = options?.id ??
2197
+ (missingWriteDependencies(table, ordinaryData).includes("id") ? reserveRowId() : undefined);
2198
+ return runAfterPreparation(client, async () => {
2199
+ const transformedData = transformInputColumns(table, ordinaryData, id ? { id } : {}, true);
2200
+ const values = toWriteRecordForOperation("Insert", transformedData, table._schema, table._table);
2201
+ const context = this.getAccessContext();
2202
+ const branch = deriveStreamingInsertBranch(table, ordinaryData);
2203
+ return client.insertStreaming(table._table, values, column, source, normalizeSelectorOptions(table._schema, table._table, branch
2204
+ ? { ...options, ...(id ? { id } : {}), branch }
2205
+ : id
2206
+ ? { ...options, id }
2207
+ : options), context?.writeSession, context?.attribution);
2208
+ });
2209
+ }
2210
+ async updateStreaming(table, id, data, options) {
2211
+ assertWritableTable(table);
2212
+ const client = this.getClient(table._schema);
2213
+ const { column, source, values: ordinaryData } = splitStreamingMutation(table, data);
2214
+ rejectIncompleteDependencies(table, ordinaryData, [column]);
2215
+ notifyLocalWrite(this);
2216
+ const context = this.getAccessContext();
2217
+ return runAfterPreparation(client, async () => {
2218
+ const transformedData = await prepareInputColumns(table, ordinaryData, "Update", id, client, context?.readSession, undefined, normalizeViewOptions(table._schema, table._table, options));
2219
+ const values = toWriteRecordForOperation("Update", transformedData, table._schema, table._table);
2220
+ return client.updateStreaming(table._table, id, values, column, source, normalizeViewOptions(table._schema, table._table, options), context?.writeSession, context?.attribution);
2221
+ });
2222
+ }
2223
+ async upsertStreaming(table, id, data, options) {
2224
+ assertWritableTable(table);
2225
+ const client = this.getClient(table._schema);
2226
+ const { column, source, values: ordinaryData } = splitStreamingMutation(table, data);
2227
+ rejectIncompleteDependencies(table, ordinaryData, [column]);
2228
+ notifyLocalWrite(this);
2229
+ const context = this.getAccessContext();
2230
+ return runAfterPreparation(client, async () => {
2231
+ const transformedData = await prepareInputColumns(table, ordinaryData, "Upsert", id, client, context?.readSession, undefined, normalizeViewOptions(table._schema, table._table, options));
2232
+ const values = toWriteRecordForOperation("Upsert", transformedData, table._schema, table._table);
2233
+ return client.upsertStreaming(table._table, id, values, column, source, normalizeViewOptions(table._schema, table._table, options), context?.writeSession, context?.attribution);
2234
+ });
2235
+ }
2236
+ /**
2237
+ * Restore a soft-deleted row without waiting for durability.
2238
+ *
2239
+ * Use {@link WriteResult.wait} to wait for durable confirmation.
2240
+ */
2241
+ restore(table, id, data, options) {
2242
+ assertWritableTable(table);
2243
+ const client = this.getClient(table._schema);
2244
+ const transformedData = table._columnTransforms
2245
+ ? transformInputColumns(table, data, { id }, true)
2246
+ : data;
2247
+ const values = toWriteRecordForOperation("Restore", transformedData, table._schema, table._table);
2248
+ const context = this.getAccessContext();
2249
+ const deferred = !!getOwnerPreparation(client)?.pending;
2250
+ const value = deferred ? immediateWriteRow(table, id, values) : undefined;
2251
+ const restored = runAfterPreparation(client, () => client.restore(table._table, id, values, normalizeSelectorOptions(table._schema, table._table, options), context?.writeSession, context?.attribution));
2252
+ return this.wrapWriteWait(restored instanceof Promise
2253
+ ? new WriteResult(value, restored.then((result) => result.txId), client)
2254
+ : restored.mapValue((row) => transformOutputRow(table, transformRow(row, table._schema, table._table))));
2255
+ }
2256
+ /**
2257
+ * Create or update a row with a caller-supplied id without waiting for durability.
2258
+ *
2259
+ * Use {@link WriteHandle.wait} to wait for durable confirmation.
2260
+ */
2261
+ upsert(table, id, data, options) {
2262
+ assertWritableTable(table);
2263
+ return this.prepareMutation(table, id, data, "Upsert", options);
2264
+ }
2265
+ prepareMutation(table, id, data, operation, options, stage) {
2266
+ const client = this.getClient(table._schema);
2267
+ const missing = missingWriteDependencies(table, data, id);
2268
+ if (getOwnerPreparation(client)?.pending || missing.length)
2269
+ data = { ...data };
2270
+ const context = this.getAccessContext();
2271
+ const normalized = normalizeViewOptions(table._schema, table._table, options);
2272
+ const result = runAfterPreparation(client, () => {
2273
+ const submit = (record, transaction) => {
2274
+ const values = toWriteRecordForOperation(operation, record, table._schema, table._table);
2275
+ if (stage)
2276
+ return stage(values);
2277
+ if (transaction) {
2278
+ if (operation === "Upsert")
2279
+ client.upsertInternal(table._table, id, values, normalized, context?.writeSession, context?.attribution, transaction);
2280
+ else
2281
+ client.updateInternal(table._table, id, values, normalized?.updatedAt, context?.writeSession, context?.attribution, transaction, normalized?.branch);
2282
+ return client.commitTransaction(transaction);
639
2283
  }
640
- else if (event.data.type === "error") {
641
- clearTimeout(timeout);
642
- worker.removeEventListener("message", handler);
643
- reject(new Error(event.data.message));
2284
+ return operation === "Upsert"
2285
+ ? client.upsert(table._table, id, values, normalized, context?.writeSession, context?.attribution)
2286
+ : client.update(table._table, id, values, normalized, context?.writeSession, context?.attribution);
2287
+ };
2288
+ if (missing.length === 0) {
2289
+ const record = table._columnTransforms ? transformInputColumns(table, data, { id }) : data;
2290
+ if (operation !== "Update")
2291
+ return submit(record);
2292
+ try {
2293
+ return submit(record);
2294
+ }
2295
+ catch (error) {
2296
+ // An update stages against the row's current cells. When this
2297
+ // replica has not loaded the row yet (a fresh process, another
2298
+ // instance), read it through the caller's session and stage again;
2299
+ // later writes wait behind this one, so their order holds.
2300
+ if (nativeCoreErrorCode(error) !== "not_observed")
2301
+ throw error;
2302
+ // The read's row count is not the answer: this replica may filter
2303
+ // out a row it now holds, lacking the rows that grant the session
2304
+ // access, and only the authority decides whether the session may
2305
+ // write it. Stage again whatever came back.
2306
+ return loadRow(client, table, id, context?.readSession, normalized?.branch).then(() => {
2307
+ try {
2308
+ return submit(record);
2309
+ }
2310
+ catch (retryError) {
2311
+ // Still not held: the server sent no row, so it does not exist
2312
+ // or the session may not read it, and the two are refused alike,
2313
+ // with the denial's code, as the authority answers.
2314
+ if (nativeCoreErrorCode(retryError) !== "not_observed")
2315
+ throw retryError;
2316
+ throw unreadableTargetError("Update", table._table);
2317
+ }
2318
+ });
2319
+ }
2320
+ }
2321
+ const transaction = client.beginTransaction("mergeable", context?.writeSession, context?.attribution);
2322
+ // An empty mergeable transaction has no staged overlay or read set. Native branch reads
2323
+ // currently require the ordinary scoped path; explicit transactions still fail closed.
2324
+ return Promise.resolve(prepareInputColumns(table, data, operation, id, client, context?.readSession, normalized?.branch ? undefined : transaction, normalized, missing))
2325
+ .then(async (record) => {
2326
+ // Partial edits already own their native transaction; mergeable reads add no read precondition.
2327
+ if (stage) {
2328
+ await client.rollbackTransaction(transaction);
2329
+ return submit(record);
644
2330
  }
645
- };
646
- worker.addEventListener("message", handler);
647
- worker.addEventListener("error", (e) => {
648
- clearTimeout(timeout);
649
- reject(new Error(`Worker load error: ${e.message}`));
2331
+ return submit(record, transaction);
2332
+ })
2333
+ .catch(async (error) => {
2334
+ await client.rollbackTransaction(transaction).catch(() => { });
2335
+ throw error;
650
2336
  });
651
2337
  });
652
- return worker;
2338
+ return this.wrapWriteWait(result instanceof Promise
2339
+ ? new WriteHandle(result.then((handle) => handle.txId), client)
2340
+ : result);
2341
+ }
2342
+ update(table, id, data, options) {
2343
+ assertWritableTable(table);
2344
+ const client = this.getClient(table._schema);
2345
+ const { replacements, descriptors } = lowerUpdate(table, data, options);
2346
+ options = withoutEditedFrom(options);
2347
+ const context = this.getAccessContext();
2348
+ if (descriptors.length > 0) {
2349
+ return this.prepareMutation(table, id, replacements, "Update", options, (updates) => client.updateLargeValues(table._table, id, updates, descriptors, normalizeViewOptions(table._schema, table._table, options), context?.writeSession, context?.attribution));
2350
+ }
2351
+ return this.prepareMutation(table, id, data, "Update", options);
653
2352
  }
654
2353
  /**
655
- * Insert a new row into a table.
656
- *
657
- * This is a **synchronous** operation - the row is created immediately
658
- * in the local WASM runtime. Sync to server happens asynchronously.
659
- *
660
- * @param table Table proxy from generated app module
661
- * @param data Init object with column values
662
- * @returns The new row's ID (UUID string)
2354
+ * Delete a row without waiting for durability.
663
2355
  *
664
- * @example
665
- * ```typescript
666
- * const id = db.insert(app.todos, { title: "Buy milk", done: false });
667
- * ```
2356
+ * Use {@link WriteHandle.wait} to wait for durable confirmation.
668
2357
  */
669
- insert(table, data) {
2358
+ delete(table, id, options) {
2359
+ assertWritableTable(table);
2360
+ const client = this.getClient(table._schema);
2361
+ const context = this.getAccessContext();
2362
+ const result = runAfterPreparation(client, () => client.delete(table._table, id, normalizeViewOptions(table._schema, table._table, options), context?.writeSession, context?.attribution));
2363
+ return this.wrapWriteWait(result instanceof Promise
2364
+ ? new WriteHandle(result.then((handle) => handle.txId), client)
2365
+ : result);
2366
+ }
2367
+ /** Request authoritative permission advice for inserting a row. */
2368
+ async canInsert(table, data) {
2369
+ const client = this.getClient(table._schema);
2370
+ const values = writeRecord("Insert", table, data);
2371
+ const context = this.getAccessContext();
2372
+ return client.requestInsertPermissionAdvice(table._table, values, context?.writeSession);
2373
+ }
2374
+ /** Request authoritative permission advice for reading a row. */
2375
+ async canRead(table, id) {
670
2376
  const client = this.getClient(table._schema);
671
- const values = toValueArray(data, table._schema, table._table);
672
- return client.create(table._table, values);
2377
+ const context = this.getAccessContext();
2378
+ return client.requestReadPermissionAdvice(table._table, id, context?.readSession);
2379
+ }
2380
+ /** Request authoritative permission advice for updating a row. */
2381
+ async canUpdate(table, id, data) {
2382
+ const client = this.getClient(table._schema);
2383
+ const updates = writeRecord("Update", table, data);
2384
+ const context = this.getAccessContext();
2385
+ return client.requestUpdatePermissionAdvice(table._table, id, updates, context?.writeSession);
2386
+ }
2387
+ /** Request authoritative permission advice for deleting a row. */
2388
+ async canDelete(table, id) {
2389
+ const client = this.getClient(table._schema);
2390
+ const context = this.getAccessContext();
2391
+ return client.requestDeletePermissionAdvice(table._table, id, context?.writeSession);
2392
+ }
2393
+ /** @internal Shared construction path; admission remains owned by the transaction. */
2394
+ createTransaction(kind, prerequisite) {
2395
+ this.assertOpen();
2396
+ notifyLocalWrite(this);
2397
+ const context = this.getAccessContext();
2398
+ const ownerClient = this.getCurrentClient();
2399
+ if (kind === "serializable" && !ownerClient) {
2400
+ throw new Error("Cannot begin a serializable transaction before the JazzClient has been created. Run a query or mutation first.");
2401
+ }
2402
+ return Transaction.createWithAdmission(kind, (schema) => this.getClient(schema), context, ownerClient ?? undefined, prerequisite);
673
2403
  }
674
2404
  /**
675
- * Insert a new row and wait for acknowledgement at the specified tier.
676
- *
677
- * @param table Table proxy from generated app module
678
- * @param data Init object with column values
679
- * @param tier Acknowledgement tier to wait for
680
- * @returns Promise resolving to the new row's ID when the tier acknowledges
2405
+ * Capture this database's local read frontier for a frozen branch base.
681
2406
  *
682
- * @example
683
- * ```typescript
684
- * const id = await db.insertWithAck(app.todos, { title: "Buy milk", done: false }, "edge");
685
- * ```
2407
+ * Includes earlier locally committed writes, including pending server
2408
+ * acceptance, and excludes uncommitted transaction changes and later writes.
2409
+ * Works offline after the first query or mutation has attached a schema.
2410
+ * The reference does not retain history or grant permission. Persist it with
2411
+ * `serializeSnapshotRef`; restoring it requires the same dataset and enough
2412
+ * retained history to answer the requested read.
686
2413
  */
687
- async insertWithAck(table, data, tier) {
688
- const client = this.getClient(table._schema);
689
- await this.ensureBridgeReady();
690
- const values = toValueArray(data, table._schema, table._table);
691
- return client.createWithAck(table._table, values, tier);
2414
+ async captureSnapshot() {
2415
+ this.assertOpen();
2416
+ const client = this.getCurrentClient();
2417
+ if (!client) {
2418
+ throw new Error("Cannot capture a snapshot before a schema is attached. Run a query or mutation first.");
2419
+ }
2420
+ // Admit capture now, before later writes, including writes whose async
2421
+ // transforms share this owner's preparation queue.
2422
+ return runAfterPreparation(client, () => client.captureSnapshot());
692
2423
  }
693
2424
  /**
694
- * @deprecated Use insertWithAck().
2425
+ * Begin a mergeable transaction.
2426
+ *
2427
+ * Use {@link Transaction.commit} to commit the transaction.
2428
+ *
2429
+ * Prefer using {@link Db.transaction} when an explicit commit is not required.
695
2430
  */
696
- async insertPersisted(table, data, tier) {
697
- return this.insertWithAck(table, data, tier);
2431
+ beginTransaction() {
2432
+ return this.createTransaction("mergeable");
698
2433
  }
699
2434
  /**
700
- * Update an existing row.
2435
+ * Begin a serializable transaction for writes that need serializable validation by the authority.
701
2436
  *
702
- * This is a **synchronous** operation - the row is updated immediately
703
- * in the local WASM runtime. Sync to server happens asynchronously.
2437
+ * Use {@link Transaction.commit} to commit the transaction.
704
2438
  *
705
- * @param table Table proxy from generated app module
706
- * @param id Row ID to update
707
- * @param data Partial object with fields to update
2439
+ * Prefer using {@link Db.serializableTransaction} when an explicit commit is not required.
2440
+ */
2441
+ beginSerializableTransaction() {
2442
+ return this.createTransaction("serializable");
2443
+ }
2444
+ /**
2445
+ * Run {@link callback} inside a mergeable transaction and commit it once the callback returns.
708
2446
  *
709
- * @example
710
- * ```typescript
711
- * db.update(app.todos, id, { done: true });
712
- * ```
2447
+ * @returns a write result containing the result of the callback
713
2448
  */
714
- update(table, id, data) {
715
- const client = this.getClient(table._schema);
716
- const updates = toUpdateRecord(data, table._schema, table._table);
717
- client.update(id, updates);
2449
+ transaction(callback) {
2450
+ const transaction = this.beginTransaction();
2451
+ return runInTransaction(transaction, callback, () => getDbTxHandleBinding(transaction, "result").ownerClient);
718
2452
  }
719
2453
  /**
720
- * Update an existing row and wait for acknowledgement at the specified tier.
2454
+ * Run {@link callback} inside a serializable transaction and commit it once the callback returns.
721
2455
  *
722
- * @param table Table proxy from generated app module
723
- * @param id Row ID to update
724
- * @param data Partial object with fields to update
725
- * @param tier Acknowledgement tier to wait for
2456
+ * @returns a write result containing the result of the callback
726
2457
  */
727
- async updateWithAck(table, id, data, tier) {
728
- const client = this.getClient(table._schema);
729
- await this.ensureBridgeReady();
730
- const updates = toUpdateRecord(data, table._schema, table._table);
731
- await client.updateWithAck(id, updates, tier);
2458
+ serializableTransaction(callback) {
2459
+ const transaction = this.beginSerializableTransaction();
2460
+ return runInTransaction(transaction, callback, () => getDbTxHandleBinding(transaction, "result").ownerClient);
732
2461
  }
733
2462
  /**
734
- * @deprecated Use updateWithAck().
2463
+ * Move this app from the thin client to the local-first one, loading it with
2464
+ * `loader` (for example `() => import("jazz-tools/local-first")`). Under a
2465
+ * Jazz provider the provider swaps in the local-first `Db` once it holds the
2466
+ * app's live queries, and this resolves then. A local-first `Db` resolves at
2467
+ * once. (A thin `Db` opened directly, outside a session, upgrades with
2468
+ * `upgradeToLocalFirst(thin, open)` from `jazz-tools/thin`, which returns
2469
+ * the new `Db` for the app to swap in itself.)
735
2470
  */
736
- async updatePersisted(table, id, data, tier) {
737
- await this.updateWithAck(table, id, data, tier);
2471
+ async upgradeToLocalFirst(loader) {
2472
+ await upgradeDbToLocalFirst(this, loader);
738
2473
  }
739
2474
  /**
740
- * Delete a row.
741
- *
742
- * This is a **synchronous** operation - the row is deleted immediately
743
- * in the local WASM runtime. Sync to server happens asynchronously.
744
- *
745
- * @param table Table proxy from generated app module
746
- * @param id Row ID to delete
747
- *
748
- * @example
749
- * ```typescript
750
- * db.deleteFrom(app.todos, id);
751
- * ```
2475
+ * Whether this `Db` reads and writes through a local store: true for a
2476
+ * local-first `Db`, and for a thin one once its session has upgraded it
2477
+ * (the same `Db` carries on), false for a thin one before. To wait for the
2478
+ * upgrade, `await db.upgradeToLocalFirst(loader)`.
752
2479
  */
753
- deleteFrom(table, id) {
754
- const client = this.getClient(table._schema);
755
- client.delete(id);
2480
+ isLocalFirst() {
2481
+ return !isThinDb(this);
756
2482
  }
757
2483
  /**
758
- * Delete a row and wait for acknowledgement at the specified tier.
759
- *
760
- * @param table Table proxy from generated app module
761
- * @param id Row ID to delete
762
- * @param tier Acknowledgement tier to wait for
2484
+ * Delete browser IndexedDB storage for this Db's active namespace.
763
2485
  */
764
- async deleteFromWithAck(table, id, tier) {
765
- const client = this.getClient(table._schema);
766
- await this.ensureBridgeReady();
767
- await client.deleteWithAck(id, tier);
2486
+ async deleteClientStorage() {
2487
+ await this.connection.deleteClientStorage();
2488
+ }
2489
+ /**
2490
+ * @internal {@link deleteClientStorage}, saying how many of the store's
2491
+ * writes (any tab's) the server hadn't confirmed: the delete took them.
2492
+ * `undefined` when the runtime can't say.
2493
+ */
2494
+ async wipeClientStorage() {
2495
+ const deletion = await this.connection.deleteClientStorage();
2496
+ return { pendingUploads: deletion ? deletion.pendingUploads : undefined };
768
2497
  }
769
2498
  /**
770
- * @deprecated Use deleteFromWithAck().
2499
+ * @internal Whether this Db still reads and writes: it isn't shutting down
2500
+ * or replaced, and its storage wasn't reset under it. A session whose
2501
+ * sign-out or sign-in failed keeps a usable Db rather than ending in error.
771
2502
  */
772
- async deleteFromPersisted(table, id, tier) {
773
- await this.deleteFromWithAck(table, id, tier);
2503
+ isUsable() {
2504
+ return !this.shutdownPromise && !this.replaced && this.connection.isUsable();
2505
+ }
2506
+ /**
2507
+ * Release the current Db instance for logout flows.
2508
+ *
2509
+ * When `wipeData` is enabled, Jazz clears local client storage before shutting this Db down.
2510
+ * Callers should still sign out of their external auth provider separately and recreate
2511
+ * `JazzProvider` / `Db` after logout.
2512
+ */
2513
+ async logout(options = {}) {
2514
+ if (options.wipeData) {
2515
+ await this.deleteClientStorage();
2516
+ }
2517
+ await this.shutdown();
774
2518
  }
775
2519
  /**
776
2520
  * Execute a query and return all matching rows as typed objects.
@@ -778,46 +2522,115 @@ export class Db {
778
2522
  * @param query QueryBuilder instance (e.g., app.todos.where({done: false}))
779
2523
  * @returns Array of typed objects matching the query
780
2524
  */
781
- async all(query, settledTier) {
2525
+ async all(query, options) {
2526
+ try {
2527
+ return await this.allInternal(query, lowerPublicDbQueryOptions(options));
2528
+ }
2529
+ catch (error) {
2530
+ // Begun before this Db handed over to a successor, and ended by that
2531
+ // (its own runtime closing): the successor answers it. Any other
2532
+ // error is the read's own answer.
2533
+ if (this.successor && isRuntimeClosed(error))
2534
+ return this.current().all(query, options);
2535
+ throw error;
2536
+ }
2537
+ }
2538
+ async allInternal(query, options) {
782
2539
  const client = this.getClient(query._schema);
2540
+ const preparation = getOwnerPreparation(client);
2541
+ if (preparation?.pending)
2542
+ await preparation.drain();
2543
+ // A newly attached browser-worker follower learns the namespace-wide
2544
+ // connection state during its init handshake. The core read gate needs
2545
+ // that state before it decides whether the first load may wait.
2546
+ const mayWaitForServer = resolveEffectiveQueryExecutionOptions(this.config, {
2547
+ tier: options?.tier,
2548
+ firstLoadRemoteWaitMs: options?.firstLoadRemoteWaitMs,
2549
+ }).firstLoadRemoteWaitMs !== undefined;
2550
+ const initialOfflineState = mayWaitForServer
2551
+ ? this.connection.initialExplicitOfflineState()
2552
+ : null;
2553
+ if (initialOfflineState)
2554
+ await initialOfflineState;
783
2555
  const builderJson = query._build();
784
- const builtQuery = normalizeBuiltQuery(JSON.parse(builderJson), query._table);
785
- const rows = await client.query(translateQuery(builderJson, query._schema), settledTier);
786
- const outputTable = builtQuery.hops.length > 0
787
- ? resolveHopOutputTable(query._schema, builtQuery.table, builtQuery.hops)
788
- : query._table;
789
- const outputIncludes = builtQuery.hops.length > 0 ? {} : builtQuery.includes;
790
- return transformRows(rows, query._schema, outputTable, outputIncludes);
2556
+ const builtQuery = normalizeBuiltQuery(JSON.parse(builderJson));
2557
+ const planningSchema = requireSchemaWithTable(query._schema, builtQuery.table);
2558
+ const outputTable = resolveQueryOutputTable(planningSchema, builtQuery);
2559
+ const prepared = prepareTransformRead(query, builtQuery, outputTable);
2560
+ const queryOptions = normalizeQueryOptions(query._schema, builtQuery.table, options);
2561
+ const wasmQuery = translateQuery(builderJson, planningSchema, prepared.physical);
2562
+ const usesRelationTraversal = queryUsesRelationTraversal(builtQuery);
2563
+ const context = this.getAccessContext();
2564
+ const effectiveTier = resolveEffectiveQueryExecutionOptions(this.config, queryOptions).tier;
2565
+ await this.ensureReady(effectiveTier === "remote" ? "server" : "runtime");
2566
+ const rows = context || usesRelationTraversal
2567
+ ? await client.queryInternal(wasmQuery, queryOptions, context?.readSession)
2568
+ : await client.queryInternal(wasmQuery, queryOptions);
2569
+ if (!prepared.computedState)
2570
+ return rows.map(prepared.transform);
2571
+ return finishComputedRead(query, builtQuery, outputTable, prepared, rows, (physical) => client.queryInternal(translateQuery(builderJson, planningSchema, physical), queryOptions, context?.readSession));
791
2572
  }
792
2573
  /**
793
- * Execute a query and return the first matching row, or null.
2574
+ * Execute a query with a limit of one and return the first matching row, or null.
794
2575
  *
795
2576
  * @param query QueryBuilder instance
796
- * @param settledTier Optional tier to hold delivery until confirmed
2577
+ * @param options Optional read durability options
797
2578
  * @returns First matching typed object, or null if none found
798
2579
  */
799
- async one(query, settledTier) {
800
- const results = await this.all(query, settledTier);
2580
+ async one(query, options) {
2581
+ const results = await this.all(limitQueryToOne(query), options);
801
2582
  return results[0] ?? null;
802
2583
  }
2584
+ /**
2585
+ * Subscribe to a query and receive its complete current result whenever it changes.
2586
+ * Each update receives a fresh result array. Prefer the object form when the
2587
+ * subscription's terminal errors must be handled explicitly. The legacy
2588
+ * function form reports unhandled terminal errors to `console.error`.
2589
+ */
2590
+ subscribe(query, callbacks, options, session) {
2591
+ const { onUpdate, onError } = typeof callbacks === "function" ? { onUpdate: callbacks, onError: undefined } : callbacks;
2592
+ const deltaCallbacks = {
2593
+ onDelta: (update) => {
2594
+ if (update.all === undefined) {
2595
+ throw new Error("Jazz subscription update is missing its materialized result.");
2596
+ }
2597
+ const splices = new Map();
2598
+ for (const change of update.delta) {
2599
+ if (change.kind === RowChangeKind.Updated && change.splices) {
2600
+ splices.set(change.id, change.splices);
2601
+ }
2602
+ }
2603
+ onUpdate(update.all, { splices });
2604
+ },
2605
+ ...(onError === undefined ? {} : { onError }),
2606
+ };
2607
+ return this.subscribeDelta(query, deltaCallbacks, lowerPublicDbQueryOptions(options), session);
2608
+ }
803
2609
  /**
804
2610
  * Subscribe to a query and receive updates when results change.
805
2611
  *
806
2612
  * The callback receives a SubscriptionDelta with:
807
- * - `all`: Complete current result set
808
- * - `delta`: Ordered list of row-level changes
2613
+ * - `all`: Complete current result set. Freshly allocated on every delta —
2614
+ * the rows are new object references each time, so diffing `all` by identity
2615
+ * sees every row as changed. Reactive-framework consumers should reconcile
2616
+ * with `applyDelta`/`reconcileArray` from `reconcile-array.js` to preserve
2617
+ * identity for unchanged rows.
2618
+ * - `delta`: Ordered list of row-level changes (see `RowDelta`)
809
2619
  *
810
2620
  * @param query QueryBuilder instance
811
- * @param callback Called with delta whenever results change
2621
+ * @param callbacks Called with deltas and, in object form, terminal subscription errors
2622
+ * @param options Optional read durability options
812
2623
  * @returns Unsubscribe function
813
2624
  *
814
2625
  * @example
815
2626
  * ```typescript
816
- * const unsubscribe = db.subscribeAll(app.todos, (delta) => {
2627
+ * import { RowChangeKind } from "jazz-tools";
2628
+ *
2629
+ * const unsubscribe = db.subscribeDelta(app.todos, (delta) => {
817
2630
  * setTodos(delta.all);
818
2631
  * for (const change of delta.delta) {
819
- * if (change.kind === 0) {
820
- * console.log("New row:", change.row);
2632
+ * if (change.kind === RowChangeKind.Added) {
2633
+ * console.log("New row:", change.item);
821
2634
  * }
822
2635
  * }
823
2636
  * });
@@ -826,82 +2639,706 @@ export class Db {
826
2639
  * unsubscribe();
827
2640
  * ```
828
2641
  */
829
- subscribeAll(query, callback, settledTier) {
830
- const manager = new SubscriptionManager();
2642
+ subscribeDelta(query, callbacks, options, session) {
2643
+ if (this.replaced)
2644
+ throw this.replaced;
2645
+ const { onDelta, onError } = typeof callbacks === "function" ? { onDelta: callbacks, onError: undefined } : callbacks;
2646
+ let ready;
2647
+ let first = true;
2648
+ const stop = this.registerMovable((db) => {
2649
+ // On the successor the query starts over: its opening result replaces
2650
+ // what the subscriber has, rows the upgrade already read in included.
2651
+ let opening = !first;
2652
+ first = false;
2653
+ const handle = db.subscribeDeltaHere(query, {
2654
+ onDelta: (delta) => {
2655
+ if (opening) {
2656
+ opening = false;
2657
+ onDelta({
2658
+ delta: delta.delta,
2659
+ all: delta.all ?? [],
2660
+ reset: true,
2661
+ });
2662
+ return;
2663
+ }
2664
+ onDelta(delta);
2665
+ },
2666
+ ...(onError === undefined ? {} : { onError }),
2667
+ }, options, session);
2668
+ ready ??= handle.ready;
2669
+ return handle;
2670
+ });
2671
+ const handle = (() => stop());
2672
+ if (ready)
2673
+ Object.defineProperty(handle, "ready", { value: ready });
2674
+ return handle;
2675
+ }
2676
+ subscribeDeltaHere(query, callbacks, options, session) {
2677
+ const { onDelta, onError } = callbacks;
2678
+ // Constructing a browser follower starts its init handshake. Do that before
2679
+ // asking whether this is a newly attaching peer.
831
2680
  const client = this.getClient(query._schema);
2681
+ // A newly attached browser peer does not yet know whether its worker can
2682
+ // open durable storage. Keep the native subscription installation in the
2683
+ // old immediate order (several hooks may register together), but hold its
2684
+ // public deltas until that one admission succeeds. This makes a corrupt
2685
+ // store fail the subscription that triggered it without publishing a
2686
+ // misleading empty opening or perturbing maintained-view registration.
2687
+ const initialReadiness = this.connection.initialExplicitOfflineState();
2688
+ const manager = new SubscriptionManager();
832
2689
  const builderJson = query._build();
833
- const builtQuery = normalizeBuiltQuery(JSON.parse(builderJson), query._table);
834
- const outputTable = builtQuery.hops.length > 0
835
- ? resolveHopOutputTable(query._schema, builtQuery.table, builtQuery.hops)
836
- : query._table;
837
- const outputIncludes = builtQuery.hops.length > 0 ? {} : builtQuery.includes;
838
- const wasmQuery = translateQuery(builderJson, query._schema);
839
- const transform = (row) => {
840
- return transformRows([row], query._schema, outputTable, outputIncludes)[0];
841
- };
842
- const subId = client.subscribe(wasmQuery, (delta) => {
843
- const typedDelta = manager.handleDelta(delta, transform);
844
- callback(typedDelta);
845
- }, settledTier);
846
- // Return unsubscribe function
847
- return () => {
848
- client.unsubscribe(subId);
2690
+ const builtQuery = normalizeBuiltQuery(JSON.parse(builderJson));
2691
+ const planningSchema = requireSchemaWithTable(query._schema, builtQuery.table);
2692
+ const outputTable = resolveQueryOutputTable(planningSchema, builtQuery);
2693
+ let prepared = prepareTransformRead(query, builtQuery, outputTable);
2694
+ let wasmQuery = translateQuery(builderJson, planningSchema, prepared.physical);
2695
+ let deliveryReady = initialReadiness === null;
2696
+ const bufferedDeltas = [];
2697
+ const queryOptions = normalizeQueryOptions(query._schema, builtQuery.table, options);
2698
+ if (queryOptions.splices) {
2699
+ assertSpliceableColumns(planningSchema, outputTable, query, queryOptions.splices);
2700
+ assertSplicesReadInPart(builtQuery, prepared.physical, queryOptions.splices);
2701
+ }
2702
+ const readSession = this.getAccessContext()?.readSession ?? session;
2703
+ let activeSubscription = null;
2704
+ let unsubscribed = false;
2705
+ let terminalized = false;
2706
+ const readyAbort = new AbortController();
2707
+ const retireNativeSubscription = (subscription) => {
2708
+ subscription.retired = true;
2709
+ const id = subscription.id;
2710
+ if (id === null || subscription.nativeUnsubscribed)
2711
+ return;
2712
+ subscription.nativeUnsubscribed = true;
2713
+ client.unsubscribe(id);
2714
+ };
2715
+ const notifyTerminalError = (error) => {
2716
+ if (!onError) {
2717
+ console.error("Unhandled Jazz subscription error", error);
2718
+ return;
2719
+ }
2720
+ try {
2721
+ onError(error);
2722
+ }
2723
+ catch (callbackError) {
2724
+ console.error("Jazz subscription error callback failed", callbackError);
2725
+ }
2726
+ };
2727
+ const completeTerminalization = (subscription) => {
2728
+ // A native runtime may fail from inside subscribe(). Record the terminal
2729
+ // outcome immediately, but wait for subscribe() to return its handle
2730
+ // before detaching and notifying the owner.
2731
+ if (subscription.installing)
2732
+ return;
2733
+ const terminalError = subscription.terminalError;
2734
+ if (terminalError === null || subscription.terminalDelivered || terminalized)
2735
+ return;
2736
+ subscription.terminalDelivered = true;
2737
+ terminalized = true;
2738
+ deliveryReady = false;
2739
+ bufferedDeltas.length = 0;
2740
+ if (activeSubscription === subscription) {
2741
+ activeSubscription = null;
2742
+ }
2743
+ retireNativeSubscription(subscription);
2744
+ if (subscription.predecessor !== null) {
2745
+ retireNativeSubscription(subscription.predecessor);
2746
+ subscription.predecessor = null;
2747
+ }
2748
+ readyAbort.abort();
2749
+ this.liveSubscriptionEnders.delete(endLive);
2750
+ this.unregisterActiveQuerySubscriptionTrace(traceId);
2751
+ manager.clear();
2752
+ notifyTerminalError(terminalError);
2753
+ };
2754
+ const terminalizeSubscription = (subscription, error) => {
2755
+ if (unsubscribed ||
2756
+ terminalized ||
2757
+ activeSubscription !== subscription ||
2758
+ subscription.terminalDelivered) {
2759
+ return;
2760
+ }
2761
+ subscription.terminalError ??= toError(error);
2762
+ completeTerminalization(subscription);
2763
+ };
2764
+ const createSubscriptionGeneration = (predecessor = null) => {
2765
+ const subscription = {
2766
+ id: null,
2767
+ installing: false,
2768
+ terminalError: null,
2769
+ terminalDelivered: false,
2770
+ retired: false,
2771
+ nativeUnsubscribed: false,
2772
+ predecessor,
2773
+ };
2774
+ activeSubscription = subscription;
2775
+ return subscription;
2776
+ };
2777
+ const deliver = (delta) => {
2778
+ if (unsubscribed || terminalized || activeSubscription === null)
2779
+ return;
2780
+ if (!deliveryReady) {
2781
+ bufferedDeltas.push(delta);
2782
+ return;
2783
+ }
2784
+ try {
2785
+ onDelta(delta);
2786
+ }
2787
+ catch (error) {
2788
+ const subscription = activeSubscription;
2789
+ if (subscription !== null)
2790
+ terminalizeSubscription(subscription, error);
2791
+ }
2792
+ };
2793
+ const handleDelta = (delta) => {
2794
+ if (unsubscribed || terminalized || activeSubscription === null)
2795
+ return;
2796
+ try {
2797
+ deliver(manager.handleDelta(delta, prepared.transform));
2798
+ }
2799
+ catch (error) {
2800
+ if (!(error instanceof MissingComputedDependency) ||
2801
+ !prepared.computedState ||
2802
+ prepared.computedState.version === prepared.version)
2803
+ throw error;
2804
+ prepared = prepareTransformRead(query, builtQuery, outputTable, prepared.computedState);
2805
+ // A dependency found only now may make a splice column read whole.
2806
+ if (queryOptions.splices)
2807
+ assertSplicesReadInPart(builtQuery, prepared.physical, queryOptions.splices);
2808
+ wasmQuery = translateQuery(builderJson, planningSchema, prepared.physical);
2809
+ retireNativeSubscription(activeSubscription);
2810
+ const replacement = createSubscriptionGeneration();
2811
+ manager.clear();
2812
+ bufferedDeltas.length = 0;
2813
+ this.unregisterActiveQuerySubscriptionTrace(traceId);
2814
+ traceId = this.registerActiveQuerySubscriptionTrace(wasmQuery, builtQuery.table, queryOptions);
2815
+ // Native initial snapshots may arrive synchronously. Defer the next
2816
+ // generation to avoid recursive installation as new inputs are found.
2817
+ queueMicrotask(() => {
2818
+ if (!this.shutdownPromise)
2819
+ startNativeSubscription(replacement);
2820
+ });
2821
+ }
2822
+ };
2823
+ const startNativeSubscription = (subscription, subscriptionOptions = queryOptions) => {
2824
+ if (unsubscribed ||
2825
+ activeSubscription !== subscription ||
2826
+ subscription.retired ||
2827
+ subscription.terminalError !== null) {
2828
+ return null;
2829
+ }
2830
+ const openingDeltas = [];
2831
+ subscription.installing = true;
2832
+ try {
2833
+ subscription.id = client.subscribeInternal(wasmQuery, {
2834
+ onUpdate: (delta) => {
2835
+ if (unsubscribed ||
2836
+ activeSubscription !== subscription ||
2837
+ subscription.terminalError !== null) {
2838
+ return;
2839
+ }
2840
+ if (subscription.installing) {
2841
+ openingDeltas.push(delta);
2842
+ return;
2843
+ }
2844
+ try {
2845
+ handleDelta(delta);
2846
+ }
2847
+ catch (error) {
2848
+ terminalizeSubscription(subscription, error);
2849
+ }
2850
+ },
2851
+ onError: (error) => {
2852
+ terminalizeSubscription(subscription, error);
2853
+ },
2854
+ }, subscriptionOptions, readSession);
2855
+ }
2856
+ catch (error) {
2857
+ subscription.installing = false;
2858
+ terminalizeSubscription(subscription, error);
2859
+ return null;
2860
+ }
2861
+ subscription.installing = false;
2862
+ if (unsubscribed || activeSubscription !== subscription || subscription.retired) {
2863
+ retireNativeSubscription(subscription);
2864
+ return null;
2865
+ }
2866
+ if (subscription.terminalError !== null) {
2867
+ completeTerminalization(subscription);
2868
+ return null;
2869
+ }
2870
+ try {
2871
+ for (const delta of openingDeltas) {
2872
+ if (activeSubscription !== subscription || subscription.terminalError !== null)
2873
+ break;
2874
+ handleDelta(delta);
2875
+ }
2876
+ }
2877
+ catch (error) {
2878
+ terminalizeSubscription(subscription, error);
2879
+ return null;
2880
+ }
2881
+ return unsubscribed || activeSubscription !== subscription || subscription.retired
2882
+ ? null
2883
+ : subscription;
2884
+ };
2885
+ let traceId = this.registerActiveQuerySubscriptionTrace(wasmQuery, builtQuery.table, queryOptions);
2886
+ const unsubscribe = () => {
2887
+ if (unsubscribed)
2888
+ return;
2889
+ unsubscribed = true;
2890
+ this.liveSubscriptionEnders.delete(endLive);
2891
+ deliveryReady = false;
2892
+ bufferedDeltas.length = 0;
2893
+ readyAbort.abort();
2894
+ this.unregisterActiveQuerySubscriptionTrace(traceId);
2895
+ if (activeSubscription !== null) {
2896
+ retireNativeSubscription(activeSubscription);
2897
+ if (activeSubscription.predecessor !== null) {
2898
+ retireNativeSubscription(activeSubscription.predecessor);
2899
+ activeSubscription.predecessor = null;
2900
+ }
2901
+ }
2902
+ activeSubscription = null;
849
2903
  manager.clear();
850
2904
  };
2905
+ const ready = initialReadiness
2906
+ ?.then(() => {
2907
+ if (unsubscribed || terminalized || activeSubscription === null || this.shutdownPromise) {
2908
+ return;
2909
+ }
2910
+ deliveryReady = true;
2911
+ for (const delta of bufferedDeltas.splice(0)) {
2912
+ if (unsubscribed || terminalized || activeSubscription === null)
2913
+ return;
2914
+ deliver(delta);
2915
+ }
2916
+ })
2917
+ .catch((error) => {
2918
+ if (unsubscribed || terminalized || activeSubscription === null || this.shutdownPromise) {
2919
+ return;
2920
+ }
2921
+ // Admission failed after native registration. Terminalize the same
2922
+ // generation before rejecting readiness so public and framework
2923
+ // consumers observe one error and no buffered opening can escape.
2924
+ terminalizeSubscription(activeSubscription, error);
2925
+ throw error;
2926
+ });
2927
+ // The public error callback owns terminal notification. Retain a rejection
2928
+ // handler because the readiness property is an internal orchestration seam
2929
+ // and public Db.subscribe callers are not required to consume it.
2930
+ if (ready)
2931
+ void ready.catch(() => undefined);
2932
+ const initialSubscription = createSubscriptionGeneration();
2933
+ const endLive = (error) => {
2934
+ if (activeSubscription !== null)
2935
+ terminalizeSubscription(activeSubscription, error);
2936
+ };
2937
+ this.liveSubscriptionEnders.add(endLive);
2938
+ // The native maintained stream owns both the opening snapshot and later
2939
+ // changes. Do not fabricate an empty opening or race it with a one-shot
2940
+ // cache read: that snapshot may be older than deltas already delivered.
2941
+ const requirement = queryOptions.tier === "remote" ? "server" : "runtime";
2942
+ if (this.connection.shouldDeferSubscriptionStart(requirement)) {
2943
+ // The worker can only classify the initial authority-tier snapshot as
2944
+ // settled after its own server transport is attached. Delay native
2945
+ // subscription creation until that topology is ready; the native stream
2946
+ // then owns the settled-snapshot gate and remains the sole data source.
2947
+ void this.ensureReady(requirement, readyAbort.signal)
2948
+ .then(() => startNativeSubscription(initialSubscription))
2949
+ .catch((error) => {
2950
+ if (unsubscribed || readyAbort.signal.aborted || this.shutdownPromise)
2951
+ return;
2952
+ terminalizeSubscription(initialSubscription, error);
2953
+ });
2954
+ }
2955
+ else {
2956
+ startNativeSubscription(initialSubscription);
2957
+ }
2958
+ const handle = unsubscribe;
2959
+ if (ready)
2960
+ Object.defineProperty(handle, "ready", { value: ready });
2961
+ return handle;
2962
+ }
2963
+ /**
2964
+ * @internal The session that owned this Db replaced it. Its live queries
2965
+ * end with a {@link DbReplacedError} naming the fix, and its reads, writes
2966
+ * and listeners throw it, so code that kept the handle fails loudly instead
2967
+ * of going silent.
2968
+ */
2969
+ markReplaced(reason) {
2970
+ this.successor?.markReplaced(reason);
2971
+ if (this.replaced)
2972
+ return;
2973
+ const error = new DbReplacedError(reason);
2974
+ this.replaced = error;
2975
+ for (const end of Array.from(this.liveSubscriptionEnders))
2976
+ end(error);
2977
+ this.liveSubscriptionEnders.clear();
2978
+ }
2979
+ /**
2980
+ * @internal The session upgraded this Db to `next`, the local-first Db of
2981
+ * the same account. This Db becomes a handle on `next`: its live queries
2982
+ * and listeners move there (each query's first result there replaces what
2983
+ * it had, so nothing goes back to loading), and its reads and writes go
2984
+ * there from now on. Only its own runtime stays behind, for the session to
2985
+ * shut down once its writes are uploaded.
2986
+ */
2987
+ adoptSuccessor(next) {
2988
+ if (this.successor)
2989
+ throw new Error("This Db already has a successor");
2990
+ const own = this.currentRuntime();
2991
+ this.successor = next;
2992
+ // A read still waiting for this runtime's server (the server is down)
2993
+ // asks `next` instead: only the drain below waits for that server.
2994
+ own?.endUnsentReads?.();
2995
+ // Upload what this runtime still holds, then stop it. Until then its
2996
+ // writes count in the sync status and in waitForSync. A stream still
2997
+ // sending its value finishes first, unless the app shuts down.
2998
+ const streams = this.letStreamsFinish();
2999
+ let draining = true;
3000
+ const drainListeners = new Set();
3001
+ const drained = this.shutdown({ waitForSync: true }).finally(() => {
3002
+ draining = false;
3003
+ for (const listener of Array.from(drainListeners))
3004
+ listener();
3005
+ });
3006
+ void drained.catch(() => { });
3007
+ this.drain = {
3008
+ done: drained,
3009
+ endStreamWait: () => streams.abort(),
3010
+ abort: () => {
3011
+ if (draining)
3012
+ this.abortGracefulShutdown();
3013
+ },
3014
+ };
3015
+ let combined = null;
3016
+ const syncStatus = () => {
3017
+ const ahead = next.getSyncStatus();
3018
+ if (!draining)
3019
+ return ahead;
3020
+ const own = Db.prototype.getSyncStatus.call(this);
3021
+ const status = {
3022
+ link: ahead.link,
3023
+ pendingUploads: ahead.pendingUploads + own.pendingUploads,
3024
+ oldestPendingAt: ahead.oldestPendingAt === null || own.oldestPendingAt === null
3025
+ ? (ahead.oldestPendingAt ?? own.oldestPendingAt)
3026
+ : Math.min(ahead.oldestPendingAt, own.oldestPendingAt),
3027
+ rejected: ahead.rejected + own.rejected,
3028
+ lastError: own.lastError && (!ahead.lastError || own.lastError.at > ahead.lastError.at)
3029
+ ? own.lastError
3030
+ : ahead.lastError,
3031
+ synced: ahead.synced && own.pendingUploads === 0,
3032
+ };
3033
+ if (combined && sameSyncStatus(status, combined))
3034
+ return combined;
3035
+ return (combined = status);
3036
+ };
3037
+ const overrides = {
3038
+ getSyncStatus: syncStatus,
3039
+ syncStatusChangeRegistration: (listener) => {
3040
+ let published = syncStatus();
3041
+ const publish = () => {
3042
+ const status = syncStatus();
3043
+ if (status === published)
3044
+ return;
3045
+ published = status;
3046
+ listener(status);
3047
+ };
3048
+ const stopAhead = next.onSyncStatusChange(publish);
3049
+ const stopOwn = draining ? this.onSyncStatusChangeHere(publish) : () => { };
3050
+ drainListeners.add(publish);
3051
+ return () => {
3052
+ stopAhead();
3053
+ stopOwn();
3054
+ drainListeners.delete(publish);
3055
+ };
3056
+ },
3057
+ waitForSync: async (options = {}) => {
3058
+ await Promise.all([
3059
+ next.waitForSync(options),
3060
+ draining ? this.waitForOwnSync(options, drained) : undefined,
3061
+ ]);
3062
+ },
3063
+ // The app's offline toggle covers both runtimes while the thin one
3064
+ // still uploads.
3065
+ disconnect: async () => {
3066
+ await Promise.all([next.disconnect(), draining ? this.connection.disconnect() : undefined]);
3067
+ },
3068
+ reconnect: async () => {
3069
+ await Promise.all([next.reconnect(), draining ? this.connection.reconnect() : undefined]);
3070
+ },
3071
+ };
3072
+ for (const name of FORWARDED_TO_SUCCESSOR) {
3073
+ Object.defineProperty(this, name, {
3074
+ configurable: true,
3075
+ value: overrides[name] ??
3076
+ ((...args) => next[name](...args)),
3077
+ });
3078
+ }
3079
+ Object.defineProperty(this, "syncStatusChangeRegistration", {
3080
+ configurable: true,
3081
+ value: overrides.syncStatusChangeRegistration,
3082
+ });
3083
+ // An app that took the thin Db offline keeps the local-first one offline.
3084
+ // The last toggle the app asked for counts, even while it is in flight.
3085
+ if (this.offlineRequested ?? this.connection.isExplicitlyOffline())
3086
+ void next.disconnect().catch(() => { });
3087
+ // Rejections this Db reported before anyone listened go to the listeners
3088
+ // on the successor (already logged here as unhandled).
3089
+ for (const event of this.pendingMutationErrorEvents.splice(0))
3090
+ next.handleMutationError(event, true);
3091
+ for (const entry of Array.from(this.movable))
3092
+ entry.move(next);
3093
+ this.movable.clear();
3094
+ }
3095
+ /**
3096
+ * Wait for this Db's own runtime's writes, as {@link waitForSync} does
3097
+ * (rejecting with the server's error for a rejected one), while it drains
3098
+ * after the upgrade. The drain ending is the wait ending.
3099
+ */
3100
+ async waitForOwnSync(options, drained) {
3101
+ const { timeoutMs, signal } = options;
3102
+ validateWriteWaitTimeout(timeoutMs);
3103
+ signal?.throwIfAborted();
3104
+ const control = new AbortController();
3105
+ const forward = () => control.abort(signal.reason);
3106
+ signal?.addEventListener("abort", forward, { once: true });
3107
+ const timer = timeoutMs === undefined
3108
+ ? undefined
3109
+ : setTimeout(() => control.abort(new WriteWaitTimeoutError("global", timeoutMs)), timeoutMs);
3110
+ try {
3111
+ // The thin runtime's writes are answered (a rejection fails the wait),
3112
+ // or its drain ends: then it has nothing left to wait for.
3113
+ await Promise.race([this.connection.waitForSync(control.signal), drained]);
3114
+ }
3115
+ finally {
3116
+ if (timer !== undefined)
3117
+ clearTimeout(timer);
3118
+ signal?.removeEventListener("abort", forward);
3119
+ }
3120
+ }
3121
+ /** The app's last {@link disconnect} (true) or {@link reconnect} (false). */
3122
+ offlineRequested;
3123
+ /** Set once this Db adopted a successor: its own runtime's last uploads. */
3124
+ drain = null;
3125
+ /** Set by {@link letStreamsFinish}. */
3126
+ streamsMayFinish = null;
3127
+ /**
3128
+ * @internal This Db's graceful shutdown lets streaming writes in flight on
3129
+ * its own runtime finish (and waits for their writes) before closing it,
3130
+ * until the returned controller aborts. Only the drain after the
3131
+ * local-first upgrade asks for this: the app didn't ask for that shutdown,
3132
+ * so it must not cut off an upload the app is making. A shutdown the app
3133
+ * asks for (a sign-out, an account switch, a close) aborts it, so it is
3134
+ * never held by a slow or stalled stream; the stream then fails saying why.
3135
+ */
3136
+ letStreamsFinish() {
3137
+ this.streamsMayFinish?.abort();
3138
+ this.streamsMayFinish = new AbortController();
3139
+ return this.streamsMayFinish;
3140
+ }
3141
+ /**
3142
+ * @internal Stop this Db's own runtime after the upgrade. With
3143
+ * `waitForSync`, its writes upload first, the way a local-first client's
3144
+ * do when it shuts down; without, they are dropped, as when a thin client
3145
+ * closes. Either way a streaming write still sending its value is cut off
3146
+ * (it fails saying why) rather than holding the app's shutdown.
3147
+ */
3148
+ async stopOwnRuntime(options = {}) {
3149
+ const drain = this.drain;
3150
+ if (!drain)
3151
+ return this.shutdown(options);
3152
+ // The app is shutting down: streams in flight no longer hold the drain.
3153
+ drain.endStreamWait();
3154
+ if (!options.waitForSync)
3155
+ drain.abort();
3156
+ await drain.done.catch(() => { });
3157
+ // An aborted or failed drain leaves the runtime open: stop it now.
3158
+ await Db.prototype.shutdown.call(this);
3159
+ }
3160
+ /** @internal The Db that does this one's work now: itself, or its successor. */
3161
+ current() {
3162
+ return this.successor?.current() ?? this;
851
3163
  }
852
3164
  /**
853
3165
  * Shutdown the Db and release all resources.
854
- * Closes all memoized JazzClient connections and the worker.
855
- */
856
- async shutdown() {
857
- this.isShuttingDown = true;
858
- this.logLeaderDebug("shutdown");
859
- this.sendFollowerClose(this.activeRemoteLeaderTabId, this.currentLeaderTerm);
860
- this.activeRemoteLeaderTabId = null;
861
- this.leaderPeerIds.clear();
862
- this.closeSyncChannel();
863
- this.detachLifecycleHooks();
864
- if (this.leaderElectionUnsubscribe) {
865
- this.leaderElectionUnsubscribe();
866
- this.leaderElectionUnsubscribe = null;
867
- }
868
- if (this.leaderElection) {
869
- this.leaderElection.stop();
870
- this.leaderElection = null;
871
- }
872
- await this.workerReconfigure;
873
- // Ensure bridge init has completed before sending shutdown —
874
- // otherwise the worker may still be opening OPFS handles
875
- await this.ensureBridgeReady();
876
- // Shutdown worker bridge — waits for OPFS handles to be released
877
- if (this.workerBridge && this.worker) {
878
- await this.workerBridge.shutdown(this.worker);
879
- this.workerBridge = null;
880
- }
881
- for (const client of this.clients.values()) {
882
- await client.shutdown();
883
- }
884
- this.clients.clear();
885
- if (this.worker) {
886
- this.worker.terminate();
887
- this.worker = null;
3166
+ * Closes the Db's runtime client.
3167
+ *
3168
+ * Idempotent: concurrent or repeated calls share the same in-flight promise.
3169
+ */
3170
+ shutdown(options = {}) {
3171
+ if (this.shutdownPromise)
3172
+ return this.shutdownPromise;
3173
+ // Publish the promise before teardown can synchronously call back into Db.
3174
+ let resolveShutdown;
3175
+ const shutdown = new Promise((resolve) => {
3176
+ resolveShutdown = resolve;
3177
+ });
3178
+ this.shutdownPromise = shutdown;
3179
+ resolveShutdown(this.runShutdown(options));
3180
+ return shutdown;
3181
+ }
3182
+ cancelSyncShutdown;
3183
+ /** @internal Credential invalidation must interrupt a graceful sync wait. */
3184
+ abortGracefulShutdown() {
3185
+ this.cancelSyncShutdown?.();
3186
+ }
3187
+ assertOpen() {
3188
+ if (this.replaced)
3189
+ throw this.replaced;
3190
+ if (this.shutdownPromise) {
3191
+ throw new Error("Cannot operate on a Db that is shutting down or closed.");
3192
+ }
3193
+ }
3194
+ shutdownListeners = new Set();
3195
+ /** @internal Dispose account refresh and invalidation observers with the context. */
3196
+ onShutdown(listener) {
3197
+ if (this.shutdownPromise)
3198
+ listener();
3199
+ else
3200
+ this.shutdownListeners.add(listener);
3201
+ return () => this.shutdownListeners.delete(listener);
3202
+ }
3203
+ async runShutdown(options) {
3204
+ if (options.waitForSync) {
3205
+ const syncAbort = new AbortController();
3206
+ const cancelled = new Promise((_resolve, reject) => {
3207
+ this.cancelSyncShutdown = () => {
3208
+ syncAbort.abort();
3209
+ reject(new Error("Graceful shutdown cancelled"));
3210
+ };
3211
+ });
3212
+ try {
3213
+ await Promise.race([
3214
+ this.runtimeSource.waitForPendingWrites?.(syncAbort.signal) ??
3215
+ this.connection.waitForPendingWrites({
3216
+ inFlightStreams: this.streamsMayFinish?.signal,
3217
+ }),
3218
+ cancelled,
3219
+ ]);
3220
+ }
3221
+ catch (error) {
3222
+ syncAbort.abort();
3223
+ this.shutdownPromise = null;
3224
+ throw new GracefulShutdownSyncError(error);
3225
+ }
3226
+ finally {
3227
+ this.cancelSyncShutdown = undefined;
3228
+ }
3229
+ }
3230
+ for (const listener of this.shutdownListeners) {
3231
+ try {
3232
+ listener();
3233
+ }
3234
+ catch (error) {
3235
+ console.error("Context cleanup failed", error);
3236
+ }
3237
+ }
3238
+ this.shutdownListeners.clear();
3239
+ this.shutdownAbort.abort();
3240
+ if (this.localFirstRefreshTimer) {
3241
+ clearTimeout(this.localFirstRefreshTimer);
3242
+ this.localFirstRefreshTimer = null;
3243
+ }
3244
+ this.clearActiveQuerySubscriptionTraces();
3245
+ this.mutationErrorListeners.clear();
3246
+ try {
3247
+ await this.connection.shutdown();
3248
+ }
3249
+ finally {
3250
+ await this.runtimeSource.shutdown();
3251
+ }
3252
+ }
3253
+ notifyActiveQuerySubscriptionTraceListeners() {
3254
+ if (this.activeQuerySubscriptionTraceListeners.size === 0) {
3255
+ return;
3256
+ }
3257
+ const snapshot = this.getActiveQuerySubscriptions();
3258
+ for (const listener of this.activeQuerySubscriptionTraceListeners) {
3259
+ listener(snapshot);
3260
+ }
3261
+ }
3262
+ registerActiveQuerySubscriptionTrace(queryJson, _queryTable, options) {
3263
+ if (!this.config.devMode) {
3264
+ return null;
3265
+ }
3266
+ const resolvedOptions = resolveEffectiveQueryExecutionOptions(this.config, options);
3267
+ // Inspector-only reads must not recursively appear in the inspector's
3268
+ // own subscription list. Public local-first still propagates and is listed.
3269
+ if (resolvedOptions.tier === "local-only")
3270
+ return null;
3271
+ const payload = this.parseRuntimeQueryTracePayload(queryJson);
3272
+ const traceId = `sub-${this.nextActiveQuerySubscriptionTraceId++}`;
3273
+ this.activeQuerySubscriptionTraces.set(traceId, {
3274
+ id: traceId,
3275
+ query: queryJson,
3276
+ table: payload.table,
3277
+ branches: payload.branches,
3278
+ tier: resolvedOptions.tier,
3279
+ createdAt: new Date().toISOString(),
3280
+ stack: trimSubscriptionTraceStack(new Error().stack),
3281
+ visibility: resolvedOptions.visibility ?? "public",
3282
+ });
3283
+ this.notifyActiveQuerySubscriptionTraceListeners();
3284
+ return traceId;
3285
+ }
3286
+ unregisterActiveQuerySubscriptionTrace(traceId) {
3287
+ if (!traceId) {
3288
+ return;
3289
+ }
3290
+ if (!this.activeQuerySubscriptionTraces.delete(traceId)) {
3291
+ return;
3292
+ }
3293
+ this.notifyActiveQuerySubscriptionTraceListeners();
3294
+ }
3295
+ clearActiveQuerySubscriptionTraces() {
3296
+ if (this.activeQuerySubscriptionTraces.size === 0) {
3297
+ return;
3298
+ }
3299
+ this.activeQuerySubscriptionTraces.clear();
3300
+ this.notifyActiveQuerySubscriptionTraceListeners();
3301
+ }
3302
+ parseRuntimeQueryTracePayload(queryJson) {
3303
+ try {
3304
+ const parsed = JSON.parse(queryJson);
3305
+ const table = typeof parsed.table === "string" ? parsed.table : "unknown";
3306
+ const branches = Array.isArray(parsed.branches)
3307
+ ? parsed.branches.filter((branch) => typeof branch === "string")
3308
+ : [];
3309
+ return {
3310
+ table,
3311
+ branches,
3312
+ };
3313
+ }
3314
+ catch {
3315
+ return {
3316
+ table: "unknown",
3317
+ branches: [],
3318
+ };
888
3319
  }
889
3320
  }
890
3321
  }
891
3322
  /**
892
- * Check if running in a browser environment with Worker support.
3323
+ * Generate a 32-byte ephemeral seed for anonymous auth.
3324
+ *
3325
+ * Uses Web Crypto or the installed native host's OS entropy.
893
3326
  */
894
- function isBrowser() {
895
- return typeof Worker !== "undefined" && typeof window !== "undefined";
3327
+ function generateEphemeralSeedBase64Url() {
3328
+ const bytes = runtimeRandomBytes(32);
3329
+ let binary = "";
3330
+ for (const b of bytes)
3331
+ binary += String.fromCharCode(b);
3332
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
896
3333
  }
897
3334
  /**
898
3335
  * Create a new Db instance with the given configuration.
899
3336
  *
900
- * This is an **async** factory function that pre-loads the WASM module.
901
- * After creation, mutations (insert/update/deleteFrom) are synchronous.
3337
+ * This is an **async** factory function that pre-loads the runtime source.
3338
+ * After creation, local-first mutations (`insert`/`update`/`delete`) are synchronous.
3339
+ * Use the `wait` method when you need a Promise that resolves at a durability tier.
902
3340
  *
903
- * In browser environments, automatically uses a dedicated worker for
904
- * OPFS persistence. In Node.js, uses in-memory storage.
3341
+ * Browser and backend runtimes open the native runtime in-process.
905
3342
  *
906
3343
  * @param config Database configuration
907
3344
  * @returns Promise resolving to Db instance ready for queries and mutations
@@ -914,11 +3351,190 @@ function isBrowser() {
914
3351
  * });
915
3352
  * ```
916
3353
  */
917
- export async function createDb(config) {
918
- const resolvedConfig = resolveLocalAuthDefaults(config);
919
- if (isBrowser()) {
920
- return Db.createWithWorker(resolvedConfig);
3354
+ function createRuntimeTokenOptions(secret, audience, ttlSeconds) {
3355
+ return {
3356
+ secret,
3357
+ audience,
3358
+ ttlSeconds,
3359
+ nowSeconds: BigInt(Math.floor(Date.now() / 1000)),
3360
+ };
3361
+ }
3362
+ /**
3363
+ * @internal Start the persistent browser worker for an account context before
3364
+ * its runtime and credential are ready. An account's browser root and worker
3365
+ * are named by its account id and registry alone, so the SharedWorker can boot
3366
+ * and compile its WASM while the page loads its own runtime and resolves auth.
3367
+ * Returns undefined when the root depends on a credential or no worker is used.
3368
+ */
3369
+ export function startBrowserWorkerLease(config, runtimeSource) {
3370
+ if (!runtimeSource.supportsBrowserWorker ||
3371
+ !isBrowserRuntime() ||
3372
+ resolveStorageDriver(config.driver).type !== "persistent" ||
3373
+ !config.accountId ||
3374
+ !config.accountRegistryAuthority ||
3375
+ config.adminSecret ||
3376
+ config.runtimeSources?.browserWorkerPort)
3377
+ return undefined;
3378
+ const lease = runtimeSource.acquireBrowserForegroundNodeLease(config);
3379
+ // Observed by the Db that adopts it, or returned by releaseUnusedLease.
3380
+ void lease.catch(() => undefined);
3381
+ leaseRoots.set(lease, browserLeaseRoot(config));
3382
+ return lease;
3383
+ }
3384
+ /** The worker realm, physical root and owner a lease was acquired for. */
3385
+ const leaseRoots = new WeakMap();
3386
+ function browserLeaseRoot(config) {
3387
+ try {
3388
+ const sources = config.runtimeSources;
3389
+ return JSON.stringify([
3390
+ resolveDefaultPersistentDbName(config),
3391
+ createBrowserStorageOwner(config),
3392
+ sources?.wasmUrl ?? null,
3393
+ sources?.baseUrl ?? null,
3394
+ sources?.brokerWorkerUrl ?? null,
3395
+ sources?.wasmVersion ?? null,
3396
+ Boolean(sources?.wasmModule || sources?.wasmSource),
3397
+ ]);
3398
+ }
3399
+ catch {
3400
+ return undefined;
3401
+ }
3402
+ }
3403
+ /**
3404
+ * An early lease is only adopted for the exact root it was acquired for; a
3405
+ * config whose principal or assets changed while it resolved gets its own.
3406
+ */
3407
+ function leaseMatches(lease, config) {
3408
+ const root = leaseRoots.get(lease);
3409
+ return root !== undefined && root === browserLeaseRoot(config);
3410
+ }
3411
+ /**
3412
+ * @internal Return a lease that no Db adopted, keeping its node reusable.
3413
+ * Resolves once the worker has the lease back (or it never issued one), so a
3414
+ * replacement acquired afterwards never queues behind it.
3415
+ */
3416
+ export async function releaseUnusedLease(lease) {
3417
+ if (!lease || leaseClaimed.has(lease))
3418
+ return;
3419
+ leaseClaimed.add(lease);
3420
+ try {
3421
+ const acquired = await lease;
3422
+ await acquired.returnWithHighWater(acquired.confirmedTxTime);
3423
+ }
3424
+ catch {
3425
+ // A lease that failed to arrive, or could not be returned, holds nothing.
3426
+ }
3427
+ }
3428
+ export async function createDbWithRuntimeSource(config, runtimeSource, earlyLease) {
3429
+ let lease = earlyLease;
3430
+ try {
3431
+ return await openDbWithRuntimeSource(config, runtimeSource, () => {
3432
+ lease ??= startBrowserWorkerLease(config, runtimeSource);
3433
+ return lease;
3434
+ });
3435
+ }
3436
+ finally {
3437
+ void releaseUnusedLease(lease);
3438
+ }
3439
+ }
3440
+ /** Leases already adopted by a Db or released; neither may happen twice. */
3441
+ const leaseClaimed = new WeakSet();
3442
+ async function openDbWithRuntimeSource(config, runtimeSource, startLease) {
3443
+ assertAccountConfig(config);
3444
+ assertNoClientBackendSecret(config);
3445
+ if (config.secret && config.cookieSession) {
3446
+ throw new Error("DbConfig error: secret and cookieSession are mutually exclusive");
3447
+ }
3448
+ if (config.secret && config.jwtToken) {
3449
+ throw new Error("DbConfig error: secret and jwtToken are mutually exclusive");
3450
+ }
3451
+ if (config.jwtToken && config.cookieSession) {
3452
+ throw new Error("DbConfig error: jwtToken and cookieSession are mutually exclusive");
3453
+ }
3454
+ // Validate a durable root before loading a runtime or creating any author-
3455
+ // adjacent state. This makes malformed/legacy input fail deterministically
3456
+ // even when a platform artifact cannot be loaded.
3457
+ const parsedLocalFirstSeed = config.secret ? authSecretSeedForMinting(config.secret) : null;
3458
+ let resolvedConfig = { ...config };
3459
+ setTrustedReservedSession(resolvedConfig, getTrustedReservedSession(config));
3460
+ // Boot the worker while this page loads its own runtime.
3461
+ const earlyLease = startLease();
3462
+ await runtimeSource.load(config);
3463
+ const { secret: _secret, jwtToken: _jwtToken, cookieSession: _cookieSession, ...configWithoutAuth } = config;
3464
+ // Local-first auth: resolve seed and mint a JWT
3465
+ const localFirstSecret = parsedLocalFirstSeed;
3466
+ if (localFirstSecret) {
3467
+ const secret = localFirstSecret;
3468
+ if (!config.jwtToken) {
3469
+ const jwtToken = runtimeSource.mintLocalFirstToken(createRuntimeTokenOptions(secret, clientScope(config), 3600));
3470
+ const trustedReservedSession = internalSessionFromVerifiedReservedJwtPayload(parseJwtPayload(jwtToken) ?? {}, "local-first");
3471
+ resolvedConfig = { ...configWithoutAuth, jwtToken };
3472
+ setTrustedReservedSession(resolvedConfig, trustedReservedSession);
3473
+ }
3474
+ }
3475
+ else if (!config.jwtToken && !config.cookieSession && !config.adminSecret) {
3476
+ // Anonymous: mint an ephemeral keypair + anonymous JWT.
3477
+ // Admin-secret clients intentionally stay sessionless so local policy
3478
+ // evaluation does not preempt backend-authorized transport writes.
3479
+ const ephemeralSeed = generateEphemeralSeedBase64Url();
3480
+ const jwtToken = runtimeSource.mintAnonymousToken(createRuntimeTokenOptions(ephemeralSeed, clientScope(config), 3600));
3481
+ const trustedReservedSession = internalSessionFromVerifiedReservedJwtPayload(parseJwtPayload(jwtToken) ?? {}, "anonymous");
3482
+ resolvedConfig = { ...configWithoutAuth, jwtToken };
3483
+ setTrustedReservedSession(resolvedConfig, trustedReservedSession);
3484
+ }
3485
+ copyAccountConfigAdmission(config, resolvedConfig);
3486
+ runtimeSource.admitConfig(resolvedConfig);
3487
+ const driver = resolveStorageDriver(resolvedConfig.driver);
3488
+ const browserWorker = runtimeSource.supportsBrowserWorker && isBrowserRuntime() && driver.type === "persistent";
3489
+ const adoptedLease = earlyLease && browserWorker && leaseMatches(earlyLease, resolvedConfig)
3490
+ ? earlyLease
3491
+ : undefined;
3492
+ if (adoptedLease) {
3493
+ leaseClaimed.add(adoptedLease);
3494
+ }
3495
+ else if (earlyLease) {
3496
+ // Hand a lease for some other root back before this Db acquires its own,
3497
+ // so the two are never held, or queued behind each other, at once.
3498
+ await releaseUnusedLease(earlyLease);
3499
+ }
3500
+ const db = browserWorker
3501
+ ? await Db.createWithBrowserWorker(resolvedConfig, runtimeSource, adoptedLease)
3502
+ : await Db.createWithDirectConnection(resolvedConfig, runtimeSource);
3503
+ if (localFirstSecret) {
3504
+ db.initLocalFirstAuth(localFirstSecret, 3600, !config.jwtToken);
3505
+ }
3506
+ return db;
3507
+ }
3508
+ /** Keep server-only admission credentials out of every client runtime factory. */
3509
+ export function assertNoClientBackendSecret(config) {
3510
+ if (Object.hasOwn(config, "backendSecret")) {
3511
+ throw new Error("DbConfig does not accept backendSecret. Run Jazz in your backend with createJazz() from jazz-tools/backend instead.");
921
3512
  }
922
- return Db.create(resolvedConfig);
3513
+ }
3514
+ function isBrowserRuntime() {
3515
+ return typeof window !== "undefined" && typeof Worker !== "undefined";
3516
+ }
3517
+ const credentialRenewers = new WeakMap();
3518
+ /**
3519
+ * @internal Declare that the caller renews this Db's credential whenever the
3520
+ * server refuses it, until the returned release is called. Global write waits
3521
+ * then outlast a renewable refusal instead of failing (#3923).
3522
+ */
3523
+ export function holdCredentialRenewal(db) {
3524
+ credentialRenewers.set(db, (credentialRenewers.get(db) ?? 0) + 1);
3525
+ let released = false;
3526
+ return () => {
3527
+ if (released)
3528
+ return;
3529
+ released = true;
3530
+ credentialRenewers.set(db, (credentialRenewers.get(db) ?? 1) - 1);
3531
+ };
3532
+ }
3533
+ /** `error` says the runtime closed, also when a connection wrapped it as its cause. */
3534
+ function isRuntimeClosed(error) {
3535
+ for (let current = error; current instanceof Error; current = current.cause)
3536
+ if (current instanceof RuntimeClosedError)
3537
+ return true;
3538
+ return false;
923
3539
  }
924
3540
  //# sourceMappingURL=db.js.map