@lunora/studio 1.0.0-alpha.294 → 1.0.0-alpha.296
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.
- package/dist/standalone/{chunk-YRVZM2TB.js → chunk-2IKYYXNM.js} +1 -1
- package/dist/standalone/{chunk-47EMK7A6.js → chunk-2LIWQ3VZ.js} +1 -1
- package/dist/standalone/{chunk-XQSJORIU.js → chunk-2QVH5KC5.js} +1 -1
- package/dist/standalone/{chunk-627GZOJ7.js → chunk-3CZQMQ7Y.js} +1 -1
- package/dist/standalone/{chunk-7IU6DKN3.js → chunk-3T3I4ANZ.js} +1 -1
- package/dist/standalone/{chunk-OFZX4WXS.js → chunk-3XJ5LMFU.js} +1 -1
- package/dist/standalone/{chunk-DYLF2FA5.js → chunk-4AZFDWOL.js} +1 -1
- package/dist/standalone/{chunk-7GMSZEJR.js → chunk-4OE3Q2HI.js} +1 -1
- package/dist/standalone/{chunk-WFICP5DT.js → chunk-5FOS25JR.js} +1 -1
- package/dist/standalone/{chunk-KVIBTEK5.js → chunk-5ROUNT7R.js} +1 -1
- package/dist/standalone/{chunk-4GQJA35F.js → chunk-7V2HV4G5.js} +1 -1
- package/dist/standalone/{chunk-QLPEA5F7.js → chunk-AWI5MNWN.js} +1 -1
- package/dist/standalone/{chunk-GN3LRVZ2.js → chunk-BSA7XEET.js} +1 -1
- package/dist/standalone/{chunk-NJGORSBO.js → chunk-BTV4JZDW.js} +1 -1
- package/dist/standalone/{chunk-4EFBLED2.js → chunk-BXZADQGW.js} +1 -1
- package/dist/standalone/{chunk-SQDJDYTC.js → chunk-C7VF7NU5.js} +1 -1
- package/dist/standalone/{chunk-67YFV2GM.js → chunk-CLF3SQ2D.js} +1 -1
- package/dist/standalone/{chunk-CVNG6XOK.js → chunk-DNI6LNZ4.js} +1 -1
- package/dist/standalone/{chunk-LW6ERMNX.js → chunk-DPIN5VWB.js} +1 -1
- package/dist/standalone/{chunk-ORVHXDZV.js → chunk-ED6UPEJL.js} +1 -1
- package/dist/standalone/{chunk-OLQTBRWX.js → chunk-EN7DL3D6.js} +1 -1
- package/dist/standalone/{chunk-L56P33FH.js → chunk-G3TVRBKA.js} +1 -1
- package/dist/standalone/{chunk-HHTHP3PA.js → chunk-GU4XLZTD.js} +1 -1
- package/dist/standalone/{chunk-7HE4UK44.js → chunk-HRFHNV4T.js} +1 -1
- package/dist/standalone/{chunk-UEKIUTCJ.js → chunk-IRK3B5SD.js} +1 -1
- package/dist/standalone/{chunk-CX4FEQNT.js → chunk-JCHPR7PH.js} +1 -1
- package/dist/standalone/{chunk-HF4A3NUS.js → chunk-JPGR5DXI.js} +1 -1
- package/dist/standalone/chunk-JYBZHVGR.js +1 -0
- package/dist/standalone/{chunk-QAPKGURH.js → chunk-L4Q5WRM6.js} +1 -1
- package/dist/standalone/{chunk-AJEX5TMG.js → chunk-LIEM55GN.js} +1 -1
- package/dist/standalone/{chunk-DGJMFHBV.js → chunk-MOW4XMIT.js} +1 -1
- package/dist/standalone/{chunk-SJ7BLQMI.js → chunk-NBBCLHM4.js} +1 -1
- package/dist/standalone/{chunk-FJ4FPLVL.js → chunk-NE4ERDVB.js} +1 -1
- package/dist/standalone/{chunk-DB4FJSOK.js → chunk-NH27P54M.js} +1 -1
- package/dist/standalone/{chunk-MEMHDCRE.js → chunk-OM3UFIFS.js} +1 -1
- package/dist/standalone/{chunk-JHYNLMYA.js → chunk-PDHHQRWE.js} +1 -1
- package/dist/standalone/{chunk-V2U4MITD.js → chunk-Q5FZ5WKC.js} +1 -1
- package/dist/standalone/{chunk-LFPYL6YU.js → chunk-QCF6JWLN.js} +1 -1
- package/dist/standalone/{chunk-MTZ5UOQ5.js → chunk-QIXPKL7H.js} +1 -1
- package/dist/standalone/{chunk-J6H3YTFH.js → chunk-R2SQETIF.js} +1 -1
- package/dist/standalone/{chunk-IKKQNSLF.js → chunk-RDLZBY3M.js} +1 -1
- package/dist/standalone/{chunk-5O3OODSZ.js → chunk-RJ2MB5BX.js} +1 -1
- package/dist/standalone/{chunk-Z2GW3PCS.js → chunk-S4KPBXNS.js} +1 -1
- package/dist/standalone/{chunk-WUJ3AOVG.js → chunk-S5KP3SFO.js} +1 -1
- package/dist/standalone/{chunk-D7NNCIX4.js → chunk-TB6R55NX.js} +1 -1
- package/dist/standalone/{chunk-WRQAHEWF.js → chunk-U5HRF22B.js} +1 -1
- package/dist/standalone/{chunk-M6LSAR5C.js → chunk-U6C2EYQE.js} +1 -1
- package/dist/standalone/{chunk-5UEMUPTW.js → chunk-UBFE7Z5K.js} +1 -1
- package/dist/standalone/{chunk-M4VOBOTG.js → chunk-UCWRZCZR.js} +1 -1
- package/dist/standalone/{chunk-C6SAOAML.js → chunk-UH7PYZPF.js} +1 -1
- package/dist/standalone/{chunk-4ELKK7SE.js → chunk-VBZWMOHM.js} +1 -1
- package/dist/standalone/{chunk-RXZJYHAH.js → chunk-VGRACTPB.js} +1 -1
- package/dist/standalone/{chunk-WM6KXJGG.js → chunk-VIWNY3G3.js} +1 -1
- package/dist/standalone/{chunk-W5TWX4V7.js → chunk-VJS2NU3M.js} +1 -1
- package/dist/standalone/{chunk-QB55CQJC.js → chunk-VLUSCROM.js} +1 -1
- package/dist/standalone/{chunk-EQSFFE7F.js → chunk-X76GJISU.js} +1 -1
- package/dist/standalone/{chunk-5XFBQCZ5.js → chunk-XMSYNYLP.js} +1 -1
- package/dist/standalone/{chunk-RVZ2WOZ5.js → chunk-YMLND4NJ.js} +1 -1
- package/dist/standalone/{chunk-EK6VMAUN.js → chunk-YQDRIIWU.js} +1 -1
- package/dist/standalone/{chunk-FJF55TPZ.js → chunk-YRQT6KMR.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +5 -5
- package/dist/standalone/chunk-3ZTPARLJ.js +0 -1
|
@@ -6,4 +6,4 @@ import{a as Yt,d as b}from"./chunk-VEK3S7MV.js";import{a,d as _,e as X,f as Xt,g
|
|
|
6
6
|
|
|
7
7
|
`);for(;u!==-1;){let d=oi(i.slice(0,u));if(i=i.slice(u+2),ui(d,e))return!0;u=i.indexOf(`
|
|
8
8
|
|
|
9
|
-
`)}return!1},"d");for(;;){let{done:u,value:d}=await s.read();if(u)break;if(o(r.decode(d,{stream:!0})),c()){await s.cancel().catch(()=>{});return}}o(r.decode()),c()||e.fail(new b("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),Ws=a((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new b("INTERNAL","httpStream: no `fetch` implementation available");let i=ci(t,e??{},s.baseUrl??""),n=new AbortController,o;s.signal&&(s.signal.aborted?n.abort():(o=a(()=>{n.abort()},"l"),s.signal.addEventListener("abort",o,{once:!0})));let c=a(()=>{o&&s.signal?.removeEventListener("abort",o)},"d"),{handle:u,iterable:d}=We({maxBuffer:s.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel")});return(async()=>{try{let h=await r(i,{headers:{accept:"text/event-stream",...s.headers},method:t.method,signal:n.signal});if(!h.ok){await h.body?.cancel().catch(()=>{}),u.fail(new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${h.status.toString()})`,{status:h.status}));return}if(!h.body){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await hi(h.body,u)}finally{c()}})().catch(h=>{if(n.signal.aborted){u.complete();return}if(h instanceof Error&&"code"in h){u.fail(h);return}u.fail(new b("HTTP_STREAM_TRANSPORT",h instanceof Error?h.message:String(h),{cause:h}))}),d},"_");var di=/["\\\u0000-\u001F\uD800-\uDFFF]/,zs=a(t=>di.test(t)?JSON.stringify(t):`"${t}"`,"y"),It=a(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return zs(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let o="[";for(let c=0;c<t.length;c++)c>0&&(o+=","),o+=It(t[c]);return o+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let o=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${o} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let s=t,r=Object.keys(s).sort(),i="{",n=!0;for(let o of r){let c=s[o];c!==void 0&&(n?n=!1:i+=",",i+=zs(o),i+=":",i+=It(c))}return i+"}"},"i"),te=a(t=>It(R(t)),"u");var Q=class t{static{a(this,"t")}static key(e,s,r){return`${e}::${te(s)}::${r??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){let s=t.keyOf(e);this.byKey.get(s)===e&&this.byKey.delete(s),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}};function ze(t){if(t!==void 0)return e=>{t(e)}}a(ze,"b");var J=a((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var Rt=0,Vs=a(()=>Rt,"h"),li=a((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),Gs=a((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),se=a((t,e)=>{Gs(t,li(e,t.optimisticLayers))},"y"),At=a((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),Gs(t,s);let n=a(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),o=a(()=>{se(t,t.serverBase)},"s");return{confirm:a(c=>{if(c===void 0){n();return}r.commitCursor=c,Rt+=1,r.acknowledgedAt=Rt,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&o()},"confirm"),rollback:a(()=>{i||(i=!0,n(),o())},"rollback")}},"g"),Ve=a((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let s=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(r=>r.commitCursor===void 0||r.commitCursor>e),t.optimisticLayers.length!==s},"k"),Js=a((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),pe=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),Ys=a((t,e)=>{let s=[],r=[],i=a((n,o)=>t.get(Q.key(n,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:a(n=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:a((n,o)=>i(n.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:a((n,o,c)=>{let u=i(n.__lunoraRef,o??{});if(!u)return;let d=At(u,()=>c);d&&(s.push(d.confirm),r.push(d.rollback))},"setQuery")}}},"_");var Ft=a(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let s=Date.parse(t);if(Number.isNaN(s))return;let r=s-Date.now();return r>0?r:void 0},"f"),fi=a((t,e)=>{let s=Ft(e);if(!(s===void 0||$e(t)!==void 0))return t.data===void 0?{retryAfterMs:s}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:s}:void 0},"v"),me=a(t=>{let e=t?.error;return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0},"l"),pi=a(()=>new $("LunoraClient: batch slot carried no error envelope"),"m"),Xs=a((t,e)=>{let s=t.error,r=typeof s?.code=="string"?s.code:void 0,i=typeof s?.message=="string"?s.message:void 0;return{code:r,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"s"),Zs=a(t=>{let{code:e,messageText:s}=Xs(t,"stream error");return e===void 0?new Error(s):new b(e,s)},"g"),Pt=a(t=>{let{code:e,messageText:s}=Xs(t,"subscription error");return{message:s,...e===void 0?{}:{code:e}}},"A"),Ge=a(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,t.data!==void 0)try{e.data=w(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"n"),Mt=a((t,e)=>{let s=Ge(t),r=fi(s,e);return r!==void 0&&(s.data=r),s},"y"),Je=a(t=>{let e=me(t);return e===void 0?pi():Ge(e)},"h");var er=0,mi=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();er+=1;let t=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${er.toString(36)}_${t}`},"d"),xt=a((t,e)=>t!==void 0&&e!==t,"f"),Xe=mi,re=a((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"o"),Ye=class{static{a(this,"l")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},s={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=s.persistence,this.onEvict=s.onEvict,this.onSizeChange=s.onSizeChange,this.version=s.version}get size(){return this.items.length}enqueue(e){let s=e;s.id??=Xe(),this.items.push(s),this.persistence?.append({args:s.args,...s.baselineSeq===void 0?{}:{baselineSeq:s.baselineSeq},clientId:s.clientId,functionPath:s.functionPath,id:s.id,identity:s.identity,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(r=>{re(this.onPersistenceError,"append",r,s.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw re(this.onPersistenceError,"load",o),o}let s=[],r=new Set(this.items.map(o=>o.id));for(let o of e)if(!r.has(o.id)){if(xt(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{re(this.onPersistenceError,"remove",c,o.id)});continue}r.add(o.id),s.push({args:o.args,baselineSeq:o.baselineSeq,clientId:o.clientId,functionPath:o.functionPath,id:o.id,identity:o.identity,reject:a(()=>{},"reject"),resolve:a(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let o of s)i.has(o)&&n.add(o.shardKey);return[...n]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;if(!this.persistence||i===void 0)continue;let n={args:r.args,...r.baselineSeq===void 0?{}:{baselineSeq:r.baselineSeq},clientId:r.clientId,functionPath:r.functionPath,id:i,identity:s,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(o=>{re(this.onPersistenceError,"replace",o,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.notifySize(),i}let s=[],r=[];for(let i of this.items)(e(i)?s:r).push(i);return this.items.length=0,this.items.push(...r),this.notifySize(),s}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],s=[];for(let r of this.items)if(r.precondition!==void 0&&!r.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",r.reject(i),e.push(r)}else s.push(r);return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of this.items){let s=new Error("CLIENT_CLOSED");s.code="CLIENT_CLOSED",e.reject(s)}this.items.length=0,this.notifySize()}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await r.replace(s)}catch(i){re(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(r=>{re(this.onPersistenceError,"remove",r,e.id)});let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var yi="lunora-outbox",bi="offline-mutations",Qt="by_id",gi=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??yi,r=t.storeName??bi,i=qe(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(Qt,"id",{unique:!0})}),n=Ke(i,r);return{append:a(async o=>{await n("readwrite",c=>x(c.add(o)))},"append"),clear:a(async()=>{await n("readwrite",o=>x(o.clear()))},"clear"),load:a(async()=>n("readonly",o=>x(o.getAll())),"load"),remove:a(async o=>{await n("readwrite",async c=>{let u=await x(c.index(Qt).getKey(o));u!==void 0&&await x(c.delete(u))})},"remove"),replace:a(async o=>{await n("readwrite",async c=>{let u=await x(c.index(Qt).getKey(o.id));u!==void 0&&await x(c.put(o,u))})},"replace")}},"w"),tr=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return gi()}},"b");var _t=a((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let o=Math.min(r,s*2**n);if(n+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){n=0}}},"s");var sr=a((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present?te(i.value):void 0;return()=>{let o=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!o.present?!0:te(o.value)===n}},"c");var Lt=500,hr=a((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Se");new TextDecoder;var vi=new TextEncoder,Si=a(t=>Ds(vi.encode(JSON.stringify(t))),"tt"),wi="x-lunora-expect-subject",Ci=a(t=>Si({subject:t}),"rt"),rr=Symbol.for("lunora:session-change"),ki="lunora:session-change",Ti="better-auth.message",Ei="signout",dr=a(()=>{let t=globalThis,e=t[rr];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[rr]=e),e},"ge"),Oi=a(()=>"document"in globalThis,"ot"),Ii=a(async()=>{let t=[];for(let e of dr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"ct"),Ri=a((t,e)=>{if(t!==Ti||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===Ei}catch{return!1}},"dt"),Ai=a(t=>{let e=[],s=a(()=>{Ii().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(ki):void 0}catch{r=void 0}if(r!==void 0){let n=r;n.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==t&&s()}),e.push(()=>{n.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let n=a(o=>{Ri(o.key,o.newValue)&&s()},"n");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"ut"),Fi=a(t=>{let e=dr();return e.listeners.add(t),e.detach===void 0&&Oi()&&(e.detach=Ai(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"ht"),Pi="/_lunora/rpc",Dt="/_lunora/rpc-batch",Mi="/_lunora/ws",xi="/_lunora/admin/shard-traffic",Qi="/_lunora/admin/scheduled",_i="/_lunora/admin/scheduled/status",Li="/_lunora/admin/scheduled/ws",Di="/_lunora/admin/scheduled/cancel",ir="/_lunora/admin/scheduled/dead",Ui="/_lunora/admin/scheduled/dead/retry",Ni="/_lunora/admin/scheduled/dead/cancel",qi="/_lunora/admin/workflows/instances",Ki="/_lunora/admin/workflows/instance",ji="/_lunora/admin/workflows/status",Wt="/_lunora/admin/storage",Bi="/_lunora/admin/storage/url",$i="/_lunora/admin/storage/buckets",Hi="/_lunora/admin/functions",Wi="/_lunora/admin/cron-jobs",zi="/_lunora/admin/cron-jobs/run",Vi="/_lunora/admin/architecture",Gi="/_lunora/admin/openapi",Ji="/_lunora/admin/openrpc",Yi="/_lunora/admin/global/tables",Xi="/_lunora/admin/global/table",Zi="/_lunora/admin/global/facet",en="/_lunora/admin/vector/indexes",tn="/_lunora/admin/vector/query",sn="/_lunora/admin/logs/archive",rn="/_lunora/admin/kv/namespaces",nn="/_lunora/admin/kv/keys",zt="/_lunora/admin/kv/value",an="/_lunora/admin/auth/users",on="/_lunora/admin/auth/sessions",cn="/_lunora/admin/auth/users/create",un="/_lunora/admin/auth/users/role",hn="/_lunora/admin/auth/users/ban",dn="/_lunora/admin/auth/users/unban",ln="/_lunora/admin/auth/users/password",fn="/_lunora/admin/auth/users/remove",pn="/_lunora/admin/auth/users/impersonate",mn="/_lunora/admin/auth/sessions/revoke",yn="/_lunora/admin/auth/sessions/revoke-all",bn="/_lunora/admin/auth/capabilities",gn="/_lunora/admin/auth/users/update",vn="/_lunora/admin/auth/accounts",Sn="/_lunora/admin/auth/accounts/unlink",wn="/_lunora/admin/auth/passkeys",Cn="/_lunora/admin/auth/passkeys/delete",kn="/_lunora/admin/auth/two-factor/disable",Tn="/_lunora/admin/auth/organizations",En="/_lunora/admin/auth/organizations/members",On="/_lunora/admin/auth/organizations/invitations",In="/_lunora/admin/auth/organizations/members/remove",Rn="/_lunora/admin/auth/organizations/invitations/cancel",An="/_lunora/admin/auth/config",Fn="/_lunora/admin/auth/sign-up-invitations",Pn="/_lunora/admin/auth/sign-up-invitations/create",Mn="/_lunora/admin/auth/sign-up-invitations/revoke",xn="/_lunora/admin/auth/organizations/create",Qn="/_lunora/admin/auth/organizations/update",_n="/_lunora/admin/auth/organizations/remove",Ln="/_lunora/admin/auth/organizations/members/add",Dn="/_lunora/admin/auth/organizations/members/invite",Un="/_lunora/admin/auth/organizations/members/role",Nn="/_lunora/admin/auth/organizations/teams",qn="/_lunora/admin/auth/organizations/teams/create",Kn="/_lunora/admin/auth/organizations/teams/update",jn="/_lunora/admin/auth/organizations/teams/remove",Bn="/_lunora/admin/auth/organizations/teams/members",$n="/_lunora/admin/auth/organizations/teams/members/add",Hn="/_lunora/admin/auth/organizations/teams/members/remove",Wn="/_lunora/admin/auth/organizations/roles",zn="/_lunora/admin/auth/organizations/roles/create",Vn="/_lunora/admin/auth/organizations/roles/update",Gn="/_lunora/admin/auth/organizations/roles/remove",Jn="/api/auth",Yn="/get-session",Xn="lunora-ping",Zn=a(async t=>(t.assertOpen(),(await t.adminFetch(Hi,"GET")).functions??[]),"Hs"),ea=a(async t=>(t.assertOpen(),(await t.adminFetch(Wi,"GET")).jobs??[]),"Ls"),ta=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(zi,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Ms"),sa=a(async t=>(t.assertOpen(),await t.adminFetch(Gi,"GET")),"Us"),ra=a(async t=>(t.assertOpen(),await t.adminFetch(Vi,"GET")),"Ns"),ia=a(async t=>(t.assertOpen(),await t.adminFetch(Ji,"GET")),"xs"),na=a(async t=>(t.assertOpen(),await t.adminFetch(Yi,"GET")),"Ds"),aa=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(R(e.filters))),w(await t.adminFetch(`${Xi}?${s.toString()}`,"GET"))},"Bs"),oa=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(R(e.filters))),w(await t.adminFetch(`${Zi}?${s.toString()}`,"GET"))},"Qs"),Vt=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"re"),nr=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"fe"),ie=a((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"k"),P=a((t,e)=>{let s=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&s.set(i,String(n));let r=s.toString();return r===""?t:`${t}?${r}`},"b"),ca=a(async t=>(t.assertOpen(),(await t.adminFetch(rn,"GET")).namespaces??[]),"Ks"),ua=a(async(t,e)=>{t.assertOpen();let s=P(nn,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"qs"),ha=a(async(t,e)=>{t.assertOpen();let s=P(zt,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Ws"),da=a(async(t,e)=>{t.assertOpen(),await t.adminFetch(zt,"PUT",e)},"js"),la=a(async(t,e)=>{t.assertOpen();let s=P(zt,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"$s"),fa=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(xi,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"Gs"),pa=a(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(sn,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"Vs"),ma=a(async t=>{let e=[],s;for(;;){let r=await t(s);if(e.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return e;if(r.cursor===s)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");s=r.cursor}},"zs"),Gt=a(t=>"args"in t?{...t,args:w(t.args)}:t,"ie"),ya=a(async t=>(t.assertOpen(),((await t.adminFetch(Qi,"GET")).records??[]).map(e=>Gt(e))),"Js"),ba=a(async t=>{t.assertOpen();let e=await t.adminFetch(_i,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"Ys"),ga=a(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(Di,"POST",{id:e})).cancelled===!0}),"Xs"),va=a(async t=>(t.assertOpen(),(await ma(async e=>await t.adminFetch(e===void 0?ir:`${ir}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>Gt(e))),"Zs"),Sa=a(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(Ui,"POST",{id:e})).retried===!0}),"er"),wa=a(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(Ni,"POST",{id:e})).removed===!0}),"tr"),Ca=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({name:e.name});e.status!==void 0&&s.set("status",e.status),e.page!==void 0&&s.set("page",String(e.page)),e.perPage!==void 0&&s.set("perPage",String(e.perPage));let r=await t.adminFetch(`${qi}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"sr"),ka=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${Ki}?${s.toString()}`,"GET");return{createdOn:r.createdOn,endedOn:r.endedOn,error:r.error,id:r.id??e.id,output:r.output,params:r.params,startedOn:r.startedOn,status:r.status??"unknown",steps:r.steps??[]}},"rr"),Ta=a(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(ji,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"ir"),Ea=a(async(t,e={})=>{t.assertOpen();let s=P(Wt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await t.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}},"nr"),Oa=a(async(t,e,s)=>{t.assertOpen();let r=`${Wt}?key=${encodeURIComponent(e)}${Vt(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"ar"),Ia=a(async t=>(t.assertOpen(),(await t.adminFetch($i,"GET")).buckets??[]),"or"),Ra=a(async(t,e)=>{t.assertOpen();let s=`${Wt}?key=${encodeURIComponent(e.key)}${Vt(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"cr"),Aa=a(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${Bi}?key=${encodeURIComponent(e)}${i}${Vt(s?.bucket)}`,o=await t.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},"dr"),Fa=a(async t=>(t.assertOpen(),(await t.adminFetch(en,"GET")).indexes??[]),"ur"),Pa=a(async(t,e)=>(t.assertOpen(),(await t.adminFetch(tn,"POST",e)).matches??[]),"hr"),ne=a((t,e)=>{try{return R(t)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${r}`,s instanceof Error?{cause:s}:void 0)}},"w"),ar=a(t=>{try{return R(t),!0}catch{return!1}},"pe"),lr=a(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Te"),Ma=a((t,e)=>{let s=Array.from({length:e});for(let r of t){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;if(!lr(r.body)){s[r.id]={error:Je({}),ok:!1};continue}let i=r.body;s[r.id]="error"in i?{error:Je(i),ok:!1}:{ok:!0,value:w(i.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"lr"),Ut=a((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"G"),xa=3e4,Qa=1e4,_a=5e3,La=3,Da=250,Ua=5e3,Na=5e3,qa=64,Ka=3,ja=1e4,Ba=8,Nt=a(t=>t==="connected"||t==="polling","V"),g=a(t=>t??"","l"),D=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"g"),$a=a(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)D(t,s)},"wr"),Ha=new TextDecoder,Wa=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return Ha.decode(t)},"Ar"),ae=class{static{a(this,"_")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[s]=e;for(let r of this.listeners)try{r(s)}catch{}}clear(){this.listeners.clear()}},Ee=a(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"F"),za=a((t,e,s)=>{Ee(t),!(e<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;let{socket:r}=t;if(Date.now()-t.lastFrameAt>e*2.5){try{r.close()}catch{}s();return}try{r.send(Xn)}catch{}},e))},"_r"),or=a((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:n,heartbeatIntervalMs:o}=s;if(i===void 0)throw new b("INTERNAL","no WebSocket implementation available");let c=new i(e);t.socket=c;let u=a(()=>{Ee(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),d=a(h=>{u(),r.onClose(h)},"d");n>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}d()}},n)),c.addEventListener("open",()=>{if(t.socket===c){t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now();try{r.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}za(t,o,d)}}),c.addEventListener("message",h=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(h)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),c.addEventListener("close",h=>{t.socket===c&&d(h)}),c.addEventListener("error",()=>{t.socket===c&&d()})},"me"),Va=a(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:n}=t,o=s>0&&e>0,c=0,u,d=!1,h=!1,l=a(()=>{u!==void 0&&(clearInterval(u),u=void 0,d=!1,i())},"h"),f=a(m=>{if(u!==void 0){if(!m){l();return}d||(d=!0,i()),r()}},"p"),p=a(()=>{h||(h=!0,n().then(f).finally(()=>{h=!1}).catch(()=>{}))},"m");return{isPolling:a(()=>u!==void 0&&d,"isPolling"),noteFailedOpen:a(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(p,s),i(),p())},"noteFailedOpen"),noteOpen:a(()=>{c=0,l()},"noteOpen"),stop:l}},"Ir"),Ga=1e4,cr=a(async t=>{let e=new AbortController,s,r=new Promise((i,n)=>{s=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},Ga)});try{return await Promise.race([t(e.signal),r])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(s)}},"ye"),fr=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Ja=a(t=>{if(t instanceof $)return!0;let e=t?.code;return e===void 0||fr.has(e)||Ot.has(e)},"Rr"),pr=6e4,Ya=1e3,Xa={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Te=a((t,e,s)=>{let r=Ft(s),i=r===void 0?void 0:{retryAfterMs:r},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new $(n,i):new b(Xa[t]??"BAD_REQUEST",n,{data:i})},"P"),Kt=a((t,e=Math.random)=>{let s=Math.min(Ya*2**Math.max(t-1,0),pr);return Math.round(s*(.5+e()*.5))},"X"),Za=a(t=>t instanceof $||fr.has(t?.code??""),"Hr"),eo=a((t,e,s)=>{let r=$e(t);return r!==void 0&&r>0?Math.min(r,pr):Za(t)?Kt(e,s):void 0},"Lr"),to=983040,so=a(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Ur"),mr=new WeakSet,yr=a(t=>{let e=new b("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) \u2014 ${t instanceof Error?t.message:String(t)}`,{cause:t});return mr.add(e),e},"we"),Ze=a(t=>t instanceof Error&&mr.has(t),"N"),ro=a(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&lr(s.body)&&e.set(s.id,s.body);return e},"Nr"),io=a(t=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:Je(t),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:w(t.result)}}catch(e){return{commitCursor:t.commitCursor,error:yr(e),kind:"undecodable"}}},"xr"),qt=a((t,e)=>`${g(t)}\0${e}`,"z"),no=a((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"Dr"),jt=class{static{a(this,"Br")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){hr(this.buffers,this.maxBuffers),this.buffers.set(qt(e,s.pokeId),{baseCheckpoint:s.baseCheckpoint,bases:new Map,epoch:s.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,s){let r=this.buffers.get(qt(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:w(c.value)})}catch(c){r.undecodable.set(s.shapeId,c);return}let n=r.parts.get(s.shapeId)??[];for(let c of i)n.push(c);r.parts.set(s.shapeId,n),s.lastMutationId!==void 0&&r.lastMutationId.set(s.shapeId,s.lastMutationId);let o=s.baseCheckpoint??r.baseCheckpoint;o!==void 0&&r.bases.set(s.shapeId,o),s.reset===!0&&r.resets.add(s.shapeId)}end(e,s){let r=qt(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},ao=a((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),n=e.bases.get(t.id),o=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=n!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==n;if(!i&&(o||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,"reseed";i&&t.rows.clear(),no(t.rows,r),s.checkpoint!==void 0&&(t.serverCursor=s.checkpoint),s.epoch!==void 0&&(t.serverEpoch=s.epoch);let u=e.lastMutationId.get(t.id);return u!==void 0&&(t.lastMutationId=u),"applied"},"Qr"),ur=a(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"be"),oo=a((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&J(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"Kr"),Bt=a((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"Z"),$t=a((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"ee"),br=a((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Ee"),et=a((t,e)=>t!==void 0&&t!==e,"x"),co=a((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","qr"),uo=a(t=>{for(let e of t.activeSubscriptions())t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Wr"),ho=a(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1},"jr"),lo=a((t,e,s)=>{if(et(s,t.identityFingerprint()))return;let r=t.leader,i=co(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&t.flushOfflineQueues()},"$r"),fo=a(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Gr"),po=a((t,e,s,r,i,n)=>{if(et(n,t.identityFingerprint()))return;let o=t.subscription(e);o&&(t.dropCacheSeed(e),br(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&Ve(o,r),se(o,s))},"Vr"),mo=a((t,e,s,r)=>{if(et(r,t.identityFingerprint()))return;let i=t.subscription(e);i&&J(i.errorCallbacks,s)},"zr"),yo=a((t,e,s,r,i,n,o)=>{if(et(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&n===t.clientIdentifier()&&Bt(c,i),$t(c))},"Jr"),bo=a((t,e,s)=>t!==null||e&&s===null,"Yr"),go=[js],vo=Promise.resolve(),Ht=class t{static{a(this,"Ae")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:a((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:a(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new Q;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new ae;statusListeners=new ae;tokenExpiredListeners=new ae;identityChangeListeners=new ae;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new ae;pendingChangeListeners=new ae;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new jt(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??ie(nr(e.url),Mi),this.wsToken=e.wsToken;let s=e.authBasePath??Jn;this.authBasePath=s.endsWith("/")?s.slice(0,-1):s,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??qs(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??xa,this.connectTimeoutMs=e.connectTimeoutMs??Qa,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??_a,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??La,this.defaultConnectionContext=e.connectionContext,this.persistence=tr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ns(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new je,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=vo),this.offlineQueue=new Ye(e.offlineQueue,{onEvict:a((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onSizeChange:a(r=>{this.pendingChangeListeners.emit(r)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${Xe()}`,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=Fi(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),u=this.authToken;this.authToken=e,this.applySubject(e,s);let d=this.identityFingerprint();d!==i&&(!r&&e!==null&&n?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&n&&!c?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(u,e),bo(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(d!==i||r||o)&&this.offlineQueue.size>0&&Nt(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){let s=this.identityVerdict(e);if(s!=="match")return{verdict:s};let r=Object.freeze({});return this.replayCredentials.set(r,{authToken:this.authToken,stamp:e}),{credential:r,verdict:s}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,s,r){let i=r?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new b("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=r?.shardKey??"",o=this.identityFingerprint(),c,u,d;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:a(h=>{c=h},"onMutationAck")})}catch(h){if(!Ze(h))throw h;d=h}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(n)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(hr(this.clientWatermarks,Ba),h=new Map,this.clientWatermarks.set(o??"",h)),h.set(n,c)}if(d!==void 0)throw d;return{applied:c===void 0||c===i,result:u}}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;let e={},s=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let r=this.sessionProbeGeneration;try{let i=await this.fetchImpl(ie(this.url,`${this.authBasePath}${Yn}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let n=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,n,r),n}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.bounceShardSockets())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=g(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r),e===void 0&&this.releaseIdleShard(s.shardKey)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=g(s.shardKey),i={context:e},n=this.connectionContextHolders.get(r);n?n.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let o=!1;return()=>{if(o)return;o=!0;let c=this.connectionContextHolders.get(r);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(r),this.refreshConnectionContext(r),this.releaseIdleShard(s.shardKey)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=g(r.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let o=n.get(e),c=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&D(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),d=u?.get(e);if(!d?.delete(s)||d.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let h=this.getConnection(r.shardKey);h&&D(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseIdleShard(r.shardKey)}}whisper(e,s,r={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey);i&&D(i,{data:ne(s??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"}),this.releaseIdleShard(r.shardKey)}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let n of r){let o=this.connections.get(n);e.push({confirmedMutationWatermark:s?.get(n)??0,hasSocket:o?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,o)=>(n.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((n,o)=>n.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){let s=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),s}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,s){this.clientQueryStore.set(e,s)}subscribeClientQuery(e,s){return this.clientQueryStore.subscribe(e,s)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,s,r){return sr(this,e,s,r)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){if(!this.readyResolved)return;let i=te(s),n=oe(e,i,r),o=this.hydratedQueryCache.get(n);if(o!==void 0)return this.cachedQueryMatchesIdentity(o)?o.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=Q.key(e,s,r),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,s,r={}){let{value:i}=await this.runMutation(e,s,r);return i}canQueueOffline(e){let{wasEverConnected:s}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(s||this.offlineQueue.queueBeforeFirstConnect)}async action(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),n=r.toArgs??(h=>({rows:h})),o=s.length,c=0,u=0,d=0;for(let h=0;h<o;h+=i){let l=s.slice(h,h+i),f=d,{committed:p}=await this.runMutation(e,n(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(f)}`},shardKey:r.shardKey});d+=1,c+=l.length,p&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:d,imported:u,queued:c-u}}async shardTraffic(e){return fa(this.adminHost,e)}async listScheduledJobs(){return ya(this.adminHost)}async schedulerStatus(){return ba(this.adminHost)}async cancelScheduledJob(e){return ga(this.adminHost,e)}async listDeadJobs(){return va(this.adminHost)}async retryDeadJob(e){return Sa(this.adminHost,e)}async removeDeadJob(e){return wa(this.adminHost,e)}async listWorkflowInstances(e){return Ca(this.adminHost,e)}async getWorkflowInstance(e){return ka(this.adminHost,e)}async setWorkflowInstanceStatus(e){return Ta(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=ie(nr(this.url),Li),r=_t(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,o=!1,c=a(()=>{o||this.closed||(n=setTimeout(h,r.next()))},"a"),u=a(f=>{if(o||this.WebSocketImpl===void 0)return;let p=f===void 0?s:`${s}?token=${encodeURIComponent(f)}`;or(i,p,this.managedSocketOptions,{onClose:a(()=>{c()},"onClose"),onMessage:a(m=>{let y;try{y=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}y.type==="jobs"&&Array.isArray(y.records)&&(r.reset(),e(y.records.map(S=>Gt(S))))},"onMessage")})},"c"),d=a(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"d"),h=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){d(f).catch(()=>{});return}u(f)},"u");h();let l=a(()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),Ee(i),i.socket?.close(),i.socket=void 0},"h");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return Zn(this.adminHost)}async getCronJobs(){return ea(this.adminHost)}async runCronJob(e){return ta(this.adminHost,e)}async fetchOpenApi(){return sa(this.adminHost)}async fetchArchitecture(){return ra(this.adminHost)}async fetchOpenRpc(){return ia(this.adminHost)}async listStorageObjects(e={}){return Ea(this.adminHost,e)}async deleteStorageObject(e,s){return Oa(this.adminHost,e,s)}async listStorageBuckets(){return Ia(this.adminHost)}async uploadStorageObject(e){return Ra(this.adminHost,e)}async signedStorageUrl(e,s){return Aa(this.adminHost,e,s)}async listGlobalTables(){return na(this.adminHost)}async readGlobalTablePage(e){return aa(this.adminHost,e)}async facetGlobalColumn(e){return oa(this.adminHost,e)}async listVectorIndexes(){return Fa(this.adminHost)}async queryVectorIndex(e){return Pa(this.adminHost,e)}async queryLogArchive(e={}){return pa(this.adminHost,e)}async listKvNamespaces(){return ca(this.adminHost)}async listKvKeys(e){return ua(this.adminHost,e)}async getKvValue(e){return ha(this.adminHost,e)}async putKvValue(e){return da(this.adminHost,e)}async deleteKvKey(e){return la(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();let s=P(an,{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(s,"GET")}async createAuthUser(e){return this.assertOpen(),await this.adminFetch(cn,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(un,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(hn,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(dn,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(ln,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(fn,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(pn,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(mn,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(yn,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(bn,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(gn,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(P(vn,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(Sn,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(P(wn,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(Cn,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(kn,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(P(Tn,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();let s=P(En,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.assertOpen();let s=P(On,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();let s=P(Fn,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(Pn,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(Mn,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(In,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(Rn,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(An,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(xn,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Qn,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(_n,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Ln,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Dn,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Un,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();let s=P(Nn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(qn,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Kn,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(jn,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();let s=P(Bn,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch($n,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(Hn,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();let s=P(Wn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(zn,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Vn,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Gn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=P(on,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){this.assertOpen();let n=s??{},o=Q.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),u=ze(r),d=ze(i.onError),h=ze(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=te(n),m=this.takeHydratedCache(e.__lunoraRef,p,i.shardKey);c={acked:!1,args:n,argsKey:p,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,wireArgs:ne(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(o,m)}if(c.callbacks.add(u),d&&c.errorCallbacks.add(d),h&&c.checkpointCallbacks.add(h),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),d&&l.errorCallbacks.delete(d),h&&l.checkpointCallbacks.delete(h),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(Q.keyOf(l)),this.subscriptions.remove(l),this.releaseIdleShard(l.shardKey))}}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:o}=r;return o!==void 0&&queueMicrotask(()=>{o({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:ne(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey)}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new b("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=r,o=s??{},{handle:c,iterable:u}=We({maxBuffer:r.maxBuffer,onCancel:a(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let d=this.getConnection(n),h={id:i,query:{args:ne(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:h,shardKey:n};this.streams.set(i,l);let f=d?.wsState==="open"&&D(d,h);if(!f&&d===void 0)return this.forgetStream(i),c.fail(new b("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=qa;){let p=d.pendingStreams.shift()?.id,m=p?this.streams.get(p):void 0;m&&(m.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(p))}d.pendingStreams.push(h)}return u}httpStream(e,s,r={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return Ws(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new b("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new b("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let s=e.leaderTabId;return s!==void 0&&s!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new b("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){let s=a(r=>g(r)===e,"t");return this.subscriptions.all().some(r=>s(r.shardKey))||[...this.shapeSubscriptions.values()].some(r=>s(r.shardKey))||[...this.streams.values()].some(r=>s(r.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(r=>s(r.shardKey))}releaseIdleShard(e){let s=g(e),r=this.connections.get(s);this.closed||s===""||r===void 0||(clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.idleTimer=void 0,!(this.closed||this.connections.get(s)!==r||this.shardInUse(s))&&(r.wasEverConnected&&this.idleClosedShards.add(s),this.teardownConnection(r),this.connections.delete(s),this.emitConnectionStatus())},Na))}forgetStream(e){let s=this.streams.get(e);this.streams.delete(e),s&&this.releaseIdleShard(s.shardKey)}teardownConnection(e){e.polling.stop();let s=g(e.shardKey);for(let[i,n]of this.streams)g(n.shardKey)===s&&(n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,Ee(e);let{socket:r}=e;if(r){e.socket=void 0;try{r.close()}catch{}}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,s={activeSubscriptions:a(()=>this.subscriptions.all(),"activeSubscriptions"),broadcastStatus:a((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:a(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:a(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:a(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:a(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:a(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:a(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:a(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:a(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:a(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:a(()=>this.clientId,"clientIdentifier"),dropCacheSeed:a(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:a((r,i,n)=>{this.ackAndAdvanceCursor(r,i,n)},"ackAndAdvanceCursor"),subscription:a(r=>this.subscriptions.get(r),"subscription")};return new Be({channelName:e,onBecomeLeader:a(()=>{uo(s)},"onBecomeLeader"),onStopBeingLeader:a(()=>{ho(s)},"onStopBeingLeader"),onConnectionStatus:a((r,i)=>{lo(s,r,i)},"onConnectionStatus"),onSubscriptionData:a((r,i,n,o,c)=>{po(s,r,i,n,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:a(()=>{fo(s)},"onLeaderClaimAnswered"),onSubscriptionError:a((r,i,n)=>{mo(s,r,i,n)},"onSubscriptionError"),onSubscriptionSettled:a((r,i,n,o,c,u)=>{yo(s,r,i,n,o,c,u)},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(ie(this.url,Dt),{body:JSON.stringify({calls:e.map((c,u)=>({args:ne(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let n;try{n=await r.json()}catch{throw new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let o=me(n);if(!r.ok||o!==void 0&&!n.results)throw o!==void 0?Ge(o):new b("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let c of n.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return Ma(n.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=s,n=r.mutationId??Xe(),o=this.takeReplayCredential(r.replayCredential),c=r.replayBaseline===void 0?this.baselineCursorFor(r.shardKey):r.replayBaseline??void 0,{confirms:u,rollbacks:d}=this.applyOptimisticUpdates(e.__lunoraRef,i,r.shardKey,r.optimistic);r.optimisticUpdate&&this.applyOptimisticUpdate(r.optimisticUpdate,s,r.shardKey,d,u);let h=this.offlineFlushes.get(g(r.shardKey));h!==void 0&&await h;let{hasSocket:l,idleClosed:f,polling:p,wasEverConnected:m,wsState:y}=this.connectionGateState(r.shardKey),{queueBeforeFirstConnect:S}=this.offlineQueue,C=m||S,T=this.WebSocketImpl!==void 0&&C,E=p||f,H=y==="connecting"&&C&&!E,W=y!=="open"&&!l&&T&&!E,ye=T&&r.replayBaseline===void 0&&this.hasPendingWriteAhead(r.shardKey),U=a(async()=>this.enqueueOfflineMutation(e,i,r.shardKey,c,n,d,u,r.precondition,r.mutationId,o?.stamp),"ne");if(W||H||ye)return U();let O;try{let N=await this.rpc(e.__lunoraRef,i,r.shardKey,{baselineSeq:c,captureBookmark:!0,...o?.flags,mutationId:n,onCommitCursor:a(Y=>{O=Y},"onCommitCursor")});for(let Y of u)Y(O);return{committed:!0,value:N}}catch(N){if(E&&T&&N instanceof TypeError&&ar(i))return U();throw this.settleFailedDirectWrite(N,O,u,d,o?.flags.authToken),N}}settleFailedDirectWrite(e,s,r,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),Ze(e)){for(let o of r)o(s);return}pe(i)}async enqueueOfflineMutation(e,s,r,i,n,o,c,u,d,h){let l=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;let f=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(f)}`,identity:l,mutationId:f,...o.length>0&&{onRejected:a(()=>{pe(o)},"onRejected")},shardKey:r})}catch(p){throw pe(o),p instanceof Error?p:new Error(String(p))}for(let p of c)p(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((f,p)=>{let m={args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,clientId:this.clientId,identity:l,precondition:u,onCommit:a(y=>{for(let S of c)S(y)},"onCommit"),reject:a(y=>{this.queuedIdentities.delete(n),Ze(y)||pe(o),p(y instanceof Error?y:new Error(String(y))),this.releaseIdleShard(r)},"reject"),resolve:f,shardKey:r};this.offlineQueue.enqueue(m),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),m.id!==void 0&&this.queuedIdentities.set(m.id,l)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=g(e);return this.offlineQueue.hasPending(r=>g(r.shardKey)===s)}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let s of e)this.queuedOfflineShardKeys.add(s),this.ensureSocket(s)}catch{}}hydrateAsOutboxLeader(){let e=a(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),s=globalThis.navigator?.locks;if(!s){e();return}s.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(r=>{if(this.closed){r();return}this.outboxLeaderRelease=r}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),s=new Map;for(let r of this.subscriptions.all())s.set(oe(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(xt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let n=s.get(r);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),se(e,s.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let s=this.cacheSeededQueries.get(e);s!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,s))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,s]of this.cacheSeededQueries){let r=this.subscriptions.get(e);r!==void 0&&(r.serverBase=void 0,r.serverCursor=void 0,r.serverEpoch=void 0,se(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=oe(e,s,r),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.hydratedQueryCache.get(s);r!==void 0&&this.cachedQueryMatchesIdentity(r)&&(this.hydratedQueryCache.delete(s),this.seedSubscriptionFromCache(e,r))}}persistQueryValue(e){let s=e.serverBase;if(!this.queryCache||s===void 0)return;let r=oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:s,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},Da))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(s=>s.wsState==="open")?"connected":e.some(s=>s.polling.isPolling())?"polling":e.some(s=>s.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let s=g(e),r;for(let i of this.subscriptions.all())g(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}async pollSubscriptions(e){let s=g(e),r=[];for(let c of this.subscriptions.all())g(c.shardKey)===s&&(ar(c.args)?r.push(c):J(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(r.length===0)return this.probeOrigin();let i=Vs(),n=this.identityFingerprint(),o;try{o=await cr(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(let[c,u]of r.entries()){let d=o[c];if(d!==void 0){if(!d.ok){J(u.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:R(d.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await cr(async s=>e(ie(this.url,Dt),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let n=[],o=[];if(!i)return{confirms:n,rollbacks:o};let c=Q.key(e,s,r),u=this.subscriptions.get(c);if(u){let d=At(u,i);d&&(n.push(d.confirm),o.push(d.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,s,r,i,n){let{confirms:o,rollbacks:c,store:u}=Ys(this.subscriptions,r);try{e(u,s)}catch{pe(c);return}i.push(...c),n.push(...o)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!D(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}let s=this.getConnection(e),r=s===void 0&&this.idleClosedShards.has(g(e));return{hasSocket:s?.socket!==void 0,idleClosed:r,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??r,wsState:s?.wsState??"idle"}}getOrCreateConnection(e){let s=g(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Va({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:a(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:a(()=>{this.emitConnectionStatus()},"onStateChange"),poll:a(async()=>this.pollSubscriptions(e),"poll")}),reconnect:_t(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}wsUrlFor(e,s){let r=[];if(e!==void 0&&r.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&r.push(`token=${encodeURIComponent(s)}`),r.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${r.join("&")}`}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[wi]=Ci(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(r.authorization=`Bearer ${n}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(r["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(r["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let o=this.bookmark.get();o&&(r["x-d1-bookmark"]=o)}return r}async rpc(e,s,r,i={}){if(!this.fetchImpl)throw new $("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,r),o=i.authToken===void 0?this.authToken:i.authToken,c=await this.fetchImpl(ie(this.url,Pi),{body:JSON.stringify({args:ne(s,`args for '${e}'`),functionPath:e,shardKey:r}),headers:n,method:"POST"});if(i.captureBookmark){let l=c.headers.get("x-d1-bookmark");l&&this.bookmark.set(l)}let u;try{u=await c.json()}catch{throw Te(c.status,c.statusText,c.headers.get("retry-after"))}let d=u;if(typeof d!="object"||d===null||Array.isArray(d))throw Te(c.status,c.statusText,c.headers.get("retry-after"));let h=me(u);if(h!==void 0)throw Mt(h,c.headers.get("retry-after"));if(!c.ok)throw Te(c.status,c.statusText,c.headers.get("retry-after"));i.onMutationAck?.(u.lastMutationId),i.onCommitCursor?.(u.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(c,r),this.recordShardCursor(r,u.commitCursor);try{return w(u.result)}catch(l){throw yr(l)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let o=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:o?(c=r,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(r),n["content-type"]="application/json");let u=await this.fetchImpl(ie(this.url,e),{body:c,headers:n,method:s}),d;try{d=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let h=me(d);if(h!==void 0){let l=new Error(h.message??"admin request failed");throw l.code=h.code,l}if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return d}effectiveConnectionContext(e){let s=this.connectionContextHolders.get(e);return s&&s.length>0?s[s.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let s=this.connections.get(e);s?.wsState==="open"&&this.sendConnectEnvelope(s)}sendConnectEnvelope(e){let s=this.effectiveConnectionContext(g(e.shardKey));D(e,{caps:go,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())g(s.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);if(!(s.wsState==="open"||s.wsState==="connecting")){if(s.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(s,e,this.wsToken).catch(()=>{});return}this.openSocket(s,e,this.wsToken)}}async openSocketWithProvidedToken(e,s,r){let i;try{i=await r()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,s,i)}openSocket(e,s,r){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),r===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,or(e,this.wsUrlFor(s,r),this.managedSocketOptions,{onClose:a(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:a(i=>{e.retired!==!0&&this.handleServerMessage(i.data,s)},"onMessage"),onOpen:a(()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Ua),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(s),this.clearResubscribeQueue(e);for(let n of this.subscriptions.all())g(n.shardKey)===g(s)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:o,type:c}of n)D(e,{id:o,type:c});this.releaseIdleShard(s)}$a(e);let i=this.whisperHandlers.get(g(s));if(i)for(let n of i.keys())D(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(s).catch(()=>{})},"onOpen")}))}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),D(r,{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(),Ee(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(g(n.shardKey)!==g(e.shardKey)||s.has(i))){if(n.durable){let o={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}markShardPendingAck(e){let s=g(e);for(let r of this.subscriptions.all())g(r.shardKey)===s&&(r.acked=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribePending.size<Ka;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribePending.set(s.id,setTimeout(()=>{this.releaseResubscribeSlot(e,s.id)},ja))}}releaseResubscribeSlot(e,s){let r=e.resubscribePending.get(s);r!==void 0&&(clearTimeout(r),e.resubscribePending.delete(s),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(let s of e.resubscribePending.values())clearTimeout(s);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.acked)return!1;let r=e.serverCursor!==void 0&&e.serverBase!==void 0;return D(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...r?{sinceSeq:e.serverCursor}:{},...r&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&D(s,{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,s){let r=Wa(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}if(i.type!=="error"&&this.getConnection(s)?.reconnect.reset(),typeof i.id=="string"){let n=this.getConnection(s);n&&this.releaseResubscribeSlot(n,i.id)}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:o,id:c,seq:u}=i,d=this.streams.get(c);d&&typeof u=="number"&&(d.lastSeq=u,typeof o=="number"&&(d.generation=o),d.durable=!0),d?.handle.push(w(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.pokeAssembler.part(s,i);break}case"pokeStart":{this.pokeAssembler.start(s,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(Zs(e)),this.forgetStream(s);return}let i=s===void 0?void 0:this.subscriptions.getById(s);if(i){let o=Pt(e),c=this.identityFingerprint(),u=Q.keyOf(i);J(i.errorCallbacks,o),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,o,c);return}let n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&J(n.errorCallbacks,Pt(e))}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){oo(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let n=this.shapeSubscriptions.get(i);n&&!r.undecodable.has(i)&&this.applyPokePart(n,r,e)}}}applyPokePart(e,s,r){let i=ao(e,s,r);if(ur(e),i==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i)return;let n;try{n=Bs(e,i.serverBase)}catch(o){J(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${o instanceof Error?o.message:String(o)}`});return}if(n===Et){this.resnapshotSubscription(i);return}if(this.dropCacheSeed(Q.keyOf(i)),br(i,n,{cursor:e.cursor,epoch:e.epoch}),e.lastMutationId!==void 0&&(Bt(i,e.lastMutationId),$t(i,!0)),this.persistQueryValue(i),Ve(i,i.serverCursor),s!==void 0&&Js(i,s),se(i,n),this.tabCoordinator?.isLeader()){let o=Q.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(o,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,e.cursor,e.epoch)}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s&&(this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&Bt(s,e.lastMutationId),$t(s),this.tabCoordinator?.isLeader())){let r=Q.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){e.acked=!0,(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),Ve(e,e.serverCursor)&&se(e,e.serverBase))}dispatchWhisper(e,s){let r=this.whisperHandlers.get(g(s))?.get(e.topic);if(!r)return;let i=w(e.data);for(let n of r)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.forgetStream(e);return}let r=this.subscriptions.getById(e);r&&(r.acked=!1,J(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(s=>{re(this.onPersistenceError,"remove",s,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);s^=n,s=Math.imul(s,16777619),r=Math.imul(r,33)+n}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let 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;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&Nt(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,s,r){if(!(this.closed||this.authToken!==e||r!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(s?.id??null,r);return}s!==null&&this.setAuthToken(e,s.id)}}adoptCookieSubject(e,s){return this.closed||this.authToken!==null||s<this.identityAnsweredAt?!1:(this.identityAnsweredAt=s,this.identitySettled=!0,this.setAuthToken(null,e),!0)}handleIdentityFrame(e,s){let r=this.getConnection(s)?.identityQuestion,{subject:i}=e;r===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,r)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,s){if(s!==void 0){this.authSubject=s,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){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return s===void 0?e.identity:s}warnRefreshWithoutSubject(e,s){e===null||s===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){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let n=s??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)o.set(c,u)}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(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,se(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,ur(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=g(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&Nt(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&(this.offlineFlushes.delete(s),this.releaseIdleShard(e))}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",l)}let i=g(e),n=this.offlineQueue.drain(h=>g(h.shardKey)===i);if(n.length===0)return;let o=[],c=[];for(let h of n){let l=this.replayGateVerdict(h);l==="send"?o.push(h):l==="hold"&&c.push(h)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}let u=this.encodableOrSettleTerminal(o);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let d=[];for(let h=0;h<u.length;h+=Lt){let l=u.slice(h,h+Lt),f=await this.replayBatched(l,e,s);if(d.push(...f.requeue),f.stop){d.push(...u.slice(h+Lt));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=g(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,Kt(i))})}noteReplayRetryDelay(e,s,r){let i=g(e),n=this.replayRetryState.get(i),o=(n?.attempts??0)+1,c=eo(s,o)??(r===null&&He(s)?Kt(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:c===void 0?n?.delayMs:Math.max(n?.delayMs??0,c)})}scheduleRateLimitedRetry(e){let s=g(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let n=this.replayRetryTimers.get(s);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{ne(r.args,`args for '${r.functionPath}'`),s.push(r)}catch(i){this.settleReplayTerminal(r,i instanceof Error?i:new Error(String(i)))}return s}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let s=this.identityFingerprint();return s===null&&this.identityUnresolved()?"unknown":e===s||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":s===null?"unknown":"mismatch"}replayGateVerdict(e){let s=this.stampOf(e);if(s===void 0)return this.queuedIdentities.delete(e.id??""),"send";let r=this.identityVerdict(s);if(r==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),r==="match")return"send";this.unpersist(e.id);let i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.resolve(s),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,s){let r=e.headers.get("x-lunora-shard-key");if(r===null||s!==void 0||this.defaultShardKey===r)return;this.defaultShardKey=r;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,s){if(typeof s!="number")return;let r=this.cursorKeyFor(e);this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,s))}shouldRequeueReplayFailure(e,s){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,s)||Ja(e)}noteReplayAuthRefusal(e,s){if(!He(e))return!1;let r=this.hashToken(s??"");return s===this.authToken&&this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,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;let s=this.replayCredentials.get(e);if(s===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:s.authToken,...Ut(s.stamp,s.authToken)},stamp:s.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(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,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let n=e[i];if(!n)continue;let o;try{let c=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:r,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...Ut(n.identity,r),mutationId:n.id,onCommitCursor:a(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(n,c,o)}catch(c){if(Ze(c)){this.settleReplayUndecodable(n,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)){this.settleReplayTerminal(n,c);continue}this.noteReplayRetryDelay(s,c,r),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,s,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let i=JSON.stringify({calls:e.map((d,h)=>({args:ne(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:h,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&so(i)>to)return await this.replayBatchedHalves(e,s,r);let n;try{n=await this.fetchImpl(ie(this.url,Dt),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...Ut(e.find(d=>d.identity!==void 0)?.identity,r)}),method:"POST"})}catch{return{requeue:e,stop:!0}}let o=n.headers.get("x-d1-bookmark");if(o&&this.bookmark.set(o),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let c,u=n.headers.get("retry-after");try{c=await n.json()}catch{return this.settleWholeBatchError(e,Te(n.status,n.statusText,u),s,r)}if(!c.results){let d=me(c),h=d===void 0?Te(n.status,n.statusText,u):Mt(d,u);return this.settleWholeBatchError(e,h,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof $||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:e,stop:!0};for(let n of e)this.settleReplayTerminal(n,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),s,r);if(n.stop)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};let o=await this.replayBatched(e.slice(i),s,r);return{requeue:[...n.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,s,r,i){let n=ro(s),o=[],c=!1,u=!1;for(let[d,h]of e.entries()){let l=io(n.get(d));switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(h,l.value,l.commitCursor);break}case"errored":{u||=He(l.error),this.shouldRequeueReplayFailure(l.error,i)?(this.noteReplayRetryDelay(r,l.error,i),o.push(h)):this.settleReplayTerminal(h,l.error);break}case"unanswered":{o.push(h);break}default:c=!0,this.settleReplayUndecodable(h,l.error,l.commitCursor)}}return c&&!u&&this.noteCredentialAccepted(i),o}};var gr=_(Xt(),1),vr=_(X(),1);var So=a(()=>{let t=(0,gr.c)(4),e=vt(),s,r,i;return t[0]!==e?(s=a(n=>e.onConnectionStatus(()=>{n()}),"o"),r=a(()=>e.connectionStatus(),"e"),i=a(()=>e.connectionStatus(),"s"),t[0]=e,t[1]=s,t[2]=r,t[3]=i):(s=t[1],r=t[2],i=t[3]),(0,vr.useSyncExternalStore)(s,r,i)},"S");export{Ht as a,Tr as b,ge as c,Qr as d,_r as e,jr as f,vt as g,So as h};
|
|
9
|
+
`)}return!1},"d");for(;;){let{done:u,value:d}=await s.read();if(u)break;if(o(r.decode(d,{stream:!0})),c()){await s.cancel().catch(()=>{});return}}o(r.decode()),c()||e.fail(new b("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),Ws=a((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new b("INTERNAL","httpStream: no `fetch` implementation available");let i=ci(t,e??{},s.baseUrl??""),n=new AbortController,o;s.signal&&(s.signal.aborted?n.abort():(o=a(()=>{n.abort()},"l"),s.signal.addEventListener("abort",o,{once:!0})));let c=a(()=>{o&&s.signal?.removeEventListener("abort",o)},"d"),{handle:u,iterable:d}=We({maxBuffer:s.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel")});return(async()=>{try{let h=await r(i,{headers:{accept:"text/event-stream",...s.headers},method:t.method,signal:n.signal});if(!h.ok){await h.body?.cancel().catch(()=>{}),u.fail(new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${h.status.toString()})`,{status:h.status}));return}if(!h.body){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await hi(h.body,u)}finally{c()}})().catch(h=>{if(n.signal.aborted){u.complete();return}if(h instanceof Error&&"code"in h){u.fail(h);return}u.fail(new b("HTTP_STREAM_TRANSPORT",h instanceof Error?h.message:String(h),{cause:h}))}),d},"_");var di=/["\\\u0000-\u001F\uD800-\uDFFF]/,zs=a(t=>di.test(t)?JSON.stringify(t):`"${t}"`,"y"),It=a(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return zs(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let o="[";for(let c=0;c<t.length;c++)c>0&&(o+=","),o+=It(t[c]);return o+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let o=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${o} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let s=t,r=Object.keys(s).sort(),i="{",n=!0;for(let o of r){let c=s[o];c!==void 0&&(n?n=!1:i+=",",i+=zs(o),i+=":",i+=It(c))}return i+"}"},"i"),te=a(t=>It(R(t)),"u");var Q=class t{static{a(this,"t")}static key(e,s,r){return`${e}::${te(s)}::${r??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){let s=t.keyOf(e);this.byKey.get(s)===e&&this.byKey.delete(s),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}};function ze(t){if(t!==void 0)return e=>{t(e)}}a(ze,"b");var J=a((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var Rt=0,Vs=a(()=>Rt,"h"),li=a((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),Gs=a((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),se=a((t,e)=>{Gs(t,li(e,t.optimisticLayers))},"y"),At=a((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),Gs(t,s);let n=a(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),o=a(()=>{se(t,t.serverBase)},"s");return{confirm:a(c=>{if(c===void 0){n();return}r.commitCursor=c,Rt+=1,r.acknowledgedAt=Rt,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&o()},"confirm"),rollback:a(()=>{i||(i=!0,n(),o())},"rollback")}},"g"),Ve=a((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let s=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(r=>r.commitCursor===void 0||r.commitCursor>e),t.optimisticLayers.length!==s},"k"),Js=a((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),pe=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),Ys=a((t,e)=>{let s=[],r=[],i=a((n,o)=>t.get(Q.key(n,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:a(n=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:a((n,o)=>i(n.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:a((n,o,c)=>{let u=i(n.__lunoraRef,o??{});if(!u)return;let d=At(u,()=>c);d&&(s.push(d.confirm),r.push(d.rollback))},"setQuery")}}},"_");var Ft=a(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let s=Date.parse(t);if(Number.isNaN(s))return;let r=s-Date.now();return r>0?r:void 0},"f"),fi=a((t,e)=>{let s=Ft(e);if(!(s===void 0||$e(t)!==void 0))return t.data===void 0?{retryAfterMs:s}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:s}:void 0},"v"),me=a(t=>{let e=t?.error;return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0},"l"),pi=a(()=>new $("LunoraClient: batch slot carried no error envelope"),"m"),Xs=a((t,e)=>{let s=t.error,r=typeof s?.code=="string"?s.code:void 0,i=typeof s?.message=="string"?s.message:void 0;return{code:r,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"s"),Zs=a(t=>{let{code:e,messageText:s}=Xs(t,"stream error");return e===void 0?new Error(s):new b(e,s)},"g"),Pt=a(t=>{let{code:e,messageText:s}=Xs(t,"subscription error");return{message:s,...e===void 0?{}:{code:e}}},"A"),Ge=a(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,t.data!==void 0)try{e.data=w(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"n"),Mt=a((t,e)=>{let s=Ge(t),r=fi(s,e);return r!==void 0&&(s.data=r),s},"y"),Je=a(t=>{let e=me(t);return e===void 0?pi():Ge(e)},"h");var er=0,mi=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();er+=1;let t=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${er.toString(36)}_${t}`},"d"),xt=a((t,e)=>t!==void 0&&e!==t,"f"),Xe=mi,re=a((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"o"),Ye=class{static{a(this,"l")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},s={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=s.persistence,this.onEvict=s.onEvict,this.onSizeChange=s.onSizeChange,this.version=s.version}get size(){return this.items.length}enqueue(e){let s=e;s.id??=Xe(),this.items.push(s),this.persistence?.append({args:s.args,...s.baselineSeq===void 0?{}:{baselineSeq:s.baselineSeq},clientId:s.clientId,functionPath:s.functionPath,id:s.id,identity:s.identity,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(r=>{re(this.onPersistenceError,"append",r,s.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw re(this.onPersistenceError,"load",o),o}let s=[],r=new Set(this.items.map(o=>o.id));for(let o of e)if(!r.has(o.id)){if(xt(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{re(this.onPersistenceError,"remove",c,o.id)});continue}r.add(o.id),s.push({args:o.args,baselineSeq:o.baselineSeq,clientId:o.clientId,functionPath:o.functionPath,id:o.id,identity:o.identity,reject:a(()=>{},"reject"),resolve:a(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let o of s)i.has(o)&&n.add(o.shardKey);return[...n]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;if(!this.persistence||i===void 0)continue;let n={args:r.args,...r.baselineSeq===void 0?{}:{baselineSeq:r.baselineSeq},clientId:r.clientId,functionPath:r.functionPath,id:i,identity:s,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(o=>{re(this.onPersistenceError,"replace",o,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.notifySize(),i}let s=[],r=[];for(let i of this.items)(e(i)?s:r).push(i);return this.items.length=0,this.items.push(...r),this.notifySize(),s}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],s=[];for(let r of this.items)if(r.precondition!==void 0&&!r.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",r.reject(i),e.push(r)}else s.push(r);return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of this.items){let s=new Error("CLIENT_CLOSED");s.code="CLIENT_CLOSED",e.reject(s)}this.items.length=0,this.notifySize()}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await r.replace(s)}catch(i){re(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(r=>{re(this.onPersistenceError,"remove",r,e.id)});let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var yi="lunora-outbox",bi="offline-mutations",Qt="by_id",gi=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??yi,r=t.storeName??bi,i=qe(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(Qt,"id",{unique:!0})}),n=Ke(i,r);return{append:a(async o=>{await n("readwrite",c=>x(c.add(o)))},"append"),clear:a(async()=>{await n("readwrite",o=>x(o.clear()))},"clear"),load:a(async()=>n("readonly",o=>x(o.getAll())),"load"),remove:a(async o=>{await n("readwrite",async c=>{let u=await x(c.index(Qt).getKey(o));u!==void 0&&await x(c.delete(u))})},"remove"),replace:a(async o=>{await n("readwrite",async c=>{let u=await x(c.index(Qt).getKey(o.id));u!==void 0&&await x(c.put(o,u))})},"replace")}},"w"),tr=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return gi()}},"b");var _t=a((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let o=Math.min(r,s*2**n);if(n+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){n=0}}},"s");var sr=a((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present?te(i.value):void 0;return()=>{let o=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!o.present?!0:te(o.value)===n}},"c");var Lt=500,hr=a((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Se");new TextDecoder;var vi=new TextEncoder,Si=a(t=>Ds(vi.encode(JSON.stringify(t))),"tt"),wi="x-lunora-expect-subject",Ci=a(t=>Si({subject:t}),"rt"),rr=Symbol.for("lunora:session-change"),ki="lunora:session-change",Ti="better-auth.message",Ei="signout",dr=a(()=>{let t=globalThis,e=t[rr];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[rr]=e),e},"Te"),Oi=a(()=>"document"in globalThis,"ot"),Ii=a(async()=>{let t=[];for(let e of dr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"ct"),Ri=a((t,e)=>{if(t!==Ti||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===Ei}catch{return!1}},"dt"),Ai=a(t=>{let e=[],s=a(()=>{Ii().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(ki):void 0}catch{r=void 0}if(r!==void 0){let n=r;n.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==t&&s()}),e.push(()=>{n.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let n=a(o=>{Ri(o.key,o.newValue)&&s()},"n");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"ut"),Fi=a(t=>{let e=dr();return e.listeners.add(t),e.detach===void 0&&Oi()&&(e.detach=Ai(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"ht"),Pi="/_lunora/rpc",Dt="/_lunora/rpc-batch",Mi="/_lunora/ws",xi="/_lunora/admin/shard-traffic",Qi="/_lunora/admin/scheduled",_i="/_lunora/admin/scheduled/status",Li="/_lunora/admin/scheduled/ws",Di="/_lunora/admin/scheduled/cancel",ir="/_lunora/admin/scheduled/dead",Ui="/_lunora/admin/scheduled/dead/retry",Ni="/_lunora/admin/scheduled/dead/cancel",qi="/_lunora/admin/workflows/instances",Ki="/_lunora/admin/workflows/instance",ji="/_lunora/admin/workflows/status",Wt="/_lunora/admin/storage",Bi="/_lunora/admin/storage/url",$i="/_lunora/admin/storage/buckets",Hi="/_lunora/admin/functions",Wi="/_lunora/admin/cron-jobs",zi="/_lunora/admin/cron-jobs/run",Vi="/_lunora/admin/architecture",Gi="/_lunora/admin/openapi",Ji="/_lunora/admin/openrpc",Yi="/_lunora/admin/global/tables",Xi="/_lunora/admin/global/table",Zi="/_lunora/admin/global/facet",en="/_lunora/admin/vector/indexes",tn="/_lunora/admin/vector/query",sn="/_lunora/admin/logs/archive",rn="/_lunora/admin/kv/namespaces",nn="/_lunora/admin/kv/keys",zt="/_lunora/admin/kv/value",an="/_lunora/admin/auth/users",on="/_lunora/admin/auth/sessions",cn="/_lunora/admin/auth/users/create",un="/_lunora/admin/auth/users/role",hn="/_lunora/admin/auth/users/ban",dn="/_lunora/admin/auth/users/unban",ln="/_lunora/admin/auth/users/password",fn="/_lunora/admin/auth/users/remove",pn="/_lunora/admin/auth/users/impersonate",mn="/_lunora/admin/auth/sessions/revoke",yn="/_lunora/admin/auth/sessions/revoke-all",bn="/_lunora/admin/auth/capabilities",gn="/_lunora/admin/auth/users/update",vn="/_lunora/admin/auth/accounts",Sn="/_lunora/admin/auth/accounts/unlink",wn="/_lunora/admin/auth/passkeys",Cn="/_lunora/admin/auth/passkeys/delete",kn="/_lunora/admin/auth/two-factor/disable",Tn="/_lunora/admin/auth/organizations",En="/_lunora/admin/auth/organizations/members",On="/_lunora/admin/auth/organizations/invitations",In="/_lunora/admin/auth/organizations/members/remove",Rn="/_lunora/admin/auth/organizations/invitations/cancel",An="/_lunora/admin/auth/config",Fn="/_lunora/admin/auth/sign-up-invitations",Pn="/_lunora/admin/auth/sign-up-invitations/create",Mn="/_lunora/admin/auth/sign-up-invitations/revoke",xn="/_lunora/admin/auth/organizations/create",Qn="/_lunora/admin/auth/organizations/update",_n="/_lunora/admin/auth/organizations/remove",Ln="/_lunora/admin/auth/organizations/members/add",Dn="/_lunora/admin/auth/organizations/members/invite",Un="/_lunora/admin/auth/organizations/members/role",Nn="/_lunora/admin/auth/organizations/teams",qn="/_lunora/admin/auth/organizations/teams/create",Kn="/_lunora/admin/auth/organizations/teams/update",jn="/_lunora/admin/auth/organizations/teams/remove",Bn="/_lunora/admin/auth/organizations/teams/members",$n="/_lunora/admin/auth/organizations/teams/members/add",Hn="/_lunora/admin/auth/organizations/teams/members/remove",Wn="/_lunora/admin/auth/organizations/roles",zn="/_lunora/admin/auth/organizations/roles/create",Vn="/_lunora/admin/auth/organizations/roles/update",Gn="/_lunora/admin/auth/organizations/roles/remove",Jn="/api/auth",Yn="/get-session",Xn="lunora-ping",Zn=a(async t=>(t.assertOpen(),(await t.adminFetch(Hi,"GET")).functions??[]),"Hs"),ea=a(async t=>(t.assertOpen(),(await t.adminFetch(Wi,"GET")).jobs??[]),"Ls"),ta=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(zi,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Ms"),sa=a(async t=>(t.assertOpen(),await t.adminFetch(Gi,"GET")),"Us"),ra=a(async t=>(t.assertOpen(),await t.adminFetch(Vi,"GET")),"Ns"),ia=a(async t=>(t.assertOpen(),await t.adminFetch(Ji,"GET")),"xs"),na=a(async t=>(t.assertOpen(),await t.adminFetch(Yi,"GET")),"Ds"),aa=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(R(e.filters))),w(await t.adminFetch(`${Xi}?${s.toString()}`,"GET"))},"Bs"),oa=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(R(e.filters))),w(await t.adminFetch(`${Zi}?${s.toString()}`,"GET"))},"Qs"),Vt=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"re"),nr=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"fe"),ie=a((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"k"),P=a((t,e)=>{let s=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&s.set(i,String(n));let r=s.toString();return r===""?t:`${t}?${r}`},"b"),ca=a(async t=>(t.assertOpen(),(await t.adminFetch(rn,"GET")).namespaces??[]),"Ks"),ua=a(async(t,e)=>{t.assertOpen();let s=P(nn,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"qs"),ha=a(async(t,e)=>{t.assertOpen();let s=P(zt,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Ws"),da=a(async(t,e)=>{t.assertOpen(),await t.adminFetch(zt,"PUT",e)},"js"),la=a(async(t,e)=>{t.assertOpen();let s=P(zt,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"$s"),fa=a(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(xi,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"Gs"),pa=a(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(sn,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"Vs"),ma=a(async t=>{let e=[],s;for(;;){let r=await t(s);if(e.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return e;if(r.cursor===s)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");s=r.cursor}},"zs"),Gt=a(t=>"args"in t?{...t,args:w(t.args)}:t,"ie"),ya=a(async t=>(t.assertOpen(),((await t.adminFetch(Qi,"GET")).records??[]).map(e=>Gt(e))),"Js"),ba=a(async t=>{t.assertOpen();let e=await t.adminFetch(_i,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"Ys"),ga=a(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(Di,"POST",{id:e})).cancelled===!0}),"Xs"),va=a(async t=>(t.assertOpen(),(await ma(async e=>await t.adminFetch(e===void 0?ir:`${ir}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>Gt(e))),"Zs"),Sa=a(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(Ui,"POST",{id:e})).retried===!0}),"er"),wa=a(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(Ni,"POST",{id:e})).removed===!0}),"tr"),Ca=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({name:e.name});e.status!==void 0&&s.set("status",e.status),e.page!==void 0&&s.set("page",String(e.page)),e.perPage!==void 0&&s.set("perPage",String(e.perPage));let r=await t.adminFetch(`${qi}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"sr"),ka=a(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${Ki}?${s.toString()}`,"GET");return{createdOn:r.createdOn,endedOn:r.endedOn,error:r.error,id:r.id??e.id,output:r.output,params:r.params,startedOn:r.startedOn,status:r.status??"unknown",steps:r.steps??[]}},"rr"),Ta=a(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(ji,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"ir"),Ea=a(async(t,e={})=>{t.assertOpen();let s=P(Wt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await t.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}},"nr"),Oa=a(async(t,e,s)=>{t.assertOpen();let r=`${Wt}?key=${encodeURIComponent(e)}${Vt(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"ar"),Ia=a(async t=>(t.assertOpen(),(await t.adminFetch($i,"GET")).buckets??[]),"or"),Ra=a(async(t,e)=>{t.assertOpen();let s=`${Wt}?key=${encodeURIComponent(e.key)}${Vt(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"cr"),Aa=a(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${Bi}?key=${encodeURIComponent(e)}${i}${Vt(s?.bucket)}`,o=await t.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},"dr"),Fa=a(async t=>(t.assertOpen(),(await t.adminFetch(en,"GET")).indexes??[]),"ur"),Pa=a(async(t,e)=>(t.assertOpen(),(await t.adminFetch(tn,"POST",e)).matches??[]),"hr"),ne=a((t,e)=>{try{return R(t)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${r}`,s instanceof Error?{cause:s}:void 0)}},"w"),ar=a(t=>{try{return R(t),!0}catch{return!1}},"pe"),lr=a(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"ge"),Ma=a((t,e)=>{let s=Array.from({length:e});for(let r of t){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;if(!lr(r.body)){s[r.id]={error:Je({}),ok:!1};continue}let i=r.body;s[r.id]="error"in i?{error:Je(i),ok:!1}:{ok:!0,value:w(i.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"lr"),Ut=a((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"G"),xa=3e4,Qa=1e4,_a=5e3,La=3,Da=250,Ua=5e3,Na=5e3,qa=64,Ka=3,ja=1e4,Ba=8,Nt=a(t=>t==="connected"||t==="polling","V"),g=a(t=>t??"","l"),D=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"T"),$a=a(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)D(t,s)},"wr"),Ha=new TextDecoder,Wa=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return Ha.decode(t)},"Ar"),ae=class{static{a(this,"_")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[s]=e;for(let r of this.listeners)try{r(s)}catch{}}clear(){this.listeners.clear()}},Ee=a(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"F"),za=a((t,e,s)=>{Ee(t),!(e<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;let{socket:r}=t;if(Date.now()-t.lastFrameAt>e*2.5){try{r.close()}catch{}s();return}try{r.send(Xn)}catch{}},e))},"_r"),or=a((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:n,heartbeatIntervalMs:o}=s;if(i===void 0)throw new b("INTERNAL","no WebSocket implementation available");let c=new i(e);t.socket=c;let u=a(()=>{Ee(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),d=a(h=>{u(),r.onClose(h)},"d");n>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}d()}},n)),c.addEventListener("open",()=>{if(t.socket===c){t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now();try{r.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}za(t,o,d)}}),c.addEventListener("message",h=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(h)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),c.addEventListener("close",h=>{t.socket===c&&d(h)}),c.addEventListener("error",()=>{t.socket===c&&d()})},"me"),Va=a(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:n}=t,o=s>0&&e>0,c=0,u,d=!1,h=!1,l=a(()=>{u!==void 0&&(clearInterval(u),u=void 0,d=!1,i())},"h"),f=a(m=>{if(u!==void 0){if(!m){l();return}d||(d=!0,i()),r()}},"p"),p=a(()=>{h||(h=!0,n().then(f).finally(()=>{h=!1}).catch(()=>{}))},"m");return{isPolling:a(()=>u!==void 0&&d,"isPolling"),noteFailedOpen:a(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(p,s),i(),p())},"noteFailedOpen"),noteOpen:a(()=>{c=0,l()},"noteOpen"),stop:l}},"Ir"),Ga=1e4,cr=a(async t=>{let e=new AbortController,s,r=new Promise((i,n)=>{s=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},Ga)});try{return await Promise.race([t(e.signal),r])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(s)}},"ye"),fr=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Ja=a(t=>{if(t instanceof $)return!0;let e=t?.code;return e===void 0||fr.has(e)||Ot.has(e)},"Rr"),pr=6e4,Ya=1e3,Xa={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Te=a((t,e,s)=>{let r=Ft(s),i=r===void 0?void 0:{retryAfterMs:r},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new $(n,i):new b(Xa[t]??"BAD_REQUEST",n,{data:i})},"P"),Kt=a((t,e=Math.random)=>{let s=Math.min(Ya*2**Math.max(t-1,0),pr);return Math.round(s*(.5+e()*.5))},"X"),Za=a(t=>t instanceof $||fr.has(t?.code??""),"Hr"),eo=a((t,e,s)=>{let r=$e(t);return r!==void 0&&r>0?Math.min(r,pr):Za(t)?Kt(e,s):void 0},"Lr"),to=983040,so=a(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Ur"),mr=new WeakSet,yr=a(t=>{let e=new b("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) \u2014 ${t instanceof Error?t.message:String(t)}`,{cause:t});return mr.add(e),e},"we"),Ze=a(t=>t instanceof Error&&mr.has(t),"N"),ro=a(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&lr(s.body)&&e.set(s.id,s.body);return e},"Nr"),io=a(t=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:Je(t),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:w(t.result)}}catch(e){return{commitCursor:t.commitCursor,error:yr(e),kind:"undecodable"}}},"xr"),qt=a((t,e)=>`${g(t)}\0${e}`,"z"),no=a((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"Dr"),jt=class{static{a(this,"Br")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){hr(this.buffers,this.maxBuffers),this.buffers.set(qt(e,s.pokeId),{baseCheckpoint:s.baseCheckpoint,bases:new Map,epoch:s.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,s){let r=this.buffers.get(qt(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:w(c.value)})}catch(c){r.undecodable.set(s.shapeId,c);return}let n=r.parts.get(s.shapeId)??[];for(let c of i)n.push(c);r.parts.set(s.shapeId,n),s.lastMutationId!==void 0&&r.lastMutationId.set(s.shapeId,s.lastMutationId);let o=s.baseCheckpoint??r.baseCheckpoint;o!==void 0&&r.bases.set(s.shapeId,o),s.reset===!0&&r.resets.add(s.shapeId)}end(e,s){let r=qt(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},ao=a((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),n=e.bases.get(t.id),o=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=n!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==n;if(!i&&(o||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,"reseed";i&&t.rows.clear(),no(t.rows,r),s.checkpoint!==void 0&&(t.serverCursor=s.checkpoint),s.epoch!==void 0&&(t.serverEpoch=s.epoch);let u=e.lastMutationId.get(t.id);return u!==void 0&&(t.lastMutationId=u),"applied"},"Qr"),ur=a(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"be"),oo=a((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&J(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"Kr"),Bt=a((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"Z"),$t=a((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"ee"),br=a((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Ee"),et=a((t,e)=>t!==void 0&&t!==e,"x"),co=a((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","qr"),uo=a(t=>{for(let e of t.activeSubscriptions())t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Wr"),ho=a(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1},"jr"),lo=a((t,e,s)=>{if(et(s,t.identityFingerprint()))return;let r=t.leader,i=co(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&t.flushOfflineQueues()},"$r"),fo=a(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Gr"),po=a((t,e,s,r,i,n)=>{if(et(n,t.identityFingerprint()))return;let o=t.subscription(e);o&&(t.dropCacheSeed(e),br(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&Ve(o,r),se(o,s))},"Vr"),mo=a((t,e,s,r)=>{if(et(r,t.identityFingerprint()))return;let i=t.subscription(e);i&&J(i.errorCallbacks,s)},"zr"),yo=a((t,e,s,r,i,n,o)=>{if(et(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&n===t.clientIdentifier()&&Bt(c,i),$t(c))},"Jr"),bo=a((t,e,s)=>t!==null||e&&s===null,"Yr"),go=[js],vo=Promise.resolve(),Ht=class t{static{a(this,"Ae")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:a((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:a(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new Q;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new ae;statusListeners=new ae;tokenExpiredListeners=new ae;identityChangeListeners=new ae;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new ae;pendingChangeListeners=new ae;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new jt(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??ie(nr(e.url),Mi),this.wsToken=e.wsToken;let s=e.authBasePath??Jn;this.authBasePath=s.endsWith("/")?s.slice(0,-1):s,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??qs(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??xa,this.connectTimeoutMs=e.connectTimeoutMs??Qa,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??_a,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??La,this.defaultConnectionContext=e.connectionContext,this.persistence=tr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Ns(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new je,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=vo),this.offlineQueue=new Ye(e.offlineQueue,{onEvict:a((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onSizeChange:a(r=>{this.pendingChangeListeners.emit(r)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${Xe()}`,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=Fi(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),u=this.authToken;this.authToken=e,this.applySubject(e,s);let d=this.identityFingerprint();d!==i&&(!r&&e!==null&&n?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&n&&!c?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(u,e),bo(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(d!==i||r||o)&&this.offlineQueue.size>0&&Nt(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){let s=this.identityVerdict(e);if(s!=="match")return{verdict:s};let r=Object.freeze({});return this.replayCredentials.set(r,{authToken:this.authToken,stamp:e}),{credential:r,verdict:s}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,s,r){let i=r?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new b("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=r?.shardKey??"",o=this.identityFingerprint(),c,u,d;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:a(h=>{c=h},"onMutationAck")})}catch(h){if(!Ze(h))throw h;d=h}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(n)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(hr(this.clientWatermarks,Ba),h=new Map,this.clientWatermarks.set(o??"",h)),h.set(n,c)}if(d!==void 0)throw d;return{applied:c===void 0||c===i,result:u}}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;let e={},s=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let r=this.sessionProbeGeneration;try{let i=await this.fetchImpl(ie(this.url,`${this.authBasePath}${Yn}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let n=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,n,r),n}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.bounceShardSockets())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=g(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r),e===void 0&&this.releaseIdleShard(s.shardKey)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=g(s.shardKey),i={context:e},n=this.connectionContextHolders.get(r);n?n.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let o=!1;return()=>{if(o)return;o=!0;let c=this.connectionContextHolders.get(r);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(r),this.refreshConnectionContext(r),this.releaseIdleShard(s.shardKey)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=g(r.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let o=n.get(e),c=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&D(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),d=u?.get(e);if(!d?.delete(s)||d.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let h=this.getConnection(r.shardKey);h&&D(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseIdleShard(r.shardKey)}}whisper(e,s,r={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey);i&&D(i,{data:ne(s??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"}),this.releaseIdleShard(r.shardKey)}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let n of r){let o=this.connections.get(n);e.push({confirmedMutationWatermark:s?.get(n)??0,hasSocket:o?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,o)=>(n.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((n,o)=>n.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){let s=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),s}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,s){this.clientQueryStore.set(e,s)}subscribeClientQuery(e,s){return this.clientQueryStore.subscribe(e,s)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,s,r){return sr(this,e,s,r)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,te(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=oe(e,s,r),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.cachedQueryMatchesIdentity(n)?n.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=Q.key(e,s,r),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,s,r={}){let{value:i}=await this.runMutation(e,s,r);return i}canQueueOffline(e){let{wasEverConnected:s}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(s||this.offlineQueue.queueBeforeFirstConnect)}async action(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),n=r.toArgs??(h=>({rows:h})),o=s.length,c=0,u=0,d=0;for(let h=0;h<o;h+=i){let l=s.slice(h,h+i),f=d,{committed:p}=await this.runMutation(e,n(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(f)}`},shardKey:r.shardKey});d+=1,c+=l.length,p&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:d,imported:u,queued:c-u}}async shardTraffic(e){return fa(this.adminHost,e)}async listScheduledJobs(){return ya(this.adminHost)}async schedulerStatus(){return ba(this.adminHost)}async cancelScheduledJob(e){return ga(this.adminHost,e)}async listDeadJobs(){return va(this.adminHost)}async retryDeadJob(e){return Sa(this.adminHost,e)}async removeDeadJob(e){return wa(this.adminHost,e)}async listWorkflowInstances(e){return Ca(this.adminHost,e)}async getWorkflowInstance(e){return ka(this.adminHost,e)}async setWorkflowInstanceStatus(e){return Ta(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=ie(nr(this.url),Li),r=_t(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,o=!1,c=a(()=>{o||this.closed||(n=setTimeout(h,r.next()))},"a"),u=a(f=>{if(o||this.WebSocketImpl===void 0)return;let p=f===void 0?s:`${s}?token=${encodeURIComponent(f)}`;or(i,p,this.managedSocketOptions,{onClose:a(()=>{c()},"onClose"),onMessage:a(m=>{let y;try{y=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}y.type==="jobs"&&Array.isArray(y.records)&&(r.reset(),e(y.records.map(S=>Gt(S))))},"onMessage")})},"c"),d=a(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"d"),h=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){d(f).catch(()=>{});return}u(f)},"u");h();let l=a(()=>{o=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),Ee(i),i.socket?.close(),i.socket=void 0},"h");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return Zn(this.adminHost)}async getCronJobs(){return ea(this.adminHost)}async runCronJob(e){return ta(this.adminHost,e)}async fetchOpenApi(){return sa(this.adminHost)}async fetchArchitecture(){return ra(this.adminHost)}async fetchOpenRpc(){return ia(this.adminHost)}async listStorageObjects(e={}){return Ea(this.adminHost,e)}async deleteStorageObject(e,s){return Oa(this.adminHost,e,s)}async listStorageBuckets(){return Ia(this.adminHost)}async uploadStorageObject(e){return Ra(this.adminHost,e)}async signedStorageUrl(e,s){return Aa(this.adminHost,e,s)}async listGlobalTables(){return na(this.adminHost)}async readGlobalTablePage(e){return aa(this.adminHost,e)}async facetGlobalColumn(e){return oa(this.adminHost,e)}async listVectorIndexes(){return Fa(this.adminHost)}async queryVectorIndex(e){return Pa(this.adminHost,e)}async queryLogArchive(e={}){return pa(this.adminHost,e)}async listKvNamespaces(){return ca(this.adminHost)}async listKvKeys(e){return ua(this.adminHost,e)}async getKvValue(e){return ha(this.adminHost,e)}async putKvValue(e){return da(this.adminHost,e)}async deleteKvKey(e){return la(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();let s=P(an,{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(s,"GET")}async createAuthUser(e){return this.assertOpen(),await this.adminFetch(cn,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(un,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(hn,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(dn,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(ln,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(fn,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(pn,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(mn,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(yn,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(bn,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(gn,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(P(vn,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(Sn,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(P(wn,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(Cn,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(kn,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(P(Tn,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();let s=P(En,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.assertOpen();let s=P(On,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();let s=P(Fn,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(Pn,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(Mn,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(In,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(Rn,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(An,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(xn,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(Qn,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(_n,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Ln,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Dn,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Un,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();let s=P(Nn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(qn,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Kn,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(jn,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();let s=P(Bn,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch($n,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(Hn,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();let s=P(Wn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(zn,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Vn,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Gn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=P(on,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){this.assertOpen();let n=s??{},o=Q.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),u=ze(r),d=ze(i.onError),h=ze(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=te(n),m=this.takeHydratedCache(e.__lunoraRef,p,i.shardKey);c={acked:!1,args:n,argsKey:p,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,wireArgs:ne(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(o,m)}if(c.callbacks.add(u),d&&c.errorCallbacks.add(d),h&&c.checkpointCallbacks.add(h),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),d&&l.errorCallbacks.delete(d),h&&l.checkpointCallbacks.delete(h),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(Q.keyOf(l)),this.subscriptions.remove(l),this.releaseIdleShard(l.shardKey))}}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:o}=r;return o!==void 0&&queueMicrotask(()=>{o({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:ne(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(n.shardKey)}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new b("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=r,o=s??{},{handle:c,iterable:u}=We({maxBuffer:r.maxBuffer,onCancel:a(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let d=this.getConnection(n),h={id:i,query:{args:ne(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:h,shardKey:n};this.streams.set(i,l);let f=d?.wsState==="open"&&D(d,h);if(!f&&d===void 0)return this.forgetStream(i),c.fail(new b("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=qa;){let p=d.pendingStreams.shift()?.id,m=p?this.streams.get(p):void 0;m&&(m.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(p))}d.pendingStreams.push(h)}return u}httpStream(e,s,r={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return Ws(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new b("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new b("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let s=e.leaderTabId;return s!==void 0&&s!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new b("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){let s=a(r=>g(r)===e,"t");return this.subscriptions.all().some(r=>s(r.shardKey))||[...this.shapeSubscriptions.values()].some(r=>s(r.shardKey))||[...this.streams.values()].some(r=>s(r.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(r=>s(r.shardKey))}releaseIdleShard(e){let s=g(e),r=this.connections.get(s);this.closed||s===""||r===void 0||(clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.idleTimer=void 0,!(this.closed||this.connections.get(s)!==r||this.shardInUse(s))&&(r.wasEverConnected&&this.idleClosedShards.add(s),this.teardownConnection(r),this.connections.delete(s),this.emitConnectionStatus())},Na))}forgetStream(e){let s=this.streams.get(e);this.streams.delete(e),s&&this.releaseIdleShard(s.shardKey)}teardownConnection(e){e.polling.stop();let s=g(e.shardKey);for(let[i,n]of this.streams)g(n.shardKey)===s&&(n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,Ee(e);let{socket:r}=e;if(r){e.socket=void 0;try{r.close()}catch{}}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,s={activeSubscriptions:a(()=>this.subscriptions.all(),"activeSubscriptions"),broadcastStatus:a((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:a(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:a(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:a(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:a(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:a(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:a(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:a(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:a(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:a(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:a(()=>this.clientId,"clientIdentifier"),dropCacheSeed:a(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:a((r,i,n)=>{this.ackAndAdvanceCursor(r,i,n)},"ackAndAdvanceCursor"),subscription:a(r=>this.subscriptions.get(r),"subscription")};return new Be({channelName:e,onBecomeLeader:a(()=>{uo(s)},"onBecomeLeader"),onStopBeingLeader:a(()=>{ho(s)},"onStopBeingLeader"),onConnectionStatus:a((r,i)=>{lo(s,r,i)},"onConnectionStatus"),onSubscriptionData:a((r,i,n,o,c)=>{po(s,r,i,n,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:a(()=>{fo(s)},"onLeaderClaimAnswered"),onSubscriptionError:a((r,i,n)=>{mo(s,r,i,n)},"onSubscriptionError"),onSubscriptionSettled:a((r,i,n,o,c,u)=>{yo(s,r,i,n,o,c,u)},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(ie(this.url,Dt),{body:JSON.stringify({calls:e.map((c,u)=>({args:ne(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let n;try{n=await r.json()}catch{throw new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let o=me(n);if(!r.ok||o!==void 0&&!n.results)throw o!==void 0?Ge(o):new b("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let c of n.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return Ma(n.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=s,n=r.mutationId??Xe(),o=this.takeReplayCredential(r.replayCredential),c=r.replayBaseline===void 0?this.baselineCursorFor(r.shardKey):r.replayBaseline??void 0,{confirms:u,rollbacks:d}=this.applyOptimisticUpdates(e.__lunoraRef,i,r.shardKey,r.optimistic);r.optimisticUpdate&&this.applyOptimisticUpdate(r.optimisticUpdate,s,r.shardKey,d,u);let h=this.offlineFlushes.get(g(r.shardKey));h!==void 0&&await h;let{hasSocket:l,idleClosed:f,polling:p,wasEverConnected:m,wsState:y}=this.connectionGateState(r.shardKey),{queueBeforeFirstConnect:S}=this.offlineQueue,C=m||S,T=this.WebSocketImpl!==void 0&&C,E=p||f,H=y==="connecting"&&C&&!E,W=y!=="open"&&!l&&T&&!E,ye=T&&r.replayBaseline===void 0&&this.hasPendingWriteAhead(r.shardKey),U=a(async()=>this.enqueueOfflineMutation(e,i,r.shardKey,c,n,d,u,r.precondition,r.mutationId,o?.stamp),"ne");if(W||H||ye)return U();let O;try{let N=await this.rpc(e.__lunoraRef,i,r.shardKey,{baselineSeq:c,captureBookmark:!0,...o?.flags,mutationId:n,onCommitCursor:a(Y=>{O=Y},"onCommitCursor")});for(let Y of u)Y(O);return{committed:!0,value:N}}catch(N){if(E&&T&&N instanceof TypeError&&ar(i))return U();throw this.settleFailedDirectWrite(N,O,u,d,o?.flags.authToken),N}}settleFailedDirectWrite(e,s,r,i,n){if(this.noteIdentityMismatch(e),n!==void 0&&this.noteReplayAuthRefusal(e,n),Ze(e)){for(let o of r)o(s);return}pe(i)}async enqueueOfflineMutation(e,s,r,i,n,o,c,u,d,h){let l=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;let f=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(f)}`,identity:l,mutationId:f,...o.length>0&&{onRejected:a(()=>{pe(o)},"onRejected")},shardKey:r})}catch(p){throw pe(o),p instanceof Error?p:new Error(String(p))}for(let p of c)p(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((f,p)=>{let m={args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,clientId:this.clientId,identity:l,precondition:u,onCommit:a(y=>{for(let S of c)S(y)},"onCommit"),reject:a(y=>{this.queuedIdentities.delete(n),Ze(y)||pe(o),p(y instanceof Error?y:new Error(String(y))),this.releaseIdleShard(r)},"reject"),resolve:f,shardKey:r};this.offlineQueue.enqueue(m),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),m.id!==void 0&&this.queuedIdentities.set(m.id,l)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=g(e);return this.offlineQueue.hasPending(r=>g(r.shardKey)===s)}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let s of e)this.queuedOfflineShardKeys.add(s),this.ensureSocket(s)}catch{}}hydrateAsOutboxLeader(){let e=a(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),s=globalThis.navigator?.locks;if(!s){e();return}s.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(r=>{if(this.closed){r();return}this.outboxLeaderRelease=r}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),s=new Map;for(let r of this.subscriptions.all())s.set(oe(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(xt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let n=s.get(r);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),se(e,s.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let s=this.cacheSeededQueries.get(e);s!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,s))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,s]of this.cacheSeededQueries){let r=this.subscriptions.get(e);r!==void 0&&(r.serverBase=void 0,r.serverCursor=void 0,r.serverEpoch=void 0,se(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=oe(e,s,r),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.hydratedQueryCache.get(s);r!==void 0&&this.cachedQueryMatchesIdentity(r)&&(this.hydratedQueryCache.delete(s),this.seedSubscriptionFromCache(e,r))}}persistQueryValue(e){let s=e.serverBase;if(!this.queryCache||s===void 0)return;let r=oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:s,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},Da))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(s=>s.wsState==="open")?"connected":e.some(s=>s.polling.isPolling())?"polling":e.some(s=>s.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let s=g(e),r;for(let i of this.subscriptions.all())g(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}async pollSubscriptions(e){let s=g(e),r=[];for(let c of this.subscriptions.all())g(c.shardKey)===s&&(ar(c.args)?r.push(c):J(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(r.length===0)return this.probeOrigin();let i=Vs(),n=this.identityFingerprint(),o;try{o=await cr(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(let[c,u]of r.entries()){let d=o[c];if(d!==void 0){if(!d.ok){J(u.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:R(d.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await cr(async s=>e(ie(this.url,Dt),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let n=[],o=[];if(!i)return{confirms:n,rollbacks:o};let c=Q.key(e,s,r),u=this.subscriptions.get(c);if(u){let d=At(u,i);d&&(n.push(d.confirm),o.push(d.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,s,r,i,n){let{confirms:o,rollbacks:c,store:u}=Ys(this.subscriptions,r);try{e(u,s)}catch{pe(c);return}i.push(...c),n.push(...o)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!D(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}let s=this.getConnection(e),r=s===void 0&&this.idleClosedShards.has(g(e));return{hasSocket:s?.socket!==void 0,idleClosed:r,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??r,wsState:s?.wsState??"idle"}}getOrCreateConnection(e){let s=g(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Va({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:a(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:a(()=>{this.emitConnectionStatus()},"onStateChange"),poll:a(async()=>this.pollSubscriptions(e),"poll")}),reconnect:_t(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}wsUrlFor(e,s){let r=[];if(e!==void 0&&r.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&r.push(`token=${encodeURIComponent(s)}`),r.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${r.join("&")}`}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[wi]=Ci(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(r.authorization=`Bearer ${n}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(r["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(r["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let o=this.bookmark.get();o&&(r["x-d1-bookmark"]=o)}return r}async rpc(e,s,r,i={}){if(!this.fetchImpl)throw new $("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,r),o=i.authToken===void 0?this.authToken:i.authToken,c=await this.fetchImpl(ie(this.url,Pi),{body:JSON.stringify({args:ne(s,`args for '${e}'`),functionPath:e,shardKey:r}),headers:n,method:"POST"});if(i.captureBookmark){let l=c.headers.get("x-d1-bookmark");l&&this.bookmark.set(l)}let u;try{u=await c.json()}catch{throw Te(c.status,c.statusText,c.headers.get("retry-after"))}let d=u;if(typeof d!="object"||d===null||Array.isArray(d))throw Te(c.status,c.statusText,c.headers.get("retry-after"));let h=me(u);if(h!==void 0)throw Mt(h,c.headers.get("retry-after"));if(!c.ok)throw Te(c.status,c.statusText,c.headers.get("retry-after"));i.onMutationAck?.(u.lastMutationId),i.onCommitCursor?.(u.commitCursor),this.noteCredentialAccepted(o),this.learnDefaultShardKey(c,r),this.recordShardCursor(r,u.commitCursor);try{return w(u.result)}catch(l){throw yr(l)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let o=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:o?(c=r,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(r),n["content-type"]="application/json");let u=await this.fetchImpl(ie(this.url,e),{body:c,headers:n,method:s}),d;try{d=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let h=me(d);if(h!==void 0){let l=new Error(h.message??"admin request failed");throw l.code=h.code,l}if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return d}effectiveConnectionContext(e){let s=this.connectionContextHolders.get(e);return s&&s.length>0?s[s.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let s=this.connections.get(e);s?.wsState==="open"&&this.sendConnectEnvelope(s)}sendConnectEnvelope(e){let s=this.effectiveConnectionContext(g(e.shardKey));D(e,{caps:go,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())g(s.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);if(!(s.wsState==="open"||s.wsState==="connecting")){if(s.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(s,e,this.wsToken).catch(()=>{});return}this.openSocket(s,e,this.wsToken)}}async openSocketWithProvidedToken(e,s,r){let i;try{i=await r()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,s,i)}openSocket(e,s,r){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),r===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,or(e,this.wsUrlFor(s,r),this.managedSocketOptions,{onClose:a(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:a(i=>{e.retired!==!0&&this.handleServerMessage(i.data,s)},"onMessage"),onOpen:a(()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Ua),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(s),this.clearResubscribeQueue(e);for(let n of this.subscriptions.all())g(n.shardKey)===g(s)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:o,type:c}of n)D(e,{id:o,type:c});this.releaseIdleShard(s)}$a(e);let i=this.whisperHandlers.get(g(s));if(i)for(let n of i.keys())D(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(s).catch(()=>{})},"onOpen")}))}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),D(r,{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(),Ee(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(g(n.shardKey)!==g(e.shardKey)||s.has(i))){if(n.durable){let o={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}n.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}markShardPendingAck(e){let s=g(e);for(let r of this.subscriptions.all())g(r.shardKey)===s&&(r.acked=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribePending.size<Ka;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribePending.set(s.id,setTimeout(()=>{this.releaseResubscribeSlot(e,s.id)},ja))}}releaseResubscribeSlot(e,s){let r=e.resubscribePending.get(s);r!==void 0&&(clearTimeout(r),e.resubscribePending.delete(s),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(let s of e.resubscribePending.values())clearTimeout(s);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.acked)return!1;let r=e.serverCursor!==void 0&&e.serverBase!==void 0;return D(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...r?{sinceSeq:e.serverCursor}:{},...r&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&D(s,{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,s){let r=Wa(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}if(i.type!=="error"&&this.getConnection(s)?.reconnect.reset(),typeof i.id=="string"){let n=this.getConnection(s);n&&this.releaseResubscribeSlot(n,i.id)}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:o,id:c,seq:u}=i,d=this.streams.get(c);d&&typeof u=="number"&&(d.lastSeq=u,typeof o=="number"&&(d.generation=o),d.durable=!0),d?.handle.push(w(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.pokeAssembler.part(s,i);break}case"pokeStart":{this.pokeAssembler.start(s,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(Zs(e)),this.forgetStream(s);return}let i=s===void 0?void 0:this.subscriptions.getById(s);if(i){let o=Pt(e),c=this.identityFingerprint(),u=Q.keyOf(i);J(i.errorCallbacks,o),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,o,c);return}let n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&J(n.errorCallbacks,Pt(e))}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){oo(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let n=this.shapeSubscriptions.get(i);n&&!r.undecodable.has(i)&&this.applyPokePart(n,r,e)}}}applyPokePart(e,s,r){let i=ao(e,s,r);if(ur(e),i==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i)return;let n;try{n=Bs(e,i.serverBase)}catch(o){J(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${o instanceof Error?o.message:String(o)}`});return}if(n===Et){this.resnapshotSubscription(i);return}if(this.dropCacheSeed(Q.keyOf(i)),br(i,n,{cursor:e.cursor,epoch:e.epoch}),e.lastMutationId!==void 0&&(Bt(i,e.lastMutationId),$t(i,!0)),this.persistQueryValue(i),Ve(i,i.serverCursor),s!==void 0&&Js(i,s),se(i,n),this.tabCoordinator?.isLeader()){let o=Q.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(o,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,e.cursor,e.epoch)}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s&&(this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&Bt(s,e.lastMutationId),$t(s),this.tabCoordinator?.isLeader())){let r=Q.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){e.acked=!0,(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),Ve(e,e.serverCursor)&&se(e,e.serverBase))}dispatchWhisper(e,s){let r=this.whisperHandlers.get(g(s))?.get(e.topic);if(!r)return;let i=w(e.data);for(let n of r)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.forgetStream(e);return}let r=this.subscriptions.getById(e);r&&(r.acked=!1,J(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(s=>{re(this.onPersistenceError,"remove",s,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);s^=n,s=Math.imul(s,16777619),r=Math.imul(r,33)+n}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let 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;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&Nt(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,s,r){if(!(this.closed||this.authToken!==e||r!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(s?.id??null,r);return}s!==null&&this.setAuthToken(e,s.id)}}adoptCookieSubject(e,s){return this.closed||this.authToken!==null||s<this.identityAnsweredAt?!1:(this.identityAnsweredAt=s,this.identitySettled=!0,this.setAuthToken(null,e),!0)}handleIdentityFrame(e,s){let r=this.getConnection(s)?.identityQuestion,{subject:i}=e;r===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,r)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,s){if(s!==void 0){this.authSubject=s,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){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return s===void 0?e.identity:s}warnRefreshWithoutSubject(e,s){e===null||s===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){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let n=s??"",o=this.clientWatermarks.get(n);if(o===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)o.set(c,u)}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(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,se(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,ur(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=g(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&Nt(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&(this.offlineFlushes.delete(s),this.releaseIdleShard(e))}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",l)}let i=g(e),n=this.offlineQueue.drain(h=>g(h.shardKey)===i);if(n.length===0)return;let o=[],c=[];for(let h of n){let l=this.replayGateVerdict(h);l==="send"?o.push(h):l==="hold"&&c.push(h)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}let u=this.encodableOrSettleTerminal(o);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let d=[];for(let h=0;h<u.length;h+=Lt){let l=u.slice(h,h+Lt),f=await this.replayBatched(l,e,s);if(d.push(...f.requeue),f.stop){d.push(...u.slice(h+Lt));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=g(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,Kt(i))})}noteReplayRetryDelay(e,s,r){let i=g(e),n=this.replayRetryState.get(i),o=(n?.attempts??0)+1,c=eo(s,o)??(r===null&&He(s)?Kt(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:c===void 0?n?.delayMs:Math.max(n?.delayMs??0,c)})}scheduleRateLimitedRetry(e){let s=g(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let n=this.replayRetryTimers.get(s);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{ne(r.args,`args for '${r.functionPath}'`),s.push(r)}catch(i){this.settleReplayTerminal(r,i instanceof Error?i:new Error(String(i)))}return s}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let s=this.identityFingerprint();return s===null&&this.identityUnresolved()?"unknown":e===s||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":s===null?"unknown":"mismatch"}replayGateVerdict(e){let s=this.stampOf(e);if(s===void 0)return this.queuedIdentities.delete(e.id??""),"send";let r=this.identityVerdict(s);if(r==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),r==="match")return"send";this.unpersist(e.id);let i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.resolve(s),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,s){let r=e.headers.get("x-lunora-shard-key");if(r===null||s!==void 0||this.defaultShardKey===r)return;this.defaultShardKey=r;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,s){if(typeof s!="number")return;let r=this.cursorKeyFor(e);this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,s))}shouldRequeueReplayFailure(e,s){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,s)||Ja(e)}noteReplayAuthRefusal(e,s){if(!He(e))return!1;let r=this.hashToken(s??"");return s===this.authToken&&this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,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;let s=this.replayCredentials.get(e);if(s===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:s.authToken,...Ut(s.stamp,s.authToken)},stamp:s.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(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,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let n=e[i];if(!n)continue;let o;try{let c=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:r,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...Ut(n.identity,r),mutationId:n.id,onCommitCursor:a(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(n,c,o)}catch(c){if(Ze(c)){this.settleReplayUndecodable(n,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)){this.settleReplayTerminal(n,c);continue}this.noteReplayRetryDelay(s,c,r),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,s,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let i=JSON.stringify({calls:e.map((d,h)=>({args:ne(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:h,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&so(i)>to)return await this.replayBatchedHalves(e,s,r);let n;try{n=await this.fetchImpl(ie(this.url,Dt),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...Ut(e.find(d=>d.identity!==void 0)?.identity,r)}),method:"POST"})}catch{return{requeue:e,stop:!0}}let o=n.headers.get("x-d1-bookmark");if(o&&this.bookmark.set(o),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let c,u=n.headers.get("retry-after");try{c=await n.json()}catch{return this.settleWholeBatchError(e,Te(n.status,n.statusText,u),s,r)}if(!c.results){let d=me(c),h=d===void 0?Te(n.status,n.statusText,u):Mt(d,u);return this.settleWholeBatchError(e,h,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof $||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:e,stop:!0};for(let n of e)this.settleReplayTerminal(n,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),s,r);if(n.stop)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};let o=await this.replayBatched(e.slice(i),s,r);return{requeue:[...n.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,s,r,i){let n=ro(s),o=[],c=!1,u=!1;for(let[d,h]of e.entries()){let l=io(n.get(d));switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(h,l.value,l.commitCursor);break}case"errored":{u||=He(l.error),this.shouldRequeueReplayFailure(l.error,i)?(this.noteReplayRetryDelay(r,l.error,i),o.push(h)):this.settleReplayTerminal(h,l.error);break}case"unanswered":{o.push(h);break}default:c=!0,this.settleReplayUndecodable(h,l.error,l.commitCursor)}}return c&&!u&&this.noteCredentialAccepted(i),o}};var gr=_(Xt(),1),vr=_(X(),1);var So=a(()=>{let t=(0,gr.c)(4),e=vt(),s,r,i;return t[0]!==e?(s=a(n=>e.onConnectionStatus(()=>{n()}),"o"),r=a(()=>e.connectionStatus(),"e"),i=a(()=>e.connectionStatus(),"s"),t[0]=e,t[1]=s,t[2]=r,t[3]=i):(s=t[1],r=t[2],i=t[3]),(0,vr.useSyncExternalStore)(s,r,i)},"S");export{Ht as a,Tr as b,ge as c,Qr as d,_r as e,jr as f,vt as g,So as h};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as T}from"./chunk-NCPW7WHO.js";import{a as S}from"./chunk-
|
|
1
|
+
import{a as T}from"./chunk-NCPW7WHO.js";import{a as S}from"./chunk-U5HRF22B.js";import{b as q}from"./chunk-55UGUCQ6.js";import{b as I}from"./chunk-VEK3S7MV.js";import{d as A,h as E,j as H,k as O}from"./chunk-HJHSQPHW.js";import{a as j,d as C,f as U,g as _}from"./chunk-I26MS5PJ.js";var V=C(U(),1);var i=C(_(),1);var L=j(G=>{let e=(0,V.c)(38),{className:w,error:t,testId:N}=G,g=A(),r=q(),l,s,n,a,c,m,o,d;if(e[0]!==w||e[1]!==t||e[2]!==r||e[3]!==N){let y=H(t),b;e[12]!==t?(b=O(t),e[12]=t,e[13]=b):b=e[13],s=b;let x;e[14]!==t?(x=S(t),e[14]=t,e[15]=x):x=e[15];let k=x,v;e[16]!==r||e[17]!==k?(v=j(()=>{r?.openConsole({errorsOnly:!0,seq:k})},"x"),e[16]=r,e[17]=k,e[18]=v):v=e[18],n=v,l=T,a=w,c=N,m="destructive";let u;e[19]!==t?(u=E(t),e[19]=t,e[20]=u):u=e[20],e[21]!==u?(o=(0,i.jsx)("p",{className:"font-medium",children:u}),e[21]=u,e[22]=o):o=e[22],d=y===void 0?null:(0,i.jsx)("p",{className:"mt-1 whitespace-pre-wrap text-xs opacity-90",children:I(y)}),e[0]=w,e[1]=t,e[2]=r,e[3]=N,e[4]=l,e[5]=s,e[6]=n,e[7]=a,e[8]=c,e[9]=m,e[10]=o,e[11]=d}else l=e[4],s=e[5],n=e[6],a=e[7],c=e[8],m=e[9],o=e[10],d=e[11];let p;e[23]!==s?(p=s===void 0?null:(0,i.jsx)("a",{"aria-label":"View documentation for this error",className:"mt-1 inline-block text-xs underline",href:s,rel:"noreferrer",target:"_blank",children:"View error docs"}),e[23]=s,e[24]=p):p=e[24];let f;e[25]!==r||e[26]!==n||e[27]!==g?(f=r===void 0?null:(0,i.jsx)("button",{className:"mt-1 block text-xs underline outline-none focus-visible:ring-1 focus-visible:ring-ring","data-testid":"error-show-in-console",onClick:n,type:"button",children:g("Show in console")}),e[25]=r,e[26]=n,e[27]=g,e[28]=f):f=e[28];let h;return e[29]!==l||e[30]!==a||e[31]!==c||e[32]!==m||e[33]!==o||e[34]!==d||e[35]!==p||e[36]!==f?(h=(0,i.jsxs)(l,{className:a,testId:c,variant:m,children:[o,d,p,f]}),e[29]=l,e[30]=a,e[31]=c,e[32]=m,e[33]=o,e[34]=d,e[35]=p,e[36]=f,e[37]=h):h=e[37],h},"G");export{L as a};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as me}from"./chunk-2I4NHEKA.js";import{a as $}from"./chunk-GCG65T2K.js";import{a as ue}from"./chunk-SV764LKQ.js";import"./chunk-AN4UDYUY.js";import"./chunk-AUGKHAMQ.js";import"./chunk-WJRYEML4.js";import{a as de}from"./chunk-ZKJS6EBE.js";import"./chunk-RGMVGZV4.js";import"./chunk-SJQERRSZ.js";import"./chunk-7Y3SY37W.js";import{b as P}from"./chunk-Q6ED4KUL.js";import"./chunk-BOMPSVRC.js";import"./chunk-55UGUCQ6.js";import{a as A}from"./chunk-4ZEL6BYL.js";import{c as ce}from"./chunk-J6H3YTFH.js";import{g as ne,h as oe}from"./chunk-DGJMFHBV.js";import"./chunk-QAQDMS6R.js";import"./chunk-VEK3S7MV.js";import{a as C}from"./chunk-2IKDEUCX.js";import{d as D,f as I,g as Q,h as W,p as _,t as ie}from"./chunk-HJHSQPHW.js";import{a as f,d as T,e as qe,f as ae,g as le,i as M}from"./chunk-I26MS5PJ.js";var Y=T(ae(),1);var h=T(qe(),1);var fe=T(ae(),1);var B=T(le(),1);var Me={connected:"bg-success",connecting:"bg-warning",idle:"bg-muted-foreground",offline:"bg-destructive",polling:"bg-warning"},he=f(()=>{let t=(0,fe.c)(18),e=D(),a=oe(),s;e:switch(a){case"connected":{let n;t[0]!==e?(n=e("Connected"),t[0]=e,t[1]=n):n=t[1],s=n;break e}case"connecting":{let n;t[2]!==e?(n=e("Connecting\u2026"),t[2]=e,t[3]=n):n=t[3],s=n;break e}case"idle":{let n;t[4]!==e?(n=e("Idle"),t[4]=e,t[5]=n):n=t[5],s=n;break e}case"offline":{let n;t[6]!==e?(n=e("Offline"),t[6]=e,t[7]=n):n=t[7],s=n;break e}case"polling":{let n;t[8]!==e?(n=e("Polling"),t[8]=e,t[9]=n):n=t[9],s=n;break e}default:s=a}let l=Me[a],c;t[10]!==l?(c=M("size-2 rounded-full",l),t[10]=l,t[11]=c):c=t[11];let i;t[12]!==c?(i=(0,B.jsx)("span",{"aria-hidden":"true",className:c}),t[12]=c,t[13]=i):i=t[13];let o;return t[14]!==a||t[15]!==i||t[16]!==s?(o=(0,B.jsxs)("span",{"aria-live":"polite",className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground","data-status":a,"data-testid":"dash-connection",role:"status",children:[i,s]}),t[14]=a,t[15]=i,t[16]=s,t[17]=o):o=t[17],o},"T");var r=T(le(),1);var Ae={crit:"destructive",ok:"secondary",warn:"default"},U=f((t,e)=>e===0?"\u2014":`${(t/e*100).toFixed(1)}%`,"P"),X=f((t,e,a)=>Number.isNaN(t)?"ok":t>=a?"crit":t>=e?"warn":"ok","z"),xe=.01,ve=.05,je=f(t=>{let e=(0,Y.c)(36),{errorCount:a,logsError:s,topErrors:l,worstFunctions:c}=t,i=D(),o;e[0]!==i?(o=i("Functions by error rate"),e[0]=i,e[1]=o):o=e[1];let n;e[2]!==o?(n=(0,r.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:o})}),e[2]=o,e[3]=n):n=e[3];let m;e[4]!==i||e[5]!==c?(m=c.length===0?(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-functions-empty",children:i("No function activity yet.")}):(0,r.jsx)("ul",{className:"divide-y divide-border",children:c.map(w=>(0,r.jsxs)("li",{className:"flex flex-wrap items-center justify-between gap-2 px-4 py-2 text-xs","data-testid":"hl-fn-row",children:[(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:w.path}),(0,r.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,r.jsx)("span",{className:"tabular-nums text-muted-foreground",children:i("{count} calls",{count:w.calls.toString()})}),(0,r.jsx)(P,{variant:Ae[X(w.errors/w.calls,xe,ve)],children:U(w.errors,w.calls)})]})]},w.path))}),e[4]=i,e[5]=c,e[6]=m):m=e[6];let p;e[7]!==n||e[8]!==m?(p=(0,r.jsxs)(C,{className:"gap-0 py-0","data-testid":"hl-functions",children:[n,m]}),e[7]=n,e[8]=m,e[9]=p):p=e[9];let v;e[10]!==i?(v=i("Recent errors"),e[10]=i,e[11]=v):v=e[11];let d;e[12]!==v?(d=(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:v}),e[12]=v,e[13]=d):d=e[13];let u=a>0?"destructive":"outline",g;e[14]!==a||e[15]!==u?(g=(0,r.jsx)(P,{"data-testid":"hl-error-count",variant:u,children:a}),e[14]=a,e[15]=u,e[16]=g):g=e[16];let x;e[17]!==d||e[18]!==g?(x=(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[d,g]}),e[17]=d,e[18]=g,e[19]=x):x=e[19];let S;e[20]!==s?(S=s!==null&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-destructive","data-testid":"hl-logs-error",role:"alert",children:s}),e[20]=s,e[21]=S):S=e[21];let E;e[22]!==s||e[23]!==i||e[24]!==l.length?(E=s===null&&l.length===0&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-errors-empty",children:i("No recent errors.")}),e[22]=s,e[23]=i,e[24]=l.length,e[25]=E):E=e[25];let q;e[26]!==l?(q=l.length>0&&(0,r.jsx)("ul",{className:"divide-y divide-border",children:l.map(Ce)}),e[26]=l,e[27]=q):q=e[27];let N;e[28]!==S||e[29]!==E||e[30]!==q||e[31]!==x?(N=(0,r.jsxs)(C,{className:"gap-0 py-0",children:[x,S,E,q]}),e[28]=S,e[29]=E,e[30]=q,e[31]=x,e[32]=N):N=e[32];let k;return e[33]!==N||e[34]!==p?(k=(0,r.jsxs)("div",{className:"grid gap-3 lg:grid-cols-2",children:[p,N]}),e[33]=N,e[34]=p,e[35]=k):k=e[35],k},"ye");function Ce(t,e){return(0,r.jsxs)("li",{className:"flex flex-col gap-0.5 px-4 py-2 text-xs","data-testid":"hl-error-row",children:[(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)("time",{className:"shrink-0 text-muted-foreground",children:ie(t.timestamp)}),t.functionPath!==void 0&&(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:t.functionPath})]}),(0,r.jsx)("span",{className:"text-destructive",children:t.message})]},`${t.timestamp.toString()}-${e.toString()}`)}f(Ce,"Te");var pe={completed:0,failed:2,in_progress:1},Ie=f(t=>{let e=0,a=0,s=0,l=0,c=!1,i=[];for(let{metrics:o}of t){if(o===null){l+=1;continue}s+=1,e+=o.requests,a+=o.errors,i.push(...o.history??[]),c||=o.historyTruncated===!0}return{errors:a,failed:l,history:i,historyTruncated:c,reachable:s,requests:e}},"Ae"),Te=f(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.path);if(l===void 0){e.set(s.path,{...s});continue}l.calls+=s.calls,l.errors+=s.errors,l.totalDurationMs+=s.totalDurationMs,l.scans=(l.scans??0)+(s.scans??0),l.maxDurationMs=Math.max(l.maxDurationMs,s.maxDurationMs),l.lastCalledAt=Math.max(l.lastCalledAt,s.lastCalledAt),(s.lastErrorAt??0)>(l.lastErrorAt??0)&&(l.lastErrorAt=s.lastErrorAt,l.lastErrorMessage=s.lastErrorMessage)}return[...e.values()]},"ke"),De=f(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.id);if(l===void 0){e.set(s.id,s);continue}let c=pe[s.status]-pe[l.status];(c>0||c===0&&(s.updatedAt??0)>(l.updatedAt??0))&&e.set(s.id,s)}return[...e.values()]},"Re"),Pe=I(A.getAuthMetrics),Fe=I(A.getFunctionStats),Le=I(A.getLogs),Re=I(A.getMetrics),ze=I(A.migrationStatus),Oe=5,ge=2e3,Ke=5,_e=.1,$e=.3,Be=1,He=50,Ue=f((t,e,a)=>t>=a?"crit":t>=e?"warn":"ok","Pe"),Ge=f(t=>{let e=new Map;for(let s of t??[]){let l=e.get(s.bucketMs)??{calls:0,errors:0};l.calls+=s.calls,l.errors+=s.errors,e.set(s.bucketMs,l)}let a=[...e.entries()].toSorted((s,l)=>s[0]-l[0]);return{errors:a.map(([,s])=>s.errors),requests:a.map(([,s])=>s.calls)}},"Ge"),Ve=f(t=>{let e=0,a=0;for(let l of t)l.status==="failed"?e+=1:l.status==="in_progress"&&(a+=1);let s="ok";return e>0?s="crit":a>0&&(s="warn"),{failed:e,level:s,running:a}},"Ve"),Je=f((t,e)=>t.failed>0?e("{count} failed",{count:t.failed.toString()}):t.running>0?e("{count} running",{count:t.running.toString()}):e("OK"),"Be"),be={crit:"bg-destructive",ok:"bg-success",warn:"bg-warning"},Ne={crit:"text-destructive",ok:"text-foreground",warn:"text-warning"},Qe={crit:"bg-destructive/10 text-destructive",ok:"bg-success/10 text-success",warn:"bg-warning/10 text-warning"},We=f(t=>t.includes("crit")?"crit":t.includes("warn")?"warn":"ok","Ke"),H=f(t=>{let e=(0,Y.c)(19),{chart:a,label:s,level:l,testId:c,value:i}=t,o=be[l],n;e[0]!==o?(n=M("size-1.5 shrink-0 rounded-full",o),e[0]=o,e[1]=n):n=e[1];let m;e[2]!==n?(m=(0,r.jsx)("span",{"aria-hidden":"true",className:n}),e[2]=n,e[3]=m):m=e[3];let p;e[4]!==s||e[5]!==m?(p=(0,r.jsxs)("span",{className:"flex items-center gap-1.5 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:[m,s]}),e[4]=s,e[5]=m,e[6]=p):p=e[6];let v=Ne[l],d;e[7]!==v?(d=M("truncate text-2xl font-semibold tabular-nums",v),e[7]=v,e[8]=d):d=e[8];let u;e[9]!==d||e[10]!==c||e[11]!==i?(u=(0,r.jsx)("span",{className:d,"data-testid":c,children:i}),e[9]=d,e[10]=c,e[11]=i,e[12]=u):u=e[12];let g;e[13]!==a||e[14]!==u?(g=(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[u,a]}),e[13]=a,e[14]=u,e[15]=g):g=e[15];let x;return e[16]!==p||e[17]!==g?(x=(0,r.jsx)(C,{className:"gap-0 py-0",children:(0,r.jsxs)("div",{className:"flex flex-col gap-2.5 p-4",children:[p,g]})}),e[16]=p,e[17]=g,e[18]=x):x=e[18],x},"U"),Xe=f(async(t,e,a)=>{let s=await Promise.all(a.map(d=>{let u=Q(d);return Promise.allSettled([t.query(Re,{},u),t.query(Fe,{},u),t.query(ze,{},u)])})),l=Q(e),c=typeof t.schedulerStatus=="function"?t.schedulerStatus():Promise.reject(new Error("scheduler status unavailable")),[i,o,n]=await Promise.allSettled([t.query(Le,{},l),t.query(Pe,{},l),c]),m=s.map(([d,u,g])=>({functions:u.status==="fulfilled"?u.value.functions:[],metrics:d.status==="fulfilled"?d.value:null,migrations:g.status==="fulfilled"?g.value.migrations:[]})),p=Ie(m),v=s[0]?.[0];return{auth:o.status==="fulfilled"?o.value:null,entries:i.status==="fulfilled"?i.value.entries:[],functions:Te(m.map(d=>d.functions)),logsError:i.status==="rejected"?W(i.reason):null,metricsError:p.reachable===0&&v?.status==="rejected"?W(v.reason):null,migrations:De(m.map(d=>d.migrations)),scheduler:n.status==="fulfilled"?n.value:null,totals:p}},"$e"),Ye=f(t=>{let e=t?.history??[];return{attempts:e.map(a=>a.attempts),failures:e.map(a=>a.failures)}},"ze"),xt=f(({initialShardKey:t})=>{let e=ne(),a=D(),[s,l]=(0,h.useState)([]),[c,i]=(0,h.useState)(null),[o,n]=(0,h.useState)(null),[m,p]=(0,h.useState)(null),[v,d]=(0,h.useState)([]),[u,g]=(0,h.useState)(null),[x,S]=(0,h.useState)(null),[E,q]=(0,h.useState)([]),[N]=(0,h.useState)(de),k=(0,h.useRef)(!1),w=(0,h.useRef)(0),G=(0,h.useRef)(0),j=(0,h.useRef)(null),F=t??"",L=(0,h.useCallback)(async()=>{if(k.current)return;k.current=!0;let b=w.current,y=await Xe(e,F,me(F,N));b===w.current&&(n(y.totals),p(y.metricsError),d(y.functions),q(y.migrations),l(y.entries),i(y.logsError),g(y.auth),S(y.scheduler),k.current=!1)},[e,N,F]);(0,h.useEffect)(()=>(_(L()),()=>{w.current+=1,k.current=!1,j.current!==null&&(clearTimeout(j.current),j.current=null)}),[L]);let ye=f(()=>{let b=Date.now()-G.current;if(b>=ge){G.current=Date.now(),_(L());return}j.current===null&&(j.current=setTimeout(()=>{j.current=null,G.current=Date.now(),_(L())},ge-b))},"ue"),{data:Z,liveError:we}=ce(A.getMetrics,{},{live:!0,shardKey:F});(0,h.useEffect)(()=>{Z!==void 0&&ye()},[Z]);let ee=s.filter(b=>b.level==="error"),ke=ee.slice(0,Oe),R=Ge(o?.history),te=Ye(u),Se=v.filter(b=>b.calls>0).toSorted((b,y)=>y.errors/y.calls-b.errors/b.calls||y.calls-b.calls).slice(0,Ke),V=Ve(E),Ee=o===null||o.requests===0?0:o.errors/o.requests,J=X(Ee,xe,ve),re=u===null?"ok":X(u.failureRate,_e,$e),se=x===null?"ok":Ue(x.backlog,Be,He),z=We([J,re,se,V.level]),O,K;return z==="crit"?(O=a("Critical"),K=a("One or more service levels are breached.")):z==="warn"?(O=a("Degraded"),K=a("Some service levels need attention.")):(O=a("All systems healthy"),K=a("All service levels are within target.")),(0,r.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-health",children:[(0,r.jsxs)(C,{className:"gap-0 py-0",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4 p-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:M("flex size-10 shrink-0 items-center justify-center rounded-full",Qe[z]),children:(0,r.jsx)("span",{className:M("size-3 rounded-full",be[z])})}),(0,r.jsxs)("div",{className:"grid leading-tight",children:[(0,r.jsx)("span",{className:"text-sm font-semibold text-foreground","data-testid":"hl-status",children:O}),(0,r.jsx)("span",{className:"text-[13px] text-muted-foreground",children:K})]})]}),(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-4",children:[(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Requests")}),(0,r.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[R.requests.length>=2&&(0,r.jsx)($,{ariaLabel:a("Requests over time"),className:"h-6 w-20 text-foreground",series:R.requests,testId:"hl-spark-requests"}),(0,r.jsx)("span",{className:"text-lg font-semibold tabular-nums text-foreground","data-testid":"hl-requests",children:(o?.requests??0).toString()})]})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Error rate")}),(0,r.jsx)("div",{className:M("text-lg font-semibold tabular-nums",Ne[J]),"data-testid":"hl-error-rate",children:o===null?"\u2014":U(o.errors,o.requests)})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(he,{}),(0,r.jsx)(ue,{message:we,prefix:"hl"})]})]})]}),m!==null&&(0,r.jsx)("div",{className:"border-t border-border bg-destructive/5 px-4 py-2 text-sm text-destructive","data-testid":"hl-metrics-error",role:"alert",children:m}),m===null&&o?.historyTruncated===!0&&(0,r.jsx)("div",{className:"border-t border-border bg-warning/5 px-4 py-2 text-sm text-muted-foreground","data-testid":"hl-history-truncated",children:a("Showing a partial request/error history \u2014 one or more shards have more data than the trend chart can display.")})]}),(0,r.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4","data-testid":"hl-slo",children:[(0,r.jsx)(H,{chart:R.errors.length>=2?(0,r.jsx)($,{ariaLabel:a("Errors over time"),className:"h-7 w-20 text-destructive",series:R.errors,testId:"hl-spark-errors"}):void 0,label:a("Error rate"),level:J,testId:"hl-slo-errorrate",value:o===null?"\u2014":U(o.errors,o.requests)}),(0,r.jsx)(H,{chart:te.failures.length>=2?(0,r.jsx)($,{ariaLabel:a("Auth failures over time"),className:"h-7 w-20 text-destructive",series:te.failures,testId:"hl-spark-auth"}):void 0,label:a("Auth failures"),level:re,testId:"hl-slo-auth",value:u===null?"\u2014":U(u.failures,u.attempts)}),(0,r.jsx)(H,{label:a("Scheduler backlog"),level:se,testId:"hl-slo-backlog",value:x===null?"\u2014":x.backlog.toString()}),(0,r.jsx)(H,{label:a("Migrations"),level:V.level,testId:"hl-slo-migrations",value:Je(V,a)})]}),(0,r.jsx)(je,{errorCount:ee.length,logsError:c,topErrors:ke,worstFunctions:Se}),(0,r.jsxs)(C,{className:"gap-0 py-0",children:[(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:a("Shards seen")}),(0,r.jsx)(P,{"data-testid":"hl-shard-count",variant:"outline",children:N.length})]}),N.length>0&&(0,r.jsx)("ul",{className:"flex flex-wrap gap-1.5 p-4",children:N.map(b=>(0,r.jsx)("li",{"data-testid":"hl-shard",children:(0,r.jsx)(P,{variant:"secondary",children:b})},b))})]})]})},"ut");export{xt as HealthPanel};
|
|
1
|
+
import{b as me}from"./chunk-2I4NHEKA.js";import{a as $}from"./chunk-GCG65T2K.js";import{a as ue}from"./chunk-SV764LKQ.js";import"./chunk-AN4UDYUY.js";import"./chunk-AUGKHAMQ.js";import"./chunk-WJRYEML4.js";import{a as de}from"./chunk-ZKJS6EBE.js";import"./chunk-RGMVGZV4.js";import"./chunk-SJQERRSZ.js";import"./chunk-7Y3SY37W.js";import{b as P}from"./chunk-Q6ED4KUL.js";import"./chunk-BOMPSVRC.js";import"./chunk-55UGUCQ6.js";import{a as A}from"./chunk-4ZEL6BYL.js";import{c as ce}from"./chunk-R2SQETIF.js";import{g as ne,h as oe}from"./chunk-MOW4XMIT.js";import"./chunk-QAQDMS6R.js";import"./chunk-VEK3S7MV.js";import{a as C}from"./chunk-2IKDEUCX.js";import{d as D,f as I,g as Q,h as W,p as _,t as ie}from"./chunk-HJHSQPHW.js";import{a as f,d as T,e as qe,f as ae,g as le,i as M}from"./chunk-I26MS5PJ.js";var Y=T(ae(),1);var h=T(qe(),1);var fe=T(ae(),1);var B=T(le(),1);var Me={connected:"bg-success",connecting:"bg-warning",idle:"bg-muted-foreground",offline:"bg-destructive",polling:"bg-warning"},he=f(()=>{let t=(0,fe.c)(18),e=D(),a=oe(),s;e:switch(a){case"connected":{let n;t[0]!==e?(n=e("Connected"),t[0]=e,t[1]=n):n=t[1],s=n;break e}case"connecting":{let n;t[2]!==e?(n=e("Connecting\u2026"),t[2]=e,t[3]=n):n=t[3],s=n;break e}case"idle":{let n;t[4]!==e?(n=e("Idle"),t[4]=e,t[5]=n):n=t[5],s=n;break e}case"offline":{let n;t[6]!==e?(n=e("Offline"),t[6]=e,t[7]=n):n=t[7],s=n;break e}case"polling":{let n;t[8]!==e?(n=e("Polling"),t[8]=e,t[9]=n):n=t[9],s=n;break e}default:s=a}let l=Me[a],c;t[10]!==l?(c=M("size-2 rounded-full",l),t[10]=l,t[11]=c):c=t[11];let i;t[12]!==c?(i=(0,B.jsx)("span",{"aria-hidden":"true",className:c}),t[12]=c,t[13]=i):i=t[13];let o;return t[14]!==a||t[15]!==i||t[16]!==s?(o=(0,B.jsxs)("span",{"aria-live":"polite",className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground","data-status":a,"data-testid":"dash-connection",role:"status",children:[i,s]}),t[14]=a,t[15]=i,t[16]=s,t[17]=o):o=t[17],o},"T");var r=T(le(),1);var Ae={crit:"destructive",ok:"secondary",warn:"default"},U=f((t,e)=>e===0?"\u2014":`${(t/e*100).toFixed(1)}%`,"P"),X=f((t,e,a)=>Number.isNaN(t)?"ok":t>=a?"crit":t>=e?"warn":"ok","z"),xe=.01,ve=.05,je=f(t=>{let e=(0,Y.c)(36),{errorCount:a,logsError:s,topErrors:l,worstFunctions:c}=t,i=D(),o;e[0]!==i?(o=i("Functions by error rate"),e[0]=i,e[1]=o):o=e[1];let n;e[2]!==o?(n=(0,r.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:o})}),e[2]=o,e[3]=n):n=e[3];let m;e[4]!==i||e[5]!==c?(m=c.length===0?(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-functions-empty",children:i("No function activity yet.")}):(0,r.jsx)("ul",{className:"divide-y divide-border",children:c.map(w=>(0,r.jsxs)("li",{className:"flex flex-wrap items-center justify-between gap-2 px-4 py-2 text-xs","data-testid":"hl-fn-row",children:[(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:w.path}),(0,r.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,r.jsx)("span",{className:"tabular-nums text-muted-foreground",children:i("{count} calls",{count:w.calls.toString()})}),(0,r.jsx)(P,{variant:Ae[X(w.errors/w.calls,xe,ve)],children:U(w.errors,w.calls)})]})]},w.path))}),e[4]=i,e[5]=c,e[6]=m):m=e[6];let p;e[7]!==n||e[8]!==m?(p=(0,r.jsxs)(C,{className:"gap-0 py-0","data-testid":"hl-functions",children:[n,m]}),e[7]=n,e[8]=m,e[9]=p):p=e[9];let v;e[10]!==i?(v=i("Recent errors"),e[10]=i,e[11]=v):v=e[11];let d;e[12]!==v?(d=(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:v}),e[12]=v,e[13]=d):d=e[13];let u=a>0?"destructive":"outline",g;e[14]!==a||e[15]!==u?(g=(0,r.jsx)(P,{"data-testid":"hl-error-count",variant:u,children:a}),e[14]=a,e[15]=u,e[16]=g):g=e[16];let x;e[17]!==d||e[18]!==g?(x=(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[d,g]}),e[17]=d,e[18]=g,e[19]=x):x=e[19];let S;e[20]!==s?(S=s!==null&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-destructive","data-testid":"hl-logs-error",role:"alert",children:s}),e[20]=s,e[21]=S):S=e[21];let E;e[22]!==s||e[23]!==i||e[24]!==l.length?(E=s===null&&l.length===0&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-errors-empty",children:i("No recent errors.")}),e[22]=s,e[23]=i,e[24]=l.length,e[25]=E):E=e[25];let q;e[26]!==l?(q=l.length>0&&(0,r.jsx)("ul",{className:"divide-y divide-border",children:l.map(Ce)}),e[26]=l,e[27]=q):q=e[27];let N;e[28]!==S||e[29]!==E||e[30]!==q||e[31]!==x?(N=(0,r.jsxs)(C,{className:"gap-0 py-0",children:[x,S,E,q]}),e[28]=S,e[29]=E,e[30]=q,e[31]=x,e[32]=N):N=e[32];let k;return e[33]!==N||e[34]!==p?(k=(0,r.jsxs)("div",{className:"grid gap-3 lg:grid-cols-2",children:[p,N]}),e[33]=N,e[34]=p,e[35]=k):k=e[35],k},"ye");function Ce(t,e){return(0,r.jsxs)("li",{className:"flex flex-col gap-0.5 px-4 py-2 text-xs","data-testid":"hl-error-row",children:[(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)("time",{className:"shrink-0 text-muted-foreground",children:ie(t.timestamp)}),t.functionPath!==void 0&&(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:t.functionPath})]}),(0,r.jsx)("span",{className:"text-destructive",children:t.message})]},`${t.timestamp.toString()}-${e.toString()}`)}f(Ce,"Te");var pe={completed:0,failed:2,in_progress:1},Ie=f(t=>{let e=0,a=0,s=0,l=0,c=!1,i=[];for(let{metrics:o}of t){if(o===null){l+=1;continue}s+=1,e+=o.requests,a+=o.errors,i.push(...o.history??[]),c||=o.historyTruncated===!0}return{errors:a,failed:l,history:i,historyTruncated:c,reachable:s,requests:e}},"Ae"),Te=f(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.path);if(l===void 0){e.set(s.path,{...s});continue}l.calls+=s.calls,l.errors+=s.errors,l.totalDurationMs+=s.totalDurationMs,l.scans=(l.scans??0)+(s.scans??0),l.maxDurationMs=Math.max(l.maxDurationMs,s.maxDurationMs),l.lastCalledAt=Math.max(l.lastCalledAt,s.lastCalledAt),(s.lastErrorAt??0)>(l.lastErrorAt??0)&&(l.lastErrorAt=s.lastErrorAt,l.lastErrorMessage=s.lastErrorMessage)}return[...e.values()]},"ke"),De=f(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.id);if(l===void 0){e.set(s.id,s);continue}let c=pe[s.status]-pe[l.status];(c>0||c===0&&(s.updatedAt??0)>(l.updatedAt??0))&&e.set(s.id,s)}return[...e.values()]},"Re"),Pe=I(A.getAuthMetrics),Fe=I(A.getFunctionStats),Le=I(A.getLogs),Re=I(A.getMetrics),ze=I(A.migrationStatus),Oe=5,ge=2e3,Ke=5,_e=.1,$e=.3,Be=1,He=50,Ue=f((t,e,a)=>t>=a?"crit":t>=e?"warn":"ok","Pe"),Ge=f(t=>{let e=new Map;for(let s of t??[]){let l=e.get(s.bucketMs)??{calls:0,errors:0};l.calls+=s.calls,l.errors+=s.errors,e.set(s.bucketMs,l)}let a=[...e.entries()].toSorted((s,l)=>s[0]-l[0]);return{errors:a.map(([,s])=>s.errors),requests:a.map(([,s])=>s.calls)}},"Ge"),Ve=f(t=>{let e=0,a=0;for(let l of t)l.status==="failed"?e+=1:l.status==="in_progress"&&(a+=1);let s="ok";return e>0?s="crit":a>0&&(s="warn"),{failed:e,level:s,running:a}},"Ve"),Je=f((t,e)=>t.failed>0?e("{count} failed",{count:t.failed.toString()}):t.running>0?e("{count} running",{count:t.running.toString()}):e("OK"),"Be"),be={crit:"bg-destructive",ok:"bg-success",warn:"bg-warning"},Ne={crit:"text-destructive",ok:"text-foreground",warn:"text-warning"},Qe={crit:"bg-destructive/10 text-destructive",ok:"bg-success/10 text-success",warn:"bg-warning/10 text-warning"},We=f(t=>t.includes("crit")?"crit":t.includes("warn")?"warn":"ok","Ke"),H=f(t=>{let e=(0,Y.c)(19),{chart:a,label:s,level:l,testId:c,value:i}=t,o=be[l],n;e[0]!==o?(n=M("size-1.5 shrink-0 rounded-full",o),e[0]=o,e[1]=n):n=e[1];let m;e[2]!==n?(m=(0,r.jsx)("span",{"aria-hidden":"true",className:n}),e[2]=n,e[3]=m):m=e[3];let p;e[4]!==s||e[5]!==m?(p=(0,r.jsxs)("span",{className:"flex items-center gap-1.5 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:[m,s]}),e[4]=s,e[5]=m,e[6]=p):p=e[6];let v=Ne[l],d;e[7]!==v?(d=M("truncate text-2xl font-semibold tabular-nums",v),e[7]=v,e[8]=d):d=e[8];let u;e[9]!==d||e[10]!==c||e[11]!==i?(u=(0,r.jsx)("span",{className:d,"data-testid":c,children:i}),e[9]=d,e[10]=c,e[11]=i,e[12]=u):u=e[12];let g;e[13]!==a||e[14]!==u?(g=(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[u,a]}),e[13]=a,e[14]=u,e[15]=g):g=e[15];let x;return e[16]!==p||e[17]!==g?(x=(0,r.jsx)(C,{className:"gap-0 py-0",children:(0,r.jsxs)("div",{className:"flex flex-col gap-2.5 p-4",children:[p,g]})}),e[16]=p,e[17]=g,e[18]=x):x=e[18],x},"U"),Xe=f(async(t,e,a)=>{let s=await Promise.all(a.map(d=>{let u=Q(d);return Promise.allSettled([t.query(Re,{},u),t.query(Fe,{},u),t.query(ze,{},u)])})),l=Q(e),c=typeof t.schedulerStatus=="function"?t.schedulerStatus():Promise.reject(new Error("scheduler status unavailable")),[i,o,n]=await Promise.allSettled([t.query(Le,{},l),t.query(Pe,{},l),c]),m=s.map(([d,u,g])=>({functions:u.status==="fulfilled"?u.value.functions:[],metrics:d.status==="fulfilled"?d.value:null,migrations:g.status==="fulfilled"?g.value.migrations:[]})),p=Ie(m),v=s[0]?.[0];return{auth:o.status==="fulfilled"?o.value:null,entries:i.status==="fulfilled"?i.value.entries:[],functions:Te(m.map(d=>d.functions)),logsError:i.status==="rejected"?W(i.reason):null,metricsError:p.reachable===0&&v?.status==="rejected"?W(v.reason):null,migrations:De(m.map(d=>d.migrations)),scheduler:n.status==="fulfilled"?n.value:null,totals:p}},"$e"),Ye=f(t=>{let e=t?.history??[];return{attempts:e.map(a=>a.attempts),failures:e.map(a=>a.failures)}},"ze"),xt=f(({initialShardKey:t})=>{let e=ne(),a=D(),[s,l]=(0,h.useState)([]),[c,i]=(0,h.useState)(null),[o,n]=(0,h.useState)(null),[m,p]=(0,h.useState)(null),[v,d]=(0,h.useState)([]),[u,g]=(0,h.useState)(null),[x,S]=(0,h.useState)(null),[E,q]=(0,h.useState)([]),[N]=(0,h.useState)(de),k=(0,h.useRef)(!1),w=(0,h.useRef)(0),G=(0,h.useRef)(0),j=(0,h.useRef)(null),F=t??"",L=(0,h.useCallback)(async()=>{if(k.current)return;k.current=!0;let b=w.current,y=await Xe(e,F,me(F,N));b===w.current&&(n(y.totals),p(y.metricsError),d(y.functions),q(y.migrations),l(y.entries),i(y.logsError),g(y.auth),S(y.scheduler),k.current=!1)},[e,N,F]);(0,h.useEffect)(()=>(_(L()),()=>{w.current+=1,k.current=!1,j.current!==null&&(clearTimeout(j.current),j.current=null)}),[L]);let ye=f(()=>{let b=Date.now()-G.current;if(b>=ge){G.current=Date.now(),_(L());return}j.current===null&&(j.current=setTimeout(()=>{j.current=null,G.current=Date.now(),_(L())},ge-b))},"ue"),{data:Z,liveError:we}=ce(A.getMetrics,{},{live:!0,shardKey:F});(0,h.useEffect)(()=>{Z!==void 0&&ye()},[Z]);let ee=s.filter(b=>b.level==="error"),ke=ee.slice(0,Oe),R=Ge(o?.history),te=Ye(u),Se=v.filter(b=>b.calls>0).toSorted((b,y)=>y.errors/y.calls-b.errors/b.calls||y.calls-b.calls).slice(0,Ke),V=Ve(E),Ee=o===null||o.requests===0?0:o.errors/o.requests,J=X(Ee,xe,ve),re=u===null?"ok":X(u.failureRate,_e,$e),se=x===null?"ok":Ue(x.backlog,Be,He),z=We([J,re,se,V.level]),O,K;return z==="crit"?(O=a("Critical"),K=a("One or more service levels are breached.")):z==="warn"?(O=a("Degraded"),K=a("Some service levels need attention.")):(O=a("All systems healthy"),K=a("All service levels are within target.")),(0,r.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-health",children:[(0,r.jsxs)(C,{className:"gap-0 py-0",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4 p-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:M("flex size-10 shrink-0 items-center justify-center rounded-full",Qe[z]),children:(0,r.jsx)("span",{className:M("size-3 rounded-full",be[z])})}),(0,r.jsxs)("div",{className:"grid leading-tight",children:[(0,r.jsx)("span",{className:"text-sm font-semibold text-foreground","data-testid":"hl-status",children:O}),(0,r.jsx)("span",{className:"text-[13px] text-muted-foreground",children:K})]})]}),(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-4",children:[(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Requests")}),(0,r.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[R.requests.length>=2&&(0,r.jsx)($,{ariaLabel:a("Requests over time"),className:"h-6 w-20 text-foreground",series:R.requests,testId:"hl-spark-requests"}),(0,r.jsx)("span",{className:"text-lg font-semibold tabular-nums text-foreground","data-testid":"hl-requests",children:(o?.requests??0).toString()})]})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Error rate")}),(0,r.jsx)("div",{className:M("text-lg font-semibold tabular-nums",Ne[J]),"data-testid":"hl-error-rate",children:o===null?"\u2014":U(o.errors,o.requests)})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(he,{}),(0,r.jsx)(ue,{message:we,prefix:"hl"})]})]})]}),m!==null&&(0,r.jsx)("div",{className:"border-t border-border bg-destructive/5 px-4 py-2 text-sm text-destructive","data-testid":"hl-metrics-error",role:"alert",children:m}),m===null&&o?.historyTruncated===!0&&(0,r.jsx)("div",{className:"border-t border-border bg-warning/5 px-4 py-2 text-sm text-muted-foreground","data-testid":"hl-history-truncated",children:a("Showing a partial request/error history \u2014 one or more shards have more data than the trend chart can display.")})]}),(0,r.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4","data-testid":"hl-slo",children:[(0,r.jsx)(H,{chart:R.errors.length>=2?(0,r.jsx)($,{ariaLabel:a("Errors over time"),className:"h-7 w-20 text-destructive",series:R.errors,testId:"hl-spark-errors"}):void 0,label:a("Error rate"),level:J,testId:"hl-slo-errorrate",value:o===null?"\u2014":U(o.errors,o.requests)}),(0,r.jsx)(H,{chart:te.failures.length>=2?(0,r.jsx)($,{ariaLabel:a("Auth failures over time"),className:"h-7 w-20 text-destructive",series:te.failures,testId:"hl-spark-auth"}):void 0,label:a("Auth failures"),level:re,testId:"hl-slo-auth",value:u===null?"\u2014":U(u.failures,u.attempts)}),(0,r.jsx)(H,{label:a("Scheduler backlog"),level:se,testId:"hl-slo-backlog",value:x===null?"\u2014":x.backlog.toString()}),(0,r.jsx)(H,{label:a("Migrations"),level:V.level,testId:"hl-slo-migrations",value:Je(V,a)})]}),(0,r.jsx)(je,{errorCount:ee.length,logsError:c,topErrors:ke,worstFunctions:Se}),(0,r.jsxs)(C,{className:"gap-0 py-0",children:[(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:a("Shards seen")}),(0,r.jsx)(P,{"data-testid":"hl-shard-count",variant:"outline",children:N.length})]}),N.length>0&&(0,r.jsx)("ul",{className:"flex flex-wrap gap-1.5 p-4",children:N.map(b=>(0,r.jsx)("li",{"data-testid":"hl-shard",children:(0,r.jsx)(P,{variant:"secondary",children:b})},b))})]})]})},"ut");export{xt as HealthPanel};
|