jazz-tools 2.0.0-alpha.9 → 2.0.0-beta.1

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