jazz-tools 2.0.0-alpha.7 → 2.0.0-alpha.70

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