@lunora/client 1.0.0-alpha.17 → 1.0.0-alpha.171

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 (90) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +16 -3
  3. package/dist/auth/index.d.mts +43 -12
  4. package/dist/auth/index.d.ts +43 -12
  5. package/dist/auth/index.mjs +1 -60
  6. package/dist/index.d.mts +808 -261
  7. package/dist/index.d.ts +808 -261
  8. package/dist/index.mjs +1 -15
  9. package/dist/packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs +1 -0
  10. package/dist/packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs +1 -0
  11. package/dist/packem_shared/LunoraClient-DnqTxmHd.mjs +1 -0
  12. package/dist/packem_shared/OfflineQueue-BWamzR6p.mjs +1 -0
  13. package/dist/packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs +1 -0
  14. package/dist/packem_shared/SKIP-d7LeP-sY.mjs +1 -0
  15. package/dist/packem_shared/SubscriptionRegistry-C3kLqped.mjs +1 -0
  16. package/dist/packem_shared/TabCoordinator-CXD7vulJ.mjs +1 -0
  17. package/dist/packem_shared/anyApi-CBOws2ZA.mjs +1 -0
  18. package/dist/packem_shared/applyDelta-CIjpZ5h9.mjs +1 -0
  19. package/dist/packem_shared/createAsyncStoragePersistence-CeUW9NTj.mjs +1 -0
  20. package/dist/packem_shared/createAsyncStorageQueryCache-Dpszf7UD.mjs +1 -0
  21. package/dist/packem_shared/createCallRunner-Bwcrfh76.mjs +1 -0
  22. package/dist/packem_shared/createClientQuery-B8Nfj-7o.mjs +1 -0
  23. package/dist/packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs +1 -0
  24. package/dist/packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs +1 -0
  25. package/dist/packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs +1 -0
  26. package/dist/packem_shared/createLocalStore-0ARUZ892.mjs +1 -0
  27. package/dist/packem_shared/createMutatorRunner-CuMRJpUx.mjs +1 -0
  28. package/dist/packem_shared/createReconnect-CjTmjJDH.mjs +1 -0
  29. package/dist/packem_shared/createServerClient-DApE8zg1.mjs +1 -0
  30. package/dist/packem_shared/createSnapshotPrecondition-5GQ_5fFu.mjs +1 -0
  31. package/dist/packem_shared/delta-merge-D_5ChS-C.mjs +1 -0
  32. package/dist/packem_shared/deserializePreloaded-Bffy70Wm.mjs +1 -0
  33. package/dist/packem_shared/function-reference.d-Br_hsKje.d.mts +45 -0
  34. package/dist/packem_shared/function-reference.d-Br_hsKje.d.ts +45 -0
  35. package/dist/packem_shared/getServerSession-BaOoo1p6.mjs +1 -0
  36. package/dist/packem_shared/httpStream-v4etRV7m.mjs +9 -0
  37. package/dist/packem_shared/idb-utility-C8WS390w.mjs +1 -0
  38. package/dist/packem_shared/local-store-DDppw8Qr.mjs +1 -0
  39. package/dist/packem_shared/lunora-client.d-CUpV_t_w.d.ts +4731 -0
  40. package/dist/packem_shared/lunora-client.d-gPd6tie1.d.mts +4731 -0
  41. package/dist/packem_shared/offline-queue-D_fr-uQ3.mjs +1 -0
  42. package/dist/packem_shared/preload.d-CyjUwQEv.d.ts +21 -0
  43. package/dist/packem_shared/preload.d-DECTCs0m.d.mts +21 -0
  44. package/dist/packem_shared/preloadQuery-uFy24PCR.mjs +1 -0
  45. package/dist/packem_shared/replay-CXXDZ1_h.mjs +1 -0
  46. package/dist/packem_shared/single-blob-store-DrhzObic.mjs +1 -0
  47. package/dist/packem_shared/wire-codec-BeIi1K-T.mjs +1 -0
  48. package/dist/packem_shared/wire-key-DCPYV4t8.mjs +1 -0
  49. package/dist/pagination/index.d.mts +42 -42
  50. package/dist/pagination/index.d.ts +42 -42
  51. package/dist/pagination/index.mjs +1 -61
  52. package/dist/query/index.d.mts +111 -43
  53. package/dist/query/index.d.ts +111 -43
  54. package/dist/query/index.mjs +1 -1
  55. package/dist/service.d.mts +49 -0
  56. package/dist/service.d.ts +49 -0
  57. package/dist/service.mjs +1 -0
  58. package/dist/ssr/index.d.mts +109 -79
  59. package/dist/ssr/index.d.ts +109 -79
  60. package/dist/ssr/index.mjs +1 -4
  61. package/dist/upload.d.mts +35 -0
  62. package/dist/upload.d.ts +35 -0
  63. package/dist/upload.mjs +1 -0
  64. package/package.json +14 -2
  65. package/dist/packem_shared/CONFLICT_ERROR_CODE-B8gQ8tyU.mjs +0 -33
  66. package/dist/packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs +0 -107
  67. package/dist/packem_shared/LunoraClient-jOfAmV8f.mjs +0 -3315
  68. package/dist/packem_shared/OfflineQueue-GGYJRmhF.mjs +0 -1
  69. package/dist/packem_shared/SKIP-vItZChkw.mjs +0 -50
  70. package/dist/packem_shared/SubscriptionRegistry-Cxr70og-.mjs +0 -1
  71. package/dist/packem_shared/applyDelta-4jFGTPA3.mjs +0 -61
  72. package/dist/packem_shared/createAsyncStoragePersistence-1Z5BZ8RC.mjs +0 -45
  73. package/dist/packem_shared/createInMemoryBookmarkStorage-BoN7a7TH.mjs +0 -11
  74. package/dist/packem_shared/createInMemoryPersistence-Ds7z8n8d.mjs +0 -119
  75. package/dist/packem_shared/createInMemoryQueryCache-iWtKPrid.mjs +0 -152
  76. package/dist/packem_shared/createLocalStore-IOur0jHF.mjs +0 -1
  77. package/dist/packem_shared/createMutationRunner-BqsavzvG.mjs +0 -21
  78. package/dist/packem_shared/createMutatorRunner-BETvCd0p.mjs +0 -31
  79. package/dist/packem_shared/createReconnect-Di_-oHH7.mjs +0 -22
  80. package/dist/packem_shared/createServerClient-Blht8tLm.mjs +0 -11
  81. package/dist/packem_shared/deserializePreloaded-C0eJTY_W.mjs +0 -4
  82. package/dist/packem_shared/getServerSession-8jXewqxd.mjs +0 -13
  83. package/dist/packem_shared/local-store-BNgN3Dw3.mjs +0 -111
  84. package/dist/packem_shared/lunora-client.d-DPLSlPiP.d.mts +0 -2425
  85. package/dist/packem_shared/lunora-client.d-DPLSlPiP.d.ts +0 -2425
  86. package/dist/packem_shared/offline-queue-B9vfdSqp.mjs +0 -170
  87. package/dist/packem_shared/preload.d-Bpi7xweC.d.mts +0 -20
  88. package/dist/packem_shared/preload.d-CmFdZFQi.d.ts +0 -20
  89. package/dist/packem_shared/preloadQuery-lobFkD2Z.mjs +0 -13
  90. package/dist/packem_shared/subscription-DoyO04-2.mjs +0 -65
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-4jFGTPA3.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-BNgN3Dw3.mjs';
6
- export { LunoraClient } from './packem_shared/LunoraClient-jOfAmV8f.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-Ds7z8n8d.mjs';
11
- export { preloadQuery, preloadedQueryResult } from './packem_shared/preloadQuery-lobFkD2Z.mjs';
12
- export { createInMemoryQueryCache, createIndexedDbQueryCache, queryCacheKey } from './packem_shared/createInMemoryQueryCache-iWtKPrid.mjs';
13
- export { createReconnect } from './packem_shared/createReconnect-Di_-oHH7.mjs';
14
- export { DEFAULT_MAX_BUFFER, createStream } from './packem_shared/DEFAULT_MAX_BUFFER-BDkqO5PW.mjs';
15
- export { S as SubscriptionRegistry } from './packem_shared/subscription-DoyO04-2.mjs';
1
+ import{anyApi as o}from"./packem_shared/anyApi-CBOws2ZA.mjs";import{RETIRE_AFTER_DURABLE_SEQ_ADVANCE as a,maxSeq as c,reconcileOptimistic as p}from"./packem_shared/RETIRE_AFTER_DURABLE_SEQ_ADVANCE-DoEHtuR8.mjs";import{createAsyncStoragePersistence as i}from"./packem_shared/createAsyncStoragePersistence-CeUW9NTj.mjs";import{createAsyncStorageQueryCache as f}from"./packem_shared/createAsyncStorageQueryCache-Dpszf7UD.mjs";import{default as x}from"./packem_shared/createInMemoryBookmarkStorage-BooZhW0n.mjs";import{createCallRunner as l}from"./packem_shared/createCallRunner-Bwcrfh76.mjs";import{createClientQuery as d}from"./packem_shared/createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as R}from"./packem_shared/TabCoordinator-CXD7vulJ.mjs";import{a as A,i as S}from"./packem_shared/delta-merge-D_5ChS-C.mjs";import{CONFLICT_ERROR_CODE as D,TransportError as Q,getErrorCode as _,getRetryAfterMs as F,isAuthReplayFailure as I,isConflictError as M,isForbiddenError as g,isRateLimitedError as L,isUnauthorizedError as O}from"./packem_shared/CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as b}from"./packem_shared/httpStream-v4etRV7m.mjs";import{c as U}from"./packem_shared/local-store-DDppw8Qr.mjs";import{LunoraClient as k}from"./packem_shared/LunoraClient-DnqTxmHd.mjs";import{createMutatorRunner as N}from"./packem_shared/createMutatorRunner-CuMRJpUx.mjs";import{O as K}from"./packem_shared/offline-queue-D_fr-uQ3.mjs";import{createInMemoryPersistence as X,createIndexedDbPersistence as j}from"./packem_shared/createInMemoryPersistence-Cz2W6XVj.mjs";import{preloadQuery as w,preloadedQueryResult as G}from"./packem_shared/preloadQuery-uFy24PCR.mjs";import{createInMemoryQueryCache as J,createIndexedDbQueryCache as W,queryCacheKey as Y}from"./packem_shared/createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as $}from"./packem_shared/createReconnect-CjTmjJDH.mjs";import{default as re}from"./packem_shared/createSnapshotPrecondition-5GQ_5fFu.mjs";import{DEFAULT_MAX_BUFFER as te,createStream as ae}from"./packem_shared/DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as pe}from"./packem_shared/SubscriptionRegistry-C3kLqped.mjs";export{D as CONFLICT_ERROR_CODE,te as DEFAULT_MAX_BUFFER,k as LunoraClient,K as OfflineQueue,a as RETIRE_AFTER_DURABLE_SEQ_ADVANCE,pe as SubscriptionRegistry,R as TabCoordinator,Q as TransportError,o as anyApi,A as applyDelta,i as createAsyncStoragePersistence,f as createAsyncStorageQueryCache,l as createCallRunner,d as createClientQuery,x as createInMemoryBookmarkStorage,X as createInMemoryPersistence,J as createInMemoryQueryCache,j as createIndexedDbPersistence,W as createIndexedDbQueryCache,U as createLocalStore,N as createMutatorRunner,$ as createReconnect,re as createSnapshotPrecondition,ae as createStream,_ as getErrorCode,F as getRetryAfterMs,b as httpStream,I as isAuthReplayFailure,M as isConflictError,g as isForbiddenError,S as isMutationDelta,L as isRateLimitedError,O as isUnauthorizedError,c as maxSeq,w as preloadQuery,G as preloadedQueryResult,Y as queryCacheKey,p 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 Ce,e as L,d as g}from"./wire-codec-BeIi1K-T.mjs";import{i as ke,a as we,P as Ee}from"./delta-merge-D_5ChS-C.mjs";import{s as ee}from"./wire-key-DCPYV4t8.mjs";import Ae from"./createInMemoryBookmarkStorage-BooZhW0n.mjs";import{ClientQueryStore as _e}from"./createClientQuery-B8Nfj-7o.mjs";import{TabCoordinator as Ie}from"./TabCoordinator-CXD7vulJ.mjs";import{TransportError as te,isAuthReplayFailure as D}from"./CONFLICT_ERROR_CODE-B7qNZMMk.mjs";import{httpStream as Oe}from"./httpStream-v4etRV7m.mjs";import{d as K,n as A,f as _,a as Re,c as Pe,b as Fe,e as Me}from"./local-store-DDppw8Qr.mjs";import{O as Le,n as se,i as He,r as Ue}from"./offline-queue-D_fr-uQ3.mjs";import{resolvePersistenceAdapter as xe}from"./createInMemoryPersistence-Cz2W6XVj.mjs";import{resolveQueryCacheAdapter as Ne,queryCacheKey as I}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{createReconnect as re}from"./createReconnect-CjTmjJDH.mjs";import{i as U,e as M,u as P,a as ie,d as ne,r as Be,b as Qe,c as De,M as Ke,f as qe,g as We}from"./replay-CXXDZ1_h.mjs";import je from"./createSnapshotPrecondition-5GQ_5fFu.mjs";import{createStream as $e}from"./DEFAULT_MAX_BUFFER-D3QH2iaq.mjs";import{SubscriptionRegistry as C}from"./SubscriptionRegistry-C3kLqped.mjs";const q=500,Ge=async c=>{const e=[];let t;for(;;){const s=await c(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}},ae=(c,e)=>{if(c.size<e)return;const t=c.keys().next().value;t!==void 0&&c.delete(t)};new TextDecoder;const Ve=new TextEncoder,ze=c=>Ce(Ve.encode(JSON.stringify(c))),Je="x-lunora-expect-subject",Ye=c=>ze({subject:c}),oe=Symbol.for("lunora:session-change"),Xe="lunora:session-change",Ze="better-auth.message",et="signout",me=()=>{const c=globalThis;let e=c[oe];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},c[oe]=e),e},tt=()=>"document"in globalThis,st=async()=>{const c=[];for(const e of me().listeners)try{c.push(e())}catch{}await Promise.allSettled(c)},rt=(c,e)=>{if(c!==Ze||e===null)return!1;try{const t=JSON.parse(e);return t?.event==="session"&&t.data?.trigger===et}catch{return!1}},it=c=>{const e=[],t=()=>{st().catch(()=>{})};let s;try{s=typeof BroadcastChannel=="function"?new BroadcastChannel(Xe):void 0}catch{s=void 0}if(s!==void 0){const i=s;i.addEventListener("message",n=>{n.data?.type==="lunora:session-change"&&n.data.tab!==c&&t()}),e.push(()=>{i.close()})}const r=globalThis;if(typeof r.addEventListener=="function"){const i=n=>{rt(n.key,n.newValue)&&t()};r.addEventListener("storage",i),e.push(()=>{r.removeEventListener?.("storage",i)})}return()=>{for(const i of e)i()}},nt=c=>{const e=me();return e.listeners.add(c),e.detach===void 0&&tt()&&(e.detach=it(e.tab)),()=>{e.listeners.delete(c),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}};class O{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 at=c=>{const{afterFailedAttempts:e,intervalMs:t,onReachable:s,onStateChange:r,poll:i}=c,n=t>0&&e>0;let a=0,o,h=!1,d=!1;const u=()=>{o!==void 0&&(clearInterval(o),o=void 0,h=!1,r())},f=p=>{if(o!==void 0){if(!p){u();return}h||(h=!0,r()),s()}},m=()=>{d||(d=!0,i().then(f).finally(()=>{d=!1}).catch(()=>{}))};return{isPolling:()=>o!==void 0&&h,noteFailedOpen:()=>{a+=1,!(!n||o!==void 0||a<e)&&(o=setInterval(m,t),r(),m())},noteOpen:()=>{a=0,u()},stop:u}},ot="/_lunora/rpc",W="/_lunora/rpc-batch",ct="/_lunora/ws",j=c=>c===void 0||c===""?"":`&bucket=${encodeURIComponent(c)}`,F=c=>{for(let e=c.length-1;e>=0;e-=1)c[e]?.()},ce=Symbol("lunora.unmergeableDelta"),ht=(c,e)=>{for(const t of e)t.op==="delete"?c.delete(t.key):t.value!==void 0&&c.set(t.key,t.value)},dt="lunora-ping",ut=3e4,lt=1e4,ft=5e3,pt=3,mt=250,yt=5e3,bt=5e3,St=64,vt=3,gt=1e4,Tt=8,Ct="/_lunora/admin/shard-traffic",kt="/_lunora/admin/scheduled",wt="/_lunora/admin/scheduled/status",Et="/_lunora/admin/scheduled/ws",At="/_lunora/admin/scheduled/cancel",he="/_lunora/admin/scheduled/dead",_t="/_lunora/admin/scheduled/dead/retry",It="/_lunora/admin/scheduled/dead/cancel",Ot="/_lunora/admin/workflows/instances",Rt="/_lunora/admin/workflows/instance",Pt="/_lunora/admin/workflows/status",$="/_lunora/admin/storage",Ft="/_lunora/admin/storage/url",Mt="/_lunora/admin/storage/buckets",Lt="/_lunora/admin/functions",Ht="/_lunora/admin/cron-jobs",Ut="/_lunora/admin/cron-jobs/run",xt="/_lunora/admin/architecture",Nt="/_lunora/admin/openapi",Bt="/_lunora/admin/openrpc",Qt="/_lunora/admin/global/tables",Dt="/_lunora/admin/global/table",Kt="/_lunora/admin/global/facet",qt="/_lunora/admin/vector/indexes",Wt="/_lunora/admin/vector/query",jt="/_lunora/admin/logs/archive",$t="/_lunora/admin/kv/namespaces",Gt="/_lunora/admin/kv/keys",G="/_lunora/admin/kv/value",Vt="/_lunora/admin/auth/users",zt="/_lunora/admin/auth/sessions",Jt="/_lunora/admin/auth/users/create",Yt="/_lunora/admin/auth/users/role",Xt="/_lunora/admin/auth/users/ban",Zt="/_lunora/admin/auth/users/unban",es="/_lunora/admin/auth/users/password",ts="/_lunora/admin/auth/users/remove",ss="/_lunora/admin/auth/users/impersonate",rs="/_lunora/admin/auth/sessions/revoke",is="/_lunora/admin/auth/sessions/revoke-all",ns="/_lunora/admin/auth/capabilities",as="/_lunora/admin/auth/users/update",os="/_lunora/admin/auth/accounts",cs="/_lunora/admin/auth/accounts/unlink",hs="/_lunora/admin/auth/passkeys",ds="/_lunora/admin/auth/passkeys/delete",us="/_lunora/admin/auth/two-factor/disable",ls="/_lunora/admin/auth/organizations",fs="/_lunora/admin/auth/organizations/members",ps="/_lunora/admin/auth/organizations/invitations",ms="/_lunora/admin/auth/organizations/members/remove",ys="/_lunora/admin/auth/organizations/invitations/cancel",bs="/_lunora/admin/auth/config",Ss="/_lunora/admin/auth/sign-up-invitations",vs="/_lunora/admin/auth/sign-up-invitations/create",gs="/_lunora/admin/auth/sign-up-invitations/revoke",Ts="/_lunora/admin/auth/organizations/create",Cs="/_lunora/admin/auth/organizations/update",ks="/_lunora/admin/auth/organizations/remove",ws="/_lunora/admin/auth/organizations/members/add",Es="/_lunora/admin/auth/organizations/members/invite",As="/_lunora/admin/auth/organizations/members/role",_s="/_lunora/admin/auth/organizations/teams",Is="/_lunora/admin/auth/organizations/teams/create",Os="/_lunora/admin/auth/organizations/teams/update",Rs="/_lunora/admin/auth/organizations/teams/remove",Ps="/_lunora/admin/auth/organizations/teams/members",Fs="/_lunora/admin/auth/organizations/teams/members/add",Ms="/_lunora/admin/auth/organizations/teams/members/remove",Ls="/_lunora/admin/auth/organizations/roles",Hs="/_lunora/admin/auth/organizations/roles/create",Us="/_lunora/admin/auth/organizations/roles/update",xs="/_lunora/admin/auth/organizations/roles/remove",Ns="/api/auth",Bs="/get-session",V=c=>c==="connected"||c==="polling",Qs=(c,e,t)=>c!==null||e&&t===null,de=c=>c.startsWith("https://")?`wss://${c.slice(8)}`:c.startsWith("http://")?`ws://${c.slice(7)}`:c,k=(c,e)=>`${c.endsWith("/")?c.slice(0,-1):c}${e}`,b=(c,e)=>{const t=new URLSearchParams;for(const[r,i]of Object.entries(e))i!==void 0&&i!==""&&t.set(r,String(i));const s=t.toString();return s===""?c:`${c}?${s}`},Ds=[Ee],l=c=>c??"",ye=(c,e)=>{const t=c.error,s=typeof t?.code=="string"?t.code:void 0,r=typeof t?.message=="string"?t.message:void 0;return{code:s,messageText:(typeof c.message=="string"?c.message:void 0)??r??e}},Ks=c=>{const{code:e,messageText:t}=ye(c,"stream error");return e===void 0?new Error(t):new y(e,t)},ue=c=>{const{code:e,messageText:t}=ye(c,"subscription error");return{message:t,...e===void 0?{}:{code:e}}};function z(c){if(c!==void 0)return e=>{c(e)}}const w=(c,e)=>{for(const t of c)try{t(e)}catch{}},qs=new TextDecoder,Ws=c=>{if(typeof c=="string")return c;if(c instanceof ArrayBuffer)return qs.decode(c)},v=(c,e)=>{if(!c.socket||c.wsState!=="open")return!1;try{return c.socket.send(JSON.stringify(e)),!0}catch{return!1}},js=c=>{if(!c.pendingStreams||c.pendingStreams.length===0)return;const e=c.pendingStreams;c.pendingStreams=[];for(const t of e)v(c,t)},X=c=>{const e=new Error(c.message??"request failed");if(e.code=c.code,c.data!==void 0)try{e.data=g(c.data)}catch{}return c.hint!==void 0&&(e.hint=c.hint),c.docsUrl!==void 0&&(e.docsUrl=c.docsUrl),e},le=(c,e)=>{const t=X(c),s=qe(t,e);return s!==void 0&&(t.data=s),t},E=(c,e)=>{try{return L(c)}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)}},$s=1e4,fe=async c=>{const e=new AbortController;let t;const s=new Promise((r,i)=>{t=setTimeout(()=>{e.abort(),i(new TypeError("LunoraClient: poll timed out"))},$s)});try{return await Promise.race([c(e.signal),s])}catch(r){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):r}finally{clearTimeout(t)}},pe=c=>{try{return L(c),!0}catch{return!1}},J=c=>"args"in c?{...c,args:g(c.args)}:c,be=c=>{const e=M(c);return e===void 0?We():X(e)},Gs=(c,e)=>{const t=Array.from({length:e});for(const s of c){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;const r=s.body;t[s.id]=r!==void 0&&"error"in r?{error:be(r),ok:!1}:{ok:!0,value:g(r?.result)}}return t.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},Y=(c,e)=>e!==null?{}:c===null?{expectSubject:null}:c?.startsWith("subj:")===!0?{expectSubject:c.slice(5)}:{},Vs=Promise.resolve();class Se{static MAX_POKE_BUFFERS=256;static createClientQuery(e,t){return{defaultValue:t,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;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 C;tabCoordinator;leaderStatus;leaderWasEverConnected=!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 O;statusListeners=new O;tokenExpiredListeners=new O;identityChangeListeners=new O;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new O;pendingChangeListeners=new O;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;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??k(de(e.url),ct),this.wsToken=e.wsToken;const t=e.authBasePath??Ns;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??Ae(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ut,this.connectTimeoutMs=e.connectTimeoutMs??lt,this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??ft,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??pt,this.defaultConnectionContext=e.connectionContext,this.persistence=xe(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ne(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new _e,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=Vs),this.offlineQueue=new Le(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-${se()}`,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=nt(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,t){const s=this.authToken!==e,r=this.identityFingerprint(),i=this.authSubject===void 0||this.subjectToken===this.authToken,n=this.subjectAwaitingReconfirm(),a=this.isKnownNobody(),o=this.authToken;this.authToken=e,this.applySubject(e,t);const h=this.identityFingerprint();h!==r&&(!s&&e!==null&&i?(this.restampQueuedIdentity(r,h),this.restampWatermarks(r,h),this.restampConnectionIdentity(r,h),this.reseedFromHydratedCache()):!s&&e===null&&r===null&&i&&!a?(this.restampWatermarks(r,h),this.restampConnectionIdentity(r,h),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(r),this.warnRefreshWithoutSubject(o,e),Qs(r,a,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(n),s&&this.authTokenListeners.emit(e),(h!==r||s||n)&&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 i=s?.shardKey??"",n=this.identityFingerprint();let a,o,h;try{o=await this.rpc(e,t,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:r,onMutationAck:u=>{a=u}})}catch(u){if(!U(u))throw u;h=u}if(a!==void 0&&a>(this.clientWatermarks.get(n??"")?.get(i)??0)){let u=this.clientWatermarks.get(n??"");u===void 0&&(ae(this.clientWatermarks,Tt),u=new Map,this.clientWatermarks.set(n??"",u)),u.set(i,a)}if(h!==void 0)throw h;return{applied:a===void 0||a===r,result:o}}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}${Bs}`),{credentials:"include",headers:e,method:"GET"});if(!r.ok)return this.identitySettled=!0,r.status===401&&this.adoptResolvedSubject(t,null,s),null;const n=(await r.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(t,n,s),n}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},i=this.connectionContextHolders.get(s);i?i.push(r):this.connectionContextHolders.set(s,[r]),this.refreshConnectionContext(s);let n=!1;return()=>{if(n)return;n=!0;const a=this.connectionContextHolders.get(s);if(!a)return;const o=a.indexOf(r);o!==-1&&a.splice(o,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 i=this.whisperHandlers.get(r);i||(i=new Map,this.whisperHandlers.set(r,i));let n=i.get(e);const a=n===void 0;if(n||(n=new Set,i.set(e,n)),n.add(t),this.ensureSocket(s.shardKey),a){const o=this.getConnection(s.shardKey);o&&v(o,{topic:e,type:"whisper_subscribe"})}return()=>{const o=this.whisperHandlers.get(r),h=o?.get(e);if(!h?.delete(t)||h.size>0)return;o?.delete(e),o?.size===0&&this.whisperHandlers.delete(r);const d=this.getConnection(s.shardKey);d&&v(d,{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&&v(r,{data:E(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 i of s){const n=this.connections.get(i);e.push({confirmedMutationWatermark:t?.get(i)??0,hasSocket:n?.socket!==void 0,shardKey:i===""?void 0:i,wasEverConnected:n?.wasEverConnected??!1,wsState:n?.wsState??"idle"})}const r=this.subscriptions.all().map(i=>({acked:i.acked,functionPath:i.fn.__lunoraRef,id:i.id,kind:"query",lastMutationId:i.lastMutationId,pendingOptimisticLayers:i.optimisticLayers.length,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size}));for(const i of this.shapeSubscriptions.values())r.push({acked:i.serverCursor!==void 0,functionPath:`shape:${i.name}`,id:i.id,kind:"shape",lastMutationId:i.lastMutationId,pendingOptimisticLayers:0,rowCount:i.rows.size,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((i,n)=>(i.shardKey??"").localeCompare(n.shardKey??"")),subscriptions:r.toSorted((i,n)=>i.functionPath.localeCompare(n.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 je(this,e,t,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,t,s){if(!this.readyResolved)return;const r=ee(t),i=I(e,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,t,s){const r=C.key(e,t,s),i=this.subscriptions.get(r);return{present:i!==void 0,value:i?.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)),i=s.toArgs??(d=>({rows:d})),n=t.length;let a=0,o=0,h=0;for(let d=0;d<n;d+=r){const u=t.slice(d,d+r),f=h,{committed:m}=await this.runMutation(e,i(u),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(f)}`},shardKey:s.shardKey});h+=1,a+=u.length,m&&(o+=u.length),s.onProgress?.({done:a,total:n})}return{chunks:h,imported:o,queued:a-o}}async shardTraffic(e){this.assertOpen();const t=await this.adminFetch(Ct,"POST",{table:e});return{failed:t.failed??0,ok:t.ok??0,shards:t.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch(kt,"GET")).records??[]).map(t=>J(t))}async schedulerStatus(){this.assertOpen();const e=await this.adminFetch(wt,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(At,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await Ge(async t=>await this.adminFetch(t===void 0?he:`${he}?cursor=${encodeURIComponent(t)}`,"GET"))).map(t=>J(t))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(_t,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(It,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.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 this.adminFetch(`${Ot}?${t.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();const t=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Rt}?${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??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Pt,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};const t=k(de(this.url),Et),s=re(this.reconnectOptions),r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0};let i,n=!1;const a=()=>{n||this.closed||(i=setTimeout(d,s.next()))},o=f=>{if(n||this.WebSocketImpl===void 0)return;const m=f===void 0?t:`${t}?token=${encodeURIComponent(f)}`;this.openManagedSocket(r,m,this.connectTimeoutMs,{onClose:()=>{a()},onMessage:p=>{let S;try{S=JSON.parse(typeof p.data=="string"?p.data:"")}catch{return}S.type==="jobs"&&Array.isArray(S.records)&&(s.reset(),e(S.records.map(T=>J(T))))}})},h=async f=>{let m;try{m=await f()}catch{a();return}o(m)},d=()=>{if(n||this.WebSocketImpl===void 0)return;const{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}o(f)};d();const u=()=>{n=!0,i!==void 0&&(clearTimeout(i),i=void 0),r.connectTimer!==void 0&&(clearTimeout(r.connectTimer),r.connectTimer=void 0),this.stopHeartbeat(r),r.socket?.close(),r.socket=void 0};return this.adminSocketTeardowns.add(u),()=>{this.adminSocketTeardowns.delete(u),u()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Lt,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Ht,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();const t=await this.adminFetch(Ut,"POST",{name:e});return{name:t.name??e,ran:t.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Nt,"GET")}async fetchArchitecture(){return this.assertOpen(),await this.adminFetch(xt,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Bt,"GET")}async listStorageObjects(e={}){this.assertOpen();const t=b($,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(t,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,t){this.assertOpen();const s=`${$}?key=${encodeURIComponent(e)}${j(t?.bucket)}`,r=await this.adminFetch(s,"DELETE");return{deleted:r.deleted===!0,key:r.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Mt,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();const t=`${$}?key=${encodeURIComponent(e.key)}${j(e.bucket)}`,s=await this.adminFetch(t,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,t){this.assertOpen();const s=t?.expiresInSeconds,r=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,i=`${Ft}?key=${encodeURIComponent(e)}${r}${j(t?.bucket)}`,n=await this.adminFetch(i,"GET");if(typeof n.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return n.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Qt,"GET")}async readGlobalTablePage(e){this.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))),g(await this.adminFetch(`${Dt}?${t.toString()}`,"GET"))}async facetGlobalColumn(e){this.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))),g(await this.adminFetch(`${Kt}?${t.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(qt,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(Wt,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();const t=await this.adminFetch(jt,"POST",e);return{nextCursor:t.nextCursor,rows:t.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch($t,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();const t=b(Gt,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(t,"GET")}async getKvValue(e){this.assertOpen();const t=b(G,{key:e.key,namespace:e.namespace});return await this.adminFetch(t,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(G,"PUT",e)}async deleteKvKey(e){this.assertOpen();const t=b(G,{key:e.key,namespace:e.namespace});await this.adminFetch(t,"DELETE")}async listAuthUsers(e={}){this.assertOpen();const t=b(Vt,{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 await this.adminFetch(Jt,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(Yt,"POST",e)}async banAuthUser(e){return await this.adminFetch(Xt,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(Zt,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(es,"POST",e)}async removeAuthUser(e){await this.adminFetch(ts,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(ss,"POST",e)}async revokeAuthSession(e){await this.adminFetch(rs,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(is,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(ns,"GET")}async updateAuthUser(e){return await this.adminFetch(as,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(b(os,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(cs,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(b(hs,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(ds,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(us,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(b(ls,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){const t=b(fs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthOrgInvitations(e){const t=b(ps,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async listAuthSignUpInvitations(e={}){const t=b(Ss,{limit:e.limit,offset:e.offset});return await this.adminFetch(t,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(vs,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(gs,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(ms,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(ys,"POST",e)}async getAuthConfig(){return await this.adminFetch(bs,"GET")}async createAuthOrganization(e){return await this.adminFetch(Ts,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(Cs,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(ks,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(ws,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(Es,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(As,"POST",e)}async listAuthOrgTeams(e){const t=b(_s,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(Is,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Os,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Rs,"POST",e)}async listAuthOrgTeamMembers(e){const t=b(Ps,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(t,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(Fs,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Ms,"POST",e)}async listAuthOrgRoles(e){const t=b(Ls,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(t,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Hs,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Us,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(xs,"POST",e)}async listAuthSessions(e={}){this.assertOpen();const t=b(zt,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(t,"GET")}subscribe(e,t,s,r={}){this.assertOpen();const i=t??{},n=C.key(e.__lunoraRef,i,r.shardKey);let a=this.subscriptions.get(n);const o=z(s),h=z(r.onError),d=z(r.onCheckpoint);if(!a){this.nextSubId+=1;const f=`sub_${this.nextSubId.toString()}`,m=ee(i),p=this.takeHydratedCache(e.__lunoraRef,m,r.shardKey);a={acked:!1,args:i,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:p?.value,optimisticLayers:[],serverBase:p?.value,serverCursor:p?.serverCursor,shardKey:r.shardKey,wireArgs:E(i,`args for '${e.__lunoraRef}'`),...p?.serverEpoch===void 0?{}:{serverEpoch:p.serverEpoch}},this.subscriptions.add(a),p!==void 0&&this.cacheSeededQueries.set(n,p)}if(a.callbacks.add(o),h&&a.errorCallbacks.add(h),d&&a.checkpointCallbacks.add(d),a.lastValue!==void 0)try{o(a.lastValue)}catch{}this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(a);const u=a;return()=>{u.callbacks.delete(o),h&&u.errorCallbacks.delete(h),d&&u.checkpointCallbacks.delete(d),u.callbacks.size===0&&(this.sendOrQueueUnsubscribe(u.shardKey,u.id,"unsubscribe"),this.returnCacheSeed(C.keyOf(u)),this.subscriptions.remove(u),this.releaseIdleShard(u.shardKey))}}subscribeShape(e,t,s={}){if(this.assertOpen(),this.followsAnotherTab()){const{onError:n}=s;return n!==void 0&&queueMicrotask(()=>{n({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()}`,i={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:E(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(r,i),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(i),()=>{this.shapeSubscriptions.delete(r),this.sendOrQueueUnsubscribe(i.shardKey,r,"shape_unsubscribe"),this.releaseIdleShard(i.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:i}=s,n=t??{},{handle:a,iterable:o}=$e({maxBuffer:s.maxBuffer,onCancel:()=>{this.cancelStream(r,i)}});this.ensureSocket(i);const h=this.getConnection(i),d={id:r,query:{args:E(n,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:i},type:"stream"},u={durable:s.durable===!0,generation:void 0,handle:a,lastSeq:0,message:d,shardKey:i};this.streams.set(r,u);const f=h?.wsState==="open"&&v(h,d);if(!f&&h===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")),o;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=St;){const p=h.pendingStreams.shift()?.id,S=p?this.streams.get(p):void 0;S&&(S.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(p))}h.pendingStreams.push(d)}return o}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 Oe(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.pokeBuffers.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())},bt))}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,i]of this.streams)l(i.shardKey)===t&&(i.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,this.stopHeartbeat(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"}`;return new Ie({channelName:e,onBecomeLeader:()=>{for(const t of this.subscriptions.all())this.ensureSocket(t.shardKey),this.queueResubscribe(t);for(const t of this.queuedOfflineShardKeys)this.ensureSocket(t);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onStopBeingLeader:()=>{for(const[t,s]of this.connections)this.teardownConnection(s),this.connections.delete(t);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},onConnectionStatus:(t,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;const r=t==="connected"&&this.leaderStatus!=="connected"||t==="polling"&&this.leaderStatus!=="connected"&&this.leaderStatus!=="polling";this.leaderStatus=t,t==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),r&&this.flushAllOfflineQueues()},onSubscriptionData:(t,s,r,i,n)=>{if(n!==void 0&&n!==this.identityFingerprint())return;const a=this.subscriptions.get(t);a&&(a.serverBase=s,this.dropCacheSeed(t),r!==void 0&&(a.serverCursor=r,i!==void 0&&(a.serverEpoch=i),K(a,r)),A(a,_(s,a.optimisticLayers)))},onLeaderClaimAnswered:()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},onSubscriptionError:(t,s,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;const i=this.subscriptions.get(t);i&&w(i.errorCallbacks,s)},onSubscriptionSettled:(t,s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;const o=this.subscriptions.get(t);if(o){this.ackAndAdvanceCursor(o,s,r),i!==void 0&&n===this.clientId&&(o.lastMutationId=Math.max(o.lastMutationId??0,i));for(const h of o.checkpointCallbacks)h({checkpoint:o.serverCursor,mutationId:o.lastMutationId})}}})}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,W),{body:JSON.stringify({calls:e.map((a,o)=>({args:E(a.args??{},`args for batch call '${a.fn.__lunoraRef}'`),functionPath:a.fn.__lunoraRef,id:o,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 i;try{i=await s.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${s.status.toString()})`)}const n=M(i);if(!s.ok||n!==void 0&&!i.results)throw n!==void 0?X(n):new y("INTERNAL",`LunoraClient: batch request failed (status ${s.status.toString()})`);for(const a of i.results??[]){const o=a.body?.commitCursor;typeof a.id=="number"&&typeof o=="number"&&this.recordShardCursor(e[a.id]?.shardKey,o)}return Gs(i.results??[],e.length)}async runMutation(e,t,s){this.assertOpen();const r=t,i=s.mutationId??se(),n=this.takeReplayCredential(s.replayCredential),a=s.replayBaseline===void 0?this.baselineCursorFor(s.shardKey):s.replayBaseline??void 0,{confirms:o,rollbacks:h}=this.applyOptimisticUpdates(e.__lunoraRef,r,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,t,s.shardKey,h,o);const d=this.offlineFlushes.get(l(s.shardKey));d!==void 0&&await d;const{hasSocket:u,idleClosed:f,polling:m,wasEverConnected:p,wsState:S}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:T}=this.offlineQueue,H=p||T,x=this.WebSocketImpl!==void 0&&H,N=m||f,ve=S==="connecting"&&H&&!N,ge=S!=="open"&&!u&&x&&!N,Te=x&&s.replayBaseline===void 0&&this.hasPendingWriteAhead(s.shardKey),Z=async()=>this.enqueueOfflineMutation(e,r,s.shardKey,a,i,h,o,s.precondition,s.mutationId,n?.stamp);if(ge||ve||Te)return Z();let B;try{const R=await this.rpc(e.__lunoraRef,r,s.shardKey,{baselineSeq:a,captureBookmark:!0,...n?.flags,mutationId:i,onCommitCursor:Q=>{B=Q}});for(const Q of o)Q(B);return{committed:!0,value:R}}catch(R){if(N&&x&&R instanceof TypeError&&pe(r))return Z();throw this.settleFailedDirectWrite(R,B,o,h,n?.flags.authToken),R}}settleFailedDirectWrite(e,t,s,r,i){if(this.noteIdentityMismatch(e),i!==void 0&&this.noteReplayAuthRefusal(e,i),U(e)){for(const n of s)n(t);return}F(r)}async enqueueOfflineMutation(e,t,s,r,i,n,a,o,h,d){const u=d===void 0?this.identityFingerprint():d;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:h??`${this.clientId}:${String(m)}`,identity:u,mutationId:m,...n.length>0&&{onRejected:()=>{F(n)}},shardKey:s})}catch(p){throw F(n),p instanceof Error?p:new Error(String(p))}for(const p of a)p(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,p)=>{const S={args:t,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:r,id:i,clientId:this.clientId,identity:u,precondition:o,onCommit:T=>{for(const H of a)H(T)},reject:T=>{this.queuedIdentities.delete(i),U(T)||F(n),p(T instanceof Error?T:new Error(String(T))),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,u)})}}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(I(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(const{key:s,...r}of e){if(He(this.persistenceVersion,r.version)){this.queryCache.remove(s).catch(()=>{});continue}const i=t.get(s);if(i&&this.cachedQueryMatchesIdentity(r)){this.seedSubscriptionFromCache(i,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(I(e.fn.__lunoraRef,e.argsKey,e.shardKey),t),A(e,_(t.value,e.optimisticLayers)))}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,A(s,_(void 0,s.optimisticLayers))),this.hydratedQueryCache.set(e,t)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,t,s){const r=I(e,t,s),i=this.hydratedQueryCache.get(r);if(!(i===void 0||!this.cachedQueryMatchesIdentity(i)))return this.hydratedQueryCache.delete(r),i}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(const e of this.subscriptions.all()){const t=I(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=I(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.getConnection(e.shardKey)?.identity,i=r===void 0?this.identityFingerprint():r;i===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(s,{identity:i,serverCursor:e.serverCursor,ts:Date.now(),value:t,...i===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(()=>{})},mt))}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.leaderStatus??"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):w(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=Me(),i=this.identityFingerprint();let n;try{n=await fe(async a=>this.sendBatch(s.map(o=>({args:o.args,fn:o.fn,shardKey:o.shardKey})),a))}catch(a){return!(a instanceof TypeError)}if(this.identityFingerprint()!==i)return!0;for(const[a,o]of s.entries()){const h=n[a];if(h!==void 0){if(!h.ok){w(o.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:L(h.value),id:o.id,type:"data"},r)}}return!0}async probeOrigin(){const{fetchImpl:e}=this;if(!e)return!1;try{return await fe(async t=>e(k(this.url,W),{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 i=[],n=[];if(!r)return{confirms:i,rollbacks:n};const a=C.key(e,t,s),o=this.subscriptions.get(a);if(o){const h=Re(o,r);h&&(i.push(h.confirm),n.push(h.rollback))}return{confirms:i,rollbacks:n}}applyOptimisticUpdate(e,t,s,r,i){const{confirms:n,rollbacks:a,store:o}=Pe(this.subscriptions,s);try{e(o,t)}catch{F(a);return}r.push(...a),i.push(...n)}getConnection(e){return this.connections.get(l(e))}sendOrQueueUnsubscribe(e,t,s){const r=this.getConnection(e);r&&!v(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.leaderStatus==="connected"?r="open":this.leaderStatus==="connecting"&&(r="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leaderStatus==="polling",wasEverConnected:this.leaderWasEverConnected,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:at({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:()=>{this.flushOfflineQueue(e).catch(()=>{})},onStateChange:()=>{this.emitConnectionStatus()},poll:async()=>this.pollSubscriptions(e)}),reconnect:re(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[Je]=Ye(e.expectSubject));const r=this.shardCursors.get(this.cursorKeyFor(t));r!==void 0&&(s["x-lunora-min-seq"]=r.toString());const i=e.authToken===void 0?this.authToken:e.authToken;if(i&&(s.authorization=`Bearer ${i}`),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 n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,t,s,r={}){if(!this.fetchImpl)throw new te("LunoraClient: no `fetch` implementation available");const i=this.rpcRequestHeaders(r,s),n=r.authToken===void 0?this.authToken:r.authToken,a=await this.fetchImpl(k(this.url,ot),{body:JSON.stringify({args:E(t,`args for '${e}'`),functionPath:e,shardKey:s}),headers:i,method:"POST"});if(r.captureBookmark){const u=a.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let o;try{o=await a.json()}catch{throw P(a.status,a.statusText,a.headers.get("retry-after"))}const h=o;if(typeof h!="object"||h===null||Array.isArray(h))throw P(a.status,a.statusText,a.headers.get("retry-after"));const d=M(o);if(d!==void 0)throw le(d,a.headers.get("retry-after"));if(!a.ok)throw P(a.status,a.statusText,a.headers.get("retry-after"));r.onMutationAck?.(o.lastMutationId),r.onCommitCursor?.(o.commitCursor),this.noteCredentialAccepted(n),this.learnDefaultShardKey(a,s),this.recordShardCursor(s,o.commitCursor);try{return g(o.result)}catch(u){throw ie(u)}}async adminFetch(e,t,s,r){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");const i={};this.authToken&&(i.authorization=`Bearer ${this.authToken}`);const n=s instanceof ArrayBuffer||s instanceof Blob;let a;s===void 0?a=void 0:n?(a=s,r!==void 0&&(i["content-type"]=r)):(a=JSON.stringify(s),i["content-type"]="application/json");const o=await this.fetchImpl(k(this.url,e),{body:a,headers:i,method:t});let h;try{h=await o.json()}catch{const u=o.statusText?` ${o.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}const d=M(h);if(d!==void 0){const u=new Error(d.message??"admin request failed");throw u.code=d.code,u}if(!o.ok){const u=o.statusText?` ${o.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${o.status.toString()}${u})`)}return h}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));v(e,{caps:Ds,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)}openManagedSocket(e,t,s,r){const{WebSocketImpl:i}=this;if(i===void 0)throw new y("INTERNAL","no WebSocket implementation available");const n=new i(t);e.socket=n;const a=()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===n&&(e.socket=void 0)},o=h=>{a(),r.onClose(h)};s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===n){try{n.close()}catch{}o()}},s)),n.addEventListener("open",()=>{if(e.socket===n){e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now();try{r.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}this.startHeartbeat(e,o)}}),n.addEventListener("message",h=>{if(e.socket===n){e.lastFrameAt=Date.now();try{r.onMessage(h)}catch(d){console.error("[lunora] server frame handler threw",d)}}}),n.addEventListener("close",h=>{e.socket===n&&o(h)}),n.addEventListener("error",()=>{e.socket===n&&o()})}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,this.openManagedSocket(e,this.wsUrlFor(t,s),this.connectTimeoutMs,{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()},yt),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(t),this.clearResubscribeQueue(e);for(const i of this.subscriptions.all())l(i.shardKey)===l(t)&&this.queueResubscribe(i);if(this.resendShapeSubscriptions(t),e.pendingUnsubscribes.length>0){const i=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(const{id:n,type:a}of i)v(e,{id:n,type:a});this.releaseIdleShard(t)}js(e);const r=this.whisperHandlers.get(l(t));if(r)for(const i of r.keys())v(e,{topic:i,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),v(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(),this.stopHeartbeat(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,i]of this.streams)if(!(l(i.shardKey)!==l(e.shardKey)||t.has(r))){if(i.durable){const n={...i.message,...i.generation===void 0?{}:{generation:i.generation},sinceChunk:i.lastSeq};i.message=n,e.pendingStreams=[...(e.pendingStreams??[]).filter(a=>a.id!==r),n];continue}i.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)}startHeartbeat(e,t){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;const{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}t();return}try{s.send(dt)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}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<vt;){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)},gt))}}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 v(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"&&v(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=Ws(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 i=this.getConnection(t);i&&this.releaseResubscribeSlot(i,r.id)}switch(r.type){case"ack":{const i=this.subscriptions.getById(r.id);i&&(i.acked=!0);return}case"chunk":{const{data:i,generation:n,id:a,seq:o}=r,h=this.streams.get(a);h&&typeof o=="number"&&(h.lastSeq=o,typeof n=="number"&&(h.generation=n),h.durable=!0),h?.handle.push(g(i));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.handlePokePart(r,t);break}case"pokeStart":{this.handlePokeStart(r,t);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(Ks(e)),this.forgetStream(s);return}const i=s===void 0?void 0:this.subscriptions.getById(s);if(i){const a=ue(e),o=this.identityFingerprint(),h=C.keyOf(i);w(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(h,a,o);return}const n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&w(n.errorCallbacks,ue(e))}pokeBufferKey(e,t){return`${l(e)}\0${t}`}handlePokeStart(e,t){ae(this.pokeBuffers,Se.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(t,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}handlePokePart(e,t){const s=this.pokeBuffers.get(this.pokeBufferKey(t,e.pokeId));if(!s)return;const r=[];try{for(const a of e.rowsPatch)r.push(a.value===void 0?a:{...a,value:g(a.value)})}catch(a){s.undecodable.set(e.shapeId,a);return}const i=s.parts.get(e.shapeId)??[];for(const a of r)i.push(a);s.parts.set(e.shapeId,i),e.lastMutationId!==void 0&&s.lastMutationId.set(e.shapeId,e.lastMutationId);const n=e.baseCheckpoint??s.baseCheckpoint;n!==void 0&&s.bases.set(e.shapeId,n),e.reset===!0&&s.resets.add(e.shapeId)}handlePokeEnd(e,t){const s=this.pokeBufferKey(t,e.pokeId),r=this.pokeBuffers.get(s);if(r){this.pokeBuffers.delete(s);for(const[i,n]of r.undecodable){const a=this.shapeSubscriptions.get(i);a&&w(a.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape — ${n instanceof Error?n.message:String(n)}`})}for(const i of r.parts.keys()){const n=this.shapeSubscriptions.get(i);n&&!r.undecodable.has(i)&&this.applyPokePart(n,r,e)}}}applyPokePart(e,t,s){const r=t.parts.get(e.id)??[],i=t.resets.has(e.id),n=t.bases.get(e.id),a=t.epoch!==void 0&&e.serverEpoch!==void 0&&t.epoch!==e.serverEpoch,o=n!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==n;if(!i&&(a||o)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}i&&e.rows.clear(),ht(e.rows,r),s.checkpoint!==void 0&&(e.serverCursor=s.checkpoint),s.epoch!==void 0&&(e.serverEpoch=s.epoch);const h=t.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),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)}emitShapeRows(e){const t=[...e.rows.values()];for(const s of e.callbacks)try{s(t)}catch{}}handleDataMessage(e,t){const{id:s}=e,r=s?this.subscriptions.getById(s):void 0;if(!r)return;let i;try{i=this.resolveDataPayload(e,r)}catch(n){w(r.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription — ${n instanceof Error?n.message:String(n)}`});return}if(i===ce){this.resnapshotSubscription(r);return}if(r.serverBase=i,this.dropCacheSeed(C.keyOf(r)),e.cursor!==void 0&&(r.serverCursor=e.cursor),e.epoch!==void 0&&(r.serverEpoch=e.epoch),e.lastMutationId!==void 0){r.lastMutationId=Math.max(r.lastMutationId??0,e.lastMutationId);for(const n of r.checkpointCallbacks)n({checkpoint:r.serverCursor,mutationId:r.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(r),K(r,r.serverCursor),t!==void 0&&Fe(r,t),A(r,_(i,r.optimisticLayers)),this.tabCoordinator?.isLeader()){const n=C.keyOf(r);this.tabCoordinator.broadcastSubscriptionData(n,i,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&&(t.lastMutationId=Math.max(t.lastMutationId??0,e.lastMutationId));for(const s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId});if(this.tabCoordinator?.isLeader()){const s=C.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),K(e,e.serverCursor)&&A(e,_(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,t){if("data"in e&&e.data!==void 0)return g(e.data);const s=g(e.delta);return ke(s)?t.serverBase===void 0?s:we(t.serverBase,s)??ce:s}dispatchWhisper(e,t){const s=this.whisperHandlers.get(l(t))?.get(e.topic);if(!s)return;const r=g(e.data);for(const i of s)try{i(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,w(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(t=>{Ue(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 i=e.charCodeAt(r);t^=i,t=Math.imul(t,16777619),s=Math.imul(s,33)+i}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 i=new Error("offline mutation discarded: auth identity changed before replay");i.code="OFFLINE_IDENTITY_CHANGED",r.reject(i),this.emitItemSettled(r,"rejected",i)}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 i=t??"",n=this.clientWatermarks.get(i);if(n===void 0)this.clientWatermarks.set(i,r);else for(const[a,o]of r)n.set(a,o)}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,A(e,_(void 0,e.optimisticLayers));for(const e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(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:i}=this;try{await this.drainOfflineQueue(e,i)}catch{}!this.closed&&this.authToken!==i&&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 d of s){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");const u=new Error("offline mutation skipped: precondition failed before replay");u.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",u)}const r=l(e),i=this.offlineQueue.drain(d=>l(d.shardKey)===r);if(i.length===0)return;const n=[],a=[];for(const d of i){const u=this.replayGateVerdict(d);u==="send"?n.push(d):u==="hold"&&a.push(d)}if(this.offlineQueue.requeue(a),a.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),n.length===0){this.scheduleRateLimitedRetry(e);return}const o=this.encodableOrSettleTerminal(n);if(o.length===0){this.scheduleRateLimitedRetry(e);return}if(o.length===1){await this.replaySequential(o,e,t),this.scheduleRateLimitedRetry(e);return}const h=[];for(let d=0;d<o.length;d+=q){const u=o.slice(d,d+q),f=await this.replayBatched(u,e,t);if(h.push(...f.requeue),f.stop){h.push(...o.slice(d+q));break}}h.length>0&&this.offlineQueue.requeue(h),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,ne(r))})}noteReplayRetryDelay(e,t,s){const r=l(e),i=this.replayRetryState.get(r),n=(i?.attempts??0)+1,a=Be(t,n)??(s===null&&D(t)?ne(n):void 0);this.replayRetryState.set(r,{attempts:n,delayMs:a===void 0?i?.delayMs:Math.max(i?.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 i=this.replayRetryTimers.get(t);i!==void 0&&clearTimeout(i),this.replayRetryTimers.set(t,setTimeout(()=>{this.replayRetryTimers.delete(t),this.flushOfflineQueue(e).catch(()=>{})},r))}encodableOrSettleTerminal(e){const t=[];for(const s of e)try{E(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)||Qe(e)}noteReplayAuthRefusal(e,t){if(!D(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,...Y(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 i=e[r];if(!i)continue;let n;try{const a=await this.rpc(i.functionPath,i.args,i.shardKey,{authToken:s,baselineSeq:i.baselineSeq,captureBookmark:!0,clientId:i.clientId??this.clientId,...Y(i.identity,s),mutationId:i.id,onCommitCursor:o=>{n=o}});this.settleReplaySuccess(i,a,n)}catch(a){if(U(a)){this.settleReplayUndecodable(i,a,n);continue}if(!this.shouldRequeueReplayFailure(a,s)){this.settleReplayTerminal(i,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((h,d)=>({args:E(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:d,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&De(r)>Ke)return await this.replayBatchedHalves(e,t,s);let i;try{i=await this.fetchImpl(k(this.url,W),{body:r,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:s,...Y(e.find(h=>h.identity!==void 0)?.identity,s)}),method:"POST"})}catch{return{requeue:e,stop:!0}}const n=i.headers.get("x-d1-bookmark");if(n&&this.bookmark.set(n),i.status===413&&e.length>1)return await this.replayBatchedHalves(e,t,s);let a;const o=i.headers.get("retry-after");try{a=await i.json()}catch{return this.settleWholeBatchError(e,P(i.status,i.statusText,o),t,s)}if(!a.results){const h=M(a),d=h===void 0?P(i.status,i.statusText,o):le(h,o);return this.settleWholeBatchError(e,d,t,s)}return{requeue:this.settleReplayBatchSlots(e,a.results,t,s),stop:!1}}settleWholeBatchError(e,t,s,r){if(t instanceof te||t.code!==void 0&&this.shouldRequeueReplayFailure(t,r))return this.noteReplayRetryDelay(s,t,r),{requeue:e,stop:!0};for(const i of e)this.settleReplayTerminal(i,t);return{requeue:[],stop:!1}}async replayBatchedHalves(e,t,s){const r=Math.ceil(e.length/2),i=await this.replayBatched(e.slice(0,r),t,s);if(i.stop)return{requeue:[...i.requeue,...e.slice(r)],stop:!0};const n=await this.replayBatched(e.slice(r),t,s);return{requeue:[...i.requeue,...n.requeue],stop:n.stop}}settleReplayBatchSlots(e,t,s,r){const i=new Map;for(const h of t)typeof h.id=="number"&&h.body!==void 0&&i.set(h.id,h.body);const n=[];let a=!1,o=!1;for(const[h,d]of e.entries()){const u=i.get(h);if(u===void 0)n.push(d);else if("error"in u){const f=be(u);o||=D(f),this.shouldRequeueReplayFailure(f,r)?(this.noteReplayRetryDelay(s,f,r),n.push(d)):this.settleReplayTerminal(d,f)}else a=!0,this.settleReplayBatchResult(d,u)}return a&&!o&&this.noteCredentialAccepted(r),n}settleReplayBatchResult(e,t){let s;try{s=g(t.result)}catch(r){this.settleReplayUndecodable(e,ie(r),t.commitCursor);return}this.settleReplaySuccess(e,s,t.commitCursor)}}export{Se 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 as i}from"./wire-key-DCPYV4t8.mjs";class r{static key(e,y,t){return`${e}::${i(y)}::${t??""}`}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(r.keyOf(e),e),this.byId.set(e.id,e)}remove(e){const y=r.keyOf(e);this.byKey.get(y)===e&&this.byKey.delete(y),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}}export{r as SubscriptionRegistry};
@@ -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
+ const a=new Map,h=new Proxy({},{get(g,e){const n=a.get(e);if(n)return n;const t=new Map,c=new Proxy({},{get(f,r){const o=t.get(r);if(o)return o;const s={__lunoraRef:`${String(e)}:${String(r)}`};return t.set(r,s),s}});return a.set(e,c),c}});export{h as anyApi};
@@ -0,0 +1 @@
1
+ import{a as e,i}from"./delta-merge-D_5ChS-C.mjs";export{e as applyDelta,i as isMutationDelta};
@@ -0,0 +1 @@
1
+ import{s as o}from"./single-blob-store-DrhzObic.mjs";const c="lunora:offline-mutations",d=n=>{const a=o(n.storage,n.key??c),r=async()=>{const e=await a.read();return Array.isArray(e)?e:[]};return{append:e=>a.serialize(async()=>{const t=await r();t.push(e),await a.write(t)}),clear:a.clear,load:()=>a.serialize(r),remove:e=>a.serialize(async()=>{const t=await r(),i=t.filter(s=>s.id!==e);i.length!==t.length&&await a.write(i)}),replace:e=>a.serialize(async()=>{const t=await r(),i=t.findIndex(s=>s.id===e.id);i!==-1&&(t[i]=e,await a.write(t))})}};export{d as createAsyncStoragePersistence};
@@ -0,0 +1 @@
1
+ import{d,e as y}from"./wire-codec-BeIi1K-T.mjs";import{assertMaxEntries as u}from"./createInMemoryQueryCache-D2uNHLfM.mjs";import{s as f}from"./single-blob-store-DrhzObic.mjs";const m="lunora:query-cache",w=50,p=s=>{const c=u(s.maxEntries??w,"createAsyncStorageQueryCache"),t=f(s.storage,s.key??m),o=async()=>{const e=d(await t.read());return typeof e=="object"&&e!==null&&!Array.isArray(e)?new Map(Object.entries(e)):new Map},n=e=>t.write(y(Object.fromEntries(e))),i=e=>{if(e.size<=c)return;const a=[...e.values()].toSorted((r,l)=>r.ts-l.ts);for(const r of a){if(e.size<=c)break;e.delete(r.key)}};return{clear:t.clear,load:()=>t.serialize(async()=>[...(await o()).values()]),put:(e,a)=>t.serialize(async()=>{const r=await o();r.set(e,{...a,key:e}),i(r),await n(r)}),remove:e=>t.serialize(async()=>{const a=await o();a.delete(e)&&await n(a)})}};export{p 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-DDppw8Qr.mjs";import"./SubscriptionRegistry-C3kLqped.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-DnqTxmHd.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-DCPYV4t8.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 g}from"./wire-codec-BeIi1K-T.mjs";const c="_id",d="_creationTime",u="page",m="pageDelta",y=t=>{if(Array.isArray(t))return t;if(g(t)&&Array.isArray(t[u]))return t[u]},l=t=>{let e;for(const n of t){const o=n[d];if(typeof o=="number"){if(e!==void 0){if(o<e)return!0;if(o>e)return!1}e=o}}return!1},x=(t,e)=>{const n=e[d];if(typeof n!="number")return t.length;const o=l(t);for(const[f,s]of t.entries()){const r=s[d];if(typeof r=="number"&&(o?r<n:r>n))return f}return t.length},A=t=>{if(typeof t!="object"||t===null)return;const e=t[c];return typeof e=="string"?e:void 0},b=t=>{if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.key=="string"&&typeof e.table=="string"&&(e.op==="insert"||e.op==="update"||e.op==="delete")},I=(t,e)=>{const n=[];for(const i of t){if(A(i)===void 0)return;n.push(i)}const{key:o,op:f,row:s}=e;if(f==="delete"){const i=n.filter(p=>p[c]!==o);return i.length===n.length?[...n]:i}if(s===void 0)return;const r=[...n],a=n.findIndex(i=>i[c]===o);return a===-1?r.splice(x(n,s),0,s):r[a]=s,r},E=(t,e)=>{const n=y(t);if(n===void 0)return;const o=I(n,e);return o===void 0||Array.isArray(t)?o:{...t,[u]:o}};export{m as P,E as a,b as i};
@@ -0,0 +1 @@
1
+ import{d as r,e as i}from"./wire-codec-BeIi1K-T.mjs";const d=e=>JSON.stringify(i(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-BeIi1K-T.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-C3kLqped.mjs";let f=0;const L=()=>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)=>{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 a=()=>{const o=r.optimisticLayers.findIndex(n=>n.id===i.id);return o===-1?!1:(r.optimisticLayers.splice(o,1),!0)},s=()=>{d(r,p(r.serverBase,r.optimisticLayers))};return{confirm:o=>{if(o===void 0){a();return}i.commitCursor=o,f+=1,i.acknowledgedAt=f,r.serverCursor!==void 0&&r.serverCursor>=o&&a()&&s()},rollback:()=>{c||(c=!0,a(),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},h=(r,e)=>{r.optimisticLayers.length!==0&&(r.optimisticLayers=r.optimisticLayers.filter(t=>t.acknowledgedAt===void 0||t.acknowledgedAt>e))},v=(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 l=y(u,()=>n);l&&(t.push(l.confirm),i.push(l.rollback))}}}};export{y as a,h as b,v as c,k as d,L as e,p as f,d as n};