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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1876) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +134 -7
  3. package/bin/jazz-tools.js +95 -68
  4. package/dist/_dev/inspector-cache-runtime.d.ts +8 -0
  5. package/dist/_dev/inspector-cache-runtime.d.ts.map +1 -0
  6. package/dist/_dev/inspector-cache-runtime.js +246 -0
  7. package/dist/_dev/inspector-cache-runtime.js.map +1 -0
  8. package/dist/_dev/inspector-client.d.ts +15 -0
  9. package/dist/_dev/inspector-client.d.ts.map +1 -0
  10. package/dist/_dev/inspector-client.js +134 -0
  11. package/dist/_dev/inspector-client.js.map +1 -0
  12. package/dist/_dev/native-account-session.d.ts +23 -0
  13. package/dist/_dev/native-account-session.d.ts.map +1 -0
  14. package/dist/_dev/native-account-session.js +61 -0
  15. package/dist/_dev/native-account-session.js.map +1 -0
  16. package/dist/_dev/native-binding-codec.d.ts +9 -0
  17. package/dist/_dev/native-binding-codec.d.ts.map +1 -0
  18. package/dist/_dev/native-binding-codec.js +9 -0
  19. package/dist/_dev/native-binding-codec.js.map +1 -0
  20. package/dist/accounts/account-manager-core.d.ts +87 -0
  21. package/dist/accounts/account-manager-core.d.ts.map +1 -0
  22. package/dist/accounts/account-manager-core.js +236 -0
  23. package/dist/accounts/account-manager-core.js.map +1 -0
  24. package/dist/accounts/browser-host.d.ts +8 -0
  25. package/dist/accounts/browser-host.d.ts.map +1 -0
  26. package/dist/accounts/browser-host.js +16 -0
  27. package/dist/accounts/browser-host.js.map +1 -0
  28. package/dist/accounts/config-capability.d.ts +26 -0
  29. package/dist/accounts/config-capability.d.ts.map +1 -0
  30. package/dist/accounts/config-capability.js +58 -0
  31. package/dist/accounts/config-capability.js.map +1 -0
  32. package/dist/accounts/context.d.ts +14 -0
  33. package/dist/accounts/context.d.ts.map +1 -0
  34. package/dist/accounts/context.js +214 -0
  35. package/dist/accounts/context.js.map +1 -0
  36. package/dist/accounts/enrollment.d.ts +95 -0
  37. package/dist/accounts/enrollment.d.ts.map +1 -0
  38. package/dist/accounts/enrollment.js +314 -0
  39. package/dist/accounts/enrollment.js.map +1 -0
  40. package/dist/accounts/exports.d.ts +3 -0
  41. package/dist/accounts/exports.d.ts.map +1 -0
  42. package/dist/accounts/exports.js +5 -0
  43. package/dist/accounts/exports.js.map +1 -0
  44. package/dist/accounts/local-first.d.ts +17 -0
  45. package/dist/accounts/local-first.d.ts.map +1 -0
  46. package/dist/accounts/local-first.js +62 -0
  47. package/dist/accounts/local-first.js.map +1 -0
  48. package/dist/accounts/persistence.d.ts +79 -0
  49. package/dist/accounts/persistence.d.ts.map +1 -0
  50. package/dist/accounts/persistence.js +533 -0
  51. package/dist/accounts/persistence.js.map +1 -0
  52. package/dist/accounts/process-store.d.ts +27 -0
  53. package/dist/accounts/process-store.d.ts.map +1 -0
  54. package/dist/accounts/process-store.js +49 -0
  55. package/dist/accounts/process-store.js.map +1 -0
  56. package/dist/accounts/registry-client.d.ts +79 -0
  57. package/dist/accounts/registry-client.d.ts.map +1 -0
  58. package/dist/accounts/registry-client.js +153 -0
  59. package/dist/accounts/registry-client.js.map +1 -0
  60. package/dist/accounts/state.d.ts +76 -0
  61. package/dist/accounts/state.d.ts.map +1 -0
  62. package/dist/accounts/state.js +172 -0
  63. package/dist/accounts/state.js.map +1 -0
  64. package/dist/app-file-enums.d.ts +9 -0
  65. package/dist/app-file-enums.d.ts.map +1 -0
  66. package/dist/app-file-enums.js +34 -0
  67. package/dist/app-file-enums.js.map +1 -0
  68. package/dist/authoring.d.ts +9 -0
  69. package/dist/authoring.d.ts.map +1 -0
  70. package/dist/authoring.js +9 -0
  71. package/dist/authoring.js.map +1 -0
  72. package/dist/backend/admission.d.ts +28 -0
  73. package/dist/backend/admission.d.ts.map +1 -0
  74. package/dist/backend/admission.js +146 -0
  75. package/dist/backend/admission.js.map +1 -0
  76. package/dist/backend/api.d.ts +12 -0
  77. package/dist/backend/api.d.ts.map +1 -0
  78. package/dist/backend/api.js +11 -0
  79. package/dist/backend/api.js.map +1 -0
  80. package/dist/backend/backend-clients.d.ts +76 -0
  81. package/dist/backend/backend-clients.d.ts.map +1 -0
  82. package/dist/backend/backend-clients.js +237 -0
  83. package/dist/backend/backend-clients.js.map +1 -0
  84. package/dist/backend/backend-issuer.d.ts +6 -0
  85. package/dist/backend/backend-issuer.d.ts.map +1 -0
  86. package/dist/backend/backend-issuer.js +6 -0
  87. package/dist/backend/backend-issuer.js.map +1 -0
  88. package/dist/backend/backend-native.d.ts +40 -0
  89. package/dist/backend/backend-native.d.ts.map +1 -0
  90. package/dist/backend/backend-native.js +37 -0
  91. package/dist/backend/backend-native.js.map +1 -0
  92. package/dist/backend/blobs.d.ts +130 -0
  93. package/dist/backend/blobs.d.ts.map +1 -0
  94. package/dist/backend/blobs.js +132 -0
  95. package/dist/backend/blobs.js.map +1 -0
  96. package/dist/backend/core-transport.d.ts +61 -0
  97. package/dist/backend/core-transport.d.ts.map +1 -0
  98. package/dist/backend/core-transport.js +106 -0
  99. package/dist/backend/core-transport.js.map +1 -0
  100. package/dist/backend/create-jazz-context.d.ts +94 -28
  101. package/dist/backend/create-jazz-context.d.ts.map +1 -1
  102. package/dist/backend/create-jazz-context.js +661 -67
  103. package/dist/backend/create-jazz-context.js.map +1 -1
  104. package/dist/backend/create-jazz-session.d.ts +125 -0
  105. package/dist/backend/create-jazz-session.d.ts.map +1 -0
  106. package/dist/backend/create-jazz-session.js +528 -0
  107. package/dist/backend/create-jazz-session.js.map +1 -0
  108. package/dist/backend/create-jazz.d.ts +677 -0
  109. package/dist/backend/create-jazz.d.ts.map +1 -0
  110. package/dist/backend/create-jazz.js +4076 -0
  111. package/dist/backend/create-jazz.js.map +1 -0
  112. package/dist/backend/early-db.d.ts +29 -0
  113. package/dist/backend/early-db.d.ts.map +1 -0
  114. package/dist/backend/early-db.js +203 -0
  115. package/dist/backend/early-db.js.map +1 -0
  116. package/dist/backend/external-jwt.d.ts +27 -0
  117. package/dist/backend/external-jwt.d.ts.map +1 -0
  118. package/dist/backend/external-jwt.js +404 -0
  119. package/dist/backend/external-jwt.js.map +1 -0
  120. package/dist/backend/from-jwt.d.ts +64 -0
  121. package/dist/backend/from-jwt.d.ts.map +1 -0
  122. package/dist/backend/from-jwt.js +104 -0
  123. package/dist/backend/from-jwt.js.map +1 -0
  124. package/dist/backend/index.d.ts +6 -3
  125. package/dist/backend/index.d.ts.map +1 -1
  126. package/dist/backend/index.js +18 -2
  127. package/dist/backend/index.js.map +1 -1
  128. package/dist/backend/inspect-ui.d.ts +14 -0
  129. package/dist/backend/inspect-ui.d.ts.map +1 -0
  130. package/dist/backend/inspect-ui.js +156 -0
  131. package/dist/backend/inspect-ui.js.map +1 -0
  132. package/dist/backend/inspect.d.ts +133 -0
  133. package/dist/backend/inspect.d.ts.map +1 -0
  134. package/dist/backend/inspect.js +1001 -0
  135. package/dist/backend/inspect.js.map +1 -0
  136. package/dist/backend/inspector-ui/0.js +2 -0
  137. package/dist/backend/inspector-ui/1.js +2 -0
  138. package/dist/backend/inspector-ui/10.js +2 -0
  139. package/dist/backend/inspector-ui/11.js +2 -0
  140. package/dist/backend/inspector-ui/12.js +2 -0
  141. package/dist/backend/inspector-ui/13.js +2 -0
  142. package/dist/backend/inspector-ui/14.js +2 -0
  143. package/dist/backend/inspector-ui/15.js +2 -0
  144. package/dist/backend/inspector-ui/16.js +2 -0
  145. package/dist/backend/inspector-ui/17.js +2 -0
  146. package/dist/backend/inspector-ui/18.js +2 -0
  147. package/dist/backend/inspector-ui/19.js +2 -0
  148. package/dist/backend/inspector-ui/2.js +2 -0
  149. package/dist/backend/inspector-ui/20.js +2 -0
  150. package/dist/backend/inspector-ui/21.js +2 -0
  151. package/dist/backend/inspector-ui/3.js +2 -0
  152. package/dist/backend/inspector-ui/4.js +2 -0
  153. package/dist/backend/inspector-ui/5.js +2 -0
  154. package/dist/backend/inspector-ui/6.js +2 -0
  155. package/dist/backend/inspector-ui/7.js +2 -0
  156. package/dist/backend/inspector-ui/8.js +2 -0
  157. package/dist/backend/inspector-ui/9.js +2 -0
  158. package/dist/backend/inspector-ui-files.d.ts +4 -0
  159. package/dist/backend/inspector-ui-files.d.ts.map +1 -0
  160. package/dist/backend/inspector-ui-files.js +26 -0
  161. package/dist/backend/no-account-error.d.ts +23 -0
  162. package/dist/backend/no-account-error.d.ts.map +1 -0
  163. package/dist/backend/no-account-error.js +30 -0
  164. package/dist/backend/no-account-error.js.map +1 -0
  165. package/dist/backend/node-native.d.ts +3 -0
  166. package/dist/backend/node-native.d.ts.map +1 -0
  167. package/dist/backend/node-native.js +19 -0
  168. package/dist/backend/node-native.js.map +1 -0
  169. package/dist/backend/node-peers.d.ts +10 -0
  170. package/dist/backend/node-peers.d.ts.map +1 -0
  171. package/dist/backend/node-peers.js +37 -0
  172. package/dist/backend/node-peers.js.map +1 -0
  173. package/dist/backend/optional-peer.d.ts +9 -0
  174. package/dist/backend/optional-peer.d.ts.map +1 -0
  175. package/dist/backend/optional-peer.js +24 -0
  176. package/dist/backend/optional-peer.js.map +1 -0
  177. package/dist/backend/request-auth.d.ts +69 -0
  178. package/dist/backend/request-auth.d.ts.map +1 -0
  179. package/dist/backend/request-auth.js +122 -0
  180. package/dist/backend/request-auth.js.map +1 -0
  181. package/dist/backend/session-expiry.d.ts +61 -0
  182. package/dist/backend/session-expiry.d.ts.map +1 -0
  183. package/dist/backend/session-expiry.js +102 -0
  184. package/dist/backend/session-expiry.js.map +1 -0
  185. package/dist/backend/signing-key.d.ts +32 -0
  186. package/dist/backend/signing-key.d.ts.map +1 -0
  187. package/dist/backend/signing-key.js +63 -0
  188. package/dist/backend/signing-key.js.map +1 -0
  189. package/dist/backend/socket-deadline.d.ts +23 -0
  190. package/dist/backend/socket-deadline.d.ts.map +1 -0
  191. package/dist/backend/socket-deadline.js +70 -0
  192. package/dist/backend/socket-deadline.js.map +1 -0
  193. package/dist/backend/store-log.d.ts +3 -0
  194. package/dist/backend/store-log.d.ts.map +1 -0
  195. package/dist/backend/store-log.js +16 -0
  196. package/dist/backend/store-log.js.map +1 -0
  197. package/dist/backend/thin-relay.d.ts +66 -0
  198. package/dist/backend/thin-relay.d.ts.map +1 -0
  199. package/dist/backend/thin-relay.js +204 -0
  200. package/dist/backend/thin-relay.js.map +1 -0
  201. package/dist/backend/thin-session-client.d.ts +23 -0
  202. package/dist/backend/thin-session-client.d.ts.map +1 -0
  203. package/dist/backend/thin-session-client.js +69 -0
  204. package/dist/backend/thin-session-client.js.map +1 -0
  205. package/dist/backend/upgrade-status.d.ts +19 -0
  206. package/dist/backend/upgrade-status.d.ts.map +1 -0
  207. package/dist/backend/upgrade-status.js +55 -0
  208. package/dist/backend/upgrade-status.js.map +1 -0
  209. package/dist/backend/vercel-store.d.ts +345 -0
  210. package/dist/backend/vercel-store.d.ts.map +1 -0
  211. package/dist/backend/vercel-store.js +1387 -0
  212. package/dist/backend/vercel-store.js.map +1 -0
  213. package/dist/backend/workerd-backend.d.ts +36 -0
  214. package/dist/backend/workerd-backend.d.ts.map +1 -0
  215. package/dist/backend/workerd-backend.js +97 -0
  216. package/dist/backend/workerd-backend.js.map +1 -0
  217. package/dist/backend/workerd.d.ts +3 -0
  218. package/dist/backend/workerd.d.ts.map +1 -0
  219. package/dist/backend/workerd.js +39 -0
  220. package/dist/backend/workerd.js.map +1 -0
  221. package/dist/backend/ws-peer.d.ts +32 -0
  222. package/dist/backend/ws-peer.d.ts.map +1 -0
  223. package/dist/backend/ws-peer.js +41 -0
  224. package/dist/backend/ws-peer.js.map +1 -0
  225. package/dist/better-auth-adapter/fixtures/app.d.ts +151 -0
  226. package/dist/better-auth-adapter/fixtures/app.d.ts.map +1 -0
  227. package/dist/better-auth-adapter/fixtures/app.js +13 -0
  228. package/dist/better-auth-adapter/fixtures/app.js.map +1 -0
  229. package/dist/better-auth-adapter/fixtures/issuer-upgrade.d.ts +20 -0
  230. package/dist/better-auth-adapter/fixtures/issuer-upgrade.d.ts.map +1 -0
  231. package/dist/better-auth-adapter/fixtures/issuer-upgrade.js +27 -0
  232. package/dist/better-auth-adapter/fixtures/issuer-upgrade.js.map +1 -0
  233. package/dist/better-auth-adapter/index.d.ts +13 -0
  234. package/dist/better-auth-adapter/index.d.ts.map +1 -0
  235. package/dist/better-auth-adapter/index.js +406 -0
  236. package/dist/better-auth-adapter/index.js.map +1 -0
  237. package/dist/better-auth-adapter/indexes.d.ts +9 -0
  238. package/dist/better-auth-adapter/indexes.d.ts.map +1 -0
  239. package/dist/better-auth-adapter/indexes.js +40 -0
  240. package/dist/better-auth-adapter/indexes.js.map +1 -0
  241. package/dist/better-auth-adapter/schema.d.ts +88 -0
  242. package/dist/better-auth-adapter/schema.d.ts.map +1 -0
  243. package/dist/better-auth-adapter/schema.js +332 -0
  244. package/dist/better-auth-adapter/schema.js.map +1 -0
  245. package/dist/better-auth-adapter/types.d.ts +13 -0
  246. package/dist/better-auth-adapter/types.d.ts.map +1 -0
  247. package/dist/better-auth-adapter/types.js +2 -0
  248. package/dist/better-auth-adapter/types.js.map +1 -0
  249. package/dist/better-auth-adapter/utils.d.ts +53 -0
  250. package/dist/better-auth-adapter/utils.d.ts.map +1 -0
  251. package/dist/better-auth-adapter/utils.js +126 -0
  252. package/dist/better-auth-adapter/utils.js.map +1 -0
  253. package/dist/browser-benchmark-mode.d.ts +6 -0
  254. package/dist/browser-benchmark-mode.d.ts.map +1 -0
  255. package/dist/browser-benchmark-mode.js +13 -0
  256. package/dist/browser-benchmark-mode.js.map +1 -0
  257. package/dist/classic-api.d.ts +59 -0
  258. package/dist/classic-api.d.ts.map +1 -0
  259. package/dist/classic-api.js +122 -0
  260. package/dist/classic-api.js.map +1 -0
  261. package/dist/cli.d.ts +38 -2
  262. package/dist/cli.d.ts.map +1 -1
  263. package/dist/cli.js +457 -265
  264. package/dist/cli.js.map +1 -1
  265. package/dist/client/index.d.ts +9 -0
  266. package/dist/client/index.d.ts.map +1 -0
  267. package/dist/client/index.js +5 -0
  268. package/dist/client/index.js.map +1 -0
  269. package/dist/cloud/api.d.ts +11 -0
  270. package/dist/cloud/api.d.ts.map +1 -0
  271. package/dist/cloud/api.js +46 -0
  272. package/dist/cloud/api.js.map +1 -0
  273. package/dist/cloud/commands.d.ts +13 -0
  274. package/dist/cloud/commands.d.ts.map +1 -0
  275. package/dist/cloud/commands.js +425 -0
  276. package/dist/cloud/commands.js.map +1 -0
  277. package/dist/cloud/credentials.d.ts +49 -0
  278. package/dist/cloud/credentials.d.ts.map +1 -0
  279. package/dist/cloud/credentials.js +219 -0
  280. package/dist/cloud/credentials.js.map +1 -0
  281. package/dist/cloud/session.d.ts +57 -0
  282. package/dist/cloud/session.d.ts.map +1 -0
  283. package/dist/cloud/session.js +269 -0
  284. package/dist/cloud/session.js.map +1 -0
  285. package/dist/codegen/relation-analyzer.d.ts +5 -12
  286. package/dist/codegen/relation-analyzer.d.ts.map +1 -1
  287. package/dist/codegen/relation-analyzer.js +53 -64
  288. package/dist/codegen/relation-analyzer.js.map +1 -1
  289. package/dist/dev/app-files.d.ts +32 -0
  290. package/dist/dev/app-files.d.ts.map +1 -0
  291. package/dist/dev/app-files.js +72 -0
  292. package/dist/dev/app-files.js.map +1 -0
  293. package/dist/dev/catalogue-api.d.ts +147 -0
  294. package/dist/dev/catalogue-api.d.ts.map +1 -0
  295. package/dist/dev/catalogue-api.js +127 -0
  296. package/dist/dev/catalogue-api.js.map +1 -0
  297. package/dist/dev/catalogue.d.ts +69 -0
  298. package/dist/dev/catalogue.d.ts.map +1 -0
  299. package/dist/dev/catalogue.js +70 -0
  300. package/dist/dev/catalogue.js.map +1 -0
  301. package/dist/dev/codegen-napi.d.ts +139 -0
  302. package/dist/dev/codegen-napi.d.ts.map +1 -0
  303. package/dist/dev/codegen-napi.js +157 -0
  304. package/dist/dev/codegen-napi.js.map +1 -0
  305. package/dist/dev/dev-server.d.ts +62 -0
  306. package/dist/dev/dev-server.d.ts.map +1 -0
  307. package/dist/dev/dev-server.js +164 -0
  308. package/dist/dev/dev-server.js.map +1 -0
  309. package/dist/dev/index.d.ts +3 -0
  310. package/dist/dev/index.d.ts.map +1 -0
  311. package/dist/dev/index.js +3 -0
  312. package/dist/dev/index.js.map +1 -0
  313. package/dist/dev/inspector-overlay/browser-control-registry.d.ts +10 -0
  314. package/dist/dev/inspector-overlay/browser-control-registry.d.ts.map +1 -0
  315. package/dist/dev/inspector-overlay/browser-control-registry.js +188 -0
  316. package/dist/dev/inspector-overlay/browser-control-registry.js.map +1 -0
  317. package/dist/dev/inspector-overlay/embedded/assets/ExportResult-C0ZojfNk.js +1 -0
  318. package/dist/dev/inspector-overlay/embedded/assets/backend-0Idv0niF.js +1 -0
  319. package/dist/dev/inspector-overlay/embedded/assets/backend-DHeT1LCS.css +1 -0
  320. package/dist/dev/inspector-overlay/embedded/assets/create-legacy-browser-delegate-DeI8PAZ5.js +1 -0
  321. package/dist/dev/inspector-overlay/embedded/assets/diag-api-3Z_Eel3W.js +1 -0
  322. package/dist/dev/inspector-overlay/embedded/assets/esm-BB6DtWpZ.js +1 -0
  323. package/dist/dev/inspector-overlay/embedded/assets/esm-B_xpsQL2.js +1 -0
  324. package/dist/dev/inspector-overlay/embedded/assets/esm-CE7mSo95.js +1 -0
  325. package/dist/dev/inspector-overlay/embedded/assets/esm-CcBEG-yV.js +1 -0
  326. package/dist/dev/inspector-overlay/embedded/assets/esm-DZrCzNXM.js +1 -0
  327. package/dist/dev/inspector-overlay/embedded/assets/esm-k373aadI.js +1 -0
  328. package/dist/dev/inspector-overlay/embedded/assets/index-DUKUt96e.js +5 -0
  329. package/dist/dev/inspector-overlay/embedded/assets/jazz-broker-worker-C_mr9Omd.js +5 -0
  330. package/dist/dev/inspector-overlay/embedded/assets/jazz_wasm-BOvbCHn3.js +1 -0
  331. package/dist/dev/inspector-overlay/embedded/assets/jazz_wasm_bg-BG8gazqt.wasm +0 -0
  332. package/dist/dev/inspector-overlay/embedded/assets/node-foreground-node-lease.browser-2mfp13Qb.js +1 -0
  333. package/dist/dev/inspector-overlay/embedded/assets/rolldown-runtime-XKyaHtl9.js +1 -0
  334. package/dist/dev/inspector-overlay/embedded/assets/src-4JwhxZaW.js +16 -0
  335. package/dist/dev/inspector-overlay/embedded/assets/src-Cq8gSOLx.css +1 -0
  336. package/dist/dev/inspector-overlay/embedded/backend.html +17 -0
  337. package/dist/dev/inspector-overlay/embedded/embedded.html +15 -0
  338. package/dist/dev/inspector-overlay/embedded/favicon.ico +0 -0
  339. package/dist/dev/inspector-overlay/host-bridge.d.ts +8 -0
  340. package/dist/dev/inspector-overlay/host-bridge.d.ts.map +1 -0
  341. package/dist/dev/inspector-overlay/host-bridge.js +139 -0
  342. package/dist/dev/inspector-overlay/host-bridge.js.map +1 -0
  343. package/dist/dev/inspector-overlay/inspector-host-types.d.ts +35 -0
  344. package/dist/dev/inspector-overlay/inspector-host-types.d.ts.map +1 -0
  345. package/dist/dev/inspector-overlay/inspector-host-types.js +10 -0
  346. package/dist/dev/inspector-overlay/inspector-host-types.js.map +1 -0
  347. package/dist/dev/inspector-overlay/loader.d.ts +24 -0
  348. package/dist/dev/inspector-overlay/loader.d.ts.map +1 -0
  349. package/dist/dev/inspector-overlay/loader.js +533 -0
  350. package/dist/dev/inspector-overlay/loader.js.map +1 -0
  351. package/dist/dev/migration-graph.d.ts +32 -0
  352. package/dist/dev/migration-graph.d.ts.map +1 -0
  353. package/dist/dev/migration-graph.js +136 -0
  354. package/dist/dev/migration-graph.js.map +1 -0
  355. package/dist/dev/migrations.d.ts +145 -0
  356. package/dist/dev/migrations.d.ts.map +1 -0
  357. package/dist/dev/migrations.js +700 -0
  358. package/dist/dev/migrations.js.map +1 -0
  359. package/dist/dev/project.d.ts +65 -0
  360. package/dist/dev/project.d.ts.map +1 -0
  361. package/dist/dev/project.js +179 -0
  362. package/dist/dev/project.js.map +1 -0
  363. package/dist/dev/schema-utils.d.ts +8 -0
  364. package/dist/dev/schema-utils.d.ts.map +1 -0
  365. package/dist/dev/schema-utils.js +75 -0
  366. package/dist/dev/schema-utils.js.map +1 -0
  367. package/dist/dev/schema-validation.d.ts +5 -0
  368. package/dist/dev/schema-validation.d.ts.map +1 -0
  369. package/dist/dev/schema-validation.js +11 -0
  370. package/dist/dev/schema-validation.js.map +1 -0
  371. package/dist/dev/ts-project.d.ts +77 -0
  372. package/dist/dev/ts-project.d.ts.map +1 -0
  373. package/dist/dev/ts-project.js +191 -0
  374. package/dist/dev/ts-project.js.map +1 -0
  375. package/dist/drivers/index.d.ts +1 -1
  376. package/dist/drivers/index.d.ts.map +1 -1
  377. package/dist/drivers/index.js.map +1 -1
  378. package/dist/drivers/schema-wire.d.ts +19 -3
  379. package/dist/drivers/schema-wire.d.ts.map +1 -1
  380. package/dist/drivers/schema-wire.js +61 -11
  381. package/dist/drivers/schema-wire.js.map +1 -1
  382. package/dist/drivers/types.d.ts +166 -29
  383. package/dist/drivers/types.d.ts.map +1 -1
  384. package/dist/drivers/types.js +5 -2
  385. package/dist/drivers/types.js.map +1 -1
  386. package/dist/dsl.d.ts +276 -121
  387. package/dist/dsl.d.ts.map +1 -1
  388. package/dist/dsl.js +196 -160
  389. package/dist/dsl.js.map +1 -1
  390. package/dist/durable-object/index.d.ts +26 -0
  391. package/dist/durable-object/index.d.ts.map +1 -0
  392. package/dist/durable-object/index.js +26 -0
  393. package/dist/durable-object/index.js.map +1 -0
  394. package/dist/e2ee/SODIUM-LICENSE.txt +36 -0
  395. package/dist/e2ee/SODIUM-SOURCES.json +4 -0
  396. package/dist/e2ee/browser.d.ts +18 -0
  397. package/dist/e2ee/browser.d.ts.map +1 -0
  398. package/dist/e2ee/browser.js +111 -0
  399. package/dist/e2ee/browser.js.map +1 -0
  400. package/dist/e2ee/context.d.ts +23 -0
  401. package/dist/e2ee/context.d.ts.map +1 -0
  402. package/dist/e2ee/context.js +49 -0
  403. package/dist/e2ee/context.js.map +1 -0
  404. package/dist/e2ee/crypto.d.ts +10 -0
  405. package/dist/e2ee/crypto.d.ts.map +1 -0
  406. package/dist/e2ee/crypto.js +22 -0
  407. package/dist/e2ee/crypto.js.map +1 -0
  408. package/dist/e2ee/envelope.d.ts +22 -0
  409. package/dist/e2ee/envelope.d.ts.map +1 -0
  410. package/dist/e2ee/envelope.js +52 -0
  411. package/dist/e2ee/envelope.js.map +1 -0
  412. package/dist/e2ee/index.d.ts +14 -0
  413. package/dist/e2ee/index.d.ts.map +1 -0
  414. package/dist/e2ee/index.js +3 -0
  415. package/dist/e2ee/index.js.map +1 -0
  416. package/dist/e2ee/large-value.d.ts +20 -0
  417. package/dist/e2ee/large-value.d.ts.map +1 -0
  418. package/dist/e2ee/large-value.js +204 -0
  419. package/dist/e2ee/large-value.js.map +1 -0
  420. package/dist/e2ee/native.d.ts +18 -0
  421. package/dist/e2ee/native.d.ts.map +1 -0
  422. package/dist/e2ee/native.js +91 -0
  423. package/dist/e2ee/native.js.map +1 -0
  424. package/dist/e2ee/record-frame.d.ts +3 -0
  425. package/dist/e2ee/record-frame.d.ts.map +1 -0
  426. package/dist/e2ee/record-frame.js +18 -0
  427. package/dist/e2ee/record-frame.js.map +1 -0
  428. package/dist/e2ee/signer.d.ts +10 -0
  429. package/dist/e2ee/signer.d.ts.map +1 -0
  430. package/dist/e2ee/signer.js +54 -0
  431. package/dist/e2ee/signer.js.map +1 -0
  432. package/dist/e2ee/sodium-browser.d.ts +2 -0
  433. package/dist/e2ee/sodium-browser.d.ts.map +1 -0
  434. package/dist/e2ee/sodium-browser.js +3432 -0
  435. package/dist/e2ee/sodium.d.ts +20 -0
  436. package/dist/e2ee/sodium.d.ts.map +1 -0
  437. package/dist/e2ee/sodium.js +165 -0
  438. package/dist/e2ee/sodium.js.map +1 -0
  439. package/dist/e2ee/types.d.ts +92 -0
  440. package/dist/e2ee/types.d.ts.map +1 -0
  441. package/dist/e2ee/types.js +2 -0
  442. package/dist/e2ee/types.js.map +1 -0
  443. package/dist/effect/backend/index.d.ts +8 -0
  444. package/dist/effect/backend/index.d.ts.map +1 -0
  445. package/dist/effect/backend/index.js +8 -0
  446. package/dist/effect/backend/index.js.map +1 -0
  447. package/dist/effect/errors.d.ts +53 -0
  448. package/dist/effect/errors.d.ts.map +1 -0
  449. package/dist/effect/errors.js +61 -0
  450. package/dist/effect/errors.js.map +1 -0
  451. package/dist/effect/index.d.ts +9 -0
  452. package/dist/effect/index.d.ts.map +1 -0
  453. package/dist/effect/index.js +9 -0
  454. package/dist/effect/index.js.map +1 -0
  455. package/dist/effect/jazz-backend.d.ts +69 -0
  456. package/dist/effect/jazz-backend.d.ts.map +1 -0
  457. package/dist/effect/jazz-backend.js +95 -0
  458. package/dist/effect/jazz-backend.js.map +1 -0
  459. package/dist/effect/jazz.d.ts +129 -0
  460. package/dist/effect/jazz.d.ts.map +1 -0
  461. package/dist/effect/jazz.js +182 -0
  462. package/dist/effect/jazz.js.map +1 -0
  463. package/dist/expo/create-account-manager.d.ts +28 -0
  464. package/dist/expo/create-account-manager.d.ts.map +1 -0
  465. package/dist/expo/create-account-manager.js +35 -0
  466. package/dist/expo/create-account-manager.js.map +1 -0
  467. package/dist/expo/create-jazz-session.d.ts +66 -0
  468. package/dist/expo/create-jazz-session.d.ts.map +1 -0
  469. package/dist/expo/create-jazz-session.js +96 -0
  470. package/dist/expo/create-jazz-session.js.map +1 -0
  471. package/dist/expo/index.d.ts +12 -0
  472. package/dist/expo/index.d.ts.map +1 -0
  473. package/dist/expo/index.js +10 -0
  474. package/dist/expo/index.js.map +1 -0
  475. package/dist/expo/metro.d.ts +20 -0
  476. package/dist/expo/metro.d.ts.map +1 -0
  477. package/dist/expo/metro.js +58 -0
  478. package/dist/expo/metro.js.map +1 -0
  479. package/dist/expo/polyfills.d.ts +2 -0
  480. package/dist/expo/polyfills.d.ts.map +1 -0
  481. package/dist/expo/polyfills.js +5 -0
  482. package/dist/expo/polyfills.js.map +1 -0
  483. package/dist/expo/provider.d.ts +10 -0
  484. package/dist/expo/provider.d.ts.map +1 -0
  485. package/dist/expo/provider.js +11 -0
  486. package/dist/expo/provider.js.map +1 -0
  487. package/dist/index.d.ts +21 -9
  488. package/dist/index.d.ts.map +1 -1
  489. package/dist/index.js +19 -12
  490. package/dist/index.js.map +1 -1
  491. package/dist/inspect/cli.d.ts +12 -0
  492. package/dist/inspect/cli.d.ts.map +1 -0
  493. package/dist/inspect/cli.js +320 -0
  494. package/dist/inspect/cli.js.map +1 -0
  495. package/dist/inspect/client.d.ts +67 -0
  496. package/dist/inspect/client.d.ts.map +1 -0
  497. package/dist/inspect/client.js +254 -0
  498. package/dist/inspect/client.js.map +1 -0
  499. package/dist/inspect/mcp.d.ts +28 -0
  500. package/dist/inspect/mcp.d.ts.map +1 -0
  501. package/dist/inspect/mcp.js +441 -0
  502. package/dist/inspect/mcp.js.map +1 -0
  503. package/dist/inspect/protocol.d.ts +317 -0
  504. package/dist/inspect/protocol.d.ts.map +1 -0
  505. package/dist/inspect/protocol.js +544 -0
  506. package/dist/inspect/protocol.js.map +1 -0
  507. package/dist/inspector/index.d.ts +10 -0
  508. package/dist/inspector/index.d.ts.map +1 -0
  509. package/dist/inspector/index.js +27 -0
  510. package/dist/inspector/index.js.map +1 -0
  511. package/dist/internal/inspector-query.d.ts +6 -0
  512. package/dist/internal/inspector-query.d.ts.map +1 -0
  513. package/dist/internal/inspector-query.js +20 -0
  514. package/dist/internal/inspector-query.js.map +1 -0
  515. package/dist/ir.d.ts +43 -7
  516. package/dist/ir.d.ts.map +1 -1
  517. package/dist/ir.js +509 -1
  518. package/dist/ir.js.map +1 -1
  519. package/dist/json-value.d.ts +6 -0
  520. package/dist/json-value.d.ts.map +1 -0
  521. package/dist/json-value.js +2 -0
  522. package/dist/json-value.js.map +1 -0
  523. package/dist/local-first/index.d.ts +18 -0
  524. package/dist/local-first/index.d.ts.map +1 -0
  525. package/dist/local-first/index.js +17 -0
  526. package/dist/local-first/index.js.map +1 -0
  527. package/dist/local-first-auth/browser.d.ts +18 -0
  528. package/dist/local-first-auth/browser.d.ts.map +1 -0
  529. package/dist/local-first-auth/browser.js +26 -0
  530. package/dist/local-first-auth/browser.js.map +1 -0
  531. package/dist/local-first-auth/encoding.d.ts +10 -0
  532. package/dist/local-first-auth/encoding.d.ts.map +1 -0
  533. package/dist/local-first-auth/encoding.js +38 -0
  534. package/dist/local-first-auth/encoding.js.map +1 -0
  535. package/dist/local-first-auth/identity.d.ts +73 -0
  536. package/dist/local-first-auth/identity.d.ts.map +1 -0
  537. package/dist/local-first-auth/identity.js +258 -0
  538. package/dist/local-first-auth/identity.js.map +1 -0
  539. package/dist/local-first-auth/index.d.ts +6 -0
  540. package/dist/local-first-auth/index.d.ts.map +1 -0
  541. package/dist/local-first-auth/index.js +4 -0
  542. package/dist/local-first-auth/index.js.map +1 -0
  543. package/dist/local-first-auth/passkey.d.ts +22 -0
  544. package/dist/local-first-auth/passkey.d.ts.map +1 -0
  545. package/dist/local-first-auth/passkey.js +116 -0
  546. package/dist/local-first-auth/passkey.js.map +1 -0
  547. package/dist/local-first-auth/recovery-phrase.d.ts +10 -0
  548. package/dist/local-first-auth/recovery-phrase.d.ts.map +1 -0
  549. package/dist/local-first-auth/recovery-phrase.js +59 -0
  550. package/dist/local-first-auth/recovery-phrase.js.map +1 -0
  551. package/dist/local-first-auth/secret.d.ts +25 -0
  552. package/dist/local-first-auth/secret.d.ts.map +1 -0
  553. package/dist/local-first-auth/secret.js +68 -0
  554. package/dist/local-first-auth/secret.js.map +1 -0
  555. package/dist/local-first-auth/server.d.ts +13 -0
  556. package/dist/local-first-auth/server.d.ts.map +1 -0
  557. package/dist/local-first-auth/server.js +32 -0
  558. package/dist/local-first-auth/server.js.map +1 -0
  559. package/dist/local-first-auth/store.d.ts +51 -0
  560. package/dist/local-first-auth/store.d.ts.map +1 -0
  561. package/dist/local-first-auth/store.js +112 -0
  562. package/dist/local-first-auth/store.js.map +1 -0
  563. package/dist/magic-columns.d.ts +40 -0
  564. package/dist/magic-columns.d.ts.map +1 -0
  565. package/dist/magic-columns.js +110 -0
  566. package/dist/magic-columns.js.map +1 -0
  567. package/dist/migration-namespace.d.ts +12 -0
  568. package/dist/migration-namespace.d.ts.map +1 -0
  569. package/dist/migration-namespace.js +13 -0
  570. package/dist/migration-namespace.js.map +1 -0
  571. package/dist/migrations.d.ts +286 -0
  572. package/dist/migrations.d.ts.map +1 -0
  573. package/dist/migrations.js +188 -0
  574. package/dist/migrations.js.map +1 -0
  575. package/dist/module-interop.d.ts +17 -0
  576. package/dist/module-interop.d.ts.map +1 -0
  577. package/dist/module-interop.js +32 -0
  578. package/dist/module-interop.js.map +1 -0
  579. package/dist/observed-jazz-client.d.ts +15 -0
  580. package/dist/observed-jazz-client.d.ts.map +1 -0
  581. package/dist/observed-jazz-client.js +47 -0
  582. package/dist/observed-jazz-client.js.map +1 -0
  583. package/dist/passkey-backup.d.ts +3 -0
  584. package/dist/passkey-backup.d.ts.map +1 -0
  585. package/dist/passkey-backup.js +2 -0
  586. package/dist/passkey-backup.js.map +1 -0
  587. package/dist/passphrase.d.ts +2 -0
  588. package/dist/passphrase.d.ts.map +1 -0
  589. package/dist/passphrase.js +2 -0
  590. package/dist/passphrase.js.map +1 -0
  591. package/dist/permissions/__fixtures__/big-label-better-auth.d.ts +89 -0
  592. package/dist/permissions/__fixtures__/big-label-better-auth.d.ts.map +1 -0
  593. package/dist/permissions/__fixtures__/big-label-better-auth.js +62 -0
  594. package/dist/permissions/__fixtures__/big-label-better-auth.js.map +1 -0
  595. package/dist/permissions/__fixtures__/big-label.d.ts +332 -0
  596. package/dist/permissions/__fixtures__/big-label.d.ts.map +1 -0
  597. package/dist/permissions/__fixtures__/big-label.js +177 -0
  598. package/dist/permissions/__fixtures__/big-label.js.map +1 -0
  599. package/dist/permissions/__fixtures__/chat-react.d.ts +112 -0
  600. package/dist/permissions/__fixtures__/chat-react.d.ts.map +1 -0
  601. package/dist/permissions/__fixtures__/chat-react.js +51 -0
  602. package/dist/permissions/__fixtures__/chat-react.js.map +1 -0
  603. package/dist/permissions/compile.d.ts +182 -0
  604. package/dist/permissions/compile.d.ts.map +1 -0
  605. package/dist/permissions/compile.js +715 -0
  606. package/dist/permissions/compile.js.map +1 -0
  607. package/dist/permissions/dsl.d.ts +158 -0
  608. package/dist/permissions/dsl.d.ts.map +1 -0
  609. package/dist/permissions/dsl.js +391 -0
  610. package/dist/permissions/dsl.js.map +1 -0
  611. package/dist/permissions/relation.d.ts +84 -0
  612. package/dist/permissions/relation.d.ts.map +1 -0
  613. package/dist/permissions/relation.js +150 -0
  614. package/dist/permissions/relation.js.map +1 -0
  615. package/dist/permissions/types.d.ts +357 -0
  616. package/dist/permissions/types.d.ts.map +1 -0
  617. package/dist/permissions/types.js +5 -0
  618. package/dist/permissions/types.js.map +1 -0
  619. package/dist/printer/app-json.d.ts +96 -0
  620. package/dist/printer/app-json.d.ts.map +1 -0
  621. package/dist/printer/app-json.js +18 -0
  622. package/dist/printer/app-json.js.map +1 -0
  623. package/dist/printer/cli.d.ts +15 -0
  624. package/dist/printer/cli.d.ts.map +1 -0
  625. package/dist/printer/cli.js +76 -0
  626. package/dist/printer/cli.js.map +1 -0
  627. package/dist/printer/defs.d.ts +11 -0
  628. package/dist/printer/defs.d.ts.map +1 -0
  629. package/dist/printer/defs.js +123 -0
  630. package/dist/printer/defs.js.map +1 -0
  631. package/dist/printer/expr.d.ts +281 -0
  632. package/dist/printer/expr.d.ts.map +1 -0
  633. package/dist/printer/expr.js +940 -0
  634. package/dist/printer/expr.js.map +1 -0
  635. package/dist/printer/format.d.ts +17 -0
  636. package/dist/printer/format.d.ts.map +1 -0
  637. package/dist/printer/format.js +315 -0
  638. package/dist/printer/format.js.map +1 -0
  639. package/dist/printer/index.d.ts +31 -0
  640. package/dist/printer/index.d.ts.map +1 -0
  641. package/dist/printer/index.js +51 -0
  642. package/dist/printer/index.js.map +1 -0
  643. package/dist/printer/migrations.d.ts +28 -0
  644. package/dist/printer/migrations.d.ts.map +1 -0
  645. package/dist/printer/migrations.js +179 -0
  646. package/dist/printer/migrations.js.map +1 -0
  647. package/dist/printer/names.d.ts +17 -0
  648. package/dist/printer/names.d.ts.map +1 -0
  649. package/dist/printer/names.js +124 -0
  650. package/dist/printer/names.js.map +1 -0
  651. package/dist/printer/permissions.d.ts +60 -0
  652. package/dist/printer/permissions.d.ts.map +1 -0
  653. package/dist/printer/permissions.js +1167 -0
  654. package/dist/printer/permissions.js.map +1 -0
  655. package/dist/printer/schema.d.ts +18 -0
  656. package/dist/printer/schema.d.ts.map +1 -0
  657. package/dist/printer/schema.js +132 -0
  658. package/dist/printer/schema.js.map +1 -0
  659. package/dist/prosemirror/anchors.d.ts +30 -0
  660. package/dist/prosemirror/anchors.d.ts.map +1 -0
  661. package/dist/prosemirror/anchors.js +28 -0
  662. package/dist/prosemirror/anchors.js.map +1 -0
  663. package/dist/prosemirror/index.d.ts +7 -0
  664. package/dist/prosemirror/index.d.ts.map +1 -0
  665. package/dist/prosemirror/index.js +7 -0
  666. package/dist/prosemirror/index.js.map +1 -0
  667. package/dist/prosemirror/markdown.d.ts +95 -0
  668. package/dist/prosemirror/markdown.d.ts.map +1 -0
  669. package/dist/prosemirror/markdown.js +428 -0
  670. package/dist/prosemirror/markdown.js.map +1 -0
  671. package/dist/prosemirror/overlays.d.ts +69 -0
  672. package/dist/prosemirror/overlays.d.ts.map +1 -0
  673. package/dist/prosemirror/overlays.js +143 -0
  674. package/dist/prosemirror/overlays.js.map +1 -0
  675. package/dist/prosemirror/presence.d.ts +39 -0
  676. package/dist/prosemirror/presence.d.ts.map +1 -0
  677. package/dist/prosemirror/presence.js +88 -0
  678. package/dist/prosemirror/presence.js.map +1 -0
  679. package/dist/prosemirror/sync.d.ts +60 -0
  680. package/dist/prosemirror/sync.d.ts.map +1 -0
  681. package/dist/prosemirror/sync.js +196 -0
  682. package/dist/prosemirror/sync.js.map +1 -0
  683. package/dist/prosemirror/text-map.d.ts +21 -0
  684. package/dist/prosemirror/text-map.d.ts.map +1 -0
  685. package/dist/prosemirror/text-map.js +85 -0
  686. package/dist/prosemirror/text-map.js.map +1 -0
  687. package/dist/react/create-jazz-client.d.ts +2 -11
  688. package/dist/react/create-jazz-client.d.ts.map +1 -1
  689. package/dist/react/create-jazz-client.js +1 -47
  690. package/dist/react/create-jazz-client.js.map +1 -1
  691. package/dist/react/index.d.ts +14 -7
  692. package/dist/react/index.d.ts.map +1 -1
  693. package/dist/react/index.js +8 -6
  694. package/dist/react/index.js.map +1 -1
  695. package/dist/react/provider-props.d.ts +7 -0
  696. package/dist/react/provider-props.d.ts.map +1 -0
  697. package/dist/react/provider-props.js +15 -0
  698. package/dist/react/provider-props.js.map +1 -0
  699. package/dist/react/provider.d.ts +19 -15
  700. package/dist/react/provider.d.ts.map +1 -1
  701. package/dist/react/provider.js +25 -5
  702. package/dist/react/provider.js.map +1 -1
  703. package/dist/react/use-all.d.ts +1 -1
  704. package/dist/react/use-all.d.ts.map +1 -1
  705. package/dist/react/use-all.js +1 -1
  706. package/dist/react/use-all.js.map +1 -1
  707. package/dist/react/use-one.d.ts +2 -0
  708. package/dist/react/use-one.d.ts.map +1 -0
  709. package/dist/react/use-one.js +2 -0
  710. package/dist/react/use-one.js.map +1 -0
  711. package/dist/react-core/index.d.ts +9 -4
  712. package/dist/react-core/index.d.ts.map +1 -1
  713. package/dist/react-core/index.js +10 -2
  714. package/dist/react-core/index.js.map +1 -1
  715. package/dist/react-core/provider.d.ts +48 -12
  716. package/dist/react-core/provider.d.ts.map +1 -1
  717. package/dist/react-core/provider.js +117 -13
  718. package/dist/react-core/provider.js.map +1 -1
  719. package/dist/react-core/session-context.d.ts +7 -0
  720. package/dist/react-core/session-context.d.ts.map +1 -0
  721. package/dist/react-core/session-context.js +8 -0
  722. package/dist/react-core/session-context.js.map +1 -0
  723. package/dist/react-core/session.d.ts +63 -0
  724. package/dist/react-core/session.d.ts.map +1 -0
  725. package/dist/react-core/session.js +97 -0
  726. package/dist/react-core/session.js.map +1 -0
  727. package/dist/react-core/use-all.d.ts +95 -3
  728. package/dist/react-core/use-all.d.ts.map +1 -1
  729. package/dist/react-core/use-all.js +126 -52
  730. package/dist/react-core/use-all.js.map +1 -1
  731. package/dist/react-core/use-auth-state.d.ts +13 -0
  732. package/dist/react-core/use-auth-state.d.ts.map +1 -0
  733. package/dist/react-core/use-auth-state.js +15 -0
  734. package/dist/react-core/use-auth-state.js.map +1 -0
  735. package/dist/react-core/use-one.d.ts +58 -0
  736. package/dist/react-core/use-one.d.ts.map +1 -0
  737. package/dist/react-core/use-one.js +19 -0
  738. package/dist/react-core/use-one.js.map +1 -0
  739. package/dist/react-core/use-sync-status.d.ts +8 -0
  740. package/dist/react-core/use-sync-status.d.ts.map +1 -0
  741. package/dist/react-core/use-sync-status.js +12 -0
  742. package/dist/react-core/use-sync-status.js.map +1 -0
  743. package/dist/react-native/abort-signal.d.ts +9 -0
  744. package/dist/react-native/abort-signal.d.ts.map +1 -0
  745. package/dist/react-native/abort-signal.js +51 -0
  746. package/dist/react-native/abort-signal.js.map +1 -0
  747. package/dist/react-native/account-session.d.ts +11 -0
  748. package/dist/react-native/account-session.d.ts.map +1 -0
  749. package/dist/react-native/account-session.js +59 -0
  750. package/dist/react-native/account-session.js.map +1 -0
  751. package/dist/react-native/create-account-manager.d.ts +28 -0
  752. package/dist/react-native/create-account-manager.d.ts.map +1 -0
  753. package/dist/react-native/create-account-manager.js +30 -0
  754. package/dist/react-native/create-account-manager.js.map +1 -0
  755. package/dist/react-native/create-db.d.ts +8 -0
  756. package/dist/react-native/create-db.d.ts.map +1 -0
  757. package/dist/react-native/create-db.js +9 -0
  758. package/dist/react-native/create-db.js.map +1 -0
  759. package/dist/react-native/create-jazz-client.d.ts +12 -10
  760. package/dist/react-native/create-jazz-client.d.ts.map +1 -1
  761. package/dist/react-native/create-jazz-client.js +6 -21
  762. package/dist/react-native/create-jazz-client.js.map +1 -1
  763. package/dist/react-native/create-jazz-session.d.ts +66 -0
  764. package/dist/react-native/create-jazz-session.d.ts.map +1 -0
  765. package/dist/react-native/create-jazz-session.js +96 -0
  766. package/dist/react-native/create-jazz-session.js.map +1 -0
  767. package/dist/react-native/errors.d.ts +6 -0
  768. package/dist/react-native/errors.d.ts.map +1 -0
  769. package/dist/react-native/errors.js +6 -0
  770. package/dist/react-native/errors.js.map +1 -0
  771. package/dist/react-native/index.d.ts +19 -9
  772. package/dist/react-native/index.d.ts.map +1 -1
  773. package/dist/react-native/index.js +13 -7
  774. package/dist/react-native/index.js.map +1 -1
  775. package/dist/react-native/native-foreground-db.d.ts +227 -0
  776. package/dist/react-native/native-foreground-db.d.ts.map +1 -0
  777. package/dist/react-native/native-foreground-db.js +905 -0
  778. package/dist/react-native/native-foreground-db.js.map +1 -0
  779. package/dist/react-native/native-relay.d.ts +7 -0
  780. package/dist/react-native/native-relay.d.ts.map +1 -0
  781. package/dist/react-native/native-relay.js +14 -0
  782. package/dist/react-native/native-relay.js.map +1 -0
  783. package/dist/react-native/provider.d.ts +19 -13
  784. package/dist/react-native/provider.d.ts.map +1 -1
  785. package/dist/react-native/provider.js +25 -5
  786. package/dist/react-native/provider.js.map +1 -1
  787. package/dist/react-native/runtime-source.d.ts +62 -0
  788. package/dist/react-native/runtime-source.d.ts.map +1 -0
  789. package/dist/react-native/runtime-source.js +314 -0
  790. package/dist/react-native/runtime-source.js.map +1 -0
  791. package/dist/react-native/use-all.d.ts +1 -1
  792. package/dist/react-native/use-all.d.ts.map +1 -1
  793. package/dist/react-native/use-all.js +1 -1
  794. package/dist/react-native/use-all.js.map +1 -1
  795. package/dist/react-native/use-one.d.ts +2 -0
  796. package/dist/react-native/use-one.d.ts.map +1 -0
  797. package/dist/react-native/use-one.js +2 -0
  798. package/dist/react-native/use-one.js.map +1 -0
  799. package/dist/reconcile-array.d.ts +45 -0
  800. package/dist/reconcile-array.d.ts.map +1 -0
  801. package/dist/reconcile-array.js +252 -0
  802. package/dist/reconcile-array.js.map +1 -0
  803. package/dist/relationships.d.ts +18 -0
  804. package/dist/relationships.d.ts.map +1 -0
  805. package/dist/relationships.js +28 -0
  806. package/dist/relationships.js.map +1 -0
  807. package/dist/runtime/auth-renewal-backoff.d.ts +14 -0
  808. package/dist/runtime/auth-renewal-backoff.d.ts.map +1 -0
  809. package/dist/runtime/auth-renewal-backoff.js +23 -0
  810. package/dist/runtime/auth-renewal-backoff.js.map +1 -0
  811. package/dist/runtime/auth-request-deadline.d.ts +3 -0
  812. package/dist/runtime/auth-request-deadline.d.ts.map +1 -0
  813. package/dist/runtime/auth-request-deadline.js +24 -0
  814. package/dist/runtime/auth-request-deadline.js.map +1 -0
  815. package/dist/runtime/auth-secret-codec.d.ts +21 -0
  816. package/dist/runtime/auth-secret-codec.d.ts.map +1 -0
  817. package/dist/runtime/auth-secret-codec.js +32 -0
  818. package/dist/runtime/auth-secret-codec.js.map +1 -0
  819. package/dist/runtime/auth-secret-store.d.ts +7 -0
  820. package/dist/runtime/auth-secret-store.d.ts.map +1 -0
  821. package/dist/runtime/auth-secret-store.js +12 -0
  822. package/dist/runtime/auth-secret-store.js.map +1 -0
  823. package/dist/runtime/auth-state.d.ts +47 -0
  824. package/dist/runtime/auth-state.d.ts.map +1 -0
  825. package/dist/runtime/auth-state.js +161 -0
  826. package/dist/runtime/auth-state.js.map +1 -0
  827. package/dist/runtime/author-id.d.ts +42 -0
  828. package/dist/runtime/author-id.d.ts.map +1 -0
  829. package/dist/runtime/author-id.js +172 -0
  830. package/dist/runtime/author-id.js.map +1 -0
  831. package/dist/runtime/authority-changed-error.d.ts +56 -0
  832. package/dist/runtime/authority-changed-error.d.ts.map +1 -0
  833. package/dist/runtime/authority-changed-error.js +74 -0
  834. package/dist/runtime/authority-changed-error.js.map +1 -0
  835. package/dist/runtime/backlog-rows.d.ts +3 -0
  836. package/dist/runtime/backlog-rows.d.ts.map +1 -0
  837. package/dist/runtime/backlog-rows.js +7 -0
  838. package/dist/runtime/backlog-rows.js.map +1 -0
  839. package/dist/runtime/browser-physical-database-epoch.d.ts +37 -0
  840. package/dist/runtime/browser-physical-database-epoch.d.ts.map +1 -0
  841. package/dist/runtime/browser-physical-database-epoch.js +89 -0
  842. package/dist/runtime/browser-physical-database-epoch.js.map +1 -0
  843. package/dist/runtime/browser-storage-invalidation.d.ts +8 -0
  844. package/dist/runtime/browser-storage-invalidation.d.ts.map +1 -0
  845. package/dist/runtime/browser-storage-invalidation.js +20 -0
  846. package/dist/runtime/browser-storage-invalidation.js.map +1 -0
  847. package/dist/runtime/browser-store-generation.d.ts +15 -0
  848. package/dist/runtime/browser-store-generation.d.ts.map +1 -0
  849. package/dist/runtime/browser-store-generation.js +48 -0
  850. package/dist/runtime/browser-store-generation.js.map +1 -0
  851. package/dist/runtime/browser-worker-assets.d.ts +31 -0
  852. package/dist/runtime/browser-worker-assets.d.ts.map +1 -0
  853. package/dist/runtime/browser-worker-assets.js +40 -0
  854. package/dist/runtime/browser-worker-assets.js.map +1 -0
  855. package/dist/runtime/browser-worker-assets.metro.d.ts +28 -0
  856. package/dist/runtime/browser-worker-assets.metro.d.ts.map +1 -0
  857. package/dist/runtime/browser-worker-assets.metro.js +52 -0
  858. package/dist/runtime/browser-worker-assets.metro.js.map +1 -0
  859. package/dist/runtime/browser-worker-assets.native.d.ts +7 -0
  860. package/dist/runtime/browser-worker-assets.native.d.ts.map +1 -0
  861. package/dist/runtime/browser-worker-assets.native.js +8 -0
  862. package/dist/runtime/browser-worker-assets.native.js.map +1 -0
  863. package/dist/runtime/browser-worker-config.d.ts +78 -0
  864. package/dist/runtime/browser-worker-config.d.ts.map +1 -0
  865. package/dist/runtime/browser-worker-config.js +299 -0
  866. package/dist/runtime/browser-worker-config.js.map +1 -0
  867. package/dist/runtime/client-config-key.d.ts +6 -0
  868. package/dist/runtime/client-config-key.d.ts.map +1 -0
  869. package/dist/runtime/client-config-key.js +83 -0
  870. package/dist/runtime/client-config-key.js.map +1 -0
  871. package/dist/runtime/client-migrations.d.ts +27 -0
  872. package/dist/runtime/client-migrations.d.ts.map +1 -0
  873. package/dist/runtime/client-migrations.js +25 -0
  874. package/dist/runtime/client-migrations.js.map +1 -0
  875. package/dist/runtime/client-registry.d.ts +21 -0
  876. package/dist/runtime/client-registry.d.ts.map +1 -0
  877. package/dist/runtime/client-registry.js +169 -0
  878. package/dist/runtime/client-registry.js.map +1 -0
  879. package/dist/runtime/client-scope.d.ts +38 -0
  880. package/dist/runtime/client-scope.d.ts.map +1 -0
  881. package/dist/runtime/client-scope.js +64 -0
  882. package/dist/runtime/client-scope.js.map +1 -0
  883. package/dist/runtime/client-session.d.ts +56 -14
  884. package/dist/runtime/client-session.d.ts.map +1 -1
  885. package/dist/runtime/client-session.js +211 -195
  886. package/dist/runtime/client-session.js.map +1 -1
  887. package/dist/runtime/client.d.ts +721 -194
  888. package/dist/runtime/client.d.ts.map +1 -1
  889. package/dist/runtime/client.js +1213 -434
  890. package/dist/runtime/client.js.map +1 -1
  891. package/dist/runtime/column-transforms.d.ts +26 -0
  892. package/dist/runtime/column-transforms.d.ts.map +1 -0
  893. package/dist/runtime/column-transforms.js +186 -0
  894. package/dist/runtime/column-transforms.js.map +1 -0
  895. package/dist/runtime/connection-manager/browser-connection-manager.d.ts +178 -0
  896. package/dist/runtime/connection-manager/browser-connection-manager.d.ts.map +1 -0
  897. package/dist/runtime/connection-manager/browser-connection-manager.js +1030 -0
  898. package/dist/runtime/connection-manager/browser-connection-manager.js.map +1 -0
  899. package/dist/runtime/connection-manager/direct-connection-manager.d.ts +28 -0
  900. package/dist/runtime/connection-manager/direct-connection-manager.d.ts.map +1 -0
  901. package/dist/runtime/connection-manager/direct-connection-manager.js +202 -0
  902. package/dist/runtime/connection-manager/direct-connection-manager.js.map +1 -0
  903. package/dist/runtime/connection-manager/index.d.ts +5 -0
  904. package/dist/runtime/connection-manager/index.d.ts.map +1 -0
  905. package/dist/runtime/connection-manager/index.js +4 -0
  906. package/dist/runtime/connection-manager/index.js.map +1 -0
  907. package/dist/runtime/connection-manager/types.d.ts +174 -0
  908. package/dist/runtime/connection-manager/types.d.ts.map +1 -0
  909. package/dist/runtime/connection-manager/types.js +396 -0
  910. package/dist/runtime/connection-manager/types.js.map +1 -0
  911. package/dist/runtime/context.d.ts +100 -30
  912. package/dist/runtime/context.d.ts.map +1 -1
  913. package/dist/runtime/context.js.map +1 -1
  914. package/dist/runtime/core-tick-failed-error.d.ts +31 -0
  915. package/dist/runtime/core-tick-failed-error.d.ts.map +1 -0
  916. package/dist/runtime/core-tick-failed-error.js +45 -0
  917. package/dist/runtime/core-tick-failed-error.js.map +1 -0
  918. package/dist/runtime/credentialed-transport.d.ts +42 -0
  919. package/dist/runtime/credentialed-transport.d.ts.map +1 -0
  920. package/dist/runtime/credentialed-transport.js +178 -0
  921. package/dist/runtime/credentialed-transport.js.map +1 -0
  922. package/dist/runtime/db-access-context.d.ts +14 -0
  923. package/dist/runtime/db-access-context.d.ts.map +1 -0
  924. package/dist/runtime/db-access-context.js +26 -0
  925. package/dist/runtime/db-access-context.js.map +1 -0
  926. package/dist/runtime/db-internal-session.d.ts +7 -0
  927. package/dist/runtime/db-internal-session.d.ts.map +1 -0
  928. package/dist/runtime/db-internal-session.js +21 -0
  929. package/dist/runtime/db-internal-session.js.map +1 -0
  930. package/dist/runtime/db-replaced-error.d.ts +21 -0
  931. package/dist/runtime/db-replaced-error.d.ts.map +1 -0
  932. package/dist/runtime/db-replaced-error.js +22 -0
  933. package/dist/runtime/db-replaced-error.js.map +1 -0
  934. package/dist/runtime/db.d.ts +857 -215
  935. package/dist/runtime/db.d.ts.map +1 -1
  936. package/dist/runtime/db.js +3474 -834
  937. package/dist/runtime/db.js.map +1 -1
  938. package/dist/runtime/default-create-db.d.ts +5 -0
  939. package/dist/runtime/default-create-db.d.ts.map +1 -0
  940. package/dist/runtime/default-create-db.js +7 -0
  941. package/dist/runtime/default-create-db.js.map +1 -0
  942. package/dist/runtime/default-runtime-source.d.ts +41 -0
  943. package/dist/runtime/default-runtime-source.d.ts.map +1 -0
  944. package/dist/runtime/default-runtime-source.js +326 -0
  945. package/dist/runtime/default-runtime-source.js.map +1 -0
  946. package/dist/runtime/delete-local-first-store.d.ts +12 -0
  947. package/dist/runtime/delete-local-first-store.d.ts.map +1 -0
  948. package/dist/runtime/delete-local-first-store.js +12 -0
  949. package/dist/runtime/delete-local-first-store.js.map +1 -0
  950. package/dist/runtime/deterministic-bytes.d.ts +6 -0
  951. package/dist/runtime/deterministic-bytes.d.ts.map +1 -0
  952. package/dist/runtime/deterministic-bytes.js +18 -0
  953. package/dist/runtime/deterministic-bytes.js.map +1 -0
  954. package/dist/runtime/graceful-shutdown-error.d.ts +17 -0
  955. package/dist/runtime/graceful-shutdown-error.d.ts.map +1 -0
  956. package/dist/runtime/graceful-shutdown-error.js +31 -0
  957. package/dist/runtime/graceful-shutdown-error.js.map +1 -0
  958. package/dist/runtime/hex.d.ts +21 -0
  959. package/dist/runtime/hex.d.ts.map +1 -0
  960. package/dist/runtime/hex.js +62 -0
  961. package/dist/runtime/hex.js.map +1 -0
  962. package/dist/runtime/history-relation.d.ts +8 -0
  963. package/dist/runtime/history-relation.d.ts.map +1 -0
  964. package/dist/runtime/history-relation.js +44 -0
  965. package/dist/runtime/history-relation.js.map +1 -0
  966. package/dist/runtime/in-process-transport.d.ts +18 -0
  967. package/dist/runtime/in-process-transport.d.ts.map +1 -0
  968. package/dist/runtime/in-process-transport.js +32 -0
  969. package/dist/runtime/in-process-transport.js.map +1 -0
  970. package/dist/runtime/index.d.ts +22 -13
  971. package/dist/runtime/index.d.ts.map +1 -1
  972. package/dist/runtime/index.js +14 -12
  973. package/dist/runtime/index.js.map +1 -1
  974. package/dist/runtime/indexeddb-page-store.d.ts +214 -0
  975. package/dist/runtime/indexeddb-page-store.d.ts.map +1 -0
  976. package/dist/runtime/indexeddb-page-store.js +848 -0
  977. package/dist/runtime/indexeddb-page-store.js.map +1 -0
  978. package/dist/runtime/introspection-fetch.d.ts +18 -0
  979. package/dist/runtime/introspection-fetch.d.ts.map +1 -0
  980. package/dist/runtime/introspection-fetch.js +12 -0
  981. package/dist/runtime/introspection-fetch.js.map +1 -0
  982. package/dist/runtime/json-schema-evaluate.d.ts +55 -0
  983. package/dist/runtime/json-schema-evaluate.d.ts.map +1 -0
  984. package/dist/runtime/json-schema-evaluate.js +946 -0
  985. package/dist/runtime/json-schema-evaluate.js.map +1 -0
  986. package/dist/runtime/json-schema-formats.d.ts +14 -0
  987. package/dist/runtime/json-schema-formats.d.ts.map +1 -0
  988. package/dist/runtime/json-schema-formats.js +555 -0
  989. package/dist/runtime/json-schema-formats.js.map +1 -0
  990. package/dist/runtime/json-schema-json.d.ts +41 -0
  991. package/dist/runtime/json-schema-json.d.ts.map +1 -0
  992. package/dist/runtime/json-schema-json.js +309 -0
  993. package/dist/runtime/json-schema-json.js.map +1 -0
  994. package/dist/runtime/json-schema-metaschemas.d.ts +1403 -0
  995. package/dist/runtime/json-schema-metaschemas.d.ts.map +1 -0
  996. package/dist/runtime/json-schema-metaschemas.js +64 -0
  997. package/dist/runtime/json-schema-metaschemas.js.map +1 -0
  998. package/dist/runtime/json-schema-regex.d.ts +32 -0
  999. package/dist/runtime/json-schema-regex.d.ts.map +1 -0
  1000. package/dist/runtime/json-schema-regex.js +895 -0
  1001. package/dist/runtime/json-schema-regex.js.map +1 -0
  1002. package/dist/runtime/json-schema-validator.d.ts +50 -0
  1003. package/dist/runtime/json-schema-validator.d.ts.map +1 -0
  1004. package/dist/runtime/json-schema-validator.js +404 -0
  1005. package/dist/runtime/json-schema-validator.js.map +1 -0
  1006. package/dist/runtime/json-text.js.map +1 -1
  1007. package/dist/runtime/local-first-token.d.ts +11 -0
  1008. package/dist/runtime/local-first-token.d.ts.map +1 -0
  1009. package/dist/runtime/local-first-token.js +20 -0
  1010. package/dist/runtime/local-first-token.js.map +1 -0
  1011. package/dist/runtime/local-first-unavailable.d.ts +40 -0
  1012. package/dist/runtime/local-first-unavailable.d.ts.map +1 -0
  1013. package/dist/runtime/local-first-unavailable.js +81 -0
  1014. package/dist/runtime/local-first-unavailable.js.map +1 -0
  1015. package/dist/runtime/local-first-upgrade.d.ts +36 -0
  1016. package/dist/runtime/local-first-upgrade.d.ts.map +1 -0
  1017. package/dist/runtime/local-first-upgrade.js +31 -0
  1018. package/dist/runtime/local-first-upgrade.js.map +1 -0
  1019. package/dist/runtime/local-write-observer.d.ts +5 -0
  1020. package/dist/runtime/local-write-observer.d.ts.map +1 -0
  1021. package/dist/runtime/local-write-observer.js +31 -0
  1022. package/dist/runtime/local-write-observer.js.map +1 -0
  1023. package/dist/runtime/metro-setup-error.d.ts +20 -0
  1024. package/dist/runtime/metro-setup-error.d.ts.map +1 -0
  1025. package/dist/runtime/metro-setup-error.js +22 -0
  1026. package/dist/runtime/metro-setup-error.js.map +1 -0
  1027. package/dist/runtime/native-artifact-compatibility.d.ts +12 -0
  1028. package/dist/runtime/native-artifact-compatibility.d.ts.map +1 -0
  1029. package/dist/runtime/native-artifact-compatibility.js +26 -0
  1030. package/dist/runtime/native-artifact-compatibility.js.map +1 -0
  1031. package/dist/runtime/native-artifact-fingerprint-napi.d.ts +2 -0
  1032. package/dist/runtime/native-artifact-fingerprint-napi.d.ts.map +1 -0
  1033. package/dist/runtime/native-artifact-fingerprint-napi.js +3 -0
  1034. package/dist/runtime/native-artifact-fingerprint-napi.js.map +1 -0
  1035. package/dist/runtime/native-artifact-fingerprint-wasm.d.ts +2 -0
  1036. package/dist/runtime/native-artifact-fingerprint-wasm.d.ts.map +1 -0
  1037. package/dist/runtime/native-artifact-fingerprint-wasm.js +3 -0
  1038. package/dist/runtime/native-artifact-fingerprint-wasm.js.map +1 -0
  1039. package/dist/runtime/native-artifact-fingerprints.d.ts +5 -0
  1040. package/dist/runtime/native-artifact-fingerprints.d.ts.map +1 -0
  1041. package/dist/runtime/native-artifact-fingerprints.js +7 -0
  1042. package/dist/runtime/native-artifact-fingerprints.js.map +1 -0
  1043. package/dist/runtime/native-artifact-mismatch-error.d.ts +25 -0
  1044. package/dist/runtime/native-artifact-mismatch-error.d.ts.map +1 -0
  1045. package/dist/runtime/native-artifact-mismatch-error.js +34 -0
  1046. package/dist/runtime/native-artifact-mismatch-error.js.map +1 -0
  1047. package/dist/runtime/native-runtime/attached-browser-worker-connection.d.ts +23 -0
  1048. package/dist/runtime/native-runtime/attached-browser-worker-connection.d.ts.map +1 -0
  1049. package/dist/runtime/native-runtime/attached-browser-worker-connection.js +45 -0
  1050. package/dist/runtime/native-runtime/attached-browser-worker-connection.js.map +1 -0
  1051. package/dist/runtime/native-runtime/auxiliary-receive-deadline.d.ts +15 -0
  1052. package/dist/runtime/native-runtime/auxiliary-receive-deadline.d.ts.map +1 -0
  1053. package/dist/runtime/native-runtime/auxiliary-receive-deadline.js +64 -0
  1054. package/dist/runtime/native-runtime/auxiliary-receive-deadline.js.map +1 -0
  1055. package/dist/runtime/native-runtime/broker-worker-load-failure.d.ts +34 -0
  1056. package/dist/runtime/native-runtime/broker-worker-load-failure.d.ts.map +1 -0
  1057. package/dist/runtime/native-runtime/broker-worker-load-failure.js +61 -0
  1058. package/dist/runtime/native-runtime/broker-worker-load-failure.js.map +1 -0
  1059. package/dist/runtime/native-runtime/browser-follower-connection.d.ts +109 -0
  1060. package/dist/runtime/native-runtime/browser-follower-connection.d.ts.map +1 -0
  1061. package/dist/runtime/native-runtime/browser-follower-connection.js +558 -0
  1062. package/dist/runtime/native-runtime/browser-follower-connection.js.map +1 -0
  1063. package/dist/runtime/native-runtime/browser-shared-worker-connection.d.ts +130 -0
  1064. package/dist/runtime/native-runtime/browser-shared-worker-connection.d.ts.map +1 -0
  1065. package/dist/runtime/native-runtime/browser-shared-worker-connection.js +988 -0
  1066. package/dist/runtime/native-runtime/browser-shared-worker-connection.js.map +1 -0
  1067. package/dist/runtime/native-runtime/browser-worker-protocol.d.ts +527 -0
  1068. package/dist/runtime/native-runtime/browser-worker-protocol.d.ts.map +1 -0
  1069. package/dist/runtime/native-runtime/browser-worker-protocol.js +296 -0
  1070. package/dist/runtime/native-runtime/browser-worker-protocol.js.map +1 -0
  1071. package/dist/runtime/native-runtime/browser-worker-transport.d.ts +56 -0
  1072. package/dist/runtime/native-runtime/browser-worker-transport.d.ts.map +1 -0
  1073. package/dist/runtime/native-runtime/browser-worker-transport.js +305 -0
  1074. package/dist/runtime/native-runtime/browser-worker-transport.js.map +1 -0
  1075. package/dist/runtime/native-runtime/exact-integer.d.ts +7 -0
  1076. package/dist/runtime/native-runtime/exact-integer.d.ts.map +1 -0
  1077. package/dist/runtime/native-runtime/exact-integer.js +18 -0
  1078. package/dist/runtime/native-runtime/exact-integer.js.map +1 -0
  1079. package/dist/runtime/native-runtime/http-stream-socket.d.ts +103 -0
  1080. package/dist/runtime/native-runtime/http-stream-socket.d.ts.map +1 -0
  1081. package/dist/runtime/native-runtime/http-stream-socket.js +554 -0
  1082. package/dist/runtime/native-runtime/http-stream-socket.js.map +1 -0
  1083. package/dist/runtime/native-runtime/inspector-control-lifecycle.d.ts +4 -0
  1084. package/dist/runtime/native-runtime/inspector-control-lifecycle.d.ts.map +1 -0
  1085. package/dist/runtime/native-runtime/inspector-control-lifecycle.js +33 -0
  1086. package/dist/runtime/native-runtime/inspector-control-lifecycle.js.map +1 -0
  1087. package/dist/runtime/native-runtime/native-codec.d.ts +172 -0
  1088. package/dist/runtime/native-runtime/native-codec.d.ts.map +1 -0
  1089. package/dist/runtime/native-runtime/native-codec.js +629 -0
  1090. package/dist/runtime/native-runtime/native-codec.js.map +1 -0
  1091. package/dist/runtime/native-runtime/native-error-code.d.ts +39 -0
  1092. package/dist/runtime/native-runtime/native-error-code.d.ts.map +1 -0
  1093. package/dist/runtime/native-runtime/native-error-code.js +64 -0
  1094. package/dist/runtime/native-runtime/native-error-code.js.map +1 -0
  1095. package/dist/runtime/native-runtime/native-row-codec.d.ts +161 -0
  1096. package/dist/runtime/native-runtime/native-row-codec.d.ts.map +1 -0
  1097. package/dist/runtime/native-runtime/native-row-codec.js +903 -0
  1098. package/dist/runtime/native-runtime/native-row-codec.js.map +1 -0
  1099. package/dist/runtime/native-runtime/native-row-descriptor-key.d.ts +15 -0
  1100. package/dist/runtime/native-runtime/native-row-descriptor-key.d.ts.map +1 -0
  1101. package/dist/runtime/native-runtime/native-row-descriptor-key.js +25 -0
  1102. package/dist/runtime/native-runtime/native-row-descriptor-key.js.map +1 -0
  1103. package/dist/runtime/native-runtime/native-runtime-adapter.d.ts +913 -0
  1104. package/dist/runtime/native-runtime/native-runtime-adapter.d.ts.map +1 -0
  1105. package/dist/runtime/native-runtime/native-runtime-adapter.js +5999 -0
  1106. package/dist/runtime/native-runtime/native-runtime-adapter.js.map +1 -0
  1107. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.d.ts +17 -0
  1108. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.d.ts.map +1 -0
  1109. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.js +4 -0
  1110. package/dist/runtime/native-runtime/node-foreground-node-lease.browser.js.map +1 -0
  1111. package/dist/runtime/native-runtime/node-foreground-node-lease.d.ts +19 -0
  1112. package/dist/runtime/native-runtime/node-foreground-node-lease.d.ts.map +1 -0
  1113. package/dist/runtime/native-runtime/node-foreground-node-lease.js +297 -0
  1114. package/dist/runtime/native-runtime/node-foreground-node-lease.js.map +1 -0
  1115. package/dist/runtime/native-runtime/row-values-transport.d.ts +2 -0
  1116. package/dist/runtime/native-runtime/row-values-transport.d.ts.map +1 -0
  1117. package/dist/runtime/native-runtime/row-values-transport.js +21 -0
  1118. package/dist/runtime/native-runtime/row-values-transport.js.map +1 -0
  1119. package/dist/runtime/native-runtime/schema-codec.d.ts +10 -0
  1120. package/dist/runtime/native-runtime/schema-codec.d.ts.map +1 -0
  1121. package/dist/runtime/native-runtime/schema-codec.js +13 -0
  1122. package/dist/runtime/native-runtime/schema-codec.js.map +1 -0
  1123. package/dist/runtime/native-runtime/session-renewal-wire.d.ts +48 -0
  1124. package/dist/runtime/native-runtime/session-renewal-wire.d.ts.map +1 -0
  1125. package/dist/runtime/native-runtime/session-renewal-wire.js +107 -0
  1126. package/dist/runtime/native-runtime/session-renewal-wire.js.map +1 -0
  1127. package/dist/runtime/native-runtime/stream-endpoint-memory.d.ts +34 -0
  1128. package/dist/runtime/native-runtime/stream-endpoint-memory.d.ts.map +1 -0
  1129. package/dist/runtime/native-runtime/stream-endpoint-memory.js +146 -0
  1130. package/dist/runtime/native-runtime/stream-endpoint-memory.js.map +1 -0
  1131. package/dist/runtime/native-runtime/websocket.d.ts +327 -0
  1132. package/dist/runtime/native-runtime/websocket.d.ts.map +1 -0
  1133. package/dist/runtime/native-runtime/websocket.js +1112 -0
  1134. package/dist/runtime/native-runtime/websocket.js.map +1 -0
  1135. package/dist/runtime/newer-build-reload.d.ts +30 -0
  1136. package/dist/runtime/newer-build-reload.d.ts.map +1 -0
  1137. package/dist/runtime/newer-build-reload.js +59 -0
  1138. package/dist/runtime/newer-build-reload.js.map +1 -0
  1139. package/dist/runtime/page-cache.d.ts +44 -0
  1140. package/dist/runtime/page-cache.d.ts.map +1 -0
  1141. package/dist/runtime/page-cache.js +104 -0
  1142. package/dist/runtime/page-cache.js.map +1 -0
  1143. package/dist/runtime/page-handle.d.ts +83 -0
  1144. package/dist/runtime/page-handle.d.ts.map +1 -0
  1145. package/dist/runtime/page-handle.js +151 -0
  1146. package/dist/runtime/page-handle.js.map +1 -0
  1147. package/dist/runtime/passkey-backup.d.ts +3 -0
  1148. package/dist/runtime/passkey-backup.d.ts.map +1 -0
  1149. package/dist/runtime/passkey-backup.js +2 -0
  1150. package/dist/runtime/passkey-backup.js.map +1 -0
  1151. package/dist/runtime/platform-url.d.ts +10 -0
  1152. package/dist/runtime/platform-url.d.ts.map +1 -0
  1153. package/dist/runtime/platform-url.js +3 -0
  1154. package/dist/runtime/platform-url.js.map +1 -0
  1155. package/dist/runtime/platform-url.native.d.ts +6 -0
  1156. package/dist/runtime/platform-url.native.d.ts.map +1 -0
  1157. package/dist/runtime/platform-url.native.js +38 -0
  1158. package/dist/runtime/platform-url.native.js.map +1 -0
  1159. package/dist/runtime/query-adapter.d.ts +7 -15
  1160. package/dist/runtime/query-adapter.d.ts.map +1 -1
  1161. package/dist/runtime/query-adapter.js +390 -110
  1162. package/dist/runtime/query-adapter.js.map +1 -1
  1163. package/dist/runtime/query-builder-shape.d.ts +75 -0
  1164. package/dist/runtime/query-builder-shape.d.ts.map +1 -0
  1165. package/dist/runtime/query-builder-shape.js +225 -0
  1166. package/dist/runtime/query-builder-shape.js.map +1 -0
  1167. package/dist/runtime/query-column-name.d.ts +3 -0
  1168. package/dist/runtime/query-column-name.d.ts.map +1 -0
  1169. package/dist/runtime/query-column-name.js +10 -0
  1170. package/dist/runtime/query-column-name.js.map +1 -0
  1171. package/dist/runtime/query-output-table.d.ts +5 -0
  1172. package/dist/runtime/query-output-table.d.ts.map +1 -0
  1173. package/dist/runtime/query-output-table.js +30 -0
  1174. package/dist/runtime/query-output-table.js.map +1 -0
  1175. package/dist/runtime/recovery-phrase.d.ts +3 -0
  1176. package/dist/runtime/recovery-phrase.d.ts.map +1 -0
  1177. package/dist/runtime/recovery-phrase.js +2 -0
  1178. package/dist/runtime/recovery-phrase.js.map +1 -0
  1179. package/dist/runtime/remote-link-state.d.ts +20 -0
  1180. package/dist/runtime/remote-link-state.d.ts.map +1 -0
  1181. package/dist/runtime/remote-link-state.js +5 -0
  1182. package/dist/runtime/remote-link-state.js.map +1 -0
  1183. package/dist/runtime/removed-provider-props.d.ts +17 -0
  1184. package/dist/runtime/removed-provider-props.d.ts.map +1 -0
  1185. package/dist/runtime/removed-provider-props.js +16 -0
  1186. package/dist/runtime/removed-provider-props.js.map +1 -0
  1187. package/dist/runtime/row-transformer.d.ts +17 -3
  1188. package/dist/runtime/row-transformer.d.ts.map +1 -1
  1189. package/dist/runtime/row-transformer.js +163 -38
  1190. package/dist/runtime/row-transformer.js.map +1 -1
  1191. package/dist/runtime/run-cleanup-steps.d.ts +5 -0
  1192. package/dist/runtime/run-cleanup-steps.d.ts.map +1 -0
  1193. package/dist/runtime/run-cleanup-steps.js +19 -0
  1194. package/dist/runtime/run-cleanup-steps.js.map +1 -0
  1195. package/dist/runtime/runtime-closed-error.d.ts +9 -0
  1196. package/dist/runtime/runtime-closed-error.d.ts.map +1 -0
  1197. package/dist/runtime/runtime-closed-error.js +12 -0
  1198. package/dist/runtime/runtime-closed-error.js.map +1 -0
  1199. package/dist/runtime/runtime-config.d.ts +13 -0
  1200. package/dist/runtime/runtime-config.d.ts.map +1 -0
  1201. package/dist/runtime/runtime-config.js +115 -0
  1202. package/dist/runtime/runtime-config.js.map +1 -0
  1203. package/dist/runtime/runtime-entropy.d.ts +14 -0
  1204. package/dist/runtime/runtime-entropy.d.ts.map +1 -0
  1205. package/dist/runtime/runtime-entropy.js +43 -0
  1206. package/dist/runtime/runtime-entropy.js.map +1 -0
  1207. package/dist/runtime/runtime-source.d.ts +206 -0
  1208. package/dist/runtime/runtime-source.d.ts.map +1 -0
  1209. package/dist/runtime/runtime-source.js +64 -0
  1210. package/dist/runtime/runtime-source.js.map +1 -0
  1211. package/dist/runtime/schema-metadata.d.ts +22 -0
  1212. package/dist/runtime/schema-metadata.d.ts.map +1 -0
  1213. package/dist/runtime/schema-metadata.js +70 -0
  1214. package/dist/runtime/schema-metadata.js.map +1 -0
  1215. package/dist/runtime/select-projection.d.ts +5 -0
  1216. package/dist/runtime/select-projection.d.ts.map +1 -0
  1217. package/dist/runtime/select-projection.js +47 -0
  1218. package/dist/runtime/select-projection.js.map +1 -0
  1219. package/dist/runtime/snapshot-ref.d.ts +24 -0
  1220. package/dist/runtime/snapshot-ref.d.ts.map +1 -0
  1221. package/dist/runtime/snapshot-ref.js +43 -0
  1222. package/dist/runtime/snapshot-ref.js.map +1 -0
  1223. package/dist/runtime/store-held-by-another-tab-error.d.ts +53 -0
  1224. package/dist/runtime/store-held-by-another-tab-error.d.ts.map +1 -0
  1225. package/dist/runtime/store-held-by-another-tab-error.js +55 -0
  1226. package/dist/runtime/store-held-by-another-tab-error.js.map +1 -0
  1227. package/dist/runtime/streaming-source.d.ts +4 -0
  1228. package/dist/runtime/streaming-source.d.ts.map +1 -0
  1229. package/dist/runtime/streaming-source.js +53 -0
  1230. package/dist/runtime/streaming-source.js.map +1 -0
  1231. package/dist/runtime/structural-values.d.ts +6 -0
  1232. package/dist/runtime/structural-values.d.ts.map +1 -0
  1233. package/dist/runtime/structural-values.js +51 -0
  1234. package/dist/runtime/structural-values.js.map +1 -0
  1235. package/dist/runtime/subscription-manager.d.ts +103 -14
  1236. package/dist/runtime/subscription-manager.d.ts.map +1 -1
  1237. package/dist/runtime/subscription-manager.js +1051 -25
  1238. package/dist/runtime/subscription-manager.js.map +1 -1
  1239. package/dist/runtime/sync-status.d.ts +178 -0
  1240. package/dist/runtime/sync-status.d.ts.map +1 -0
  1241. package/dist/runtime/sync-status.js +163 -0
  1242. package/dist/runtime/sync-status.js.map +1 -0
  1243. package/dist/runtime/sync-telemetry.d.ts +35 -0
  1244. package/dist/runtime/sync-telemetry.d.ts.map +1 -0
  1245. package/dist/runtime/sync-telemetry.js +354 -0
  1246. package/dist/runtime/sync-telemetry.js.map +1 -0
  1247. package/dist/runtime/system-identity.d.ts +5 -0
  1248. package/dist/runtime/system-identity.d.ts.map +1 -0
  1249. package/dist/runtime/system-identity.js +10 -0
  1250. package/dist/runtime/system-identity.js.map +1 -0
  1251. package/dist/runtime/telemetry-env.d.ts +2 -0
  1252. package/dist/runtime/telemetry-env.d.ts.map +1 -0
  1253. package/dist/runtime/telemetry-env.js +16 -0
  1254. package/dist/runtime/telemetry-env.js.map +1 -0
  1255. package/dist/runtime/telemetry-env.native.d.ts +3 -0
  1256. package/dist/runtime/telemetry-env.native.d.ts.map +1 -0
  1257. package/dist/runtime/telemetry-env.native.js +7 -0
  1258. package/dist/runtime/telemetry-env.native.js.map +1 -0
  1259. package/dist/runtime/text-anchors.d.ts +58 -0
  1260. package/dist/runtime/text-anchors.d.ts.map +1 -0
  1261. package/dist/runtime/text-anchors.js +9 -0
  1262. package/dist/runtime/text-anchors.js.map +1 -0
  1263. package/dist/runtime/unsupported-storage-codecs-error.d.ts +53 -0
  1264. package/dist/runtime/unsupported-storage-codecs-error.d.ts.map +1 -0
  1265. package/dist/runtime/unsupported-storage-codecs-error.js +74 -0
  1266. package/dist/runtime/unsupported-storage-codecs-error.js.map +1 -0
  1267. package/dist/runtime/url.d.ts +32 -0
  1268. package/dist/runtime/url.d.ts.map +1 -0
  1269. package/dist/runtime/url.js +96 -0
  1270. package/dist/runtime/url.js.map +1 -0
  1271. package/dist/runtime/utf8.d.ts +10 -0
  1272. package/dist/runtime/utf8.d.ts.map +1 -0
  1273. package/dist/runtime/utf8.js +93 -0
  1274. package/dist/runtime/utf8.js.map +1 -0
  1275. package/dist/runtime/util.d.ts +18 -0
  1276. package/dist/runtime/util.d.ts.map +1 -0
  1277. package/dist/runtime/util.js +59 -0
  1278. package/dist/runtime/util.js.map +1 -0
  1279. package/dist/runtime/value-converter.d.ts +9 -17
  1280. package/dist/runtime/value-converter.d.ts.map +1 -1
  1281. package/dist/runtime/value-converter.js +156 -42
  1282. package/dist/runtime/value-converter.js.map +1 -1
  1283. package/dist/runtime/wasm-loader.d.ts +6 -0
  1284. package/dist/runtime/wasm-loader.d.ts.map +1 -0
  1285. package/dist/runtime/wasm-loader.js +127 -0
  1286. package/dist/runtime/wasm-loader.js.map +1 -0
  1287. package/dist/runtime/write-preparation.d.ts +24 -0
  1288. package/dist/runtime/write-preparation.d.ts.map +1 -0
  1289. package/dist/runtime/write-preparation.js +63 -0
  1290. package/dist/runtime/write-preparation.js.map +1 -0
  1291. package/dist/runtime/write-row.d.ts +8 -0
  1292. package/dist/runtime/write-row.d.ts.map +1 -0
  1293. package/dist/runtime/write-row.js +17 -0
  1294. package/dist/runtime/write-row.js.map +1 -0
  1295. package/dist/schema-builders.d.ts +48 -0
  1296. package/dist/schema-builders.d.ts.map +1 -0
  1297. package/dist/schema-builders.js +26 -0
  1298. package/dist/schema-builders.js.map +1 -0
  1299. package/dist/schema-dsl/define-schema.d.ts +32 -0
  1300. package/dist/schema-dsl/define-schema.d.ts.map +1 -0
  1301. package/dist/schema-dsl/define-schema.js +80 -0
  1302. package/dist/schema-dsl/define-schema.js.map +1 -0
  1303. package/dist/schema-dsl/readable-app.d.ts +30 -0
  1304. package/dist/schema-dsl/readable-app.d.ts.map +1 -0
  1305. package/dist/schema-dsl/readable-app.js +139 -0
  1306. package/dist/schema-dsl/readable-app.js.map +1 -0
  1307. package/dist/schema-dsl/table.d.ts +101 -0
  1308. package/dist/schema-dsl/table.d.ts.map +1 -0
  1309. package/dist/schema-dsl/table.js +153 -0
  1310. package/dist/schema-dsl/table.js.map +1 -0
  1311. package/dist/schema-errors.d.ts +6 -0
  1312. package/dist/schema-errors.d.ts.map +1 -0
  1313. package/dist/schema-errors.js +6 -0
  1314. package/dist/schema-errors.js.map +1 -0
  1315. package/dist/schema-loader.d.ts +16 -0
  1316. package/dist/schema-loader.d.ts.map +1 -0
  1317. package/dist/schema-loader.js +108 -0
  1318. package/dist/schema-loader.js.map +1 -0
  1319. package/dist/schema-name.d.ts +2 -0
  1320. package/dist/schema-name.d.ts.map +1 -0
  1321. package/dist/schema-name.js +19 -0
  1322. package/dist/schema-name.js.map +1 -0
  1323. package/dist/schema-namespace.d.ts +7 -0
  1324. package/dist/schema-namespace.d.ts.map +1 -0
  1325. package/dist/schema-namespace.js +7 -0
  1326. package/dist/schema-namespace.js.map +1 -0
  1327. package/dist/schema-permissions.d.ts +12 -0
  1328. package/dist/schema-permissions.d.ts.map +1 -0
  1329. package/dist/schema-permissions.js +17 -0
  1330. package/dist/schema-permissions.js.map +1 -0
  1331. package/dist/schema-source.d.ts +11 -0
  1332. package/dist/schema-source.d.ts.map +1 -0
  1333. package/dist/schema-source.js +53 -0
  1334. package/dist/schema-source.js.map +1 -0
  1335. package/dist/schema.d.ts +95 -38
  1336. package/dist/schema.d.ts.map +1 -1
  1337. package/dist/schema.js +1 -16
  1338. package/dist/schema.js.map +1 -1
  1339. package/dist/session/backend-watch.d.ts +186 -0
  1340. package/dist/session/backend-watch.d.ts.map +1 -0
  1341. package/dist/session/backend-watch.js +698 -0
  1342. package/dist/session/backend-watch.js.map +1 -0
  1343. package/dist/session/config-options.d.ts +15 -0
  1344. package/dist/session/config-options.d.ts.map +1 -0
  1345. package/dist/session/config-options.js +55 -0
  1346. package/dist/session/config-options.js.map +1 -0
  1347. package/dist/session/consumer.d.ts +3 -0
  1348. package/dist/session/consumer.d.ts.map +1 -0
  1349. package/dist/session/consumer.js +3 -0
  1350. package/dist/session/consumer.js.map +1 -0
  1351. package/dist/session/create-jazz-session.d.ts +123 -0
  1352. package/dist/session/create-jazz-session.d.ts.map +1 -0
  1353. package/dist/session/create-jazz-session.js +542 -0
  1354. package/dist/session/create-jazz-session.js.map +1 -0
  1355. package/dist/session/follow-user.d.ts +72 -0
  1356. package/dist/session/follow-user.d.ts.map +1 -0
  1357. package/dist/session/follow-user.js +147 -0
  1358. package/dist/session/follow-user.js.map +1 -0
  1359. package/dist/session/jazz-session.d.ts +234 -0
  1360. package/dist/session/jazz-session.d.ts.map +1 -0
  1361. package/dist/session/jazz-session.js +528 -0
  1362. package/dist/session/jazz-session.js.map +1 -0
  1363. package/dist/session/native-backend-watch.d.ts +4 -0
  1364. package/dist/session/native-backend-watch.d.ts.map +1 -0
  1365. package/dist/session/native-backend-watch.js +14 -0
  1366. package/dist/session/native-backend-watch.js.map +1 -0
  1367. package/dist/session/no-kept-device-account-error.d.ts +6 -0
  1368. package/dist/session/no-kept-device-account-error.d.ts.map +1 -0
  1369. package/dist/session/no-kept-device-account-error.js +8 -0
  1370. package/dist/session/no-kept-device-account-error.js.map +1 -0
  1371. package/dist/session/replica-ledger.d.ts +164 -0
  1372. package/dist/session/replica-ledger.d.ts.map +1 -0
  1373. package/dist/session/replica-ledger.js +496 -0
  1374. package/dist/session/replica-ledger.js.map +1 -0
  1375. package/dist/session/state.d.ts +135 -0
  1376. package/dist/session/state.d.ts.map +1 -0
  1377. package/dist/session/state.js +535 -0
  1378. package/dist/session/state.js.map +1 -0
  1379. package/dist/shared/index.d.ts +20 -0
  1380. package/dist/shared/index.d.ts.map +1 -0
  1381. package/dist/shared/index.js +17 -0
  1382. package/dist/shared/index.js.map +1 -0
  1383. package/dist/solid/create-solid-jazz-client-internal.d.ts +13 -0
  1384. package/dist/solid/create-solid-jazz-client-internal.d.ts.map +1 -0
  1385. package/dist/solid/create-solid-jazz-client-internal.js +82 -0
  1386. package/dist/solid/create-solid-jazz-client-internal.js.map +1 -0
  1387. package/dist/solid/create-solid-jazz-client-internal.ssr.js +101 -0
  1388. package/dist/solid/create-solid-jazz-client-internal.ssr.js.map +1 -0
  1389. package/dist/solid/create-solid-jazz-client.d.ts +24 -0
  1390. package/dist/solid/create-solid-jazz-client.d.ts.map +1 -0
  1391. package/dist/solid/create-solid-jazz-client.js +42 -0
  1392. package/dist/solid/create-solid-jazz-client.js.map +1 -0
  1393. package/dist/solid/create-solid-jazz-client.ssr.js +45 -0
  1394. package/dist/solid/create-solid-jazz-client.ssr.js.map +1 -0
  1395. package/dist/solid/index.d.ts +13 -0
  1396. package/dist/solid/index.d.ts.map +1 -0
  1397. package/dist/solid/index.js +9 -0
  1398. package/dist/solid/index.ssr.js +9 -0
  1399. package/dist/solid/provider.d.ts +25 -0
  1400. package/dist/solid/provider.d.ts.map +1 -0
  1401. package/dist/solid/provider.js +48 -0
  1402. package/dist/solid/provider.js.map +1 -0
  1403. package/dist/solid/provider.ssr.js +48 -0
  1404. package/dist/solid/provider.ssr.js.map +1 -0
  1405. package/dist/solid/session-context.d.ts +14 -0
  1406. package/dist/solid/session-context.d.ts.map +1 -0
  1407. package/dist/solid/session-context.js +6 -0
  1408. package/dist/solid/session-context.js.map +1 -0
  1409. package/dist/solid/session-context.ssr.js +10 -0
  1410. package/dist/solid/session-context.ssr.js.map +1 -0
  1411. package/dist/solid/session.d.ts +55 -0
  1412. package/dist/solid/session.d.ts.map +1 -0
  1413. package/dist/solid/session.js +130 -0
  1414. package/dist/solid/session.js.map +1 -0
  1415. package/dist/solid/session.ssr.js +156 -0
  1416. package/dist/solid/session.ssr.js.map +1 -0
  1417. package/dist/solid/solid-jazz-client-store.d.ts +11 -0
  1418. package/dist/solid/solid-jazz-client-store.d.ts.map +1 -0
  1419. package/dist/solid/solid-jazz-client-store.js +38 -0
  1420. package/dist/solid/solid-jazz-client-store.js.map +1 -0
  1421. package/dist/solid/solid-jazz-client-store.ssr.js +39 -0
  1422. package/dist/solid/solid-jazz-client-store.ssr.js.map +1 -0
  1423. package/dist/solid/use-all.d.ts +18 -0
  1424. package/dist/solid/use-all.d.ts.map +1 -0
  1425. package/dist/solid/use-all.js +71 -0
  1426. package/dist/solid/use-all.js.map +1 -0
  1427. package/dist/solid/use-all.ssr.js +84 -0
  1428. package/dist/solid/use-all.ssr.js.map +1 -0
  1429. package/dist/solid/use-one.d.ts +18 -0
  1430. package/dist/solid/use-one.d.ts.map +1 -0
  1431. package/dist/solid/use-one.js +27 -0
  1432. package/dist/solid/use-one.js.map +1 -0
  1433. package/dist/solid/use-one.ssr.js +27 -0
  1434. package/dist/solid/use-one.ssr.js.map +1 -0
  1435. package/dist/solid/use-sync-status.d.ts +8 -0
  1436. package/dist/solid/use-sync-status.d.ts.map +1 -0
  1437. package/dist/solid/use-sync-status.js +13 -0
  1438. package/dist/solid/use-sync-status.js.map +1 -0
  1439. package/dist/solid/use-sync-status.ssr.js +20 -0
  1440. package/dist/solid/use-sync-status.ssr.js.map +1 -0
  1441. package/dist/subscription-store-internal.d.ts +11 -0
  1442. package/dist/subscription-store-internal.d.ts.map +1 -0
  1443. package/dist/subscription-store-internal.js +18 -0
  1444. package/dist/subscription-store-internal.js.map +1 -0
  1445. package/dist/subscriptions-orchestrator.d.ts +92 -14
  1446. package/dist/subscriptions-orchestrator.d.ts.map +1 -1
  1447. package/dist/subscriptions-orchestrator.js +390 -75
  1448. package/dist/subscriptions-orchestrator.js.map +1 -1
  1449. package/dist/svelte/JazzProvider.svelte +110 -0
  1450. package/dist/svelte/JazzProvider.svelte.d.ts +24 -0
  1451. package/dist/svelte/JazzProvider.svelte.d.ts.map +1 -0
  1452. package/dist/svelte/JazzSvelteClientProvider.svelte +83 -0
  1453. package/dist/svelte/JazzSvelteClientProvider.svelte.d.ts +15 -0
  1454. package/dist/svelte/JazzSvelteClientProvider.svelte.d.ts.map +1 -0
  1455. package/dist/svelte/context.svelte.d.ts +19 -3
  1456. package/dist/svelte/context.svelte.d.ts.map +1 -1
  1457. package/dist/svelte/context.svelte.js +21 -5
  1458. package/dist/svelte/create-jazz-client.d.ts +2 -8
  1459. package/dist/svelte/create-jazz-client.d.ts.map +1 -1
  1460. package/dist/svelte/create-jazz-client.js +1 -17
  1461. package/dist/svelte/index.d.ts +14 -7
  1462. package/dist/svelte/index.d.ts.map +1 -1
  1463. package/dist/svelte/index.js +10 -7
  1464. package/dist/svelte/query-subscription.svelte.d.ts +60 -0
  1465. package/dist/svelte/query-subscription.svelte.d.ts.map +1 -0
  1466. package/dist/svelte/query-subscription.svelte.js +135 -0
  1467. package/dist/svelte/session-state.d.ts +27 -0
  1468. package/dist/svelte/session-state.d.ts.map +1 -0
  1469. package/dist/svelte/session-state.js +49 -0
  1470. package/dist/svelte/sync-status.d.ts +11 -0
  1471. package/dist/svelte/sync-status.d.ts.map +1 -0
  1472. package/dist/svelte/sync-status.js +15 -0
  1473. package/dist/testing/fixtures/with-bigint/schema.d.ts +18 -0
  1474. package/dist/testing/fixtures/with-bigint/schema.d.ts.map +1 -0
  1475. package/dist/testing/fixtures/with-bigint/schema.js +15 -0
  1476. package/dist/testing/fixtures/with-bigint/schema.js.map +1 -0
  1477. package/dist/testing/index.d.ts +6 -1
  1478. package/dist/testing/index.d.ts.map +1 -1
  1479. package/dist/testing/index.js +5 -1
  1480. package/dist/testing/index.js.map +1 -1
  1481. package/dist/testing/policy-test-app.d.ts +129 -0
  1482. package/dist/testing/policy-test-app.d.ts.map +1 -0
  1483. package/dist/testing/policy-test-app.js +229 -0
  1484. package/dist/testing/policy-test-app.js.map +1 -0
  1485. package/dist/testing/test-app.d.ts +272 -0
  1486. package/dist/testing/test-app.d.ts.map +1 -0
  1487. package/dist/testing/test-app.js +62 -0
  1488. package/dist/testing/test-app.js.map +1 -0
  1489. package/dist/testing/test-jazz.d.ts +119 -0
  1490. package/dist/testing/test-jazz.d.ts.map +1 -0
  1491. package/dist/testing/test-jazz.js +162 -0
  1492. package/dist/testing/test-jazz.js.map +1 -0
  1493. package/dist/testing/test-jwt-issuer.d.ts +19 -0
  1494. package/dist/testing/test-jwt-issuer.d.ts.map +1 -0
  1495. package/dist/testing/test-jwt-issuer.js +40 -0
  1496. package/dist/testing/test-jwt-issuer.js.map +1 -0
  1497. package/dist/text-field/index.d.ts +40 -0
  1498. package/dist/text-field/index.d.ts.map +1 -0
  1499. package/dist/text-field/index.js +129 -0
  1500. package/dist/text-field/index.js.map +1 -0
  1501. package/dist/thin/index.d.ts +80 -0
  1502. package/dist/thin/index.d.ts.map +1 -0
  1503. package/dist/thin/index.js +219 -0
  1504. package/dist/thin/index.js.map +1 -0
  1505. package/dist/thin/self-signed-token.d.ts +13 -0
  1506. package/dist/thin/self-signed-token.d.ts.map +1 -0
  1507. package/dist/thin/self-signed-token.js +100 -0
  1508. package/dist/thin/self-signed-token.js.map +1 -0
  1509. package/dist/thin/thin-runtime-source.d.ts +19 -0
  1510. package/dist/thin/thin-runtime-source.d.ts.map +1 -0
  1511. package/dist/thin/thin-runtime-source.js +66 -0
  1512. package/dist/thin/thin-runtime-source.js.map +1 -0
  1513. package/dist/thin/thin-runtime.d.ts +294 -0
  1514. package/dist/thin/thin-runtime.d.ts.map +1 -0
  1515. package/dist/thin/thin-runtime.js +1492 -0
  1516. package/dist/thin/thin-runtime.js.map +1 -0
  1517. package/dist/thin/wire.d.ts +160 -0
  1518. package/dist/thin/wire.d.ts.map +1 -0
  1519. package/dist/thin/wire.js +304 -0
  1520. package/dist/thin/wire.js.map +1 -0
  1521. package/dist/typed-app.d.ts +644 -0
  1522. package/dist/typed-app.d.ts.map +1 -0
  1523. package/dist/typed-app.js +549 -0
  1524. package/dist/typed-app.js.map +1 -0
  1525. package/dist/vue/create-jazz-client.d.ts +3 -0
  1526. package/dist/vue/create-jazz-client.d.ts.map +1 -0
  1527. package/dist/vue/create-jazz-client.js +2 -0
  1528. package/dist/vue/create-jazz-client.js.map +1 -0
  1529. package/dist/vue/index.d.ts +13 -0
  1530. package/dist/vue/index.d.ts.map +1 -0
  1531. package/dist/vue/index.js +9 -0
  1532. package/dist/vue/index.js.map +1 -0
  1533. package/dist/vue/provider.d.ts +50 -0
  1534. package/dist/vue/provider.d.ts.map +1 -0
  1535. package/dist/vue/provider.js +97 -0
  1536. package/dist/vue/provider.js.map +1 -0
  1537. package/dist/vue/session-key.d.ts +15 -0
  1538. package/dist/vue/session-key.d.ts.map +1 -0
  1539. package/dist/vue/session-key.js +7 -0
  1540. package/dist/vue/session-key.js.map +1 -0
  1541. package/dist/vue/session.d.ts +40 -0
  1542. package/dist/vue/session.d.ts.map +1 -0
  1543. package/dist/vue/session.js +112 -0
  1544. package/dist/vue/session.js.map +1 -0
  1545. package/dist/vue/use-all.d.ts +61 -0
  1546. package/dist/vue/use-all.d.ts.map +1 -0
  1547. package/dist/vue/use-all.js +104 -0
  1548. package/dist/vue/use-all.js.map +1 -0
  1549. package/dist/vue/use-one.d.ts +24 -0
  1550. package/dist/vue/use-one.d.ts.map +1 -0
  1551. package/dist/vue/use-one.js +17 -0
  1552. package/dist/vue/use-one.js.map +1 -0
  1553. package/dist/vue/use-sync-status.d.ts +9 -0
  1554. package/dist/vue/use-sync-status.d.ts.map +1 -0
  1555. package/dist/vue/use-sync-status.js +16 -0
  1556. package/dist/vue/use-sync-status.js.map +1 -0
  1557. package/dist/web/create-jazz-client.d.ts +12 -0
  1558. package/dist/web/create-jazz-client.d.ts.map +1 -0
  1559. package/dist/web/create-jazz-client.js +35 -0
  1560. package/dist/web/create-jazz-client.js.map +1 -0
  1561. package/dist/web/lazy-local-first.d.ts +5 -0
  1562. package/dist/web/lazy-local-first.d.ts.map +1 -0
  1563. package/dist/web/lazy-local-first.js +8 -0
  1564. package/dist/web/lazy-local-first.js.map +1 -0
  1565. package/dist/web/registered-jazz-client.d.ts +15 -0
  1566. package/dist/web/registered-jazz-client.d.ts.map +1 -0
  1567. package/dist/web/registered-jazz-client.js +35 -0
  1568. package/dist/web/registered-jazz-client.js.map +1 -0
  1569. package/dist/where-operators.d.ts +13 -0
  1570. package/dist/where-operators.d.ts.map +1 -0
  1571. package/dist/where-operators.js +66 -0
  1572. package/dist/where-operators.js.map +1 -0
  1573. package/dist/window-client-storage.d.ts +7 -0
  1574. package/dist/window-client-storage.d.ts.map +1 -0
  1575. package/dist/window-client-storage.js +27 -0
  1576. package/dist/window-client-storage.js.map +1 -0
  1577. package/dist/worker/jazz-broker-worker-core.d.ts +34 -0
  1578. package/dist/worker/jazz-broker-worker-core.d.ts.map +1 -0
  1579. package/dist/worker/jazz-broker-worker-core.js +2241 -0
  1580. package/dist/worker/jazz-broker-worker-core.js.map +1 -0
  1581. package/dist/worker/jazz-broker-worker.d.ts +3 -0
  1582. package/dist/worker/jazz-broker-worker.d.ts.map +1 -0
  1583. package/dist/worker/jazz-broker-worker.js +5 -0
  1584. package/dist/worker/jazz_wasm_bg.wasm +0 -0
  1585. package/dist/worker/mutation-error-delivery.d.ts +8 -0
  1586. package/dist/worker/mutation-error-delivery.d.ts.map +1 -0
  1587. package/dist/worker/mutation-error-delivery.js +10 -0
  1588. package/dist/worker/mutation-error-delivery.js.map +1 -0
  1589. package/dist/worker/runtime-admission.d.ts +34 -0
  1590. package/dist/worker/runtime-admission.d.ts.map +1 -0
  1591. package/dist/worker/runtime-admission.js +60 -0
  1592. package/dist/worker/runtime-admission.js.map +1 -0
  1593. package/dist/worker/vite-dev-broker.d.ts +2 -0
  1594. package/dist/worker/vite-dev-broker.d.ts.map +1 -0
  1595. package/dist/worker/vite-dev-broker.js +8 -0
  1596. package/dist/worker/vite-dev-broker.js.map +1 -0
  1597. package/package.json +299 -37
  1598. package/bin/native/.gitkeep +0 -0
  1599. package/bin/native/jazz-tools-darwin-arm64 +0 -0
  1600. package/bin/native/jazz-tools-darwin-x64 +0 -0
  1601. package/bin/native/jazz-tools-linux-arm64 +0 -0
  1602. package/bin/native/jazz-tools-linux-x64 +0 -0
  1603. package/bin/native/jazz-tools-windows-x64.exe +0 -0
  1604. package/dist/backend/create-jazz-context.test.d.ts +0 -2
  1605. package/dist/backend/create-jazz-context.test.d.ts.map +0 -1
  1606. package/dist/backend/create-jazz-context.test.js +0 -141
  1607. package/dist/backend/create-jazz-context.test.js.map +0 -1
  1608. package/dist/cli.test.d.ts +0 -2
  1609. package/dist/cli.test.d.ts.map +0 -1
  1610. package/dist/cli.test.js +0 -154
  1611. package/dist/cli.test.js.map +0 -1
  1612. package/dist/codegen/codegen.test.d.ts +0 -2
  1613. package/dist/codegen/codegen.test.d.ts.map +0 -1
  1614. package/dist/codegen/codegen.test.js +0 -914
  1615. package/dist/codegen/codegen.test.js.map +0 -1
  1616. package/dist/codegen/index.d.ts +0 -18
  1617. package/dist/codegen/index.d.ts.map +0 -1
  1618. package/dist/codegen/index.js +0 -22
  1619. package/dist/codegen/index.js.map +0 -1
  1620. package/dist/codegen/query-builder-generator.d.ts +0 -26
  1621. package/dist/codegen/query-builder-generator.d.ts.map +0 -1
  1622. package/dist/codegen/query-builder-generator.js +0 -342
  1623. package/dist/codegen/query-builder-generator.js.map +0 -1
  1624. package/dist/codegen/schema-reader.d.ts +0 -12
  1625. package/dist/codegen/schema-reader.d.ts.map +0 -1
  1626. package/dist/codegen/schema-reader.js +0 -180
  1627. package/dist/codegen/schema-reader.js.map +0 -1
  1628. package/dist/codegen/type-generator.d.ts +0 -29
  1629. package/dist/codegen/type-generator.d.ts.map +0 -1
  1630. package/dist/codegen/type-generator.js +0 -296
  1631. package/dist/codegen/type-generator.js.map +0 -1
  1632. package/dist/dev-tools/dev-tools.d.ts +0 -15
  1633. package/dist/dev-tools/dev-tools.d.ts.map +0 -1
  1634. package/dist/dev-tools/dev-tools.js +0 -297
  1635. package/dist/dev-tools/dev-tools.js.map +0 -1
  1636. package/dist/dev-tools/extension-panel.d.ts +0 -19
  1637. package/dist/dev-tools/extension-panel.d.ts.map +0 -1
  1638. package/dist/dev-tools/extension-panel.js +0 -419
  1639. package/dist/dev-tools/extension-panel.js.map +0 -1
  1640. package/dist/dev-tools/index.d.ts +0 -3
  1641. package/dist/dev-tools/index.d.ts.map +0 -1
  1642. package/dist/dev-tools/index.js +0 -3
  1643. package/dist/dev-tools/index.js.map +0 -1
  1644. package/dist/dev-tools/protocol.d.ts +0 -49
  1645. package/dist/dev-tools/protocol.d.ts.map +0 -1
  1646. package/dist/dev-tools/protocol.js +0 -40
  1647. package/dist/dev-tools/protocol.js.map +0 -1
  1648. package/dist/dsl.test.d.ts +0 -2
  1649. package/dist/dsl.test.d.ts.map +0 -1
  1650. package/dist/dsl.test.js +0 -51
  1651. package/dist/dsl.test.js.map +0 -1
  1652. package/dist/permissions/index.d.ts +0 -146
  1653. package/dist/permissions/index.d.ts.map +0 -1
  1654. package/dist/permissions/index.js +0 -1211
  1655. package/dist/permissions/index.js.map +0 -1
  1656. package/dist/permissions/index.test.d.ts +0 -2
  1657. package/dist/permissions/index.test.d.ts.map +0 -1
  1658. package/dist/permissions/index.test.js +0 -830
  1659. package/dist/permissions/index.test.js.map +0 -1
  1660. package/dist/permissions/type-inference.test.d.ts +0 -2
  1661. package/dist/permissions/type-inference.test.d.ts.map +0 -1
  1662. package/dist/permissions/type-inference.test.js +0 -149
  1663. package/dist/permissions/type-inference.test.js.map +0 -1
  1664. package/dist/react/create-jazz-client.integration.test.d.ts +0 -2
  1665. package/dist/react/create-jazz-client.integration.test.d.ts.map +0 -1
  1666. package/dist/react/create-jazz-client.integration.test.js +0 -82
  1667. package/dist/react/create-jazz-client.integration.test.js.map +0 -1
  1668. package/dist/react/create-jazz-client.test.d.ts +0 -2
  1669. package/dist/react/create-jazz-client.test.d.ts.map +0 -1
  1670. package/dist/react/create-jazz-client.test.js +0 -135
  1671. package/dist/react/create-jazz-client.test.js.map +0 -1
  1672. package/dist/react/synthetic-user-switcher.d.ts +0 -9
  1673. package/dist/react/synthetic-user-switcher.d.ts.map +0 -1
  1674. package/dist/react/synthetic-user-switcher.js +0 -65
  1675. package/dist/react/synthetic-user-switcher.js.map +0 -1
  1676. package/dist/react/synthetic-users.d.ts +0 -2
  1677. package/dist/react/synthetic-users.d.ts.map +0 -1
  1678. package/dist/react/synthetic-users.js +0 -2
  1679. package/dist/react/synthetic-users.js.map +0 -1
  1680. package/dist/react/synthetic-users.test.d.ts +0 -2
  1681. package/dist/react/synthetic-users.test.d.ts.map +0 -1
  1682. package/dist/react/synthetic-users.test.js +0 -43
  1683. package/dist/react/synthetic-users.test.js.map +0 -1
  1684. package/dist/react/use-link-external-identity.d.ts +0 -25
  1685. package/dist/react/use-link-external-identity.d.ts.map +0 -1
  1686. package/dist/react/use-link-external-identity.js +0 -45
  1687. package/dist/react/use-link-external-identity.js.map +0 -1
  1688. package/dist/react-native/create-jazz-client.test.d.ts +0 -2
  1689. package/dist/react-native/create-jazz-client.test.d.ts.map +0 -1
  1690. package/dist/react-native/create-jazz-client.test.js +0 -162
  1691. package/dist/react-native/create-jazz-client.test.js.map +0 -1
  1692. package/dist/react-native/create-jazz-rn-runtime.d.ts +0 -13
  1693. package/dist/react-native/create-jazz-rn-runtime.d.ts.map +0 -1
  1694. package/dist/react-native/create-jazz-rn-runtime.js +0 -7
  1695. package/dist/react-native/create-jazz-rn-runtime.js.map +0 -1
  1696. package/dist/react-native/db.d.ts +0 -16
  1697. package/dist/react-native/db.d.ts.map +0 -1
  1698. package/dist/react-native/db.js +0 -50
  1699. package/dist/react-native/db.js.map +0 -1
  1700. package/dist/react-native/db.test.d.ts +0 -2
  1701. package/dist/react-native/db.test.d.ts.map +0 -1
  1702. package/dist/react-native/db.test.js +0 -148
  1703. package/dist/react-native/db.test.js.map +0 -1
  1704. package/dist/react-native/jazz-rn-runtime-adapter.d.ts +0 -56
  1705. package/dist/react-native/jazz-rn-runtime-adapter.d.ts.map +0 -1
  1706. package/dist/react-native/jazz-rn-runtime-adapter.js +0 -192
  1707. package/dist/react-native/jazz-rn-runtime-adapter.js.map +0 -1
  1708. package/dist/react-native/jazz-rn-runtime-adapter.test.d.ts +0 -2
  1709. package/dist/react-native/jazz-rn-runtime-adapter.test.d.ts.map +0 -1
  1710. package/dist/react-native/jazz-rn-runtime-adapter.test.js +0 -165
  1711. package/dist/react-native/jazz-rn-runtime-adapter.test.js.map +0 -1
  1712. package/dist/runtime/client-session.test.d.ts +0 -2
  1713. package/dist/runtime/client-session.test.d.ts.map +0 -1
  1714. package/dist/runtime/client-session.test.js +0 -84
  1715. package/dist/runtime/client-session.test.js.map +0 -1
  1716. package/dist/runtime/client.for-request.test.d.ts +0 -2
  1717. package/dist/runtime/client.for-request.test.d.ts.map +0 -1
  1718. package/dist/runtime/client.for-request.test.js +0 -191
  1719. package/dist/runtime/client.for-request.test.js.map +0 -1
  1720. package/dist/runtime/cloud-server.integration.test.d.ts +0 -2
  1721. package/dist/runtime/cloud-server.integration.test.d.ts.map +0 -1
  1722. package/dist/runtime/cloud-server.integration.test.js +0 -1210
  1723. package/dist/runtime/cloud-server.integration.test.js.map +0 -1
  1724. package/dist/runtime/dynamic-query.d.ts +0 -10
  1725. package/dist/runtime/dynamic-query.d.ts.map +0 -1
  1726. package/dist/runtime/dynamic-query.js +0 -11
  1727. package/dist/runtime/dynamic-query.js.map +0 -1
  1728. package/dist/runtime/leader-lock.d.ts +0 -15
  1729. package/dist/runtime/leader-lock.d.ts.map +0 -1
  1730. package/dist/runtime/leader-lock.js +0 -49
  1731. package/dist/runtime/leader-lock.js.map +0 -1
  1732. package/dist/runtime/local-auth.d.ts +0 -32
  1733. package/dist/runtime/local-auth.d.ts.map +0 -1
  1734. package/dist/runtime/local-auth.js +0 -93
  1735. package/dist/runtime/local-auth.js.map +0 -1
  1736. package/dist/runtime/local-auth.test.d.ts +0 -2
  1737. package/dist/runtime/local-auth.test.d.ts.map +0 -1
  1738. package/dist/runtime/local-auth.test.js +0 -50
  1739. package/dist/runtime/local-auth.test.js.map +0 -1
  1740. package/dist/runtime/query-adapter.test.d.ts +0 -5
  1741. package/dist/runtime/query-adapter.test.d.ts.map +0 -1
  1742. package/dist/runtime/query-adapter.test.js +0 -1249
  1743. package/dist/runtime/query-adapter.test.js.map +0 -1
  1744. package/dist/runtime/row-transformer.test.d.ts +0 -5
  1745. package/dist/runtime/row-transformer.test.d.ts.map +0 -1
  1746. package/dist/runtime/row-transformer.test.js +0 -385
  1747. package/dist/runtime/row-transformer.test.js.map +0 -1
  1748. package/dist/runtime/schema-fetch.d.ts +0 -17
  1749. package/dist/runtime/schema-fetch.d.ts.map +0 -1
  1750. package/dist/runtime/schema-fetch.js +0 -33
  1751. package/dist/runtime/schema-fetch.js.map +0 -1
  1752. package/dist/runtime/schema-fetch.test.d.ts +0 -2
  1753. package/dist/runtime/schema-fetch.test.d.ts.map +0 -1
  1754. package/dist/runtime/schema-fetch.test.js +0 -87
  1755. package/dist/runtime/schema-fetch.test.js.map +0 -1
  1756. package/dist/runtime/subscription-manager.test.d.ts +0 -5
  1757. package/dist/runtime/subscription-manager.test.d.ts.map +0 -1
  1758. package/dist/runtime/subscription-manager.test.js +0 -120
  1759. package/dist/runtime/subscription-manager.test.js.map +0 -1
  1760. package/dist/runtime/sync-transport.d.ts +0 -163
  1761. package/dist/runtime/sync-transport.d.ts.map +0 -1
  1762. package/dist/runtime/sync-transport.js +0 -477
  1763. package/dist/runtime/sync-transport.js.map +0 -1
  1764. package/dist/runtime/sync-transport.test.d.ts +0 -2
  1765. package/dist/runtime/sync-transport.test.d.ts.map +0 -1
  1766. package/dist/runtime/sync-transport.test.js +0 -310
  1767. package/dist/runtime/sync-transport.test.js.map +0 -1
  1768. package/dist/runtime/tab-leader-election.d.ts +0 -97
  1769. package/dist/runtime/tab-leader-election.d.ts.map +0 -1
  1770. package/dist/runtime/tab-leader-election.js +0 -339
  1771. package/dist/runtime/tab-leader-election.js.map +0 -1
  1772. package/dist/runtime/tab-leader-election.test.d.ts +0 -2
  1773. package/dist/runtime/tab-leader-election.test.d.ts.map +0 -1
  1774. package/dist/runtime/tab-leader-election.test.js +0 -278
  1775. package/dist/runtime/tab-leader-election.test.js.map +0 -1
  1776. package/dist/runtime/testing/wasm-runtime-test-utils.d.ts +0 -13
  1777. package/dist/runtime/testing/wasm-runtime-test-utils.d.ts.map +0 -1
  1778. package/dist/runtime/testing/wasm-runtime-test-utils.js +0 -76
  1779. package/dist/runtime/testing/wasm-runtime-test-utils.js.map +0 -1
  1780. package/dist/runtime/utils.d.ts +0 -2
  1781. package/dist/runtime/utils.d.ts.map +0 -1
  1782. package/dist/runtime/utils.js +0 -16
  1783. package/dist/runtime/utils.js.map +0 -1
  1784. package/dist/runtime/value-converter.test.d.ts +0 -5
  1785. package/dist/runtime/value-converter.test.d.ts.map +0 -1
  1786. package/dist/runtime/value-converter.test.js +0 -222
  1787. package/dist/runtime/value-converter.test.js.map +0 -1
  1788. package/dist/runtime/worker-bridge.d.ts +0 -82
  1789. package/dist/runtime/worker-bridge.d.ts.map +0 -1
  1790. package/dist/runtime/worker-bridge.js +0 -308
  1791. package/dist/runtime/worker-bridge.js.map +0 -1
  1792. package/dist/runtime/worker-bridge.race-harness.test.d.ts +0 -2
  1793. package/dist/runtime/worker-bridge.race-harness.test.d.ts.map +0 -1
  1794. package/dist/runtime/worker-bridge.race-harness.test.js +0 -284
  1795. package/dist/runtime/worker-bridge.race-harness.test.js.map +0 -1
  1796. package/dist/runtime/worker-bridge.test.d.ts +0 -2
  1797. package/dist/runtime/worker-bridge.test.d.ts.map +0 -1
  1798. package/dist/runtime/worker-bridge.test.js +0 -233
  1799. package/dist/runtime/worker-bridge.test.js.map +0 -1
  1800. package/dist/sql-gen.d.ts +0 -4
  1801. package/dist/sql-gen.d.ts.map +0 -1
  1802. package/dist/sql-gen.js +0 -163
  1803. package/dist/sql-gen.js.map +0 -1
  1804. package/dist/sql-gen.test.d.ts +0 -2
  1805. package/dist/sql-gen.test.d.ts.map +0 -1
  1806. package/dist/sql-gen.test.js +0 -412
  1807. package/dist/sql-gen.test.js.map +0 -1
  1808. package/dist/subscriptions-orchestrator.integration.test.d.ts +0 -2
  1809. package/dist/subscriptions-orchestrator.integration.test.d.ts.map +0 -1
  1810. package/dist/subscriptions-orchestrator.integration.test.js +0 -192
  1811. package/dist/subscriptions-orchestrator.integration.test.js.map +0 -1
  1812. package/dist/subscriptions-orchestrator.test.d.ts +0 -2
  1813. package/dist/subscriptions-orchestrator.test.d.ts.map +0 -1
  1814. package/dist/subscriptions-orchestrator.test.js +0 -367
  1815. package/dist/subscriptions-orchestrator.test.js.map +0 -1
  1816. package/dist/svelte/JazzSvelteProvider.svelte +0 -49
  1817. package/dist/svelte/JazzSvelteProvider.svelte.d.ts +0 -13
  1818. package/dist/svelte/JazzSvelteProvider.svelte.d.ts.map +0 -1
  1819. package/dist/svelte/SyntheticUserSwitcher.svelte +0 -121
  1820. package/dist/svelte/SyntheticUserSwitcher.svelte.d.ts +0 -11
  1821. package/dist/svelte/SyntheticUserSwitcher.svelte.d.ts.map +0 -1
  1822. package/dist/svelte/context.test.d.ts +0 -2
  1823. package/dist/svelte/context.test.d.ts.map +0 -1
  1824. package/dist/svelte/context.test.js +0 -55
  1825. package/dist/svelte/create-jazz-client.test.d.ts +0 -2
  1826. package/dist/svelte/create-jazz-client.test.d.ts.map +0 -1
  1827. package/dist/svelte/create-jazz-client.test.js +0 -50
  1828. package/dist/svelte/use-all.svelte.d.ts +0 -32
  1829. package/dist/svelte/use-all.svelte.d.ts.map +0 -1
  1830. package/dist/svelte/use-all.svelte.js +0 -61
  1831. package/dist/svelte/use-all.test.d.ts +0 -2
  1832. package/dist/svelte/use-all.test.d.ts.map +0 -1
  1833. package/dist/svelte/use-all.test.js +0 -158
  1834. package/dist/svelte/use-link-external-identity.d.ts +0 -25
  1835. package/dist/svelte/use-link-external-identity.d.ts.map +0 -1
  1836. package/dist/svelte/use-link-external-identity.js +0 -33
  1837. package/dist/svelte/use-link-external-identity.test.d.ts +0 -2
  1838. package/dist/svelte/use-link-external-identity.test.d.ts.map +0 -1
  1839. package/dist/svelte/use-link-external-identity.test.js +0 -97
  1840. package/dist/synthetic-user-switcher.d.ts +0 -16
  1841. package/dist/synthetic-user-switcher.d.ts.map +0 -1
  1842. package/dist/synthetic-user-switcher.js +0 -134
  1843. package/dist/synthetic-user-switcher.js.map +0 -1
  1844. package/dist/synthetic-users.d.ts +0 -32
  1845. package/dist/synthetic-users.d.ts.map +0 -1
  1846. package/dist/synthetic-users.js +0 -124
  1847. package/dist/synthetic-users.js.map +0 -1
  1848. package/dist/testing/fixtures/basic/app.d.ts +0 -55
  1849. package/dist/testing/fixtures/basic/app.d.ts.map +0 -1
  1850. package/dist/testing/fixtures/basic/app.js +0 -174
  1851. package/dist/testing/fixtures/basic/app.js.map +0 -1
  1852. package/dist/testing/fixtures/basic/current.d.ts +0 -2
  1853. package/dist/testing/fixtures/basic/current.d.ts.map +0 -1
  1854. package/dist/testing/fixtures/basic/current.js +0 -6
  1855. package/dist/testing/fixtures/basic/current.js.map +0 -1
  1856. package/dist/testing/index.test.d.ts +0 -2
  1857. package/dist/testing/index.test.d.ts.map +0 -1
  1858. package/dist/testing/index.test.js +0 -234
  1859. package/dist/testing/index.test.js.map +0 -1
  1860. package/dist/testing/local-jazz-server.d.ts +0 -34
  1861. package/dist/testing/local-jazz-server.d.ts.map +0 -1
  1862. package/dist/testing/local-jazz-server.js +0 -313
  1863. package/dist/testing/local-jazz-server.js.map +0 -1
  1864. package/dist/testing/relation-ir-test-helpers.d.ts +0 -3
  1865. package/dist/testing/relation-ir-test-helpers.d.ts.map +0 -1
  1866. package/dist/testing/relation-ir-test-helpers.js +0 -258
  1867. package/dist/testing/relation-ir-test-helpers.js.map +0 -1
  1868. package/dist/worker/jazz-worker.d.ts +0 -9
  1869. package/dist/worker/jazz-worker.d.ts.map +0 -1
  1870. package/dist/worker/jazz-worker.js +0 -555
  1871. package/dist/worker/jazz-worker.js.map +0 -1
  1872. package/dist/worker/jazz-worker.ts +0 -630
  1873. package/dist/worker/worker-protocol.d.ts +0 -136
  1874. package/dist/worker/worker-protocol.d.ts.map +0 -1
  1875. package/dist/worker/worker-protocol.js +0 -7
  1876. package/dist/worker/worker-protocol.js.map +0 -1
@@ -0,0 +1,4076 @@
1
+ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { verifyChallenge } from "../local-first-auth/server.js";
3
+ import { BACKEND_SIGNING_KEY_ROUTE, backendSigningKeys } from "./signing-key.js";
4
+ import { resolve } from "node:path";
5
+ import { backendNative, inProcessCore } from "./backend-native.js";
6
+ import { BINDING_ORIGIN, bindingTransport, networkTransport, } from "./core-transport.js";
7
+ import { registerInProcessTransport } from "../runtime/in-process-transport.js";
8
+ import { accountAppId, localFirstAccountId } from "../accounts/local-first.js";
9
+ import { AUTHENTICATE_EXPIRES_AT_MISSING } from "../accounts/registry-client.js";
10
+ import { LOCAL_FIRST_JWT_ISSUER, parseJwtPayload } from "../runtime/client-session.js";
11
+ import { verifyLocalFirstToken } from "../runtime/local-first-token.js";
12
+ import { endpointScope } from "../runtime/client-scope.js";
13
+ import { mapAuthReason } from "../runtime/auth-state.js";
14
+ import { clientHelloFeatures, decodeWebSocketFrameBatch, decodeWireError, encodeAuthFailedBatch, encodeWebSocketFrameBatch, REAUTHENTICATE_WIRE_MESSAGE_PREFIX, } from "../runtime/native-runtime/websocket.js";
15
+ import { SESSION_RENEWAL_HEADER, SESSION_RENEWAL_PRELUDE_FIELD, WIRE_FRAME_RENEW, decodeRenewFrame, encodeRenewSoonFrame, } from "../runtime/native-runtime/session-renewal-wire.js";
16
+ import { STREAM_RECORD_MESSAGE, STREAM_RECORD_SESSION, StreamRecordReader, encodeStreamClose, encodeStreamRecord, } from "../runtime/native-runtime/http-stream-socket.js";
17
+ import { resolveSchemaSource } from "../schema-source.js";
18
+ import { shippedMigrations } from "../runtime/client-migrations.js";
19
+ import { checkRunningBindings } from "../dev/app-files.js";
20
+ import { loadBackendApp, provideCodegenNapi } from "../dev/codegen-napi.js";
21
+ import { BUNDLE_HEADER } from "./admission.js";
22
+ import { boundApp } from "../typed-app.js";
23
+ import { publishLoadedDeployment } from "../dev/catalogue.js";
24
+ import { DeploymentError } from "../dev/catalogue-api.js";
25
+ import { backendDbAttributedTo, backendDbForSession, openJazzSession, } from "./create-jazz-session.js";
26
+ import { openThinSessionClient } from "./thin-session-client.js";
27
+ import { asksThinResults, ThinRelay } from "./thin-relay.js";
28
+ import { BackendClientsUnavailable, backendClientVerifier, } from "./backend-clients.js";
29
+ import { BACKEND_USER_ISSUER } from "./backend-issuer.js";
30
+ import { earlyDb } from "./early-db.js";
31
+ import { checkNamespaceOption, checkRegionOption, coreName, onVercelDeployment, onVercelHost, openVercelCore, refuseVercelAppId, refuseVercelName, } from "./vercel-store.js";
32
+ import { logStoreOpened } from "./store-log.js";
33
+ export { perBranch } from "./vercel-store.js";
34
+ import { files } from "./blobs.js";
35
+ import { createInspector, inspectorSettings, newTokenSecret, } from "./inspect.js";
36
+ import { createInspectorUi } from "./inspect-ui.js";
37
+ export { files, s3, vercelBlob, } from "./blobs.js";
38
+ import { AuthenticateExpiresAtError, reauthenticateAt, sessionDeadline, startTimer, withCheckedExpiry, } from "./session-expiry.js";
39
+ import { NoJazzAccountError } from "./no-account-error.js";
40
+ import { deviceAccountSession, deviceProofOf, isAuthenticationUnavailableError, RequestAuthenticationError, } from "./request-auth.js";
41
+ import { optionalPeerImportError } from "./optional-peer.js";
42
+ import { closingBeforeDeadline } from "./socket-deadline.js";
43
+ import { importWs, vercelUpgradesSockets } from "./ws-peer.js";
44
+ /**
45
+ * A SQLite core in this process, kept in the directory `path`. It generates
46
+ * its app id on first start and keeps it in its own file, `<path>/jazz.sqlite`,
47
+ * with the rest of its identity, so a copy of that file is the same store
48
+ * (alpha.65's `jazz-alpha59-alpha60-import` leaves an alpha.59 app's id in
49
+ * `<path>/app-id`, which the first open takes over). To
50
+ * open a copy beside the original, detach it first: `jazz-tools store detach`. Large
51
+ * values' bytes go to `blobs`, by default `files()` in `<path>/blobs`.
52
+ *
53
+ * Only one process can open `path` at a time (it holds `<path>/jazz.lock`
54
+ * while the core is open); a second one fails with "already open". It
55
+ * refuses to start on serverless hosts with no lasting disk (Vercel, AWS
56
+ * Lambda, Netlify): use `vercel()` or `remote()` there.
57
+ */
58
+ export function sqlite(options) {
59
+ refuseStoreAppId("sqlite", options);
60
+ const blobs = options.blobs ?? files();
61
+ if (blobs !== "sqlite" &&
62
+ (typeof blobs !== "object" || (blobs.kind !== "files" && blobs.kind !== "s3"))) {
63
+ throw new Error('sqlite(): blobs must be files(), s3() or "sqlite"');
64
+ }
65
+ return { kind: "sqlite", path: options.path, blobs };
66
+ }
67
+ /**
68
+ * An in-memory core in this process: for tests and throwaway previews. Each
69
+ * one is its own store, with a new app id.
70
+ */
71
+ export function memory(options) {
72
+ refuseStoreAppId("memory", options);
73
+ return { kind: "memory" };
74
+ }
75
+ /** Stores keep their own app id; one passed from JavaScript is refused, not ignored. */
76
+ function refuseStoreAppId(store, options) {
77
+ if (typeof options === "object" && options !== null && "appId" in options) {
78
+ throw new Error(`${store}(): appId is not an option: the store keeps its own app id. To keep an alpha.59 app's id, import its data with \`jazz-alpha59-alpha60-import import --app-id\` from the v2.0.0-alpha.65 release.`);
79
+ }
80
+ }
81
+ /**
82
+ * A core running elsewhere (Jazz Cloud, or a sync server you run), serving
83
+ * the app `appId`, reached from this backend with the app's one secret (its
84
+ * admin secret), or with a `backendCredential` of your own. Browsers still
85
+ * talk only to your backend: it decides who each user is, and the core
86
+ * trusts it to say so. The secret never leaves your server.
87
+ */
88
+ export function remote(options) {
89
+ const appId = options.appId;
90
+ if (typeof appId !== "string" || !appId.trim()) {
91
+ throw new Error("remote(): appId must name the app the core serves (it is empty)");
92
+ }
93
+ let backendCredential;
94
+ let secret;
95
+ if ("backendCredential" in options) {
96
+ backendCredential = options.backendCredential;
97
+ }
98
+ else {
99
+ secret = options.secret;
100
+ if (secret === undefined && "adminSecret" in options) {
101
+ throw new Error("remote(): `adminSecret` and `backendSecret` were replaced by one `secret`, the app's admin secret");
102
+ }
103
+ if (typeof secret !== "string" || !secret.trim()) {
104
+ throw new Error("remote(): secret must be the app's admin secret (it is empty)");
105
+ }
106
+ const given = secret;
107
+ backendCredential = () => given;
108
+ }
109
+ return {
110
+ kind: "remote",
111
+ url: options.url.replace(/\/+$/, ""),
112
+ appId,
113
+ backendCredential,
114
+ ...(secret === undefined ? {} : { secret }),
115
+ };
116
+ }
117
+ /** The shortest core secret a Durable Object core accepts. */
118
+ const DURABLE_OBJECT_SECRET_MIN_LENGTH = 32;
119
+ /** The hosts a `durableObjects()` url may reach over plain http. */
120
+ const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
121
+ /** How long the store waits for the core to name its app. */
122
+ const DURABLE_OBJECT_APP_TIMEOUT_MS = 30_000;
123
+ /** An app id the core may name: no path separators, dots or line breaks. */
124
+ const DURABLE_OBJECT_APP_ID = /^[A-Za-z0-9_-]{1,128}$/;
125
+ /**
126
+ * A core running in a Cloudflare Durable Object: one SQLite-backed object per
127
+ * app, in a Worker you deploy that exports `JazzCore` and forwards requests to
128
+ * it with `routeJazzRequest` (both from `jazz-tools/durable-object`). `url` is
129
+ * that Worker's origin (e.g. `https://my-app-jazz.example.workers.dev`) and
130
+ * `secret` its `JAZZ_CORE_SECRET`: a random string of at least 32 characters
131
+ * that stays the same across deployments. The object keeps its own app id,
132
+ * which this backend asks it for when the store opens.
133
+ *
134
+ * Large values' bytes go where the core's Worker puts them, so there is no
135
+ * `blobs` option here: bind an R2 bucket to that Worker as `JAZZ_BLOBS`
136
+ * (recommended), or they stay in the object's SQLite.
137
+ *
138
+ * The core admits only this backend, which holds the secret; browsers keep
139
+ * talking to your backend. A Durable Object core doesn't run thin-client
140
+ * transactions (your backend runs them, as with any core) and has no
141
+ * HTTP-stream fallback for the backend's own sockets.
142
+ *
143
+ * @experimental Durable Object cores are new; the options and the Worker's
144
+ * bindings may still change.
145
+ */
146
+ export function durableObjects(options) {
147
+ if (typeof options === "object" && options !== null && "appId" in options) {
148
+ throw new Error("durableObjects(): appId is not an option: the store keeps its own app id, in the Worker's Durable Object");
149
+ }
150
+ const lifecycle = options?.lifecycle;
151
+ if (lifecycle !== undefined && lifecycle !== "while-connected" && lifecycle !== "hibernate") {
152
+ throw new TypeError('durableObjects(): lifecycle must be "while-connected" or "hibernate"');
153
+ }
154
+ if (typeof options === "object" && options !== null && "binding" in options) {
155
+ const { binding, secret } = options;
156
+ if (typeof binding !== "object" ||
157
+ binding === null ||
158
+ (typeof binding.fetch !== "function" &&
159
+ typeof binding.idFromName !== "function")) {
160
+ throw new Error("durableObjects(): binding must be the Worker's JazzCore Durable Object binding, e.g. env.JAZZ");
161
+ }
162
+ checkCoreSecret(secret);
163
+ return {
164
+ kind: "durableObjects",
165
+ url: BINDING_ORIGIN,
166
+ binding,
167
+ secret,
168
+ ...(lifecycle && { lifecycle }),
169
+ };
170
+ }
171
+ const { url, secret } = (options ?? {});
172
+ let origin;
173
+ try {
174
+ origin = new URL(url);
175
+ }
176
+ catch {
177
+ // Refused below.
178
+ }
179
+ if (!origin ||
180
+ (origin.protocol !== "https:" && origin.protocol !== "http:") ||
181
+ origin.pathname.replace(/\/+$/, "") !== "" ||
182
+ origin.search ||
183
+ origin.hash) {
184
+ throw new Error(`durableObjects(): url must be the Worker's origin, like "https://my-app-jazz.example.workers.dev"; got ${JSON.stringify(url)}`);
185
+ }
186
+ if (origin.username || origin.password) {
187
+ throw new Error("durableObjects(): url must not carry a user name or password; the core secret is the only credential");
188
+ }
189
+ // The secret goes with every request: in the clear only to this machine
190
+ // (`wrangler dev`, tests).
191
+ if (origin.protocol === "http:" && !LOOPBACK_HOSTS.has(origin.hostname)) {
192
+ throw new Error(`durableObjects(): url must be https:// (http:// only for localhost, 127.0.0.1 or [::1]); got ${JSON.stringify(url)}`);
193
+ }
194
+ checkCoreSecret(secret);
195
+ return { kind: "durableObjects", url: origin.origin, secret, ...(lifecycle && { lifecycle }) };
196
+ }
197
+ function checkCoreSecret(secret) {
198
+ if (typeof secret !== "string" || secret.length < DURABLE_OBJECT_SECRET_MIN_LENGTH) {
199
+ throw new Error(`durableObjects(): secret must be the Worker's JAZZ_CORE_SECRET, a random string of at least ${DURABLE_OBJECT_SECRET_MIN_LENGTH} characters`);
200
+ }
201
+ }
202
+ /**
203
+ * The `remote()` store a `durableObjects()` store opens as: the Worker's
204
+ * object tells this backend its app id (`GET /app`, with the core secret).
205
+ */
206
+ async function durableObjectCore(store) {
207
+ const transport = store.binding ? bindingTransport(store.binding) : networkTransport();
208
+ let response;
209
+ let body;
210
+ try {
211
+ response = await transport.fetch(`${store.url}/app`, {
212
+ headers: { [CREDENTIAL_HEADER]: store.secret },
213
+ redirect: "manual",
214
+ signal: AbortSignal.timeout(DURABLE_OBJECT_APP_TIMEOUT_MS),
215
+ });
216
+ body = (await response.json().catch(() => undefined));
217
+ }
218
+ catch (error) {
219
+ if (error?.name === "TimeoutError") {
220
+ throw new Error(`createJazz: the Durable Object core at ${store.url} did not answer within ${DURABLE_OBJECT_APP_TIMEOUT_MS / 1000}s; this Jazz tries again on its next use`, { cause: error });
221
+ }
222
+ throw unreachableCore(store.url, error);
223
+ }
224
+ if (response.status === 401 || response.status === 403) {
225
+ throw new Error(`createJazz: the Durable Object core at ${store.url} refused the secret: durableObjects()'s secret must be the Worker's JAZZ_CORE_SECRET`);
226
+ }
227
+ // The id goes into request paths and log lines: only a plain one.
228
+ if (!response.ok || typeof body?.appId !== "string" || !DURABLE_OBJECT_APP_ID.test(body.appId)) {
229
+ throw new Error(`createJazz: ${store.url} did not answer as a Jazz Durable Object core (GET /app: ${response.status}); is url the Worker that exports JazzCore, on this jazz-tools version?`);
230
+ }
231
+ return {
232
+ ...remote({ url: store.url, appId: body.appId, secret: store.secret }),
233
+ transport,
234
+ lifecycle: store.lifecycle,
235
+ };
236
+ }
237
+ /**
238
+ * The store for apps deployed on Vercel. Use it in dev too: outside a
239
+ * production or preview deployment (`next dev`, `vercel dev`, tests) it runs
240
+ * `local`, by default `sqlite({ path: ".jazz/local" })`.
241
+ *
242
+ * Deployed, it runs a core in a persistent Vercel Sandbox in your own Vercel
243
+ * project, with its data on a Drive, in `region` (required, e.g. `"iad1"`,
244
+ * where earlier versions created every core; fixed at creation, and a
245
+ * different region for an existing core throws). `namespace` (required) says which: the
246
+ * Sandbox is `jazz-<project>-<namespace>`, e.g. one core per environment
247
+ * with `namespace: ({ environment }) => environment`, or production's core
248
+ * and one per preview branch with
249
+ * `namespace: ({ environment, branch }) => environment === "production" ? "production" : perBranch(branch)`.
250
+ * It is created on first use, wakes when a request needs it (about a second)
251
+ * and stops after `idleMs` without requests or sockets. The function's Vercel
252
+ * OIDC token is its only credential, so there are no secrets and no env vars:
253
+ * the core admits only tokens naming the workload its first start pinned
254
+ * (team, project and environment by name), and a deployment of another
255
+ * environment refuses to start or retarget it. All previews share one
256
+ * workload, so preview branches' cores are kept apart, not secured from each
257
+ * other. Anyone with Sandbox access to the project controls its cores. The
258
+ * token comes with each request (it can't be read at module scope), so the
259
+ * core opens on the first request, not when `createJazz` is called; work
260
+ * between requests uses the freshest one seen, and open sockets outlive its
261
+ * expiry. A team or project rename (or
262
+ * a change of OIDC issuer mode) changes the workload: delete `/data/trust` in
263
+ * the Sandbox to re-pin the core. Install `@vercel/sandbox` and
264
+ * `@vercel/functions` next to `jazz-tools`. A deployment of a newer jazz-tools
265
+ * restarts the core on its version, and an older deployment never moves it
266
+ * back. Branch cores are not deleted when a branch merges yet: each keeps its
267
+ * Sandbox and a Drive of up to `maxDriveBytes` until you remove them.
268
+ */
269
+ export function vercel(options) {
270
+ // Refused here, not on the first deployed request: in dev the local
271
+ // store runs and would never read them.
272
+ refuseVercelAppId(options ?? {});
273
+ refuseVercelName(options ?? {});
274
+ checkNamespaceOption(options ?? {});
275
+ checkRegionOption(options ?? {});
276
+ const { local, ...rest } = options;
277
+ return { kind: "vercel", options: rest, local: local ?? sqlite({ path: ".jazz/local" }) };
278
+ }
279
+ function blobOptions(blobs) {
280
+ if (blobs === "sqlite")
281
+ return { blobs: "sqlite" };
282
+ if (blobs.kind === "s3") {
283
+ return {
284
+ blobs: "s3",
285
+ ...(blobs.bucket === undefined ? {} : { s3Bucket: blobs.bucket }),
286
+ ...(blobs.region === undefined ? {} : { s3Region: blobs.region }),
287
+ ...(blobs.endpoint === undefined ? {} : { s3Endpoint: blobs.endpoint }),
288
+ ...(blobs.prefix === undefined ? {} : { s3Prefix: blobs.prefix }),
289
+ };
290
+ }
291
+ return { blobs: "files", ...(blobs.dir === undefined ? {} : { blobsDir: blobs.dir }) };
292
+ }
293
+ /**
294
+ * The marker's brand, registered globally like `createJazz`'s store registry:
295
+ * a bundler may load this module more than once (Next dev evaluates it per
296
+ * route), and a shared Jazz must still recognise a marker made by another copy.
297
+ */
298
+ const LOCAL_FIRST_GUEST_BRAND = Symbol.for("jazz-tools.acceptDeviceAccounts.guest");
299
+ const LOCAL_FIRST_GUEST = Object.freeze({
300
+ [LOCAL_FIRST_GUEST_BRAND]: true,
301
+ kind: "jazz:local-first-guest",
302
+ });
303
+ /** Whether `answer` is {@link acceptDeviceAccounts}'s marker, from any copy of this module. */
304
+ function isDeviceAccountsAnswer(answer) {
305
+ return (typeof answer === "object" &&
306
+ answer !== null &&
307
+ answer[LOCAL_FIRST_GUEST_BRAND] === true);
308
+ }
309
+ /**
310
+ * `authenticate`'s answer, checked: a user must have a string `userId`. Any
311
+ * other answer is a bug in the app's `authenticate`, said so here rather than
312
+ * as a failure from the core about a missing identity.
313
+ */
314
+ function checkedUser(answer) {
315
+ const userId = answer?.userId;
316
+ if (typeof answer === "object" && answer !== null && typeof userId === "string" && userId !== "")
317
+ return answer;
318
+ throw new TypeError(`createJazz: authenticate must return { userId: string, expiresAt: number }, acceptDeviceAccounts(request) or null; it returned ${describeAnswer(answer)}`);
319
+ }
320
+ /**
321
+ * `authenticate`'s answer for an error message: its shape, never its values,
322
+ * since a wrong answer may well be a token or a session.
323
+ */
324
+ function describeAnswer(answer) {
325
+ if (typeof answer !== "object" || answer === null)
326
+ return kindOf(answer);
327
+ const keys = Reflect.ownKeys(answer).map(String);
328
+ const detail = "userId" in answer ? `, userId: ${kindOf(answer.userId)}` : "";
329
+ return `an object with keys [${keys.join(", ")}]${detail}`;
330
+ }
331
+ function kindOf(value) {
332
+ if (value === null || value === undefined)
333
+ return String(value);
334
+ if (value === "")
335
+ return "an empty string";
336
+ const type = Array.isArray(value) ? "array" : typeof value;
337
+ return `${/^[aeiou]/.test(type) ? "an" : "a"} ${type}`;
338
+ }
339
+ /** `request` without the credentials a browser sends with it (its cookies, an `Authorization` header). */
340
+ function withoutCredentials(request) {
341
+ const headers = new Headers(request.headers);
342
+ headers.delete("cookie");
343
+ headers.delete("authorization");
344
+ return new Request(request.url, { method: request.method, headers });
345
+ }
346
+ /**
347
+ * Let this request through as a device account, when it comes from one: an
348
+ * account whose key lives on the user's device, with no user in your auth.
349
+ * It's how your app lets people in as guests, and a local-first friendly way
350
+ * to sign in at all. Device accounts are refused unless `authenticate`
351
+ * returns this, since only your permissions stand between them and your
352
+ * data.
353
+ *
354
+ * ```ts
355
+ * authenticate: async (request) => {
356
+ * const session = await auth.api.getSession({ headers: request.headers });
357
+ * if (!session) return acceptDeviceAccounts(request);
358
+ * return {
359
+ * userId: session.user.id,
360
+ * expiresAt: Math.floor(session.session.expiresAt.getTime() / 1000),
361
+ * };
362
+ * },
363
+ * ```
364
+ *
365
+ * An app with no sign-in of its own, where every browser has a device
366
+ * account, passes it as is: `authenticate: acceptDeviceAccounts`.
367
+ *
368
+ * For a request that is not a device account's, it means the same as `null`:
369
+ * no one is signed in.
370
+ *
371
+ * A device account's request may also carry a user's cookie: someone signed
372
+ * in (or up) on that browser, and the device account still uploads its
373
+ * writes before it links to them. Jazz then asks `authenticate` about the
374
+ * request without its cookies and `Authorization` header, so the device
375
+ * account is let in as it would be on its own.
376
+ *
377
+ * This gates device accounts' sync, and their requests to your own routes:
378
+ * `forReqUser` takes the device's proof (`Authorization: Bearer`), and
379
+ * `withAttribution` and `accountFor` do with `{ deviceAccounts: true }`.
380
+ * Linking one to a user who signs up
381
+ * (`linkDeviceAccount()`) is authorised by your sign-in (`authenticate`
382
+ * naming that user) plus the device key's proof of a one-time challenge, so
383
+ * it works even when your app doesn't accept device accounts for sync.
384
+ */
385
+ export function acceptDeviceAccounts(_request) {
386
+ return LOCAL_FIRST_GUEST;
387
+ }
388
+ /** How long a stream session reuses `authenticate`'s answer by default (`streamAuthReuseSeconds`). */
389
+ const DEFAULT_STREAM_AUTH_REUSE_SECONDS = 60;
390
+ /**
391
+ * Request headers that differ from send to send without saying who sent it:
392
+ * set per request by proxies, hosts and tracing, or describing the body.
393
+ * Named one by one: every other header counts as a credential, since an
394
+ * app's `authenticate` may read any of them (an identity-aware proxy's
395
+ * `x-forwarded-user`, `cf-access-jwt-assertion`, a client certificate), and
396
+ * a changed one asks `authenticate` again.
397
+ */
398
+ const PER_REQUEST_HEADER = /^(content-length|content-type|content-encoding|transfer-encoding|date|via|forwarded|traceparent|tracestate|baggage|sentry-trace|x-request-id|x-correlation-id|x-amzn-trace-id|x-cloud-trace-context|x-b3-(traceid|spanid|parentspanid|sampled|flags)|b3|x-real-ip|true-client-ip|x-jazz-stream-key|x-forwarded-(for|host|proto|port|prefix|server)|cf-(ray|ipcountry|visitor|worker|ew-via|cache-status|connecting-ip)|x-vercel-(id|deployment-url|forwarded-for|ip-[a-z-]+|proxied-for|proxy-signature(-ts)?|sc-[a-z-]+|internal-[a-z-]+)|x-matched-path)$/;
399
+ /** A digest of what an app's `authenticate` may read off a stream send. */
400
+ function streamCredentials(request) {
401
+ const hash = createHash("sha256").update(request.url).update("\0");
402
+ const names = [];
403
+ request.headers.forEach((_, name) => {
404
+ if (!PER_REQUEST_HEADER.test(name))
405
+ names.push(name);
406
+ });
407
+ for (const name of names.sort()) {
408
+ hash
409
+ .update(name)
410
+ .update("\0")
411
+ .update(request.headers.get(name) ?? "")
412
+ .update("\0");
413
+ }
414
+ return hash.digest("base64url");
415
+ }
416
+ const DEFAULT_BASE_PATH = "/jazz";
417
+ // Routes a browser may reach. Everything else (admin, backend admission,
418
+ // shutdown) stays behind this backend.
419
+ /** How long a sync session may take to send its sign-in (its first message). */
420
+ const PRELUDE_DEADLINE_MS = 30_000;
421
+ /** On createJazz's 426 for a socket path: this endpoint serves the HTTP stream. */
422
+ const STREAM_AVAILABLE_HEADER = "x-jazz-stream";
423
+ /** The answer for a socket path where this host can't upgrade sockets. */
424
+ const useHttpStream = () => new Response("WebSocket upgrade not available here; use the HTTP stream", {
425
+ status: 426,
426
+ headers: { [STREAM_AVAILABLE_HEADER]: "1" },
427
+ });
428
+ /** The stream session's key, on each send and close (see `openStream`). */
429
+ const STREAM_KEY_HEADER = "x-jazz-stream-key";
430
+ const PUBLIC_APP_ROUTES = /^\/apps\/[^/]+\/(schemas|schema\/[^/]+)$/;
431
+ // What a browser can't hand the core: secrets, a backend credential or the
432
+ // access it states, or the core's own mark for sockets a credential vouched for.
433
+ // Nor a bearer token: this backend decides who a request is (`authenticate`,
434
+ // backend clients), never the core.
435
+ const STRIPPED_HEADERS = [
436
+ "authorization",
437
+ "x-jazz-backend-secret",
438
+ "x-jazz-admin-secret",
439
+ "x-jazz-session",
440
+ "x-jazz-backend-credential",
441
+ "x-jazz-backend-access",
442
+ "x-jazz-internal-workload-vouched",
443
+ ];
444
+ const CREDENTIAL_HEADER = "x-jazz-backend-credential";
445
+ const ACCESS_HEADER = "x-jazz-backend-access";
446
+ // What the secret slots carry to a remote core: the access stated next to
447
+ // the backend credential decides what a request gets, not these.
448
+ const STAND_IN_SECRET = "stated-by-backend-credential";
449
+ /**
450
+ * The app's secret, when this backend holds it: `remote()`'s `secret`, or
451
+ * an in-process core's own. A core reached with a backend credential holds
452
+ * only {@link STAND_IN_SECRET}, which is no secret.
453
+ */
454
+ function appSecretOf(store, core) {
455
+ if (store.kind === "remote" && store.secret)
456
+ return store.secret;
457
+ return core.adminSecret === STAND_IN_SECRET ? undefined : core.adminSecret;
458
+ }
459
+ /**
460
+ * The refusal of every local-first identity by a core that admits none: one
461
+ * an older jazz-tools started with local-first auth off (cores have no such
462
+ * switch since 2.0.0-alpha.62), or a Jazz Cloud app's with it turned off.
463
+ */
464
+ const LOCAL_FIRST_AUTH_DISABLED = "local_first_auth_disabled";
465
+ /** The core's answer for an identity it refuses: one a link retired, or a revoked user. */
466
+ const IDENTITY_NOT_AUTHORIZED = "identity_not_authorized";
467
+ /**
468
+ * What such a core tells a guest's session (jazz-server's
469
+ * `LOCAL_FIRST_AUTH_DISABLED_MESSAGE` before 2.0.0-alpha.62).
470
+ */
471
+ const CORE_REFUSES_GUESTS = "Local-first auth is not enabled";
472
+ // The core's refusal of a user session `jazz.revokeUser` ended: an
473
+ // `auth_failed` / `after_auth` error frame with its `SESSION_REVOKED`
474
+ // message. Batches larger than an error batch can be aren't decoded.
475
+ const CORE_REVOKED_SESSION = "session revoked: jazz.revokeUser ended this user's sessions";
476
+ const CORE_REVOKED_BATCH_MAX_BYTES = 512;
477
+ // `WireFrame::Error`'s postcard tag, the first byte of its frame.
478
+ const WIRE_FRAME_ERROR_TAG = 1;
479
+ /**
480
+ * Whether a core→client batch is the core ending the session as revoked.
481
+ * Only a decoded error frame counts: row data that happens to contain the
482
+ * message (any user can write it) never does.
483
+ */
484
+ function isCoreRevocation(data) {
485
+ if (data.byteLength > CORE_REVOKED_BATCH_MAX_BYTES)
486
+ return false;
487
+ let frames;
488
+ try {
489
+ frames = decodeWebSocketFrameBatch(data);
490
+ }
491
+ catch {
492
+ return false;
493
+ }
494
+ return frames.some((frame) => {
495
+ if (frame[0] !== WIRE_FRAME_ERROR_TAG)
496
+ return false;
497
+ try {
498
+ const error = decodeWireError(frame);
499
+ return (error.code === "auth_failed" &&
500
+ error.retry === "after_auth" &&
501
+ error.message === CORE_REVOKED_SESSION);
502
+ }
503
+ catch {
504
+ return false;
505
+ }
506
+ });
507
+ }
508
+ // What a browser's request to a public route carries on to a remote core:
509
+ // never its cookies or its app session.
510
+ const REMOTE_FORWARDED_HEADERS = ["accept", "content-type", "if-none-match"];
511
+ const MAX_STREAM_MESSAGE_BYTES = 2 * 1024 * 1024;
512
+ /**
513
+ * Bytes a session's client may have sent that the core has not taken yet.
514
+ * A transport that waits for the core stays well under it; past it, the
515
+ * client ignored flow control and its session ends.
516
+ */
517
+ const MAX_WAITING_SESSION_BYTES = 32 * 1024 * 1024;
518
+ /** What `inspector` is when createJazz isn't given one: one object, so the Inspector reads it once. */
519
+ const NO_INSPECTOR_OPTIONS = Object.freeze({});
520
+ /** The peer address of requests that came through a Node handler, where Jazz can know it. */
521
+ const remoteAddresses = new WeakMap();
522
+ function headerPairs(headers) {
523
+ const pairs = [];
524
+ headers.forEach((value, name) => {
525
+ if (!STRIPPED_HEADERS.includes(name.toLowerCase()))
526
+ pairs.push([name, value]);
527
+ });
528
+ return pairs;
529
+ }
530
+ function coreResponse(response) {
531
+ const headers = new Headers();
532
+ for (const [name, value] of response.headers)
533
+ headers.append(name, value);
534
+ const nullBody = response.status === 204 || response.status === 304;
535
+ return new Response(nullBody ? null : response.body, {
536
+ status: response.status,
537
+ headers,
538
+ });
539
+ }
540
+ function toBytes(data) {
541
+ if (data instanceof Uint8Array)
542
+ return data;
543
+ if (data instanceof ArrayBuffer)
544
+ return new Uint8Array(data);
545
+ if (Array.isArray(data))
546
+ return Buffer.concat(data);
547
+ if (typeof data === "string")
548
+ return new TextEncoder().encode(data);
549
+ throw new Error("unsupported socket message");
550
+ }
551
+ function arrayBufferOf(bytes) {
552
+ return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
553
+ }
554
+ /** A WebSocket-shaped session on the core, for clients in this process. */
555
+ function inProcessWebSocket(open) {
556
+ return class InProcessSocket {
557
+ binaryType = "arraybuffer";
558
+ readyState = 0;
559
+ listeners = new Map();
560
+ session;
561
+ constructor(url) {
562
+ queueMicrotask(() => {
563
+ if (this.readyState !== 0)
564
+ return;
565
+ try {
566
+ this.session = open(url, (error, event) => this.onCoreEvent(error, event));
567
+ }
568
+ catch (error) {
569
+ this.emit("error", error);
570
+ this.finish(1011, error instanceof Error ? error.message : String(error));
571
+ return;
572
+ }
573
+ // Open only once the core's side is: a session that never reaches
574
+ // the core then closes without having opened, which a client (and
575
+ // the vercel() store's waking socket) can tell from a session that
576
+ // dropped.
577
+ const opened = this.session.opened;
578
+ if (!opened)
579
+ return this.markOpen();
580
+ void opened.then(() => this.markOpen());
581
+ });
582
+ }
583
+ markOpen() {
584
+ if (this.readyState !== 0)
585
+ return;
586
+ this.readyState = 1;
587
+ this.emit("open");
588
+ }
589
+ addEventListener(type, listener) {
590
+ const list = this.listeners.get(type) ?? [];
591
+ list.push(listener);
592
+ this.listeners.set(type, list);
593
+ }
594
+ send(data) {
595
+ if (this.readyState !== 1 || !this.session)
596
+ throw new Error("socket is not open");
597
+ // Like a socket's own buffer: messages wait here, in order, until the
598
+ // core has room, so this client's pace is the core's.
599
+ this.outbox.push(toBytes(data));
600
+ void this.drain();
601
+ }
602
+ outbox = [];
603
+ draining = false;
604
+ async drain() {
605
+ if (this.draining)
606
+ return;
607
+ this.draining = true;
608
+ try {
609
+ while (this.outbox.length > 0 && this.readyState === 1 && this.session) {
610
+ const data = this.outbox.shift();
611
+ const sent = this.session.sendWithRoom
612
+ ? await this.session.sendWithRoom(data)
613
+ : this.session.send(data);
614
+ if (!sent)
615
+ break;
616
+ }
617
+ }
618
+ catch (error) {
619
+ this.emit("error", error);
620
+ this.close();
621
+ }
622
+ finally {
623
+ this.draining = false;
624
+ }
625
+ }
626
+ close() {
627
+ if (this.readyState >= 2)
628
+ return;
629
+ this.session?.close();
630
+ this.finish(1000, "client closed");
631
+ }
632
+ onCoreEvent(error, event) {
633
+ if (error) {
634
+ this.emit("error", error);
635
+ this.finish(1011, error.message);
636
+ }
637
+ else if (event.kind === "message" && event.data) {
638
+ this.emit("message", { data: arrayBufferOf(event.data) });
639
+ }
640
+ else if (event.kind === "close") {
641
+ this.finish(event.code ?? 1000, event.reason ?? "");
642
+ }
643
+ }
644
+ emit(type, event) {
645
+ for (const listener of this.listeners.get(type) ?? [])
646
+ listener(event);
647
+ }
648
+ finish(code, reason) {
649
+ if (this.readyState >= 2)
650
+ return;
651
+ this.readyState = 3;
652
+ this.emit("close", { code, reason });
653
+ }
654
+ };
655
+ }
656
+ /** The app's schema versions, migrations and permissions, as its code declares them. */
657
+ async function applyBundle(origin, options) {
658
+ // Published, never activated: this backend's sessions are pinned to its
659
+ // bundle, so deployments of the app serve side by side and a rollback is
660
+ // publishing the older bundle again.
661
+ const deployed = await publishLoadedDeployment({
662
+ appId: options.appId,
663
+ serverUrl: origin,
664
+ adminSecret: options.adminSecret,
665
+ allowDroppingHistory: options.allowDroppingHistory,
666
+ }, options.loaded).catch((error) => {
667
+ // A core without `/bundles` predates per-deployment permissions; it
668
+ // must not be handed a deployment it would activate for every backend.
669
+ if (error instanceof DeploymentError && (error.status === 404 || error.status === 405)) {
670
+ throw new Error("createJazz: the sync server predates per-deployment permissions bundles; upgrade it before this backend", { cause: error });
671
+ }
672
+ throw error;
673
+ });
674
+ // An older core answers a publish without the bundle it made.
675
+ if (!deployed.bundle) {
676
+ throw new Error("createJazz: the core did not publish a permissions bundle; upgrade it");
677
+ }
678
+ // The loader's own warnings were printed when the permissions loaded; the
679
+ // rest (tables without policies) are the publish's.
680
+ if (!options.quiet) {
681
+ for (const warning of deployed.warnings ?? []) {
682
+ if (!options.loaded.warnings.includes(warning))
683
+ console.warn(`jazz: ${warning}`);
684
+ }
685
+ }
686
+ return deployed.bundle;
687
+ }
688
+ /**
689
+ * `socket`, its first frame (the prelude) pinned to the published bundle
690
+ * this backend serves with. The core honours the pin only on this backend's
691
+ * word, so whatever bundle a browser stated is replaced.
692
+ */
693
+ export function pinnedSocket(socket, bundle) {
694
+ let first = true;
695
+ /** `data`, with the pin stamped into the prelude; null if it can't be. */
696
+ const pin = (data) => {
697
+ if (!first)
698
+ return data;
699
+ first = false;
700
+ const pinned = withBundle(data, bundle());
701
+ // A prelude the pin cannot be stamped into would open unpinned.
702
+ if (pinned === null)
703
+ socket.close();
704
+ return pinned;
705
+ };
706
+ return {
707
+ send(data) {
708
+ const pinned = pin(data);
709
+ return pinned !== null && socket.send(pinned);
710
+ },
711
+ async sendWithRoom(data) {
712
+ const pinned = pin(data);
713
+ if (pinned === null)
714
+ return false;
715
+ return socket.sendWithRoom ? socket.sendWithRoom(pinned) : socket.send(pinned);
716
+ },
717
+ close: () => socket.close(),
718
+ ...(socket.opened ? { opened: socket.opened } : {}),
719
+ };
720
+ }
721
+ /**
722
+ * `prelude` pinned to `bundle`, or with no pin while none is published yet
723
+ * (the backend's own sockets while it boots): a bundle a browser stated
724
+ * never reaches the core. `null` when the prelude is not a JSON object.
725
+ */
726
+ function withBundle(prelude, bundle) {
727
+ let parsed;
728
+ try {
729
+ parsed = JSON.parse(new TextDecoder().decode(prelude));
730
+ }
731
+ catch {
732
+ return null;
733
+ }
734
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
735
+ return null;
736
+ const { bundle: _stated, ...rest } = parsed;
737
+ return new TextEncoder().encode(JSON.stringify(bundle === undefined ? rest : { ...rest, bundle }));
738
+ }
739
+ /** `bundle` is the published bundle every socket the core opens is pinned to. */
740
+ async function openInProcessCore(store, bundle) {
741
+ const backendSecret = randomBytes(32).toString("base64url");
742
+ const adminSecret = randomBytes(32).toString("base64url");
743
+ // The core holds `<path>/jazz.lock` with an OS lock while it's open.
744
+ if (store.kind === "sqlite")
745
+ refuseServerlessDisk(store.path);
746
+ // A SQLite store keeps its app id in its own file: a new one on first
747
+ // start, so the app's identities stay the same across restarts (and
748
+ // restores of the file) without the app naming an id.
749
+ const core = await inProcessCore(store.kind).open({
750
+ ...(store.kind === "sqlite" ? {} : { appId: randomUUID() }),
751
+ backendSecret,
752
+ adminSecret,
753
+ ...(store.kind === "sqlite"
754
+ ? { dataDir: store.path, ...blobOptions(store.blobs) }
755
+ : { inMemory: true }),
756
+ });
757
+ const handle = async (method, path, headers, body) => core.handle(method, path, headers, Buffer.from(body));
758
+ const serverUrl = `http://jazz-${randomUUID()}.invalid`;
759
+ const unregister = registerInProcessTransport(serverUrl, {
760
+ fetch: async (input, init) => {
761
+ const request = new Request(input, init);
762
+ const url = new URL(request.url);
763
+ return coreResponse(await handle(request.method, url.pathname + url.search, [...request.headers].map(([name, value]) => [name, value]), new Uint8Array(await request.arrayBuffer())));
764
+ },
765
+ // This process's own clients: no handshake deadline, as a burst of
766
+ // synchronous writes right after one opens holds its Hello back.
767
+ WebSocket: inProcessWebSocket((_url, onEvent) => pinnedSocket(core.openInProcessSocket(onEvent), bundle)),
768
+ });
769
+ const appId = core.appId;
770
+ const opened = {
771
+ appId,
772
+ ...(core.tokenSecret == null ? {} : { tokenSecret: core.tokenSecret }),
773
+ serverUrl,
774
+ adminSecret,
775
+ backendSecret,
776
+ handle,
777
+ openSocket: (headers, onEvent) => pinnedSocket(core.openSocket(headers, onEvent), bundle),
778
+ async close() {
779
+ unregister();
780
+ await core.close();
781
+ },
782
+ };
783
+ return opened;
784
+ }
785
+ /**
786
+ * Serverless functions have no disk that outlives an instance (or none
787
+ * writable at all), so a sqlite store there loses data silently.
788
+ */
789
+ function refuseServerlessDisk(dir) {
790
+ const host = onVercelHost()
791
+ ? "Vercel"
792
+ : process.env.AWS_LAMBDA_FUNCTION_NAME
793
+ ? "AWS Lambda"
794
+ : process.env.NETLIFY
795
+ ? "Netlify"
796
+ : undefined;
797
+ if (!host)
798
+ return;
799
+ throw new Error(`sqlite({ path: ${JSON.stringify(dir)} }) can't keep data on ${host}: its functions have no lasting disk. ` +
800
+ (host === "Vercel" ? "Use vercel(), whose local store runs sqlite() in dev, or " : "Use ") +
801
+ "remote({ url, appId, secret }) to a sync server or Jazz Cloud.");
802
+ }
803
+ /** The access a request from this process's own clients asks for, by the secret slot it fills. */
804
+ function accessOffered(headers) {
805
+ if (headers.has("x-jazz-admin-secret"))
806
+ return "admin";
807
+ if (headers.has("x-jazz-backend-secret"))
808
+ return "backend";
809
+ return "session";
810
+ }
811
+ /**
812
+ * A core reached over the network. Every request and socket carries the
813
+ * backend credential and the access it states; a core that trusts a workload
814
+ * admits nothing else, and either way the secrets a request offers itself
815
+ * never count next to it. `secrets` fill the secret slots (stand-ins unless
816
+ * the caller holds the real ones).
817
+ */
818
+ function openRemoteCore(appId, target, bundle) {
819
+ const socketUrl = `${target.url.replace(/^http/, "ws")}/apps/${encodeURIComponent(appId)}/ws`;
820
+ const transport = target.transport ?? networkTransport();
821
+ const credentialHeaders = async (access) => {
822
+ const credential = await target.backendCredential();
823
+ if (typeof credential !== "string" || !credential) {
824
+ throw new Error("backendCredential() returned no credential");
825
+ }
826
+ return access === "session"
827
+ ? [[CREDENTIAL_HEADER, credential]]
828
+ : [
829
+ [CREDENTIAL_HEADER, credential],
830
+ [ACCESS_HEADER, access],
831
+ ];
832
+ };
833
+ const withoutStated = (headers) => headers.filter(([name]) => {
834
+ const lower = name.toLowerCase();
835
+ return lower !== CREDENTIAL_HEADER && lower !== ACCESS_HEADER;
836
+ });
837
+ const core = {
838
+ appId,
839
+ serverUrl: `http://jazz-remote-${randomUUID()}.invalid`,
840
+ adminSecret: target.secrets?.adminSecret ?? STAND_IN_SECRET,
841
+ backendSecret: target.secrets?.backendSecret ?? STAND_IN_SECRET,
842
+ async handle(method, path, headers, body, access = "session") {
843
+ const response = await transport.fetch(`${target.url}${path}`, {
844
+ method,
845
+ // The request carries this backend's credential: never to another
846
+ // URL. ("manual", not "error", which workerd doesn't implement.)
847
+ redirect: "manual",
848
+ headers: [...withoutStated(headers), ...(await credentialHeaders(access))].map(([name, value]) => [name, value]),
849
+ ...(method === "GET" || method === "HEAD" ? {} : { body: body }),
850
+ });
851
+ if (response.type === "opaqueredirect" || (response.status >= 300 && response.status < 400)) {
852
+ await response.body?.cancel();
853
+ throw new TypeError(`the Jazz core at ${target.url} answered with a redirect`);
854
+ }
855
+ const replyHeaders = [];
856
+ response.headers.forEach((value, name) => {
857
+ // fetch already decoded the body.
858
+ if (name !== "content-encoding" && name !== "content-length") {
859
+ replyHeaders.push([name, value]);
860
+ }
861
+ });
862
+ return {
863
+ status: response.status,
864
+ headers: replyHeaders,
865
+ body: new Uint8Array(await response.arrayBuffer()),
866
+ };
867
+ },
868
+ openSocket: (_headers, onEvent, access = "session") => pinnedSocket(connect(socketUrl, onEvent, access), bundle),
869
+ async close() {
870
+ unregister();
871
+ },
872
+ };
873
+ // Browsers' own headers stay here: the core sees only this backend.
874
+ function connect(url, onEvent, access) {
875
+ let ws;
876
+ const queued = [];
877
+ let ended = false;
878
+ let markOpened;
879
+ const opened = new Promise((resolve) => {
880
+ markOpened = resolve;
881
+ });
882
+ const finish = (code, reason) => {
883
+ if (ended)
884
+ return;
885
+ ended = true;
886
+ onEvent(null, { kind: "close", code, reason });
887
+ };
888
+ credentialHeaders(access)
889
+ .then((headers) => {
890
+ if (ended)
891
+ return;
892
+ if (target.lifecycle === "hibernate")
893
+ headers.push(["x-jazz-socket-lifecycle", "hibernate"]);
894
+ ws = transport.openWebSocket(url, Object.fromEntries(headers));
895
+ ws.binaryType = "arraybuffer";
896
+ ws.addEventListener("open", () => {
897
+ for (const data of queued.splice(0))
898
+ ws.send(data);
899
+ if (!ended)
900
+ markOpened();
901
+ });
902
+ ws.addEventListener("message", (event) => {
903
+ const data = typeof event.data === "string"
904
+ ? new TextEncoder().encode(event.data)
905
+ : new Uint8Array(event.data);
906
+ onEvent(null, { kind: "message", data });
907
+ });
908
+ ws.addEventListener("close", (event) => finish(event.code, event.reason));
909
+ // A socket that never connects (the core is down or restarting) can
910
+ // report only the error, and stay CONNECTING: without this, the link
911
+ // waits on it forever instead of retrying.
912
+ ws.addEventListener("error", () => {
913
+ finish(1006, "connection to the core failed");
914
+ try {
915
+ ws?.close();
916
+ }
917
+ catch {
918
+ // Already closing.
919
+ }
920
+ });
921
+ })
922
+ // A failing credential hook, or a socket that can't even be created.
923
+ .catch((error) => finish(1011, error instanceof Error ? error.message : "no backend credential"));
924
+ return {
925
+ send(data) {
926
+ if (ended)
927
+ return false;
928
+ if (ws?.readyState === 1)
929
+ ws.send(data);
930
+ else
931
+ queued.push(data);
932
+ return true;
933
+ },
934
+ close() {
935
+ ended = true;
936
+ ws?.close();
937
+ },
938
+ opened,
939
+ };
940
+ }
941
+ // This process's own clients (the backend's session) reach the core
942
+ // through an in-process origin, so they present the credential too.
943
+ const unregister = registerInProcessTransport(core.serverUrl, {
944
+ fetch: async (input, init) => {
945
+ const request = new Request(input, init);
946
+ const url = new URL(request.url);
947
+ const headers = [];
948
+ request.headers.forEach((value, name) => headers.push([name, value]));
949
+ return coreResponse(await core.handle(request.method, url.pathname + url.search, headers, new Uint8Array(await request.arrayBuffer()), accessOffered(request.headers)));
950
+ },
951
+ WebSocket: inProcessWebSocket((url, onEvent) => {
952
+ const { pathname, search } = new URL(url);
953
+ return pinnedSocket(connect(`${target.url.replace(/^http/, "ws")}${pathname}${search}`, onEvent, "backend"), bundle);
954
+ }),
955
+ });
956
+ return core;
957
+ }
958
+ /**
959
+ * A request `authenticate` names no user for: what an app answers with 401.
960
+ * (A throwing `authenticate` passes its own error through instead.)
961
+ */
962
+ function signedOut(operation) {
963
+ return new RequestAuthenticationError(`${operation}: the request has no signed-in user`, {
964
+ code: "signed_out",
965
+ });
966
+ }
967
+ /** How long `close()` waits for pending writes to reach the core. */
968
+ const CLOSE_SYNC_TIMEOUT_MS = 10_000;
969
+ function jazzSettings(options) {
970
+ if (options.recheckSeconds !== undefined)
971
+ throw new Error("createJazz: recheckSeconds was removed. A sync session now lasts until the expiresAt your authenticate returns, and then authenticates again on its client's new connection; to end a user's sessions at once, call jazz.revokeUser(userId).");
972
+ const reuse = options.streamAuthReuseSeconds;
973
+ if (reuse !== undefined && !(typeof reuse === "number" && reuse >= 0 && Number.isFinite(reuse)))
974
+ throw new Error(`createJazz: streamAuthReuseSeconds must be a number of seconds, 0 or more; got ${JSON.stringify(reuse)}`);
975
+ const basePath = (options.basePath ?? DEFAULT_BASE_PATH).replace(/\/+$/, "");
976
+ const publicUrls = [options.publicUrl ?? []].flat().map((value) => {
977
+ try {
978
+ // The same form a browser client scopes itself by (`clientScope`).
979
+ if (!/^(https?|wss?):\/\//.test(value))
980
+ throw new Error("relative");
981
+ return endpointScope(value);
982
+ }
983
+ catch {
984
+ throw new Error(`createJazz: publicUrl ${JSON.stringify(value)} is not an absolute URL like "https://app.example.com/jazz"`);
985
+ }
986
+ });
987
+ const allowedOrigins = new Set((options.allowedOrigins ?? []).map((origin) => {
988
+ let parsed;
989
+ try {
990
+ parsed = new URL(origin).origin;
991
+ }
992
+ catch {
993
+ // Not a URL: refused below.
994
+ }
995
+ // "localhost:3000" parses with an opaque "null" origin, which would let
996
+ // sandboxed iframes and file:// pages through.
997
+ if (!parsed || parsed === "null") {
998
+ throw new Error(`createJazz: allowedOrigins entry ${JSON.stringify(origin)} is not an origin like "https://app.example.com"`);
999
+ }
1000
+ return parsed;
1001
+ }));
1002
+ if ("appId" in options) {
1003
+ throw new Error("createJazz(): appId moved to the store: remote({ url, appId, secret }) names the app it serves, and sqlite(), memory() and vercel() keep their own id.");
1004
+ }
1005
+ return { basePath, publicUrls, allowedOrigins };
1006
+ }
1007
+ /** The store this process runs: `vercel()` outside a Vercel deployment runs its `local` store. */
1008
+ function runningStore(store) {
1009
+ return store.kind === "vercel" && !onVercelDeployment() ? store.local : store;
1010
+ }
1011
+ /** The line a store logs when it opens (a `vercel()` core logs its own). */
1012
+ function storeOpenedLine(store, provider) {
1013
+ if (store.kind === "sqlite")
1014
+ return `jazz: store sqlite at ${store.path}`;
1015
+ if (store.kind === "memory")
1016
+ return "jazz: store memory (its data lasts as long as this process)";
1017
+ return `jazz: store ${provider} at ${store.url} (app ${store.appId})`;
1018
+ }
1019
+ /**
1020
+ * Open `store` and apply the schema, migrations and permissions `options`
1021
+ * declare to its core.
1022
+ */
1023
+ async function openJazz(initial, opening) {
1024
+ const store = opening.kind === "durableObjects" ? await durableObjectCore(opening) : opening;
1025
+ let options = initial;
1026
+ let { basePath, publicUrls, allowedOrigins } = jazzSettings(options);
1027
+ // The bundle this backend published: every socket to the core carries it,
1028
+ // and the core governs this backend's sessions by its permissions alone.
1029
+ let pin;
1030
+ const bundle = () => pin;
1031
+ const core = store.kind === "remote"
1032
+ ? openRemoteCore(store.appId, store, bundle)
1033
+ : store.kind === "vercel"
1034
+ ? await openVercelCore({
1035
+ options: store.options,
1036
+ // The function's OIDC token is the core's only credential.
1037
+ openRemote: ({ appId, url, backendCredential }) => openRemoteCore(appId, { url, backendCredential }, bundle),
1038
+ })
1039
+ : await openInProcessCore(store, bundle);
1040
+ // A vercel() core says which it opened itself.
1041
+ if (store.kind !== "vercel")
1042
+ logStoreOpened(storeOpenedLine(store, opening.kind));
1043
+ const appId = core.appId;
1044
+ const issuer = BACKEND_USER_ISSUER;
1045
+ // An in-memory store's agent tokens last as long as its data: this process.
1046
+ const memoryTokenSecret = newTokenSecret();
1047
+ /** Publish `next`'s bundle: what it is pinned by. Publishing one already published changes nothing. */
1048
+ const publish = async (next) => {
1049
+ await compiledPermissions(next);
1050
+ return applyBundle(core.serverUrl, {
1051
+ ...next,
1052
+ loaded: compiled.get(next),
1053
+ appId,
1054
+ adminSecret: core.adminSecret,
1055
+ quiet: testHarnessOptions.has(next),
1056
+ });
1057
+ };
1058
+ /** Publish `next`'s bundle and open the backend's own session on it. */
1059
+ async function backendSession(next, published) {
1060
+ pin = published ?? (await publish(next));
1061
+ const session = await openJazzSession({
1062
+ appId,
1063
+ app: next.app,
1064
+ permissions: await compiledPermissions(next),
1065
+ serverUrl: core.serverUrl,
1066
+ driver: { type: "memory" },
1067
+ initial: { backendSecret: core.backendSecret },
1068
+ });
1069
+ const opened = session.getSnapshot();
1070
+ if (opened.status !== "ready" || !opened.client) {
1071
+ await session.close();
1072
+ throw opened.error ?? new Error(`Jazz backend session did not open (${opened.status})`);
1073
+ }
1074
+ return { session, client: opened.client };
1075
+ }
1076
+ let session;
1077
+ let backend;
1078
+ try {
1079
+ ({ session, client: backend } = await backendSession(options));
1080
+ }
1081
+ catch (error) {
1082
+ await core.close();
1083
+ throw store.kind === "remote" ? unreachableCore(store.url, error) : error;
1084
+ }
1085
+ let backendClients = backendClientVerifier(options.backendClients ?? []);
1086
+ /**
1087
+ * A later `createJazz` for this store (a dev server's hot reload): publish
1088
+ * its bundle, move the backend's own database to it, and read its options
1089
+ * from now on. Open sync sessions stay; the core reconnects those pinned
1090
+ * to the old bundle.
1091
+ */
1092
+ async function reload(next) {
1093
+ const settings = jazzSettings(next);
1094
+ inspectorSettings(next.inspector ?? NO_INSPECTOR_OPTIONS);
1095
+ // The same app and permissions (a reload of a module that imports them
1096
+ // unchanged, or a hot reload that rebuilt equal ones): the bundle, and
1097
+ // the backend's session with its writes and `forReqUser` dbs, stay.
1098
+ if (next.app !== options.app || next.permissions !== options.permissions) {
1099
+ const published = await publish(next);
1100
+ if (published !== pin) {
1101
+ const previousPin = pin;
1102
+ let fresh;
1103
+ try {
1104
+ fresh = await backendSession(next, published);
1105
+ }
1106
+ catch (error) {
1107
+ pin = previousPin;
1108
+ throw error;
1109
+ }
1110
+ retire(session);
1111
+ ({ session, client: backend } = fresh);
1112
+ }
1113
+ }
1114
+ options = next;
1115
+ ({ basePath, publicUrls, allowedOrigins } = settings);
1116
+ backendClients = backendClientVerifier(next.backendClients ?? []);
1117
+ upgradesSockets = attached || (next.upgradesSockets ?? false);
1118
+ }
1119
+ /**
1120
+ * Sessions a reload replaced. Each stays open for
1121
+ * `RETIRED_SESSION_GRACE_MS`, so the writes it has in flight and the
1122
+ * `forReqUser` dbs requests still hold finish, then closes (draining its
1123
+ * writes); a close of this Jazz closes those left.
1124
+ */
1125
+ const retiring = new Set();
1126
+ function retire(old) {
1127
+ let closed;
1128
+ const closeOld = () => {
1129
+ clearTimeout(timer);
1130
+ return (closed ??= old
1131
+ .close()
1132
+ .catch((error) => console.error("jazz: a retired session did not close", error))
1133
+ .finally(() => retiring.delete(closeOld)));
1134
+ };
1135
+ const timer = setTimeout(closeOld, RETIRED_SESSION_GRACE_MS);
1136
+ timer.unref?.();
1137
+ retiring.add(closeOld);
1138
+ }
1139
+ // An `authenticate` that returns expired answers, or none at all, is a
1140
+ // bug in the app: said once per process.
1141
+ let warnedExpiredAnswer = false;
1142
+ function warnExpiredAnswer() {
1143
+ if (warnedExpiredAnswer)
1144
+ return;
1145
+ warnedExpiredAnswer = true;
1146
+ console.error("createJazz: authenticate named a user with an expiresAt in the past, so Jazz treats them as signed out. Return the expiry of the session the user is signed in with (the one a sign-out ends), in Unix seconds, not of a short-lived access token.");
1147
+ }
1148
+ let warnedMissingExpiry = false;
1149
+ function warnMissingExpiry(error) {
1150
+ if (warnedMissingExpiry)
1151
+ return;
1152
+ warnedMissingExpiry = true;
1153
+ console.error(error.message);
1154
+ }
1155
+ /**
1156
+ * Who sent `request`: a scoped backend client's user, or the user the
1157
+ * app's own `authenticate` names. A trusted backend client has no user.
1158
+ */
1159
+ async function authenticate(request) {
1160
+ const answer = await requestAnswer(request);
1161
+ return answer === "device-account" ? null : answer;
1162
+ }
1163
+ /**
1164
+ * {@link authenticate}, telling apart a request `authenticate` let in as a
1165
+ * device account (`acceptDeviceAccounts`) from one it names no one for.
1166
+ * Only the backend's own API (`forReqUser` and friends) needs that: a
1167
+ * socket's guest is decided from its prelude instead (`admitPrelude`).
1168
+ */
1169
+ async function requestAnswer(request) {
1170
+ const client = await backendClients.resolve(request);
1171
+ if (client !== null)
1172
+ return client !== "refused" && client.kind === "user"
1173
+ ? { ...client.user, expiresAt: client.expiresAt }
1174
+ : null;
1175
+ const answer = await askAuthenticate(request);
1176
+ if (answer === null)
1177
+ return null;
1178
+ if (isDeviceAccountsAnswer(answer))
1179
+ return "device-account";
1180
+ const user = withCheckedExpiry(checkedUser(answer));
1181
+ // An answer that has already expired names no one, here and in every
1182
+ // other place that asks (who is signed in, sign-in, forReqUser), so a
1183
+ // client can't be told it is signed in while its sync is refused.
1184
+ if (user.expiresAt * 1000 <= Date.now()) {
1185
+ warnExpiredAnswer();
1186
+ return null;
1187
+ }
1188
+ return user;
1189
+ }
1190
+ async function askAuthenticate(request) {
1191
+ if (!options.authenticate)
1192
+ return null;
1193
+ try {
1194
+ return (await options.authenticate(request)) ?? null;
1195
+ }
1196
+ catch (error) {
1197
+ // The app's own code failed (a missing auth secret, its session store
1198
+ // down). Its own API calls (forReqUser) get the error as it is; a Jazz
1199
+ // route answers 500 and logs it, rather than reject (see `handle`).
1200
+ const thrown = isObject(error) ? error : new Error(String(error));
1201
+ thrownByAuthenticate.add(thrown);
1202
+ throw thrown;
1203
+ }
1204
+ }
1205
+ /** Whether the app lets `request` in as a device account (`acceptDeviceAccounts`). */
1206
+ let warnedGuestsOff = false;
1207
+ async function acceptsGuest(request) {
1208
+ const answer = await askAuthenticate(request);
1209
+ if (isDeviceAccountsAnswer(answer))
1210
+ return true;
1211
+ // A user is signed in on this browser too: one who just signed up, whose
1212
+ // guest still uploads its writes before it links to them. A guest is
1213
+ // bound to its own key, never to that user, and whether the app lets
1214
+ // guests in doesn't depend on who else is signed in: ask as the request
1215
+ // would be without the user's credentials.
1216
+ if (answer && isDeviceAccountsAnswer(await askAuthenticate(withoutCredentials(request))))
1217
+ return true;
1218
+ if (!warnedGuestsOff) {
1219
+ warnedGuestsOff = true;
1220
+ console.warn("createJazz: refused a device account. To let guests sync, return acceptDeviceAccounts(request) from authenticate for them.");
1221
+ }
1222
+ return false;
1223
+ }
1224
+ /** Say once that the core turns every device account away, whatever `authenticate` says. */
1225
+ let warnedGuestsOffOnCore = false;
1226
+ function warnGuestsOffOnCore() {
1227
+ if (warnedGuestsOffOnCore)
1228
+ return;
1229
+ warnedGuestsOffOnCore = true;
1230
+ console.error("createJazz: the core refuses device accounts (local_first_auth_disabled), so they can't sync or link. It runs an older jazz-tools with device accounts off: upgrade it (a vercel() core is restarted on the newer version by the next deployment), or turn them on for a Jazz Cloud app with `jazz-tools apps auth set <appId> --allow-device-accounts true`.");
1231
+ }
1232
+ let warnedNoCoreRevocation = false;
1233
+ function warnNoCoreRevocation() {
1234
+ if (warnedNoCoreRevocation)
1235
+ return;
1236
+ warnedNoCoreRevocation = true;
1237
+ console.error("createJazz: the core has no session revocation (it runs an older jazz-tools), so jazz.revokeUser ends only the sessions this backend instance serves; sessions on other instances end at their expiresAt. Upgrade the core (a vercel() core is restarted on the newer version by the next deployment).");
1238
+ }
1239
+ /** One admin account request to the core: this backend vouches for the identities. */
1240
+ async function adminAccounts(operation, body) {
1241
+ const parsed = (await adminAccountsCall(operation, body));
1242
+ return { ...parsed, account: String(parsed.account) };
1243
+ }
1244
+ async function adminAccountsCall(operation, body) {
1245
+ const response = await core.handle("POST", `/apps/${encodeURIComponent(accountAppId(appId))}/admin/accounts/${operation}`, [
1246
+ ["x-jazz-admin-secret", core.adminSecret],
1247
+ ["content-type", "application/json"],
1248
+ ], new TextEncoder().encode(JSON.stringify(body)), "admin");
1249
+ const text = new TextDecoder().decode(response.body);
1250
+ if (response.status !== 200) {
1251
+ throw Object.assign(new Error(`Jazz account ${operation} failed (${response.status}): ${text}`), {
1252
+ status: response.status,
1253
+ code: text.trim(),
1254
+ });
1255
+ }
1256
+ return JSON.parse(text);
1257
+ }
1258
+ /**
1259
+ * The keys this backend signs its own statements with (link challenges,
1260
+ * session renewal tickets), one per label: derived from the app's secret
1261
+ * when this backend holds it, else from the backend signing key the core
1262
+ * hands it (jazz#5553), so every instance of the backend shares them.
1263
+ */
1264
+ const signingKey = backendSigningKeys({
1265
+ appId: accountAppId(appId),
1266
+ secret: appSecretOf(store, core),
1267
+ fetchShared: async () => {
1268
+ const response = await core.handle("GET", `/apps/${encodeURIComponent(accountAppId(appId))}/${BACKEND_SIGNING_KEY_ROUTE}`, [["x-jazz-admin-secret", core.adminSecret]], new Uint8Array(), "admin");
1269
+ // A core from before the route.
1270
+ if (response.status === 404)
1271
+ return null;
1272
+ const text = new TextDecoder().decode(response.body);
1273
+ if (response.status !== 200) {
1274
+ throw Object.assign(new Error(`Jazz backend signing key failed (${response.status}): ${text}`), { status: response.status, code: text.trim() });
1275
+ }
1276
+ const { key } = JSON.parse(text);
1277
+ const bytes = typeof key === "string" ? Buffer.from(key, "base64url") : undefined;
1278
+ if (!bytes || bytes.length !== 32) {
1279
+ throw new Error("Jazz backend signing key failed: the core's answer holds no 32-byte key");
1280
+ }
1281
+ return bytes;
1282
+ },
1283
+ });
1284
+ const identity = (userId) => ({ issuer, subject: userId });
1285
+ // A user's account never changes once assigned (linking only adds
1286
+ // identities to an account), so the core is asked once per user for a
1287
+ // while, not on every sign-in, socket and request. Only assignments are
1288
+ // cached: a user without an account may get one at any moment.
1289
+ const accounts = new Map();
1290
+ const ACCOUNT_CACHE_LIMIT = 10_000;
1291
+ function remember(userId, account) {
1292
+ if (accounts.size >= ACCOUNT_CACHE_LIMIT) {
1293
+ accounts.delete(accounts.keys().next().value);
1294
+ }
1295
+ accounts.set(userId, {
1296
+ account,
1297
+ until: Date.now() + (options.sessionTtlSeconds ?? 3600) * 1000,
1298
+ });
1299
+ return account;
1300
+ }
1301
+ /**
1302
+ * The user's account, or null while they have none. Never creates one:
1303
+ * only a client's sign-in (`backend-sign-in`), a guest's link
1304
+ * (`backend-link`) and `createAccountFor` do, so a device account can
1305
+ * still link to a user the backend has only looked up or acted for (V9).
1306
+ */
1307
+ async function existingAccountOf(userId) {
1308
+ const cached = accounts.get(userId);
1309
+ if (cached && cached.until > Date.now())
1310
+ return cached.account;
1311
+ try {
1312
+ const { account } = await adminAccounts("resolve", { identity: identity(userId) });
1313
+ return remember(userId, account);
1314
+ }
1315
+ catch (error) {
1316
+ // Only the core's own "no account for this identity" answer: any other
1317
+ // 404 (an unknown app, a missing route) is a server error, not a user
1318
+ // without an account.
1319
+ const { status, code } = error;
1320
+ if (status === 404 && code === "identity_not_assigned")
1321
+ return null;
1322
+ throw error;
1323
+ }
1324
+ }
1325
+ /** The user's account, created if they have none (a sign-in, or `createAccountFor`). */
1326
+ async function accountOf(userId) {
1327
+ const cached = accounts.get(userId);
1328
+ if (cached && cached.until > Date.now())
1329
+ return cached.account;
1330
+ const { account } = await adminAccounts("login-or-register", { identity: identity(userId) });
1331
+ return remember(userId, account);
1332
+ }
1333
+ /** The user's session, on the account they already have. */
1334
+ async function sessionFor(user, caller) {
1335
+ const account = await existingAccountOf(user.userId);
1336
+ if (account === null)
1337
+ throw new NoJazzAccountError(user.userId, caller);
1338
+ return {
1339
+ account_id: account,
1340
+ issuer,
1341
+ user_id: user.userId,
1342
+ claims: user.claims ?? {},
1343
+ authMode: "external",
1344
+ };
1345
+ }
1346
+ async function linkIdentity(link) {
1347
+ if (link.from === link.to)
1348
+ throw new Error("linkIdentity: from and to are the same identity");
1349
+ const { account } = await adminAccounts("link", {
1350
+ from: identity(link.from),
1351
+ to: identity(link.to),
1352
+ });
1353
+ return { account };
1354
+ }
1355
+ /**
1356
+ * The account sign-in a browser makes with only the app's own session: the
1357
+ * backend's `authenticate` names the user, and the core resolves (or
1358
+ * creates) their account.
1359
+ */
1360
+ async function backendSignIn(request) {
1361
+ if (request.method !== "POST")
1362
+ return new Response(null, { status: 405 });
1363
+ const user = await authenticate(request);
1364
+ if (!user)
1365
+ return new Response("signed_out", { status: 401 });
1366
+ const account = await accountOf(user.userId);
1367
+ const expiresAt = Math.floor(Date.now() / 1000) + (options.sessionTtlSeconds ?? 3600);
1368
+ return Response.json({ account, identity: identity(user.userId), claims: user.claims ?? {}, expiresAt }, { headers: { "Cache-Control": "no-store" } });
1369
+ }
1370
+ /**
1371
+ * Who `request`'s user is, without changing anything: the user
1372
+ * `authenticate` names, and whether the core already holds an account for
1373
+ * them. A browser's session asks this to follow the backend; only a sign-in
1374
+ * (`backend-sign-in`) or a link (`backend-link`) assigns an account, so a
1375
+ * device account whose user has none yet can still link to them. No one
1376
+ * signed in answers 200 `{ user: null }`, not 401.
1377
+ */
1378
+ async function backendUser(request) {
1379
+ if (request.method !== "POST")
1380
+ return new Response(null, { status: 405 });
1381
+ const user = await authenticate(request);
1382
+ // No one signed in is an answer, not a refused request: 200, so a
1383
+ // signed-out page load logs no red 4xx in devtools. The body has no
1384
+ // `identity`, which every client (alpha.60 on) reads as signed out.
1385
+ // Clients still read a 401 as signed out too, for older backends.
1386
+ if (!user)
1387
+ return Response.json({ user: null }, { headers: { "Cache-Control": "no-store" } });
1388
+ let account;
1389
+ try {
1390
+ account = await existingAccountOf(user.userId);
1391
+ }
1392
+ catch (error) {
1393
+ // The core refuses this identity (it was revoked): say so, as the
1394
+ // core does, rather than fail as a server error.
1395
+ if (error.status === 403)
1396
+ return new Response("identity_not_authorized", { status: 403 });
1397
+ throw error;
1398
+ }
1399
+ // A browser renewing its open sync session in place (see
1400
+ // `session-renewal-wire.ts`) gets a ticket for it, on this answer.
1401
+ const renewing = request.headers.get(SESSION_RENEWAL_HEADER);
1402
+ let renewal;
1403
+ if (renewing && renewing.length <= 128) {
1404
+ // Renewal is an extra: without a ticket (the signing key couldn't be
1405
+ // had from the core) the session reconnects at its expiry instead.
1406
+ renewal = await issueRenewalTicket(user, renewing).catch((error) => {
1407
+ console.error("jazz: couldn't issue a session renewal ticket", error);
1408
+ return undefined;
1409
+ });
1410
+ }
1411
+ return Response.json({
1412
+ account,
1413
+ identity: identity(user.userId),
1414
+ claims: user.claims ?? {},
1415
+ ...(renewal ? { renewal } : {}),
1416
+ }, { headers: { "Cache-Control": "no-store" } });
1417
+ }
1418
+ /**
1419
+ * Renewal tickets: what lets a sync session be extended over its open
1420
+ * socket. The browser's ordinary request (which carried its cookies, maybe
1421
+ * refreshed by `refresh`) may reach another instance than the one holding
1422
+ * the socket, so the answer travels back through the browser, signed with
1423
+ * a key every instance of this app derives from the core's admin secret
1424
+ * (or, without one, a key of this instance's own: see below).
1425
+ * A ticket names the user, the one session it renews, the claims it was
1426
+ * issued with and the new expiry, and is good for a minute.
1427
+ */
1428
+ // The key is `signingKey`'s (see there): every instance of this backend
1429
+ // has it, except behind an older core reached with a backend credential
1430
+ // alone, where each instance signs with a key of its own and a ticket
1431
+ // renews only a socket the instance that issued it holds. Elsewhere, the
1432
+ // session reconnects at its expiry, as without renewal.
1433
+ const RENEWAL_TICKET_TTL_SECONDS = 60;
1434
+ const renewalKey = () => signingKey("jazz-session-renewal-v1");
1435
+ const renewalMac = async (payload) => createHmac("sha256", await renewalKey())
1436
+ .update(payload)
1437
+ .digest("base64url");
1438
+ const claimsDigest = async (claims) => createHmac("sha256", await renewalKey())
1439
+ .update(stableJson(claims ?? {}))
1440
+ .digest("base64url");
1441
+ async function issueRenewalTicket(user, session) {
1442
+ const payload = Buffer.from(JSON.stringify({
1443
+ v: 1,
1444
+ sub: user.userId,
1445
+ ses: session,
1446
+ cl: await claimsDigest(user.claims),
1447
+ until: user.expiresAt,
1448
+ exp: Math.floor(Date.now() / 1000) + RENEWAL_TICKET_TTL_SECONDS,
1449
+ })).toString("base64url");
1450
+ return `${payload}.${await renewalMac(payload)}`;
1451
+ }
1452
+ /**
1453
+ * The new expiry (Unix seconds) a ticket gives session `session` of
1454
+ * `userId` admitted with `claims`, when this backend issued it for that
1455
+ * session and it is still fresh; else null.
1456
+ */
1457
+ async function readRenewalTicket(ticket, session, userId, claims) {
1458
+ const [payload, mac, extra] = ticket.split(".");
1459
+ if (!payload || !mac || extra !== undefined)
1460
+ return null;
1461
+ const expected = Buffer.from(await renewalMac(payload));
1462
+ const given = Buffer.from(mac);
1463
+ if (expected.length !== given.length || !timingSafeEqual(expected, given))
1464
+ return null;
1465
+ let read;
1466
+ try {
1467
+ read = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
1468
+ }
1469
+ catch {
1470
+ return null;
1471
+ }
1472
+ const now = Date.now() / 1000;
1473
+ if (read.v !== 1 ||
1474
+ read.sub !== userId ||
1475
+ read.ses !== session ||
1476
+ read.cl !== (await claimsDigest(claims)) ||
1477
+ typeof read.exp !== "number" ||
1478
+ read.exp <= now ||
1479
+ typeof read.until !== "number" ||
1480
+ !Number.isFinite(read.until) ||
1481
+ read.until <= now) {
1482
+ return null;
1483
+ }
1484
+ return read.until;
1485
+ }
1486
+ /**
1487
+ * Link challenges: a guest links only on a proof made for one challenge,
1488
+ * never on its sync token, so a leaked token can't link it to someone
1489
+ * else. A challenge names the user it links to and expires quickly; it is
1490
+ * signed with a key only this app's backend holds (`signingKey`'s, which
1491
+ * every instance of it shares), and its nonce becomes the link's
1492
+ * single-use intent id at the core, so a proof works once.
1493
+ */
1494
+ const LINK_CHALLENGE_TTL_SECONDS = 120;
1495
+ const challengeMac = async (payload) => createHmac("sha256", await signingKey("jazz-link-challenge-v1"))
1496
+ .update(payload)
1497
+ .digest("base64url");
1498
+ async function issueLinkChallenge(userId) {
1499
+ const expiresAt = Math.floor(Date.now() / 1000) + LINK_CHALLENGE_TTL_SECONDS;
1500
+ const payload = Buffer.from(JSON.stringify({ v: 1, sub: userId, nonce: randomUUID(), exp: expiresAt })).toString("base64url");
1501
+ return { challenge: `${payload}.${await challengeMac(payload)}`, expiresAt };
1502
+ }
1503
+ /** The nonce of a challenge this backend issued for `userId`, still fresh; else null. */
1504
+ async function readLinkChallenge(challenge, userId) {
1505
+ if (typeof challenge !== "string" || challenge.length > 1024)
1506
+ return null;
1507
+ const [payload, mac, extra] = challenge.split(".");
1508
+ if (!payload || !mac || extra !== undefined)
1509
+ return null;
1510
+ const expected = Buffer.from(await challengeMac(payload));
1511
+ const given = Buffer.from(mac);
1512
+ if (expected.length !== given.length || !timingSafeEqual(expected, given))
1513
+ return null;
1514
+ let claims;
1515
+ try {
1516
+ claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
1517
+ }
1518
+ catch {
1519
+ return null;
1520
+ }
1521
+ if (claims.v !== 1 ||
1522
+ claims.sub !== userId ||
1523
+ typeof claims.nonce !== "string" ||
1524
+ typeof claims.exp !== "number" ||
1525
+ claims.exp <= Date.now() / 1000) {
1526
+ return null;
1527
+ }
1528
+ return claims.nonce;
1529
+ }
1530
+ /** A challenge for the guest to sign before it links to the signed-in user. */
1531
+ async function backendLinkChallenge(request) {
1532
+ if (request.method !== "POST")
1533
+ return new Response(null, { status: 405 });
1534
+ const user = await authenticate(request);
1535
+ if (!user)
1536
+ return new Response("signed_out", { status: 401 });
1537
+ return Response.json(await issueLinkChallenge(user.userId), {
1538
+ headers: { "Cache-Control": "no-store" },
1539
+ });
1540
+ }
1541
+ /**
1542
+ * A guest who just signed up: link their device account's identity to the
1543
+ * user `authenticate` now names, so the account and its data carry over.
1544
+ * The device account proves itself by signing a challenge issued for this user
1545
+ * (see {@link issueLinkChallenge}).
1546
+ */
1547
+ async function backendLink(request) {
1548
+ if (request.method !== "POST")
1549
+ return new Response(null, { status: 405 });
1550
+ const user = await authenticate(request);
1551
+ if (!user)
1552
+ return new Response("signed_out", { status: 401 });
1553
+ let body;
1554
+ try {
1555
+ body = (await request.json());
1556
+ }
1557
+ catch {
1558
+ return new Response("local_first_proof_required", { status: 400 });
1559
+ }
1560
+ const nonce = await readLinkChallenge(body?.challenge, user.userId);
1561
+ if (!nonce)
1562
+ return new Response("invalid_link_challenge", { status: 400 });
1563
+ let guest;
1564
+ try {
1565
+ const proven = verifyChallenge(String(body.proof ?? ""), body.challenge);
1566
+ guest = { issuer: proven.issuer, subject: proven.subject };
1567
+ }
1568
+ catch {
1569
+ return new Response("invalid_local_first_proof", { status: 401 });
1570
+ }
1571
+ // The guest's account follows from its key and the namespace it was
1572
+ // founded in: this app's id, or one of this endpoint's URLs for an
1573
+ // app-less client. Any other namespace is another app's guest.
1574
+ const founding = linkAudience(request, body.audience);
1575
+ if (!founding)
1576
+ return new Response("invalid_local_first_proof", { status: 401 });
1577
+ const account = localFirstAccountId(founding.endpoint ?? appId, guest.subject);
1578
+ const userIs = async (expected) => (await adminAccounts("resolve", { identity: identity(user.userId) })).account === expected;
1579
+ let guestRevoked = false;
1580
+ try {
1581
+ try {
1582
+ await adminAccounts("found-local-first", {
1583
+ identity: guest,
1584
+ ...(founding.endpoint !== undefined ? { audience: founding.endpoint } : {}),
1585
+ });
1586
+ }
1587
+ catch (error) {
1588
+ // A guest key an earlier link retired: only that link's own user
1589
+ // gets an answer (the retry of a link whose response was lost).
1590
+ if (error.status !== 403 ||
1591
+ error.code !== IDENTITY_NOT_AUTHORIZED ||
1592
+ !(await userIs(account)))
1593
+ throw error;
1594
+ guestRevoked = true;
1595
+ }
1596
+ if (!guestRevoked) {
1597
+ try {
1598
+ await adminAccounts("link", { from: guest, to: identity(user.userId), nonce });
1599
+ }
1600
+ catch (error) {
1601
+ // Linking is idempotent for this guest and this user: when the user
1602
+ // already belongs to the guest's account (an earlier link went
1603
+ // through, then perhaps its revoke failed, or another tab's link
1604
+ // won the race and revoked the key since), this link is done. A
1605
+ // used challenge (the core refuses its nonce first) and a user of
1606
+ // another account are still refused.
1607
+ const { status, code } = error;
1608
+ const retired = status === 403 && code === IDENTITY_NOT_AUTHORIZED;
1609
+ if ((status !== 409 && !retired) || !(await userIs(account)))
1610
+ throw error;
1611
+ // Refused for a retired key: the link that won already retired it.
1612
+ if (retired)
1613
+ guestRevoked = true;
1614
+ }
1615
+ }
1616
+ }
1617
+ catch (error) {
1618
+ const status = error.status;
1619
+ // A core that admits no local-first accounts refuses every guest, not
1620
+ // this user's link: say that, not that the user has another account.
1621
+ if (error.code === LOCAL_FIRST_AUTH_DISABLED) {
1622
+ warnGuestsOffOnCore();
1623
+ // A setup problem on the backend's side, not a refusal of this link:
1624
+ // 503, so the client tries again later.
1625
+ return new Response(LOCAL_FIRST_AUTH_DISABLED, { status: 503 });
1626
+ }
1627
+ // Only the core's own refusals refuse the link for good: an invalid
1628
+ // link intent (400), a retired or foreign identity (403), a user with
1629
+ // no account to check (404), an identity of another account (409).
1630
+ // Its reason stays on the backend.
1631
+ if (status === 400 || status === 403 || status === 404 || status === 409)
1632
+ return new Response("link_refused", { status: 409 });
1633
+ // Anything else (the core down or failing, its credential check
1634
+ // refusing this backend mid-rotation, a proxy's 408 or 429) may pass on
1635
+ // a retry, so say so rather than strand the guest.
1636
+ console.error("Jazz: linking a guest failed on the core", error);
1637
+ return new Response("account_registry_unavailable", { status: 503 });
1638
+ }
1639
+ if (options.guestKeyAfterLink === "revoke" && !guestRevoked) {
1640
+ // The link already stands. If the revoke fails, the guest key stays
1641
+ // usable until the browser retries the link, which is idempotent and
1642
+ // revokes then: a server error, logged here, not a silent success.
1643
+ const revoked = await core.handle("POST", `/apps/${encodeURIComponent(accountAppId(appId))}/admin/accounts/revoke`, [
1644
+ ["x-jazz-admin-secret", core.adminSecret],
1645
+ ["content-type", "application/json"],
1646
+ ], new TextEncoder().encode(JSON.stringify({ approver: identity(user.userId), target: guest })), "admin");
1647
+ if (revoked.status !== 204) {
1648
+ console.error(`Jazz: revoking the guest key after a link failed (${revoked.status}): ${new TextDecoder().decode(revoked.body)}`);
1649
+ return new Response("guest_key_revoke_failed", { status: 500 });
1650
+ }
1651
+ }
1652
+ const expiresAt = Math.floor(Date.now() / 1000) + (options.sessionTtlSeconds ?? 3600);
1653
+ return Response.json({ account, identity: identity(user.userId), claims: user.claims ?? {}, expiresAt }, { headers: { "Cache-Control": "no-store" } });
1654
+ }
1655
+ /** The sessions this instance serves, for the Inspector's `sessions`. */
1656
+ const liveSessions = new Set();
1657
+ /** Thin sessions' transaction clients running now. */
1658
+ let thinClients = 0;
1659
+ /**
1660
+ * The client a thin session's transactions are served by (SPEC 8.14):
1661
+ * in memory, linked to the core as the session, for the app's schema.
1662
+ * Refused for a thin client built against another version of it, and
1663
+ * `null` past the cap.
1664
+ */
1665
+ function openThinClient(schema, link) {
1666
+ if (thinClients >= MAX_THIN_TRANSACTION_CLIENTS)
1667
+ return null;
1668
+ // The session's own link: the socket the relay opens for it, with the
1669
+ // prelude the backend admitted for it, as the session's own socket is
1670
+ // opened (a guest vouched for an endpoint keeps that vouching).
1671
+ const webSocket = inProcessWebSocket((_url, onEvent) => withPrelude(core.openSocket(link.headers, onEvent, link.access), link.prelude));
1672
+ const client = openThinSessionClient({
1673
+ appId,
1674
+ schema,
1675
+ serverUrl: core.serverUrl,
1676
+ prelude: link.prelude,
1677
+ trusted: link.trusted,
1678
+ webSocket,
1679
+ migrations: shippedMigrations(resolveSchemaSource(options.app)),
1680
+ });
1681
+ thinClients += 1;
1682
+ let closed = false;
1683
+ return {
1684
+ serve: (request) => client.serve(request),
1685
+ async close() {
1686
+ if (closed)
1687
+ return;
1688
+ closed = true;
1689
+ try {
1690
+ await client.close();
1691
+ }
1692
+ finally {
1693
+ thinClients -= 1;
1694
+ }
1695
+ },
1696
+ };
1697
+ }
1698
+ function openClientSession(request, onEvent, transport) {
1699
+ // The core socket opens once the prelude is admitted, with the access
1700
+ // that admission needs: a vouched user's session is the backend's, and
1701
+ // so is the endpoint it vouches for on a guest's behalf; a guest signed
1702
+ // for the app itself rides on its own token alone.
1703
+ let socket;
1704
+ let ended = false;
1705
+ let userId;
1706
+ let trusted = false;
1707
+ // A thin client's socket (its Hello asks for thin results): its
1708
+ // transactions are served here (SPEC 8.14), the rest relayed.
1709
+ let helloSeen = false;
1710
+ // What the client's Hello offered, read as it arrives (before the core
1711
+ // sees it): a refusal names its reason to a client that reads one
1712
+ // (`FEATURE_TYPED_ERROR_REASON`). Undefined until then.
1713
+ let clientFeatures;
1714
+ let helloArrived;
1715
+ const hello = new Promise((resolve) => (helloArrived = resolve));
1716
+ // A refusal before the Hello waits for it, briefly: a client sends it
1717
+ // right behind its prelude, while `authenticate` runs.
1718
+ const awaitHello = async () => {
1719
+ let timer;
1720
+ try {
1721
+ await Promise.race([
1722
+ hello,
1723
+ new Promise((resolve) => (timer = setTimeout(resolve, HELLO_WAIT_MS))),
1724
+ ]);
1725
+ }
1726
+ finally {
1727
+ clearTimeout(timer);
1728
+ }
1729
+ };
1730
+ let thin;
1731
+ // The prelude the core admitted the session's socket with: its own
1732
+ // client connects with the same.
1733
+ let thinLink;
1734
+ // Users `revokeUser` named while this session's admission ran.
1735
+ let admitting = true;
1736
+ const revokedWhileAdmitting = new Set();
1737
+ // A session that never sends its prelude ends too.
1738
+ let stopExpiry = startTimer(() => {
1739
+ onEvent(null, { kind: "close", code: 1008, reason: "no sign-in in time" });
1740
+ end();
1741
+ }, PRELUDE_DEADLINE_MS);
1742
+ const end = () => {
1743
+ if (ended)
1744
+ return;
1745
+ ended = true;
1746
+ liveSessions.delete(live);
1747
+ stopExpiry?.();
1748
+ thin?.end();
1749
+ socket?.close();
1750
+ };
1751
+ // A signed-in browser's session renewed in place (see
1752
+ // `session-renewal-wire.ts`): the id its tickets name, and the claims
1753
+ // it was admitted with, which a ticket must match.
1754
+ let renewal;
1755
+ // Tell the client when to renew: well before the session must end, so
1756
+ // a background tab's throttled timer still makes it.
1757
+ const tellRenewal = (at) => {
1758
+ if (!renewal || ended)
1759
+ return;
1760
+ renewal.told = true;
1761
+ const left = at - Date.now();
1762
+ // Too close to the expiry to renew: the session reconnects then.
1763
+ if (left < MIN_RENEWAL_NOTICE_MS)
1764
+ return;
1765
+ onEvent(null, {
1766
+ kind: "message",
1767
+ data: Buffer.from(encodeWebSocketFrameBatch([
1768
+ encodeRenewSoonFrame(renewal.session, Math.max(left - RENEWAL_LEAD_MS, left / 2)),
1769
+ ])),
1770
+ });
1771
+ };
1772
+ let renewalAt = 0;
1773
+ // A ticket the client brings back over the socket: extend the session to
1774
+ // the expiry `authenticate` gave on the client's renewal request. A
1775
+ // ticket that doesn't hold (or one this backend can't check now: its
1776
+ // signing key couldn't be had from the core) changes nothing, and the
1777
+ // session ends at its expiry as before.
1778
+ const renew = async (ticket) => {
1779
+ if (!renewal || !userId || ended)
1780
+ return;
1781
+ let until;
1782
+ try {
1783
+ until = await readRenewalTicket(ticket, renewal.session, userId, renewal.claims);
1784
+ }
1785
+ catch (error) {
1786
+ console.error("jazz: couldn't check a session renewal ticket", error);
1787
+ return;
1788
+ }
1789
+ if (until === null || !renewal || ended)
1790
+ return;
1791
+ const now = Date.now();
1792
+ const at = reauthenticateAt(now, sessionDeadline(now, until, options.sessionTtlSeconds));
1793
+ if (at === null)
1794
+ return;
1795
+ if (at <= renewalAt) {
1796
+ // Renewed, but no later than before (the app's `refresh` keeps a
1797
+ // token until it nearly expires): ask again, closer to the expiry.
1798
+ tellRenewal(renewalAt);
1799
+ return;
1800
+ }
1801
+ renewalAt = at;
1802
+ stopExpiry?.();
1803
+ stopExpiry = startTimer(reauthenticate, at - now);
1804
+ tellRenewal(at);
1805
+ };
1806
+ // Ask the client to connect again, so the app's auth decides on a new
1807
+ // request: a planned reconnect the client doesn't show as an outage.
1808
+ const reauthenticate = () => {
1809
+ if (ended)
1810
+ return;
1811
+ onEvent(null, { kind: "message", data: reauthenticateBatch(clientFeatures) });
1812
+ onEvent(null, { kind: "close", code: 1008, reason: "reauthenticate" });
1813
+ end();
1814
+ };
1815
+ const admit = async (prelude) => {
1816
+ const admitted = await admitPrelude(request, prelude).finally(() => (admitting = false));
1817
+ if (admitted &&
1818
+ admitted !== UNVERIFIED_CREDENTIAL &&
1819
+ admitted.userId !== undefined &&
1820
+ revokedWhileAdmitting.has(admitted.userId) &&
1821
+ !ended) {
1822
+ // Admitted on an answer `authenticate` gave before the app revoked
1823
+ // this user: refused as the sessions `revokeUser` ended are.
1824
+ clientSession.revoke("revokeUser");
1825
+ return false;
1826
+ }
1827
+ if (!admitted || admitted === UNVERIFIED_CREDENTIAL || ended) {
1828
+ // An auth failure, not a dropped link: the client stops retrying and
1829
+ // reports `offline: auth`, and its session asks the backend whether
1830
+ // anyone is still signed in. A credential that was sent and not
1831
+ // accepted is `invalid` to the client; none at all is `missing`.
1832
+ if (!ended)
1833
+ await awaitHello();
1834
+ if (!ended)
1835
+ onEvent(null, {
1836
+ kind: "message",
1837
+ data: admitted === UNVERIFIED_CREDENTIAL
1838
+ ? authFailedBatch("session invalid: this backend did not accept the credential the client sent", "invalid", clientFeatures)
1839
+ : authFailedBatch("session missing: not signed in", "missing", clientFeatures),
1840
+ });
1841
+ onEvent(null, { kind: "close", code: 1008, reason: "not signed in" });
1842
+ end();
1843
+ return false;
1844
+ }
1845
+ userId = admitted.userId;
1846
+ trusted = admitted.trusted;
1847
+ thinLink = {
1848
+ prelude: admitted.prelude,
1849
+ access: admitted.access,
1850
+ trusted: admitted.trusted,
1851
+ headers: headerPairs(request.headers),
1852
+ };
1853
+ stopExpiry?.();
1854
+ const admittedAt = Date.now();
1855
+ if (admitted.user) {
1856
+ // A signed-in user's session holds until the expiry `authenticate`
1857
+ // gave it, and at most `sessionTtlSeconds`. Shortly before, the
1858
+ // client is asked to connect again, so `authenticate` decides on its
1859
+ // new request with current cookies.
1860
+ const at = reauthenticateAt(admittedAt, sessionDeadline(admittedAt, admitted.user.expiresAt, options.sessionTtlSeconds));
1861
+ if (at === null) {
1862
+ // `authenticate` named the user with an answer already expired.
1863
+ warnExpiredAnswer();
1864
+ await awaitHello();
1865
+ if (ended)
1866
+ return false;
1867
+ onEvent(null, {
1868
+ kind: "message",
1869
+ data: authFailedBatch("session expired: authenticate returned an expiresAt in the past", "expired", clientFeatures),
1870
+ });
1871
+ onEvent(null, { kind: "close", code: 1008, reason: "session expired" });
1872
+ end();
1873
+ return false;
1874
+ }
1875
+ stopExpiry = startTimer(reauthenticate, at - admittedAt);
1876
+ renewalAt = at;
1877
+ // Told once the core's hello reached the client, which takes no
1878
+ // other frame before it.
1879
+ if (admitted.renewal)
1880
+ renewal = { session: randomUUID(), claims: admitted.user.claims, told: false };
1881
+ }
1882
+ else if (admitted.guest) {
1883
+ // A guest's key is its credential; the app lets it in anew each
1884
+ // `sessionTtlSeconds`, the same way.
1885
+ const ttl = (options.sessionTtlSeconds ?? 3600) * 1000;
1886
+ stopExpiry = startTimer(reauthenticate, ttl);
1887
+ }
1888
+ else {
1889
+ // A backend client's session ends with its token, so it reconnects
1890
+ // with a fresh one.
1891
+ const ttl = Math.min((options.sessionTtlSeconds ?? 3600) * 1000, admitted.expiresAt === undefined ? Infinity : admitted.expiresAt * 1000 - admittedAt);
1892
+ stopExpiry = startTimer(end, ttl);
1893
+ }
1894
+ // A guest's session the core refuses because it admits no device
1895
+ // accounts at all: the client only goes offline, so say why here.
1896
+ // The core refuses in its first message, so only that one is looked at.
1897
+ let firstFromCore = admitted.guest === true;
1898
+ // A user's session the core ends because `revokeUser` ran, on this
1899
+ // instance or another: refused here as `revokeUser` refuses it, and
1900
+ // nothing more from the core reaches the client.
1901
+ let revokedByCore = false;
1902
+ const relay = (error, event) => {
1903
+ if (revokedByCore)
1904
+ return;
1905
+ if (admitted.user &&
1906
+ event.kind === "message" &&
1907
+ event.data &&
1908
+ isCoreRevocation(event.data)) {
1909
+ revokedByCore = true;
1910
+ clientSession.revoke("revokeUser");
1911
+ return;
1912
+ }
1913
+ if (firstFromCore && event.kind === "message" && event.data) {
1914
+ firstFromCore = false;
1915
+ const { buffer, byteOffset, byteLength } = event.data;
1916
+ if (Buffer.from(buffer, byteOffset, byteLength).includes(CORE_REFUSES_GUESTS))
1917
+ warnGuestsOffOnCore();
1918
+ }
1919
+ onEvent(error, event);
1920
+ if (thin && event.kind === "message" && event.data)
1921
+ thin.fromCore(event.data);
1922
+ if (renewal && !renewal.told && event.kind === "message")
1923
+ tellRenewal(renewalAt);
1924
+ };
1925
+ socket = core.openSocket(headerPairs(request.headers), relay, admitted.access);
1926
+ return socket.send(admitted.prelude);
1927
+ };
1928
+ // Messages after the prelude wait for its admission, in order.
1929
+ let chain;
1930
+ // Bytes handed to `deliver` the core has not taken yet: a host that
1931
+ // doesn't wait for it (a socket that can't pause) is cut off past the
1932
+ // limit, as the core cuts off a peer that ignores flow control.
1933
+ let waitingBytes = 0;
1934
+ const deliver = (data) => {
1935
+ if (ended)
1936
+ return Promise.resolve(false);
1937
+ // The message after the prelude is the client's Hello.
1938
+ if (chain && clientFeatures === undefined) {
1939
+ clientFeatures = clientHelloFeatures(data) ?? 0;
1940
+ helloArrived();
1941
+ }
1942
+ // A renewal ticket is for this backend, never for the core.
1943
+ if (renewal && chain) {
1944
+ const ticket = renewalTicketIn(data);
1945
+ if (ticket !== null) {
1946
+ void renew(ticket);
1947
+ return Promise.resolve(true);
1948
+ }
1949
+ }
1950
+ if (waitingBytes + data.byteLength > MAX_WAITING_SESSION_BYTES) {
1951
+ // 1013 (try again later): the client may come back and send at the
1952
+ // pace this host takes.
1953
+ onEvent(null, {
1954
+ kind: "close",
1955
+ code: 1013,
1956
+ reason: "client sent faster than the server takes",
1957
+ });
1958
+ end();
1959
+ return Promise.resolve(false);
1960
+ }
1961
+ waitingBytes += data.byteLength;
1962
+ const taken = (ok) => {
1963
+ waitingBytes -= data.byteLength;
1964
+ return ok;
1965
+ };
1966
+ chain = chain
1967
+ ? chain
1968
+ .then(async (ok) => {
1969
+ if (!ok || ended || !socket)
1970
+ return false;
1971
+ const core = socket;
1972
+ const toCore = (message) => core.sendWithRoom ? core.sendWithRoom(message) : core.send(message);
1973
+ if (!helloSeen) {
1974
+ helloSeen = true;
1975
+ if (asksThinResults(data) && thinLink)
1976
+ thin = new ThinRelay({
1977
+ openClient: (schema) => openThinClient(schema, thinLink),
1978
+ toCore,
1979
+ toClient: (message) => onEvent(null, { kind: "message", data: message }),
1980
+ close: (code, reason) => {
1981
+ onEvent(null, { kind: "close", code, reason });
1982
+ end();
1983
+ },
1984
+ });
1985
+ }
1986
+ else if (thin) {
1987
+ return thin.fromClient(data);
1988
+ }
1989
+ return toCore(data);
1990
+ })
1991
+ .catch(() => {
1992
+ // A core that failed to take a message ends the session.
1993
+ onEvent(null, { kind: "close", code: 1011, reason: "session failed" });
1994
+ end();
1995
+ return false;
1996
+ })
1997
+ .then(taken)
1998
+ : admit(data)
1999
+ .catch(async (error) => {
2000
+ if (!ended && isRefusal(error)) {
2001
+ // The core refused this identity (revoked, local-first auth
2002
+ // disabled, invalid): an auth failure the client must not
2003
+ // retry, reported as a sign-in refusal is.
2004
+ await awaitHello();
2005
+ if (ended)
2006
+ return false;
2007
+ const code = refusalCode(error);
2008
+ onEvent(null, {
2009
+ kind: "message",
2010
+ data: authFailedBatch(`session refused: ${code}`, mapAuthReason(code), clientFeatures),
2011
+ });
2012
+ onEvent(null, { kind: "close", code: 1008, reason: "sign-in refused" });
2013
+ }
2014
+ else {
2015
+ // The core is unreachable or failed (5xx), or the app's own
2016
+ // `authenticate` threw: the client tries again later. An
2017
+ // `authenticate` without `expiresAt` fails the same way every
2018
+ // time: say why, once.
2019
+ if (error instanceof AuthenticateExpiresAtError)
2020
+ warnMissingExpiry(error);
2021
+ if (isAuthenticationUnavailableError(error))
2022
+ console.error(error);
2023
+ else if (isThrownByAuthenticate(error)) {
2024
+ console.error(AUTHENTICATE_THREW_MESSAGE, error);
2025
+ }
2026
+ onEvent(null, { kind: "close", code: 1011, reason: "admission failed" });
2027
+ }
2028
+ end();
2029
+ return false;
2030
+ })
2031
+ .then(taken);
2032
+ return chain;
2033
+ };
2034
+ const clientSession = {
2035
+ send(data) {
2036
+ if (ended)
2037
+ return false;
2038
+ void deliver(data);
2039
+ return true;
2040
+ },
2041
+ deliver,
2042
+ close: end,
2043
+ revoke(reason) {
2044
+ if (ended)
2045
+ return;
2046
+ // A refusal the client doesn't retry: its session asks the backend
2047
+ // who is signed in, and signs out if no one is.
2048
+ onEvent(null, {
2049
+ kind: "message",
2050
+ data: authFailedBatch(`session revoked: ${reason}`, "revoked", clientFeatures),
2051
+ });
2052
+ onEvent(null, { kind: "close", code: 1008, reason: "session revoked" });
2053
+ end();
2054
+ },
2055
+ revokeWhileAdmitting(revoked) {
2056
+ if (admitting && !ended)
2057
+ revokedWhileAdmitting.add(revoked);
2058
+ },
2059
+ get userId() {
2060
+ return userId;
2061
+ },
2062
+ get trusted() {
2063
+ return trusted;
2064
+ },
2065
+ };
2066
+ const live = { session: clientSession, transport, openedAt: Date.now() };
2067
+ liveSessions.add(live);
2068
+ return clientSession;
2069
+ }
2070
+ /**
2071
+ * Turn a browser prelude into one the core admits on this backend's word:
2072
+ * the user `authenticate` finds on this request, with their account and
2073
+ * claims, vouched for with the backend secret. A device account's
2074
+ * prelude passes through: the core verifies its self-signed token. Any
2075
+ * other credential, or a prelude naming another user, is refused: with
2076
+ * {@link UNVERIFIED_CREDENTIAL} when the client sent a token or backend
2077
+ * client credential that doesn't verify here, with `null` when it sent
2078
+ * none that names anyone.
2079
+ */
2080
+ async function admitPrelude(request, prelude) {
2081
+ let parsed;
2082
+ try {
2083
+ parsed = JSON.parse(new TextDecoder().decode(prelude));
2084
+ }
2085
+ catch {
2086
+ return null;
2087
+ }
2088
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
2089
+ return null;
2090
+ // Between the client and this backend only: the core never sees it.
2091
+ const renewal = parsed[SESSION_RENEWAL_PRELUDE_FIELD] === 1;
2092
+ delete parsed[SESSION_RENEWAL_PRELUDE_FIELD];
2093
+ // Vouch only for an `auth` that carries exactly one client credential.
2094
+ const vouchedAuth = (base) => {
2095
+ const hasToken = base.jwt_token != null;
2096
+ const hasSession = base.backend_session != null;
2097
+ if (hasToken === hasSession)
2098
+ throw new Error("createJazz: a guest prelude must carry exactly one credential");
2099
+ return { ...base, backend_secret: core.backendSecret };
2100
+ };
2101
+ const separateAuth = parsed.auth != null && typeof parsed.auth === "object" && !Array.isArray(parsed.auth);
2102
+ const auth = (separateAuth ? parsed.auth : parsed);
2103
+ // Credentials are read from `auth` alone; top-level copies are dropped.
2104
+ if (separateAuth) {
2105
+ for (const field of PRELUDE_CREDENTIAL_FIELDS)
2106
+ delete parsed[field];
2107
+ }
2108
+ const client = await backendClients.resolve(request);
2109
+ if (client === "refused")
2110
+ return UNVERIFIED_CREDENTIAL;
2111
+ if (client?.kind === "backend") {
2112
+ // A trusted backend client syncs with this backend's authority: it
2113
+ // states a backend secret (any stand-in) and, to act for a user, that
2114
+ // user's session, as the main backend's own client does (the user's
2115
+ // policies then apply to those writes at the core). Never an admin
2116
+ // secret or a token of its own.
2117
+ for (const key of ["admin_secret", "jwt_token"]) {
2118
+ if (parsed[key] != null || auth[key] != null)
2119
+ return null;
2120
+ }
2121
+ if (parsed.backend_secret == null && auth.backend_secret == null)
2122
+ return null;
2123
+ const vouched = { backend_secret: core.backendSecret };
2124
+ const rewritten = { ...parsed, ...vouched, auth: { ...auth, ...vouched } };
2125
+ return {
2126
+ prelude: new TextEncoder().encode(JSON.stringify(rewritten)),
2127
+ userId: undefined,
2128
+ access: "backend",
2129
+ trusted: true,
2130
+ expiresAt: client.expiresAt,
2131
+ };
2132
+ }
2133
+ const others = ["backend_secret", "admin_secret", "backend_session"];
2134
+ // Browser worker transports send `jwt_token: null` alongside a backend
2135
+ // session; only a real token counts as one.
2136
+ const token = auth.jwt_token;
2137
+ if (token !== undefined && token !== null) {
2138
+ const localFirst = typeof token === "string" && parseJwtPayload(token)?.iss === LOCAL_FIRST_JWT_ISSUER;
2139
+ const alone = others.every((key) => parsed[key] == null && auth[key] == null);
2140
+ // A token this backend can't verify (an external JWT, a forged or
2141
+ // malformed one), or one sent with other credentials or for another
2142
+ // endpoint: a credential that was presented and not accepted.
2143
+ if (!localFirst || !alone || parsed.local_first_audience != null)
2144
+ return UNVERIFIED_CREDENTIAL;
2145
+ // A guest has no user here: its session is bound to its own key.
2146
+ if (client)
2147
+ return UNVERIFIED_CREDENTIAL;
2148
+ const audience = guestAudience(request, token);
2149
+ if (!audience)
2150
+ return UNVERIFIED_CREDENTIAL;
2151
+ // Guests are off unless the app's `authenticate` lets this one in.
2152
+ if (!(await acceptsGuest(request)))
2153
+ return UNVERIFIED_CREDENTIAL;
2154
+ if (audience.endpoint === undefined) {
2155
+ // Its own token decides who it is; the backend's secret only vouches
2156
+ // for the bundle this socket is pinned to (see `pinnedSocket`).
2157
+ const pinned = { ...parsed, auth: vouchedAuth(auth) };
2158
+ return {
2159
+ prelude: new TextEncoder().encode(JSON.stringify(pinned)),
2160
+ userId: undefined,
2161
+ access: "session",
2162
+ trusted: false,
2163
+ guest: true,
2164
+ };
2165
+ }
2166
+ // Signed for this endpoint, which the core can't know: vouch for it.
2167
+ const vouched = {
2168
+ ...parsed,
2169
+ local_first_audience: audience.endpoint,
2170
+ auth: vouchedAuth(auth),
2171
+ };
2172
+ // The backend's word on the endpoint needs backend access; the
2173
+ // guest's own token still decides who it is.
2174
+ return {
2175
+ prelude: new TextEncoder().encode(JSON.stringify(vouched)),
2176
+ userId: undefined,
2177
+ access: "backend",
2178
+ trusted: false,
2179
+ guest: true,
2180
+ };
2181
+ }
2182
+ const stated = auth.backend_session;
2183
+ if (!stated || typeof stated !== "object")
2184
+ return null;
2185
+ for (const credential of ["backend_secret", "admin_secret"]) {
2186
+ if (parsed[credential] != null || auth[credential] != null)
2187
+ return null;
2188
+ }
2189
+ // The core compares this with the user's revocation mark: a
2190
+ // `revokeUser` on any instance after this moment ends the session, and
2191
+ // one before it refuses the session (see `revokeUser`).
2192
+ const authenticatedAt = Date.now();
2193
+ const user = await authenticate(request);
2194
+ if (!user || user.userId !== stated.user_id)
2195
+ return null;
2196
+ // A browser states a user's session only once its sign-in (or link)
2197
+ // gave them an account; this never makes one.
2198
+ let session;
2199
+ try {
2200
+ session = await sessionFor(user, "a sync session");
2201
+ }
2202
+ catch (error) {
2203
+ if (error instanceof NoJazzAccountError)
2204
+ return null;
2205
+ throw error;
2206
+ }
2207
+ const vouched = {
2208
+ backend_secret: core.backendSecret,
2209
+ backend_session: { ...session, authenticatedAt },
2210
+ };
2211
+ const rewritten = { ...parsed, ...vouched, auth: { ...auth, ...vouched } };
2212
+ return {
2213
+ prelude: new TextEncoder().encode(JSON.stringify(rewritten)),
2214
+ userId: user.userId,
2215
+ user,
2216
+ access: "backend",
2217
+ trusted: false,
2218
+ expiresAt: client?.expiresAt,
2219
+ // A scoped backend client's session ends with its token instead.
2220
+ ...(renewal && !client ? { renewal: true } : {}),
2221
+ };
2222
+ }
2223
+ /** `streamAuthReuseSeconds`, read live so a hot reload's options apply. */
2224
+ const streamAuthReuseMs = () => (options.streamAuthReuseSeconds ?? DEFAULT_STREAM_AUTH_REUSE_SECONDS) * 1000;
2225
+ // HTTP stream sessions, by id, with the key that proves a request comes
2226
+ // from the client that opened them.
2227
+ const streams = new Map();
2228
+ // Sockets accepted for clients, so close() can end them.
2229
+ const clientSockets = new Set();
2230
+ // Why stream sessions this process served lately ended, by id: a send that
2231
+ // arrives after its session ended (refused at sign-in, say) is told that,
2232
+ // not that it reached the wrong instance.
2233
+ const endedStreams = new Map();
2234
+ const ENDED_STREAMS_KEPT = 1000;
2235
+ function openStream(request) {
2236
+ const id = randomUUID();
2237
+ // The id goes in URLs (and so in logs); the key only in a header.
2238
+ const key = randomBytes(32);
2239
+ let controller;
2240
+ let closed = false;
2241
+ const end = (code, reason) => {
2242
+ if (closed)
2243
+ return;
2244
+ closed = true;
2245
+ streams.delete(id);
2246
+ endedStreams.set(id, { key, reason: reason || `closed (${code})` });
2247
+ if (endedStreams.size > ENDED_STREAMS_KEPT) {
2248
+ endedStreams.delete(endedStreams.keys().next().value);
2249
+ }
2250
+ try {
2251
+ controller.enqueue(encodeStreamClose(code, reason));
2252
+ controller.close();
2253
+ }
2254
+ catch {
2255
+ // The client already went away.
2256
+ }
2257
+ };
2258
+ const body = new ReadableStream({
2259
+ start(c) {
2260
+ controller = c;
2261
+ },
2262
+ cancel() {
2263
+ streams.get(id)?.session.close();
2264
+ end(1001, "client went away");
2265
+ },
2266
+ });
2267
+ let socket;
2268
+ try {
2269
+ socket = openClientSession(request, (error, event) => {
2270
+ if (error)
2271
+ return end(1011, error.message);
2272
+ if (event.kind === "message" && event.data) {
2273
+ if (!closed)
2274
+ controller.enqueue(encodeStreamRecord(STREAM_RECORD_MESSAGE, event.data));
2275
+ }
2276
+ else if (event.kind === "close") {
2277
+ end(event.code ?? 1000, event.reason ?? "");
2278
+ }
2279
+ }, "stream");
2280
+ }
2281
+ catch (error) {
2282
+ return new Response(error instanceof Error ? error.message : String(error), { status: 503 });
2283
+ }
2284
+ streams.set(id, { session: socket, key, end, authAsks: 0 });
2285
+ controller.enqueue(encodeStreamRecord(STREAM_RECORD_SESSION, new TextEncoder().encode(JSON.stringify({ id, key: key.toString("base64url") }))));
2286
+ return new Response(body, {
2287
+ headers: {
2288
+ "Content-Type": "application/octet-stream",
2289
+ "Cache-Control": "no-store",
2290
+ "X-Accel-Buffering": "no",
2291
+ },
2292
+ });
2293
+ }
2294
+ function holdsKey(request, key) {
2295
+ const given = Buffer.from(request.headers.get(STREAM_KEY_HEADER) ?? "", "base64url");
2296
+ return given.length === key.length && timingSafeEqual(given, key);
2297
+ }
2298
+ /**
2299
+ * The stream session `id`, when `request` comes from the client that
2300
+ * opened it (it carries the session's key) and, once the session is
2301
+ * admitted as a user, from that user still: a session id alone (which
2302
+ * can end up in logs) doesn't let anyone act in it, before admission or
2303
+ * for a guest either.
2304
+ */
2305
+ async function ownStream(id, request) {
2306
+ const entry = streams.get(id);
2307
+ if (!entry) {
2308
+ const ended = endedStreams.get(id);
2309
+ if (ended !== undefined) {
2310
+ if (!holdsKey(request, ended.key))
2311
+ return new Response("not this stream's client", { status: 403 });
2312
+ return new Response(`stream session ended: ${ended.reason}`, { status: 410 });
2313
+ }
2314
+ // Sessions live in the process that opened them.
2315
+ return new Response("unknown stream session: HTTP stream sessions need a single backend instance or sticky routing", { status: 404 });
2316
+ }
2317
+ if (!holdsKey(request, entry.key)) {
2318
+ return new Response("not this stream's client", { status: 403 });
2319
+ }
2320
+ const socket = entry.session;
2321
+ if (socket.trusted) {
2322
+ const client = await backendClients.resolve(request);
2323
+ if (client === null || client === "refused" || client.kind !== "backend") {
2324
+ return new Response("not this backend client", { status: 403 });
2325
+ }
2326
+ }
2327
+ else if (socket.userId !== undefined) {
2328
+ // A send carrying the same credentials as one `authenticate` admitted
2329
+ // lately is the same user: an app save is several sends in a row, and
2330
+ // asking the app's auth (a session lookup) on each was most of their
2331
+ // server time. Any change to what `authenticate` may read asks it
2332
+ // again; so does an answer past its `expiresAt`, or older than
2333
+ // `streamAuthReuseSeconds`, so a sign-out elsewhere that kept this
2334
+ // cookie (or a ban) reaches the stream within that long, where before
2335
+ // it did on its next send. `revokeUser` ends the session at once.
2336
+ const credentials = streamCredentials(request);
2337
+ const checked = entry.checked;
2338
+ if (checked &&
2339
+ checked.credentials === credentials &&
2340
+ performance.now() - checked.askedAt < streamAuthReuseMs() &&
2341
+ Date.now() < checked.userUntil) {
2342
+ return socket;
2343
+ }
2344
+ entry.checked = undefined;
2345
+ const ask = ++entry.authAsks;
2346
+ const askedAt = performance.now();
2347
+ const user = await authenticate(request);
2348
+ if (user?.userId !== socket.userId)
2349
+ return new Response("not signed in", { status: 403 });
2350
+ // Keep only the latest ask's answer (a slower earlier one must not
2351
+ // undo a refusal since), and none once the session ended meanwhile.
2352
+ if (streamAuthReuseMs() > 0 && entry.authAsks === ask && streams.get(id) === entry) {
2353
+ entry.checked = { credentials, userUntil: user.expiresAt * 1000, askedAt };
2354
+ }
2355
+ }
2356
+ return socket;
2357
+ }
2358
+ /**
2359
+ * A client's DELETE, ending its stream session. The key alone proves the
2360
+ * client here, unless the request is signed in as someone else: clients
2361
+ * end their sessions as they sign out, once the app's sign-in has gone, so
2362
+ * a signed-out request may end the session it holds the key of. A session
2363
+ * that already ended is done (204): its client often learns that only
2364
+ * from this answer (#5187).
2365
+ */
2366
+ async function endStream(id, request) {
2367
+ const entry = streams.get(id);
2368
+ if (!entry) {
2369
+ const ended = endedStreams.get(id);
2370
+ if (ended && holdsKey(request, ended.key))
2371
+ return new Response(null, { status: 204 });
2372
+ const refused = await ownStream(id, request);
2373
+ return refused instanceof Response ? refused : new Response(null, { status: 204 });
2374
+ }
2375
+ if (!holdsKey(request, entry.key)) {
2376
+ return new Response("not this stream's client", { status: 403 });
2377
+ }
2378
+ const socket = entry.session;
2379
+ if (socket.trusted) {
2380
+ const client = await backendClients.resolve(request);
2381
+ if (client === null || client === "refused" || client.kind !== "backend") {
2382
+ return new Response("not this backend client", { status: 403 });
2383
+ }
2384
+ }
2385
+ else if (socket.userId !== undefined) {
2386
+ const user = await authenticate(request);
2387
+ if (user && user.userId !== socket.userId) {
2388
+ return new Response("signed in as someone else", { status: 403 });
2389
+ }
2390
+ }
2391
+ socket.close();
2392
+ return new Response(null, { status: 204 });
2393
+ }
2394
+ /**
2395
+ * Pass a send's records to the session as they arrive, each once the core
2396
+ * has room for it: the body is not read ahead of the core, so a client
2397
+ * sending faster than the core takes is held back by the request itself.
2398
+ */
2399
+ async function streamSend(id, request) {
2400
+ const socket = await ownStream(id, request);
2401
+ if (socket instanceof Response)
2402
+ return socket;
2403
+ // A send's records go in whole and in order: one send at a time.
2404
+ if (sendingStreams.has(id)) {
2405
+ return new Response("a send to this stream is in progress", { status: 409 });
2406
+ }
2407
+ sendingStreams.add(id);
2408
+ try {
2409
+ return await passStreamRecords(socket, request);
2410
+ }
2411
+ finally {
2412
+ sendingStreams.delete(id);
2413
+ }
2414
+ }
2415
+ /** Stream sessions with a send in progress. */
2416
+ const sendingStreams = new Set();
2417
+ async function passStreamRecords(socket, request) {
2418
+ const refuse = (reason) => {
2419
+ socket.close();
2420
+ return new Response(reason, { status: 400 });
2421
+ };
2422
+ const records = new StreamRecordReader();
2423
+ const body = request.body?.getReader();
2424
+ for (;;) {
2425
+ const chunk = body ? await body.read() : { done: true, value: undefined };
2426
+ if (chunk.done)
2427
+ break;
2428
+ for (const record of records.push(chunk.value)) {
2429
+ if (record.kind !== STREAM_RECORD_MESSAGE ||
2430
+ record.payload.byteLength > MAX_STREAM_MESSAGE_BYTES) {
2431
+ void body?.cancel().catch(() => undefined);
2432
+ return refuse("invalid record");
2433
+ }
2434
+ if (!(await socket.deliver(record.payload))) {
2435
+ void body?.cancel().catch(() => undefined);
2436
+ return new Response("session ended", { status: 410 });
2437
+ }
2438
+ }
2439
+ // A record no message may be: refused before it is buffered.
2440
+ if (records.pending > 5 + MAX_STREAM_MESSAGE_BYTES) {
2441
+ void body?.cancel().catch(() => undefined);
2442
+ return refuse("invalid record");
2443
+ }
2444
+ }
2445
+ if (records.pending > 0)
2446
+ return refuse("truncated record");
2447
+ return new Response(null, { status: 204 });
2448
+ }
2449
+ /** Close codes a socket may send: 1005/1006/1015 only describe a close. */
2450
+ function sendableCloseCode(code) {
2451
+ if (code === undefined || code === 1005)
2452
+ return 1000;
2453
+ if (code === 1006 || code === 1015)
2454
+ return 1011;
2455
+ return code;
2456
+ }
2457
+ function acceptSocket(request, ws) {
2458
+ if (!originAllowed(request)) {
2459
+ ws.close(1008, "origin not allowed");
2460
+ return;
2461
+ }
2462
+ // A paused socket reads no close handshake: resume it to close.
2463
+ const close = (code, reason) => {
2464
+ ws.resume?.();
2465
+ ws.close(code, reason);
2466
+ };
2467
+ let socket;
2468
+ try {
2469
+ socket = openClientSession(request, (error, event) => {
2470
+ if (error)
2471
+ return close(1011, error.message);
2472
+ if (event.kind === "message" && event.data)
2473
+ ws.send(event.data);
2474
+ else if (event.kind === "close") {
2475
+ close(sendableCloseCode(event.code), event.reason ?? "");
2476
+ }
2477
+ }, "socket");
2478
+ }
2479
+ catch (error) {
2480
+ close(1013, error instanceof Error ? error.message : String(error));
2481
+ return;
2482
+ }
2483
+ clientSockets.add(ws);
2484
+ // Messages go to the core in order, each once it has room; the socket
2485
+ // is not read while one waits, so a fast client is held back.
2486
+ let waiting = 0;
2487
+ ws.on("message", (data) => {
2488
+ waiting += 1;
2489
+ ws.pause?.();
2490
+ // `deliver` resolves false, never rejects, when the session fails.
2491
+ void socket.deliver(toBytes(data)).then((ok) => {
2492
+ waiting -= 1;
2493
+ if (!ok)
2494
+ close(1000, "session ended");
2495
+ else if (waiting === 0)
2496
+ ws.resume?.();
2497
+ });
2498
+ });
2499
+ ws.on("close", () => {
2500
+ clientSockets.delete(ws);
2501
+ socket.close();
2502
+ });
2503
+ ws.on("error", () => socket.close());
2504
+ }
2505
+ /**
2506
+ * Whether a browser on the request's origin may act as its user here.
2507
+ * Sign-in and sync ride the app's own session (usually a cookie), which a
2508
+ * browser also attaches to requests that other pages start, so a request
2509
+ * from another origin is refused: one with no Origin (a non-browser
2510
+ * client, which holds no ambient cookie) passes. The backend's own origin
2511
+ * is the host the request was sent to, as a proxy forwards it.
2512
+ */
2513
+ /** This process upgrades sockets for handle() and nodeHandler (set by attach()). */
2514
+ let upgradesSockets = options.upgradesSockets ?? false;
2515
+ let attached = false;
2516
+ function originAllowed(request) {
2517
+ const origin = request.headers.get("origin");
2518
+ if (origin === null) {
2519
+ const site = request.headers.get("sec-fetch-site");
2520
+ return site === null || site === "same-origin" || site === "none";
2521
+ }
2522
+ if (allowedOrigins.has(origin))
2523
+ return true;
2524
+ let parsed;
2525
+ try {
2526
+ parsed = new URL(origin);
2527
+ }
2528
+ catch {
2529
+ return false; // "null" (a sandboxed or opaque origin) or garbage
2530
+ }
2531
+ const requestHost = request.headers.get("x-forwarded-host")?.split(",")[0]?.trim() ||
2532
+ request.headers.get("host") ||
2533
+ new URL(request.url).host;
2534
+ if (parsed.host !== requestHost)
2535
+ return false;
2536
+ // A page over plain http may not act on a backend reached over https. The
2537
+ // other way round is allowed: a proxy that ends TLS may hand us plain http.
2538
+ const requestScheme = request.headers.get("x-forwarded-proto")?.split(",")[0]?.trim().toLowerCase() ||
2539
+ new URL(request.url).protocol.replace(/:$/, "");
2540
+ return !(requestScheme === "https" && parsed.protocol === "http:");
2541
+ }
2542
+ /**
2543
+ * A trusted backend client asks to sync as a backend (what a backend's
2544
+ * own client asks its core first). Only its token admits it: the core is
2545
+ * asked with this backend's secret. Anyone else gets the 404 this route
2546
+ * has without backend clients.
2547
+ */
2548
+ async function admitBackendClient(request) {
2549
+ const client = await backendClients.resolve(request);
2550
+ if (client === null)
2551
+ return new Response("Not found", { status: 404 });
2552
+ if (client === "refused" || client.kind !== "backend") {
2553
+ return new Response("not a trusted backend client", { status: 401 });
2554
+ }
2555
+ if (request.method !== "POST")
2556
+ return new Response(null, { status: 405 });
2557
+ const response = await core.handle("POST", `/apps/${encodeURIComponent(accountAppId(appId))}/backend/admit`, [["x-jazz-backend-secret", core.backendSecret]], new Uint8Array(0), "backend");
2558
+ if (response.status !== 204)
2559
+ return new Response(null, { status: 502 });
2560
+ // The bundle this backend pins the client's socket to (see
2561
+ // `pinnedSocket`): a client that evaluates its users' reads against its
2562
+ // own permissions checks they are the ones published here (jazz#5808).
2563
+ return new Response(null, {
2564
+ status: 204,
2565
+ headers: pin === undefined ? undefined : { [BUNDLE_HEADER]: pin },
2566
+ });
2567
+ }
2568
+ /**
2569
+ * A trusted backend client asks for a user's session, to act for them
2570
+ * (`client.forUser`): the account `forReqUser` would act as for a request
2571
+ * of theirs. Never creates an account (see `createAccountFor`). Anyone but
2572
+ * a trusted machine gets what `admitBackendClient` gives them.
2573
+ */
2574
+ async function backendClientUserSession(request) {
2575
+ const client = await backendClients.resolve(request);
2576
+ if (client === null)
2577
+ return new Response("Not found", { status: 404 });
2578
+ if (client === "refused" || client.kind !== "backend") {
2579
+ return new Response("not a trusted backend client", { status: 401 });
2580
+ }
2581
+ if (request.method !== "POST")
2582
+ return new Response(null, { status: 405 });
2583
+ let userId;
2584
+ try {
2585
+ ({ userId } = (await request.json()));
2586
+ }
2587
+ catch {
2588
+ return new Response("expected a JSON body", { status: 400 });
2589
+ }
2590
+ if (typeof userId !== "string" || userId === "") {
2591
+ return new Response("userId must be a non-empty string", { status: 400 });
2592
+ }
2593
+ let account;
2594
+ try {
2595
+ account = await existingAccountOf(userId);
2596
+ }
2597
+ catch (error) {
2598
+ // The core refuses this identity (it was revoked): say so, as
2599
+ // `backendUser` does, rather than fail as a server error.
2600
+ if (error.status === 403)
2601
+ return Response.json({ code: "identity_not_authorized" }, { status: 403 });
2602
+ throw error;
2603
+ }
2604
+ const noStore = { "Cache-Control": "no-store" };
2605
+ if (account === null)
2606
+ return Response.json({ code: "no_account" }, { status: 404, headers: noStore });
2607
+ return Response.json({ account, issuer }, { headers: noStore });
2608
+ }
2609
+ /**
2610
+ * The session `forReqUser` and `withAttribution` act as: the user
2611
+ * `authenticate` names (on the account they already have), or, when
2612
+ * `authenticate` lets the request in as a device account and the caller
2613
+ * takes device accounts, the device account whose proof it carries. Null
2614
+ * when neither names anyone.
2615
+ */
2616
+ async function requestSession(request, caller, deviceAccounts) {
2617
+ const answer = await requestAnswer(request);
2618
+ if (answer === null)
2619
+ return null;
2620
+ if (answer !== "device-account")
2621
+ return sessionFor(answer, caller);
2622
+ if (!deviceAccounts)
2623
+ return null;
2624
+ const device = await deviceAccountOf(request);
2625
+ return device && deviceAccountSession(device, appId, device.audience);
2626
+ }
2627
+ /**
2628
+ * The device account a plain request proves it is, for a request
2629
+ * `authenticate` let in as one: its local-first token as `Authorization:
2630
+ * Bearer` (`db.getDeviceAccountProof()`), checked as a socket's is.
2631
+ * Its signature, issuer and expiry, and an audience of this app or one of
2632
+ * this endpoint's URLs (`guestAudience`, so a proof for another endpoint
2633
+ * is refused); then the core admits it (`found-local-first`), which
2634
+ * refuses a key a link retired and names the account the key opens. Null
2635
+ * for a request with no proof; a proof that doesn't verify or isn't
2636
+ * admitted throws a {@link RequestAuthenticationError}.
2637
+ */
2638
+ async function deviceAccountOf(request) {
2639
+ const token = deviceProofOf(request);
2640
+ if (token === null)
2641
+ return null;
2642
+ const audience = guestAudience(request, token);
2643
+ if (!audience) {
2644
+ throw new RequestAuthenticationError("the request's device-account proof is invalid, expired or for another endpoint", { code: "invalid_device_proof" });
2645
+ }
2646
+ const { subject } = audience;
2647
+ const verifiedFor = audience.endpoint ?? appId;
2648
+ let account;
2649
+ try {
2650
+ ({ account } = await adminAccounts("found-local-first", {
2651
+ identity: { issuer: LOCAL_FIRST_JWT_ISSUER, subject },
2652
+ ...(audience.endpoint !== undefined ? { audience: audience.endpoint } : {}),
2653
+ }));
2654
+ }
2655
+ catch (error) {
2656
+ const { status, code } = error;
2657
+ if (code === LOCAL_FIRST_AUTH_DISABLED) {
2658
+ warnGuestsOffOnCore();
2659
+ throw error;
2660
+ }
2661
+ // The core refuses this key: a link retired it (`guestKeyAfterLink`).
2662
+ if (status === 403 && code === IDENTITY_NOT_AUTHORIZED) {
2663
+ throw new RequestAuthenticationError("the request's device account key was revoked", {
2664
+ code: "device_account_revoked",
2665
+ });
2666
+ }
2667
+ throw error;
2668
+ }
2669
+ return { token, subject, account, audience: verifiedFor };
2670
+ }
2671
+ /**
2672
+ * The endpoint URLs a browser may have named this backend by, as its client
2673
+ * scope (see `clientScope`): the page's origin when it is one this backend
2674
+ * serves, and this request's own host, each with `basePath`.
2675
+ */
2676
+ function endpointAudiences(request) {
2677
+ if (publicUrls.length)
2678
+ return publicUrls;
2679
+ const audiences = new Set();
2680
+ // The page origin when it is this Host or an allowed origin, and this
2681
+ // Host. A browser can't forge Host, but a caller reaching this backend
2682
+ // directly can, so production backends should set `publicUrl`.
2683
+ // X-Forwarded-Host is never read here.
2684
+ const url = new URL(request.url);
2685
+ const host = request.headers.get("host") || url.host;
2686
+ const forwardedProto = request.headers
2687
+ .get("x-forwarded-proto")
2688
+ ?.split(",")[0]
2689
+ ?.trim()
2690
+ .toLowerCase();
2691
+ const scheme = forwardedProto === "https" || url.protocol === "https:" ? "https" : "http";
2692
+ const origin = request.headers.get("origin");
2693
+ if (origin) {
2694
+ try {
2695
+ const parsed = new URL(origin);
2696
+ if (allowedOrigins.has(parsed.origin) || parsed.host === host)
2697
+ audiences.add(`${parsed.origin}${basePath}`);
2698
+ }
2699
+ catch {
2700
+ // Not an origin a page has.
2701
+ }
2702
+ }
2703
+ try {
2704
+ audiences.add(`${new URL(`${scheme}://${host}`).origin}${basePath}`);
2705
+ }
2706
+ catch {
2707
+ // A host header no URL takes.
2708
+ }
2709
+ return [...audiences];
2710
+ }
2711
+ const warnedAudiences = new Set();
2712
+ let warnedHeaderAudience = false;
2713
+ /** Say once per audience why a guest's proof was refused, so a proxy mismatch is visible. */
2714
+ function warnUnknownAudience(token, accepted, isAudience = false) {
2715
+ const audience = isAudience ? token : parseJwtPayload(token)?.aud;
2716
+ const named = typeof audience === "string" ? audience : JSON.stringify(audience);
2717
+ if (warnedAudiences.has(named) || warnedAudiences.size > 100)
2718
+ return;
2719
+ warnedAudiences.add(named);
2720
+ console.warn(`createJazz: refused a device account whose proof is for ${named}; this endpoint accepts ${JSON.stringify([appId, ...accepted])}. If browsers reach Jazz through a proxy that changes the host or path, set publicUrl to the URL they use.`);
2721
+ }
2722
+ /**
2723
+ * What a device account's proof is for: this app (an app whose browser
2724
+ * clients still name its id, or carry it as their `scope`), one of this
2725
+ * endpoint's URLs, or neither (null).
2726
+ */
2727
+ function guestAudience(request, token) {
2728
+ try {
2729
+ return { subject: verifyLocalFirstToken(token, appId) };
2730
+ }
2731
+ catch {
2732
+ // Not this app's id; try the endpoint.
2733
+ }
2734
+ const endpoints = endpointAudiences(request);
2735
+ for (const endpoint of endpoints) {
2736
+ try {
2737
+ const subject = verifyLocalFirstToken(token, endpoint);
2738
+ if (!publicUrls.length && !warnedHeaderAudience && !isLocalEndpoint(endpoint)) {
2739
+ warnedHeaderAudience = true;
2740
+ console.warn(`createJazz: vouched for a device account of ${endpoint}, taken from the request's headers. Set publicUrl to the URL browsers use so a caller can't name another host.`);
2741
+ }
2742
+ return { endpoint, subject };
2743
+ }
2744
+ catch {
2745
+ // Not this one.
2746
+ }
2747
+ }
2748
+ warnUnknownAudience(token, endpoints);
2749
+ return null;
2750
+ }
2751
+ /**
2752
+ * The namespace a linking guest names for its account: this app (no
2753
+ * audience, or the app's id), one of this endpoint's URLs, or neither (null).
2754
+ */
2755
+ function linkAudience(request, audience) {
2756
+ // Tokens name their audience as given or as its app id (a UUID).
2757
+ const names = (value) => audience === value || audience === accountAppId(value);
2758
+ if (audience === undefined || (typeof audience === "string" && names(appId)))
2759
+ return {};
2760
+ if (typeof audience !== "string")
2761
+ return null;
2762
+ const endpoints = endpointAudiences(request);
2763
+ const endpoint = endpoints.find(names);
2764
+ if (endpoint !== undefined)
2765
+ return { endpoint };
2766
+ warnUnknownAudience(audience, endpoints, true);
2767
+ return null;
2768
+ }
2769
+ /** The path below `basePath`, or null for a request Jazz doesn't serve. */
2770
+ function innerPath(request) {
2771
+ const { pathname } = new URL(request.url);
2772
+ if (pathname === basePath)
2773
+ return "/";
2774
+ if (!pathname.startsWith(`${basePath}/`))
2775
+ return null;
2776
+ return pathname.slice(basePath.length);
2777
+ }
2778
+ /**
2779
+ * Answer `request`. `upgrades`: whether the handler it came through
2780
+ * upgrades sockets on this host, which decides what a plain request for
2781
+ * the socket path is told.
2782
+ */
2783
+ async function handle(request, upgrades = upgradesSockets) {
2784
+ try {
2785
+ return await route(request, upgrades);
2786
+ }
2787
+ catch (error) {
2788
+ if (error instanceof AuthenticateExpiresAtError) {
2789
+ // The app's own setup is wrong, the same way on every request: tell
2790
+ // the client by a stable code it explains (naming the fix), and log
2791
+ // the detail (what `authenticate` returned) here once. The response
2792
+ // carries nothing of the app's answer.
2793
+ warnMissingExpiry(error);
2794
+ return new Response(AUTHENTICATE_EXPIRES_AT_MISSING, {
2795
+ status: 500,
2796
+ headers: { "Cache-Control": "no-store" },
2797
+ });
2798
+ }
2799
+ if (isAuthenticationUnavailableError(error)) {
2800
+ // The identity provider is down, not the app's code: the client
2801
+ // retries and stays signed in. The reason stays in the logs.
2802
+ console.error(error);
2803
+ return new Response(AUTHENTICATION_UNAVAILABLE, {
2804
+ status: 503,
2805
+ headers: { "Retry-After": "5", "Cache-Control": "no-store" },
2806
+ });
2807
+ }
2808
+ if (isThrownByAuthenticate(error)) {
2809
+ // The reason (it can name the app's internals) stays in the logs.
2810
+ console.error(AUTHENTICATE_THREW_MESSAGE, error);
2811
+ return new Response(AUTHENTICATE_FAILED, {
2812
+ status: 500,
2813
+ headers: { "Cache-Control": "no-store" },
2814
+ });
2815
+ }
2816
+ if (!(error instanceof BackendClientsUnavailable))
2817
+ throw error;
2818
+ // The reason stays in the backend's logs.
2819
+ console.error(error);
2820
+ return new Response("backend client keys unavailable", {
2821
+ status: 503,
2822
+ headers: { "Retry-After": "5" },
2823
+ });
2824
+ }
2825
+ }
2826
+ /**
2827
+ * `handle(request)`, through the app's `refresh` middleware when it has
2828
+ * one: the one route a browser asks before its sync session expires.
2829
+ */
2830
+ async function refreshThen(request, handle) {
2831
+ if (!options.refresh)
2832
+ return handle(request);
2833
+ // Only the browser's own POST, which `route` checked the origin of: a
2834
+ // cross-site navigation (a GET) must never rotate the app's session.
2835
+ if (request.method !== "POST")
2836
+ return new Response(null, { status: 405 });
2837
+ const response = await options.refresh(request, (next) => {
2838
+ if (!isRequestLike(next)) {
2839
+ throw new TypeError("createJazz: refresh must call next with a Request");
2840
+ }
2841
+ return handle(next);
2842
+ });
2843
+ if (!isResponseLike(response)) {
2844
+ throw new TypeError("createJazz: refresh must return the Response next gave it (or another)");
2845
+ }
2846
+ return response;
2847
+ }
2848
+ async function route(request, upgrades) {
2849
+ const path = innerPath(request);
2850
+ if (path === null)
2851
+ return new Response("Not found", { status: 404 });
2852
+ if (request.method !== "GET" && request.method !== "HEAD" && !originAllowed(request)) {
2853
+ return new Response("origin not allowed", { status: 403 });
2854
+ }
2855
+ if (path === "/inspect" || path.startsWith("/inspect/")) {
2856
+ return inspector.handle(request, path);
2857
+ }
2858
+ if (/^\/apps\/[^/]+\/accounts\/backend-sign-in$/.test(path)) {
2859
+ return backendSignIn(request);
2860
+ }
2861
+ if (/^\/apps\/[^/]+\/accounts\/backend-user$/.test(path)) {
2862
+ return refreshThen(request, backendUser);
2863
+ }
2864
+ if (/^\/apps\/[^/]+\/backend\/admit$/.test(path)) {
2865
+ return admitBackendClient(request);
2866
+ }
2867
+ if (/^\/apps\/[^/]+\/backend\/user-session$/.test(path)) {
2868
+ return backendClientUserSession(request);
2869
+ }
2870
+ if (/^\/apps\/[^/]+\/accounts\/backend-link$/.test(path)) {
2871
+ return backendLink(request);
2872
+ }
2873
+ if (/^\/apps\/[^/]+\/accounts\/backend-link\/challenge$/.test(path)) {
2874
+ return backendLinkChallenge(request);
2875
+ }
2876
+ const stream = /^\/apps\/[^/]+\/stream(?:\/([^/]+))?$/.exec(path);
2877
+ if (stream) {
2878
+ const id = stream[1] && decodeURIComponent(stream[1]);
2879
+ if (!id && request.method === "POST")
2880
+ return openStream(request);
2881
+ if (id && request.method === "POST")
2882
+ return streamSend(id, request);
2883
+ if (id && request.method === "DELETE")
2884
+ return endStream(id, request);
2885
+ return new Response(null, { status: 405 });
2886
+ }
2887
+ if (path.endsWith("/ws")) {
2888
+ // A plain request for the socket path: the browser client asks this
2889
+ // after a socket failed before it opened. Where this host upgrades
2890
+ // sockets (attach(), or Vercel), that failure was transient (a
2891
+ // restart, a draining instance) and the client should retry the
2892
+ // socket. Only where it can't does the marker send it to the stream
2893
+ // at once; the client also switches after several failed sockets in
2894
+ // a row, when something in between doesn't pass upgrades on. It asks
2895
+ // with a POST, so a page origin the socket was refused for is refused
2896
+ // here too (403, above), and not taken for a proxy's doing.
2897
+ if (upgrades) {
2898
+ return new Response("Upgrade to a WebSocket", { status: 426 });
2899
+ }
2900
+ return useHttpStream();
2901
+ }
2902
+ if (!PUBLIC_APP_ROUTES.test(path))
2903
+ return new Response("Not found", { status: 404 });
2904
+ const url = new URL(request.url);
2905
+ const body = request.method === "GET" || request.method === "HEAD"
2906
+ ? Buffer.alloc(0)
2907
+ : Buffer.from(await request.arrayBuffer());
2908
+ const headers = headerPairs(request.headers);
2909
+ // A browser names the app however its scope does; the core knows it by id.
2910
+ const corePath = path.replace(/^\/apps\/[^/]+/, `/apps/${encodeURIComponent(appId)}`);
2911
+ return coreResponse(await core.handle(request.method, corePath + url.search, store.kind === "remote" || store.kind === "vercel"
2912
+ ? headers.filter(([name]) => REMOTE_FORWARDED_HEADERS.includes(name.toLowerCase()))
2913
+ : headers, body));
2914
+ }
2915
+ async function nextHandler(request) {
2916
+ const path = innerPath(request);
2917
+ // On Vercel this handler upgrades sockets (below), once `ws` is
2918
+ // installed; elsewhere (next dev) only if attach() runs on the same
2919
+ // server. Where it can't, a socket gets the HTTP stream marker, as a
2920
+ // plain request for the socket path does.
2921
+ const onVercel = onVercelHost();
2922
+ const vercelUpgrades = onVercel && (await vercelUpgradesSockets());
2923
+ if (request.method === "GET" &&
2924
+ path?.endsWith("/ws") &&
2925
+ request.headers.get("upgrade")?.toLowerCase() === "websocket" &&
2926
+ onVercel) {
2927
+ if (!originAllowed(request))
2928
+ return new Response("origin not allowed", { status: 403 });
2929
+ if (!vercelUpgrades)
2930
+ return useHttpStream();
2931
+ // An optional peer: a literal import inside `try`, so bundlers report
2932
+ // a missing one at runtime, not on every route (see importSandboxSdk).
2933
+ let vercelFunctions;
2934
+ try {
2935
+ vercelFunctions = (await backendNative().importPeer("@vercel/functions"));
2936
+ }
2937
+ catch (error) {
2938
+ throw optionalPeerImportError("Jazz on Vercel", "@vercel/functions", error);
2939
+ }
2940
+ const { upgradeWebSocket } = vercelFunctions;
2941
+ // The socket ends with this invocation, at the route's maxDuration:
2942
+ // close it just before, so the client reconnects without a stall.
2943
+ const deadline = vercelFunctions.getDeadline?.()?.getTime();
2944
+ return upgradeWebSocket((ws) => acceptSocket(request, deadline === undefined ? ws : closingBeforeDeadline(ws, deadline)), { maxPayload: MAX_STREAM_MESSAGE_BYTES });
2945
+ }
2946
+ return handle(request, upgradesSockets || vercelUpgrades);
2947
+ }
2948
+ function nodeRequest(req) {
2949
+ const host = req.headers.host ?? "localhost";
2950
+ const headers = new Headers();
2951
+ for (const [name, value] of Object.entries(req.headers)) {
2952
+ if (value === undefined)
2953
+ continue;
2954
+ for (const item of Array.isArray(value) ? value : [value])
2955
+ headers.append(name, item);
2956
+ }
2957
+ const hasBody = req.method !== "GET" && req.method !== "HEAD";
2958
+ // A body parser mounted before nodeHandler (express.json(), express.raw())
2959
+ // has read the stream already: its buffer is the body, or nothing is.
2960
+ const parsed = req.body;
2961
+ // No bytes to read: what a parser made of nothing (`{}`) doesn't matter.
2962
+ const empty = req.headers["content-length"] === "0" ||
2963
+ (req.headers["content-length"] === undefined &&
2964
+ req.headers["transfer-encoding"] === undefined);
2965
+ const json = /^application\/json\b/i.test(req.headers["content-type"] ?? "");
2966
+ let body;
2967
+ if (hasBody && req.readableEnded) {
2968
+ if (parsed instanceof Uint8Array) {
2969
+ body = parsed;
2970
+ }
2971
+ else if (empty) {
2972
+ body = undefined;
2973
+ }
2974
+ else if (json && parsed !== null && typeof parsed === "object") {
2975
+ // express.json()'s result: Jazz's JSON routes read it as JSON again
2976
+ // (none signs its bytes), so it serves as the body.
2977
+ body = JSON.stringify(parsed);
2978
+ headers.delete("content-length");
2979
+ }
2980
+ else {
2981
+ throw new Error("jazz: the request body was already read by another handler; mount jazz.nodeHandler before body parsers such as express.json()");
2982
+ }
2983
+ }
2984
+ else if (hasBody) {
2985
+ body = req;
2986
+ }
2987
+ const request = new Request(`http://${host}${req.url ?? "/"}`, {
2988
+ method: req.method,
2989
+ headers,
2990
+ ...(body === undefined ? {} : { body, duplex: "half" }),
2991
+ });
2992
+ const address = req.socket?.remoteAddress;
2993
+ if (address)
2994
+ remoteAddresses.set(request, address);
2995
+ return request;
2996
+ }
2997
+ function nodeHandler(req, res, next) {
2998
+ // Only Jazz's own paths: a request for the app passes on untouched, its
2999
+ // body unread, whatever read it before.
3000
+ const pathname = requestPathname(req.url);
3001
+ if (pathname === null || (pathname !== basePath && !pathname.startsWith(`${basePath}/`))) {
3002
+ if (next)
3003
+ return next();
3004
+ res.statusCode = 404;
3005
+ res.end();
3006
+ return;
3007
+ }
3008
+ let request;
3009
+ try {
3010
+ request = nodeRequest(req);
3011
+ }
3012
+ catch (error) {
3013
+ console.error(error instanceof Error ? error.message : error);
3014
+ // A code the client reports, so the browser doesn't fail silently.
3015
+ res.statusCode = 500;
3016
+ res.end("request_body_already_read");
3017
+ return;
3018
+ }
3019
+ void handle(request).then(async (response) => {
3020
+ res.statusCode = response.status;
3021
+ response.headers.forEach((value, name) => res.setHeader(name, value));
3022
+ if (!response.body)
3023
+ return void res.end();
3024
+ res.flushHeaders();
3025
+ const reader = response.body.getReader();
3026
+ res.on("close", () => void reader.cancel().catch(() => undefined));
3027
+ for (;;) {
3028
+ const { done, value } = await reader.read();
3029
+ if (done)
3030
+ break;
3031
+ res.write(value);
3032
+ }
3033
+ res.end();
3034
+ }, (error) => {
3035
+ // The reason stays in the backend's logs, not in the response.
3036
+ console.error("jazz: request failed", error);
3037
+ res.statusCode = 500;
3038
+ res.end("Internal error");
3039
+ });
3040
+ }
3041
+ function upgrade(wss, req, socket, head) {
3042
+ let request;
3043
+ try {
3044
+ request = nodeRequest(req);
3045
+ }
3046
+ catch {
3047
+ // A request no URL can be made of (a bad Host header).
3048
+ socket.end(BAD_UPGRADE);
3049
+ return;
3050
+ }
3051
+ const path = innerPath(request);
3052
+ if (path === null || !SOCKET_PATH.test(path))
3053
+ return void socket.end(BAD_UPGRADE);
3054
+ if (!originAllowed(request)) {
3055
+ socket.end("HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n");
3056
+ return;
3057
+ }
3058
+ wss.handleUpgrade(req, socket, head, (ws) => acceptSocket(request, ws));
3059
+ }
3060
+ function markAttached() {
3061
+ upgradesSockets = true;
3062
+ attached = true;
3063
+ }
3064
+ // The Inspector follows `reload`: it reads the current options each time.
3065
+ let schemaOf = null;
3066
+ const inspector = createInspector({
3067
+ appId,
3068
+ get basePath() {
3069
+ return basePath;
3070
+ },
3071
+ get publicUrls() {
3072
+ return publicUrls;
3073
+ },
3074
+ schema: () => {
3075
+ if (schemaOf?.app !== options.app) {
3076
+ schemaOf = { app: options.app, schema: resolveSchemaSource(options.app) };
3077
+ }
3078
+ return schemaOf.schema;
3079
+ },
3080
+ get permissions() {
3081
+ return compiledPermissionsOf(options);
3082
+ },
3083
+ db: () => backend.db,
3084
+ dbAs: async (user) => backendDbForSession(backend, await sessionFor(user, "inspect `as`")),
3085
+ sessions: () => [...liveSessions].map(({ session: live, transport, openedAt }) => ({
3086
+ userId: live.userId ?? null,
3087
+ kind: live.trusted ? "backend-client" : live.userId === undefined ? "guest" : "user",
3088
+ transport,
3089
+ openedAt,
3090
+ })),
3091
+ get hook() {
3092
+ return options.inspect;
3093
+ },
3094
+ get options() {
3095
+ return options.inspector ?? NO_INSPECTOR_OPTIONS;
3096
+ },
3097
+ tokenSecret: async () => {
3098
+ const configured = options.inspector?.tokenSecret;
3099
+ if (configured !== undefined)
3100
+ return configured;
3101
+ if (store.kind === "remote")
3102
+ return store.secret ?? null;
3103
+ if (store.kind === "sqlite")
3104
+ return core.tokenSecret ?? null;
3105
+ if (store.kind === "memory")
3106
+ return memoryTokenSecret;
3107
+ // A Vercel core's only credential is the function's OIDC token: there
3108
+ // is no shared secret to sign with.
3109
+ return null;
3110
+ },
3111
+ remoteAddress: (request) => remoteAddresses.get(request),
3112
+ serveUi: createInspectorUi(),
3113
+ });
3114
+ let closing;
3115
+ return {
3116
+ appId,
3117
+ get basePath() {
3118
+ return basePath;
3119
+ },
3120
+ reload,
3121
+ handle: (request) => handle(request),
3122
+ next: () => ({ GET: nextHandler, POST: nextHandler, DELETE: nextHandler }),
3123
+ upgrade,
3124
+ markAttached,
3125
+ nodeHandler,
3126
+ acceptSocket,
3127
+ get db() {
3128
+ return backend.db;
3129
+ },
3130
+ linkIdentity,
3131
+ async forReqUser(request) {
3132
+ const who = await requestSession(request, "forReqUser", true);
3133
+ if (!who)
3134
+ throw signedOut("forReqUser");
3135
+ return backendDbForSession(backend, who);
3136
+ },
3137
+ async withAttribution(request, options) {
3138
+ const who = await requestSession(request, "withAttribution", options?.deviceAccounts === true);
3139
+ if (!who)
3140
+ throw signedOut("withAttribution");
3141
+ return backendDbAttributedTo(backend, who);
3142
+ },
3143
+ async accountFor(request, options) {
3144
+ const answer = await requestAnswer(request);
3145
+ if (answer === null)
3146
+ return null;
3147
+ if (answer === "device-account") {
3148
+ if (options?.deviceAccounts !== true)
3149
+ return null;
3150
+ const device = await deviceAccountOf(request);
3151
+ return device?.account ?? null;
3152
+ }
3153
+ return existingAccountOf(answer.userId);
3154
+ },
3155
+ async createAccountFor(userId) {
3156
+ if (typeof userId !== "string" || userId === "")
3157
+ throw new Error("createAccountFor: pass the user's id, as your authenticate names it");
3158
+ return accountOf(userId);
3159
+ },
3160
+ async revokeUser(userId) {
3161
+ if (typeof userId !== "string" || userId === "")
3162
+ throw new Error("revokeUser: pass the user's id, as your authenticate names it");
3163
+ // Sessions whose `authenticate` started before now end, wherever they
3164
+ // are served.
3165
+ const revokedBefore = Date.now();
3166
+ let ended = 0;
3167
+ for (const { session } of [...liveSessions]) {
3168
+ if (session.trusted)
3169
+ continue;
3170
+ // A session still signing in may turn out to be theirs: its
3171
+ // `authenticate` may have read their cookie before the app ended it.
3172
+ if (session.userId === undefined)
3173
+ session.revokeWhileAdmitting(userId);
3174
+ if (session.userId !== userId)
3175
+ continue;
3176
+ session.revoke("revokeUser");
3177
+ ended += 1;
3178
+ }
3179
+ // The core ends the sessions other instances serve (on serverless,
3180
+ // usually not this one), and refuses any they admit later on an
3181
+ // `authenticate` answer from before now.
3182
+ try {
3183
+ await adminAccountsCall("revoke-sessions", { identity: identity(userId), revokedBefore });
3184
+ }
3185
+ catch (error) {
3186
+ // A core without the route: only this instance's sessions end.
3187
+ // The route never answers 404 itself (a refused secret is 401/403,
3188
+ // a core without a registry 503), so any 404 means it's missing.
3189
+ if (error.status !== 404)
3190
+ throw error;
3191
+ warnNoCoreRevocation();
3192
+ }
3193
+ return ended;
3194
+ },
3195
+ close() {
3196
+ closing ??= (async () => {
3197
+ // Every client connection ends, so the host's own shutdown (which
3198
+ // waits for the connections it serves) can finish, and the clients
3199
+ // reconnect to whichever instance serves next.
3200
+ for (const stream of [...streams.values()]) {
3201
+ stream.session.close();
3202
+ stream.end(1012, "server shutting down");
3203
+ }
3204
+ streams.clear();
3205
+ for (const ws of [...clientSockets]) {
3206
+ ws.resume?.();
3207
+ ws.close(1012, "server shutting down");
3208
+ }
3209
+ clientSockets.clear();
3210
+ await Promise.all([...retiring].map((close) => close()));
3211
+ // Writes that resolved at the "local" tier may still be on their way
3212
+ // to the core. Hand them over before closing it, so a close right
3213
+ // after a write never loses it.
3214
+ const timer = setTimeout(() => backend.db.abortGracefulShutdown(), CLOSE_SYNC_TIMEOUT_MS);
3215
+ await backend
3216
+ .shutdown({ waitForSync: true })
3217
+ .catch((error) => {
3218
+ console.warn("Jazz backend closed before every write reached the core.", error);
3219
+ })
3220
+ .finally(() => clearTimeout(timer));
3221
+ await session.close();
3222
+ await core.close();
3223
+ })();
3224
+ return closing;
3225
+ },
3226
+ };
3227
+ }
3228
+ /**
3229
+ * Run Jazz inside your backend. It applies the schema, migrations and
3230
+ * permissions your code declares to its core (in this process, or a remote
3231
+ * one), and serves sync on your own origin under `basePath`. There is no
3232
+ * separate deploy step: a rollback of your backend rolls Jazz back with it.
3233
+ *
3234
+ * It opens nothing when called, so a module can export it at its top level:
3235
+ * the store opens on first use (a request, a `db` call, `ready()`). A process
3236
+ * runs one Jazz per store (a `sqlite()` directory, a `vercel()` core): a
3237
+ * later `createJazz` for it (a dev server's hot reload, another module
3238
+ * graph) returns that same Jazz with the later
3239
+ * call's app, permissions and options. Each `remote()` and `memory()` store
3240
+ * is its own: a module that hot reloads keeps that Jazz across reloads
3241
+ * itself, or closes it.
3242
+ */
3243
+ export function createJazz(options) {
3244
+ jazzSettings(options);
3245
+ return openFacade(options);
3246
+ }
3247
+ /**
3248
+ * `createJazz` for a test harness that fronts a test core with `remote()`
3249
+ * (`startTestJazz`): its apps may be defined in code with
3250
+ * `{ migrations: "none" }`, as a test's are. Not exported to apps.
3251
+ */
3252
+ export function createTestJazz(options) {
3253
+ jazzSettings(options);
3254
+ // A test's app is defined in code: the project's committed files describe
3255
+ // another, so there is nothing to compare it with.
3256
+ testHarnessOptions.add(options);
3257
+ return openFacade(options);
3258
+ }
3259
+ /** The options of `createTestJazz` calls, which skip {@link checkRunningBindings}. */
3260
+ const testHarnessOptions = new WeakSet();
3261
+ /** What the Rust loader made of each options' bindings and permissions file, once checked. */
3262
+ const compiled = new WeakMap();
3263
+ /** The checked permissions of options {@link compiledPermissions} has loaded. */
3264
+ function compiledPermissionsOf(options) {
3265
+ const loaded = compiled.get(options);
3266
+ if (!loaded)
3267
+ throw new Error("createJazz: the app's permissions are not loaded yet");
3268
+ return loaded.permissions;
3269
+ }
3270
+ /**
3271
+ * Check the app's bindings and permissions and compile the permissions with
3272
+ * Jazz's Rust loader, as `jazz-tools generate` checks them: refused when the
3273
+ * bindings were generated from another jazz.app.json than the project's
3274
+ * (stale bindings), or when jazz.permissions.json doesn't hold for the
3275
+ * app's schema. A deployed backend without jazz.app.json in reach checks
3276
+ * only the permissions.
3277
+ */
3278
+ async function compiledPermissions(options) {
3279
+ const cached = compiled.get(options);
3280
+ if (cached)
3281
+ return cached.permissions;
3282
+ const bound = boundAppOf(options.app);
3283
+ // Jazz's loader through a static jazz-napi import, so bundlers and file
3284
+ // tracers (Next.js, Vercel) ship the addon with the backend.
3285
+ provideCodegenNapi(backendNative().codegen);
3286
+ if (!testHarnessOptions.has(options) && backendNative().host === "node")
3287
+ await checkRunningBindings(bound.source);
3288
+ const permissions = options.permissions;
3289
+ // `$schema` names the file's version; a legacy (pre-alpha.66) file has `format`.
3290
+ if (!isRecord(permissions) ||
3291
+ (typeof permissions.$schema !== "string" && typeof permissions.format !== "number")) {
3292
+ throw new Error('createJazz: `permissions` must be the app\'s jazz.permissions.json, imported as JSON: `import permissions from "./jazz.permissions.json" with { type: "json" }`.');
3293
+ }
3294
+ let loaded;
3295
+ try {
3296
+ loaded = await loadBackendApp(bound, JSON.stringify(permissions));
3297
+ }
3298
+ catch (error) {
3299
+ const message = error instanceof Error ? error.message : String(error);
3300
+ throw new Error(`createJazz: ${message}`, { cause: error });
3301
+ }
3302
+ for (const warning of loaded.warnings)
3303
+ console.warn(`jazz: ${warning}`);
3304
+ compiled.set(options, loaded);
3305
+ return loaded.permissions;
3306
+ }
3307
+ function isRecord(value) {
3308
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3309
+ }
3310
+ /** What the generated bindings passed to `bindApp`, or a refusal naming where `app` comes from. */
3311
+ function boundAppOf(app) {
3312
+ let schema;
3313
+ try {
3314
+ schema = resolveSchemaSource(app);
3315
+ }
3316
+ catch (error) {
3317
+ // A CommonJS-wrapped bindings module says so itself, with its fix.
3318
+ const message = error instanceof Error ? error.message : "";
3319
+ throw new Error(message.includes("arrived as { default: … }")
3320
+ ? `createJazz: ${message}`
3321
+ : 'createJazz: `app` must be the app that jazz.generated.ts exports (`import { app } from "./jazz.generated"`).', { cause: error });
3322
+ }
3323
+ const bound = boundApp(schema);
3324
+ if (!bound) {
3325
+ throw new Error('createJazz: `app` must be the app that jazz.generated.ts exports (`import { app } from "./jazz.generated"`); ' +
3326
+ "run `npx jazz-tools generate` to generate it, or see https://jazz.tools/docs/operating/backups-and-upgrades#upgrading-from-alpha70-to-beta0 for an alpha.64 app.");
3327
+ }
3328
+ return bound;
3329
+ }
3330
+ function openFacade(options) {
3331
+ // Checked at startup, so a missing `ws` is in the logs before the first socket.
3332
+ if (onVercelHost())
3333
+ void vercelUpgradesSockets();
3334
+ const store = runningStore(options.store);
3335
+ const key = storeKey(store);
3336
+ const entries = registry();
3337
+ const shared = key === undefined ? undefined : entries.get(key);
3338
+ if (shared && !shared.closing) {
3339
+ adoptStore(shared, store);
3340
+ shared.options = options;
3341
+ return shared.jazz;
3342
+ }
3343
+ // A Jazz for this store still closing: the new one opens once it let go.
3344
+ const entry = newEntry(options, store, key, shared?.released);
3345
+ if (key !== undefined)
3346
+ entries.set(key, entry);
3347
+ return entry.jazz;
3348
+ }
3349
+ /** How long a session a reload replaced stays open for the requests still using it. */
3350
+ const RETIRED_SESSION_GRACE_MS = 60_000;
3351
+ /** How long `close()` waits for a store still opening before it gives up on it. */
3352
+ export const CLOSE_WAITS_FOR_OPEN_MS = 30_000;
3353
+ /** A failed open is tried again after this, doubling up to `MAX_OPEN_RETRY_MS`. */
3354
+ const FIRST_OPEN_RETRY_MS = 1_000;
3355
+ const MAX_OPEN_RETRY_MS = 30_000;
3356
+ /** At most this many sockets wait for the store to open, each holding at most this much. */
3357
+ export const MAX_HELD_SOCKETS = 1_000;
3358
+ export const MAX_HELD_SOCKET_BYTES = 4 * 1024 * 1024;
3359
+ const REGISTRY = Symbol.for("jazz-tools.createJazz.stores");
3360
+ /**
3361
+ * Open stores by key, on `globalThis` so that two copies of this module
3362
+ * (a bundler's server and route chunks, a hot reload) share them.
3363
+ */
3364
+ function registry() {
3365
+ const scope = globalThis;
3366
+ return (scope[REGISTRY] ??= new Map());
3367
+ }
3368
+ /**
3369
+ * The store's identity in this process: one Jazz runs per store, so a hot
3370
+ * reload finds the one it opened. A `remote()` store has none: two
3371
+ * backends (deployments, tests) may each run their own Jazz on one remote
3372
+ * app, with their own permissions. Nor has a `memory()` store, a new,
3373
+ * empty database each time. A module that hot reloads keeps such a Jazz
3374
+ * across reloads itself (on `globalThis`), or closes it.
3375
+ */
3376
+ function storeKey(store) {
3377
+ if (store.kind === "sqlite")
3378
+ return `sqlite:${resolve(store.path)}`;
3379
+ if (store.kind === "vercel") {
3380
+ const project = store.options.credentials?.projectId ?? process.env.VERCEL_PROJECT_ID;
3381
+ let name;
3382
+ try {
3383
+ name = project ? coreName(project, store.options.namespace, process.env).name : undefined;
3384
+ }
3385
+ catch {
3386
+ // No namespace for this deployment: its open reports that, not createJazz.
3387
+ }
3388
+ // Without a name the core is unknown: its open reports that.
3389
+ return name ? `vercel:${name}` : undefined;
3390
+ }
3391
+ return undefined;
3392
+ }
3393
+ /**
3394
+ * What a store's settings are. The functions it holds (a credential hook)
3395
+ * are not settings: the open store calls the latest call's. A Sandbox SDK
3396
+ * is: another one is another setting.
3397
+ */
3398
+ function storeSettings(store) {
3399
+ return JSON.stringify(store, (name, value) => {
3400
+ if (name === "sdk" && value !== undefined)
3401
+ return `sdk#${identity(value)}`;
3402
+ return typeof value === "function" ? "function" : value;
3403
+ });
3404
+ }
3405
+ const identities = new WeakMap();
3406
+ let lastIdentity = 0;
3407
+ function identity(value) {
3408
+ let id = identities.get(value);
3409
+ if (id === undefined)
3410
+ identities.set(value, (id = ++lastIdentity));
3411
+ return id;
3412
+ }
3413
+ /**
3414
+ * The entry's store, its function settings (a credential hook) calling
3415
+ * through to the latest `createJazz` call's, so a reload applies them.
3416
+ */
3417
+ function liveStore(entry) {
3418
+ const through = (value, current) => {
3419
+ const out = { ...value };
3420
+ for (const [name, field] of Object.entries(value)) {
3421
+ if (typeof field !== "function")
3422
+ continue;
3423
+ out[name] = (...args) => {
3424
+ const latest = current()?.[name];
3425
+ return (typeof latest === "function" ? latest : field)(...args);
3426
+ };
3427
+ }
3428
+ return out;
3429
+ };
3430
+ const store = entry.store;
3431
+ if (store.kind === "vercel") {
3432
+ return {
3433
+ ...store,
3434
+ options: through(store.options, () => entry.store.kind === "vercel" ? entry.store.options : undefined),
3435
+ };
3436
+ }
3437
+ return through(store, () => entry.store);
3438
+ }
3439
+ /**
3440
+ * A later `createJazz` for an entry's store. Before the store opens it takes
3441
+ * the new settings; once open, settings that would need another core are
3442
+ * refused, so a change never silently goes unapplied.
3443
+ */
3444
+ function adoptStore(entry, store) {
3445
+ if (!entry.opening && !entry.opened) {
3446
+ entry.store = store;
3447
+ // A later call (a hot reload after a fix) tries the open again at once.
3448
+ entry.failure = undefined;
3449
+ return;
3450
+ }
3451
+ if (storeSettings(store) !== storeSettings(entry.store)) {
3452
+ throw new Error(`createJazz(): ${entry.key} is already open in this process with other store settings; restart the process to change them`);
3453
+ }
3454
+ // The same settings: its function settings are the latest call's now.
3455
+ entry.store = store;
3456
+ }
3457
+ function newEntry(options, store, key, after) {
3458
+ const entry = { key, store, options, after };
3459
+ entry.jazz = facade(entry);
3460
+ return entry;
3461
+ }
3462
+ /**
3463
+ * The entry's open Jazz, with the latest call's options applied. Once it is
3464
+ * closing, only `draining` (the writes made before the close) still gets it.
3465
+ */
3466
+ async function settled(entry, draining = false) {
3467
+ for (;;) {
3468
+ if (entry.closing && !draining)
3469
+ throw new Error("createJazz: this Jazz was closed");
3470
+ const opened = await (entry.opening ?? openEntry(entry));
3471
+ if (entry.closing && !draining)
3472
+ throw new Error("createJazz: this Jazz was closed");
3473
+ if (entry.applied === entry.options)
3474
+ return opened;
3475
+ await (entry.reloading ??= reloadEntry(entry, opened));
3476
+ }
3477
+ }
3478
+ /**
3479
+ * Open the entry's store. A failed open is not tried again at once: until
3480
+ * its backoff has passed, every use fails with the same error, so a store
3481
+ * that is down is not asked again on every request.
3482
+ */
3483
+ function openEntry(entry) {
3484
+ const failed = entry.failure;
3485
+ if (failed && Date.now() < failed.retryAt)
3486
+ return Promise.reject(failed.error);
3487
+ const options = entry.options;
3488
+ const opening = (async () => {
3489
+ await entry.after;
3490
+ return openJazz(options, liveStore(entry));
3491
+ })().then((opened) => {
3492
+ entry.failure = undefined;
3493
+ if (entry.attached)
3494
+ opened.markAttached();
3495
+ entry.opened = opened;
3496
+ entry.applied = options;
3497
+ drainOnSignal(entry);
3498
+ return opened;
3499
+ }, (error) => {
3500
+ const delayMs = failed
3501
+ ? Math.min(failed.delayMs * 2, MAX_OPEN_RETRY_MS)
3502
+ : FIRST_OPEN_RETRY_MS;
3503
+ entry.failure = { error, retryAt: Date.now() + delayMs, delayMs };
3504
+ if (entry.opening === opening)
3505
+ entry.opening = undefined;
3506
+ throw error;
3507
+ });
3508
+ entry.opening = opening;
3509
+ return opening;
3510
+ }
3511
+ /** The signals a host stops a server with (a deploy, a rolling restart, Ctrl-C). */
3512
+ const SHUTDOWN_SIGNALS = ["SIGTERM", "SIGINT"];
3513
+ /** Every open Jazz in this process, closed when the process is asked to stop. */
3514
+ const drained = new Set();
3515
+ const onShutdownSignal = (signal) => void shutDownOnSignal(signal);
3516
+ /**
3517
+ * Close every open Jazz when the process is asked to stop. A host's own
3518
+ * shutdown (`next start`, an Effect runtime, `server.close()`) waits for the
3519
+ * connections it serves, and Jazz's sync sockets and streams last until Jazz
3520
+ * ends them: without this, the process lingers and keeps its store locked
3521
+ * for as long as a browser stays connected. The clients reconnect to
3522
+ * whichever instance serves next. With no other handler for the signal the
3523
+ * process then stops as it would have; otherwise that handler decides.
3524
+ */
3525
+ function drainOnSignal(entry) {
3526
+ if (typeof process === "undefined" || typeof process.on !== "function")
3527
+ return;
3528
+ if (drained.size === 0) {
3529
+ for (const signal of SHUTDOWN_SIGNALS)
3530
+ process.on(signal, onShutdownSignal);
3531
+ }
3532
+ drained.add(entry);
3533
+ }
3534
+ function undrain(entry) {
3535
+ if (!drained.delete(entry) || drained.size > 0)
3536
+ return;
3537
+ for (const signal of SHUTDOWN_SIGNALS)
3538
+ process.off(signal, onShutdownSignal);
3539
+ }
3540
+ async function shutDownOnSignal(signal) {
3541
+ for (const each of SHUTDOWN_SIGNALS)
3542
+ process.off(each, onShutdownSignal);
3543
+ const open = [...drained];
3544
+ drained.clear();
3545
+ await Promise.allSettled(open.map((entry) => entry.jazz.close()));
3546
+ // Nobody else asked to handle it: stop the way the signal would have.
3547
+ if (process.listenerCount(signal) === 0)
3548
+ process.kill(process.pid, signal);
3549
+ }
3550
+ /**
3551
+ * Close the entry: apply the writes made before the close, then close its
3552
+ * store. A store still opening is waited for at most
3553
+ * `CLOSE_WAITS_FOR_OPEN_MS`; past that the writes still waiting fail and
3554
+ * the store closes once it has opened. Until it has, a new `createJazz` for
3555
+ * the store waits for it rather than finding the store held.
3556
+ */
3557
+ async function closeEntry(entry, early) {
3558
+ let release;
3559
+ entry.released = new Promise((resolve) => (release = resolve));
3560
+ const stopped = (async () => {
3561
+ await early.drain();
3562
+ const opened = await entry.opening?.catch(() => undefined);
3563
+ await entry.reloading?.catch(() => undefined);
3564
+ await opened?.close();
3565
+ })();
3566
+ void stopped
3567
+ .catch(() => undefined)
3568
+ .finally(() => {
3569
+ if (entry.key !== undefined && registry().get(entry.key) === entry) {
3570
+ registry().delete(entry.key);
3571
+ }
3572
+ undrain(entry);
3573
+ release();
3574
+ });
3575
+ let timer;
3576
+ const gaveUp = new Promise((resolve) => {
3577
+ timer = setTimeout(() => resolve(true), CLOSE_WAITS_FOR_OPEN_MS);
3578
+ });
3579
+ const late = await Promise.race([stopped.then(() => false), gaveUp]);
3580
+ clearTimeout(timer);
3581
+ if (!late)
3582
+ return;
3583
+ early.abandon(new Error("createJazz: closed before its store opened"));
3584
+ console.warn(`jazz: close() gave up after ${CLOSE_WAITS_FOR_OPEN_MS / 1000}s waiting for ${entry.key ?? "its store"} to open; it closes once it has`);
3585
+ }
3586
+ async function reloadEntry(entry, opened) {
3587
+ const options = entry.options;
3588
+ try {
3589
+ await opened.reload(options);
3590
+ entry.applied = options;
3591
+ }
3592
+ finally {
3593
+ entry.reloading = undefined;
3594
+ }
3595
+ }
3596
+ /** The entry's open Jazz when nothing is left to apply, without waiting. */
3597
+ function settledNow(entry) {
3598
+ return !entry.closing && entry.applied === entry.options ? entry.opened : undefined;
3599
+ }
3600
+ /**
3601
+ * A socket handed over before the store opened: it keeps what arrives until
3602
+ * the session takes it over, so no message is lost while it waits. Past
3603
+ * `MAX_HELD_SOCKET_BYTES` held, it is closed (1013, try again later).
3604
+ */
3605
+ function heldSocket(ws) {
3606
+ const held = [];
3607
+ let heldBytes = 0;
3608
+ let listeners = null;
3609
+ const deliver = (event) => {
3610
+ if (!listeners) {
3611
+ if (event[0] === "message") {
3612
+ heldBytes += byteLength(event[1]);
3613
+ if (heldBytes > MAX_HELD_SOCKET_BYTES) {
3614
+ held.length = 0;
3615
+ ws.close(1013, "store still opening");
3616
+ return;
3617
+ }
3618
+ }
3619
+ return void held.push(event);
3620
+ }
3621
+ if (event[0] === "message")
3622
+ listeners.message?.(event[1], event[2]);
3623
+ else if (event[0] === "close")
3624
+ listeners.close?.();
3625
+ else
3626
+ listeners.error?.(event[1]);
3627
+ };
3628
+ ws.on("message", (data, isBinary) => deliver(["message", data, isBinary]));
3629
+ ws.on("close", () => deliver(["close"]));
3630
+ ws.on("error", (error) => deliver(["error", error]));
3631
+ const socket = {
3632
+ send: (data) => ws.send(data),
3633
+ close: (code, reason) => ws.close(code, reason),
3634
+ pause: () => ws.pause?.(),
3635
+ resume: () => ws.resume?.(),
3636
+ on(event, listener) {
3637
+ const first = listeners === null;
3638
+ listeners ??= {};
3639
+ listeners[event] = listener;
3640
+ // The session adds its listeners in one go: replay once it has.
3641
+ if (first) {
3642
+ queueMicrotask(() => {
3643
+ for (const event of held.splice(0))
3644
+ deliver(event);
3645
+ });
3646
+ }
3647
+ return socket;
3648
+ },
3649
+ };
3650
+ return { socket, refuse: (reason) => ws.close(1011, reason) };
3651
+ }
3652
+ function byteLength(data) {
3653
+ if (typeof data === "string")
3654
+ return data.length * 3;
3655
+ if (Array.isArray(data))
3656
+ return data.reduce((sum, part) => sum + byteLength(part), 0);
3657
+ const sized = data;
3658
+ return typeof sized?.byteLength === "number" ? sized.byteLength : 0;
3659
+ }
3660
+ /**
3661
+ * A remote core that could not be reached, named, instead of the bare
3662
+ * `fetch failed` the request saw. The next use of this Jazz tries again.
3663
+ */
3664
+ function unreachableCore(url, error) {
3665
+ const cause = error?.cause;
3666
+ if (!(error instanceof TypeError) || !cause)
3667
+ return error;
3668
+ const why = typeof cause.code === "string" ? cause.code : String(cause.message ?? error.message);
3669
+ return new Error(`createJazz: could not reach the Jazz core at ${url} (${why}); this Jazz tries again on its next use`, { cause: error });
3670
+ }
3671
+ async function socketUpgrader() {
3672
+ const { WebSocketServer } = await importWs("attach()");
3673
+ return new WebSocketServer({
3674
+ noServer: true,
3675
+ maxPayload: MAX_STREAM_MESSAGE_BYTES,
3676
+ });
3677
+ }
3678
+ /** A sync socket's path below `basePath`. */
3679
+ const SOCKET_PATH = /^\/apps\/[^/]+\/ws$/;
3680
+ /** Whether an upgrade's URL is a sync socket of this Jazz (`<basePath>/apps/<app>/ws`). */
3681
+ function isSocketUpgrade(url, basePath) {
3682
+ const pathname = requestPathname(url);
3683
+ return (pathname !== null &&
3684
+ pathname.startsWith(`${basePath}/`) &&
3685
+ SOCKET_PATH.test(pathname.slice(basePath.length)));
3686
+ }
3687
+ /** A Node request's path, or null for one no URL can be made of: not Jazz's. */
3688
+ function requestPathname(url) {
3689
+ try {
3690
+ return new URL(url ?? "/", "http://localhost").pathname;
3691
+ }
3692
+ catch {
3693
+ return null;
3694
+ }
3695
+ }
3696
+ /**
3697
+ * Whether `server` is an HTTP/2 server that can't serve HTTP/1: one without
3698
+ * upgrades (h2c, or TLS without `allowHTTP1`). Node keeps the options under
3699
+ * a symbol; a server that hides them is taken as able.
3700
+ */
3701
+ function http2Only(server) {
3702
+ const name = server.constructor?.name;
3703
+ if (name === "Http2Server")
3704
+ return true;
3705
+ if (name !== "Http2SecureServer")
3706
+ return false;
3707
+ const key = Object.getOwnPropertySymbols(server).find((symbol) => symbol.description === "options");
3708
+ const options = key
3709
+ ? server[key]
3710
+ : undefined;
3711
+ return options !== undefined && options.allowHTTP1 !== true;
3712
+ }
3713
+ /**
3714
+ * What a 503 tells the client to wait: until the store is tried again. The
3715
+ * reason stays in the backend's logs; it can name internal hosts.
3716
+ */
3717
+ function retryAfterSeconds(entry) {
3718
+ const at = entry.failure?.retryAt;
3719
+ return at === undefined ? 1 : Math.max(1, Math.ceil((at - Date.now()) / 1000));
3720
+ }
3721
+ const UNAVAILABLE_BODY = "Jazz is unavailable; try again shortly";
3722
+ /**
3723
+ * The 503 a Jazz route answers while its store can't open, or after it
3724
+ * closed. After a close it also closes the connection: a host shutting down
3725
+ * (`next start` on SIGTERM) waits for its keep-alive connections, and a
3726
+ * client re-opening its sync stream over one would keep it, and the
3727
+ * process, alive. (A Fetch response can't tell an HTTP/2 host, which drops
3728
+ * the header with a warning; nodeHandler leaves it off there.)
3729
+ */
3730
+ function storeUnavailable(retryAfter, closed, error) {
3731
+ const why = devStoreError(closed ? undefined : error);
3732
+ return new Response(why ? `${UNAVAILABLE_BODY}: ${why}` : UNAVAILABLE_BODY, {
3733
+ status: 503,
3734
+ headers: {
3735
+ "content-type": "text/plain",
3736
+ "retry-after": String(retryAfter),
3737
+ ...(why ? { [STORE_ERROR_HEADER]: "1" } : {}),
3738
+ ...(closed ? { connection: "close" } : {}),
3739
+ },
3740
+ });
3741
+ }
3742
+ /**
3743
+ * Header on a 503 whose body says why the store did not open. Only in
3744
+ * development (NODE_ENV "development"): there the reason (a deploy the store
3745
+ * refused, say) otherwise shows only in the server log, while the browser
3746
+ * sees a generic refusal and retries (#5053). The client's socket probe
3747
+ * reads it and logs it in the browser console.
3748
+ */
3749
+ const STORE_ERROR_HEADER = "x-jazz-store-error";
3750
+ /** Why the store did not open, for a 503's body in development; else undefined. */
3751
+ function devStoreError(error) {
3752
+ if (error === undefined || typeof process === "undefined")
3753
+ return undefined;
3754
+ if (process.env.NODE_ENV !== "development")
3755
+ return undefined;
3756
+ const message = error instanceof Error ? error.message : String(error);
3757
+ return `the store did not open: ${message}`;
3758
+ }
3759
+ const storeUnavailableUpgrade = (retryAfter) => `HTTP/1.1 503 Service Unavailable\r\nRetry-After: ${retryAfter}\r\nConnection: close\r\n\r\n`;
3760
+ const BAD_UPGRADE = "HTTP/1.1 400 Bad Request\r\nConnection: close\r\n\r\n";
3761
+ /** The `Jazz` every `createJazz` for one store returns. */
3762
+ function facade(entry) {
3763
+ const use = () => settled(entry);
3764
+ const basePath = () => jazzSettings(entry.options).basePath;
3765
+ // After close() its routes answer 503 as the host shuts down: no news.
3766
+ const logUnavailable = (error) => {
3767
+ if (!entry.closing)
3768
+ console.error("jazz: the store did not open", error);
3769
+ };
3770
+ /** The open Jazz, or the 503 a Jazz route answers while its store can't open. */
3771
+ const useOr503 = async () => {
3772
+ try {
3773
+ return await use();
3774
+ }
3775
+ catch (error) {
3776
+ logUnavailable(error);
3777
+ return storeUnavailable(retryAfterSeconds(entry), entry.closing !== undefined, error);
3778
+ }
3779
+ };
3780
+ const handle = async (request) => {
3781
+ const opened = await useOr503();
3782
+ return opened instanceof Response ? opened : opened.handle(request);
3783
+ };
3784
+ const nextHandler = async (request) => {
3785
+ const opened = await useOr503();
3786
+ return opened instanceof Response ? opened : opened.next().GET(request);
3787
+ };
3788
+ // The writes made before a close still apply as it drains them.
3789
+ const early = earlyDb(async () => (await settled(entry, true)).db, () => settledNow(entry)?.db);
3790
+ const db = early.db;
3791
+ let heldSockets = 0;
3792
+ /** The servers `attach()` took the upgrades of: a second call changes nothing. */
3793
+ const attachedTo = new WeakSet();
3794
+ const jazz = {
3795
+ get basePath() {
3796
+ return basePath();
3797
+ },
3798
+ handle,
3799
+ next: () => ({ GET: nextHandler, POST: nextHandler, DELETE: nextHandler }),
3800
+ async attach(server) {
3801
+ // An HTTP/2 server without HTTP/1 never sees a WebSocket upgrade.
3802
+ if (http2Only(server)) {
3803
+ throw new Error("attach(): an HTTP/2 server has no WebSocket upgrades; pass an HTTP/1 server (or an HTTPS one with allowHTTP1), or serve Jazz with handle() alone, over its HTTP stream");
3804
+ }
3805
+ if (attachedTo.has(server))
3806
+ return;
3807
+ attachedTo.add(server);
3808
+ const wss = await socketUpgrader();
3809
+ // Upgrades work from now on, opened or not: the store opens on the
3810
+ // first socket (or request), and one that can't open is refused with
3811
+ // a 503 the client retries, instead of failing the host's startup.
3812
+ entry.attached = true;
3813
+ entry.opened?.markAttached();
3814
+ const take = (opened, req, socket, head) => {
3815
+ try {
3816
+ opened.upgrade(wss, req, socket, head);
3817
+ }
3818
+ catch (error) {
3819
+ console.error("jazz: a socket upgrade failed", error);
3820
+ socket.destroy();
3821
+ }
3822
+ };
3823
+ const upgradeJazz = (req, socket, head) => {
3824
+ const now = settledNow(entry);
3825
+ if (now)
3826
+ return take(now, req, socket, head);
3827
+ use().then((opened) => take(opened, req, socket, head), (error) => {
3828
+ logUnavailable(error);
3829
+ socket.end(storeUnavailableUpgrade(retryAfterSeconds(entry)));
3830
+ });
3831
+ };
3832
+ const events = server;
3833
+ // Jazz's own sync sockets go to Jazz alone: another upgrade listener
3834
+ // on the server (a custom Next.js server adds one on its first
3835
+ // request) would take the same socket too, and close it. The listener
3836
+ // is there because Node only emits upgrades to a server that has one.
3837
+ events.on("upgrade", () => undefined);
3838
+ const emit = events.emit;
3839
+ events.emit = function (event, ...args) {
3840
+ if (event === "upgrade" && isSocketUpgrade(args[0].url, basePath())) {
3841
+ upgradeJazz(...args);
3842
+ return true;
3843
+ }
3844
+ return emit.call(this, event, ...args);
3845
+ };
3846
+ events.on("close", () => wss.close());
3847
+ },
3848
+ nodeHandler(req, res, next) {
3849
+ const now = settledNow(entry);
3850
+ if (now)
3851
+ return now.nodeHandler(req, res, next);
3852
+ const prefix = basePath();
3853
+ const pathname = requestPathname(req.url);
3854
+ // Requests Jazz doesn't serve pass on without opening the store.
3855
+ if (pathname === null || (pathname !== prefix && !pathname.startsWith(`${prefix}/`))) {
3856
+ if (next)
3857
+ return next();
3858
+ res.statusCode = 404;
3859
+ res.end();
3860
+ return;
3861
+ }
3862
+ use().then((opened) => opened.nodeHandler(req, res, next), (error) => {
3863
+ logUnavailable(error);
3864
+ res.statusCode = 503;
3865
+ res.setHeader("retry-after", String(retryAfterSeconds(entry)));
3866
+ // HTTP/2 has no Connection header (Node warns and drops it).
3867
+ if (entry.closing && req.httpVersionMajor < 2)
3868
+ res.setHeader("connection", "close");
3869
+ res.setHeader("content-type", "text/plain");
3870
+ const why = devStoreError(entry.closing ? undefined : error);
3871
+ if (why)
3872
+ res.setHeader(STORE_ERROR_HEADER, "1");
3873
+ res.end(why ? `${UNAVAILABLE_BODY}: ${why}` : UNAVAILABLE_BODY);
3874
+ });
3875
+ },
3876
+ acceptSocket(request, ws) {
3877
+ const now = settledNow(entry);
3878
+ if (now)
3879
+ return now.acceptSocket(request, ws);
3880
+ if (heldSockets >= MAX_HELD_SOCKETS)
3881
+ return ws.close(1013, "store still opening");
3882
+ heldSockets++;
3883
+ const { socket, refuse } = heldSocket(ws);
3884
+ use()
3885
+ .then((opened) => opened.acceptSocket(request, socket), (error) => {
3886
+ logUnavailable(error);
3887
+ refuse("store unavailable");
3888
+ })
3889
+ .finally(() => heldSockets--);
3890
+ },
3891
+ db,
3892
+ forReqUser: async (request) => (await use()).forReqUser(request),
3893
+ withAttribution: async (request, options) => (await use()).withAttribution(request, options),
3894
+ accountFor: async (request, options) => (await use()).accountFor(request, options),
3895
+ createAccountFor: async (userId) => (await use()).createAccountFor(userId),
3896
+ revokeUser: async (userId) => (await use()).revokeUser(userId),
3897
+ linkIdentity: async (link) => (await use()).linkIdentity(link),
3898
+ async ready() {
3899
+ await use();
3900
+ return jazz;
3901
+ },
3902
+ close() {
3903
+ return (entry.closing ??= closeEntry(entry, early));
3904
+ },
3905
+ };
3906
+ // Not enumerable, so printing or comparing a Jazz before it opens reads it not.
3907
+ Object.defineProperty(jazz, "appId", {
3908
+ get() {
3909
+ const opened = entry.opened;
3910
+ if (!opened) {
3911
+ throw new Error("jazz.appId is known once the store has opened: `await jazz.ready()` first");
3912
+ }
3913
+ return opened.appId;
3914
+ },
3915
+ });
3916
+ return jazz;
3917
+ }
3918
+ /** An account request the core answered with a 4xx: a refusal, not an outage. */
3919
+ function isRefusal(error) {
3920
+ const status = error?.status;
3921
+ // Timeouts and throttling are 4xx too, but pass.
3922
+ if (status === 408 || status === 425 || status === 429)
3923
+ return false;
3924
+ return typeof status === "number" && status >= 400 && status < 500;
3925
+ }
3926
+ function refusalCode(error) {
3927
+ const message = error instanceof Error ? error.message : "";
3928
+ const code = /: ([a-z_]{1,80})$/.exec(message)?.[1];
3929
+ return code ?? "refused";
3930
+ }
3931
+ /** How long before a sync session must end its client is asked to renew it, at most. */
3932
+ const RENEWAL_LEAD_MS = 60_000;
3933
+ /** The least time before a session must end that a renewal is still asked for. */
3934
+ const MIN_RENEWAL_NOTICE_MS = 2_000;
3935
+ /**
3936
+ * The ticket in `batch` when it is a client's lone renew frame (see
3937
+ * `session-renewal-wire.ts`), else null. Looks at a few bytes before
3938
+ * decoding anything, so sync traffic passes untouched.
3939
+ */
3940
+ function renewalTicketIn(batch) {
3941
+ if (batch.byteLength > 4096 || batch[0] !== 1)
3942
+ return null;
3943
+ let offset = 1;
3944
+ while (offset < batch.byteLength && (batch[offset] & 0x80) !== 0)
3945
+ offset += 1;
3946
+ if (batch[offset + 1] !== WIRE_FRAME_RENEW)
3947
+ return null;
3948
+ try {
3949
+ const frames = decodeWebSocketFrameBatch(batch);
3950
+ return frames.length === 1 ? decodeRenewFrame(frames[0]) : null;
3951
+ }
3952
+ catch {
3953
+ return null;
3954
+ }
3955
+ }
3956
+ /** JSON with object keys sorted, so equal claims always digest alike. */
3957
+ function stableJson(value) {
3958
+ if (Array.isArray(value))
3959
+ return `[${value.map(stableJson).join(",")}]`;
3960
+ if (value && typeof value === "object") {
3961
+ const entries = Object.entries(value)
3962
+ .filter(([, item]) => item !== undefined)
3963
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
3964
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableJson(item)}`).join(",")}}`;
3965
+ }
3966
+ return JSON.stringify(value) ?? "null";
3967
+ }
3968
+ /** A fetch `Request`, also from another realm or framework (Next's `NextRequest`). */
3969
+ function isRequestLike(value) {
3970
+ return (!!value &&
3971
+ typeof value === "object" &&
3972
+ typeof value.url === "string" &&
3973
+ typeof value.headers?.get === "function");
3974
+ }
3975
+ /** A fetch `Response`, also from another realm or framework (Next's `NextResponse`). */
3976
+ function isResponseLike(value) {
3977
+ return (!!value &&
3978
+ typeof value === "object" &&
3979
+ typeof value.status === "number" &&
3980
+ typeof value.headers?.get === "function");
3981
+ }
3982
+ /** A WireFrame::Error batch with code AuthFailed and retry Never. */
3983
+ /**
3984
+ * The error a session sends its client when the expiry its app's auth gave
3985
+ * it is near: `auth_failed` with `after_resume` retry, which a client takes
3986
+ * as "connect again now" (`isReauthenticateWireError`). A client that
3987
+ * doesn't know it takes it as a refused credential and asks its backend.
3988
+ */
3989
+ function reauthenticateBatch(clientFeatures) {
3990
+ return Buffer.from(encodeAuthFailedBatch("after_resume", `${REAUTHENTICATE_WIRE_MESSAGE_PREFIX} the session reached the expiry authenticate gave it`, "reauthenticate", clientFeatures));
3991
+ }
3992
+ /** How long a refusal before the client's Hello waits for it (see `awaitHello`). */
3993
+ const HELLO_WAIT_MS = 1_000;
3994
+ /**
3995
+ * What `admitPrelude` answers for a credential the client sent that doesn't
3996
+ * verify on this backend: the client reports it as `invalid`, not `missing`.
3997
+ */
3998
+ const UNVERIFIED_CREDENTIAL = "unverified-credential";
3999
+ /**
4000
+ * Prelude slots that carry a credential. When the client sends a distinct
4001
+ * `auth` object, `admitPrelude` reads these from `auth` alone and drops any
4002
+ * top-level copy, so a credential it checks is exactly the one forwarded to
4003
+ * the core (`local_first_audience` is the backend's own word on a guest's
4004
+ * endpoint, never the client's).
4005
+ */
4006
+ const PRELUDE_CREDENTIAL_FIELDS = [
4007
+ "jwt_token",
4008
+ "backend_secret",
4009
+ "admin_secret",
4010
+ "backend_session",
4011
+ "local_first_audience",
4012
+ ];
4013
+ /**
4014
+ * What a Jazz route answers (500) when the app's `authenticate` threw. The
4015
+ * error goes to the backend's log; the response carries only this code.
4016
+ */
4017
+ const AUTHENTICATE_FAILED = "authenticate_failed";
4018
+ /**
4019
+ * What a Jazz route answers (503, with Retry-After) when the app's
4020
+ * `authenticate` could not check a credential because its identity
4021
+ * provider is unreachable (`fromJWT`'s JWKS).
4022
+ */
4023
+ const AUTHENTICATION_UNAVAILABLE = "authentication_unavailable";
4024
+ /** What the backend logs, before the error, when the app's `authenticate` threw. */
4025
+ const AUTHENTICATE_THREW_MESSAGE = "createJazz: your authenticate threw, so Jazz answered this request with a 500. Fix the error below (a missing secret or environment variable is a common cause); authenticate should return null for a request with no signed-in user.";
4026
+ /** Errors the app's `authenticate` threw (or rejected with), as they reach a route. */
4027
+ const thrownByAuthenticate = new WeakSet();
4028
+ function isThrownByAuthenticate(error) {
4029
+ return isObject(error) && thrownByAuthenticate.has(error);
4030
+ }
4031
+ function isObject(value) {
4032
+ return (typeof value === "object" && value !== null) || typeof value === "function";
4033
+ }
4034
+ /**
4035
+ * A refused credential (`auth_failed`, retry `never`), naming `reason` to a
4036
+ * client whose Hello offered `FEATURE_TYPED_ERROR_REASON`. The message keeps
4037
+ * its reason word first, for clients that read it from there.
4038
+ */
4039
+ function authFailedBatch(message, reason, clientFeatures) {
4040
+ return Buffer.from(encodeAuthFailedBatch("never", message, reason, clientFeatures));
4041
+ }
4042
+ /** A development endpoint on this machine, where header-derived audiences are fine. */
4043
+ function isLocalEndpoint(endpoint) {
4044
+ try {
4045
+ const host = new URL(endpoint).hostname;
4046
+ return (host === "localhost" ||
4047
+ host.endsWith(".localhost") ||
4048
+ host === "127.0.0.1" ||
4049
+ host === "[::1]");
4050
+ }
4051
+ catch {
4052
+ return false;
4053
+ }
4054
+ }
4055
+ /** Thin sessions with transactions a backend serves at once, each with a client of its own. */
4056
+ const MAX_THIN_TRANSACTION_CLIENTS = 256;
4057
+ /** `socket`, sending `prelude` in place of the first message a client sends. */
4058
+ function withPrelude(socket, prelude) {
4059
+ let first = true;
4060
+ const replace = (data) => {
4061
+ if (!first)
4062
+ return data;
4063
+ first = false;
4064
+ return prelude;
4065
+ };
4066
+ return {
4067
+ send: (data) => socket.send(replace(data)),
4068
+ async sendWithRoom(data) {
4069
+ const sent = replace(data);
4070
+ return socket.sendWithRoom ? socket.sendWithRoom(sent) : socket.send(sent);
4071
+ },
4072
+ close: () => socket.close(),
4073
+ ...(socket.opened ? { opened: socket.opened } : {}),
4074
+ };
4075
+ }
4076
+ //# sourceMappingURL=create-jazz.js.map