@lunora/studio 1.0.0-alpha.329 → 1.0.0-alpha.330

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/standalone/{chunk-Q3QEBLD4.js → chunk-2PNG3QHQ.js} +1 -1
  2. package/dist/standalone/{chunk-5S45W3DS.js → chunk-3ADTLIRI.js} +1 -1
  3. package/dist/standalone/{chunk-Q7DBKLSB.js → chunk-3CBQDJ4S.js} +1 -1
  4. package/dist/standalone/{chunk-I5HQKJIE.js → chunk-3RSD3XAG.js} +1 -1
  5. package/dist/standalone/{chunk-FQZPHXRY.js → chunk-5LEVE36K.js} +1 -1
  6. package/dist/standalone/{chunk-LPQKR3EY.js → chunk-6B7YJY6X.js} +1 -1
  7. package/dist/standalone/{chunk-UB6IGAMO.js → chunk-6XIDYONR.js} +1 -1
  8. package/dist/standalone/{chunk-VJIYYQZP.js → chunk-74WMPCOL.js} +1 -1
  9. package/dist/standalone/{chunk-D63COTYE.js → chunk-7XYNQ3JS.js} +1 -1
  10. package/dist/standalone/{chunk-B545WZOQ.js → chunk-A4R7GZQS.js} +1 -1
  11. package/dist/standalone/{chunk-CQQ6GJY4.js → chunk-AFX6YYGP.js} +1 -1
  12. package/dist/standalone/{chunk-RSPLE3QM.js → chunk-AJSSEAMP.js} +1 -1
  13. package/dist/standalone/{chunk-3QL4ND7D.js → chunk-BPBEVNUM.js} +1 -1
  14. package/dist/standalone/{chunk-O7IHOSPM.js → chunk-C5KBRXQG.js} +1 -1
  15. package/dist/standalone/{chunk-PZKQMSHC.js → chunk-CVPVFONU.js} +1 -1
  16. package/dist/standalone/{chunk-HIS2QOIN.js → chunk-CYWRJGWD.js} +1 -1
  17. package/dist/standalone/{chunk-QJAHVMEQ.js → chunk-D3HPOVEQ.js} +1 -1
  18. package/dist/standalone/{chunk-ZGUIX5JS.js → chunk-DQSV2OFA.js} +1 -1
  19. package/dist/standalone/{chunk-6W4HLFYQ.js → chunk-DS2DTZFS.js} +1 -1
  20. package/dist/standalone/{chunk-D74GLIZ3.js → chunk-DSXEICMD.js} +1 -1
  21. package/dist/standalone/{chunk-GKXBHP5C.js → chunk-DXYCOA4Y.js} +1 -1
  22. package/dist/standalone/{chunk-CWIHIVUM.js → chunk-FGVGIVB6.js} +1 -1
  23. package/dist/standalone/{chunk-3QV7HHQG.js → chunk-G3NIGELJ.js} +1 -1
  24. package/dist/standalone/{chunk-FSSQB6RQ.js → chunk-GPNP4QSZ.js} +1 -1
  25. package/dist/standalone/{chunk-AQOISTOA.js → chunk-GV2QZP42.js} +1 -1
  26. package/dist/standalone/{chunk-SLD4Y7CB.js → chunk-GV6O3NPO.js} +1 -1
  27. package/dist/standalone/{chunk-3INTX6UT.js → chunk-GXYXVKOM.js} +1 -1
  28. package/dist/standalone/{chunk-SCOPHATU.js → chunk-HHT7X6VO.js} +1 -1
  29. package/dist/standalone/{chunk-6RZVYKOR.js → chunk-HKQSHNFB.js} +1 -1
  30. package/dist/standalone/{chunk-M5NO6HJW.js → chunk-I5RZUA4J.js} +1 -1
  31. package/dist/standalone/{chunk-7KGJZ7AR.js → chunk-J5NS6XO4.js} +1 -1
  32. package/dist/standalone/{chunk-KGHRCSAH.js → chunk-K7OJ77CA.js} +1 -1
  33. package/dist/standalone/{chunk-2X5KA4QQ.js → chunk-KRVD6WPH.js} +1 -1
  34. package/dist/standalone/{chunk-3N44IWPE.js → chunk-KXYSX2SV.js} +1 -1
  35. package/dist/standalone/{chunk-AXODHTFK.js → chunk-LSEISHAB.js} +1 -1
  36. package/dist/standalone/{chunk-6NM256XN.js → chunk-LXBSXLLK.js} +1 -1
  37. package/dist/standalone/{chunk-XOVK37LR.js → chunk-MCHTZFX6.js} +1 -1
  38. package/dist/standalone/{chunk-MBW6E2H5.js → chunk-MRFJSQBZ.js} +1 -1
  39. package/dist/standalone/{chunk-FZMPKYDN.js → chunk-NA7GP6EE.js} +1 -1
  40. package/dist/standalone/{chunk-7EX5FYKJ.js → chunk-NXVOCK3P.js} +1 -1
  41. package/dist/standalone/{chunk-7VIAQGP3.js → chunk-OU56VN3R.js} +1 -1
  42. package/dist/standalone/{chunk-U27WIISY.js → chunk-P6UD4I65.js} +1 -1
  43. package/dist/standalone/{chunk-C36GGBU5.js → chunk-PAAYRW3Q.js} +1 -1
  44. package/dist/standalone/{chunk-BVCS2OKM.js → chunk-PDF22AMX.js} +1 -1
  45. package/dist/standalone/{chunk-VMCP3XCC.js → chunk-PH4VNMUO.js} +1 -1
  46. package/dist/standalone/{chunk-Q4IPXFP3.js → chunk-PLVFYL6L.js} +1 -1
  47. package/dist/standalone/{chunk-RYIJBW4I.js → chunk-QBTZMN5E.js} +1 -1
  48. package/dist/standalone/{chunk-CZKPLENB.js → chunk-QJACMRR5.js} +1 -1
  49. package/dist/standalone/{chunk-OOEPWT7Q.js → chunk-S63L3TCR.js} +1 -1
  50. package/dist/standalone/{chunk-M4EGHOJK.js → chunk-SZIEPXZM.js} +1 -1
  51. package/dist/standalone/{chunk-DUEZHBXW.js → chunk-TM5C7YPO.js} +1 -1
  52. package/dist/standalone/{chunk-H3O25TSD.js → chunk-TSNDFT5D.js} +1 -1
  53. package/dist/standalone/{chunk-EJGPVJWW.js → chunk-ULW7I6FO.js} +1 -1
  54. package/dist/standalone/{chunk-UBTQ3IAP.js → chunk-V3RAWH63.js} +1 -1
  55. package/dist/standalone/{chunk-A3V7GS5F.js → chunk-WMPXMPVF.js} +1 -1
  56. package/dist/standalone/{chunk-2A7MUTXH.js → chunk-Y57U7WES.js} +1 -1
  57. package/dist/standalone/{chunk-FOW5IME7.js → chunk-YGNPACVK.js} +1 -1
  58. package/dist/standalone/{chunk-SAMGHROD.js → chunk-YPY2NU35.js} +1 -1
  59. package/dist/standalone/{chunk-XR4FVOPT.js → chunk-YQQTRX55.js} +1 -1
  60. package/dist/standalone/{chunk-P3T2TLBH.js → chunk-ZBRLJQ46.js} +1 -1
  61. package/dist/standalone/studio.js +1 -1
  62. package/package.json +4 -4
@@ -6,4 +6,4 @@ import{a as ns,d as b}from"./chunk-WS7WNXF3.js";import{a as n,d as _,e as ee,f a
6
6
 
7
7
  `);for(;p!==-1;){let f=Di(c.slice(0,p));if(c=c.slice(p+2),s.onFrame?.(),f.id!==void 0&&s.onId?.(f.id),f.retry!==void 0&&s.onRetry?.(f.retry),Ki(f,e))return!0;p=c.indexOf(`
8
8
 
9
- `)}return!1},"p"),l=n(()=>a.cancel().then(()=>{},()=>{}),"T");try{for(;;){let{done:p,value:f}=await Ys(a,i);if(p)break;if(d(o.decode(f,{stream:!0})),h())return await l(),!0}return d(o.decode()),h()}catch(p){throw r.abort(),l().catch(()=>{}),p}},"D"),qi=n(async(t,e)=>{e.aborted||await new Promise(s=>{let r,i=n(()=>{clearTimeout(r),s()},"s");r=setTimeout(()=>{e.removeEventListener("abort",i),s()},t),e.addEventListener("abort",i,{once:!0})})},"U"),ji=n((t,e)=>{if(typeof t!="object"||t===null)return;let{code:s,error:r,why:i}=t;if(!(typeof s!="string"||typeof r!="string"))return new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${e.toString()}, ${s}): ${r}`,{status:e,why:typeof i=="string"?i:void 0})},"J"),Wi=n(async(t,e)=>{let s,r=new Promise(a=>{s=setTimeout(()=>{a(void 0)},_i)}),i=t.json().catch(a=>{if(e.aborted)throw a});try{return await Promise.race([i,r])}finally{clearTimeout(s),await t.body?.cancel().catch(()=>{})}},"Y"),Bi=n((t,e)=>{let s=Object.entries(t??{}).filter(([r])=>e===void 0||r.toLowerCase()!=="last-event-id");return{accept:"text/event-stream",...Object.fromEntries(s),...e===void 0?{}:{"last-event-id":e}}},"q"),Zs=n(t=>t instanceof Error&&"code"in t?t:new b("HTTP_STREAM_TRANSPORT",t instanceof Error?t.message:String(t),{cause:t}),"A"),er=n((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=Ui(t,e??{},s.baseUrl??""),a=new AbortController,o;s.signal&&(s.signal.aborted?a.abort():(o=n(()=>{a.abort()},"c"),s.signal.addEventListener("abort",o,{once:!0})));let c=n(()=>{o&&s.signal?.removeEventListener("abort",o)},"m"),{handle:u,iterable:d}=Xe({maxBuffer:s.maxBuffer,onCancel:n(()=>{a.abort()},"onCancel"),onFail:n(()=>{a.abort()},"onFail")}),h=s.reconnect??!1,l=Oe(),{lastEventId:p}=s,f,m=0,y=n(()=>{l.reset(),m=0},"M"),v={},w=n(S=>{try{S()}catch(R){throw v.value={error:R},R}},"R"),T={onFrame:y,onId:n(S=>{w(()=>s.onEventId?.(S)),p=S},"onId"),onRetry:n(S=>{w(()=>s.onRetry?.(S)),f=S},"onRetry")},I=n(async()=>{let S=Bi(s.headers,p),R=new b("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"),V=new AbortController,Q=n(()=>{V.abort()},"g");a.signal.addEventListener("abort",Q,{once:!0});try{let k=await r(i,{headers:S,method:t.method,signal:V.signal});if(!k.ok){let W=await Wi(k,a.signal);u.fail(ji(W,k.status)??new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${k.status.toString()})`,{status:k.status}));return}if(!k.body){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}return{completed:await Ni(k.body,u,T,V,s.idleTimeoutMs),error:R}}catch(k){if(a.signal.aborted){u.complete();return}if(v.value){let{error:W}=v.value;u.fail(W instanceof Error?W:new b("HTTP_STREAM_CALLBACK","httpStream: an onEventId/onRetry callback threw"));return}return{completed:!1,error:Zs(k)}}finally{a.signal.removeEventListener("abort",Q)}},"O");return(async()=>{try{for(;;){if(a.signal.aborted){u.complete();return}let S=await I();if(!S)return;if(S.completed||!h||m>=Qi){S.completed||u.fail(S.error);return}m+=1,await qi(f??l.next(),a.signal)}}finally{c()}})().catch(S=>{if(a.signal.aborted){u.complete();return}u.fail(Zs(S))}),d},"V");var et=n(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"a"),Lt=n(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"h"),q=n((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"$"),F=n((t,e)=>{let s=new URLSearchParams;for(let[i,a]of Object.entries(e))a!==void 0&&a!==""&&s.set(i,String(a));let r=s.toString();return r===""?t:`${t}?${r}`},"d"),$i="http://same-origin.invalid",xt=n(t=>new URL(t,$i),"p"),Hi=/^[a-z][a-z\d+.-]*:/iu,Qt=n((t,e)=>{if(Hi.test(e))return t.toString();let s=`${t.pathname}${t.search}${t.hash}`;return e.startsWith("//")?`//${t.host}${s}`:s},"S");var x=class t{static{n(this,"t")}static key(e,s,r){return`${e}::${K(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 tt(t){if(t!==void 0)return e=>{t(e)}}n(tt,"b");var Y=n((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var _t=0,tr=n(()=>_t,"h"),zi=n((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),sr=n((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),re=n((t,e)=>{sr(t,zi(e,t.optimisticLayers))},"y"),Dt=n((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),sr(t,s);let a=n(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),o=n(()=>{re(t,t.serverBase)},"s");return{confirm:n(c=>{if(c===void 0){a();return}r.commitCursor=c,_t+=1,r.acknowledgedAt=_t,t.serverCursor!==void 0&&t.serverCursor>=c&&a()&&o()},"confirm"),rollback:n(()=>{i||(i=!0,a(),o())},"rollback")}},"g"),st=n((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"),rr=n((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),ae=n(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),ir=n((t,e)=>{let s=[],r=[],i=n((a,o)=>t.get(x.key(a,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:n(a=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===a.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:n((a,o)=>i(a.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:n((a,o,c)=>{let u=i(a.__lunoraRef,o??{});if(!u)return;let d=Dt(u,()=>c);d&&(s.push(d.confirm),r.push(d.rollback))},"setQuery")}}},"_");var Ut=n(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"),Gi=n((t,e)=>{let s=Ut(e);if(!(s===void 0||Ye(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"),fe=n(t=>{let e=t?.error;if(typeof e!="object"||e===null||Array.isArray(e))return;let{why:s,...r}=e;return typeof s=="string"?{...r,why:s}:r},"l"),Kt=n(()=>new D("LunoraClient: batch slot carried no error envelope"),"p"),nr=n((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}},"n"),ar=n(t=>{let{code:e,messageText:s}=nr(t,"stream error"),r=t.error?.why,i=e===void 0?new Error(s):new b(e,s);return typeof r=="string"&&(i.why=r),i},"h"),Nt=n(t=>{let{code:e,messageText:s}=nr(t,"subscription error"),r=t.error?.why;return{message:s,...e===void 0?{}:{code:e},...typeof r=="string"?{why:r}:{}}},"w"),Vi=Symbol.for("lunora.serverVerdict"),Ie=n(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,e[Vi]=!0,t.data!==void 0)try{e.data=E(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),typeof t.why=="string"&&(e.why=t.why),e},"i"),qt=n((t,e)=>{let s=Ie(t),r=Gi(s,e);return r!==void 0&&(s.data=r),s},"b"),rt=n(t=>{let e=fe(t);return e===void 0?Kt():Ie(e)},"A");var or=0,Ji=n(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();or+=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)}_${or.toString(36)}_${t}`},"d"),jt=n((t,e)=>t!==void 0&&e!==t,"f"),nt=Ji,me=n((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)},"h"),it=class{static{n(this,"p")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;onReplayingChange;version;items=[];replayingIds=new Set;appending=new Map;unsettled=new Map;unpersisted=new Set;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.onReplayingChange=s.onReplayingChange,this.version=s.version}get size(){return this.items.length}get replaying(){return this.replayingIds.size}enqueue(e){let s=e;s.id??=nt();let r=this.items.length;for(;s.issueSeq!==void 0&&r>0&&(this.items[r-1]?.issueSeq??-1)>s.issueSeq;)r-=1;this.items.splice(r,0,s),this.unsettled.set(s.id,s),this.persist(this.recordOf(s,s.id)),this.evictOverflow(),this.notifySize()}discard(e){this.unsettled.delete(e),this.unpersisted.delete(e),this.replayingIds.delete(e)&&this.onReplayingChange?.();let{persistence:s}=this;s&&(this.appending.get(e)??Promise.resolve()).then(async()=>s.remove(e)).catch(r=>{me(this.onPersistenceError,"remove",r,e)})}flushUnpersisted(){for(let e of this.unpersisted){let s=this.unsettled.get(e);s&&!this.appending.has(e)&&this.persist(this.recordOf(s,e))}}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw me(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(jt(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{me(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:n(()=>{},"reject"),resolve:n(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),a=new Set;for(let o of s)i.has(o)&&a.add(o.shardKey);return[...a]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;!this.persistence||i===void 0||this.rewriteStamp(i,this.recordOf(r,i)).catch(a=>{me(this.onPersistenceError,"replace",a,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.markReplaying(i),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.markReplaying(s),this.notifySize(),s}requeue(e){if(e.length!==0){for(let s of e)s.id!==void 0&&this.replayingIds.delete(s.id);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 new Set([...this.items,...this.unsettled.values()])){let s=new Error("CLIENT_CLOSED"),r=e.id??"",i=n(o=>{s.code="CLIENT_CLOSED",s.persisted=o,e.reject(s)},"s"),a=this.appending.get(r);this.replayingIds.has(r)?i(!1):a===void 0?i(this.persistence!==void 0&&!this.unpersisted.has(r)):a.catch(()=>!1).then(i).catch(()=>{})}this.items.length=0,this.replayingIds.clear(),this.unsettled.clear(),this.unpersisted.clear(),this.notifySize()}recordOf(e,s){return{args:e.args,...e.baselineSeq===void 0?{}:{baselineSeq:e.baselineSeq},clientId:e.clientId,functionPath:e.functionPath,id:s,identity:e.identity,shardKey:e.shardKey,...this.version===void 0?{}:{version:this.version}}}persist(e){let{persistence:s}=this;if(!s)return;let r=(async()=>{try{return await s.append(e),this.unpersisted.delete(e.id),!0}catch(i){return this.unsettled.has(e.id)&&this.unpersisted.add(e.id),me(this.onPersistenceError,"append",i,e.id),!1}})();this.appending.set(e.id,r),r.finally(()=>{this.appending.get(e.id)===r&&this.appending.delete(e.id)}).catch(()=>{})}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await this.appending.get(e),await r.replace(s)}catch(i){me(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.discard(e.id);let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}markReplaying(e){for(let s of e)s.id!==void 0&&this.replayingIds.add(s.id)}notifySize(){this.onSizeChange?.(this.items.length)}};var Yi="lunora-outbox",Xi="offline-mutations",Wt="by_id",Zi=n((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??Xi,i=ze(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(Wt,"id",{unique:!0})}),a=Ge(i,r);return{append:n(async o=>{await a("readwrite",c=>L(c.add(o)))},"append"),clear:n(async()=>{await a("readwrite",o=>L(o.clear()))},"clear"),load:n(async()=>a("readonly",o=>L(o.getAll())),"load"),remove:n(async o=>{await a("readwrite",async c=>{let u=await L(c.index(Wt).getKey(o));u!==void 0&&await L(c.delete(u))})},"remove"),replace:n(async o=>{await a("readwrite",async c=>{let u=await L(c.index(Wt).getKey(o.id));u!==void 0&&await L(c.put(o,u))})},"replace")}},"w"),cr=n((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return Zi()}},"b");var ur=n((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),a=i.present?K(i.value):void 0;return()=>{let o=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!o.present?!0:K(o.value)===a}},"c");var Bt=500,br=n((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Ae"),X="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",tn=n(t=>{let e="",s=0,r=t.length-2;for(;s<r;s+=3){let a=t[s]<<16|t[s+1]<<8|t[s+2];e+=X.charAt(a>>18&63)+X.charAt(a>>12&63)+X.charAt(a>>6&63)+X.charAt(a&63)}let i=t.length-s;if(i===1){let a=t[s]<<16;e+=X.charAt(a>>18&63)+X.charAt(a>>12&63)}else if(i===2){let a=t[s]<<16|t[s+1]<<8;e+=X.charAt(a>>18&63)+X.charAt(a>>12&63)+X.charAt(a>>6&63)}return e},"gt");new TextDecoder;var sn=new TextEncoder,rn=n(t=>tn(sn.encode(JSON.stringify(t))),"kt"),nn="x-lunora-expect-subject",an=n(t=>rn({subject:t}),"Ct"),hr=Symbol.for("lunora:session-change"),on="lunora:session-change",cn="better-auth.message",un="signout",gr=n(()=>{let t=globalThis,e=t[hr];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[hr]=e),e},"_e"),hn=n(()=>"document"in globalThis,"It"),dn=n(async()=>{let t=[];for(let e of gr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"Ot"),ln=n((t,e)=>{if(t!==cn||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===un}catch{return!1}},"Rt"),pn=n(t=>{let e=[],s=n(()=>{dn().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(on):void 0}catch{r=void 0}if(r!==void 0){let a=r;a.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==t&&s()}),e.push(()=>{a.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let a=n(o=>{ln(o.key,o.newValue)&&s()},"r");i.addEventListener("storage",a),e.push(()=>{i.removeEventListener?.("storage",a)})}return()=>{for(let a of e)a()}},"Pt"),fn=n(t=>{let e=gr();return e.listeners.add(t),e.detach===void 0&&hn()&&(e.detach=pn(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"Ft"),mn="/_lunora/rpc",$t="/_lunora/rpc-batch",Ht="/_lunora/ws",yn="/_lunora/admin/shard-traffic",bn="/_lunora/admin/scheduled",gn="/_lunora/admin/scheduled/status",vn="/_lunora/admin/scheduled/ws",Sn="/_lunora/admin/scheduled/cancel",dr="/_lunora/admin/scheduled/dead",wn="/_lunora/admin/scheduled/dead/retry",Cn="/_lunora/admin/scheduled/dead/cancel",kn="/_lunora/admin/workflows/instances",Tn="/_lunora/admin/workflows/instance",En="/_lunora/admin/workflows/status",ts="/_lunora/admin/storage",On="/_lunora/admin/storage/url",In="/_lunora/admin/storage/buckets",Rn="/_lunora/admin/functions",An="/_lunora/admin/cron-jobs",Fn="/_lunora/admin/cron-jobs/run",Pn="/_lunora/admin/architecture",Mn="/_lunora/admin/openapi",Ln="/_lunora/admin/openrpc",xn="/_lunora/admin/global/tables",Qn="/_lunora/admin/global/table",_n="/_lunora/admin/global/facet",Dn="/_lunora/admin/vector/indexes",Un="/_lunora/admin/vector/query",Kn="/_lunora/admin/logs/archive",Nn="/_lunora/admin/kv/namespaces",qn="/_lunora/admin/kv/keys",ss="/_lunora/admin/kv/value",jn="/_lunora/admin/auth/users",Wn="/_lunora/admin/auth/sessions",Bn="/_lunora/admin/auth/users/create",$n="/_lunora/admin/auth/users/role",Hn="/_lunora/admin/auth/users/ban",zn="/_lunora/admin/auth/users/unban",Gn="/_lunora/admin/auth/users/password",Vn="/_lunora/admin/auth/users/remove",Jn="/_lunora/admin/auth/users/impersonate",Yn="/_lunora/admin/auth/sessions/revoke",Xn="/_lunora/admin/auth/sessions/revoke-all",Zn="/_lunora/admin/auth/capabilities",ea="/_lunora/admin/auth/users/update",ta="/_lunora/admin/auth/accounts",sa="/_lunora/admin/auth/accounts/unlink",ra="/_lunora/admin/auth/passkeys",ia="/_lunora/admin/auth/passkeys/delete",na="/_lunora/admin/auth/two-factor/disable",aa="/_lunora/admin/auth/organizations",oa="/_lunora/admin/auth/organizations/members",ca="/_lunora/admin/auth/organizations/invitations",ua="/_lunora/admin/auth/organizations/members/remove",ha="/_lunora/admin/auth/organizations/invitations/cancel",da="/_lunora/admin/auth/config",la="/_lunora/admin/auth/sign-up-invitations",pa="/_lunora/admin/auth/sign-up-invitations/create",fa="/_lunora/admin/auth/sign-up-invitations/revoke",ma="/_lunora/admin/auth/organizations/create",ya="/_lunora/admin/auth/organizations/update",ba="/_lunora/admin/auth/organizations/remove",ga="/_lunora/admin/auth/organizations/members/add",va="/_lunora/admin/auth/organizations/members/invite",Sa="/_lunora/admin/auth/organizations/members/role",wa="/_lunora/admin/auth/organizations/teams",Ca="/_lunora/admin/auth/organizations/teams/create",ka="/_lunora/admin/auth/organizations/teams/update",Ta="/_lunora/admin/auth/organizations/teams/remove",Ea="/_lunora/admin/auth/organizations/teams/members",Oa="/_lunora/admin/auth/organizations/teams/members/add",Ia="/_lunora/admin/auth/organizations/teams/members/remove",Ra="/_lunora/admin/auth/organizations/roles",Aa="/_lunora/admin/auth/organizations/roles/create",Fa="/_lunora/admin/auth/organizations/roles/update",Pa="/_lunora/admin/auth/organizations/roles/remove",Ma="/api/auth",La="/get-session",xa="lunora-ping",Qa=n(async t=>(t.assertOpen(),(await t.adminFetch(Rn,"GET")).functions??[]),"Zs"),_a=n(async t=>(t.assertOpen(),(await t.adminFetch(An,"GET")).jobs??[]),"ei"),Da=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Fn,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"ti"),Ua=n(async t=>(t.assertOpen(),await t.adminFetch(Mn,"GET")),"si"),Ka=n(async t=>(t.assertOpen(),await t.adminFetch(Pn,"GET")),"ii"),Na=n(async t=>(t.assertOpen(),await t.adminFetch(Ln,"GET")),"ni"),qa=n(async t=>(t.assertOpen(),await t.adminFetch(xn,"GET")),"ri"),ja=n(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(B(e.filters))),E(await t.adminFetch(`${Qn}?${s.toString()}`,"GET"))},"oi"),Wa=n(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(B(e.filters))),E(await t.adminFetch(`${_n}?${s.toString()}`,"GET"))},"ai"),Ba=n(async t=>(t.assertOpen(),(await t.adminFetch(Nn,"GET")).namespaces??[]),"ci"),$a=n(async(t,e)=>{t.assertOpen();let s=F(qn,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"di"),Ha=n(async(t,e)=>{t.assertOpen();let s=F(ss,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"ui"),za=n(async(t,e)=>{t.assertOpen(),await t.adminFetch(ss,"PUT",e)},"hi"),Ga=n(async(t,e)=>{t.assertOpen();let s=F(ss,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"li"),Va=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(yn,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"fi"),Ja=n(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(Kn,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"pi"),Ya=n(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}},"mi"),rs=n(t=>"args"in t?{...t,args:E(t.args)}:t,"ae"),Xa=n(async t=>(t.assertOpen(),((await t.adminFetch(bn,"GET")).records??[]).map(e=>rs(e))),"yi"),Za=n(async t=>{t.assertOpen();let e=await t.adminFetch(gn,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"Si"),eo=n(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(Sn,"POST",{id:e})).cancelled===!0}),"bi"),to=n(async t=>(t.assertOpen(),(await Ya(async e=>await t.adminFetch(e===void 0?dr:`${dr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>rs(e))),"vi"),so=n(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(wn,"POST",{id:e})).retried===!0}),"gi"),ro=n(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(Cn,"POST",{id:e})).removed===!0}),"Ti"),io=n(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(`${kn}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"ki"),no=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${Tn}?${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??[]}},"wi"),ao=n(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(En,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"Ci"),oo=n(async(t,e={})=>{t.assertOpen();let s=F(ts,{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??[]}},"Ei"),co=n(async(t,e,s)=>{t.assertOpen();let r=`${ts}?key=${encodeURIComponent(e)}${et(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"Ai"),uo=n(async t=>(t.assertOpen(),(await t.adminFetch(In,"GET")).buckets??[]),"_i"),ho=n(async(t,e)=>{t.assertOpen();let s=`${ts}?key=${encodeURIComponent(e.key)}${et(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"Ii"),lo=n(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,a=`${On}?key=${encodeURIComponent(e)}${i}${et(s?.bucket)}`,o=await t.adminFetch(a,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},"Oi"),po=n(async t=>(t.assertOpen(),(await t.adminFetch(Dn,"GET")).indexes??[]),"Ri"),fo=n(async(t,e)=>(t.assertOpen(),(await t.adminFetch(Un,"POST",e)).matches??[]),"Pi"),G=n((t,e)=>{try{return B(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)}},"E"),Vt=n(t=>{try{return B(t),!0}catch{return!1}},"ee"),vr=n(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Ie"),mo=n((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(!vr(r.body)){s[r.id]={error:rt({}),ok:!1};continue}let i=r.body;s[r.id]="error"in i?{error:rt(i),ok:!1}:{ok:!0,value:E(i.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"Fi"),zt=n((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"J"),at=n(t=>t==="connected"||t==="polling","q"),g=n(t=>t??"","l"),j=n((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"k"),yo=n(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)j(t,s)},"Li"),bo=new TextDecoder,go=n(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return bo.decode(t)},"Hi"),Z=class{static{n(this,"R")}listeners=new Set;get size(){return this.listeners.size}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()}},ye=n(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"H"),vo=n((t,e,s)=>{ye(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(xa)}catch{}},e))},"Ui"),lr=n((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:a,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=n(()=>{ye(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),d=n(h=>{u(),r.onClose(h)},"u");a>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}d()}},a)),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)}t.socket===c&&vo(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()})},"Te"),So=n(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:a}=t,o=s>0&&e>0,c=0,u,d=!1,h=!1,l=n(()=>{u!==void 0&&(clearInterval(u),u=void 0,d=!1,i())},"h"),p=n(m=>{if(u!==void 0){if(!m){l();return}d||(d=!0,i()),r()}},"p"),f=n(()=>{h||(h=!0,a().then(p).finally(()=>{h=!1}).catch(()=>{}))},"f");return{isPolling:n(()=>u!==void 0&&d,"isPolling"),noteFailedOpen:n(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(f,s),i(),f())},"noteFailedOpen"),noteOpen:n(()=>{c=0,l()},"noteOpen"),stop:l}},"Ni"),wo=1e4,pr=n(async t=>ne(wo,void 0,t,()=>new TypeError("LunoraClient: poll timed out")),"ke"),Sr=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),fr=n(t=>{if(t instanceof D)return!0;let e=t?.code;return e===void 0||Sr.has(e)||Pt.has(e)},"we"),Co=1e3,wr=6e4,ko={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Re=n((t,e,s)=>{let r=Ut(s),i=r===void 0?void 0:{retryAfterMs:r},a=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new D(a,i):new b(ko[t]??"BAD_REQUEST",a,{data:i})},"D"),Jt=n((t,e=Math.random)=>{let s=Math.min(Co*2**Math.max(t-1,0),wr);return Math.round(s*(.5+e()*.5))},"te"),To=n(t=>{let e=t?.code;return t instanceof D||e===void 0||Sr.has(e)},"Bi"),Eo=n((t,e,s)=>{let r=Ye(t);return r!==void 0&&r>0?Math.min(r,wr):To(t)?Jt(e,s):void 0},"Qi"),Oo=983040,Io=n(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Ki"),Cr=new WeakSet,kr=n(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 Cr.add(e),e},"Fe"),ot=n(t=>t instanceof Error&&Cr.has(t),"K"),Ro=n(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&vr(s.body)&&e.set(s.id,s.body);return e},"Gi"),Ao=n(t=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:rt(t),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:E(t.result)}}catch(e){return{commitCursor:t.commitCursor,error:kr(e),kind:"undecodable"}}},"ji"),Gt=n((t,e)=>`${g(t)}\0${e}`,"Y"),Fo=n((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"$i"),Yt=class{static{n(this,"Vi")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){br(this.buffers,this.maxBuffers),this.buffers.set(Gt(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(Gt(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:E(c.value)})}catch(c){r.undecodable.set(s.shapeId,c);return}let a=r.parts.get(s.shapeId)??[];for(let c of i)a.push(c);r.parts.set(s.shapeId,a),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=Gt(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},Po=n((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),a=e.bases.get(t.id),o=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=a!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==a;if(!i&&(o||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,t.answered=!1,"reseed";i&&t.rows.clear(),Fo(t.rows,r),t.answered=!0,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"},"zi"),mr=n(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"Ce"),Mo=n((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&Y(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"Ji"),Xt=n((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"se"),Zt=n((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"ie"),Tr=n((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Le"),Lo=n((t,e)=>e.cursor!==void 0&&t.serverCursor!==void 0&&t.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===t.serverEpoch&&e.cursor<t.serverCursor,"Yi"),ct=n((t,e)=>t!==void 0&&t!==e,"G"),xo=n((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","Xi"),Qo=n(t=>{for(let e of t.activeSubscriptions())e.valueReceived=!1,t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.activeShapes())e.answered=!1,t.ensureSocket(e.shardKey);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint()),t.emitConnectionStatus()},"Zi"),_o=n(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1;for(let s of t.activeSubscriptions())s.acked=!1,s.valueReceived=!1;for(let s of t.activeShapes())s.answered=!1;t.emitConnectionStatus()},"en"),Do=n((t,e,s)=>{if(ct(s,t.identityFingerprint()))return;let r=t.leader,i=xo(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&t.flushOfflineQueues()},"tn"),Uo=n(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"sn"),Ko=n((t,e,s,r,i,a)=>{if(ct(a,t.identityFingerprint()))return;let o=t.subscription(e);if(!o)return;t.dropCacheSeed(e);let c=!o.valueReceived;o.valueReceived=!0,Tr(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&st(o,r),re(o,s),c&&t.emitConnectionStatus()},"nn"),No=n((t,e,s,r)=>{if(ct(r,t.identityFingerprint()))return;let i=t.subscription(e);if(i){let a=!i.valueReceived;i.valueReceived=!0,Y(i.errorCallbacks,s),a&&t.emitConnectionStatus()}},"rn"),qo=n((t,e,s,r,i,a,o)=>{if(ct(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&a===t.clientIdentifier()&&Xt(c,i),Zt(c))},"on"),jo=n((t,e,s)=>t!==null||e&&s===null,"an"),Wo=n(t=>t.sensitive===!0,"cn"),Bo=n((t,e)=>{if(!Wo(t))return e;if(e.onlineOnly===!1)throw new b("BAD_REQUEST",`'${t.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},"dn"),$o=[Vs],Ho=100,Er=1e4,zo=n(async(t,e,s,r)=>{let i=new AbortController,a=setTimeout(()=>{i.abort()},Er);try{let o=await t(e,{body:s,credentials:"include",headers:r,method:"POST",signal:i.signal});return await o.text(),o.status}finally{clearTimeout(a)}},"ln"),yr=n((t,e)=>new b("OFFLINE_NOT_QUEUED",`'${t}' is online-only and the connection is not live, so it was not queued`,{cause:e}),"Ee"),Go=n((t,e)=>t instanceof TypeError&&Vt(e),"fn"),Vo=n((t,e,s,r)=>e||t===!0&&s&&!r,"pn"),Jo=Promise.resolve(),es=class t{static{n(this,"He")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:n((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:n(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;wsTokenGeneration=0;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new x;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 Z;statusListeners=new Z;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new Z;identityChangeListeners=new Z;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new Z;pendingChangeListeners=new Z;syncStatusListeners=new Z;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Yt(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??q(Lt(e.url),Ht),this.wsToken=e.wsToken;let s=e.authBasePath??Ma;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??zs(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??3e4,this.connectTimeoutMs=e.connectTimeoutMs??1e4,this.rpcTimeoutMs=e.rpcTimeoutMs??3e4,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??5e3,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??3,this.defaultConnectionContext=e.connectionContext,this.persistence=cr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Hs(e.queryCache),this.clientQueryStore=new Ve,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=Jo),this.offlineQueue=new it(e.offlineQueue,{onEvict:n((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onReplayingChange:n(()=>{this.emitSyncStatus()},"onReplayingChange"),onSizeChange:n(r=>{this.pendingChangeListeners.emit(r),this.emitSyncStatus()},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${nt()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=fn(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),a=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&&a?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&a&&!c?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(u,e),jo(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(d!==i||r||o)&&this.offlineQueue.size>0&&at(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 a=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:n(h=>{c=h},"onMutationAck")})}catch(h){if(!ot(h))throw h;d=h}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(a)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(br(this.clientWatermarks,8),h=new Map,this.clientWatermarks.set(o??"",h)),h.set(a,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(q(this.url,`${this.authBasePath}${La}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let a=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,a,r),a}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.wsTokenGeneration+=1,this.resetRoomSends(),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},a=this.connectionContextHolders.get(r);a?a.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),a=this.whisperHandlers.get(i);a||(a=new Map,this.whisperHandlers.set(i,a));let o=a.get(e),c=o===void 0;if(o||(o=new Set,a.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&this.sendWhisperJoin(u,i,e)}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&&j(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(r.shardKey)}}subscribeLiveTopic(e){let{onError:s,onEvent:r,shardKey:i,stream:a,topic:o}=e;if(o.length===0)throw new b("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;let c=`ws-live-${String(this.nextLiveSocketId)}`,u=g(i),d=`/live/${a}/control`,h=this.whisperSubscribe(o,()=>{},{shardKey:i}),l=n(()=>{let y=h;h=void 0,y?.()},"p"),p=this.liveSocketGrants.get(u);p===void 0&&(p=new Map,this.liveSocketGrants.set(u,p)),p.set(c,{onError:s,onEvent:r,release:l,stream:a,topic:o});let f=this.getConnection(i)?.connectionId;f!==void 0&&this.grantWhenJoined(i,c,f);let m=!1;return()=>{if(m)return;m=!0;let y=this.liveSocketGrants.get(u),v=y?.delete(c)===!0;y?.size===0&&this.liveSocketGrants.delete(u);let w=this.getConnection(i)?.connectionId;v&&w!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:w,stream:a,subscriptionId:c,topic:o}),l()}}whisper(e,s,r={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,G(s??null,`whisper data for topic '${e}'`),r)}connectRoom(e,s,r={}){let i=`room:${e.name}`,a=this.whisperSubscribe(i,p=>{s.onMessage(p)},r),o=!1,c=[],u=n(()=>{c.length=0},"c"),d=n(()=>{for(;c.length>0&&this.roomSendsAdmitted(r.shardKey);){if(!this.sendEncodedWhisper(i,c[0],r))return;c.shift()}},"u"),h=g(r.shardKey),l=this.roomFlushes.get(h)??new Set;return l.add(d),this.roomFlushes.set(h,l),this.roomIdentityResets.add(u),{close:n(()=>{o=!0,c.length=0,l.delete(d),l.size===0&&this.roomFlushes.delete(h),this.roomIdentityResets.delete(u),a()},"close"),send:n(p=>{if(o||this.closed||this.WebSocketImpl===void 0)return!1;let f=G(p,`room message for '${i}'`),m=typeof structuredClone=="function"?structuredClone(f):JSON.parse(JSON.stringify(f));return d(),c.length===0&&this.roomSendsAdmitted(r.shardKey)&&this.sendEncodedWhisper(i,m,r)?!0:c.length>=Ho?!1:(c.push(m),!0)},"send")}}connectWebSocket(e,s,r={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),send:n(()=>{},"send")};let i=n(c=>{try{c?.()}catch(u){console.error("[lunora] socket route handler threw",u)}},"i"),a,o=this.openSupplementarySocket(this.supplementaryUrl(e),{onClose:n(()=>{clearTimeout(a),i(s.onClose)},"onClose"),onMessage:n(c=>{let u;try{u=JSON.parse(typeof c.data=="string"?c.data:"")}catch{return}u.type==="message"&&(o.resetBackoff(),i(()=>{s.onMessage(E(u.data))}))},"onMessage"),onOpen:n(()=>{clearTimeout(a);let c=o.socket();a=setTimeout(()=>{o.socket()===c&&o.resetBackoff()},5e3),i(s.onOpen)},"onOpen"),shardKey:r.shardKey});return{close:n(()=>{clearTimeout(a),o.close()},"close"),send:n(c=>{let u=JSON.stringify(G(c,`socket message for '${e}'`)),d=o.socket();if(d!==void 0)try{d.send(u)}catch{}},"send")}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}syncStatus(){let e=this.computeStatus(),s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader(),r=0;for(let a of this.subscriptions.all())(s||this.connectionGateState(a.shardKey).polling?a.valueReceived:a.acked)||(r+=1);for(let a of this.shapeSubscriptions.values())a.answered||(r+=1);let i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:r,pendingWrites:i,synced:at(e)&&r===0&&i===0}}onSyncStatus(e){let s=this.syncStatusListeners.add(e),r=this.syncStatus();return this.lastSyncStatus=r,e(r),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 a of r){let o=this.connections.get(a);e.push({confirmedMutationWatermark:s?.get(a)??0,hasSocket:o?.socket!==void 0,shardKey:a===""?void 0:a,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(a=>({acked:a.acked,functionPath:a.fn.__lunoraRef,id:a.id,kind:"query",lastMutationId:a.lastMutationId,pendingOptimisticLayers:a.optimisticLayers.length,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size}));for(let a of this.shapeSubscriptions.values())i.push({acked:a.answered,functionPath:`shape:${a.name}`,id:a.id,kind:"shape",lastMutationId:a.lastMutationId,pendingOptimisticLayers:0,rowCount:a.rows.size,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((a,o)=>(a.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((a,o)=>a.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 ur(this,e,s,r)}whenReady(e={}){return e.signal===void 0?this.readyPromise:Mt(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,K(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=ie(e,s,r),a=this.hydratedQueryCache.get(i);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=x.key(e,s,r),a=this.subscriptions.get(i);return{present:a!==void 0,value:a?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,signal:r.signal})}async batch(e){return ne(this.rpcTimeoutMs,void 0,async s=>this.sendBatch(e,s))}async mutation(e,s,r={}){if(r.signal?.aborted)throw pe(r.signal);let{value:i}=await Mt(this.runMutation(e,s,r),r.signal);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,signal:r.signal,unbounded:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),a=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),p=d,{committed:f}=await this.runMutation(e,a(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(p)}`},shardKey:r.shardKey});d+=1,c+=l.length,f&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:d,imported:u,queued:c-u}}async shardTraffic(e){return Va(this.adminHost,e)}async listScheduledJobs(){return Xa(this.adminHost)}async schedulerStatus(){return Za(this.adminHost)}async cancelScheduledJob(e){return eo(this.adminHost,e)}async listDeadJobs(){return to(this.adminHost)}async retryDeadJob(e){return so(this.adminHost,e)}async removeDeadJob(e){return ro(this.adminHost,e)}async listWorkflowInstances(e){return io(this.adminHost,e)}async getWorkflowInstance(e){return no(this.adminHost,e)}async setWorkflowInstanceStatus(e){return ao(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=this.openSupplementarySocket(q(Lt(this.url),vn),{onMessage:n(r=>{let i;try{i=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(s.resetBackoff(),e(i.records.map(a=>rs(a))))},"onMessage")});return s.close}async listFunctions(){return Qa(this.adminHost)}async getCronJobs(){return _a(this.adminHost)}async runCronJob(e){return Da(this.adminHost,e)}async fetchOpenApi(){return Ua(this.adminHost)}async fetchArchitecture(){return Ka(this.adminHost)}async fetchOpenRpc(){return Na(this.adminHost)}async listStorageObjects(e={}){return oo(this.adminHost,e)}async deleteStorageObject(e,s){return co(this.adminHost,e,s)}async listStorageBuckets(){return uo(this.adminHost)}async uploadStorageObject(e){return ho(this.adminHost,e)}async signedStorageUrl(e,s){return lo(this.adminHost,e,s)}async listGlobalTables(){return qa(this.adminHost)}async readGlobalTablePage(e){return ja(this.adminHost,e)}async facetGlobalColumn(e){return Wa(this.adminHost,e)}async listVectorIndexes(){return po(this.adminHost)}async queryVectorIndex(e){return fo(this.adminHost,e)}async queryLogArchive(e={}){return Ja(this.adminHost,e)}async listKvNamespaces(){return Ba(this.adminHost)}async listKvKeys(e){return $a(this.adminHost,e)}async getKvValue(e){return Ha(this.adminHost,e)}async putKvValue(e){return za(this.adminHost,e)}async deleteKvKey(e){return Ga(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();let s=F(jn,{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(Bn,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch($n,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(Hn,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(zn,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(Gn,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(Vn,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(Jn,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(Yn,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(Xn,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(Zn,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(ea,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(F(ta,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(sa,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(F(ra,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(ia,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(na,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(F(aa,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();let s=F(oa,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.assertOpen();let s=F(ca,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();let s=F(la,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(pa,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(fa,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(ua,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(ha,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(da,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ma,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ya,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(ba,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(ga,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(va,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Sa,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();let s=F(wa,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Ca,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(ka,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(Ta,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();let s=F(Ea,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(Oa,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(Ia,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();let s=F(Ra,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Aa,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Fa,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Pa,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=F(Wn,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};let a=s??{},o=x.key(e.__lunoraRef,a,i.shardKey),c=this.subscriptions.get(o),u=tt(r),d=tt(i.onError),h=tt(i.onCheckpoint);if(!c){this.nextSubId+=1;let m=`sub_${this.nextSubId.toString()}`,y=K(a),v=this.takeHydratedCache(e.__lunoraRef,y,i.shardKey);c={acked:!1,args:a,argsKey:y,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:m,lastValue:v?.value,optimisticLayers:[],serverBase:v?.value,serverCursor:v?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:G(a,`args for '${e.__lunoraRef}'`),...v?.serverEpoch===void 0?{}:{serverEpoch:v.serverEpoch}},this.subscriptions.add(c),this.emitSyncStatus(),v!==void 0&&this.cacheSeededQueries.set(o,v)}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,p=!1,f=n(()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",f),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(x.keyOf(l)),this.subscriptions.remove(l);let m=this.getConnection(l.shardKey);m&&this.settleSubscribeWatchdog(m,l.id),this.releaseIdleShard(l.shardKey),this.emitSyncStatus()}},"f");return i.signal?.addEventListener("abort",f,{once:!0}),i.signal?.aborted&&f(),f}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()}`,a={answered:!1,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:G(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,a),this.emitSyncStatus(),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(a),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(a.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(a.shardKey),this.emitSyncStatus()}}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:a}=r,o=s??{},{handle:c,iterable:u}=Xe({maxBuffer:r.maxBuffer,onCancel:n(()=>{this.cancelStream(i,a)},"onCancel")});this.ensureSocket(a);let d=this.getConnection(a),h={id:i,query:{args:G(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:a},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:h,shardKey:a};this.streams.set(i,l);let p=d?.wsState==="open"&&j(d,h);if(!p&&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(!p){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=64;){let f=d.pendingStreams.shift()?.id,m=f?this.streams.get(f):void 0;m&&(m.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}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 er(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0;for(let e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=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(),this.supplementaryBounces.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.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.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=n(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())},5e3))}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,a]of this.streams)g(a.shardKey)===s&&(a.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,ye(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={activeShapes:n(()=>[...this.shapeSubscriptions.values()],"activeShapes"),activeSubscriptions:n(()=>this.subscriptions.all(),"activeSubscriptions"),broadcastStatus:n((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:n(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:n(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:n(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:n(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:n(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:n(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:n(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:n(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:n(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:n(()=>this.clientId,"clientIdentifier"),dropCacheSeed:n(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:n((r,i,a)=>{this.ackAndAdvanceCursor(r,i,a)},"ackAndAdvanceCursor"),subscription:n(r=>this.subscriptions.get(r),"subscription")};return new Je({channelName:e,onBecomeLeader:n(()=>{Qo(s)},"onBecomeLeader"),onStopBeingLeader:n(()=>{_o(s)},"onStopBeingLeader"),onConnectionStatus:n((r,i)=>{Do(s,r,i)},"onConnectionStatus"),onSubscriptionData:n((r,i,a,o,c)=>{Ko(s,r,i,a,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:n(()=>{Uo(s)},"onLeaderClaimAnswered"),onSubscriptionError:n((r,i,a)=>{No(s,r,i,a)},"onSubscriptionError"),onSubscriptionSettled:n((r,i,a,o,c,u)=>{qo(s,r,i,a,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(q(this.url,$t),{body:JSON.stringify({calls:e.map((c,u)=>({args:G(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 a;try{a=await r.json()}catch{throw new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let o=fe(a);if(!r.ok||o!==void 0&&!a.results)throw o!==void 0?Ie(o):new b("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let c of a.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return mo(a.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=Bo(e,r),a=s,o=i.mutationId??nt();this.mutationIssueCounter+=1;let c=this.mutationIssueCounter,u=this.takeReplayCredential(i.replayCredential),d=i.replayBaseline===void 0?this.baselineCursorFor(i.shardKey):i.replayBaseline??void 0;this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);let{confirms:h,rollbacks:l}=this.applyOptimisticUpdates(e.__lunoraRef,a,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,s,i.shardKey,l,h);let p=i.onlineOnly?void 0:this.offlineFlushes.get(g(i.shardKey));p!==void 0&&await p;let{httpFirst:f,midReconnect:m,shouldQueueOffline:y,socketDown:v}=this.writeQueueGate(i.shardKey),w=!i.onlineOnly&&y&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),T=n(async(S=!1)=>this.enqueueOfflineMutation(e,a,i.shardKey,d,o,l,h,S?void 0:i.precondition,i.mutationId,u?.stamp,S,c),"g");if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,l),v||m||w)return T();let I;try{let S=await this.rpc(e.__lunoraRef,a,i.shardKey,{baselineSeq:d,captureBookmark:!0,...u?.flags,mutationId:o,onCommitCursor:n(R=>{I=R},"onCommitCursor")});for(let R of h)R(I);return{committed:!0,value:S}}catch(S){let R=Go(S,a),V=f&&y&&R,Q=this.ownSocketOpen(i.shardKey);if(y&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(S instanceof TypeError||S instanceof D)&&Vt(a)){let k=T(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),k}throw this.settleFailedDirectWrite(S,I,h,l,u?.flags.authToken),Vo(i.onlineOnly,V,R,Q)?yr(e.__lunoraRef,S):S}}refuseOnlineOnlyWhenDown(e,s,r=[]){if(!s.onlineOnly)return;let i=this.writeQueueGate(s.shardKey);if(i.socketDown||i.midReconnect)throw ae(r),yr(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){let{hasSocket:s,idleClosed:r,polling:i,wasEverConnected:a,wsState:o}=this.connectionGateState(e),{queueBeforeFirstConnect:c}=this.offlineQueue,u=a||c,d=this.WebSocketImpl!==void 0&&u,h=i||r;return{httpFirst:h,midReconnect:o==="connecting"&&u&&!h,shouldQueueOffline:d,socketDown:o!=="open"&&!s&&d&&!h,socketOpen:o==="open"}}settleFailedDirectWrite(e,s,r,i,a){if(this.noteIdentityMismatch(e),a!==void 0&&this.noteReplayAuthRefusal(e,a),ot(e)){for(let o of r)o(s);return}ae(i)}async enqueueOfflineMutation(e,s,r,i,a,o,c,u,d,h,l,p){let f=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;let m=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(m)}`,identity:f,mutationId:m,...o.length>0&&{onRejected:n(()=>{ae(o)},"onRejected")},shardKey:r})}catch(y){throw ae(o),y instanceof Error?y:new Error(String(y))}for(let y of c)y(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,y)=>{let v={ambiguousSend:l,args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:a,issueSeq:p,clientId:this.clientId,identity:f,precondition:u,onCommit:n(w=>{for(let T of c)T(w)},"onCommit"),reject:n(w=>{this.queuedIdentities.delete(a),ot(w)||ae(o),y(w instanceof Error?w:new Error(String(w))),this.releaseIdleShard(r)},"reject"),resolve:m,shardKey:r};this.offlineQueue.enqueue(v),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),v.id!==void 0&&this.queuedIdentities.set(v.id,f)})}}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=n(()=>{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(ie(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(jt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let a=s.get(r);if(a&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(a,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(ie(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),re(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,re(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=ie(e,s,r),a=this.hydratedQueryCache.get(i);if(!(a===void 0||!this.cachedQueryMatchesIdentity(a)))return this.hydratedQueryCache.delete(i),a}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=ie(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=ie(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,a=i===void 0?this.identityFingerprint():i;a===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:a,serverCursor:e.serverCursor,ts:Date.now(),value:s,...a===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(()=>{})},250))}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)))}installPageHideFlush(){let e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;let s=n(()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},"t"),r=n(()=>{e.document?.visibilityState==="hidden"&&s()},"s");e.addEventListener("pagehide",s),e.document?.addEventListener("visibilitychange",r),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",s),e.document?.removeEventListener("visibilitychange",r)}}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&&(Vt(c.args)?r.push(c):(this.markQueryRejected(c,!0),Y(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=tr(),a=this.identityFingerprint(),o;try{o=await pr(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()!==a)return!0;for(let[c,u]of r.entries()){let d=o[c];if(d!==void 0){if(!d.ok){this.markQueryRejected(u,!0),Y(u.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:B(d.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await pr(async s=>e(q(this.url,$t),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;let e=this.syncStatus(),s=this.lastSyncStatus;s?.connection===e.connection&&s.pendingSubscriptions===e.pendingSubscriptions&&s.pendingWrites===e.pendingWrites&&s.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){let e=this.computeStatus();this.emitSyncStatus(),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 a=[],o=[];if(!i)return{confirms:a,rollbacks:o};let c=x.key(e,s,r),u=this.subscriptions.get(c);if(u){let d=Dt(u,i);d&&(a.push(d.confirm),o.push(d.rollback))}return{confirms:a,rollbacks:o}}applyOptionalOptimisticUpdate(e,s,r,i,a){e&&this.applyOptimisticUpdate(e,s,r,i,a)}applyOptimisticUpdate(e,s,r,i,a){let{confirms:o,rollbacks:c,store:u}=ir(this.subscriptions,r);try{e(u,s)}catch{ae(c);return}i.push(...c),a.push(...o)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!j(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:So({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:n(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:n(()=>{this.emitConnectionStatus()},"onStateChange"),poll:n(async()=>this.pollSubscriptions(e),"poll")}),reconnect:Oe(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}openSupplementarySocket(e,s){if(this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),resetBackoff:n(()=>{},"resetBackoff"),socket:n(()=>{},"socket")};let r=Oe(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},a,o=!1,c=n(()=>{o||this.closed||(a=setTimeout(h,r.next()))},"a"),u=n(f=>{o||this.WebSocketImpl===void 0||lr(i,this.wsUrlFor(s.shardKey,f,e),this.managedSocketOptions,{onClose:n(()=>{c(),s.onClose?.()},"onClose"),onMessage:s.onMessage,...s.onOpen===void 0?{}:{onOpen:s.onOpen}})},"c"),d=n(async f=>{let m=this.wsTokenGeneration,y;try{y=await f()}catch{c();return}if(m!==this.wsTokenGeneration){h();return}u(y)},"u"),h=n(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){d(f).catch(()=>{});return}u(f)},"d");h();let l=n(()=>{o=!0,a!==void 0&&(clearTimeout(a),a=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),ye(i);let{socket:f}=i;i.socket=void 0;try{f?.close()}catch{}},"h");this.adminSocketTeardowns.add(l);let p=n(()=>{let{socket:f}=i;if(f!==void 0){i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),ye(i);try{f.close()}catch{}s.onClose?.(),c()}},"p");return this.supplementaryBounces.add(p),{close:n(()=>{l(),this.adminSocketTeardowns.delete(l),this.supplementaryBounces.delete(p)},"close"),resetBackoff:n(()=>{r.reset()},"resetBackoff"),socket:n(()=>i.socket,"socket")}}supplementaryUrl(e){let s=xt(this.wsUrl),r=s.pathname.endsWith(Ht)?s.pathname.slice(0,-Ht.length):s.pathname;return s.pathname=q(r,e),Qt(s,this.wsUrl)}wsUrlFor(e,s,r=this.wsUrl){if(e===void 0&&s===void 0)return r;let i=xt(r),a=new Set([...e===void 0?[]:["shard"],...s===void 0?[]:["token"]]),o=[...i.searchParams].filter(([c])=>!a.has(c)).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);return e!==void 0&&o.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&o.push(`token=${encodeURIComponent(s)}`),i.search=o.join("&"),Qt(i,r)}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[nn]=an(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let a=e.authToken===void 0?this.authToken:e.authToken;if(a&&(r.authorization=`Bearer ${a}`),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={}){let{fetchImpl:a}=this;if(!a)throw new D("LunoraClient: no `fetch` implementation available");let o=this.rpcRequestHeaders(i,r),c=i.authToken===void 0?this.authToken:i.authToken,u=JSON.stringify({args:G(s,`args for '${e}'`),functionPath:e,shardKey:r}),{body:d,response:h}=await ne(i.unbounded?0:this.rpcTimeoutMs,i.signal,async f=>{let m=await a(q(this.url,mn),{body:u,headers:o,method:"POST",signal:f});try{return{body:await m.json(),response:m}}catch{return{body:void 0,response:m}}});if(i.captureBookmark){let f=h.headers.get("x-d1-bookmark");f&&this.bookmark.set(f)}if(d===void 0)throw Re(h.status,h.statusText,h.headers.get("retry-after"));let l=d;if(typeof l!="object"||l===null||Array.isArray(l))throw Re(h.status,h.statusText,h.headers.get("retry-after"));let p=fe(d);if(p!==void 0)throw qt(p,h.headers.get("retry-after"));if(!h.ok)throw Re(h.status,h.statusText,h.headers.get("retry-after"));i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(c),this.learnDefaultShardKey(h,r),this.recordShardCursor(r,d.commitCursor);try{return E(d.result)}catch(f){throw kr(f)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let a={};this.authToken&&(a.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&&(a["content-type"]=i)):(c=JSON.stringify(r),a["content-type"]="application/json");let u=await this.fetchImpl(q(this.url,e),{body:c,headers:a,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=fe(d);if(h!==void 0)throw Ie({...h,message:h.message??"admin request failed"});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));j(e,{caps:$o,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=this.wsTokenGeneration,a=Symbol("ws-token-attempt"),o;e.providerAttempt=a;try{o=await ne(this.connectTimeoutMs,void 0,async()=>r(),()=>new Error("LunoraClient: wsToken provider timed out"))}catch{e.providerAttempt===a&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===a&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(i!==this.wsTokenGeneration){typeof this.wsToken=="function"?await this.openSocketWithProvidedToken(e,s,this.wsToken):this.openSocket(e,s,this.wsToken);return}this.openSocket(e,s,o)}}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,lr(e,this.wsUrlFor(s,r),this.managedSocketOptions,{onClose:n(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:n(i=>{e.retired!==!0&&this.handleServerMessage(i.data,s)},"onMessage"),onOpen:n(()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},5e3),this.markShardPendingAck(s,!0),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.clearResubscribeQueue(e);for(let o of this.subscriptions.all())g(o.shardKey)===g(s)&&this.queueResubscribe(o);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let o=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:c,type:u}of o)j(e,{id:c,type:u});this.releaseIdleShard(s)}yo(e);let i=g(s),a=this.whisperHandlers.get(i);if(this.dropWhisperJoinWaiters(i),this.whisperJoins.set(i,new Map),a)for(let o of a.keys())this.sendWhisperJoin(e,i,o);e.roomsRejoined=!0,this.releaseRoomSends(s),this.flushOfflineQueue(s).catch(()=>{})},"onOpen")}))}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),j(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(),ye(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(g(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,a]of this.streams)if(!(g(a.shardKey)!==g(e.shardKey)||s.has(i))){if(a.durable){let o={...a.message,...a.generation===void 0?{}:{generation:a.generation},sinceChunk:a.lastSeq};a.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}a.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,s=!1){let r=g(e);for(let i of this.subscriptions.all())g(i.shardKey)===r&&(i.acked=!1,s&&(i.valueReceived=!1));for(let i of this.shapeSubscriptions.values())g(i.shardKey)===r&&(i.answered=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<3;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribeSlots.add(s.id)}}settleSubscribeWatchdog(e,s){clearTimeout(e.unackedWatchdogs.get(s)),e.unackedWatchdogs.delete(s),e.resubscribeSlots.delete(s)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(let s of e.unackedWatchdogs.values())clearTimeout(s);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,s=!1){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.acked)return!1;let i=e.serverCursor!==void 0&&e.serverBase!==void 0,a=j(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return a&&!s&&this.armUnackedWatchdog(r,e),a}armUnackedWatchdog(e,s){clearTimeout(e.unackedWatchdogs.get(s.id)),e.unackedWatchdogs.set(s.id,setTimeout(()=>{!s.acked&&this.subscriptions.getById(s.id)===s&&this.sendSubscribeIfOpen(s,!0),this.settleSubscribeWatchdog(e,s.id)},1e4))}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&j(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=go(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 a=this.getConnection(s);if(a){let{id:o}=i;this.settleSubscribeWatchdog(a,o)}}switch(i.type){case"ack":{let a=this.subscriptions.getById(i.id);a&&this.ackAndAdvanceCursor(a,void 0,void 0);return}case"chunk":{let{data:a,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(E(a));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),this.adoptSocketConnectionId(i,s),this.confirmShardIdentity(s);break}case"live":{this.dispatchLive(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}case"whisper_subscribed":{this.acknowledgeWhisperJoin(g(s),i.topic);break}}}handleErrorMessage(e){let s=e.error?.code;if(s==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(s==="STREAM_ID_IN_USE")return;let{id:r}=e,i=r===void 0?void 0:this.streams.get(r);if(i&&r!==void 0){i.handle.fail(ar(e)),this.forgetStream(r);return}let a=r===void 0?void 0:this.subscriptions.getById(r);if(a){let c=Nt(e),u=this.identityFingerprint(),d=x.keyOf(a);this.markQueryRejected(a),Y(a.errorCallbacks,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,c,u);return}let o=r===void 0?void 0:this.shapeSubscriptions.get(r);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),Y(o.errorCallbacks,Nt(e)))}markQueryRejected(e,s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){let r=s?"valueReceived":"acked";e[r]||(e[r]=!0,this.emitSyncStatus())}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){Mo(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let a=this.shapeSubscriptions.get(i);a&&!r.undecodable.has(i)&&this.applyPokePart(a,r,e)}}}applyPokePart(e,s,r){let i=e.answered,a=Po(e,s,r);if(e.answered!==i&&this.emitSyncStatus(),mr(e),a==="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,this.emitSyncStatus(),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||e.type==="data"&&Lo(i,e))return;let a;try{a=Js(e,i.serverBase)}catch(c){Y(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${c instanceof Error?c.message:String(c)}`});return}if(a===Ft){this.resnapshotSubscription(i);return}this.dropCacheSeed(x.keyOf(i));let o=s!==void 0&&!i.valueReceived;if(Tr(i,a,{cursor:e.cursor,epoch:e.epoch}),o&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(Xt(i,e.lastMutationId),Zt(i,!0)),this.persistQueryValue(i),st(i,i.serverCursor),s!==void 0&&rr(i,s),re(i,a),this.tabCoordinator?.isLeader()){let c=x.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(c,a,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&&Xt(s,e.lastMutationId),Zt(s),this.tabCoordinator?.isLeader())){let r=x.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){let i=!e.acked;e.acked=!0,i&&this.emitSyncStatus(),(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),st(e,e.serverCursor)&&re(e,e.serverBase))}adoptSocketConnectionId(e,s){let r=this.getConnection(s);if(!(r===void 0||typeof e.connectionId!="string")){r.connectionId=e.connectionId,r.whisperAck=e.whisperAck===!0;for(let i of this.liveSocketGrants.get(g(s))?.keys()??[])this.grantWhenJoined(s,i,e.connectionId)}}grantWhenJoined(e,s,r){let i=g(e),a=this.liveSocketGrants.get(i)?.get(s);if(a===void 0)return;let{stream:o,topic:c}=a,u=n(()=>{this.liveSocketGrants.get(i)?.get(s)===void 0||this.getConnection(e)?.connectionId!==r||this.postLiveControl(`/live/${o}/control`,e,{action:"subscribe",connectionId:r,stream:o,subscriptionId:s,topic:c},d=>{this.refuseLiveGrant(e,s,d,r)})},"c");this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,c,u):u()}sendWhisperJoin(e,s,r){let i=this.whisperJoinState(s,r);i.pending+=1,i.joined=!1,j(e,{topic:r,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,s){let r=this.whisperJoins.get(e)?.get(s);if(r!==void 0&&(r.pending=Math.max(0,r.pending-1),!(r.pending>0))){r.joined=!0;for(let i of r.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,s)}}releaseWhisperJoin(e,s){if(this.whisperHandlers.get(e)?.has(s)===!0)return;let r=this.whisperJoins.get(e),i=r?.get(s);if(!(r===void 0||i===void 0||i.pending>0)){for(let a of i.waiters.splice(0))clearTimeout(a.timer);r.delete(s),r.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,s,r){let i=this.whisperJoinState(e,s);if(i.joined){r();return}let a={run:r,timer:void 0};a.timer=setTimeout(()=>{i.waiters=i.waiters.filter(o=>o!==a),r()},Er),i.waiters.push(a)}dropWhisperJoinWaiters(e){for(let s of this.whisperJoins.get(e)?.values()??[])for(let r of s.waiters.splice(0))clearTimeout(r.timer)}whisperJoinState(e,s){let r=this.whisperJoins.get(e);r===void 0&&(r=new Map,this.whisperJoins.set(e,r));let i=r.get(s);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},r.set(s,i)),i}refuseLiveGrant(e,s,r,i){let a=g(e),o=this.liveSocketGrants.get(a),c=o?.get(s);o===void 0||c===void 0||this.getConnection(e)?.connectionId!==i||(o.delete(s),o.size===0&&this.liveSocketGrants.delete(a),c.release(),c.onError?.({status:r,topic:c.topic}))}postLiveControl(e,s,r,i){let{fetchImpl:a}=this;if(!a)return;let o=JSON.stringify(s===void 0?r:{...r,shardKey:s}),c=this.rpcRequestHeaders({},s);this.liveControlChain=this.liveControlChain.then(()=>zo(a,q(this.url,e),o,c)).then(u=>{u>=400&&u<500&&u!==404&&u!==401&&i?.(u)}).catch(()=>{})}dispatchLive(e,s){let r=this.liveSocketGrants.get(g(s));if(!r)return;let i=E(e.data);for(let a of r.values())if(!(a.stream!==e.stream||a.topic!==e.topic))try{a.onEvent(i)}catch{}}dispatchWhisper(e,s){let r=this.whisperHandlers.get(g(s))?.get(e.topic);if(!r)return;let i=E(e.data);for(let a of r)try{a(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,this.emitSyncStatus(),Y(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(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 a=e.charCodeAt(i);s^=a,s=Math.imul(s,16777619),r=Math.imul(r,33)+a}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&&at(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)}sendEncodedWhisper(e,s,r){this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey),a=i!==void 0&&j(i,{data:s,topic:e,type:"whisper"});return this.releaseIdleShard(r.shardKey),a}roomSendsAdmitted(e){let s=this.getConnection(e);return s?.wsState==="open"&&s.retired!==!0&&s.identityConfirmed===!0&&s.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(let s of this.roomFlushes.get(g(e))??[])s()}confirmShardIdentity(e){let s=this.getConnection(e);s!==void 0&&(s.identityConfirmed=!0),this.releaseRoomSends(e)}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 a=new Error("offline mutation discarded: auth identity changed before replay");a.code="OFFLINE_IDENTITY_CHANGED",i.reject(a),this.emitItemSettled(i,"rejected",a)}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 a=s??"",o=this.clientWatermarks.get(a);if(o===void 0)this.clientWatermarks.set(a,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.resetRoomSends(),this.revokeCacheSeededValues();for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,e.valueReceived=!1,re(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,mr(e);this.emitSyncStatus(),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()}resetRoomSends(){for(let e of this.roomIdentityResets)e()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}for(let e of this.supplementaryBounces)e()}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:a}=this;try{await this.drainOfflineQueue(e,a)}catch{}!this.closed&&this.authToken!==a&&this.offlineQueue.size>0&&at(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),a=this.offlineQueue.drain(h=>g(h.shardKey)===i);if(a.length===0)return;let o=[],c=[];for(let h of a){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+=Bt){let l=u.slice(h,h+Bt),p=await this.replayBatched(l,e,s);if(d.push(...p.requeue),p.stop||p.requeue.length>0){d.push(...u.slice(h+Bt));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,Jt(i))})}noteReplayRetryDelay(e,s,r){let i=g(e),a=this.replayRetryState.get(i),o=(a?.attempts??0)+1,c=Eo(s,o)??(r===null&&Ee(s)?Jt(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:c===void 0?a?.delayMs:Math.max(a?.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 a=this.replayRetryTimers.get(s);a!==void 0&&clearTimeout(a),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{G(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)||fr(e)}noteReplayAuthRefusal(e,s){if(!Ee(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,...zt(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)}spendsLastReplayAttempt(e,s){if(e.id===void 0)return!1;let r=s?.code;if(e.ambiguousSend!==!0||Ee(s)||r==="RATE_LIMITED"||r==="TOO_MANY_REQUESTS"||!fr(s))return!1;let i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=5}keepUnexhaustedAmbiguousWrites(e,s){return e.filter(r=>r.ambiguousSend===!0&&this.spendsLastReplayAttempt(r,s)?(this.settleReplayTerminal(r,s),!1):!0)}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 a=e[i];if(!a)continue;let o;try{let c=await this.rpc(a.functionPath,a.args,a.shardKey,{authToken:r,baselineSeq:a.baselineSeq,captureBookmark:!0,clientId:a.clientId??this.clientId,...zt(a.identity,r),mutationId:a.id,onCommitCursor:n(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(a,c,o)}catch(c){if(ot(c)){this.settleReplayUndecodable(a,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)||this.spendsLastReplayAttempt(a,c)){this.settleReplayTerminal(a,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((h,l)=>({args:G(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:l,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&Io(i)>Oo)return await this.replayBatchedHalves(e,s,r);let{fetchImpl:a}=this,o,c;try{({payload:c,response:o}=await ne(this.rpcTimeoutMs,void 0,async h=>{let l=await a(q(this.url,$t),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...zt(e.find(p=>p.identity!==void 0)?.identity,r)}),method:"POST",signal:h});if(l.status===413&&e.length>1)return{payload:void 0,response:l};try{return{payload:await l.json(),response:l}}catch{return{payload:void 0,response:l}}}))}catch(h){return this.noteReplayRetryDelay(s,h,r),{requeue:this.keepUnexhaustedAmbiguousWrites(e,h),stop:!0}}let u=o.headers.get("x-d1-bookmark");if(u&&this.bookmark.set(u),o.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let d=o.headers.get("retry-after");if(!c)return this.settleWholeBatchError(e,Re(o.status,o.statusText,d),s,r);if(!Array.isArray(c.results)){let h=fe(c),l=h===void 0?Re(o.status,o.statusText,d):qt(h,d);return this.settleWholeBatchError(e,l,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof D||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,s),stop:!0};for(let a of e)this.settleReplayTerminal(a,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),a=await this.replayBatched(e.slice(0,i),s,r);if(a.stop||a.requeue.length>0)return{requeue:[...a.requeue,...e.slice(i)],stop:!0};let o=await this.replayBatched(e.slice(i),s,r);return{requeue:[...a.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,s,r,i){let a=Ro(s),o=[],c=!1,u=!1;for(let[d,h]of e.entries()){let l=Ao(a.get(d));switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(h,l.value,l.commitCursor);break}case"errored":{u||=Ee(l.error),this.shouldRequeueReplayFailure(l.error,i)&&!this.spendsLastReplayAttempt(h,l.error)?(this.noteReplayRetryDelay(r,l.error,i),o.push(h)):this.settleReplayTerminal(h,l.error);break}case"unanswered":{let p=Kt();if(this.spendsLastReplayAttempt(h,p)){this.settleReplayTerminal(h,p);break}this.noteReplayRetryDelay(r,p,i),o.push(h);break}default:c=!0,this.settleReplayUndecodable(h,l.error,l.commitCursor)}}return c&&!u&&this.noteCredentialAccepted(i),o}};var Or=_(as(),1),Ir=_(ee(),1);var Yo=n(()=>{let t=(0,Or.c)(4),e=Ot(),s,r,i;return t[0]!==e?(s=n(a=>e.onConnectionStatus(()=>{a()}),"o"),r=n(()=>e.connectionStatus(),"e"),i=n(()=>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,Ir.useSyncExternalStore)(s,r,i)},"S");export{be as a,Me as b,B as c,E as d,Vr as e,es as f,ei as g,ve as h,hi as i,di as j,fi as k,Ot as l,Yo as m};
9
+ `)}return!1},"p"),l=n(()=>a.cancel().then(()=>{},()=>{}),"T");try{for(;;){let{done:p,value:f}=await Ys(a,i);if(p)break;if(d(o.decode(f,{stream:!0})),h())return await l(),!0}return d(o.decode()),h()}catch(p){throw r.abort(),l().catch(()=>{}),p}},"D"),qi=n(async(t,e)=>{e.aborted||await new Promise(s=>{let r,i=n(()=>{clearTimeout(r),s()},"s");r=setTimeout(()=>{e.removeEventListener("abort",i),s()},t),e.addEventListener("abort",i,{once:!0})})},"U"),ji=n((t,e)=>{if(typeof t!="object"||t===null)return;let{code:s,error:r,why:i}=t;if(!(typeof s!="string"||typeof r!="string"))return new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${e.toString()}, ${s}): ${r}`,{status:e,why:typeof i=="string"?i:void 0})},"J"),Wi=n(async(t,e)=>{let s,r=new Promise(a=>{s=setTimeout(()=>{a(void 0)},_i)}),i=t.json().catch(a=>{if(e.aborted)throw a});try{return await Promise.race([i,r])}finally{clearTimeout(s),await t.body?.cancel().catch(()=>{})}},"Y"),Bi=n((t,e)=>{let s=Object.entries(t??{}).filter(([r])=>e===void 0||r.toLowerCase()!=="last-event-id");return{accept:"text/event-stream",...Object.fromEntries(s),...e===void 0?{}:{"last-event-id":e}}},"q"),Zs=n(t=>t instanceof Error&&"code"in t?t:new b("HTTP_STREAM_TRANSPORT",t instanceof Error?t.message:String(t),{cause:t}),"A"),er=n((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=Ui(t,e??{},s.baseUrl??""),a=new AbortController,o;s.signal&&(s.signal.aborted?a.abort():(o=n(()=>{a.abort()},"c"),s.signal.addEventListener("abort",o,{once:!0})));let c=n(()=>{o&&s.signal?.removeEventListener("abort",o)},"m"),{handle:u,iterable:d}=Xe({maxBuffer:s.maxBuffer,onCancel:n(()=>{a.abort()},"onCancel"),onFail:n(()=>{a.abort()},"onFail")}),h=s.reconnect??!1,l=Oe(),{lastEventId:p}=s,f,m=0,y=n(()=>{l.reset(),m=0},"M"),v={},w=n(S=>{try{S()}catch(R){throw v.value={error:R},R}},"R"),T={onFrame:y,onId:n(S=>{w(()=>s.onEventId?.(S)),p=S},"onId"),onRetry:n(S=>{w(()=>s.onRetry?.(S)),f=S},"onRetry")},I=n(async()=>{let S=Bi(s.headers,p),R=new b("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"),V=new AbortController,Q=n(()=>{V.abort()},"g");a.signal.addEventListener("abort",Q,{once:!0});try{let k=await r(i,{headers:S,method:t.method,signal:V.signal});if(!k.ok){let W=await Wi(k,a.signal);u.fail(ji(W,k.status)??new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${k.status.toString()})`,{status:k.status}));return}if(!k.body){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}return{completed:await Ni(k.body,u,T,V,s.idleTimeoutMs),error:R}}catch(k){if(a.signal.aborted){u.complete();return}if(v.value){let{error:W}=v.value;u.fail(W instanceof Error?W:new b("HTTP_STREAM_CALLBACK","httpStream: an onEventId/onRetry callback threw"));return}return{completed:!1,error:Zs(k)}}finally{a.signal.removeEventListener("abort",Q)}},"O");return(async()=>{try{for(;;){if(a.signal.aborted){u.complete();return}let S=await I();if(!S)return;if(S.completed||!h||m>=Qi){S.completed||u.fail(S.error);return}m+=1,await qi(f??l.next(),a.signal)}}finally{c()}})().catch(S=>{if(a.signal.aborted){u.complete();return}u.fail(Zs(S))}),d},"V");var et=n(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"a"),Lt=n(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"h"),q=n((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"$"),F=n((t,e)=>{let s=new URLSearchParams;for(let[i,a]of Object.entries(e))a!==void 0&&a!==""&&s.set(i,String(a));let r=s.toString();return r===""?t:`${t}?${r}`},"d"),$i="http://same-origin.invalid",xt=n(t=>new URL(t,$i),"p"),Hi=/^[a-z][a-z\d+.-]*:/iu,Qt=n((t,e)=>{if(Hi.test(e))return t.toString();let s=`${t.pathname}${t.search}${t.hash}`;return e.startsWith("//")?`//${t.host}${s}`:s},"S");var x=class t{static{n(this,"t")}static key(e,s,r){return`${e}::${K(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 tt(t){if(t!==void 0)return e=>{t(e)}}n(tt,"b");var Y=n((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var _t=0,tr=n(()=>_t,"h"),zi=n((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),sr=n((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),re=n((t,e)=>{sr(t,zi(e,t.optimisticLayers))},"y"),Dt=n((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),sr(t,s);let a=n(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),o=n(()=>{re(t,t.serverBase)},"s");return{confirm:n(c=>{if(c===void 0){a();return}r.commitCursor=c,_t+=1,r.acknowledgedAt=_t,t.serverCursor!==void 0&&t.serverCursor>=c&&a()&&o()},"confirm"),rollback:n(()=>{i||(i=!0,a(),o())},"rollback")}},"g"),st=n((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"),rr=n((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),ae=n(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),ir=n((t,e)=>{let s=[],r=[],i=n((a,o)=>t.get(x.key(a,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:n(a=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===a.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:n((a,o)=>i(a.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:n((a,o,c)=>{let u=i(a.__lunoraRef,o??{});if(!u)return;let d=Dt(u,()=>c);d&&(s.push(d.confirm),r.push(d.rollback))},"setQuery")}}},"_");var Ut=n(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"),Gi=n((t,e)=>{let s=Ut(e);if(!(s===void 0||Ye(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"),fe=n(t=>{let e=t?.error;if(typeof e!="object"||e===null||Array.isArray(e))return;let{why:s,...r}=e;return typeof s=="string"?{...r,why:s}:r},"l"),Kt=n(()=>new D("LunoraClient: batch slot carried no error envelope"),"p"),nr=n((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}},"n"),ar=n(t=>{let{code:e,messageText:s}=nr(t,"stream error"),r=t.error?.why,i=e===void 0?new Error(s):new b(e,s);return typeof r=="string"&&(i.why=r),i},"h"),Nt=n(t=>{let{code:e,messageText:s}=nr(t,"subscription error"),r=t.error?.why;return{message:s,...e===void 0?{}:{code:e},...typeof r=="string"?{why:r}:{}}},"w"),Vi=Symbol.for("lunora.serverVerdict"),Ie=n(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,e[Vi]=!0,t.data!==void 0)try{e.data=E(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),typeof t.why=="string"&&(e.why=t.why),e},"i"),qt=n((t,e)=>{let s=Ie(t),r=Gi(s,e);return r!==void 0&&(s.data=r),s},"b"),rt=n(t=>{let e=fe(t);return e===void 0?Kt():Ie(e)},"A");var or=0,Ji=n(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();or+=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)}_${or.toString(36)}_${t}`},"d"),jt=n((t,e)=>t!==void 0&&e!==t,"f"),nt=Ji,me=n((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)},"h"),it=class{static{n(this,"p")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;onReplayingChange;version;items=[];replayingIds=new Set;appending=new Map;unsettled=new Map;unpersisted=new Set;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.onReplayingChange=s.onReplayingChange,this.version=s.version}get size(){return this.items.length}get replaying(){return this.replayingIds.size}enqueue(e){let s=e;s.id??=nt();let r=this.items.length;for(;s.issueSeq!==void 0&&r>0&&(this.items[r-1]?.issueSeq??-1)>s.issueSeq;)r-=1;this.items.splice(r,0,s),this.unsettled.set(s.id,s),this.persist(this.recordOf(s,s.id)),this.evictOverflow(),this.notifySize()}discard(e){this.unsettled.delete(e),this.unpersisted.delete(e),this.replayingIds.delete(e)&&this.onReplayingChange?.();let{persistence:s}=this;s&&(this.appending.get(e)??Promise.resolve()).then(async()=>s.remove(e)).catch(r=>{me(this.onPersistenceError,"remove",r,e)})}flushUnpersisted(){for(let e of this.unpersisted){let s=this.unsettled.get(e);s&&!this.appending.has(e)&&this.persist(this.recordOf(s,e))}}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw me(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(jt(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{me(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:n(()=>{},"reject"),resolve:n(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),a=new Set;for(let o of s)i.has(o)&&a.add(o.shardKey);return[...a]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;!this.persistence||i===void 0||this.rewriteStamp(i,this.recordOf(r,i)).catch(a=>{me(this.onPersistenceError,"replace",a,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.markReplaying(i),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.markReplaying(s),this.notifySize(),s}requeue(e){if(e.length!==0){for(let s of e)s.id!==void 0&&this.replayingIds.delete(s.id);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 new Set([...this.items,...this.unsettled.values()])){let s=new Error("CLIENT_CLOSED"),r=e.id??"",i=n(o=>{s.code="CLIENT_CLOSED",s.persisted=o,e.reject(s)},"s"),a=this.appending.get(r);this.replayingIds.has(r)?i(!1):a===void 0?i(this.persistence!==void 0&&!this.unpersisted.has(r)):a.catch(()=>!1).then(i).catch(()=>{})}this.items.length=0,this.replayingIds.clear(),this.unsettled.clear(),this.unpersisted.clear(),this.notifySize()}recordOf(e,s){return{args:e.args,...e.baselineSeq===void 0?{}:{baselineSeq:e.baselineSeq},clientId:e.clientId,functionPath:e.functionPath,id:s,identity:e.identity,shardKey:e.shardKey,...this.version===void 0?{}:{version:this.version}}}persist(e){let{persistence:s}=this;if(!s)return;let r=(async()=>{try{return await s.append(e),this.unpersisted.delete(e.id),!0}catch(i){return this.unsettled.has(e.id)&&this.unpersisted.add(e.id),me(this.onPersistenceError,"append",i,e.id),!1}})();this.appending.set(e.id,r),r.finally(()=>{this.appending.get(e.id)===r&&this.appending.delete(e.id)}).catch(()=>{})}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await this.appending.get(e),await r.replace(s)}catch(i){me(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.discard(e.id);let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}markReplaying(e){for(let s of e)s.id!==void 0&&this.replayingIds.add(s.id)}notifySize(){this.onSizeChange?.(this.items.length)}};var Yi="lunora-outbox",Xi="offline-mutations",Wt="by_id",Zi=n((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??Xi,i=ze(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(Wt,"id",{unique:!0})}),a=Ge(i,r);return{append:n(async o=>{await a("readwrite",c=>L(c.add(o)))},"append"),clear:n(async()=>{await a("readwrite",o=>L(o.clear()))},"clear"),load:n(async()=>a("readonly",o=>L(o.getAll())),"load"),remove:n(async o=>{await a("readwrite",async c=>{let u=await L(c.index(Wt).getKey(o));u!==void 0&&await L(c.delete(u))})},"remove"),replace:n(async o=>{await a("readwrite",async c=>{let u=await L(c.index(Wt).getKey(o.id));u!==void 0&&await L(c.put(o,u))})},"replace")}},"w"),cr=n((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return Zi()}},"b");var ur=n((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),a=i.present?K(i.value):void 0;return()=>{let o=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!o.present?!0:K(o.value)===a}},"c");var Bt=500,br=n((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Ae"),X="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",tn=n(t=>{let e="",s=0,r=t.length-2;for(;s<r;s+=3){let a=t[s]<<16|t[s+1]<<8|t[s+2];e+=X.charAt(a>>18&63)+X.charAt(a>>12&63)+X.charAt(a>>6&63)+X.charAt(a&63)}let i=t.length-s;if(i===1){let a=t[s]<<16;e+=X.charAt(a>>18&63)+X.charAt(a>>12&63)}else if(i===2){let a=t[s]<<16|t[s+1]<<8;e+=X.charAt(a>>18&63)+X.charAt(a>>12&63)+X.charAt(a>>6&63)}return e},"gt");new TextDecoder;var sn=new TextEncoder,rn=n(t=>tn(sn.encode(JSON.stringify(t))),"kt"),nn="x-lunora-expect-subject",an=n(t=>rn({subject:t}),"Ct"),hr=Symbol.for("lunora:session-change"),on="lunora:session-change",cn="better-auth.message",un="signout",gr=n(()=>{let t=globalThis,e=t[hr];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[hr]=e),e},"_e"),hn=n(()=>"document"in globalThis,"It"),dn=n(async()=>{let t=[];for(let e of gr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"Ot"),ln=n((t,e)=>{if(t!==cn||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===un}catch{return!1}},"Rt"),pn=n(t=>{let e=[],s=n(()=>{dn().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(on):void 0}catch{r=void 0}if(r!==void 0){let a=r;a.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==t&&s()}),e.push(()=>{a.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let a=n(o=>{ln(o.key,o.newValue)&&s()},"r");i.addEventListener("storage",a),e.push(()=>{i.removeEventListener?.("storage",a)})}return()=>{for(let a of e)a()}},"Pt"),fn=n(t=>{let e=gr();return e.listeners.add(t),e.detach===void 0&&hn()&&(e.detach=pn(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"Ft"),mn="/_lunora/rpc",$t="/_lunora/rpc-batch",Ht="/_lunora/ws",yn="/_lunora/admin/shard-traffic",bn="/_lunora/admin/scheduled",gn="/_lunora/admin/scheduled/status",vn="/_lunora/admin/scheduled/ws",Sn="/_lunora/admin/scheduled/cancel",dr="/_lunora/admin/scheduled/dead",wn="/_lunora/admin/scheduled/dead/retry",Cn="/_lunora/admin/scheduled/dead/cancel",kn="/_lunora/admin/workflows/instances",Tn="/_lunora/admin/workflows/instance",En="/_lunora/admin/workflows/status",ts="/_lunora/admin/storage",On="/_lunora/admin/storage/url",In="/_lunora/admin/storage/buckets",Rn="/_lunora/admin/functions",An="/_lunora/admin/cron-jobs",Fn="/_lunora/admin/cron-jobs/run",Pn="/_lunora/admin/architecture",Mn="/_lunora/admin/openapi",Ln="/_lunora/admin/openrpc",xn="/_lunora/admin/global/tables",Qn="/_lunora/admin/global/table",_n="/_lunora/admin/global/facet",Dn="/_lunora/admin/vector/indexes",Un="/_lunora/admin/vector/query",Kn="/_lunora/admin/logs/archive",Nn="/_lunora/admin/kv/namespaces",qn="/_lunora/admin/kv/keys",ss="/_lunora/admin/kv/value",jn="/_lunora/admin/auth/users",Wn="/_lunora/admin/auth/sessions",Bn="/_lunora/admin/auth/users/create",$n="/_lunora/admin/auth/users/role",Hn="/_lunora/admin/auth/users/ban",zn="/_lunora/admin/auth/users/unban",Gn="/_lunora/admin/auth/users/password",Vn="/_lunora/admin/auth/users/remove",Jn="/_lunora/admin/auth/users/impersonate",Yn="/_lunora/admin/auth/sessions/revoke",Xn="/_lunora/admin/auth/sessions/revoke-all",Zn="/_lunora/admin/auth/capabilities",ea="/_lunora/admin/auth/users/update",ta="/_lunora/admin/auth/accounts",sa="/_lunora/admin/auth/accounts/unlink",ra="/_lunora/admin/auth/passkeys",ia="/_lunora/admin/auth/passkeys/delete",na="/_lunora/admin/auth/two-factor/disable",aa="/_lunora/admin/auth/organizations",oa="/_lunora/admin/auth/organizations/members",ca="/_lunora/admin/auth/organizations/invitations",ua="/_lunora/admin/auth/organizations/members/remove",ha="/_lunora/admin/auth/organizations/invitations/cancel",da="/_lunora/admin/auth/config",la="/_lunora/admin/auth/sign-up-invitations",pa="/_lunora/admin/auth/sign-up-invitations/create",fa="/_lunora/admin/auth/sign-up-invitations/revoke",ma="/_lunora/admin/auth/organizations/create",ya="/_lunora/admin/auth/organizations/update",ba="/_lunora/admin/auth/organizations/remove",ga="/_lunora/admin/auth/organizations/members/add",va="/_lunora/admin/auth/organizations/members/invite",Sa="/_lunora/admin/auth/organizations/members/role",wa="/_lunora/admin/auth/organizations/teams",Ca="/_lunora/admin/auth/organizations/teams/create",ka="/_lunora/admin/auth/organizations/teams/update",Ta="/_lunora/admin/auth/organizations/teams/remove",Ea="/_lunora/admin/auth/organizations/teams/members",Oa="/_lunora/admin/auth/organizations/teams/members/add",Ia="/_lunora/admin/auth/organizations/teams/members/remove",Ra="/_lunora/admin/auth/organizations/roles",Aa="/_lunora/admin/auth/organizations/roles/create",Fa="/_lunora/admin/auth/organizations/roles/update",Pa="/_lunora/admin/auth/organizations/roles/remove",Ma="/api/auth",La="/get-session",xa="lunora-ping",Qa=n(async t=>(t.assertOpen(),(await t.adminFetch(Rn,"GET")).functions??[]),"Zs"),_a=n(async t=>(t.assertOpen(),(await t.adminFetch(An,"GET")).jobs??[]),"ei"),Da=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Fn,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"ti"),Ua=n(async t=>(t.assertOpen(),await t.adminFetch(Mn,"GET")),"si"),Ka=n(async t=>(t.assertOpen(),await t.adminFetch(Pn,"GET")),"ii"),Na=n(async t=>(t.assertOpen(),await t.adminFetch(Ln,"GET")),"ni"),qa=n(async t=>(t.assertOpen(),await t.adminFetch(xn,"GET")),"ri"),ja=n(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(B(e.filters))),E(await t.adminFetch(`${Qn}?${s.toString()}`,"GET"))},"oi"),Wa=n(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(B(e.filters))),E(await t.adminFetch(`${_n}?${s.toString()}`,"GET"))},"ai"),Ba=n(async t=>(t.assertOpen(),(await t.adminFetch(Nn,"GET")).namespaces??[]),"ci"),$a=n(async(t,e)=>{t.assertOpen();let s=F(qn,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"di"),Ha=n(async(t,e)=>{t.assertOpen();let s=F(ss,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"ui"),za=n(async(t,e)=>{t.assertOpen(),await t.adminFetch(ss,"PUT",e)},"hi"),Ga=n(async(t,e)=>{t.assertOpen();let s=F(ss,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"li"),Va=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(yn,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"fi"),Ja=n(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(Kn,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"pi"),Ya=n(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}},"mi"),rs=n(t=>"args"in t?{...t,args:E(t.args)}:t,"ae"),Xa=n(async t=>(t.assertOpen(),((await t.adminFetch(bn,"GET")).records??[]).map(e=>rs(e))),"yi"),Za=n(async t=>{t.assertOpen();let e=await t.adminFetch(gn,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"Si"),eo=n(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(Sn,"POST",{id:e})).cancelled===!0}),"bi"),to=n(async t=>(t.assertOpen(),(await Ya(async e=>await t.adminFetch(e===void 0?dr:`${dr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>rs(e))),"vi"),so=n(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(wn,"POST",{id:e})).retried===!0}),"gi"),ro=n(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(Cn,"POST",{id:e})).removed===!0}),"Ti"),io=n(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(`${kn}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"ki"),no=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${Tn}?${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??[]}},"wi"),ao=n(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(En,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"Ci"),oo=n(async(t,e={})=>{t.assertOpen();let s=F(ts,{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??[]}},"Ei"),co=n(async(t,e,s)=>{t.assertOpen();let r=`${ts}?key=${encodeURIComponent(e)}${et(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"Ai"),uo=n(async t=>(t.assertOpen(),(await t.adminFetch(In,"GET")).buckets??[]),"_i"),ho=n(async(t,e)=>{t.assertOpen();let s=`${ts}?key=${encodeURIComponent(e.key)}${et(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"Ii"),lo=n(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,a=`${On}?key=${encodeURIComponent(e)}${i}${et(s?.bucket)}`,o=await t.adminFetch(a,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},"Oi"),po=n(async t=>(t.assertOpen(),(await t.adminFetch(Dn,"GET")).indexes??[]),"Ri"),fo=n(async(t,e)=>(t.assertOpen(),(await t.adminFetch(Un,"POST",e)).matches??[]),"Pi"),G=n((t,e)=>{try{return B(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)}},"E"),Vt=n(t=>{try{return B(t),!0}catch{return!1}},"ee"),vr=n(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Ie"),mo=n((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(!vr(r.body)){s[r.id]={error:rt({}),ok:!1};continue}let i=r.body;s[r.id]="error"in i?{error:rt(i),ok:!1}:{ok:!0,value:E(i.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"Fi"),zt=n((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"J"),at=n(t=>t==="connected"||t==="polling","q"),g=n(t=>t??"","l"),j=n((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"k"),yo=n(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)j(t,s)},"Li"),bo=new TextDecoder,go=n(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return bo.decode(t)},"Hi"),Z=class{static{n(this,"R")}listeners=new Set;get size(){return this.listeners.size}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()}},ye=n(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"H"),vo=n((t,e,s)=>{ye(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(xa)}catch{}},e))},"Ui"),lr=n((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:a,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=n(()=>{ye(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),d=n(h=>{u(),r.onClose(h)},"u");a>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}d()}},a)),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)}t.socket===c&&vo(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()})},"Te"),So=n(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:a}=t,o=s>0&&e>0,c=0,u,d=!1,h=!1,l=n(()=>{u!==void 0&&(clearInterval(u),u=void 0,d=!1,i())},"h"),p=n(m=>{if(u!==void 0){if(!m){l();return}d||(d=!0,i()),r()}},"p"),f=n(()=>{h||(h=!0,a().then(p).finally(()=>{h=!1}).catch(()=>{}))},"f");return{isPolling:n(()=>u!==void 0&&d,"isPolling"),noteFailedOpen:n(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(f,s),i(),f())},"noteFailedOpen"),noteOpen:n(()=>{c=0,l()},"noteOpen"),stop:l}},"Ni"),wo=1e4,pr=n(async t=>ne(wo,void 0,t,()=>new TypeError("LunoraClient: poll timed out")),"ke"),Sr=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),fr=n(t=>{if(t instanceof D)return!0;let e=t?.code;return e===void 0||Sr.has(e)||Pt.has(e)},"we"),Co=1e3,wr=6e4,ko={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Re=n((t,e,s)=>{let r=Ut(s),i=r===void 0?void 0:{retryAfterMs:r},a=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new D(a,i):new b(ko[t]??"BAD_REQUEST",a,{data:i})},"D"),Jt=n((t,e=Math.random)=>{let s=Math.min(Co*2**Math.max(t-1,0),wr);return Math.round(s*(.5+e()*.5))},"te"),To=n(t=>{let e=t?.code;return t instanceof D||e===void 0||Sr.has(e)},"Bi"),Eo=n((t,e,s)=>{let r=Ye(t);return r!==void 0&&r>0?Math.min(r,wr):To(t)?Jt(e,s):void 0},"Qi"),Oo=983040,Io=n(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Ki"),Cr=new WeakSet,kr=n(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 Cr.add(e),e},"Fe"),ot=n(t=>t instanceof Error&&Cr.has(t),"K"),Ro=n(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&vr(s.body)&&e.set(s.id,s.body);return e},"Gi"),Ao=n(t=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:rt(t),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:E(t.result)}}catch(e){return{commitCursor:t.commitCursor,error:kr(e),kind:"undecodable"}}},"ji"),Gt=n((t,e)=>`${g(t)}\0${e}`,"Y"),Fo=n((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"$i"),Yt=class{static{n(this,"Vi")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){br(this.buffers,this.maxBuffers),this.buffers.set(Gt(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(Gt(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:E(c.value)})}catch(c){r.undecodable.set(s.shapeId,c);return}let a=r.parts.get(s.shapeId)??[];for(let c of i)a.push(c);r.parts.set(s.shapeId,a),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=Gt(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},Po=n((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),a=e.bases.get(t.id),o=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=a!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==a;if(!i&&(o||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,t.answered=!1,"reseed";i&&t.rows.clear(),Fo(t.rows,r),t.answered=!0,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"},"zi"),mr=n(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"Ce"),Mo=n((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&Y(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"Ji"),Xt=n((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"se"),Zt=n((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"ie"),Tr=n((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Le"),Lo=n((t,e)=>e.cursor!==void 0&&t.serverCursor!==void 0&&t.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===t.serverEpoch&&e.cursor<t.serverCursor,"Yi"),ct=n((t,e)=>t!==void 0&&t!==e,"G"),xo=n((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","Xi"),Qo=n(t=>{for(let e of t.activeSubscriptions())e.valueReceived=!1,t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.activeShapes())e.answered=!1,t.ensureSocket(e.shardKey);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint()),t.emitConnectionStatus()},"Zi"),_o=n(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1;for(let s of t.activeSubscriptions())s.acked=!1,s.valueReceived=!1;for(let s of t.activeShapes())s.answered=!1;t.emitConnectionStatus()},"en"),Do=n((t,e,s)=>{if(ct(s,t.identityFingerprint()))return;let r=t.leader,i=xo(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&t.flushOfflineQueues()},"tn"),Uo=n(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"sn"),Ko=n((t,e,s,r,i,a)=>{if(ct(a,t.identityFingerprint()))return;let o=t.subscription(e);if(!o)return;t.dropCacheSeed(e);let c=!o.valueReceived;o.valueReceived=!0,Tr(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&st(o,r),re(o,s),c&&t.emitConnectionStatus()},"nn"),No=n((t,e,s,r)=>{if(ct(r,t.identityFingerprint()))return;let i=t.subscription(e);if(i){let a=!i.valueReceived;i.valueReceived=!0,Y(i.errorCallbacks,s),a&&t.emitConnectionStatus()}},"rn"),qo=n((t,e,s,r,i,a,o)=>{if(ct(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&a===t.clientIdentifier()&&Xt(c,i),Zt(c))},"on"),jo=n((t,e,s)=>t!==null||e&&s===null,"an"),Wo=n(t=>t.sensitive===!0,"cn"),Bo=n((t,e)=>{if(!Wo(t))return e;if(e.onlineOnly===!1)throw new b("BAD_REQUEST",`'${t.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},"dn"),$o=[Vs],Ho=100,Er=1e4,zo=n(async(t,e,s,r)=>{let i=new AbortController,a=setTimeout(()=>{i.abort()},Er);try{let o=await t(e,{body:s,credentials:"include",headers:r,method:"POST",signal:i.signal});return await o.text(),o.status}finally{clearTimeout(a)}},"ln"),yr=n((t,e)=>new b("OFFLINE_NOT_QUEUED",`'${t}' is online-only and the connection is not live, so it was not queued`,{cause:e}),"Ee"),Go=n((t,e)=>t instanceof TypeError&&Vt(e),"fn"),Vo=n((t,e,s,r)=>e||t===!0&&s&&!r,"pn"),Jo=Promise.resolve(),es=class t{static{n(this,"He")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:n((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:n(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;wsTokenGeneration=0;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new x;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 Z;statusListeners=new Z;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new Z;identityChangeListeners=new Z;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new Z;pendingChangeListeners=new Z;syncStatusListeners=new Z;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Yt(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??q(Lt(e.url),Ht),this.wsToken=e.wsToken;let s=e.authBasePath??Ma;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??zs(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??3e4,this.connectTimeoutMs=e.connectTimeoutMs??1e4,this.rpcTimeoutMs=e.rpcTimeoutMs??3e4,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??5e3,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??3,this.defaultConnectionContext=e.connectionContext,this.persistence=cr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Hs(e.queryCache),this.clientQueryStore=new Ve,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=Jo),this.offlineQueue=new it(e.offlineQueue,{onEvict:n((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onReplayingChange:n(()=>{this.emitSyncStatus()},"onReplayingChange"),onSizeChange:n(r=>{this.pendingChangeListeners.emit(r),this.emitSyncStatus()},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${nt()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=fn(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),a=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&&a?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&a&&!c?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(u,e),jo(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(d!==i||r||o)&&this.offlineQueue.size>0&&at(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 a=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:n(h=>{c=h},"onMutationAck")})}catch(h){if(!ot(h))throw h;d=h}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(a)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(br(this.clientWatermarks,8),h=new Map,this.clientWatermarks.set(o??"",h)),h.set(a,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(q(this.url,`${this.authBasePath}${La}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let a=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,a,r),a}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.wsTokenGeneration+=1,this.resetRoomSends(),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},a=this.connectionContextHolders.get(r);a?a.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),a=this.whisperHandlers.get(i);a||(a=new Map,this.whisperHandlers.set(i,a));let o=a.get(e),c=o===void 0;if(o||(o=new Set,a.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&this.sendWhisperJoin(u,i,e)}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&&j(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(r.shardKey)}}subscribeLiveTopic(e){let{onError:s,onEvent:r,shardKey:i,stream:a,topic:o}=e;if(o.length===0)throw new b("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;let c=`ws-live-${String(this.nextLiveSocketId)}`,u=g(i),d=`/live/${a}/control`,h=this.whisperSubscribe(o,()=>{},{shardKey:i}),l=n(()=>{let y=h;h=void 0,y?.()},"p"),p=this.liveSocketGrants.get(u);p===void 0&&(p=new Map,this.liveSocketGrants.set(u,p)),p.set(c,{onError:s,onEvent:r,release:l,stream:a,topic:o});let f=this.getConnection(i)?.connectionId;f!==void 0&&this.grantWhenJoined(i,c,f);let m=!1;return()=>{if(m)return;m=!0;let y=this.liveSocketGrants.get(u),v=y?.delete(c)===!0;y?.size===0&&this.liveSocketGrants.delete(u);let w=this.getConnection(i)?.connectionId;v&&w!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:w,stream:a,subscriptionId:c,topic:o}),l()}}whisper(e,s,r={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,G(s??null,`whisper data for topic '${e}'`),r)}connectRoom(e,s,r={}){let i=`room:${e.name}`,a=this.whisperSubscribe(i,p=>{s.onMessage(p)},r),o=!1,c=[],u=n(()=>{c.length=0},"c"),d=n(()=>{for(;c.length>0&&this.roomSendsAdmitted(r.shardKey);){if(!this.sendEncodedWhisper(i,c[0],r))return;c.shift()}},"u"),h=g(r.shardKey),l=this.roomFlushes.get(h)??new Set;return l.add(d),this.roomFlushes.set(h,l),this.roomIdentityResets.add(u),{close:n(()=>{o=!0,c.length=0,l.delete(d),l.size===0&&this.roomFlushes.delete(h),this.roomIdentityResets.delete(u),a()},"close"),send:n(p=>{if(o||this.closed||this.WebSocketImpl===void 0)return!1;let f=G(p,`room message for '${i}'`),m=typeof structuredClone=="function"?structuredClone(f):JSON.parse(JSON.stringify(f));return d(),c.length===0&&this.roomSendsAdmitted(r.shardKey)&&this.sendEncodedWhisper(i,m,r)?!0:c.length>=Ho?!1:(c.push(m),!0)},"send")}}connectWebSocket(e,s,r={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),send:n(()=>{},"send")};let i=n(c=>{try{c?.()}catch(u){console.error("[lunora] socket route handler threw",u)}},"i"),a,o=this.openSupplementarySocket(this.supplementaryUrl(e),{onClose:n(()=>{clearTimeout(a),i(s.onClose)},"onClose"),onMessage:n(c=>{let u;try{u=JSON.parse(typeof c.data=="string"?c.data:"")}catch{return}u.type==="message"&&(o.resetBackoff(),i(()=>{s.onMessage(E(u.data))}))},"onMessage"),onOpen:n(()=>{clearTimeout(a);let c=o.socket();a=setTimeout(()=>{o.socket()===c&&o.resetBackoff()},5e3),i(s.onOpen)},"onOpen"),shardKey:r.shardKey});return{close:n(()=>{clearTimeout(a),o.close()},"close"),send:n(c=>{let u=JSON.stringify(G(c,`socket message for '${e}'`)),d=o.socket();if(d!==void 0)try{d.send(u)}catch{}},"send")}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}syncStatus(){let e=this.computeStatus(),s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader(),r=0;for(let a of this.subscriptions.all())(s||this.connectionGateState(a.shardKey).polling?a.valueReceived:a.acked)||(r+=1);for(let a of this.shapeSubscriptions.values())a.answered||(r+=1);let i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:r,pendingWrites:i,synced:at(e)&&r===0&&i===0}}onSyncStatus(e){let s=this.syncStatusListeners.add(e),r=this.syncStatus();return this.lastSyncStatus=r,e(r),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 a of r){let o=this.connections.get(a);e.push({confirmedMutationWatermark:s?.get(a)??0,hasSocket:o?.socket!==void 0,shardKey:a===""?void 0:a,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(a=>({acked:a.acked,functionPath:a.fn.__lunoraRef,id:a.id,kind:"query",lastMutationId:a.lastMutationId,pendingOptimisticLayers:a.optimisticLayers.length,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size}));for(let a of this.shapeSubscriptions.values())i.push({acked:a.answered,functionPath:`shape:${a.name}`,id:a.id,kind:"shape",lastMutationId:a.lastMutationId,pendingOptimisticLayers:0,rowCount:a.rows.size,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((a,o)=>(a.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((a,o)=>a.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 ur(this,e,s,r)}whenReady(e={}){return e.signal===void 0?this.readyPromise:Mt(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,K(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=ie(e,s,r),a=this.hydratedQueryCache.get(i);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=x.key(e,s,r),a=this.subscriptions.get(i);return{present:a!==void 0,value:a?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,signal:r.signal})}async batch(e){return ne(this.rpcTimeoutMs,void 0,async s=>this.sendBatch(e,s))}async mutation(e,s,r={}){if(r.signal?.aborted)throw pe(r.signal);let{value:i}=await Mt(this.runMutation(e,s,r),r.signal);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,signal:r.signal,unbounded:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),a=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),p=d,{committed:f}=await this.runMutation(e,a(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(p)}`},shardKey:r.shardKey});d+=1,c+=l.length,f&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:d,imported:u,queued:c-u}}async shardTraffic(e){return Va(this.adminHost,e)}async listScheduledJobs(){return Xa(this.adminHost)}async schedulerStatus(){return Za(this.adminHost)}async cancelScheduledJob(e){return eo(this.adminHost,e)}async listDeadJobs(){return to(this.adminHost)}async retryDeadJob(e){return so(this.adminHost,e)}async removeDeadJob(e){return ro(this.adminHost,e)}async listWorkflowInstances(e){return io(this.adminHost,e)}async getWorkflowInstance(e){return no(this.adminHost,e)}async setWorkflowInstanceStatus(e){return ao(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=this.openSupplementarySocket(q(Lt(this.url),vn),{onMessage:n(r=>{let i;try{i=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(s.resetBackoff(),e(i.records.map(a=>rs(a))))},"onMessage")});return s.close}async listFunctions(){return Qa(this.adminHost)}async getCronJobs(){return _a(this.adminHost)}async runCronJob(e){return Da(this.adminHost,e)}async fetchOpenApi(){return Ua(this.adminHost)}async fetchArchitecture(){return Ka(this.adminHost)}async fetchOpenRpc(){return Na(this.adminHost)}async listStorageObjects(e={}){return oo(this.adminHost,e)}async deleteStorageObject(e,s){return co(this.adminHost,e,s)}async listStorageBuckets(){return uo(this.adminHost)}async uploadStorageObject(e){return ho(this.adminHost,e)}async signedStorageUrl(e,s){return lo(this.adminHost,e,s)}async listGlobalTables(){return qa(this.adminHost)}async readGlobalTablePage(e){return ja(this.adminHost,e)}async facetGlobalColumn(e){return Wa(this.adminHost,e)}async listVectorIndexes(){return po(this.adminHost)}async queryVectorIndex(e){return fo(this.adminHost,e)}async queryLogArchive(e={}){return Ja(this.adminHost,e)}async listKvNamespaces(){return Ba(this.adminHost)}async listKvKeys(e){return $a(this.adminHost,e)}async getKvValue(e){return Ha(this.adminHost,e)}async putKvValue(e){return za(this.adminHost,e)}async deleteKvKey(e){return Ga(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();let s=F(jn,{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(Bn,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch($n,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(Hn,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(zn,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(Gn,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(Vn,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(Jn,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(Yn,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(Xn,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(Zn,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(ea,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(F(ta,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(sa,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(F(ra,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(ia,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(na,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(F(aa,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();let s=F(oa,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.assertOpen();let s=F(ca,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();let s=F(la,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(pa,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(fa,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(ua,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(ha,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(da,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ma,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ya,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(ba,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(ga,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(va,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(Sa,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();let s=F(wa,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Ca,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(ka,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(Ta,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();let s=F(Ea,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(Oa,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(Ia,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();let s=F(Ra,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Aa,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Fa,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Pa,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=F(Wn,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};let a=s??{},o=x.key(e.__lunoraRef,a,i.shardKey),c=this.subscriptions.get(o),u=tt(r),d=tt(i.onError),h=tt(i.onCheckpoint);if(!c){this.nextSubId+=1;let m=`sub_${this.nextSubId.toString()}`,y=K(a),v=this.takeHydratedCache(e.__lunoraRef,y,i.shardKey);c={acked:!1,args:a,argsKey:y,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:m,lastValue:v?.value,optimisticLayers:[],serverBase:v?.value,serverCursor:v?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:G(a,`args for '${e.__lunoraRef}'`),...v?.serverEpoch===void 0?{}:{serverEpoch:v.serverEpoch}},this.subscriptions.add(c),this.emitSyncStatus(),v!==void 0&&this.cacheSeededQueries.set(o,v)}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,p=!1,f=n(()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",f),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(x.keyOf(l)),this.subscriptions.remove(l);let m=this.getConnection(l.shardKey);m&&this.settleSubscribeWatchdog(m,l.id),this.releaseIdleShard(l.shardKey),this.emitSyncStatus()}},"f");return i.signal?.addEventListener("abort",f,{once:!0}),i.signal?.aborted&&f(),f}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()}`,a={answered:!1,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:G(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,a),this.emitSyncStatus(),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(a),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(a.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(a.shardKey),this.emitSyncStatus()}}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:a}=r,o=s??{},{handle:c,iterable:u}=Xe({maxBuffer:r.maxBuffer,onCancel:n(()=>{this.cancelStream(i,a)},"onCancel")});this.ensureSocket(a);let d=this.getConnection(a),h={id:i,query:{args:G(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:a},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:h,shardKey:a};this.streams.set(i,l);let p=d?.wsState==="open"&&j(d,h);if(!p&&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(!p){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=64;){let f=d.pendingStreams.shift()?.id,m=f?this.streams.get(f):void 0;m&&(m.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}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 er(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0;for(let e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=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(),this.supplementaryBounces.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.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.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=n(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())},5e3))}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,a]of this.streams)g(a.shardKey)===s&&(a.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,ye(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={activeShapes:n(()=>[...this.shapeSubscriptions.values()],"activeShapes"),activeSubscriptions:n(()=>this.subscriptions.all(),"activeSubscriptions"),broadcastStatus:n((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:n(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:n(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:n(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:n(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:n(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:n(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:n(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:n(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:n(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:n(()=>this.clientId,"clientIdentifier"),dropCacheSeed:n(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:n((r,i,a)=>{this.ackAndAdvanceCursor(r,i,a)},"ackAndAdvanceCursor"),subscription:n(r=>this.subscriptions.get(r),"subscription")};return new Je({channelName:e,onBecomeLeader:n(()=>{Qo(s)},"onBecomeLeader"),onStopBeingLeader:n(()=>{_o(s)},"onStopBeingLeader"),onConnectionStatus:n((r,i)=>{Do(s,r,i)},"onConnectionStatus"),onSubscriptionData:n((r,i,a,o,c)=>{Ko(s,r,i,a,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:n(()=>{Uo(s)},"onLeaderClaimAnswered"),onSubscriptionError:n((r,i,a)=>{No(s,r,i,a)},"onSubscriptionError"),onSubscriptionSettled:n((r,i,a,o,c,u)=>{qo(s,r,i,a,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(q(this.url,$t),{body:JSON.stringify({calls:e.map((c,u)=>({args:G(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 a;try{a=await r.json()}catch{throw new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let o=fe(a);if(!r.ok||o!==void 0&&!a.results)throw o!==void 0?Ie(o):new b("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let c of a.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return mo(a.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=Bo(e,r),a=s,o=i.mutationId??nt();this.mutationIssueCounter+=1;let c=this.mutationIssueCounter,u=this.takeReplayCredential(i.replayCredential),d=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);let{confirms:h,rollbacks:l}=this.applyOptimisticUpdates(e.__lunoraRef,a,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,s,i.shardKey,l,h);let p=i.onlineOnly?void 0:this.offlineFlushes.get(g(i.shardKey));p!==void 0&&await p;let{httpFirst:f,midReconnect:m,shouldQueueOffline:y,socketDown:v}=this.writeQueueGate(i.shardKey),w=!i.onlineOnly&&y&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),T=n(async(S=!1)=>this.enqueueOfflineMutation(e,a,i.shardKey,d,o,l,h,S?void 0:i.precondition,i.mutationId,u?.stamp,S,c),"g");if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,l),v||m||w)return T();let I;try{let S=await this.rpc(e.__lunoraRef,a,i.shardKey,{baselineSeq:d,captureBookmark:!0,...u?.flags,mutationId:o,onCommitCursor:n(R=>{I=R},"onCommitCursor")});for(let R of h)R(I);return{committed:!0,value:S}}catch(S){let R=Go(S,a),V=f&&y&&R,Q=this.ownSocketOpen(i.shardKey);if(y&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(S instanceof TypeError||S instanceof D)&&Vt(a)){let k=T(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),k}throw this.settleFailedDirectWrite(S,I,h,l,u?.flags.authToken),Vo(i.onlineOnly,V,R,Q)?yr(e.__lunoraRef,S):S}}refuseOnlineOnlyWhenDown(e,s,r=[]){if(!s.onlineOnly)return;let i=this.writeQueueGate(s.shardKey);if(i.socketDown||i.midReconnect)throw ae(r),yr(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){let{hasSocket:s,idleClosed:r,polling:i,wasEverConnected:a,wsState:o}=this.connectionGateState(e),{queueBeforeFirstConnect:c}=this.offlineQueue,u=a||c,d=this.WebSocketImpl!==void 0&&u,h=i||r;return{httpFirst:h,midReconnect:o==="connecting"&&u&&!h,shouldQueueOffline:d,socketDown:o!=="open"&&!s&&d&&!h,socketOpen:o==="open"}}settleFailedDirectWrite(e,s,r,i,a){if(this.noteIdentityMismatch(e),a!==void 0&&this.noteReplayAuthRefusal(e,a),ot(e)){for(let o of r)o(s);return}ae(i)}async enqueueOfflineMutation(e,s,r,i,a,o,c,u,d,h,l,p){let f=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;let m=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(m)}`,identity:f,mutationId:m,...o.length>0&&{onRejected:n(()=>{ae(o)},"onRejected")},shardKey:r})}catch(y){throw ae(o),y instanceof Error?y:new Error(String(y))}for(let y of c)y(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((m,y)=>{let v={ambiguousSend:l,args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:a,issueSeq:p,clientId:this.clientId,identity:f,precondition:u,onCommit:n(w=>{for(let T of c)T(w)},"onCommit"),reject:n(w=>{this.queuedIdentities.delete(a),ot(w)||ae(o),y(w instanceof Error?w:new Error(String(w))),this.releaseIdleShard(r)},"reject"),resolve:m,shardKey:r};this.offlineQueue.enqueue(v),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),v.id!==void 0&&this.queuedIdentities.set(v.id,f)})}}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=n(()=>{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(ie(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(jt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let a=s.get(r);if(a&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(a,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(ie(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),re(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,re(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=ie(e,s,r),a=this.hydratedQueryCache.get(i);if(!(a===void 0||!this.cachedQueryMatchesIdentity(a)))return this.hydratedQueryCache.delete(i),a}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=ie(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=ie(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,a=i===void 0?this.identityFingerprint():i;a===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:a,serverCursor:e.serverCursor,ts:Date.now(),value:s,...a===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(()=>{})},250))}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)))}installPageHideFlush(){let e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;let s=n(()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},"t"),r=n(()=>{e.document?.visibilityState==="hidden"&&s()},"s");e.addEventListener("pagehide",s),e.document?.addEventListener("visibilitychange",r),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",s),e.document?.removeEventListener("visibilitychange",r)}}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}composedBaselineFor(e,s){return e===void 0?this.baselineCursorFor(s):e??void 0}async pollSubscriptions(e){let s=g(e),r=[];for(let c of this.subscriptions.all())g(c.shardKey)===s&&(Vt(c.args)?r.push(c):(this.markQueryRejected(c,!0),Y(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=tr(),a=this.identityFingerprint(),o;try{o=await pr(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()!==a)return!0;for(let[c,u]of r.entries()){let d=o[c];if(d!==void 0){if(!d.ok){this.markQueryRejected(u,!0),Y(u.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:B(d.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await pr(async s=>e(q(this.url,$t),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;let e=this.syncStatus(),s=this.lastSyncStatus;s?.connection===e.connection&&s.pendingSubscriptions===e.pendingSubscriptions&&s.pendingWrites===e.pendingWrites&&s.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){let e=this.computeStatus();this.emitSyncStatus(),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 a=[],o=[];if(!i)return{confirms:a,rollbacks:o};let c=x.key(e,s,r),u=this.subscriptions.get(c);if(u){let d=Dt(u,i);d&&(a.push(d.confirm),o.push(d.rollback))}return{confirms:a,rollbacks:o}}applyOptionalOptimisticUpdate(e,s,r,i,a){e&&this.applyOptimisticUpdate(e,s,r,i,a)}applyOptimisticUpdate(e,s,r,i,a){let{confirms:o,rollbacks:c,store:u}=ir(this.subscriptions,r);try{e(u,s)}catch{ae(c);return}i.push(...c),a.push(...o)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!j(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:So({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:n(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:n(()=>{this.emitConnectionStatus()},"onStateChange"),poll:n(async()=>this.pollSubscriptions(e),"poll")}),reconnect:Oe(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}openSupplementarySocket(e,s){if(this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),resetBackoff:n(()=>{},"resetBackoff"),socket:n(()=>{},"socket")};let r=Oe(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},a,o=!1,c=n(()=>{o||this.closed||(a=setTimeout(h,r.next()))},"a"),u=n(f=>{o||this.WebSocketImpl===void 0||lr(i,this.wsUrlFor(s.shardKey,f,e),this.managedSocketOptions,{onClose:n(()=>{c(),s.onClose?.()},"onClose"),onMessage:s.onMessage,...s.onOpen===void 0?{}:{onOpen:s.onOpen}})},"c"),d=n(async f=>{let m=this.wsTokenGeneration,y;try{y=await f()}catch{c();return}if(m!==this.wsTokenGeneration){h();return}u(y)},"u"),h=n(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){d(f).catch(()=>{});return}u(f)},"d");h();let l=n(()=>{o=!0,a!==void 0&&(clearTimeout(a),a=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),ye(i);let{socket:f}=i;i.socket=void 0;try{f?.close()}catch{}},"h");this.adminSocketTeardowns.add(l);let p=n(()=>{let{socket:f}=i;if(f!==void 0){i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),ye(i);try{f.close()}catch{}s.onClose?.(),c()}},"p");return this.supplementaryBounces.add(p),{close:n(()=>{l(),this.adminSocketTeardowns.delete(l),this.supplementaryBounces.delete(p)},"close"),resetBackoff:n(()=>{r.reset()},"resetBackoff"),socket:n(()=>i.socket,"socket")}}supplementaryUrl(e){let s=xt(this.wsUrl),r=s.pathname.endsWith(Ht)?s.pathname.slice(0,-Ht.length):s.pathname;return s.pathname=q(r,e),Qt(s,this.wsUrl)}wsUrlFor(e,s,r=this.wsUrl){if(e===void 0&&s===void 0)return r;let i=xt(r),a=new Set([...e===void 0?[]:["shard"],...s===void 0?[]:["token"]]),o=[...i.searchParams].filter(([c])=>!a.has(c)).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);return e!==void 0&&o.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&o.push(`token=${encodeURIComponent(s)}`),i.search=o.join("&"),Qt(i,r)}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[nn]=an(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let a=e.authToken===void 0?this.authToken:e.authToken;if(a&&(r.authorization=`Bearer ${a}`),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={}){let{fetchImpl:a}=this;if(!a)throw new D("LunoraClient: no `fetch` implementation available");let o=this.rpcRequestHeaders(i,r),c=i.authToken===void 0?this.authToken:i.authToken,u=JSON.stringify({args:G(s,`args for '${e}'`),functionPath:e,shardKey:r}),{body:d,response:h}=await ne(i.unbounded?0:this.rpcTimeoutMs,i.signal,async f=>{let m=await a(q(this.url,mn),{body:u,headers:o,method:"POST",signal:f});try{return{body:await m.json(),response:m}}catch{return{body:void 0,response:m}}});if(i.captureBookmark){let f=h.headers.get("x-d1-bookmark");f&&this.bookmark.set(f)}if(d===void 0)throw Re(h.status,h.statusText,h.headers.get("retry-after"));let l=d;if(typeof l!="object"||l===null||Array.isArray(l))throw Re(h.status,h.statusText,h.headers.get("retry-after"));let p=fe(d);if(p!==void 0)throw qt(p,h.headers.get("retry-after"));if(!h.ok)throw Re(h.status,h.statusText,h.headers.get("retry-after"));i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(c),this.learnDefaultShardKey(h,r),this.recordShardCursor(r,d.commitCursor);try{return E(d.result)}catch(f){throw kr(f)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let a={};this.authToken&&(a.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&&(a["content-type"]=i)):(c=JSON.stringify(r),a["content-type"]="application/json");let u=await this.fetchImpl(q(this.url,e),{body:c,headers:a,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=fe(d);if(h!==void 0)throw Ie({...h,message:h.message??"admin request failed"});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));j(e,{caps:$o,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=this.wsTokenGeneration,a=Symbol("ws-token-attempt"),o;e.providerAttempt=a;try{o=await ne(this.connectTimeoutMs,void 0,async()=>r(),()=>new Error("LunoraClient: wsToken provider timed out"))}catch{e.providerAttempt===a&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===a&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(i!==this.wsTokenGeneration){typeof this.wsToken=="function"?await this.openSocketWithProvidedToken(e,s,this.wsToken):this.openSocket(e,s,this.wsToken);return}this.openSocket(e,s,o)}}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,lr(e,this.wsUrlFor(s,r),this.managedSocketOptions,{onClose:n(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:n(i=>{e.retired!==!0&&this.handleServerMessage(i.data,s)},"onMessage"),onOpen:n(()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},5e3),this.markShardPendingAck(s,!0),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.clearResubscribeQueue(e);for(let o of this.subscriptions.all())g(o.shardKey)===g(s)&&this.queueResubscribe(o);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let o=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:c,type:u}of o)j(e,{id:c,type:u});this.releaseIdleShard(s)}yo(e);let i=g(s),a=this.whisperHandlers.get(i);if(this.dropWhisperJoinWaiters(i),this.whisperJoins.set(i,new Map),a)for(let o of a.keys())this.sendWhisperJoin(e,i,o);e.roomsRejoined=!0,this.releaseRoomSends(s),this.flushOfflineQueue(s).catch(()=>{})},"onOpen")}))}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),j(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(),ye(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(g(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,a]of this.streams)if(!(g(a.shardKey)!==g(e.shardKey)||s.has(i))){if(a.durable){let o={...a.message,...a.generation===void 0?{}:{generation:a.generation},sinceChunk:a.lastSeq};a.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}a.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,s=!1){let r=g(e);for(let i of this.subscriptions.all())g(i.shardKey)===r&&(i.acked=!1,s&&(i.valueReceived=!1));for(let i of this.shapeSubscriptions.values())g(i.shardKey)===r&&(i.answered=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<3;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribeSlots.add(s.id)}}settleSubscribeWatchdog(e,s){clearTimeout(e.unackedWatchdogs.get(s)),e.unackedWatchdogs.delete(s),e.resubscribeSlots.delete(s)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(let s of e.unackedWatchdogs.values())clearTimeout(s);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,s=!1){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.acked)return!1;let i=e.serverCursor!==void 0&&e.serverBase!==void 0,a=j(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return a&&!s&&this.armUnackedWatchdog(r,e),a}armUnackedWatchdog(e,s){clearTimeout(e.unackedWatchdogs.get(s.id)),e.unackedWatchdogs.set(s.id,setTimeout(()=>{!s.acked&&this.subscriptions.getById(s.id)===s&&this.sendSubscribeIfOpen(s,!0),this.settleSubscribeWatchdog(e,s.id)},1e4))}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&j(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=go(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 a=this.getConnection(s);if(a){let{id:o}=i;this.settleSubscribeWatchdog(a,o)}}switch(i.type){case"ack":{let a=this.subscriptions.getById(i.id);a&&this.ackAndAdvanceCursor(a,void 0,void 0);return}case"chunk":{let{data:a,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(E(a));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),this.adoptSocketConnectionId(i,s),this.confirmShardIdentity(s);break}case"live":{this.dispatchLive(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}case"whisper_subscribed":{this.acknowledgeWhisperJoin(g(s),i.topic);break}}}handleErrorMessage(e){let s=e.error?.code;if(s==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(s==="STREAM_ID_IN_USE")return;let{id:r}=e,i=r===void 0?void 0:this.streams.get(r);if(i&&r!==void 0){i.handle.fail(ar(e)),this.forgetStream(r);return}let a=r===void 0?void 0:this.subscriptions.getById(r);if(a){let c=Nt(e),u=this.identityFingerprint(),d=x.keyOf(a);this.markQueryRejected(a),Y(a.errorCallbacks,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,c,u);return}let o=r===void 0?void 0:this.shapeSubscriptions.get(r);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),Y(o.errorCallbacks,Nt(e)))}markQueryRejected(e,s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){let r=s?"valueReceived":"acked";e[r]||(e[r]=!0,this.emitSyncStatus())}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){Mo(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let a=this.shapeSubscriptions.get(i);a&&!r.undecodable.has(i)&&this.applyPokePart(a,r,e)}}}applyPokePart(e,s,r){let i=e.answered,a=Po(e,s,r);if(e.answered!==i&&this.emitSyncStatus(),mr(e),a==="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,this.emitSyncStatus(),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||e.type==="data"&&Lo(i,e))return;let a;try{a=Js(e,i.serverBase)}catch(c){Y(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${c instanceof Error?c.message:String(c)}`});return}if(a===Ft){this.resnapshotSubscription(i);return}this.dropCacheSeed(x.keyOf(i));let o=s!==void 0&&!i.valueReceived;if(Tr(i,a,{cursor:e.cursor,epoch:e.epoch}),o&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(Xt(i,e.lastMutationId),Zt(i,!0)),this.persistQueryValue(i),st(i,i.serverCursor),s!==void 0&&rr(i,s),re(i,a),this.tabCoordinator?.isLeader()){let c=x.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(c,a,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&&Xt(s,e.lastMutationId),Zt(s),this.tabCoordinator?.isLeader())){let r=x.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){let i=!e.acked;e.acked=!0,i&&this.emitSyncStatus(),(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),st(e,e.serverCursor)&&re(e,e.serverBase))}adoptSocketConnectionId(e,s){let r=this.getConnection(s);if(!(r===void 0||typeof e.connectionId!="string")){r.connectionId=e.connectionId,r.whisperAck=e.whisperAck===!0;for(let i of this.liveSocketGrants.get(g(s))?.keys()??[])this.grantWhenJoined(s,i,e.connectionId)}}grantWhenJoined(e,s,r){let i=g(e),a=this.liveSocketGrants.get(i)?.get(s);if(a===void 0)return;let{stream:o,topic:c}=a,u=n(()=>{this.liveSocketGrants.get(i)?.get(s)===void 0||this.getConnection(e)?.connectionId!==r||this.postLiveControl(`/live/${o}/control`,e,{action:"subscribe",connectionId:r,stream:o,subscriptionId:s,topic:c},d=>{this.refuseLiveGrant(e,s,d,r)})},"c");this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,c,u):u()}sendWhisperJoin(e,s,r){let i=this.whisperJoinState(s,r);i.pending+=1,i.joined=!1,j(e,{topic:r,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,s){let r=this.whisperJoins.get(e)?.get(s);if(r!==void 0&&(r.pending=Math.max(0,r.pending-1),!(r.pending>0))){r.joined=!0;for(let i of r.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,s)}}releaseWhisperJoin(e,s){if(this.whisperHandlers.get(e)?.has(s)===!0)return;let r=this.whisperJoins.get(e),i=r?.get(s);if(!(r===void 0||i===void 0||i.pending>0)){for(let a of i.waiters.splice(0))clearTimeout(a.timer);r.delete(s),r.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,s,r){let i=this.whisperJoinState(e,s);if(i.joined){r();return}let a={run:r,timer:void 0};a.timer=setTimeout(()=>{i.waiters=i.waiters.filter(o=>o!==a),r()},Er),i.waiters.push(a)}dropWhisperJoinWaiters(e){for(let s of this.whisperJoins.get(e)?.values()??[])for(let r of s.waiters.splice(0))clearTimeout(r.timer)}whisperJoinState(e,s){let r=this.whisperJoins.get(e);r===void 0&&(r=new Map,this.whisperJoins.set(e,r));let i=r.get(s);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},r.set(s,i)),i}refuseLiveGrant(e,s,r,i){let a=g(e),o=this.liveSocketGrants.get(a),c=o?.get(s);o===void 0||c===void 0||this.getConnection(e)?.connectionId!==i||(o.delete(s),o.size===0&&this.liveSocketGrants.delete(a),c.release(),c.onError?.({status:r,topic:c.topic}))}postLiveControl(e,s,r,i){let{fetchImpl:a}=this;if(!a)return;let o=JSON.stringify(s===void 0?r:{...r,shardKey:s}),c=this.rpcRequestHeaders({},s);this.liveControlChain=this.liveControlChain.then(()=>zo(a,q(this.url,e),o,c)).then(u=>{u>=400&&u<500&&u!==404&&u!==401&&i?.(u)}).catch(()=>{})}dispatchLive(e,s){let r=this.liveSocketGrants.get(g(s));if(!r)return;let i=E(e.data);for(let a of r.values())if(!(a.stream!==e.stream||a.topic!==e.topic))try{a.onEvent(i)}catch{}}dispatchWhisper(e,s){let r=this.whisperHandlers.get(g(s))?.get(e.topic);if(!r)return;let i=E(e.data);for(let a of r)try{a(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,this.emitSyncStatus(),Y(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(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 a=e.charCodeAt(i);s^=a,s=Math.imul(s,16777619),r=Math.imul(r,33)+a}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&&at(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)}sendEncodedWhisper(e,s,r){this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey),a=i!==void 0&&j(i,{data:s,topic:e,type:"whisper"});return this.releaseIdleShard(r.shardKey),a}roomSendsAdmitted(e){let s=this.getConnection(e);return s?.wsState==="open"&&s.retired!==!0&&s.identityConfirmed===!0&&s.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(let s of this.roomFlushes.get(g(e))??[])s()}confirmShardIdentity(e){let s=this.getConnection(e);s!==void 0&&(s.identityConfirmed=!0),this.releaseRoomSends(e)}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 a=new Error("offline mutation discarded: auth identity changed before replay");a.code="OFFLINE_IDENTITY_CHANGED",i.reject(a),this.emitItemSettled(i,"rejected",a)}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 a=s??"",o=this.clientWatermarks.get(a);if(o===void 0)this.clientWatermarks.set(a,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.resetRoomSends(),this.revokeCacheSeededValues();for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,e.valueReceived=!1,re(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,mr(e);this.emitSyncStatus(),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()}resetRoomSends(){for(let e of this.roomIdentityResets)e()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}for(let e of this.supplementaryBounces)e()}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:a}=this;try{await this.drainOfflineQueue(e,a)}catch{}!this.closed&&this.authToken!==a&&this.offlineQueue.size>0&&at(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),a=this.offlineQueue.drain(h=>g(h.shardKey)===i);if(a.length===0)return;let o=[],c=[];for(let h of a){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+=Bt){let l=u.slice(h,h+Bt),p=await this.replayBatched(l,e,s);if(d.push(...p.requeue),p.stop||p.requeue.length>0){d.push(...u.slice(h+Bt));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,Jt(i))})}noteReplayRetryDelay(e,s,r){let i=g(e),a=this.replayRetryState.get(i),o=(a?.attempts??0)+1,c=Eo(s,o)??(r===null&&Ee(s)?Jt(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:c===void 0?a?.delayMs:Math.max(a?.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 a=this.replayRetryTimers.get(s);a!==void 0&&clearTimeout(a),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{G(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)||fr(e)}noteReplayAuthRefusal(e,s){if(!Ee(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,...zt(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)}spendsLastReplayAttempt(e,s){if(e.id===void 0)return!1;let r=s?.code;if(e.ambiguousSend!==!0||Ee(s)||r==="RATE_LIMITED"||r==="TOO_MANY_REQUESTS"||!fr(s))return!1;let i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=5}keepUnexhaustedAmbiguousWrites(e,s){return e.filter(r=>r.ambiguousSend===!0&&this.spendsLastReplayAttempt(r,s)?(this.settleReplayTerminal(r,s),!1):!0)}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 a=e[i];if(!a)continue;let o;try{let c=await this.rpc(a.functionPath,a.args,a.shardKey,{authToken:r,baselineSeq:a.baselineSeq,captureBookmark:!0,clientId:a.clientId??this.clientId,...zt(a.identity,r),mutationId:a.id,onCommitCursor:n(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(a,c,o)}catch(c){if(ot(c)){this.settleReplayUndecodable(a,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)||this.spendsLastReplayAttempt(a,c)){this.settleReplayTerminal(a,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((h,l)=>({args:G(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:l,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&Io(i)>Oo)return await this.replayBatchedHalves(e,s,r);let{fetchImpl:a}=this,o,c;try{({payload:c,response:o}=await ne(this.rpcTimeoutMs,void 0,async h=>{let l=await a(q(this.url,$t),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...zt(e.find(p=>p.identity!==void 0)?.identity,r)}),method:"POST",signal:h});if(l.status===413&&e.length>1)return{payload:void 0,response:l};try{return{payload:await l.json(),response:l}}catch{return{payload:void 0,response:l}}}))}catch(h){return this.noteReplayRetryDelay(s,h,r),{requeue:this.keepUnexhaustedAmbiguousWrites(e,h),stop:!0}}let u=o.headers.get("x-d1-bookmark");if(u&&this.bookmark.set(u),o.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let d=o.headers.get("retry-after");if(!c)return this.settleWholeBatchError(e,Re(o.status,o.statusText,d),s,r);if(!Array.isArray(c.results)){let h=fe(c),l=h===void 0?Re(o.status,o.statusText,d):qt(h,d);return this.settleWholeBatchError(e,l,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof D||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,s),stop:!0};for(let a of e)this.settleReplayTerminal(a,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),a=await this.replayBatched(e.slice(0,i),s,r);if(a.stop||a.requeue.length>0)return{requeue:[...a.requeue,...e.slice(i)],stop:!0};let o=await this.replayBatched(e.slice(i),s,r);return{requeue:[...a.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,s,r,i){let a=Ro(s),o=[],c=!1,u=!1;for(let[d,h]of e.entries()){let l=Ao(a.get(d));switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(h,l.value,l.commitCursor);break}case"errored":{u||=Ee(l.error),this.shouldRequeueReplayFailure(l.error,i)&&!this.spendsLastReplayAttempt(h,l.error)?(this.noteReplayRetryDelay(r,l.error,i),o.push(h)):this.settleReplayTerminal(h,l.error);break}case"unanswered":{let p=Kt();if(this.spendsLastReplayAttempt(h,p)){this.settleReplayTerminal(h,p);break}this.noteReplayRetryDelay(r,p,i),o.push(h);break}default:c=!0,this.settleReplayUndecodable(h,l.error,l.commitCursor)}}return c&&!u&&this.noteCredentialAccepted(i),o}};var Or=_(as(),1),Ir=_(ee(),1);var Yo=n(()=>{let t=(0,Or.c)(4),e=Ot(),s,r,i;return t[0]!==e?(s=n(a=>e.onConnectionStatus(()=>{a()}),"o"),r=n(()=>e.connectionStatus(),"e"),i=n(()=>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,Ir.useSyncExternalStore)(s,r,i)},"S");export{be as a,Me as b,B as c,E as d,Vr as e,es as f,ei as g,ve as h,hi as i,di as j,fi as k,Ot as l,Yo as m};