@lunora/client 1.0.0-alpha.21 → 1.0.0-alpha.211

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 (89) hide show
  1. package/README.md +16 -3
  2. package/dist/auth/index.d.mts +43 -12
  3. package/dist/auth/index.d.ts +43 -12
  4. package/dist/auth/index.mjs +1 -60
  5. package/dist/index.d.mts +809 -268
  6. package/dist/index.d.ts +809 -268
  7. package/dist/index.mjs +1 -15
  8. package/dist/packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs +1 -0
  9. package/dist/packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs +1 -0
  10. package/dist/packem_shared/LunoraClient-BSI0RIrs.mjs +1 -0
  11. package/dist/packem_shared/OfflineQueue-BWamzR6p.mjs +1 -0
  12. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  13. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  14. package/dist/packem_shared/SubscriptionRegistry-5CHmk3d8.mjs +1 -0
  15. package/dist/packem_shared/TabCoordinator-CXD7vulJ.mjs +1 -0
  16. package/dist/packem_shared/applyDelta-UuKQOPo1.mjs +1 -0
  17. package/dist/packem_shared/createAsyncStoragePersistence-DXlhLrFv.mjs +1 -0
  18. package/dist/packem_shared/createAsyncStorageQueryCache-CAPNYhcK.mjs +1 -0
  19. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  20. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  21. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  22. package/dist/packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs +1 -0
  23. package/dist/packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs +1 -0
  24. package/dist/packem_shared/createLocalStore-CriEK0Fm.mjs +1 -0
  25. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  26. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  27. package/dist/packem_shared/createServerClient-D7ZQOnat.mjs +1 -0
  28. package/dist/packem_shared/createSnapshotPrecondition-D-WkMTIs.mjs +1 -0
  29. package/dist/packem_shared/delta-merge-CDCNlktH.mjs +1 -0
  30. package/dist/packem_shared/deserializePreloaded-CEQci6cB.mjs +1 -0
  31. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  32. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  33. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  34. package/dist/packem_shared/httpStream-B5J3zeB8.mjs +9 -0
  35. package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
  36. package/dist/packem_shared/local-store-CtP_1rJj.mjs +1 -0
  37. package/dist/packem_shared/lunora-client.d-B-1VFscs.d.mts +4647 -0
  38. package/dist/packem_shared/lunora-client.d-_Qd50jQo.d.ts +4647 -0
  39. package/dist/packem_shared/offline-queue-D_fr-uQ3.mjs +1 -0
  40. package/dist/packem_shared/preload.d-D82baNUQ.d.mts +21 -0
  41. package/dist/packem_shared/preload.d-ubxA2STh.d.ts +21 -0
  42. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  43. package/dist/packem_shared/single-blob-store-D7kYfN1I.mjs +1 -0
  44. package/dist/packem_shared/wire-codec-3Mj5UgNj.mjs +1 -0
  45. package/dist/packem_shared/wire-errors-CYMmnEcW.mjs +1 -0
  46. package/dist/packem_shared/wire-key-3XBGlnux.mjs +1 -0
  47. package/dist/pagination/index.d.mts +42 -42
  48. package/dist/pagination/index.d.ts +42 -42
  49. package/dist/pagination/index.mjs +1 -61
  50. package/dist/query/index.d.mts +111 -43
  51. package/dist/query/index.d.ts +111 -43
  52. package/dist/query/index.mjs +1 -1
  53. package/dist/service.d.mts +49 -0
  54. package/dist/service.d.ts +49 -0
  55. package/dist/service.mjs +1 -0
  56. package/dist/ssr/index.d.mts +109 -79
  57. package/dist/ssr/index.d.ts +109 -79
  58. package/dist/ssr/index.mjs +1 -4
  59. package/dist/upload.d.mts +35 -0
  60. package/dist/upload.d.ts +35 -0
  61. package/dist/upload.mjs +1 -0
  62. package/package.json +14 -2
  63. package/dist/packem_shared/CONFLICT_ERROR_CODE-B8gQ8tyU.mjs +0 -33
  64. package/dist/packem_shared/DEFAULT_MAX_BUFFER-7hFnzNk9.mjs +0 -110
  65. package/dist/packem_shared/LunoraClient-kXpHNyaE.mjs +0 -3460
  66. package/dist/packem_shared/OfflineQueue-GGYJRmhF.mjs +0 -1
  67. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  68. package/dist/packem_shared/SubscriptionRegistry-DjGKZsqq.mjs +0 -1
  69. package/dist/packem_shared/applyDelta-CRKZ1PBt.mjs +0 -81
  70. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  71. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  72. package/dist/packem_shared/createInMemoryPersistence-DZ2VHWgm.mjs +0 -79
  73. package/dist/packem_shared/createInMemoryQueryCache-DiaGZkA2.mjs +0 -112
  74. package/dist/packem_shared/createLocalStore-jRoqmazl.mjs +0 -2
  75. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  76. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  77. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  78. package/dist/packem_shared/createServerClient-DF-3mLmb.mjs +0 -11
  79. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  80. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  81. package/dist/packem_shared/idb-utility-DrSVX43Q.mjs +0 -48
  82. package/dist/packem_shared/local-store-BveBeFEo.mjs +0 -106
  83. package/dist/packem_shared/lunora-client.d-BYkEjCEJ.d.mts +0 -2540
  84. package/dist/packem_shared/lunora-client.d-BYkEjCEJ.d.ts +0 -2540
  85. package/dist/packem_shared/offline-queue-B9vfdSqp.mjs +0 -170
  86. package/dist/packem_shared/preload.d-B-vyHnml.d.ts +0 -20
  87. package/dist/packem_shared/preload.d-DrfuisCE.d.mts +0 -20
  88. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  89. package/dist/packem_shared/subscription-BjynOXCU.mjs +0 -68
package/dist/index.mjs CHANGED
@@ -1,15 +1 @@
1
- export { createAsyncStoragePersistence } from './packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs';
2
- export { default as createInMemoryBookmarkStorage } from './packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs';
3
- export { applyDelta, isMutationDelta } from './packem_shared/applyDelta-CRKZ1PBt.mjs';
4
- export { CONFLICT_ERROR_CODE, getErrorCode, getRetryAfterMs, isConflictError, isForbiddenError, isRateLimitedError, isUnauthorizedError } from './packem_shared/CONFLICT_ERROR_CODE-B8gQ8tyU.mjs';
5
- export { c as createLocalStore } from './packem_shared/local-store-BveBeFEo.mjs';
6
- export { LunoraClient } from './packem_shared/LunoraClient-kXpHNyaE.mjs';
7
- export { createMutationRunner } from './packem_shared/createMutationRunner-BqsavzvG.mjs';
8
- export { createMutatorRunner } from './packem_shared/createMutatorRunner-BETvCd0p.mjs';
9
- export { O as OfflineQueue } from './packem_shared/offline-queue-B9vfdSqp.mjs';
10
- export { createInMemoryPersistence, createIndexedDbPersistence } from './packem_shared/createInMemoryPersistence-DZ2VHWgm.mjs';
11
- export { preloadQuery, preloadedQueryResult } from './packem_shared/preloadQuery-lobFkD2Z.mjs';
12
- export { createInMemoryQueryCache, createIndexedDbQueryCache, queryCacheKey } from './packem_shared/createInMemoryQueryCache-DiaGZkA2.mjs';
13
- export { createReconnect } from './packem_shared/createReconnect-Di_-oHH7.mjs';
14
- export { DEFAULT_MAX_BUFFER, createStream } from './packem_shared/DEFAULT_MAX_BUFFER-7hFnzNk9.mjs';
15
- export { S as SubscriptionRegistry } from './packem_shared/subscription-BjynOXCU.mjs';
1
+ import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as o,maxSeq as t,reconcileOptimistic as a}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as n}from"./packem_shared/createAsyncStoragePersistence-DXlhLrFv.mjs";import{createAsyncStorageQueryCache as i}from"./packem_shared/createAsyncStorageQueryCache-CAPNYhcK.mjs";import{default as f}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as x}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as l}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as d}from"./packem_shared/TabCoordinator-CXD7vulJ.mjs";import{a as R,i as C}from"./packem_shared/delta-merge-CDCNlktH.mjs";import{CONFLICT_ERROR_CODE as S,TransportError as h,getErrorCode as D,getRetryAfterMs as Q,isAuthReplayFailure as _,isConflictError as F,isForbiddenError as I,isRateLimitedError as M,isUnauthorizedError as g}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as O}from"./packem_shared/httpStream-B5J3zeB8.mjs";import{c as b}from"./packem_shared/local-store-CtP_1rJj.mjs";import{LunoraClient as U}from"./packem_shared/LunoraClient-BSI0RIrs.mjs";import{createMutatorRunner as k}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as N}from"./packem_shared/offline-queue-D_fr-uQ3.mjs";import{createInMemoryPersistence as K,createIndexedDbPersistence as V}from"./packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs";import{preloadQuery as j,preloadedQueryResult as v}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as G,createIndexedDbQueryCache as H,queryCacheKey as J}from"./packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as Y}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as $}from"./packem_shared/createSnapshotPrecondition-D-WkMTIs.mjs";import{DEFAULT_MAX_BUFFER as re,createStream as oe}from"./packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as ae}from"./packem_shared/SubscriptionRegistry-5CHmk3d8.mjs";export{S as CONFLICT_ERROR_CODE,re as DEFAULT_MAX_BUFFER,U as LunoraClient,N as OfflineQueue,o as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,ae as SubscriptionRegistry,d as TabCoordinator,h as TransportError,R as applyDelta,n as createAsyncStoragePersistence,i as createAsyncStorageQueryCache,x as createCallRunner,l as createClientQuery,f as createInMemoryBookmarkStorage,K as createInMemoryPersistence,G as createInMemoryQueryCache,V as createIndexedDbPersistence,H as createIndexedDbQueryCache,b as createLocalStore,k as createMutatorRunner,Y as createReconnect,$ as createSnapshotPrecondition,oe as createStream,D as getErrorCode,Q as getRetryAfterMs,O as httpStream,_ as isAuthReplayFailure,F as isConflictError,I as isForbiddenError,C as isMutationDelta,M as isRateLimitedError,g as isUnauthorizedError,t as maxSeq,j as preloadQuery,v as preloadedQueryResult,J as queryCacheKey,a as reconcileOptimistic};
@@ -0,0 +1 @@
1
+ import{ERROR_CATALOG as e,LunoraError as n}from"@lunora/errors";const s=new Set(Object.keys(e));class R extends n{constructor(o,t){super("INTERNAL",o,{data:t})}}const E="CONFLICT",a=r=>r instanceof Error&&r.code===E,O=r=>r instanceof Error&&r.code==="FORBIDDEN",d=r=>r instanceof Error&&r.code==="UNAUTHORIZED",N=r=>r instanceof Error&&r.code==="TOO_MANY_REQUESTS",T=r=>{if(!(r instanceof Error))return;const{code:o}=r;return typeof o=="string"&&s.has(o)?o:void 0},f=r=>{const o=r?.data?.retryAfterMs;return typeof o=="number"&&Number.isFinite(o)?o:void 0},c=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),u=r=>c.has(r?.code??"");export{c as AUTH_REPLAY_ERROR_CODES,E as CONFLICT_ERROR_CODE,R as TransportError,T as getErrorCode,f as getRetryAfterMs,u as isAuthReplayFailure,a as isConflictError,O as isForbiddenError,N as isRateLimitedError,d as isUnauthorizedError};
@@ -0,0 +1 @@
1
+ import{LunoraError as h}from"@lunora/errors";const m=1024,p=f=>{const i=f.maxBuffer??m,r=[],o=[];let n=!1,t,l=!1;const u=()=>{const e=o.shift();if(!e)return!1;if(t)return e.reject(t),!0;if(r.length>0){const s=r.shift();return e.resolve({done:!1,value:s}),!0}return n?(e.resolve({done:!0,value:void 0}),!0):(o.unshift(e),!1)},a={complete(){if(!(n||t))for(n=!0;u(););},fail(e){if(!(n||t))for(t=e,r.length=0;u(););},push(e){if(!(n||t||l)){if(r.length>=i){a.fail(new h("STREAM_BACKPRESSURE",`stream buffer overflow (max=${i.toString()}); the consumer cannot keep up with the producer`));return}r.push(e),u()}}},c=()=>{if(!l){l=!0,n=!0,r.length=0;try{f.onCancel()}catch{}for(;u(););}};return{handle:a,iterable:{cancel:c,[Symbol.asyncIterator](){return{next(){if(t)return Promise.reject(t);if(r.length>0){const e=r.shift();return Promise.resolve({done:!1,value:e})}return n?Promise.resolve({done:!0,value:void 0}):new Promise((e,s)=>{o.push({reject:s,resolve:e})})},return(){return c(),Promise.resolve({done:!0,value:void 0})}}}}}};export{m as DEFAULT_MAX_BUFFER,p as createStream};
@@ -0,0 +1 @@
1
+ import{LunoraError as y}from"@lunora/errors";import{t as Re,a as L,d as C}from"./wire-codec-3Mj5UgNj.mjs";import{r as Pe,U as Fe,P as He}from"./delta-merge-CDCNlktH.mjs";import{s as ae}from"./wire-key-3XBGlnux.mjs";import Le from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{s as J,a as Me,e as U,r as Ue,b as oe,c as Ne,d as ce}from"./wire-errors-CYMmnEcW.mjs";import{ClientQueryStore as xe}from"./createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as De}from"./TabCoordinator-CXD7vulJ.mjs";import{TransportError as H,getRetryAfterMs as Be,AUTH_REPLAY_ERROR_CODES as Qe,isAuthReplayFailure as q}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as Ke}from"./httpStream-B5J3zeB8.mjs";import{d as Y,r as I,a as R,b as qe,c as We,e as je,f as $e}from"./local-store-CtP_1rJj.mjs";import{O as Ge,n as de,i as Ve,r as ze}from"./offline-queue-D_fr-uQ3.mjs";import{resolvePersistenceAdapter as Je}from"./createInMemoryPersistence-Cz2W6XVj.mjs";import{resolveQueryCacheAdapter as Ye,queryCacheKey as A}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as ue}from"./createReconnect-CjTmjJDH.mjs";import{fanSubscriptionError as E,SubscriptionRegistry as v,wrapSubscriber as W}from"./SubscriptionRegistry-5CHmk3d8.mjs";import Xe from"./createSnapshotPrecondition-D-WkMTIs.mjs";import{createStream as Ze}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";const j=500,Se=(i,e)=>{if(i.size<e)return;const t=i.keys().next().value;t!==void 0&&i.delete(t)};new TextDecoder;const et=new TextEncoder,tt=i=>Re(et.encode(JSON.stringify(i))),st="x-lunora-expect-subject",rt=i=>tt({subject:i}),he=Symbol.for("lunora:session-change"),it="lunora:session-change",nt="better-auth.message",at="signout",Te=()=>{const i=globalThis;let e=i[he];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},i[he]=e),e},ot=()=>"document"in globalThis,ct=async()=>{const i=[];for(const e of Te().listeners)try{i.push(e())}catch{}await Promise.allSettled(i)},dt=(i,e)=>{if(i!==nt||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===at}catch{return!1}},ut=i=>{const e=[],t=()=>{ct().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(it):void 0}catch{s=void 0}if(s!==void 0){const n=s;n.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==i&&t()}),e.push(()=>{n.close()})}const r=globalThis;if(typeof r.addEventListener=="function"){const n=o=>{dt(o.key,o.newValue)&&t()};r.addEventListener("storage",n),e.push(()=>{r.removeEventListener?.("storage",n)})}return()=>{for(const n of e)n()}},ht=i=>{const e=Te();return e.listeners.add(i),e.detach===void 0&&ot()&&(e.detach=ut(e.tab)),()=>{e.listeners.delete(i),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},lt="/_lunora/rpc",$="/_lunora/rpc-batch",ft="/_lunora/ws",pt="/_lunora/admin/shard-traffic",mt="/_lunora/admin/scheduled",yt="/_lunora/admin/scheduled/status",bt="/_lunora/admin/scheduled/ws",St="/_lunora/admin/scheduled/cancel",le="/_lunora/admin/scheduled/dead",Tt="/_lunora/admin/scheduled/dead/retry",gt="/_lunora/admin/scheduled/dead/cancel",vt="/_lunora/admin/workflows/instances",Ct="/_lunora/admin/workflows/instance",kt="/_lunora/admin/workflows/status",te="/_lunora/admin/storage",wt="/_lunora/admin/storage/url",Et="/_lunora/admin/storage/buckets",At="/_lunora/admin/functions",_t="/_lunora/admin/cron-jobs",It="/_lunora/admin/cron-jobs/run",Ot="/_lunora/admin/architecture",Rt="/_lunora/admin/openapi",Pt="/_lunora/admin/openrpc",Ft="/_lunora/admin/global/tables",Ht="/_lunora/admin/global/table",Lt="/_lunora/admin/global/facet",Mt="/_lunora/admin/vector/indexes",Ut="/_lunora/admin/vector/query",Nt="/_lunora/admin/logs/archive",xt="/_lunora/admin/kv/namespaces",Dt="/_lunora/admin/kv/keys",se="/_lunora/admin/kv/value",Bt="/_lunora/admin/auth/users",Qt="/_lunora/admin/auth/sessions",Kt="/_lunora/admin/auth/users/create",qt="/_lunora/admin/auth/users/role",Wt="/_lunora/admin/auth/users/ban",jt="/_lunora/admin/auth/users/unban",$t="/_lunora/admin/auth/users/password",Gt="/_lunora/admin/auth/users/remove",Vt="/_lunora/admin/auth/users/impersonate",zt="/_lunora/admin/auth/sessions/revoke",Jt="/_lunora/admin/auth/sessions/revoke-all",Yt="/_lunora/admin/auth/capabilities",Xt="/_lunora/admin/auth/users/update",Zt="/_lunora/admin/auth/accounts",es="/_lunora/admin/auth/accounts/unlink",ts="/_lunora/admin/auth/passkeys",ss="/_lunora/admin/auth/passkeys/delete",rs="/_lunora/admin/auth/two-factor/disable",is="/_lunora/admin/auth/organizations",ns="/_lunora/admin/auth/organizations/members",as="/_lunora/admin/auth/organizations/invitations",os="/_lunora/admin/auth/organizations/members/remove",cs="/_lunora/admin/auth/organizations/invitations/cancel",ds="/_lunora/admin/auth/config",us="/_lunora/admin/auth/sign-up-invitations",hs="/_lunora/admin/auth/sign-up-invitations/create",ls="/_lunora/admin/auth/sign-up-invitations/revoke",fs="/_lunora/admin/auth/organizations/create",ps="/_lunora/admin/auth/organizations/update",ms="/_lunora/admin/auth/organizations/remove",ys="/_lunora/admin/auth/organizations/members/add",bs="/_lunora/admin/auth/organizations/members/invite",Ss="/_lunora/admin/auth/organizations/members/role",Ts="/_lunora/admin/auth/organizations/teams",gs="/_lunora/admin/auth/organizations/teams/create",vs="/_lunora/admin/auth/organizations/teams/update",Cs="/_lunora/admin/auth/organizations/teams/remove",ks="/_lunora/admin/auth/organizations/teams/members",ws="/_lunora/admin/auth/organizations/teams/members/add",Es="/_lunora/admin/auth/organizations/teams/members/remove",As="/_lunora/admin/auth/organizations/roles",_s="/_lunora/admin/auth/organizations/roles/create",Is="/_lunora/admin/auth/organizations/roles/update",Os="/_lunora/admin/auth/organizations/roles/remove",Rs="/api/auth",Ps="/get-session",Fs="lunora-ping",Hs=async i=>(i.assertOpen(),(await i.adminFetch(At,"GET")).functions??[]),Ls=async i=>(i.assertOpen(),(await i.adminFetch(_t,"GET")).jobs??[]),Ms=async(i,e)=>{i.assertOpen();const t=await i.adminFetch(It,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}},Us=async i=>(i.assertOpen(),await i.adminFetch(Rt,"GET")),Ns=async i=>(i.assertOpen(),await i.adminFetch(Ot,"GET")),xs=async i=>(i.assertOpen(),await i.adminFetch(Pt,"GET")),Ds=async i=>(i.assertOpen(),await i.adminFetch(Ft,"GET")),Bs=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.offset!==void 0&&t.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(L(e.filters))),C(await i.adminFetch(`${Ht}?${t.toString()}`,"GET"))},Qs=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&t.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&t.set("filters",JSON.stringify(L(e.filters))),C(await i.adminFetch(`${Lt}?${t.toString()}`,"GET"))},re=i=>i===void 0||i===""?"":`&bucket=${encodeURIComponent(i)}`,fe=i=>i.startsWith("https://")?`wss://${i.slice(8)}`:i.startsWith("http://")?`ws://${i.slice(7)}`:i,k=(i,e)=>`${i.endsWith("/")?i.slice(0,-1):i}${e}`,b=(i,e)=>{const t=new URLSearchParams;for(const[r,n]of Object.entries(e))n!==void 0&&n!==""&&t.set(r,String(n));const s=t.toString();return s===""?i:`${i}?${s}`},Ks=async i=>(i.assertOpen(),(await i.adminFetch(xt,"GET")).namespaces??[]),qs=async(i,e)=>{i.assertOpen();const t=b(Dt,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await i.adminFetch(t,"GET")},Ws=async(i,e)=>{i.assertOpen();const t=b(se,{key:e.key,namespace:e.namespace});return await i.adminFetch(t,"GET")},js=async(i,e)=>{i.assertOpen(),await i.adminFetch(se,"PUT",e)},$s=async(i,e)=>{i.assertOpen();const t=b(se,{key:e.key,namespace:e.namespace});await i.adminFetch(t,"DELETE")},Gs=async(i,e)=>{i.assertOpen();const t=await i.adminFetch(pt,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}},Vs=async(i,e={})=>{i.assertOpen();const t=await i.adminFetch(Nt,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}},zs=async i=>{const e=[];let t;for(;;){const s=await i(t);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===t)throw new Error("collectPages: the list did not advance its cursor — refusing to page forever");t=s.cursor}},ie=i=>"args"in i?{...i,args:C(i.args)}:i,Js=async i=>(i.assertOpen(),((await i.adminFetch(mt,"GET")).records??[]).map(t=>ie(t))),Ys=async i=>{i.assertOpen();const e=await i.adminFetch(yt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},Xs=async(i,e)=>(i.assertOpen(),{cancelled:(await i.adminFetch(St,"POST",{id:e})).cancelled===!0}),Zs=async i=>(i.assertOpen(),(await zs(async t=>await i.adminFetch(t===void 0?le:`${le}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>ie(t))),er=async(i,e)=>(i.assertOpen(),{retried:(await i.adminFetch(Tt,"POST",{id:e})).retried===!0}),tr=async(i,e)=>(i.assertOpen(),{removed:(await i.adminFetch(gt,"POST",{id:e})).removed===!0}),sr=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({name:e.name});e.status!==void 0&&t.set("status",e.status),e.page!==void 0&&t.set("page",String(e.page)),e.perPage!==void 0&&t.set("perPage",String(e.perPage));const s=await i.adminFetch(`${vt}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}},rr=async(i,e)=>{i.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await i.adminFetch(`${Ct}?${t.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}},ir=async(i,e)=>(i.assertOpen(),{status:(await i.adminFetch(kt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),nr=async(i,e={})=>{i.assertOpen();const t=b(te,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await i.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}},ar=async(i,e,t)=>{i.assertOpen();const s=`${te}?key=${encodeURIComponent(e)}${re(t?.bucket)}`,r=await i.adminFetch(s,"DELETE");return{deleted:r.deleted===!0,key:r.key??e}},or=async i=>(i.assertOpen(),(await i.adminFetch(Et,"GET")).buckets??[]),cr=async(i,e)=>{i.assertOpen();const t=`${te}?key=${encodeURIComponent(e.key)}${re(e.bucket)}`,s=await i.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}},dr=async(i,e,t)=>{i.assertOpen();const s=t?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${wt}?key=${encodeURIComponent(e)}${r}${re(t?.bucket)}`,o=await i.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},ur=async i=>(i.assertOpen(),(await i.adminFetch(Mt,"GET")).indexes??[]),hr=async(i,e)=>(i.assertOpen(),(await i.adminFetch(Ut,"POST",e)).matches??[]),w=(i,e)=>{try{return L(i)}catch(t){const s=t instanceof Error?t.message:String(t);throw new TypeError(`LunoraClient: cannot encode ${e} — ${s}`,t instanceof Error?{cause:t}:void 0)}},pe=i=>{try{return L(i),!0}catch{return!1}},ge=i=>i!==null&&typeof i=="object"&&("error"in i||"result"in i),lr=(i,e)=>{const t=Array.from({length:e});for(const s of i){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;if(!ge(s.body)){t[s.id]={error:J({}),ok:!1};continue}const r=s.body;t[s.id]="error"in r?{error:J(r),ok:!1}:{ok:!0,value:C(r.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},G=(i,e)=>e!==null?{}:i===null?{expectSubject:null}:i?.startsWith("subj:")===!0?{expectSubject:i.slice(5)}:{},fr=3e4,pr=1e4,mr=5e3,yr=3,br=250,Sr=5e3,Tr=5e3,gr=64,vr=3,Cr=1e4,kr=8,V=i=>i==="connected"||i==="polling",l=i=>i??"",T=(i,e)=>{if(!i.socket||i.wsState!=="open")return!1;try{return i.socket.send(JSON.stringify(e)),!0}catch{return!1}},wr=i=>{if(!i.pendingStreams||i.pendingStreams.length===0)return;const e=i.pendingStreams;i.pendingStreams=[];for(const t of e)T(i,t)},Er=new TextDecoder,Ar=i=>{if(typeof i=="string")return i;if(i instanceof ArrayBuffer)return Er.decode(i)};class _{listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){const[t]=e;for(const s of this.listeners)try{s(t)}catch{}}clear(){this.listeners.clear()}}const F=i=>{i.heartbeatTimer!==void 0&&(clearInterval(i.heartbeatTimer),i.heartbeatTimer=void 0)},_r=(i,e,t)=>{F(i),!(e<=0)&&(i.heartbeatTimer=setInterval(()=>{if(!i.socket)return;const{socket:s}=i;if(Date.now()-i.lastFrameAt>e*2.5){try{s.close()}catch{}t();return}try{s.send(Fs)}catch{}},e))},me=(i,e,t,s)=>{const{WebSocketImpl:r,connectTimeoutMs:n,heartbeatIntervalMs:o}=t;if(r===void 0)throw new y("INTERNAL","no WebSocket implementation available");const a=new r(e);i.socket=a;const c=()=>{F(i),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),i.socket===a&&(i.socket=void 0)},d=u=>{c(),s.onClose(u)};n>0&&(i.connectTimer=setTimeout(()=>{if(i.connectTimer=void 0,i.socket===a){try{a.close()}catch{}d()}},n)),a.addEventListener("open",()=>{if(i.socket===a){i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),i.lastFrameAt=Date.now();try{s.onOpen?.()}catch(u){console.error("[lunora] connection open handler threw",u)}_r(i,o,d)}}),a.addEventListener("message",u=>{if(i.socket===a){i.lastFrameAt=Date.now();try{s.onMessage(u)}catch(h){console.error("[lunora] server frame handler threw",h)}}}),a.addEventListener("close",u=>{i.socket===a&&d(u)}),a.addEventListener("error",()=>{i.socket===a&&d()})},Ir=i=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:r,poll:n}=i,o=t>0&&e>0;let a=0,c,d=!1,u=!1;const h=()=>{c!==void 0&&(clearInterval(c),c=void 0,d=!1,r())},p=f=>{if(c!==void 0){if(!f){h();return}d||(d=!0,r()),s()}},m=()=>{u||(u=!0,n().then(p).finally(()=>{u=!1}).catch(()=>{}))};return{isPolling:()=>c!==void 0&&d,noteFailedOpen:()=>{a+=1,!(!o||c!==void 0||a<e)&&(c=setInterval(m,t),r(),m())},noteOpen:()=>{a=0,h()},stop:h}},Or=1e4,ye=async i=>{const e=new AbortController;let t;const s=new Promise((r,n)=>{t=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},Or)});try{return await Promise.race([i(e.signal),s])}catch(r){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):r}finally{clearTimeout(t)}},ve=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Rr=i=>{if(i instanceof H)return!0;const e=i?.code;return e===void 0||ve.has(e)||Qe.has(e)},Ce=6e4,Pr=1e3,Fr={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},P=(i,e,t)=>{const s=Me(t),r=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${i.toString()}${e?` ${e}`:""})`;return i<400||i>=500||i===408?new H(n,r):new y(Fr[i]??"BAD_REQUEST",n,{data:r})},X=(i,e=Math.random)=>{const t=Math.min(Pr*2**Math.max(i-1,0),Ce);return Math.round(t*(.5+e()*.5))},Hr=i=>i instanceof H||ve.has(i?.code??""),Lr=(i,e,t)=>{const s=Be(i);return s!==void 0&&s>0?Math.min(s,Ce):Hr(i)?X(e,t):void 0},Mr=983040,Ur=i=>typeof TextEncoder>"u"?i.length:new TextEncoder().encode(i).length,ke=new WeakSet,we=i=>{const e=new y("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) — ${i instanceof Error?i.message:String(i)}`,{cause:i});return ke.add(e),e},N=i=>i instanceof Error&&ke.has(i),Nr=i=>{const e=new Map;for(const t of i)typeof t.id=="number"&&ge(t.body)&&e.set(t.id,t.body);return e},xr=i=>{if(i===void 0)return{kind:"unanswered"};if("error"in i)return{error:J(i),kind:"errored"};try{return{commitCursor:i.commitCursor,kind:"committed",value:C(i.result)}}catch(e){return{commitCursor:i.commitCursor,error:we(e),kind:"undecodable"}}},z=(i,e)=>`${l(i)}\0${e}`,Dr=(i,e)=>{for(const t of e)t.op==="delete"?i.delete(t.key):t.value!==void 0&&i.set(t.key,t.value)};class Br{constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,t){Se(this.buffers,this.maxBuffers),this.buffers.set(z(e,t.pokeId),{baseCheckpoint:t.baseCheckpoint,bases:new Map,epoch:t.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,t){const s=this.buffers.get(z(e,t.pokeId));if(!s)return;const r=[];try{for(const a of t.rowsPatch)r.push(a.value===void 0?a:{...a,value:C(a.value)})}catch(a){s.undecodable.set(t.shapeId,a);return}const n=s.parts.get(t.shapeId)??[];for(const a of r)n.push(a);s.parts.set(t.shapeId,n),t.lastMutationId!==void 0&&s.lastMutationId.set(t.shapeId,t.lastMutationId);const o=t.baseCheckpoint??s.baseCheckpoint;o!==void 0&&s.bases.set(t.shapeId,o),t.reset===!0&&s.resets.add(t.shapeId)}end(e,t){const s=z(e,t),r=this.buffers.get(s);return r&&this.buffers.delete(s),r}clear(){this.buffers.clear()}}const Qr=(i,e,t)=>{const s=e.parts.get(i.id)??[],r=e.resets.has(i.id),n=e.bases.get(i.id),o=e.epoch!==void 0&&i.serverEpoch!==void 0&&e.epoch!==i.serverEpoch,a=n!==void 0&&i.serverCursor!==void 0&&i.serverCursor!==n;if(!r&&(o||a))return i.rows.clear(),i.serverCursor=void 0,i.serverEpoch=void 0,"reseed";r&&i.rows.clear(),Dr(i.rows,s),t.checkpoint!==void 0&&(i.serverCursor=t.checkpoint),t.epoch!==void 0&&(i.serverEpoch=t.epoch);const c=e.lastMutationId.get(i.id);return c!==void 0&&(i.lastMutationId=c),"applied"},be=i=>{const e=[...i.rows.values()];for(const t of i.callbacks)try{t(e)}catch{}},Kr=(i,e)=>{for(const[t,s]of e.undecodable){const r=i.get(t);r&&E(r.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${s instanceof Error?s.message:String(s)}`})}},Z=(i,e)=>{i.lastMutationId=Math.max(i.lastMutationId??0,e)},ee=(i,e=!1)=>{for(const t of i.checkpointCallbacks)t({checkpoint:i.serverCursor,mutationId:i.lastMutationId,...e&&{rowsFollow:!0}})},Ee=(i,e,t)=>{i.serverBase=e,t.cursor!==void 0&&(i.serverCursor=t.cursor),t.epoch!==void 0&&(i.serverEpoch=t.epoch)},x=(i,e)=>i!==void 0&&i!==e,qr=(i,e)=>e==="connected"&&i!=="connected"||e==="polling"&&i!=="connected"&&i!=="polling",Wr=i=>{for(const e of i.activeSubscriptions())i.ensureSocket(e.shardKey),i.queueResubscribe(e);for(const e of i.queuedShardKeys())i.ensureSocket(e);i.broadcastStatus(i.computeStatus(),i.identityFingerprint())},jr=i=>{i.closeConnections();const e=i.leader;e.status=void 0,e.wasEverConnected=!1},$r=(i,e,t)=>{if(x(t,i.identityFingerprint()))return;const s=i.leader,r=qr(s.status,e);s.status=e,e==="connected"&&(s.wasEverConnected=!0),i.emitConnectionStatus(),r&&i.flushOfflineQueues()},Gr=i=>{i.isLeader()&&i.broadcastStatus(i.computeStatus(),i.identityFingerprint())},Vr=(i,e,t,s,r,n)=>{if(x(n,i.identityFingerprint()))return;const o=i.subscription(e);o&&(i.dropCacheSeed(e),Ee(o,t,s===void 0?{}:{cursor:s,epoch:r}),s!==void 0&&Y(o,s),I(o,t))},zr=(i,e,t,s)=>{if(x(s,i.identityFingerprint()))return;const r=i.subscription(e);r&&E(r.errorCallbacks,t)},Jr=(i,e,t,s,r,n,o)=>{if(x(o,i.identityFingerprint()))return;const a=i.subscription(e);a&&(i.ackAndAdvanceCursor(a,t,s),r!==void 0&&n===i.clientIdentifier()&&Z(a,r),ee(a))},Yr=(i,e,t)=>i!==null||e&&t===null,Xr=[He],Zr=Promise.resolve();class Ae{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;adminHost={adminFetch:(...e)=>this.adminFetch(...e),assertOpen:()=>{this.assertOpen()}};clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new v;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new _;statusListeners=new _;tokenExpiredListeners=new _;identityChangeListeners=new _;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new _;pendingChangeListeners=new _;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Br(Ae.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??k(fe(e.url),ft),this.wsToken=e.wsToken;const t=e.authBasePath??Rs;this.authBasePath=t.endsWith("/")?t.slice(0,-1):t,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??Le(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??fr,this.connectTimeoutMs=e.connectTimeoutMs??pr,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??mr,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??yr,this.defaultConnectionContext=e.connectionContext,this.persistence=Je(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ye(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new xe,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Zr),this.offlineQueue=new Ge(e.offlineQueue,{onEvict:(s,r)=>{this.emitItemSettled(s,"rejected",r),this.releaseIdleShard(s.shardKey)},onSizeChange:s=>{this.pendingChangeListeners.emit(s)},persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${de()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=ht(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,r=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),a=this.isKnownNobody(),c=this.authToken;this.authToken=e,this.applySubject(e,t);const d=this.identityFingerprint();d!==r&&(!s&&e!==null&&n?(this.restampQueuedIdentity(r,d),this.restampWatermarks(r,d),this.restampConnectionIdentity(r,d),this.reseedFromHydratedCache()):!s&&e===null&&r===null&&n&&!a?(this.restampWatermarks(r,d),this.restampConnectionIdentity(r,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(r),this.warnRefreshWithoutSubject(c,e),Yr(r,a,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),s&&this.authTokenListeners.emit(e),(d!==r||s||o)&&this.offlineQueue.size>0&&V(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){const t=this.identityVerdict(e);if(t!=="match")return{verdict:t};const s=Object.freeze({});return this.replayCredentials.set(s,{authToken:this.authToken,stamp:e}),{credential:s,verdict:t}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,t,s){const r=s?.clientSeq;if(r!==void 0&&(!Number.isInteger(r)||r<=0))throw new y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(r)}`);const n=s?.shardKey??"",o=this.identityFingerprint();let a,c,d;try{c=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:h=>{a=h}})}catch(h){if(!N(h))throw h;d=h}if(a!==void 0&&a>(this.clientWatermarks.get(o??"")?.get(n)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(Se(this.clientWatermarks,kr),h=new Map,this.clientWatermarks.set(o??"",h)),h.set(n,a)}if(d!==void 0)throw d;return{applied:a===void 0||a===r,result:c}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;const e={},t=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;const s=this.sessionProbeGeneration;try{const r=await this.fetchImpl(k(this.url,`${this.authBasePath}${Ps}`),{credentials:"include",headers:e,method:"GET"});if(!r.ok)return this.identitySettled=!0,r.status===401&&this.adoptResolvedSubject(t,null,s),null;const o=(await r.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,o,s),o}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.bounceShardSockets())}setConnectionContext(e,t={}){this.assertLeaderOwnedSurface("setConnectionContext");const s=l(t.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s),e===void 0&&this.releaseIdleShard(t.shardKey)}acquireConnectionContext(e,t={}){if(this.followsAnotherTab())return()=>{};const s=l(t.shardKey),r={context:e},n=this.connectionContextHolders.get(s);n?n.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let o=!1;return()=>{if(o)return;o=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const c=a.indexOf(r);c!==-1&&a.splice(c,1),a.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s),this.releaseIdleShard(t.shardKey)}}whisperSubscribe(e,t,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");const r=l(s.shardKey);let n=this.whisperHandlers.get(r);n||(n=new Map,this.whisperHandlers.set(r,n));let o=n.get(e);const a=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(t),this.ensureSocket(s.shardKey),a){const c=this.getConnection(s.shardKey);c&&T(c,{topic:e,type:"whisper_subscribe"})}return()=>{const c=this.whisperHandlers.get(r),d=c?.get(e);if(!d?.delete(t)||d.size>0)return;c?.delete(e),c?.size===0&&this.whisperHandlers.delete(r);const u=this.getConnection(s.shardKey);u&&T(u,{topic:e,type:"whisper_unsubscribe"}),this.releaseIdleShard(s.shardKey)}}whisper(e,t,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);const r=this.getConnection(s.shardKey);r&&T(r,{data:w(t??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"}),this.releaseIdleShard(s.shardKey)}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){const t=this.statusListeners.add(e);return e(this.computeStatus()),t}pendingCount(){return this.offlineQueue.size}debug(){const e=[],t=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...t?.keys()??[]]);for(const n of s){const o=this.connections.get(n);e.push({confirmedMutationWatermark:t?.get(n)??0,hasSocket:o?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}const r=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(const n of this.shapeSubscriptions.values())r.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,o)=>(n.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:r.toSorted((n,o)=>n.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){const t=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),t}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,t){this.clientQueryStore.set(e,t)}subscribeClientQuery(e,t){return this.clientQueryStore.subscribe(e,t)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,t,s){return Xe(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){return this.peekHydratedQueryByKey(e,ae(t),s)}peekHydratedQueryByKey(e,t,s){if(!this.readyResolved)return;const r=A(e,t,s),n=this.hydratedQueryCache.get(r);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const r=v.key(e,t,s),n=this.subscriptions.get(r);return{present:n!==void 0,value:n?.lastValue}}async query(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,t,s={}){const{value:r}=await this.runMutation(e,t,s);return r}canQueueOffline(e){const{wasEverConnected:t}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(t||this.offlineQueue.queueBeforeFirstConnect)}async action(e,t,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,t,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,t,s={}){this.assertOpen();const r=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(u=>({rows:u})),o=t.length;let a=0,c=0,d=0;for(let u=0;u<o;u+=r){const h=t.slice(u,u+r),p=d,{committed:m}=await this.runMutation(e,n(h),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(p)}`},shardKey:s.shardKey});d+=1,a+=h.length,m&&(c+=h.length),s.onProgress?.({done:a,total:o})}return{chunks:d,imported:c,queued:a-c}}async shardTraffic(e){return Gs(this.adminHost,e)}async listScheduledJobs(){return Js(this.adminHost)}async schedulerStatus(){return Ys(this.adminHost)}async cancelScheduledJob(e){return Xs(this.adminHost,e)}async listDeadJobs(){return Zs(this.adminHost)}async retryDeadJob(e){return er(this.adminHost,e)}async removeDeadJob(e){return tr(this.adminHost,e)}async listWorkflowInstances(e){return sr(this.adminHost,e)}async getWorkflowInstance(e){return rr(this.adminHost,e)}async setWorkflowInstanceStatus(e){return ir(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=k(fe(this.url),bt),s=ue(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let n,o=!1;const a=()=>{o||this.closed||(n=setTimeout(u,s.next()))},c=p=>{if(o||this.WebSocketImpl===void 0)return;const m=p===void 0?t:`${t}?token=${encodeURIComponent(p)}`;me(r,m,this.managedSocketOptions,{onClose:()=>{a()},onMessage:f=>{let S;try{S=JSON.parse(typeof f.data=="string"?f.data:"")}catch{return}S.type==="jobs"&&Array.isArray(S.records)&&(s.reset(),e(S.records.map(g=>ie(g))))}})},d=async p=>{let m;try{m=await p()}catch{a();return}c(m)},u=()=>{if(o||this.WebSocketImpl===void 0)return;const{wsToken:p}=this;if(typeof p=="function"){d(p).catch(()=>{});return}c(p)};u();const h=()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),F(r),r.socket?.close(),r.socket=void 0};return this.adminSocketTeardowns.add(h),()=>{this.adminSocketTeardowns.delete(h),h()}}async listFunctions(){return Hs(this.adminHost)}async getCronJobs(){return Ls(this.adminHost)}async runCronJob(e){return Ms(this.adminHost,e)}async fetchOpenApi(){return Us(this.adminHost)}async fetchArchitecture(){return Ns(this.adminHost)}async fetchOpenRpc(){return xs(this.adminHost)}async listStorageObjects(e={}){return nr(this.adminHost,e)}async deleteStorageObject(e,t){return ar(this.adminHost,e,t)}async listStorageBuckets(){return or(this.adminHost)}async uploadStorageObject(e){return cr(this.adminHost,e)}async signedStorageUrl(e,t){return dr(this.adminHost,e,t)}async listGlobalTables(){return Ds(this.adminHost)}async readGlobalTablePage(e){return Bs(this.adminHost,e)}async facetGlobalColumn(e){return Qs(this.adminHost,e)}async listVectorIndexes(){return ur(this.adminHost)}async queryVectorIndex(e){return hr(this.adminHost,e)}async queryLogArchive(e={}){return Vs(this.adminHost,e)}async listKvNamespaces(){return Ks(this.adminHost)}async listKvKeys(e){return qs(this.adminHost,e)}async getKvValue(e){return Ws(this.adminHost,e)}async putKvValue(e){return js(this.adminHost,e)}async deleteKvKey(e){return $s(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();const t=b(Bt,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(t,"GET")}async createAuthUser(e){return this.assertOpen(),await this.adminFetch(Kt,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(qt,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(Wt,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(jt,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch($t,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(Gt,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(Vt,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(zt,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(Jt,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(Yt,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(Xt,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(b(Zt,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(es,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(b(ts,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(ss,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(rs,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(b(is,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();const t=b(ns,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){this.assertOpen();const t=b(as,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();const t=b(us,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(hs,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(ls,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(os,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(cs,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(ds,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(fs,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ps,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(ms,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(ys,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(bs,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Ss,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();const t=b(Ts,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(gs,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(vs,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(Cs,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();const t=b(ks,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(ws,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(Es,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();const t=b(As,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(_s,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Is,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Os,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=b(Qt,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,r={}){this.assertOpen();const n=t??{},o=v.key(e.__lunoraRef,n,r.shardKey);let a=this.subscriptions.get(o);const c=W(s),d=W(r.onError),u=W(r.onCheckpoint);if(!a){this.nextSubId+=1;const p=`sub_${this.nextSubId.toString()}`,m=ae(n),f=this.takeHydratedCache(e.__lunoraRef,m,r.shardKey);a={acked:!1,args:n,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:p,lastValue:f?.value,optimisticLayers:[],serverBase:f?.value,serverCursor:f?.serverCursor,shardKey:r.shardKey,wireArgs:w(n,`args for '${e.__lunoraRef}'`),...f?.serverEpoch===void 0?{}:{serverEpoch:f.serverEpoch}},this.subscriptions.add(a),f!==void 0&&this.cacheSeededQueries.set(o,f)}if(a.callbacks.add(c),d&&a.errorCallbacks.add(d),u&&a.checkpointCallbacks.add(u),a.lastValue!==void 0)try{c(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const h=a;return()=>{h.callbacks.delete(c),d&&h.errorCallbacks.delete(d),u&&h.checkpointCallbacks.delete(u),h.callbacks.size===0&&(this.sendOrQueueUnsubscribe(h.shardKey,h.id,"unsubscribe"),this.returnCacheSeed(v.keyOf(h)),this.subscriptions.remove(h),this.releaseIdleShard(h.shardKey))}}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:o}=s;return o!==void 0&&queueMicrotask(()=>{o({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;const r=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([t]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:r,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:w(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(r,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(n.shardKey,r,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey)}}stream(e,t,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new y("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;const r=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,o=t??{},{handle:a,iterable:c}=Ze({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(r,n)}});this.ensureSocket(n);const d=this.getConnection(n),u={id:r,query:{args:w(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},h={durable:s.durable===!0,generation:void 0,handle:a,lastSeq:0,message:u,shardKey:n};this.streams.set(r,h);const p=d?.wsState==="open"&&T(d,u);if(!p&&d===void 0)return this.forgetStream(r),a.fail(new y("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),c;if(!p){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=gr;){const f=d.pendingStreams.shift()?.id,S=f?this.streams.get(f):void 0;S&&(S.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}d.pendingStreams.push(u)}return c}httpStream(e,t,s={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const r={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Ke(e,t,{baseUrl:this.url,fetch:this.fetchImpl,headers:r,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(const e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(const e of this.connections.values())this.teardownConnection(e);for(const e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(const e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new y("INTERNAL","LunoraClient is closed")}followsAnotherTab(){const e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;const t=e.leaderTabId;return t!==void 0&&t!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new y("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){const t=s=>l(s)===e;return this.subscriptions.all().some(s=>t(s.shardKey))||[...this.shapeSubscriptions.values()].some(s=>t(s.shardKey))||[...this.streams.values()].some(s=>t(s.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(s=>t(s.shardKey))}releaseIdleShard(e){const t=l(e),s=this.connections.get(t);this.closed||t===""||s===void 0||(clearTimeout(s.idleTimer),s.idleTimer=setTimeout(()=>{s.idleTimer=void 0,!(this.closed||this.connections.get(t)!==s||this.shardInUse(t))&&(s.wasEverConnected&&this.idleClosedShards.add(t),this.teardownConnection(s),this.connections.delete(t),this.emitConnectionStatus())},Tr))}forgetStream(e){const t=this.streams.get(e);this.streams.delete(e),t&&this.releaseIdleShard(t.shardKey)}teardownConnection(e){e.polling.stop();const t=l(e.shardKey);for(const[r,n]of this.streams)l(n.shardKey)===t&&(n.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(r));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,F(e);const{socket:s}=e;if(s){e.socket=void 0;try{s.close()}catch{}}e.wsState="closed"}createTabCoordinator(){const e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,t={activeSubscriptions:()=>this.subscriptions.all(),broadcastStatus:(s,r)=>this.tabCoordinator?.broadcastConnectionStatus(s,r),closeConnections:()=>{for(const[s,r]of this.connections)this.teardownConnection(r),this.connections.delete(s)},computeStatus:()=>this.computeStatus(),emitConnectionStatus:()=>{this.emitConnectionStatus()},ensureSocket:s=>{this.ensureSocket(s)},flushOfflineQueues:()=>{this.flushAllOfflineQueues()},identityFingerprint:()=>this.identityFingerprint(),isLeader:()=>this.tabCoordinator?.isLeader()===!0,leader:this.leader,queueResubscribe:s=>{this.queueResubscribe(s)},queuedShardKeys:()=>this.queuedOfflineShardKeys,clientIdentifier:()=>this.clientId,dropCacheSeed:s=>{this.dropCacheSeed(s)},ackAndAdvanceCursor:(s,r,n)=>{this.ackAndAdvanceCursor(s,r,n)},subscription:s=>this.subscriptions.get(s)};return new De({channelName:e,onBecomeLeader:()=>{Wr(t)},onStopBeingLeader:()=>{jr(t)},onConnectionStatus:(s,r)=>{$r(t,s,r)},onSubscriptionData:(s,r,n,o,a)=>{Vr(t,s,r,n,o,a)},onLeaderClaimAnswered:()=>{Gr(t)},onSubscriptionError:(s,r,n)=>{zr(t,s,r,n)},onSubscriptionSettled:(s,r,n,o,a,c)=>{Jr(t,s,r,n,o,a,c)}})}async sendBatch(e,t){if(this.assertOpen(),!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];const s=await this.fetchImpl(k(this.url,$),{body:JSON.stringify({calls:e.map((a,c)=>({args:w(a.args??{},`args for batch call '${a.fn.__lunoraRef}'`),functionPath:a.fn.__lunoraRef,id:c,shardKey:a.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:t}),r=s.headers.get("x-d1-bookmark");r&&this.bookmark.set(r);let n;try{n=await s.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}const o=U(n);if(!s.ok||o!==void 0&&!n.results)throw o!==void 0?Ue(o):new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);for(const a of n.results??[]){const c=a.body?.commitCursor;typeof a.id=="number"&&typeof c=="number"&&this.recordShardCursor(e[a.id]?.shardKey,c)}return lr(n.results??[],e.length)}async runMutation(e,t,s){this.assertOpen();const r=t,n=s.mutationId??de(),o=this.takeReplayCredential(s.replayCredential),a=s.replayBaseline===void 0?this.baselineCursorFor(s.shardKey):s.replayBaseline??void 0,{confirms:c,rollbacks:d}=this.applyOptimisticUpdates(e.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,d,c);const u=this.offlineFlushes.get(l(s.shardKey));u!==void 0&&await u;const{hasSocket:h,idleClosed:p,polling:m,wasEverConnected:f,wsState:S}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:g}=this.offlineQueue,M=f||g,D=this.WebSocketImpl!==void 0&&M,B=m||p,_e=S==="connecting"&&M&&!B,Ie=S!=="open"&&!h&&D&&!B,Oe=D&&s.replayBaseline===void 0&&this.hasPendingWriteAhead(s.shardKey),ne=async()=>this.enqueueOfflineMutation(e,r,s.shardKey,a,n,d,c,s.precondition,s.mutationId,o?.stamp);if(Ie||_e||Oe)return ne();let Q;try{const O=await this.rpc(e.__lunoraRef,r,s.shardKey,{baselineSeq:a,captureBookmark:!0,...o?.flags,mutationId:n,onCommitCursor:K=>{Q=K}});for(const K of c)K(Q);return{committed:!0,value:O}}catch(O){if(B&&D&&O instanceof TypeError&&pe(r))return ne();throw this.settleFailedDirectWrite(O,Q,c,d,o?.flags.authToken),O}}settleFailedDirectWrite(e,t,s,r,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),N(e)){for(const o of s)o(t);return}R(r)}async enqueueOfflineMutation(e,t,s,r,n,o,a,c,d,u){const h=u===void 0?this.identityFingerprint():u;if(this.outbox){this.outboxMutationCounter+=1;const m=this.outboxMutationCounter;try{await this.outbox.enqueue({args:t,baselineSeq:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(m)}`,identity:h,mutationId:m,...o.length>0&&{onRejected:()=>{R(o)}},shardKey:s})}catch(f){throw R(o),f instanceof Error?f:new Error(String(f))}for(const f of a)f(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,f)=>{const S={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:r,id:n,clientId:this.clientId,identity:h,precondition:c,onCommit:g=>{for(const M of a)M(g)},reject:g=>{this.queuedIdentities.delete(n),N(g)||R(o),f(g instanceof Error?g:new Error(String(g))),this.releaseIdleShard(s)},resolve:m,shardKey:s};this.offlineQueue.enqueue(S),this.queuedOfflineShardKeys.add(s),this.ensureSocket(s),S.id!==void 0&&this.queuedIdentities.set(S.id,h)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;const t=l(e);return this.offlineQueue.hasPending(s=>l(s.shardKey)===t)}async hydratePersistedQueue(){try{const e=await this.offlineQueue.hydrate();for(const t of e)this.queuedOfflineShardKeys.add(t),this.ensureSocket(t)}catch{}}hydrateAsOutboxLeader(){const e=()=>{this.hydratePersistedQueue().catch(()=>{})},t=globalThis.navigator?.locks;if(!t){e();return}t.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{const e=await this.queryCache.load(),t=new Map;for(const s of this.subscriptions.all())t.set(A(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...r}of e){if(Ve(this.persistenceVersion,r.version)){this.queryCache.remove(s).catch(()=>{});continue}const n=t.get(s);if(n&&this.cachedQueryMatchesIdentity(r)){this.seedSubscriptionFromCache(n,r);continue}this.hydratedQueryCache.set(s,r)}}catch{}}seedSubscriptionFromCache(e,t){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(t)||(e.serverBase=t.value,e.serverCursor=t.serverCursor,t.serverEpoch!==void 0&&(e.serverEpoch=t.serverEpoch),this.cacheSeededQueries.set(A(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),I(e,t.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){const t=this.cacheSeededQueries.get(e);t!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,t))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(const[e,t]of this.cacheSeededQueries){const s=this.subscriptions.get(e);s!==void 0&&(s.serverBase=void 0,s.serverCursor=void 0,s.serverEpoch=void 0,I(s,void 0)),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const r=A(e,t,s),n=this.hydratedQueryCache.get(r);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(r),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=A(e.fn.__lunoraRef,e.argsKey,e.shardKey),s=this.hydratedQueryCache.get(t);s!==void 0&&this.cachedQueryMatchesIdentity(s)&&(this.hydratedQueryCache.delete(t),this.seedSubscriptionFromCache(e,s))}}persistQueryValue(e){const t=e.serverBase;if(!this.queryCache||t===void 0)return;const s=A(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.getConnection(e.shardKey)?.identity,n=r===void 0?this.identityFingerprint():r;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:t,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},br))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;const{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}const t=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(t.map(async([s,r])=>e.put(s,r)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";const e=[...this.connections.values()];return e.length===0?"idle":e.some(t=>t.wsState==="open")?"connected":e.some(t=>t.polling.isPolling())?"polling":e.some(t=>t.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){const t=l(e);let s;for(const r of this.subscriptions.all())l(r.shardKey)!==t||r.serverCursor===void 0||(s=s===void 0?r.serverCursor:Math.max(s,r.serverCursor));return s}async pollSubscriptions(e){const t=l(e),s=[];for(const a of this.subscriptions.all())l(a.shardKey)===t&&(pe(a.args)?s.push(a):E(a.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(s.length===0)return this.probeOrigin();const r=$e(),n=this.identityFingerprint();let o;try{o=await ye(async a=>this.sendBatch(s.map(c=>({args:c.args,fn:c.fn,shardKey:c.shardKey})),a))}catch(a){return!(a instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(const[a,c]of s.entries()){const d=o[a];if(d!==void 0){if(!d.ok){E(c.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:L(d.value),id:c.id,type:"data"},r)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await ye(async t=>e(k(this.url,$),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:t})),!0}catch{return!1}}emitConnectionStatus(){const e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,t,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:t})}applyOptimisticUpdates(e,t,s,r){const n=[],o=[];if(!r)return{confirms:n,rollbacks:o};const a=v.key(e,t,s),c=this.subscriptions.get(a);if(c){const d=qe(c,r);d&&(n.push(d.confirm),o.push(d.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,t,s,r,n){const{confirms:o,rollbacks:a,store:c}=We(this.subscriptions,s);try{e(c,t)}catch{R(a);return}r.push(...a),n.push(...o)}getConnection(e){return this.connections.get(l(e))}sendOrQueueUnsubscribe(e,t,s){const r=this.getConnection(e);r&&!T(r,{id:t,type:s})&&r.pendingUnsubscribes.push({id:t,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let r="idle";return this.leader.status==="connected"?r="open":this.leader.status==="connecting"&&(r="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:r}}const t=this.getConnection(e),s=t===void 0&&this.idleClosedShards.has(l(e));return{hasSocket:t?.socket!==void 0,idleClosed:s,polling:t?.polling.isPolling()??!1,wasEverConnected:t?.wasEverConnected??s,wsState:t?.wsState??"idle"}}getOrCreateConnection(e){const t=l(e);let s=this.connections.get(t);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Ir({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:ue(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(t),wsState:"idle"},this.connections.set(t,s)),s}wsUrlFor(e,t){const s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),t!==void 0&&s.push(`token=${encodeURIComponent(t)}`),s.length===0)return this.wsUrl;const r=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${r}${s.join("&")}`}rpcRequestHeaders(e,t){const s={"content-type":"application/json"};e.expectSubject!==void 0&&(s[st]=rt(e.expectSubject));const r=this.shardCursors.get(this.cursorKeyFor(t));r!==void 0&&(s["x-lunora-min-seq"]=r.toString());const n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(s.authorization=`Bearer ${n}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(s["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){const o=this.bookmark.get();o&&(s["x-d1-bookmark"]=o)}return s}async rpc(e,t,s,r={}){if(!this.fetchImpl)throw new H("LunoraClient: no `fetch` implementation available");const n=this.rpcRequestHeaders(r,s),o=r.authToken===void 0?this.authToken:r.authToken,a=await this.fetchImpl(k(this.url,lt),{body:JSON.stringify({args:w(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(r.captureBookmark){const h=a.headers.get("x-d1-bookmark");h&&this.bookmark.set(h)}let c;try{c=await a.json()}catch{throw P(a.status,a.statusText,a.headers.get("retry-after"))}const d=c;if(typeof d!="object"||d===null||Array.isArray(d))throw P(a.status,a.statusText,a.headers.get("retry-after"));const u=U(c);if(u!==void 0)throw oe(u,a.headers.get("retry-after"));if(!a.ok)throw P(a.status,a.statusText,a.headers.get("retry-after"));r.onMutationAck?.(c.lastMutationId),r.onCommitCursor?.(c.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(a,s),this.recordShardCursor(s,c.commitCursor);try{return C(c.result)}catch(h){throw we(h)}}async adminFetch(e,t,s,r){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);const o=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:o?(a=s,r!==void 0&&(n["content-type"]=r)):(a=JSON.stringify(s),n["content-type"]="application/json");const c=await this.fetchImpl(k(this.url,e),{body:a,headers:n,method:t});let d;try{d=await c.json()}catch{const h=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${c.status.toString()}${h})`)}const u=U(d);if(u!==void 0){const h=new Error(u.message??"admin request failed");throw h.code=u.code,h}if(!c.ok){const h=c.statusText?` ${c.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${c.status.toString()}${h})`)}return d}effectiveConnectionContext(e){const t=this.connectionContextHolders.get(e);return t&&t.length>0?t[t.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){const t=this.connections.get(e);t?.wsState==="open"&&this.sendConnectEnvelope(t)}sendConnectEnvelope(e){const t=this.effectiveConnectionContext(l(e.shardKey));T(e,{caps:Xr,clientId:this.clientId,id:"connect",type:"connect",...t===void 0?{}:{context:t}})}resendShapeSubscriptions(e){for(const t of this.shapeSubscriptions.values())l(t.shardKey)===l(e)&&this.sendShapeSubscribeIfOpen(t)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;const t=this.getOrCreateConnection(e);if(!(t.wsState==="open"||t.wsState==="connecting")){if(t.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(t,e,this.wsToken).catch(()=>{});return}this.openSocket(t,e,this.wsToken)}}async openSocketWithProvidedToken(e,t,s){let r;try{r=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,t,r)}openSocket(e,t,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),s===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,me(e,this.wsUrlFor(t,s),this.managedSocketOptions,{onClose:r=>{r?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},onMessage:r=>{e.retired!==!0&&this.handleServerMessage(r.data,t)},onOpen:()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Sr),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t),this.clearResubscribeQueue(e);for(const n of this.subscriptions.all())l(n.shardKey)===l(t)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:o,type:a}of n)T(e,{id:o,type:a});this.releaseIdleShard(t)}wr(e);const r=this.whisperHandlers.get(l(t));if(r)for(const n of r.keys())T(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(t).catch(()=>{})}}))}cancelStream(e,t){const s=this.getConnection(t);s&&(s.pendingStreams=s.pendingStreams?.filter(r=>r.id!==e),T(s,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),F(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);const t=new Set((e.pendingStreams??[]).map(r=>r.id));for(const[r,n]of this.streams)if(!(l(n.shardKey)!==l(e.shardKey)||t.has(r))){if(n.durable){const o={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(a=>a.id!==r),o];continue}n.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(r)}if(this.WebSocketImpl===void 0)return;const s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}markShardPendingAck(e){const t=l(e);for(const s of this.subscriptions.all())l(s.shardKey)===t&&(s.acked=!1)}queueResubscribe(e){const t=this.getConnection(e.shardKey);t&&(t.resubscribeQueue.push(e),this.drainResubscribeQueue(t))}drainResubscribeQueue(e){for(;e.resubscribePending.size<vr;){const t=e.resubscribeQueue.shift();if(!t)return;this.subscriptions.getById(t.id)&&this.sendSubscribeIfOpen(t)&&e.resubscribePending.set(t.id,setTimeout(()=>{this.releaseResubscribeSlot(e,t.id)},Cr))}}releaseResubscribeSlot(e,t){const s=e.resubscribePending.get(t);s!==void 0&&(clearTimeout(s),e.resubscribePending.delete(t),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(const t of e.resubscribePending.values())clearTimeout(t);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);if(t?.wsState!=="open"||e.acked)return!1;const s=e.serverCursor!==void 0&&e.serverBase!==void 0;return T(t,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...s?{sinceSeq:e.serverCursor}:{},...s&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){const t=this.getConnection(e.shardKey);t?.wsState==="open"&&T(t,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,t){const s=Ar(e);if(s===void 0)return;let r;try{r=JSON.parse(s)}catch{return}if(r.type!=="error"&&this.getConnection(t)?.reconnect.reset(),typeof r.id=="string"){const n=this.getConnection(t);n&&this.releaseResubscribeSlot(n,r.id)}switch(r.type){case"ack":{const n=this.subscriptions.getById(r.id);n&&(n.acked=!0);return}case"chunk":{const{data:n,generation:o,id:a,seq:c}=r,d=this.streams.get(a);d&&typeof c=="number"&&(d.lastSeq=c,typeof o=="number"&&(d.generation=o),d.durable=!0),d?.handle.push(C(n));return}case"complete":{this.handleCompleteMessage(r.id);return}case"data":case"delta":{this.handleDataMessage(r);return}case"error":{this.handleErrorMessage(r);break}case"identity":{this.handleIdentityFrame(r,t);break}case"pokeEnd":{this.handlePokeEnd(r,t);break}case"pokePart":{this.pokeAssembler.part(t,r);break}case"pokeStart":{this.pokeAssembler.start(t,r);break}case"resume":{this.handleResumeMessage(r);break}case"settled":{this.handleSettledMessage(r);break}case"whisper":{this.dispatchWhisper(r,t);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}const{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(Ne(e)),this.forgetStream(s);return}const n=s===void 0?void 0:this.subscriptions.getById(s);if(n){const a=ce(e),c=this.identityFingerprint(),d=v.keyOf(n);E(n.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,a,c);return}const o=s===void 0?void 0:this.shapeSubscriptions.get(s);o&&E(o.errorCallbacks,ce(e))}handlePokeEnd(e,t){const s=this.pokeAssembler.end(t,e.pokeId);if(s){Kr(this.shapeSubscriptions,s);for(const r of s.parts.keys()){const n=this.shapeSubscriptions.get(r);n&&!s.undecodable.has(r)&&this.applyPokePart(n,s,e)}}}applyPokePart(e,t,s){const r=Qr(e,t,s);if(be(e),r==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,t){const{id:s}=e,r=s?this.subscriptions.getById(s):void 0;if(!r)return;let n;try{n=Pe(e,r.serverBase)}catch(o){E(r.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${o instanceof Error?o.message:String(o)}`});return}if(n===Fe){this.resnapshotSubscription(r);return}if(this.dropCacheSeed(v.keyOf(r)),Ee(r,n,{cursor:e.cursor,epoch:e.epoch}),e.lastMutationId!==void 0&&(Z(r,e.lastMutationId),ee(r,!0)),this.persistQueryValue(r),Y(r,r.serverCursor),t!==void 0&&je(r,t),I(r,n),this.tabCoordinator?.isLeader()){const o=v.keyOf(r);this.tabCoordinator.broadcastSubscriptionData(o,n,r.serverCursor,r.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){const t=this.subscriptions.getById(e.id);t&&this.ackAndAdvanceCursor(t,e.cursor,e.epoch)}handleSettledMessage(e){const t=this.subscriptions.getById(e.id);if(t&&(this.ackAndAdvanceCursor(t,e.cursor,e.epoch),e.lastMutationId!==void 0&&Z(t,e.lastMutationId),ee(t),this.tabCoordinator?.isLeader())){const s=v.keyOf(t);this.tabCoordinator.broadcastSubscriptionSettled(s,t.serverCursor,t.serverEpoch,t.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,t,s){e.acked=!0,(t!==void 0&&t!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(t!==void 0&&(e.serverCursor=t),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),Y(e,e.serverCursor)&&I(e,e.serverBase))}dispatchWhisper(e,t){const s=this.whisperHandlers.get(l(t))?.get(e.topic);if(!s)return;const r=C(e.data);for(const n of s)try{n(r,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){const t=this.streams.get(e);if(t){t.handle.complete(),this.forgetStream(e);return}const s=this.subscriptions.getById(e);s&&(s.acked=!1,E(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{ze(this.onPersistenceError,"remove",t,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;const e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let t=2166136261,s=5381;for(let r=0;r<e.length;r+=1){const n=e.charCodeAt(r);t^=n,t=Math.imul(t,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(t>>>0).toString(36)}:${(s>>>0).toString(36)}`}credentialStamp(){const e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;const t=this.authToken;return t===null?!1:this.hashToken(t)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&V(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,t,s){if(!(this.closed||this.authToken!==e||s!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(t?.id??null,s);return}t!==null&&this.setAuthToken(e,t.id)}}adoptCookieSubject(e,t){return this.closed||this.authToken!==null||t<this.identityAnsweredAt?!1:(this.identityAnsweredAt=t,this.identitySettled=!0,this.setAuthToken(null,e),!0)}handleIdentityFrame(e,t){const s=this.getConnection(t)?.identityQuestion,{subject:r}=e;s===void 0||r!==null&&typeof r!="string"||this.adoptCookieSubject(r,s)||!this.closed&&this.authToken===null&&(r===null?null:`subj:${r}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,t){if(t!==void 0){this.authSubject=t,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){const t=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return t===void 0?e.identity:t}warnRefreshWithoutSubject(e,t){e===null||t===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){const t=this.offlineQueue.drain(),s=[];for(const r of t){if(this.identityVerdict(this.stampOf(r))!=="mismatch"){s.push(r);continue}this.queuedIdentities.delete(r.id??""),this.unpersist(r.id);const n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",r.reject(n),this.emitItemSettled(r,"rejected",n)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,t){for(const s of this.connections.values())s.identity===e&&(s.identity=t)}restampQueuedIdentity(e,t){for(const[s,r]of this.queuedIdentities)r===e&&this.queuedIdentities.set(s,t);this.offlineQueue.restampIdentity(e,t)}restampWatermarks(e,t){const s=e??"",r=this.clientWatermarks.get(s);if(r===void 0)return;this.clientWatermarks.delete(s);const n=t??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,r);else for(const[a,c]of r)o.set(a,c)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.revokeCacheSeededValues();for(const e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,I(e,void 0);for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,be(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;const e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(const e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(const e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){const t=l(e),s=this.offlineFlushes.get(t);if(s===void 0&&this.offlineQueue.size===0)return;const r=(async()=>{await(s??Promise.resolve());const{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&V(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(t,r),await r,this.offlineFlushes.get(t)===r&&(this.offlineFlushes.delete(t),this.releaseIdleShard(e))}async drainOfflineQueue(e,t){const s=this.offlineQueue.drainConflict();for(const u of s){this.unpersist(u.id),this.queuedIdentities.delete(u.id??"");const h=new Error("offline mutation skipped: precondition failed before replay");h.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(u,"rejected",h)}const r=l(e),n=this.offlineQueue.drain(u=>l(u.shardKey)===r);if(n.length===0)return;const o=[],a=[];for(const u of n){const h=this.replayGateVerdict(u);h==="send"?o.push(u):h==="hold"&&a.push(u)}if(this.offlineQueue.requeue(a),a.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}const c=this.encodableOrSettleTerminal(o);if(c.length===0){this.scheduleRateLimitedRetry(e);return}if(c.length===1){await this.replaySequential(c,e,t),this.scheduleRateLimitedRetry(e);return}const d=[];for(let u=0;u<c.length;u+=j){const h=c.slice(u,u+j),p=await this.replayBatched(h,e,t);if(d.push(...p.requeue),p.stop){d.push(...c.slice(u+j));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){const t=l(e),s=this.replayRetryState.get(t),r=(s?.attempts??0)+1;this.replayRetryState.set(t,{attempts:r,delayMs:Math.max(s?.delayMs??0,X(r))})}noteReplayRetryDelay(e,t,s){const r=l(e),n=this.replayRetryState.get(r),o=(n?.attempts??0)+1,a=Lr(t,o)??(s===null&&q(t)?X(o):void 0);this.replayRetryState.set(r,{attempts:o,delayMs:a===void 0?n?.delayMs:Math.max(n?.delayMs??0,a)})}scheduleRateLimitedRetry(e){const t=l(e),s=this.replayRetryState.get(t),r=s?.delayMs;if(s===void 0||r===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(t);return}s.delayMs=void 0;const n=this.replayRetryTimers.get(t);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},r))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{w(s.args,`args for '${s.functionPath}'`),t.push(s)}catch(r){this.settleReplayTerminal(s,r instanceof Error?r:new Error(String(r)))}return t}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";const t=this.identityFingerprint();return t===null&&this.identityUnresolved()?"unknown":e===t||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":t===null?"unknown":"mismatch"}replayGateVerdict(e){const t=this.stampOf(e);if(t===void 0)return this.queuedIdentities.delete(e.id??""),"send";const s=this.identityVerdict(t);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="match")return"send";this.unpersist(e.id);const r=new Error("offline mutation skipped: auth identity changed before replay");return r.code="OFFLINE_IDENTITY_CHANGED",e.reject(r),this.emitItemSettled(e,"rejected",r),"reject"}settleReplaySuccess(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(t),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,t){const s=e.headers.get("x-lunora-shard-key");if(s===null||t!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;const r=this.shardCursors.get("");r!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r)),this.shardCursors.delete(""))}recordShardCursor(e,t){if(typeof t!="number")return;const s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,t))}shouldRequeueReplayFailure(e,t){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,t)||Rr(e)}noteReplayAuthRefusal(e,t){if(!q(e))return!1;const s=this.hashToken(t??"");return t===this.authToken&&this.authRefusalNotifiedFor!==s&&(this.authRefusalNotifiedFor=s,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;const t=this.replayCredentials.get(e);if(t===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:t.authToken,...G(t.stamp,t.authToken)},stamp:t.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;const t=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===t&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,t,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.reject(t),this.emitItemSettled(e,"committed",t)}settleReplayTerminal(e,t){this.unpersist(e.id),e.reject(t),this.emitItemSettled(e,"rejected",t)}async replaySequential(e,t,s){for(let r=0;r<e.length;r+=1){const n=e[r];if(!n)continue;let o;try{const a=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:s,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...G(n.identity,s),mutationId:n.id,onCommitCursor:c=>{o=c}});this.settleReplaySuccess(n,a,o)}catch(a){if(N(a)){this.settleReplayUndecodable(n,a,o);continue}if(!this.shouldRequeueReplayFailure(a,s)){this.settleReplayTerminal(n,a);continue}this.noteReplayRetryDelay(t,a,s),this.offlineQueue.requeue(e.slice(r));return}}}async replayBatched(e,t,s){if(!this.fetchImpl)return{requeue:e,stop:!0};const r=JSON.stringify({calls:e.map((d,u)=>({args:w(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:u,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&Ur(r)>Mr)return await this.replayBatchedHalves(e,t,s);let n;try{n=await this.fetchImpl(k(this.url,$),{body:r,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...G(e.find(d=>d.identity!==void 0)?.identity,s)}),method:"POST"})}catch{return{requeue:e,stop:!0}}const o=n.headers.get("x-d1-bookmark");if(o&&this.bookmark.set(o),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);let a;const c=n.headers.get("retry-after");try{a=await n.json()}catch{return this.settleWholeBatchError(e,P(n.status,n.statusText,c),t,s)}if(!a.results){const d=U(a),u=d===void 0?P(n.status,n.statusText,c):oe(d,c);return this.settleWholeBatchError(e,u,t,s)}return{requeue:this.settleReplayBatchSlots(e,a.results,t,s),stop:!1}}settleWholeBatchError(e,t,s,r){if(t instanceof H||t.code!==void 0&&this.shouldRequeueReplayFailure(t,r))return this.noteReplayRetryDelay(s,t,r),{requeue:e,stop:!0};for(const n of e)this.settleReplayTerminal(n,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const r=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,r),t,s);if(n.stop)return{requeue:[...n.requeue,...e.slice(r)],stop:!0};const o=await this.replayBatched(e.slice(r),t,s);return{requeue:[...n.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,t,s,r){const n=Nr(t),o=[];let a=!1,c=!1;for(const[d,u]of e.entries()){const h=xr(n.get(d));switch(h.kind){case"committed":{a=!0,this.settleReplaySuccess(u,h.value,h.commitCursor);break}case"errored":{c||=q(h.error),this.shouldRequeueReplayFailure(h.error,r)?(this.noteReplayRetryDelay(s,h.error,r),o.push(u)):this.settleReplayTerminal(u,h.error);break}case"unanswered":{o.push(u);break}default:a=!0,this.settleReplayUndecodable(u,h.error,h.commitCursor)}}return a&&!c&&this.noteCredentialAccepted(r),o}}export{Ae as LunoraClient};
@@ -0,0 +1 @@
1
+ import{O as s,n,r as o}from"./offline-queue-D_fr-uQ3.mjs";export{s as OfflineQueue,n as nextId,o as reportPersistenceError};
@@ -0,0 +1 @@
1
+ const E=s=>{let e=-1;for(const r of s)r.seq>e&&(e=r.seq);return e},A=2,f=(s,e)=>{const r=e.filter(t=>t.role==="user"),a=E(e),o=new Set;return s.filter(t=>{for(const[n,c]of r.entries())if(!o.has(n)&&c.seq>t.maxDurableSeqAtSend&&c.content===t.content)return o.add(n),!1;return a-t.maxDurableSeqAtSend<2})};export{A as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,E as maxSeq,f as reconcileOptimistic};
@@ -0,0 +1 @@
1
+ const f="skip",E=e=>e instanceof Error?{message:e.message}:{message:String(e)},b=(e,s,n,t,a={})=>{if(n===f)return t.onReset?.(),()=>{};let o=!1;const c=r=>{o||t.onError?.(r)},i=t.onError?c:void 0;let u;try{u=e.subscribe(s,n,r=>{o||t.onData(r)},{onError:i,shardKey:a.shardKey})}catch(r){if(!t.onError)throw r;return c(E(r)),()=>{o=!0}}return()=>{o=!0,u()}};export{f as SKIP,b as createQuerySubscription,E as toSubscriptionError};
@@ -0,0 +1 @@
1
+ import{s}from"./wire-key-3XBGlnux.mjs";class t{static key(e,r,i){return`${e}::${s(r)}::${i??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){const r=t.keyOf(e);this.byKey.get(r)===e&&this.byKey.delete(r),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}}function b(y){if(y!==void 0)return e=>{y(e)}}const d=(y,e)=>{for(const r of y)try{r(e)}catch{}};export{t as SubscriptionRegistry,d as fanSubscriptionError,b as wrapSubscriber};
@@ -0,0 +1 @@
1
+ let d=0;const s="lunora-bridge",o=1e3,h=3e3;class l{bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(t={}){if(d+=1,this.tabId=`tab_${String(d)}_${crypto.randomUUID()}`,this.heartbeatInterval=t.heartbeatInterval??o,this.leaderTimeout=t.leaderTimeout??h,this.onBecomeLeader=t.onBecomeLeader,this.onStopBeingLeader=t.onStopBeingLeader,this.onConnectionStatus=t.onConnectionStatus,this.onSubscriptionData=t.onSubscriptionData,this.onLeaderClaimAnswered=t.onLeaderClaimAnswered,this.onSubscriptionError=t.onSubscriptionError,this.onSubscriptionSettled=t.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(t.channelName??s),this.bc.addEventListener("message",e=>{this.handleMessage(e.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(t,e,i,a,r){this.leader&&this.broadcast({type:"subscription-data",tabId:this.tabId,key:t,data:e,...i===void 0?{}:{cursor:i},...a===void 0?{}:{epoch:a},...r===void 0?{}:{identity:r}})}broadcastSubscriptionError(t,e,i){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:t,error:e,...i===void 0?{}:{identity:i}})}broadcastSubscriptionSettled(t,e,i,a,r,n){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:t,...e===void 0?{}:{cursor:e},...i===void 0?{}:{epoch:i},...a===void 0?{}:{lastMutationId:a},...r===void 0?{}:{clientId:r},...n===void 0?{}:{identity:n}})}broadcastConnectionStatus(t,e){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:t,...e===void 0?{}:{identity:e}})}broadcast(t){this.bc?.postMessage(t)}handleMessage(t){switch(t.type){case"claim-leadership":{this.handleClaimLeadership(t);break}case"connection-status":{if(this.leader||t.tabId===this.tabId)break;this.onConnectionStatus?.(t.status,t.identity);break}case"heartbeat":{this.handleHeartbeat(t);break}case"subscription-data":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionData?.(t.key,t.data,t.cursor,t.epoch,t.identity);break}case"subscription-error":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionError?.(t.key,t.error,t.identity);break}case"subscription-settled":{if(this.leader||t.tabId===this.tabId)break;this.onSubscriptionSettled?.(t.key,t.cursor,t.epoch,t.lastMutationId,t.clientId,t.identity);break}case"yield-leadership":{this.knownLeader===t.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(t){if(t.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&t.tabId<this.tabId&&(this.knownLeader=t.tabId,this.lastHeartbeat=t.ts)}}handleHeartbeat(t){if(t.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(t);return}this.lastHeartbeat=t.ts,this.knownLeader=t.tabId}}resolveLeaderVsLeaderTieBreak(t){t.tabId<this.tabId?(this.leader=!1,this.knownLeader=t.tabId,this.lastHeartbeat=t.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!this.running||this.leader)return;if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}}export{l as TabCoordinator};
@@ -0,0 +1 @@
1
+ import{U as s,a as e,i as l,r}from"./delta-merge-CDCNlktH.mjs";import"./wire-codec-3Mj5UgNj.mjs";export{s as UNMERGEABLE_DELTA,e as applyDelta,l as isMutationDelta,r as resolveDataPayload};
@@ -0,0 +1 @@
1
+ import{e as l}from"./wire-codec-3Mj5UgNj.mjs";import{s as d,C as w}from"./single-blob-store-D7kYfN1I.mjs";const g="lunora:offline-mutations",u=n=>{const o=n.key??g,r=d(n.storage,o),c=e=>Array.isArray(e)?e:[],s=async()=>{const e=await r.read();if(e===w)throw new Error(`createAsyncStoragePersistence: the stored outbox under '${o}' can't be decoded — refusing to overwrite it; call clear() to discard it`);return c(e)};return{append:e=>r.serialize(async()=>{l("createAsyncStoragePersistence",e.functionPath,e.args);const t=await s();t.push(e),await r.write(t)}),clear:r.clear,load:()=>r.serialize(async()=>c(await r.read())),remove:e=>r.serialize(async()=>{const t=await s(),a=t.filter(i=>i.id!==e);a.length!==t.length&&await r.write(a)}),replace:e=>r.serialize(async()=>{l("createAsyncStoragePersistence",e.functionPath,e.args);const t=await s(),a=t.findIndex(i=>i.id===e.id);a!==-1&&(t[a]=e,await r.write(t))})}};export{u as createAsyncStoragePersistence};
@@ -0,0 +1 @@
1
+ import{assertMaxEntries as y}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{s as u}from"./single-blob-store-D7kYfN1I.mjs";const w="lunora:query-cache",d=50,E=s=>{const n=y(s.maxEntries??d,"createAsyncStorageQueryCache"),r=u(s.storage,s.key??w),c=async()=>{const e=await r.read();return typeof e=="object"&&e!==null&&!Array.isArray(e)?new Map(Object.entries(e)):new Map},o=e=>r.write(Object.fromEntries(e)),i=e=>{if(e.size<=n)return;const a=[...e.values()].toSorted((t,l)=>t.ts-l.ts);for(const t of a){if(e.size<=n)break;e.delete(t.key)}};return{clear:r.clear,load:()=>r.serialize(async()=>[...(await c()).values()]),put:(e,a)=>r.serialize(async()=>{const t=await c();t.set(e,{...a,key:e}),i(t),await o(t)}),remove:e=>r.serialize(async()=>{const a=await c();a.delete(e)&&await o(a)})}};export{E as createAsyncStorageQueryCache};
@@ -0,0 +1 @@
1
+ const s=(c,r)=>{let n=0,e=0;return async(i,l)=>{e+=1;const o=e;n+=1,r.setPending(!0);try{const t=await c(i,l);return o===e&&r.setResult(t),t}catch(t){const a=t instanceof Error?t:new Error(String(t));throw o===e&&r.setError(a),a}finally{n-=1,r.setPending(n>0)}}};export{s as createCallRunner};
@@ -0,0 +1 @@
1
+ class u{values=new Map;subscribers=new Map;get(e){return this.values.has(e.key)?this.values.get(e.key):e.defaultValue}set(e,t){if(t===void 0){this.reset(e);return}this.values.set(e.key,t),this.notify(e.key,t)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}clear(){this.values.clear(),this.subscribers.clear()}subscribe(e,t){let s=this.subscribers.get(e.key);return s||(s=new Set,this.subscribers.set(e.key,s)),s.add(t),()=>{s.delete(t),s.size===0&&this.subscribers.delete(e.key)}}notify(e,t){const s=this.subscribers.get(e);if(s)for(const r of s)try{r(t)}catch{}}}const a=(i,e)=>({defaultValue:e,key:i});export{u as ClientQueryStore,a as createClientQuery};
@@ -0,0 +1 @@
1
+ const r=()=>{let e=null;return{get:()=>e,set:t=>{e=t}}};export{r as default};
@@ -0,0 +1 @@
1
+ import{LunoraError as u}from"@lunora/errors";import{p as s,c as f,a as y}from"./idb-utility-C8WS390w.mjs";const x=()=>{const r=new Map,t=e=>({...e,args:{...e.args}});return{append:e=>(r.set(e.id,t(e)),Promise.resolve()),clear:()=>(r.clear(),Promise.resolve()),load:()=>Promise.resolve([...r.values()].map(e=>t(e))),remove:e=>(r.delete(e),Promise.resolve()),replace:e=>(r.has(e.id)&&r.set(e.id,t(e)),Promise.resolve())}},m="lunora-outbox",p="offline-mutations",d="by_id",w=(r={})=>{const t=r.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!t)throw new u("INTERNAL","createIndexedDbPersistence: no IndexedDB available — pass `indexedDB` or use createInMemoryPersistence()");const e=r.databaseName??m,c=r.storeName??p,l=y(t,e,1,a=>{a.objectStoreNames.contains(c)||a.createObjectStore(c,{autoIncrement:!0}).createIndex(d,"id",{unique:!0})}),o=f(l,c);return{append:async a=>{await o("readwrite",n=>s(n.add(a)))},clear:async()=>{await o("readwrite",a=>s(a.clear()))},load:async()=>o("readonly",a=>s(a.getAll())),remove:async a=>{await o("readwrite",async n=>{const i=await s(n.index(d).getKey(a));i!==void 0&&await s(n.delete(i))})},replace:async a=>{await o("readwrite",async n=>{const i=await s(n.index(d).getKey(a.id));i!==void 0&&await s(n.put(a,i))})}}},b=(r,t=!0)=>{if(r!==!1){if(r)return r;if(!(!t||typeof indexedDB>"u"))return w()}};export{x as createInMemoryPersistence,w as createIndexedDbPersistence,b as resolvePersistenceAdapter};
@@ -0,0 +1 @@
1
+ import{LunoraError as v}from"@lunora/errors";import{p as u,c as h,a as I}from"./idb-utility-C8WS390w.mjs";const T=(e,o,a)=>`${e}::${o}::${a??""}`,w=500,E=(e,o)=>{if(!Number.isInteger(e)||e<1)throw new v("INTERNAL",`${o}: maxEntries must be a positive integer, got ${String(e)}`);return e},B=(e={})=>{const o=E(e.maxEntries??w,"createInMemoryQueryCache"),a=new Map,s=r=>({...r,value:structuredClone(r.value)}),l=()=>{if(a.size<=o)return;const r=[...a.values()].toSorted((n,y)=>n.ts-y.ts);for(const n of r){if(a.size<=o)break;a.delete(n.key)}};return{clear:()=>(a.clear(),Promise.resolve()),load:()=>Promise.resolve([...a.values()].map(r=>s(r))),put:(r,n)=>(a.set(r,s({...n,key:r})),l(),Promise.resolve()),remove:r=>(a.delete(r),Promise.resolve())}},A="lunora-query-cache",b="query-cache",f="by_ts",p=1,N=(e={})=>{const o=e.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!o)throw new v("INTERNAL","createIndexedDbQueryCache: no IndexedDB available — pass `indexedDB` or use createInMemoryQueryCache()");const a=e.databaseName??A,s=e.storeName??b,l=E(e.maxEntries??w,"createIndexedDbQueryCache"),r=I(o,a,p,t=>{t.objectStoreNames.contains(s)||t.createObjectStore(s,{keyPath:"key"}).createIndex(f,"ts",{unique:!1})}),n=h(r,s),y=async t=>{let c=await u(t.count())-l;c<=0||await new Promise((D,x)=>{const d=t.index(f).openCursor();d.addEventListener("success",()=>{const m=d.result;if(!m||c<=0){D();return}m.delete(),c-=1,m.continue()}),d.addEventListener("error",()=>{x(d.error??new Error("IndexedDB eviction failed"))})})};return{clear:async()=>{await n("readwrite",t=>u(t.clear()))},load:async()=>n("readonly",t=>u(t.getAll())),put:async(t,i)=>{await n("readwrite",async c=>{await u(c.put({...i,key:t})),await y(c)})},remove:async t=>{await n("readwrite",i=>u(i.delete(t)))}}},L=e=>{if(e!==!1){if(e)return e;if(!(typeof indexedDB>"u"))return N()}};export{E as assertMaxEntries,B as createInMemoryQueryCache,N as createIndexedDbQueryCache,T as queryCacheKey,L as resolveQueryCacheAdapter};
@@ -0,0 +1 @@
1
+ import{c as t}from"./local-store-CtP_1rJj.mjs";import"./SubscriptionRegistry-5CHmk3d8.mjs";export{t as createLocalStore};
@@ -0,0 +1 @@
1
+ const d=(a,t)=>{let e=0,r=0;return{mutate:async c=>{r+=1;const n=r;e+=1,t.setPending(!0);try{await a(c).isPersisted.promise,n===r&&t.setError(void 0)}catch(o){const i=o instanceof Error?o:new Error(String(o));throw n===r&&t.setError(i),i}finally{e-=1,t.setPending(e>0)}},reset:()=>{t.setError(void 0)}}};export{d as createMutatorRunner};
@@ -0,0 +1 @@
1
+ const s=(t={},r=Math.random)=>{const i=t.initialDelayMs??250,c=t.maxDelayMs??3e4,l=t.jitter??!0;let e=0;return{next(){const n=Math.min(c,i*2**e);if(e+=1,!l)return n;const a=n/2;return Math.floor(a+r()*(n-a))},reset(){e=0}}};export{s as createReconnect};
@@ -0,0 +1 @@
1
+ import{LunoraClient as r}from"./LunoraClient-BSI0RIrs.mjs";const c=e=>{const t=new r({fetch:e.fetch,url:e.url});return e.token!==void 0&&t.setAuthToken(e.token),t};export{c as createServerClient};
@@ -0,0 +1 @@
1
+ import{s as a}from"./wire-key-3XBGlnux.mjs";const c=(t,r,n,o)=>{const e=t.peekActiveQuerySnapshot(r.__lunoraRef,n,o),p=e.present?a(e.value):void 0;return()=>{const s=t.peekActiveQuerySnapshot(r.__lunoraRef,n,o);return!e.present||!s.present?!0:a(s.value)===p}};export{c as default};
@@ -0,0 +1 @@
1
+ import{i as y,d as l}from"./wire-codec-3Mj5UgNj.mjs";const c="_id",d="_creationTime",a="page",_="pageDelta",g=t=>{if(Array.isArray(t))return t;if(y(t)&&Array.isArray(t[a]))return t[a]},A=t=>{let n;for(const e of t){const o=e[d];if(typeof o=="number"){if(n!==void 0){if(o<n)return!0;if(o>n)return!1}n=o}}return!1},x=(t,n)=>{const e=n[d];if(typeof e!="number")return t.length;const o=A(t);for(const[f,s]of t.entries()){const r=s[d];if(typeof r=="number"&&(o?r<e:r>e))return f}return t.length},D=t=>{if(typeof t!="object"||t===null)return;const n=t[c];return typeof n=="string"?n:void 0},E=t=>{if(typeof t!="object"||t===null)return!1;const n=t;return typeof n.key=="string"&&typeof n.table=="string"&&(n.op==="insert"||n.op==="update"||n.op==="delete")},I=(t,n)=>{const e=[];for(const i of t){if(D(i)===void 0)return;e.push(i)}const{key:o,op:f,row:s}=n;if(f==="delete"){const i=e.filter(p=>p[c]!==o);return i.length===e.length?[...e]:i}if(s===void 0)return;const r=[...e],u=e.findIndex(i=>i[c]===o);return u===-1?r.splice(x(e,s),0,s):r[u]=s,r},b=(t,n)=>{const e=g(t);if(e===void 0)return;const o=I(e,n);return o===void 0||Array.isArray(t)?o:{...t,[a]:o}},v=Symbol("lunora.unmergeableDelta"),m=(t,n)=>{if("data"in t&&t.data!==void 0)return l(t.data);const e=l(t.delta);return E(e)?n===void 0?e:b(n,e)??v:e};export{_ as P,v as U,b as a,E as i,m as r};
@@ -0,0 +1 @@
1
+ import{d as r,a}from"./wire-codec-3Mj5UgNj.mjs";const d=e=>JSON.stringify(a(e)).replaceAll("<",String.raw`\u003c`),o=e=>r(JSON.parse(e));export{o as deserializePreloaded,d as serializePreloaded};
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The generated function-reference type, shared by every package that needs to
3
+ * infer a call's args or return from `api.<file>.<fn>`.
4
+ *
5
+ * This lives in `shared/` rather than in one package because the consumers span
6
+ * a dependency boundary they must not cross: `@lunora/scheduler` and
7
+ * `@lunora/workflow` accept a reference in `runAfter`/`runAt`/`step.run*` but
8
+ * cannot depend on `@lunora/client`, which is a browser package. Each of them
9
+ * previously hand-copied this declaration, and both copies silently rotted when
10
+ * the phantom carrier was renamed — the conditional matched an OPTIONAL property
11
+ * that no longer existed, so `ArgsOf<F>` quietly resolved to `unknown` and every
12
+ * `step.run(ref, args)` in the repo lost its arg checking without a single error.
13
+ *
14
+ * `shared/` is the repo's answer to exactly that shape: bundler-inlined,
15
+ * zero-dependency source imported by relative path, so it creates no runtime
16
+ * edge between the packages that inline it. Being ONE declaration, there is
17
+ * nothing to keep in lockstep and no drift test to write.
18
+ */
19
+ /** The registered function kinds a {@link FunctionReference} can describe. `stream` is a query that yields multiple frames over the WS. */
20
+ type FunctionKind = "action" | "mutation" | "query" | "stream";
21
+ /**
22
+ * Opaque reference to a registered function emitted by `@lunora/codegen`.
23
+ *
24
+ * At runtime it carries the `<file>:<function>` identifier in `__lunoraRef`.
25
+ * Generated declarations decorate this with phantom type parameters so callers
26
+ * can infer args / return values per call site.
27
+ */
28
+ interface FunctionReference<Kind extends FunctionKind = FunctionKind, Args = unknown, Return = unknown> {
29
+ /**
30
+ * Phantom marker carrying the `Kind`/`Args`/`Return` type parameters for
31
+ * inference. Never present at runtime; declared as a covariant (output)
32
+ * position so a concrete reference stays assignable to a widened one.
33
+ */
34
+ readonly __lunoraPhantom?: {
35
+ args: Args;
36
+ kind: Kind;
37
+ returns: Return;
38
+ };
39
+ readonly __lunoraRef: string;
40
+ }
41
+ /** Extract the args type from a {@link FunctionReference}. */
42
+ type ArgsOf<F> = F extends FunctionReference<infer _K, infer A, infer _R> ? A : never;
43
+ /** Extract the return type from a {@link FunctionReference}. */
44
+ type ReturnOf<F> = F extends FunctionReference<infer _K, infer _A, infer R> ? R : never;
45
+ export { ArgsOf as A, FunctionReference as F, ReturnOf as R };
@@ -0,0 +1,45 @@
1
+ /**
2
+ * The generated function-reference type, shared by every package that needs to
3
+ * infer a call's args or return from `api.<file>.<fn>`.
4
+ *
5
+ * This lives in `shared/` rather than in one package because the consumers span
6
+ * a dependency boundary they must not cross: `@lunora/scheduler` and
7
+ * `@lunora/workflow` accept a reference in `runAfter`/`runAt`/`step.run*` but
8
+ * cannot depend on `@lunora/client`, which is a browser package. Each of them
9
+ * previously hand-copied this declaration, and both copies silently rotted when
10
+ * the phantom carrier was renamed — the conditional matched an OPTIONAL property
11
+ * that no longer existed, so `ArgsOf<F>` quietly resolved to `unknown` and every
12
+ * `step.run(ref, args)` in the repo lost its arg checking without a single error.
13
+ *
14
+ * `shared/` is the repo's answer to exactly that shape: bundler-inlined,
15
+ * zero-dependency source imported by relative path, so it creates no runtime
16
+ * edge between the packages that inline it. Being ONE declaration, there is
17
+ * nothing to keep in lockstep and no drift test to write.
18
+ */
19
+ /** The registered function kinds a {@link FunctionReference} can describe. `stream` is a query that yields multiple frames over the WS. */
20
+ type FunctionKind = "action" | "mutation" | "query" | "stream";
21
+ /**
22
+ * Opaque reference to a registered function emitted by `@lunora/codegen`.
23
+ *
24
+ * At runtime it carries the `<file>:<function>` identifier in `__lunoraRef`.
25
+ * Generated declarations decorate this with phantom type parameters so callers
26
+ * can infer args / return values per call site.
27
+ */
28
+ interface FunctionReference<Kind extends FunctionKind = FunctionKind, Args = unknown, Return = unknown> {
29
+ /**
30
+ * Phantom marker carrying the `Kind`/`Args`/`Return` type parameters for
31
+ * inference. Never present at runtime; declared as a covariant (output)
32
+ * position so a concrete reference stays assignable to a widened one.
33
+ */
34
+ readonly __lunoraPhantom?: {
35
+ args: Args;
36
+ kind: Kind;
37
+ returns: Return;
38
+ };
39
+ readonly __lunoraRef: string;
40
+ }
41
+ /** Extract the args type from a {@link FunctionReference}. */
42
+ type ArgsOf<F> = F extends FunctionReference<infer _K, infer A, infer _R> ? A : never;
43
+ /** Extract the return type from a {@link FunctionReference}. */
44
+ type ReturnOf<F> = F extends FunctionReference<infer _K, infer _A, infer R> ? R : never;
45
+ export { ArgsOf as A, FunctionReference as F, ReturnOf as R };
@@ -0,0 +1 @@
1
+ const s=e=>e instanceof Headers?e:e.headers,a=async(e,t)=>{const r=s(e);return await t.api.getSession({headers:r})??null};export{a as getServerSession};
@@ -0,0 +1,9 @@
1
+ import{LunoraError as f}from"@lunora/errors";import{d as p}from"./wire-codec-3Mj5UgNj.mjs";import{createStream as u}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";const m=/^ /u,h=t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),S=t=>{let s="";const e=[];for(const o of t.split(`
2
+ `))o.startsWith("event:")?s=o.slice(6).replace(m,""):o.startsWith("data:")&&e.push(o.slice(5).replace(m,""));return{data:e.join(`
3
+ `),event:s}},T=(t,s,e)=>{const o=s.params??{},c=t.path.split("/").map(a=>{if(!a.startsWith(":"))return a;const n=a.slice(1),r=o[n];if(r===void 0)throw new f("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${n}" for route ${t.path}`);return encodeURIComponent(h(r))}).join("/"),i=new URLSearchParams;for(const[a,n]of Object.entries(s.searchParams??{}))n!==void 0&&i.set(a,h(n));const l=i.toString();return`${e.endsWith("/")?e.slice(0,-1):e}${c}${l===""?"":`?${l}`}`},E=(t,s)=>{if(t.event==="complete")return s.complete(),!0;if(t.event==="error"){let e={};try{e=JSON.parse(t.data)}catch{}const o=typeof e.message=="string"?e.message:"stream error",c=typeof e.code=="string"?e.code:"HTTP_STREAM_ERROR";return s.fail(new f(c,o)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{s.push(p(JSON.parse(t.data)))}catch{return s.fail(new f("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},b=async(t,s)=>{const e=t.getReader(),o=new TextDecoder;let c="",i=!1;const l=a=>{let n=i?`\r${a}`:a;i=n.endsWith("\r"),i&&(n=n.slice(0,-1)),c+=n.replaceAll(`\r
4
+ `,`
5
+ `)},d=()=>{let a=c.indexOf(`
6
+
7
+ `);for(;a!==-1;){const n=S(c.slice(0,a));if(c=c.slice(a+2),E(n,s))return!0;a=c.indexOf(`
8
+
9
+ `)}return!1};for(;;){const{done:a,value:n}=await e.read();if(a)break;if(l(o.decode(n,{stream:!0})),d()){await e.cancel().catch(()=>{});return}}l(o.decode()),d()||s.fail(new f("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},_=(t,s,e={})=>{const o=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!o)throw new f("INTERNAL","httpStream: no `fetch` implementation available");const c=T(t,s??{},e.baseUrl??""),i=new AbortController;let l;e.signal&&(e.signal.aborted?i.abort():(l=()=>{i.abort()},e.signal.addEventListener("abort",l,{once:!0})));const d=()=>{l&&e.signal?.removeEventListener("abort",l)},{handle:a,iterable:n}=u({maxBuffer:e.maxBuffer,onCancel:()=>{i.abort()}});return(async()=>{try{const r=await o(c,{headers:{accept:"text/event-stream",...e.headers},method:t.method,signal:i.signal});if(!r.ok){await r.body?.cancel().catch(()=>{}),a.fail(new f("HTTP_STREAM_STATUS",`httpStream: request failed (status ${r.status.toString()})`,{status:r.status}));return}if(!r.body){a.fail(new f("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await b(r.body,a)}finally{d()}})().catch(r=>{if(i.signal.aborted){a.complete();return}if(r instanceof Error&&"code"in r){a.fail(r);return}a.fail(new f("HTTP_STREAM_TRANSPORT",r instanceof Error?r.message:String(r),{cause:r}))}),n};export{_ as httpStream};
@@ -0,0 +1 @@
1
+ const c=e=>new Promise((n,a)=>{e.addEventListener("success",()=>{n(e.result)}),e.addEventListener("error",()=>{a(e.error??new Error("IndexedDB request failed"))})}),E=(e,n,a,o)=>{let s;return()=>s||(s=new Promise((r,d)=>{const t=e.open(n,a);t.addEventListener("upgradeneeded",()=>{o(t.result)}),t.addEventListener("success",()=>{r(t.result)}),t.addEventListener("error",()=>{d(t.error??new Error("IndexedDB open failed"))})}),s)},u=(e,n)=>async(a,o)=>{const r=(await e()).transaction(n,a),d=await o(r.objectStore(n));return await new Promise((t,i)=>{r.addEventListener("complete",()=>{t()}),r.addEventListener("error",()=>{i(r.error??new Error("IndexedDB transaction failed"))}),r.addEventListener("abort",()=>{i(r.error??new Error("IndexedDB transaction aborted"))})}),d};export{E as a,u as c,c as p};
@@ -0,0 +1 @@
1
+ import{SubscriptionRegistry as m}from"./SubscriptionRegistry-5CHmk3d8.mjs";let f=0;const h=()=>f,p=(r,e)=>{let t=r;for(const i of e)try{t=i.transform(t)}catch{}return t},d=(r,e)=>{if(e!==r.lastValue){r.lastValue=e;for(const t of r.callbacks)try{t(e)}catch{}}},y=(r,e)=>{d(r,p(e,r.optimisticLayers))},g=(r,e)=>{let t;try{t=e(r.lastValue)}catch{return}const i={id:Symbol("optimistic"),transform:e};let c=!1;r.optimisticLayers.push(i),d(r,t);const l=()=>{const o=r.optimisticLayers.findIndex(n=>n.id===i.id);return o===-1?!1:(r.optimisticLayers.splice(o,1),!0)},s=()=>{y(r,r.serverBase)};return{confirm:o=>{if(o===void 0){l();return}i.commitCursor=o,f+=1,i.acknowledgedAt=f,r.serverCursor!==void 0&&r.serverCursor>=o&&l()&&s()},rollback:()=>{c||(c=!0,l(),s())}}},k=(r,e)=>{if(e===void 0||r.optimisticLayers.length===0)return!1;const t=r.optimisticLayers.length;return r.optimisticLayers=r.optimisticLayers.filter(i=>i.commitCursor===void 0||i.commitCursor>e),r.optimisticLayers.length!==t},b=(r,e)=>{r.optimisticLayers.length!==0&&(r.optimisticLayers=r.optimisticLayers.filter(t=>t.acknowledgedAt===void 0||t.acknowledgedAt>e))},v=r=>{for(let e=r.length-1;e>=0;e-=1)r[e]?.()},_=(r,e)=>{const t=[],i=[],c=(s,o)=>r.get(m.key(s,o,e));return{confirms:t,rollbacks:i,store:{getAllQueries:s=>{const o=[];for(const n of r.all())n.fn.__lunoraRef===s.__lunoraRef&&(n.shardKey??"")===(e??"")&&o.push({args:n.args,value:n.lastValue});return o},getQuery:(s,o)=>c(s.__lunoraRef,o??{})?.lastValue,setQuery:(s,o,n)=>{const u=c(s.__lunoraRef,o??{});if(!u)return;const a=g(u,()=>n);a&&(t.push(a.confirm),i.push(a.rollback))}}}};export{v as a,g as b,_ as c,k as d,b as e,h as f,y as r};