@lunora/studio 1.0.0-alpha.224 → 1.0.0-alpha.225
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/FileBrowser.mjs +4 -4
- package/dist/packem_chunks/SchemaViewer.mjs +1 -1
- package/dist/packem_chunks/TableEditor.mjs +1 -1
- package/dist/packem_chunks/permissions-panel.mjs +1 -1
- package/dist/packem_chunks/vector-browser.mjs +1 -1
- package/dist/packem_chunks/workflows-panel.mjs +1 -1
- package/dist/packem_shared/DataBrowser-B5Sl4vMa.mjs +4 -0
- package/dist/packem_shared/DataFilters-CYZFt2EK.mjs +1 -0
- package/dist/packem_shared/{GlobalDataBrowser-CR138dEZ.mjs → GlobalDataBrowser-BzhSVDvF.mjs} +1 -1
- package/dist/packem_shared/table-list-sidebar-CYRSPLIv.mjs +1 -0
- package/dist/standalone/{chunk-UWHH6R7J.js → chunk-43HEY5SJ.js} +1 -1
- package/dist/standalone/{chunk-S6ZFBF3S.js → chunk-46EQO6E7.js} +1 -1
- package/dist/standalone/chunk-4QWQLDFZ.js +1 -0
- package/dist/standalone/{chunk-WXDKJUXF.js → chunk-5ITJRE7T.js} +1 -1
- package/dist/standalone/{chunk-FQEKYLWQ.js → chunk-6JJLA4DT.js} +1 -1
- package/dist/standalone/{chunk-7UHE2RRI.js → chunk-6SG5Y2X3.js} +1 -1
- package/dist/standalone/{chunk-UTIAX6IO.js → chunk-7FZPPR6U.js} +1 -1
- package/dist/standalone/{chunk-GFB3DJBT.js → chunk-7JR5NBZT.js} +1 -1
- package/dist/standalone/chunk-AHIYIRQJ.js +1 -0
- package/dist/standalone/{chunk-NHLLFFXW.js → chunk-B5757NYK.js} +1 -1
- package/dist/standalone/{chunk-74CQY3AB.js → chunk-CCHE3AP7.js} +1 -1
- package/dist/standalone/{chunk-KDY4VSAF.js → chunk-CEWWYWDH.js} +1 -1
- package/dist/standalone/{chunk-GQWFRBCJ.js → chunk-CFZF73E5.js} +1 -1
- package/dist/standalone/{chunk-SWS6R7OJ.js → chunk-CGBR52EF.js} +1 -1
- package/dist/standalone/{chunk-OBUY7UZO.js → chunk-CGWLZBB7.js} +1 -1
- package/dist/standalone/chunk-E34I2O2H.js +1 -0
- package/dist/standalone/{chunk-SL2WTTEZ.js → chunk-EN3YBGYA.js} +1 -1
- package/dist/standalone/{chunk-CFYXGSV3.js → chunk-FFHEYNCC.js} +1 -1
- package/dist/standalone/{chunk-FZAGSACU.js → chunk-FJ33XGJ2.js} +1 -1
- package/dist/standalone/{chunk-G6JWVIBX.js → chunk-FYTLD6ZB.js} +1 -1
- package/dist/standalone/{chunk-27ILKCWI.js → chunk-FZ5ZSUA2.js} +1 -1
- package/dist/standalone/{chunk-KME5TGGZ.js → chunk-GC7R2JNV.js} +1 -1
- package/dist/standalone/{chunk-WRSH2CJD.js → chunk-HSWCIY4E.js} +1 -1
- package/dist/standalone/{chunk-QWBMBXUI.js → chunk-IDGVZH7L.js} +1 -1
- package/dist/standalone/{chunk-KJOMRSX7.js → chunk-IOZMKJXM.js} +1 -1
- package/dist/standalone/{chunk-2LJKZSU4.js → chunk-J7PUQPIK.js} +1 -1
- package/dist/standalone/{chunk-SB535MB2.js → chunk-JBFHGYJ7.js} +1 -1
- package/dist/standalone/{chunk-RK5UUSYK.js → chunk-LGHZBMSX.js} +1 -1
- package/dist/standalone/{chunk-WQ6OGGRQ.js → chunk-LWS3QK2Z.js} +1 -1
- package/dist/standalone/{chunk-EVGASJNW.js → chunk-MTPPT5DN.js} +1 -1
- package/dist/standalone/chunk-N3N44LM3.js +1 -0
- package/dist/standalone/{chunk-JL7WQ35Y.js → chunk-NAABU3WM.js} +1 -1
- package/dist/standalone/{chunk-QOQ56UE7.js → chunk-NMS7725B.js} +1 -1
- package/dist/standalone/{chunk-3G3KM5QW.js → chunk-OGFGCB3X.js} +1 -1
- package/dist/standalone/{chunk-PCYB6Q5V.js → chunk-OQQ3KQUW.js} +1 -1
- package/dist/standalone/{chunk-D6Z2ZUU7.js → chunk-OYO24LYQ.js} +1 -1
- package/dist/standalone/{chunk-NZKXQEZ5.js → chunk-PG7XHMUR.js} +1 -1
- package/dist/standalone/{chunk-FMEXQNO7.js → chunk-PGX7ADT3.js} +1 -1
- package/dist/standalone/{chunk-4YXKODH3.js → chunk-RBESZ4U6.js} +1 -1
- package/dist/standalone/{chunk-OMTRTMGC.js → chunk-RHCY7FOG.js} +1 -1
- package/dist/standalone/chunk-RWYC2UZQ.js +4 -0
- package/dist/standalone/{chunk-7FTSNUL7.js → chunk-SEQJ26SP.js} +1 -1
- package/dist/standalone/{chunk-2OW5U2BZ.js → chunk-SX43GWLQ.js} +1 -1
- package/dist/standalone/{chunk-IL34SD2J.js → chunk-T7TBRE7I.js} +1 -1
- package/dist/standalone/{chunk-WLLOZ3HS.js → chunk-UKEPEJQE.js} +1 -1
- package/dist/standalone/{chunk-E6YTK54J.js → chunk-VCJJ6V4Q.js} +1 -1
- package/dist/standalone/{chunk-Q5H5UZCT.js → chunk-VELEXXBI.js} +1 -1
- package/dist/standalone/{chunk-VVQBWSND.js → chunk-WH5TVSUG.js} +1 -1
- package/dist/standalone/{chunk-WM5HSIP3.js → chunk-WSZOB3GK.js} +1 -1
- package/dist/standalone/{chunk-3UW7JOCC.js → chunk-X4WJS7OY.js} +1 -1
- package/dist/standalone/{chunk-RFNTIPZM.js → chunk-XBSC4FT4.js} +1 -1
- package/dist/standalone/chunk-XEW4IUTU.js +5 -0
- package/dist/standalone/{chunk-I7GBAQ72.js → chunk-XUH4K2HN.js} +1 -1
- package/dist/standalone/{chunk-INHSAPFB.js → chunk-YQ7E3R3D.js} +1 -1
- package/dist/standalone/{chunk-KTBJ5SQO.js → chunk-YU2KFHL7.js} +1 -1
- package/dist/standalone/{chunk-TSNKMJKC.js → chunk-ZVJOW25X.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/dist/styles.css +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/DataBrowser-DWSaSSRj.mjs +0 -4
- package/dist/packem_shared/DataFilters-Cocu-WWE.mjs +0 -1
- package/dist/packem_shared/table-list-sidebar-DxvakjpR.mjs +0 -1
- package/dist/standalone/chunk-2ZFFWSLG.js +0 -1
- package/dist/standalone/chunk-3EDFZHY5.js +0 -5
- package/dist/standalone/chunk-DG5KSS6E.js +0 -1
- package/dist/standalone/chunk-EBNWZ33C.js +0 -1
- package/dist/standalone/chunk-FS4K5TEX.js +0 -1
- package/dist/standalone/chunk-OIHA5CMU.js +0 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as D}from"./chunk-Z5O2NQAV.js";import{b as C}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import"./chunk-35DM4JJG.js";import{a as L}from"./chunk-4ZEL6BYL.js";import{c as $}from"./chunk-
|
|
1
|
+
import{a as D}from"./chunk-Z5O2NQAV.js";import{b as C}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import"./chunk-35DM4JJG.js";import{a as L}from"./chunk-4ZEL6BYL.js";import{c as $}from"./chunk-FZ5ZSUA2.js";import"./chunk-PG7XHMUR.js";import"./chunk-FSRSK4LY.js";import"./chunk-5ICUJ4IA.js";import{a as I}from"./chunk-FKVZRPV5.js";import{a as T,b as k,c as A,d as g,e as c,f as l}from"./chunk-HEAQVSNS.js";import{a as b,e as S}from"./chunk-WUWBZPUK.js";import{d as w}from"./chunk-PTZD7RUZ.js";import{a as f,d as y,f as _,g as j}from"./chunk-YKXDMIHQ.js";var O=y(_(),1);var t=y(j(),1);var E="container:",M={error:"error",sleep:"sleeping",start:"running",stop:"stopped"},B=f(e=>{let n=e.indexOf(":");if(n===-1)return{event:e.trim()};let r=e.slice(n+1).trim(),a=e.slice(0,n).trim();return r===""?{event:a}:{detail:r,event:a}},"B"),P=f(e=>{let n=new Map;for(let r of e){let a=r.functionPath??"";if(!a.startsWith(E))continue;let i=a.slice(E.length);if(i==="")continue;let s=JSON.stringify([i,r.instance??""]),o=n.get(s);if(o!==void 0&&o.timestamp>=r.timestamp)continue;let{detail:p,event:d}=B(r.message);n.set(s,{detail:p,event:d,exitCode:r.exitCode,instance:r.instance,level:r.level,name:i,state:M[d]??"unknown",timestamp:r.timestamp})}return[...n.values()].toSorted((r,a)=>r.name.localeCompare(a.name)||(r.instance??"").localeCompare(a.instance??""))},"D"),W={error:"destructive",running:"success",sleeping:"info",stopped:"outline",unknown:"secondary"},q=f(e=>{let{entries:n}=e??{};return Array.isArray(n)?n:[]},"P"),V=f(()=>{let e=(0,O.c)(19),n=w(),r,a;e[0]===Symbol.for("react.memo_cache_sentinel")?(r={},a={live:!0,shardKey:""},e[0]=r,e[1]=a):(r=e[0],a=e[1]);let{data:i,error:s,liveError:o}=$(L.getLogs,r,a),p=i!==void 0,d;if(e[2]!==i||e[3]!==s||e[4]!==o||e[5]!==p||e[6]!==n){let N=P(q(i)),x;e[8]!==s?(x=s!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"containers-error",role:"alert",children:s}),e[8]=s,e[9]=x):x=e[9];let m;e[10]!==n?(m=n("Cloudflare Containers are observed from their lifecycle log stream. This shows the current state per instance \u2014 ports and health checks aren't carried in that stream."),e[10]=n,e[11]=m):m=e[11];let u;e[12]!==m?(u=(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:m}),e[12]=m,e[13]=u):u=e[13];let h;e[14]!==o?(h=(0,t.jsx)(D,{message:o,prefix:"containers"}),e[14]=o,e[15]=h):h=e[15];let v;e[16]!==u||e[17]!==h?(v=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[u,h]}),e[16]=u,e[17]=h,e[18]=v):v=e[18],d=(0,t.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-containers-panel",children:[x,v,p&&N.length===0?(0,t.jsx)(I,{description:n("No container lifecycle activity yet. Instances declared with defineContainer show up here once they start, sleep, stop, or error."),testId:"containers-empty",title:n("No container activity")}):(0,t.jsx)(b,{className:"overflow-hidden py-0",children:(0,t.jsx)(S,{className:"px-0",children:(0,t.jsxs)(T,{"data-testid":"containers-table",children:[(0,t.jsx)(k,{children:(0,t.jsxs)(g,{children:[(0,t.jsx)(c,{children:n("Container")}),(0,t.jsx)(c,{children:n("Instance")}),(0,t.jsx)(c,{children:n("State")}),(0,t.jsx)(c,{children:n("Last event")}),(0,t.jsx)(c,{children:n("Detail")}),(0,t.jsx)(c,{children:n("Exit")}),(0,t.jsx)(c,{children:n("When")})]})}),(0,t.jsx)(A,{children:N.map(F)})]})})})]}),e[2]=i,e[3]=s,e[4]=o,e[5]=p,e[6]=n,e[7]=d}else d=e[7];return d},"q");function F(e){return(0,t.jsxs)(g,{"data-testid":`containers-row-${e.name}${e.instance===void 0?"":`-${e.instance}`}`,children:[(0,t.jsx)(l,{className:"font-mono text-xs",children:e.name}),(0,t.jsx)(l,{className:"max-w-40 truncate font-mono text-xs text-muted-foreground",title:e.instance,children:e.instance??"\u2014"}),(0,t.jsx)(l,{children:(0,t.jsx)(C,{variant:W[e.state],children:e.state})}),(0,t.jsx)(l,{className:"font-mono text-xs text-muted-foreground",children:e.event}),(0,t.jsx)(l,{className:"max-w-64 truncate text-xs text-muted-foreground",title:e.detail,children:e.detail??"\u2014"}),(0,t.jsx)(l,{className:"font-mono text-xs tabular-nums text-muted-foreground",children:e.exitCode??"\u2014"}),(0,t.jsx)(l,{className:"text-xs tabular-nums text-muted-foreground",children:new Date(e.timestamp).toLocaleString()})]},`${e.name}/${e.instance??""}`)}f(F,"j");export{V as default};
|
|
@@ -6,4 +6,4 @@ import{a as _t,d as y}from"./chunk-5ICUJ4IA.js";import{a as o,d as L,e as ie,f a
|
|
|
6
6
|
|
|
7
7
|
`);for(;u!==-1;){let h=Yr(i.slice(0,u));if(i=i.slice(u+2),Zr(h,e))return!0;u=i.indexOf(`
|
|
8
8
|
|
|
9
|
-
`)}return!1},"d");for(;;){let{done:u,value:h}=await s.read();if(u)break;if(a(r.decode(h,{stream:!0})),c()){await s.cancel().catch(()=>{});return}}a(r.decode()),c()||e.fail(new y("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),xs=o((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new y("INTERNAL","httpStream: no `fetch` implementation available");let i=Xr(t,e??{},s.baseUrl??""),n=new AbortController,a;s.signal&&(s.signal.aborted?n.abort():(a=o(()=>{n.abort()},"l"),s.signal.addEventListener("abort",a,{once:!0})));let c=o(()=>{a&&s.signal?.removeEventListener("abort",a)},"d"),{handle:u,iterable:h}=Be({maxBuffer:s.maxBuffer,onCancel:o(()=>{n.abort()},"onCancel")});return(async()=>{try{let d=await r(i,{headers:{accept:"text/event-stream",...s.headers},method:t.method,signal:n.signal});if(!d.ok){await d.body?.cancel().catch(()=>{}),u.fail(new y("HTTP_STREAM_STATUS",`httpStream: request failed (status ${d.status.toString()})`,{status:d.status}));return}if(!d.body){u.fail(new y("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await ei(d.body,u)}finally{c()}})().catch(d=>{if(n.signal.aborted){u.complete();return}if(d instanceof Error&&"code"in d){u.fail(d);return}u.fail(new y("HTTP_STREAM_TRANSPORT",d instanceof Error?d.message:String(d),{cause:d}))}),h},"_");var ti=/["\\\u0000-\u001F\uD800-\uDFFF]/,Ls=o(t=>ti.test(t)?JSON.stringify(t):`"${t}"`,"y"),yt=o(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return Ls(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let a="[";for(let c=0;c<t.length;c++)c>0&&(a+=","),a+=yt(t[c]);return a+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let a=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${a} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let s=t,r=Object.keys(s).sort(),i="{",n=!0;for(let a of r){let c=s[a];c!==void 0&&(n?n=!1:i+=",",i+=Ls(a),i+=":",i+=yt(c))}return i+"}"},"i"),Y=o(t=>yt(E(t)),"u");var P=class t{static{o(this,"r")}static key(e,s,r){return`${e}::${Y(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()}};var bt=0,Qs=o(()=>bt,"L"),X=o((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),V=o((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),gt=o((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),V(t,s);let n=o(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"a"),a=o(()=>{V(t,X(t.serverBase,t.optimisticLayers))},"s");return{confirm:o(c=>{if(c===void 0){n();return}r.commitCursor=c,bt+=1,r.acknowledgedAt=bt,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&a()},"confirm"),rollback:o(()=>{i||(i=!0,n(),a())},"rollback")}},"y"),$e=o((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"),_s=o((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"h"),Ds=o((t,e)=>{let s=[],r=[],i=o((n,a)=>t.get(P.key(n,a,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:o(n=>{let a=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&a.push({args:c.args,value:c.lastValue});return a},"getAllQueries"),getQuery:o((n,a)=>i(n.__lunoraRef,a??{})?.lastValue,"getQuery"),setQuery:o((n,a,c)=>{let u=i(n.__lunoraRef,a??{});if(!u)return;let h=gt(u,()=>c);h&&(s.push(h.confirm),r.push(h.rollback))},"setQuery")}}},"v");var Us=0,si=o(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();Us+=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)}_${Us.toString(36)}_${t}`},"d"),vt=o((t,e)=>t!==void 0&&e!==t,"f"),He=si,Z=o((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"o"),We=class{static{o(this,"l")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},s={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=s.persistence,this.onEvict=s.onEvict,this.onSizeChange=s.onSizeChange,this.version=s.version}get size(){return this.items.length}enqueue(e){let s=e;s.id??=He(),this.items.push(s),this.persistence?.append({args:s.args,...s.baselineSeq===void 0?{}:{baselineSeq:s.baselineSeq},clientId:s.clientId,functionPath:s.functionPath,id:s.id,identity:s.identity,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(r=>{Z(this.onPersistenceError,"append",r,s.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(a){throw Z(this.onPersistenceError,"load",a),a}let s=[],r=new Set(this.items.map(a=>a.id));for(let a of e)if(!r.has(a.id)){if(vt(this.version,a.version)){this.persistence.remove(a.id).catch(c=>{Z(this.onPersistenceError,"remove",c,a.id)});continue}r.add(a.id),s.push({args:a.args,baselineSeq:a.baselineSeq,clientId:a.clientId,functionPath:a.functionPath,id:a.id,identity:a.identity,reject:o(()=>{},"reject"),resolve:o(()=>{},"resolve"),shardKey:a.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let a of s)i.has(a)&&n.add(a.shardKey);return[...n]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;if(!this.persistence||i===void 0)continue;let n={args:r.args,...r.baselineSeq===void 0?{}:{baselineSeq:r.baselineSeq},clientId:r.clientId,functionPath:r.functionPath,id:i,identity:s,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(a=>{Z(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.notifySize(),i}let s=[],r=[];for(let i of this.items)(e(i)?s:r).push(i);return this.items.length=0,this.items.push(...r),this.notifySize(),s}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],s=[];for(let r of this.items)if(r.precondition!==void 0&&!r.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",r.reject(i),e.push(r)}else s.push(r);return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of this.items){let s=new Error("CLIENT_CLOSED");s.code="CLIENT_CLOSED",e.reject(s)}this.items.length=0,this.notifySize()}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await r.replace(s)}catch(i){Z(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(r=>{Z(this.onPersistenceError,"remove",r,e.id)});let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var ri="lunora-outbox",ii="offline-mutations",St="by_id",ni=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new y("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??ri,r=t.storeName??ii,i=Ne(e,s,1,a=>{a.objectStoreNames.contains(r)||a.createObjectStore(r,{autoIncrement:!0}).createIndex(St,"id",{unique:!0})}),n=qe(i,r);return{append:o(async a=>{await n("readwrite",c=>A(c.add(a)))},"append"),clear:o(async()=>{await n("readwrite",a=>A(a.clear()))},"clear"),load:o(async()=>n("readonly",a=>A(a.getAll())),"load"),remove:o(async a=>{await n("readwrite",async c=>{let u=await A(c.index(St).getKey(a));u!==void 0&&await A(c.delete(u))})},"remove"),replace:o(async a=>{await n("readwrite",async c=>{let u=await A(c.index(St).getKey(a.id));u!==void 0&&await A(c.put(a,u))})},"replace")}},"w"),Ns=o((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return ni()}},"b");var wt=o((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let a=Math.min(r,s*2**n);if(n+=1,!i)return a;let c=a/2;return Math.floor(c+e()*(a-c))},reset(){n=0}}},"s");var qs=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),js=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED","UNAUTHORIZED"]),Ks=o(t=>js.has(t?.code??""),"y"),Bs=o(t=>{if(t instanceof B)return!0;let e=t?.code;return e===void 0||qs.has(e)||js.has(e)},"O"),$s=6e4,ai=1e3,Ws=o(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},"A"),oi={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},de=o((t,e,s)=>{let r=Ws(s),i=r===void 0?void 0:{retryAfterMs:r},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new B(n,i):new y(oi[t]??"BAD_REQUEST",n,{data:i})},"M"),le=o(t=>{let e=t?.error;return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0},"h"),Hs=o(()=>new B("LunoraClient: batch slot carried no error envelope"),"p"),zs=o((t,e)=>{let s=Ws(e);if(!(s===void 0||mt(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},"N"),Ct=o((t,e=Math.random)=>{let s=Math.min(ai*2**Math.max(t-1,0),$s);return Math.round(s*(.5+e()*.5))},"f"),ci=o(t=>t instanceof B||qs.has(t?.code??""),"T"),Vs=o((t,e,s)=>{let r=mt(t);return r!==void 0&&r>0?Math.min(r,$s):ci(t)?Ct(e,s):void 0},"v"),Gs=983040,Js=o(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"m"),Ys=new WeakSet,kt=o(t=>{let e=new y("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 Ys.add(e),e},"U"),we=o(t=>t instanceof Error&&Ys.has(t),"b");var Xs=o((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present?Y(i.value):void 0;return()=>{let a=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!a.present?!0:Y(a.value)===n}},"c");var Tt=500,ui=o(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}},"We"),Zs=o((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"te");new TextDecoder;var hi=new TextEncoder,di=o(t=>ks(hi.encode(JSON.stringify(t))),"je"),li="x-lunora-expect-subject",fi=o(t=>di({subject:t}),"ze"),er=Symbol.for("lunora:session-change"),pi="lunora:session-change",mi="better-auth.message",yi="signout",cr=o(()=>{let t=globalThis,e=t[er];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[er]=e),e},"de"),bi=o(()=>"document"in globalThis,"Xe"),gi=o(async()=>{let t=[];for(let e of cr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"Ze"),vi=o((t,e)=>{if(t!==mi||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===yi}catch{return!1}},"et"),Si=o(t=>{let e=[],s=o(()=>{gi().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(pi):void 0}catch{r=void 0}if(r!==void 0){let n=r;n.addEventListener("message",a=>{a.data?.type==="lunora:session-change"&&a.data.tab!==t&&s()}),e.push(()=>{n.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let n=o(a=>{vi(a.key,a.newValue)&&s()},"i");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"tt"),wi=o(t=>{let e=cr();return e.listeners.add(t),e.detach===void 0&&bi()&&(e.detach=Si(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"st"),re=class{static{o(this,"O")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[s]=e;for(let r of this.listeners)try{r(s)}catch{}}clear(){this.listeners.clear()}},Ci=o(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:n}=t,a=s>0&&e>0,c=0,u,h=!1,d=!1,l=o(()=>{u!==void 0&&(clearInterval(u),u=void 0,h=!1,i())},"u"),f=o(m=>{if(u!==void 0){if(!m){l();return}h||(h=!0,i()),r()}},"f"),p=o(()=>{d||(d=!0,n().then(f).finally(()=>{d=!1}).catch(()=>{}))},"p");return{isPolling:o(()=>u!==void 0&&h,"isPolling"),noteFailedOpen:o(()=>{c+=1,!(!a||u!==void 0||c<e)&&(u=setInterval(p,s),i(),p())},"noteFailedOpen"),noteOpen:o(()=>{c=0,l()},"noteOpen"),stop:l}},"rt"),ki="/_lunora/rpc",Et="/_lunora/rpc-batch",Ti="/_lunora/ws",It=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"D"),Ce=o(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"F"),tr=Symbol("lunora.unmergeableDelta"),Ei=o((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"at"),Ii="lunora-ping",Oi=3e4,Ri=1e4,Ai=5e3,Pi=3,Fi=250,Mi=5e3,xi=64,Li=3,Qi=1e4,_i=8,Di="/_lunora/admin/shard-traffic",Ui="/_lunora/admin/scheduled",Ni="/_lunora/admin/scheduled/status",qi="/_lunora/admin/scheduled/ws",ji="/_lunora/admin/scheduled/cancel",sr="/_lunora/admin/scheduled/dead",Ki="/_lunora/admin/scheduled/dead/retry",Bi="/_lunora/admin/scheduled/dead/cancel",$i="/_lunora/admin/workflows/instances",Wi="/_lunora/admin/workflows/instance",Hi="/_lunora/admin/workflows/status",Ot="/_lunora/admin/storage",zi="/_lunora/admin/storage/url",Vi="/_lunora/admin/storage/buckets",Gi="/_lunora/admin/functions",Ji="/_lunora/admin/cron-jobs",Yi="/_lunora/admin/cron-jobs/run",Xi="/_lunora/admin/openapi",Zi="/_lunora/admin/openrpc",en="/_lunora/admin/global/tables",tn="/_lunora/admin/global/table",sn="/_lunora/admin/global/facet",rn="/_lunora/admin/vector/indexes",nn="/_lunora/admin/vector/query",an="/_lunora/admin/logs/archive",on="/_lunora/admin/kv/namespaces",cn="/_lunora/admin/kv/keys",Rt="/_lunora/admin/kv/value",un="/_lunora/admin/auth/users",hn="/_lunora/admin/auth/sessions",dn="/_lunora/admin/auth/users/create",ln="/_lunora/admin/auth/users/role",fn="/_lunora/admin/auth/users/ban",pn="/_lunora/admin/auth/users/unban",mn="/_lunora/admin/auth/users/password",yn="/_lunora/admin/auth/users/remove",bn="/_lunora/admin/auth/users/impersonate",gn="/_lunora/admin/auth/sessions/revoke",vn="/_lunora/admin/auth/sessions/revoke-all",Sn="/_lunora/admin/auth/capabilities",wn="/_lunora/admin/auth/users/update",Cn="/_lunora/admin/auth/accounts",kn="/_lunora/admin/auth/accounts/unlink",Tn="/_lunora/admin/auth/passkeys",En="/_lunora/admin/auth/passkeys/delete",In="/_lunora/admin/auth/two-factor/disable",On="/_lunora/admin/auth/organizations",Rn="/_lunora/admin/auth/organizations/members",An="/_lunora/admin/auth/organizations/invitations",Pn="/_lunora/admin/auth/organizations/members/remove",Fn="/_lunora/admin/auth/organizations/invitations/cancel",Mn="/_lunora/admin/auth/config",xn="/_lunora/admin/auth/sign-up-invitations",Ln="/_lunora/admin/auth/sign-up-invitations/create",Qn="/_lunora/admin/auth/sign-up-invitations/revoke",_n="/_lunora/admin/auth/organizations/create",Dn="/_lunora/admin/auth/organizations/update",Un="/_lunora/admin/auth/organizations/remove",Nn="/_lunora/admin/auth/organizations/members/add",qn="/_lunora/admin/auth/organizations/members/invite",jn="/_lunora/admin/auth/organizations/members/role",Kn="/_lunora/admin/auth/organizations/teams",Bn="/_lunora/admin/auth/organizations/teams/create",$n="/_lunora/admin/auth/organizations/teams/update",Wn="/_lunora/admin/auth/organizations/teams/remove",Hn="/_lunora/admin/auth/organizations/teams/members",zn="/_lunora/admin/auth/organizations/teams/members/add",Vn="/_lunora/admin/auth/organizations/teams/members/remove",Gn="/_lunora/admin/auth/organizations/roles",Jn="/_lunora/admin/auth/organizations/roles/create",Yn="/_lunora/admin/auth/organizations/roles/update",Xn="/_lunora/admin/auth/organizations/roles/remove",Zn="/api/auth",ea="/get-session",At=o(t=>t==="connected"||t==="polling","W"),ta=o((t,e,s)=>t!==null||e&&s===null,"Hs"),rr=o(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"ne"),ee=o((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"C"),R=o((t,e)=>{let s=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&s.set(i,String(n));let r=s.toString();return r===""?t:`${t}?${r}`},"S"),sa=[Rs],g=o(t=>t??"","l"),ur=o((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}},"ue"),ra=o(t=>{let{code:e,messageText:s}=ur(t,"stream error");return e===void 0?new Error(s):new y(e,s)},"xs"),ir=o(t=>{let{code:e,messageText:s}=ur(t,"subscription error");return{message:s,...e===void 0?{}:{code:e}}},"ae");function Pt(t){if(t!==void 0)return e=>{t(e)}}o(Pt,"$");var te=o((t,e)=>{for(let s of t)try{s(e)}catch{}},"k"),ia=new TextDecoder,na=o(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return ia.decode(t)},"Bs"),Q=o((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"g"),Lt=o(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,t.data!==void 0)try{e.data=S(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"z"),nr=o((t,e)=>{let s=Lt(t),r=zs(s,e);return r!==void 0&&(s.data=r),s},"oe"),se=o((t,e)=>{try{return E(t)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${r}`,s instanceof Error?{cause:s}:void 0)}},"w"),aa=1e4,ar=o(async t=>{let e=new AbortController,s,r=new Promise((i,n)=>{s=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},aa)});try{return await Promise.race([t(e.signal),r])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(s)}},"ce"),or=o(t=>{try{return E(t),!0}catch{return!1}},"he"),Ft=o(t=>"args"in t?{...t,args:S(t.args)}:t,"j"),hr=o(t=>{let e=le(t);return e===void 0?Hs():Lt(e)},"le"),oa=o((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;let i=r.body;s[r.id]=i!==void 0&&"error"in i?{error:hr(i),ok:!1}:{ok:!0,value:S(i?.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"Ds"),Mt=o((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"G"),ca=Promise.resolve(),xt=class t{static{o(this,"fe")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new P;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;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 re;statusListeners=new re;tokenExpiredListeners=new re;identityChangeListeners=new re;authRefusalNotifiedFor;mutationSettledListeners=new re;pendingChangeListeners=new re;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??ee(rr(e.url),Ti),this.wsToken=e.wsToken;let s=e.authBasePath??Zn;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??Is(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Oi,this.connectTimeoutMs=e.connectTimeoutMs??Ri,this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??Ai,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Pi,this.defaultConnectionContext=e.connectionContext,this.persistence=Ns(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Es(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new je,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=ca),this.offlineQueue=new We(e.offlineQueue,{onEvict:o((r,i)=>{this.emitItemSettled(r,"rejected",i)},"onEvict"),onSizeChange:o(r=>{this.pendingChangeListeners.emit(r)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${He()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=wi(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),c=this.isKnownNobody();this.authToken=e,this.applySubject(e,s);let u=this.identityFingerprint();u!==i&&(!r&&e!==null&&n?(this.restampQueuedIdentity(i,u),this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&n&&!c?(this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),ta(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(a),r&&this.authTokenListeners.emit(e),(u!==i||r||a)&&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){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"}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 y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=r?.shardKey??"",a=this.identityFingerprint(),c,u,h;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o(d=>{c=d},"onMutationAck")})}catch(d){if(!we(d))throw d;h=d}if(c!==void 0&&c>(this.clientWatermarks.get(a??"")?.get(n)??0)){let d=this.clientWatermarks.get(a??"");d===void 0&&(Zs(this.clientWatermarks,_i),d=new Map,this.clientWatermarks.set(a??"",d)),d.set(n,c)}if(h!==void 0)throw h;return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}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(ee(this.url,`${this.authBasePath}${ea}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let n=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,n,r),n}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.bounceShardSockets())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=g(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=g(s.shardKey),i={context:e},n=this.connectionContextHolders.get(r);n?n.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let a=!1;return()=>{if(a)return;a=!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)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=g(r.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let a=n.get(e),c=a===void 0;if(a||(a=new Set,n.set(e,a)),a.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&Q(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(s)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(r.shardKey);d&&Q(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,s,r={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey);i&&Q(i,{data:se(s??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let n of r){let a=this.connections.get(n);e.push({confirmedMutationWatermark:s?.get(n)??0,hasSocket:a?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,a)=>(n.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((n,a)=>n.functionPath.localeCompare(a.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 Xs(this,e,s,r)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){if(!this.readyResolved)return;let i=Y(s),n=ae(e,i,r),a=this.hydratedQueryCache.get(n);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=P.key(e,s,r),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,s,r={}){let{value:i}=await this.runMutation(e,s,r);return i}canQueueOffline(e){let{wasEverConnected:s}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(s||this.offlineQueue.queueBeforeFirstConnect)}async action(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),n=r.toArgs??(d=>({rows:d})),a=s.length,c=0,u=0,h=0;for(let d=0;d<a;d+=i){let l=s.slice(d,d+i),f=h,{committed:p}=await this.runMutation(e,n(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(f)}`},shardKey:r.shardKey});h+=1,c+=l.length,p&&(u+=l.length),r.onProgress?.({done:c,total:a})}return{chunks:h,imported:u,queued:c-u}}async shardTraffic(e){this.assertOpen();let s=await this.adminFetch(Di,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch(Ui,"GET")).records??[]).map(e=>Ft(e))}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(Ni,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(ji,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await ui(async e=>await this.adminFetch(e===void 0?sr:`${sr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>Ft(e))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Ki,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Bi,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.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 this.adminFetch(`${$i}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}}async getWorkflowInstance(e){this.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await this.adminFetch(`${Wi}?${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??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Hi,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=ee(rr(this.url),qi),r=wt(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,a=!1,c=o(()=>{a||this.closed||(n=setTimeout(d,r.next()))},"a"),u=o(f=>{if(a||this.WebSocketImpl===void 0)return;let p=f===void 0?s:`${s}?token=${encodeURIComponent(f)}`;this.openManagedSocket(i,p,this.connectTimeoutMs,{onClose:o(()=>{c()},"onClose"),onMessage:o(m=>{let b;try{b=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(r.reset(),e(b.records.map(w=>Ft(w))))},"onMessage")})},"o"),h=o(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"h"),d=o(()=>{if(a||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}u(f)},"d");d();let l=o(()=>{a=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close(),i.socket=void 0},"u");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Gi,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Ji,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let s=await this.adminFetch(Yi,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Xi,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Zi,"GET")}async listStorageObjects(e={}){this.assertOpen();let s=R(Ot,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await this.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}}async deleteStorageObject(e,s){this.assertOpen();let r=`${Ot}?key=${encodeURIComponent(e)}${It(s?.bucket)}`,i=await this.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Vi,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let s=`${Ot}?key=${encodeURIComponent(e.key)}${It(e.bucket)}`,r=await this.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}}async signedStorageUrl(e,s){this.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${zi}?key=${encodeURIComponent(e)}${i}${It(s?.bucket)}`,a=await this.adminFetch(n,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(en,"GET")}async readGlobalTablePage(e){this.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(E(e.filters))),S(await this.adminFetch(`${tn}?${s.toString()}`,"GET"))}async facetGlobalColumn(e){this.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(E(e.filters))),S(await this.adminFetch(`${sn}?${s.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(rn,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(nn,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let s=await this.adminFetch(an,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(on,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let s=R(cn,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(s,"GET")}async getKvValue(e){this.assertOpen();let s=R(Rt,{key:e.key,namespace:e.namespace});return await this.adminFetch(s,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(Rt,"PUT",e)}async deleteKvKey(e){this.assertOpen();let s=R(Rt,{key:e.key,namespace:e.namespace});await this.adminFetch(s,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let s=R(un,{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 await this.adminFetch(dn,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(ln,"POST",e)}async banAuthUser(e){return await this.adminFetch(fn,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(pn,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(mn,"POST",e)}async removeAuthUser(e){await this.adminFetch(yn,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(bn,"POST",e)}async revokeAuthSession(e){await this.adminFetch(gn,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(vn,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(Sn,"GET")}async updateAuthUser(e){return await this.adminFetch(wn,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(R(Cn,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(kn,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(R(Tn,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(En,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(In,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(R(On,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let s=R(Rn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){let s=R(An,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){let s=R(xn,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(Ln,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(Qn,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(Pn,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(Fn,"POST",e)}async getAuthConfig(){return await this.adminFetch(Mn,"GET")}async createAuthOrganization(e){return await this.adminFetch(_n,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(Dn,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(Un,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(Nn,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(qn,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(jn,"POST",e)}async listAuthOrgTeams(e){let s=R(Kn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(Bn,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch($n,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Wn,"POST",e)}async listAuthOrgTeamMembers(e){let s=R(Hn,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(zn,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Vn,"POST",e)}async listAuthOrgRoles(e){let s=R(Gn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Jn,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Yn,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Xn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=R(hn,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){this.assertOpen();let n=s??{},a=P.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(a),u=Pt(r),h=Pt(i.onError),d=Pt(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=Y(n),m=this.takeHydratedCache(e.__lunoraRef,p,i.shardKey);c={acked:!1,args:n,argsKey:p,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,wireArgs:se(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(a,m)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(P.keyOf(l)),this.subscriptions.remove(l))}}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:a}=r;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:se(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new y("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=r,a=s??{},{handle:c,iterable:u}=Be({maxBuffer:r.maxBuffer,onCancel:o(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:se(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n,started:!1};this.streams.set(i,l);let f=h?.wsState==="open"&&Q(h,d);if(l.started=f,!f&&h===void 0)return this.streams.delete(i),c.fail(new y("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=xi;){let p=h.pendingStreams.shift()?.id,m=p?this.streams.get(p):void 0;m&&(m.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(p))}h.pendingStreams.push(d)}return u}httpStream(e,s,r={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return xs(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new y("INTERNAL","LunoraClient is closed")}followsAnotherTab(){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 y("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}teardownConnection(e){e.polling.stop();let s=g(e.shardKey);for(let[r,i]of this.streams)g(i.shardKey)===s&&(i.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(r));if(e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new Ke({channelName:e,onBecomeLeader:o(()=>{for(let s of this.subscriptions.all())this.ensureSocket(s.shardKey),this.queueResubscribe(s);for(let s of this.queuedOfflineShardKeys)this.ensureSocket(s);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:o(()=>{for(let[s,r]of this.connections)this.teardownConnection(r),this.connections.delete(s);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:o((s,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;let i=s==="connected"&&this.leaderStatus!=="connected"||s==="polling"&&this.leaderStatus!=="connected"&&this.leaderStatus!=="polling";this.leaderStatus=s,s==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},"onConnectionStatus"),onSubscriptionData:o((s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;let c=this.subscriptions.get(s);c&&(c.serverBase=r,this.dropCacheSeed(s),i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),$e(c,i)),V(c,X(r,c.optimisticLayers)))},"onSubscriptionData"),onLeaderClaimAnswered:o(()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onLeaderClaimAnswered"),onSubscriptionError:o((s,r,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;let n=this.subscriptions.get(s);n&&te(n.errorCallbacks,r)},"onSubscriptionError"),onSubscriptionSettled:o((s,r,i,n,a,c)=>{if(c!==void 0&&c!==this.identityFingerprint())return;let u=this.subscriptions.get(s);if(u){this.ackAndAdvanceCursor(u,r,i),n!==void 0&&a===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let h of u.checkpointCallbacks)h({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(ee(this.url,Et),{body:JSON.stringify({calls:e.map((c,u)=>({args:se(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let n;try{n=await r.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let a=le(n);if(!r.ok||a!==void 0&&!n.results)throw a!==void 0?Lt(a):new y("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let c of n.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return oa(n.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=s,n=r.mutationId??He(),a=r.replayBaseline===void 0?this.baselineCursorFor(r.shardKey):r.replayBaseline??void 0,{confirms:c,rollbacks:u}=this.applyOptimisticUpdates(e.__lunoraRef,i,r.shardKey,r.optimistic);r.optimisticUpdate&&this.applyOptimisticUpdate(r.optimisticUpdate,s,r.shardKey,u,c);let h=this.offlineFlushes.get(g(r.shardKey));h!==void 0&&await h;let{hasSocket:d,polling:l,wasEverConnected:f,wsState:p}=this.connectionGateState(r.shardKey),{queueBeforeFirstConnect:m}=this.offlineQueue,b=f||m,w=this.WebSocketImpl!==void 0&&b,k=p==="connecting"&&b&&!l,F=p!=="open"&&!d&&w&&!l,_=w&&r.replayBaseline===void 0&&this.hasPendingWriteAhead(r.shardKey),N=o(async()=>this.enqueueOfflineMutation(e,i,r.shardKey,a,n,u,c,r.precondition,r.mutationId),"V");if(F||k||_)return N();let D;try{let $=await this.rpc(e.__lunoraRef,i,r.shardKey,{baselineSeq:a,captureBookmark:!0,...Mt(r.replayIdentity,this.authToken),mutationId:n,onCommitCursor:o(M=>{D=M},"onCommitCursor")});for(let M of c)M(D);return{committed:!0,value:$}}catch($){if(l&&w&&$ instanceof TypeError&&or(i))return N();throw this.settleFailedDirectWrite($,D,c,u),$}}settleFailedDirectWrite(e,s,r,i){if(this.noteIdentityMismatch(e),we(e)){for(let n of r)n(s);return}Ce(i)}async enqueueOfflineMutation(e,s,r,i,n,a,c,u,h){let d=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let l=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:h??`${this.clientId}:${String(l)}`,identity:d,mutationId:l,...a.length>0&&{onRejected:o(()=>{Ce(a)},"onRejected")},shardKey:r})}catch(f){throw Ce(a),f instanceof Error?f:new Error(String(f))}for(let f of c)f(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((l,f)=>{let p={args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,clientId:this.clientId,identity:d,precondition:u,onCommit:o(m=>{for(let b of c)b(m)},"onCommit"),reject:o(m=>{this.queuedIdentities.delete(n),we(m)||Ce(a),f(m instanceof Error?m:new Error(String(m)))},"reject"),resolve:l,shardKey:r};this.offlineQueue.enqueue(p),this.queuedOfflineShardKeys.add(r),p.id!==void 0&&this.queuedIdentities.set(p.id,d)})}}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=o(()=>{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(ae(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(vt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let n=s.get(r);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(ae(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),V(e,X(s.value,e.optimisticLayers)))}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,V(r,X(void 0,r.optimisticLayers))),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=ae(e,s,r),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=ae(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=ae(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:s,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},Fi))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"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&&(or(c.args)?r.push(c):te(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=Qs(),n=this.identityFingerprint(),a;try{a=await ar(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(let[c,u]of r.entries()){let h=a[c];if(h!==void 0){if(!h.ok){te(u.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:E(h.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await ar(async s=>e(ee(this.url,Et),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let n=[],a=[];if(!i)return{confirms:n,rollbacks:a};let c=P.key(e,s,r),u=this.subscriptions.get(c);if(u){let h=gt(u,i);h&&(n.push(h.confirm),a.push(h.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,s,r,i,n){let{confirms:a,rollbacks:c,store:u}=Ds(this.subscriptions,r);try{e(u,s)}catch{Ce(c);return}i.push(...c),n.push(...a)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!Q(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let r="idle";return this.leaderStatus==="connected"?r="open":this.leaderStatus==="connecting"&&(r="connecting"),{hasSocket:!1,polling:this.leaderStatus==="polling",wasEverConnected:this.leaderWasEverConnected,wsState:r}}let s=this.getConnection(e);return{hasSocket:s?.socket!==void 0,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??!1,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:Ci({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:o(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:o(()=>{this.emitConnectionStatus()},"onStateChange"),poll:o(async()=>this.pollSubscriptions(e),"poll")}),reconnect:wt(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(s,r)),r}wsUrlFor(e,s){let r=[];if(e!==void 0&&r.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&r.push(`token=${encodeURIComponent(s)}`),r.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${r.join("&")}`}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[li]=fi(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(r.authorization=`Bearer ${n}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(r["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(r["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let a=this.bookmark.get();a&&(r["x-d1-bookmark"]=a)}return r}async rpc(e,s,r,i={}){if(!this.fetchImpl)throw new B("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,r),a=await this.fetchImpl(ee(this.url,ki),{body:JSON.stringify({args:se(s,`args for '${e}'`),functionPath:e,shardKey:r}),headers:n,method:"POST"});if(i.captureBookmark){let d=a.headers.get("x-d1-bookmark");d&&this.bookmark.set(d)}let c;try{c=await a.json()}catch{throw de(a.status,a.statusText,a.headers.get("retry-after"))}let u=c;if(typeof u!="object"||u===null||Array.isArray(u))throw de(a.status,a.statusText,a.headers.get("retry-after"));let h=le(c);if(h!==void 0)throw nr(h,a.headers.get("retry-after"));if(!a.ok)throw de(a.status,a.statusText,a.headers.get("retry-after"));i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.learnDefaultShardKey(a,r),this.recordShardCursor(r,c.commitCursor);try{return S(c.result)}catch(d){throw kt(d)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let a=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:a?(c=r,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(r),n["content-type"]="application/json");let u=await this.fetchImpl(ee(this.url,e),{body:c,headers:n,method:s}),h;try{h=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let d=le(h);if(d!==void 0){let l=new Error(d.message??"admin request failed");throw l.code=d.code,l}if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return h}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));Q(e,{caps:sa,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())g(s.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);if(!(s.wsState==="open"||s.wsState==="connecting")){if(s.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(s,e,this.wsToken).catch(()=>{});return}this.openSocket(s,e,this.wsToken)}}async openSocketWithProvidedToken(e,s,r){let i;try{i=await r()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,s,i)}openManagedSocket(e,s,r,i){let{WebSocketImpl:n}=this;if(n===void 0)throw new y("INTERNAL","no WebSocket implementation available");let a=new n(s);e.socket=a;let c=o(()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===a&&(e.socket=void 0)},"a"),u=o(h=>{c(),i.onClose(h)},"o");r>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===a){try{a.close()}catch{}u()}},r)),a.addEventListener("open",()=>{if(e.socket===a){e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now();try{i.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}this.startHeartbeat(e,u)}}),a.addEventListener("message",h=>{if(e.socket===a){e.lastFrameAt=Date.now();try{i.onMessage(h)}catch(d){console.error("[lunora] server frame handler threw",d)}}}),a.addEventListener("close",h=>{e.socket===a&&u(h)}),a.addEventListener("error",()=>{e.socket===a&&u()})}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,this.openManagedSocket(e,this.wsUrlFor(s,r),this.connectTimeoutMs,{onClose:o(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:o(i=>{e.retired!==!0&&this.handleServerMessage(i.data,s)},"onMessage"),onOpen:o(()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Mi),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(s),this.clearResubscribeQueue(e);for(let n of this.subscriptions.all())g(n.shardKey)===g(s)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:a,type:c}of n)Q(e,{id:a,type:c})}this.flushPendingStreams(e);let i=this.whisperHandlers.get(g(s));if(i)for(let n of i.keys())Q(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(s).catch(()=>{})},"onOpen")}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;let s=e.pendingStreams;e.pendingStreams=[];for(let r of s){let i=Q(e,r)?this.streams.get(String(r.id)):void 0;i&&(i.started=!0)}}cancelStream(e,s){let r=this.getConnection(s),i=this.streams.get(e);r&&(r.pendingStreams=r.pendingStreams?.filter(n=>n.id!==e),!Q(r,{id:e,type:"unsubscribe"})&&i?.durable===!0&&i.started&&r.pendingUnsubscribes.push({id:e,type:"unsubscribe"})),this.streams.delete(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),this.stopHeartbeat(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(g(n.shardKey)!==g(e.shardKey)||s.has(i))){if(n.durable){let a={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),a];continue}n.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}startHeartbeat(e,s){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;let{socket:r}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{r.close()}catch{}s();return}try{r.send(Ii)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){let s=g(e);for(let r of this.subscriptions.all())g(r.shardKey)===s&&(r.acked=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribePending.size<Li;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribePending.set(s.id,setTimeout(()=>{this.releaseResubscribeSlot(e,s.id)},Qi))}}releaseResubscribeSlot(e,s){let r=e.resubscribePending.get(s);r!==void 0&&(clearTimeout(r),e.resubscribePending.delete(s),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(let s of e.resubscribePending.values())clearTimeout(s);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.acked)return!1;let r=e.serverCursor!==void 0&&e.serverBase!==void 0;return Q(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...r?{sinceSeq:e.serverCursor}:{},...r&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&Q(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=na(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}if(i.type!=="error"&&this.getConnection(s)?.reconnect.reset(),typeof i.id=="string"){let n=this.getConnection(s);n&&this.releaseResubscribeSlot(n,i.id)}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:a,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof a=="number"&&(h.generation=a),h.durable=!0),h?.handle.push(S(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.handlePokePart(i,s);break}case"pokeStart":{this.handlePokeStart(i,s);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(ra(e)),this.streams.delete(s);return}let i=s===void 0?void 0:this.subscriptions.getById(s);if(i){let a=ir(e),c=this.identityFingerprint(),u=P.keyOf(i);te(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,a,c);return}let n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&te(n.errorCallbacks,ir(e))}pokeBufferKey(e,s){return`${g(e)}\0${s}`}handlePokeStart(e,s){Zs(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(s,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}handlePokePart(e,s){let r=this.pokeBuffers.get(this.pokeBufferKey(s,e.pokeId));if(!r)return;let i=[];try{for(let c of e.rowsPatch)i.push(c.value===void 0?c:{...c,value:S(c.value)})}catch(c){r.undecodable.set(e.shapeId,c);return}let n=r.parts.get(e.shapeId)??[];for(let c of i)n.push(c);r.parts.set(e.shapeId,n),e.lastMutationId!==void 0&&r.lastMutationId.set(e.shapeId,e.lastMutationId);let a=e.baseCheckpoint??r.baseCheckpoint;a!==void 0&&r.bases.set(e.shapeId,a),e.reset===!0&&r.resets.add(e.shapeId)}handlePokeEnd(e,s){let r=this.pokeBufferKey(s,e.pokeId),i=this.pokeBuffers.get(r);if(i){this.pokeBuffers.delete(r);for(let[n,a]of i.undecodable){let c=this.shapeSubscriptions.get(n);c&&te(c.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${a instanceof Error?a.message:String(a)}`})}for(let n of i.parts.keys()){let a=this.shapeSubscriptions.get(n);a&&!i.undecodable.has(n)&&this.applyPokePart(a,i,e)}}}applyPokePart(e,s,r){let i=s.parts.get(e.id)??[],n=s.resets.has(e.id),a=s.bases.get(e.id),c=s.epoch!==void 0&&e.serverEpoch!==void 0&&s.epoch!==e.serverEpoch,u=a!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==a;if(!n&&(c||u)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}n&&e.rows.clear(),Ei(e.rows,i),r.checkpoint!==void 0&&(e.serverCursor=r.checkpoint),r.epoch!==void 0&&(e.serverEpoch=r.epoch);let h=s.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){let s=[...e.rows.values()];for(let r of e.callbacks)try{r(s)}catch{}}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i)return;let n;try{n=this.resolveDataPayload(e,i)}catch(a){te(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${a instanceof Error?a.message:String(a)}`});return}if(n===tr){this.resnapshotSubscription(i);return}if(i.serverBase=n,this.dropCacheSeed(P.keyOf(i)),e.cursor!==void 0&&(i.serverCursor=e.cursor),e.epoch!==void 0&&(i.serverEpoch=e.epoch),e.lastMutationId!==void 0){i.lastMutationId=Math.max(i.lastMutationId??0,e.lastMutationId);for(let a of i.checkpointCallbacks)a({checkpoint:i.serverCursor,mutationId:i.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(i),$e(i,i.serverCursor),s!==void 0&&_s(i,s),V(i,X(n,i.optimisticLayers)),this.tabCoordinator?.isLeader()){let a=P.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(a,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,e.cursor,e.epoch)}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s){this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&(s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId));for(let r of s.checkpointCallbacks)r({checkpoint:s.serverCursor,mutationId:s.lastMutationId});if(this.tabCoordinator?.isLeader()){let r=P.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,s,r){e.acked=!0,(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),$e(e,e.serverCursor)&&V(e,X(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,s){if("data"in e&&e.data!==void 0)return S(e.data);let r=S(e.delta);return As(r)?s.serverBase===void 0?r:Ps(s.serverBase,r)??tr:r}dispatchWhisper(e,s){let r=this.whisperHandlers.get(g(s))?.get(e.topic);if(!r)return;let i=S(e.data);for(let n of r)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.streams.delete(e);return}let r=this.subscriptions.getById(e);r&&(r.acked=!1,te(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(s=>{Z(this.onPersistenceError,"remove",s,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);s^=n,s=Math.imul(s,16777619),r=Math.imul(r,33)+n}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&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)}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}rejectQueuedForIdentityChange(e){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.replayIdentityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let n=s??"",a=this.clientWatermarks.get(n);if(a===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)a.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.revokeCacheSeededValues();for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,V(e,X(void 0,e.optimisticLayers));for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e);this.bounceShardSockets(),this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=g(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&At(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&this.offlineFlushes.delete(s)}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let d of r){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",l)}let i=g(e),n=this.offlineQueue.drain(d=>g(d.shardKey)===i);if(n.length===0)return;let a=[],c=[];for(let d of n){let l=this.replayGateVerdict(d);l==="send"?a.push(d):l==="hold"&&c.push(d)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),a.length===0){this.scheduleRateLimitedRetry(e);return}let u=this.encodableOrSettleTerminal(a);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let h=[];for(let d=0;d<u.length;d+=Tt){let l=u.slice(d,d+Tt),f=await this.replayBatched(l,e,s);if(h.push(...f.requeue),f.stop){h.push(...u.slice(d+Tt));break}}h.length>0&&this.offlineQueue.requeue(h),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,Ct(i))})}noteReplayRetryDelay(e,s){let r=g(e),i=this.replayRetryState.get(r),n=(i?.attempts??0)+1,a=Vs(s,n);this.replayRetryState.set(r,{attempts:n,delayMs:a===void 0?i?.delayMs:Math.max(i?.delayMs??0,a)})}scheduleRateLimitedRetry(e){let s=g(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let n=this.replayRetryTimers.get(s);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{se(r.args,`args for '${r.functionPath}'`),s.push(r)}catch(i){this.settleReplayTerminal(r,i instanceof Error?i:new Error(String(i)))}return s}replayGateVerdict(e){let s=this.stampOf(e);if(s===void 0)return this.queuedIdentities.delete(e.id??""),"send";let r=this.replayIdentityVerdict(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){if(this.noteIdentityMismatch(e))return!0;if(Ks(e)){let r=this.hashToken(s??"");return s===this.authToken&&this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}return Bs(e)}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let n=e[i];if(!n)continue;let a;try{let c=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:r,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...Mt(n.identity,r),mutationId:n.id,onCommitCursor:o(u=>{a=u},"onCommitCursor")});this.settleReplaySuccess(n,c,a)}catch(c){if(we(c)){this.settleReplayUndecodable(n,c,a);continue}if(!this.shouldRequeueReplayFailure(c,r)){this.settleReplayTerminal(n,c);continue}this.noteReplayRetryDelay(s,c),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,d)=>({args:se(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:d,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&Js(i)>Gs)return await this.replayBatchedHalves(e,s,r);let n;try{n=await this.fetchImpl(ee(this.url,Et),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...Mt(e.find(h=>h.identity!==void 0)?.identity,r)}),method:"POST"})}catch{return{requeue:e,stop:!0}}let a=n.headers.get("x-d1-bookmark");if(a&&this.bookmark.set(a),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let c,u=n.headers.get("retry-after");try{c=await n.json()}catch{return this.settleWholeBatchError(e,de(n.status,n.statusText,u),s,r)}if(!c.results){let h=le(c),d=h===void 0?de(n.status,n.statusText,u):nr(h,u);return this.settleWholeBatchError(e,d,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof B||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s),{requeue:e,stop:!0};for(let n of e)this.settleReplayTerminal(n,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),s,r);if(n.stop)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};let a=await this.replayBatched(e.slice(i),s,r);return{requeue:[...n.requeue,...a.requeue],stop:a.stop}}settleReplayBatchSlots(e,s,r,i){let n=new Map;for(let c of s)typeof c.id=="number"&&c.body!==void 0&&n.set(c.id,c.body);let a=[];for(let[c,u]of e.entries()){let h=n.get(c);if(h===void 0)a.push(u);else if("error"in h){let d=hr(h);this.shouldRequeueReplayFailure(d,i)?(this.noteReplayRetryDelay(r,d),a.push(u)):this.settleReplayTerminal(u,d)}else this.settleReplayBatchResult(u,h)}return a}settleReplayBatchResult(e,s){let r;try{r=S(s.result)}catch(i){this.settleReplayUndecodable(e,kt(i),s.commitCursor);return}this.settleReplaySuccess(e,r,s.commitCursor)}};var dr=L(Dt(),1),lr=L(ie(),1);var ua=o(()=>{let t=(0,dr.c)(4),e=ht(),s,r,i;return t[0]!==e?(s=o(n=>e.onConnectionStatus(()=>{n()}),"o"),r=o(()=>e.connectionStatus(),"e"),i=o(()=>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,lr.useSyncExternalStore)(s,r,i)},"S");export{xt as a,br as b,rt as c,Rr as d,Lr as e,ht as f,ua as g};
|
|
9
|
+
`)}return!1},"d");for(;;){let{done:u,value:h}=await s.read();if(u)break;if(a(r.decode(h,{stream:!0})),c()){await s.cancel().catch(()=>{});return}}a(r.decode()),c()||e.fail(new y("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),xs=o((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new y("INTERNAL","httpStream: no `fetch` implementation available");let i=Xr(t,e??{},s.baseUrl??""),n=new AbortController,a;s.signal&&(s.signal.aborted?n.abort():(a=o(()=>{n.abort()},"l"),s.signal.addEventListener("abort",a,{once:!0})));let c=o(()=>{a&&s.signal?.removeEventListener("abort",a)},"d"),{handle:u,iterable:h}=Be({maxBuffer:s.maxBuffer,onCancel:o(()=>{n.abort()},"onCancel")});return(async()=>{try{let d=await r(i,{headers:{accept:"text/event-stream",...s.headers},method:t.method,signal:n.signal});if(!d.ok){await d.body?.cancel().catch(()=>{}),u.fail(new y("HTTP_STREAM_STATUS",`httpStream: request failed (status ${d.status.toString()})`,{status:d.status}));return}if(!d.body){u.fail(new y("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await ei(d.body,u)}finally{c()}})().catch(d=>{if(n.signal.aborted){u.complete();return}if(d instanceof Error&&"code"in d){u.fail(d);return}u.fail(new y("HTTP_STREAM_TRANSPORT",d instanceof Error?d.message:String(d),{cause:d}))}),h},"_");var ti=/["\\\u0000-\u001F\uD800-\uDFFF]/,Ls=o(t=>ti.test(t)?JSON.stringify(t):`"${t}"`,"y"),yt=o(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return Ls(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let a="[";for(let c=0;c<t.length;c++)c>0&&(a+=","),a+=yt(t[c]);return a+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let a=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${a} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let s=t,r=Object.keys(s).sort(),i="{",n=!0;for(let a of r){let c=s[a];c!==void 0&&(n?n=!1:i+=",",i+=Ls(a),i+=":",i+=yt(c))}return i+"}"},"i"),Y=o(t=>yt(E(t)),"u");var P=class t{static{o(this,"r")}static key(e,s,r){return`${e}::${Y(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()}};var bt=0,Qs=o(()=>bt,"L"),X=o((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),V=o((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),gt=o((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),V(t,s);let n=o(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"a"),a=o(()=>{V(t,X(t.serverBase,t.optimisticLayers))},"s");return{confirm:o(c=>{if(c===void 0){n();return}r.commitCursor=c,bt+=1,r.acknowledgedAt=bt,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&a()},"confirm"),rollback:o(()=>{i||(i=!0,n(),a())},"rollback")}},"y"),$e=o((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"),_s=o((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"h"),Ds=o((t,e)=>{let s=[],r=[],i=o((n,a)=>t.get(P.key(n,a,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:o(n=>{let a=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&a.push({args:c.args,value:c.lastValue});return a},"getAllQueries"),getQuery:o((n,a)=>i(n.__lunoraRef,a??{})?.lastValue,"getQuery"),setQuery:o((n,a,c)=>{let u=i(n.__lunoraRef,a??{});if(!u)return;let h=gt(u,()=>c);h&&(s.push(h.confirm),r.push(h.rollback))},"setQuery")}}},"v");var Us=0,si=o(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();Us+=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)}_${Us.toString(36)}_${t}`},"d"),vt=o((t,e)=>t!==void 0&&e!==t,"f"),He=si,Z=o((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"o"),We=class{static{o(this,"l")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},s={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=s.persistence,this.onEvict=s.onEvict,this.onSizeChange=s.onSizeChange,this.version=s.version}get size(){return this.items.length}enqueue(e){let s=e;s.id??=He(),this.items.push(s),this.persistence?.append({args:s.args,...s.baselineSeq===void 0?{}:{baselineSeq:s.baselineSeq},clientId:s.clientId,functionPath:s.functionPath,id:s.id,identity:s.identity,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(r=>{Z(this.onPersistenceError,"append",r,s.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(a){throw Z(this.onPersistenceError,"load",a),a}let s=[],r=new Set(this.items.map(a=>a.id));for(let a of e)if(!r.has(a.id)){if(vt(this.version,a.version)){this.persistence.remove(a.id).catch(c=>{Z(this.onPersistenceError,"remove",c,a.id)});continue}r.add(a.id),s.push({args:a.args,baselineSeq:a.baselineSeq,clientId:a.clientId,functionPath:a.functionPath,id:a.id,identity:a.identity,reject:o(()=>{},"reject"),resolve:o(()=>{},"resolve"),shardKey:a.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let a of s)i.has(a)&&n.add(a.shardKey);return[...n]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;if(!this.persistence||i===void 0)continue;let n={args:r.args,...r.baselineSeq===void 0?{}:{baselineSeq:r.baselineSeq},clientId:r.clientId,functionPath:r.functionPath,id:i,identity:s,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(a=>{Z(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.notifySize(),i}let s=[],r=[];for(let i of this.items)(e(i)?s:r).push(i);return this.items.length=0,this.items.push(...r),this.notifySize(),s}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],s=[];for(let r of this.items)if(r.precondition!==void 0&&!r.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",r.reject(i),e.push(r)}else s.push(r);return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of this.items){let s=new Error("CLIENT_CLOSED");s.code="CLIENT_CLOSED",e.reject(s)}this.items.length=0,this.notifySize()}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await r.replace(s)}catch(i){Z(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(r=>{Z(this.onPersistenceError,"remove",r,e.id)});let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var ri="lunora-outbox",ii="offline-mutations",St="by_id",ni=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new y("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??ri,r=t.storeName??ii,i=Ne(e,s,1,a=>{a.objectStoreNames.contains(r)||a.createObjectStore(r,{autoIncrement:!0}).createIndex(St,"id",{unique:!0})}),n=qe(i,r);return{append:o(async a=>{await n("readwrite",c=>A(c.add(a)))},"append"),clear:o(async()=>{await n("readwrite",a=>A(a.clear()))},"clear"),load:o(async()=>n("readonly",a=>A(a.getAll())),"load"),remove:o(async a=>{await n("readwrite",async c=>{let u=await A(c.index(St).getKey(a));u!==void 0&&await A(c.delete(u))})},"remove"),replace:o(async a=>{await n("readwrite",async c=>{let u=await A(c.index(St).getKey(a.id));u!==void 0&&await A(c.put(a,u))})},"replace")}},"w"),Ns=o((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return ni()}},"b");var wt=o((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let a=Math.min(r,s*2**n);if(n+=1,!i)return a;let c=a/2;return Math.floor(c+e()*(a-c))},reset(){n=0}}},"s");var qs=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),js=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED","UNAUTHORIZED"]),Ks=o(t=>js.has(t?.code??""),"y"),Bs=o(t=>{if(t instanceof B)return!0;let e=t?.code;return e===void 0||qs.has(e)||js.has(e)},"O"),$s=6e4,ai=1e3,Ws=o(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},"A"),oi={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},de=o((t,e,s)=>{let r=Ws(s),i=r===void 0?void 0:{retryAfterMs:r},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new B(n,i):new y(oi[t]??"BAD_REQUEST",n,{data:i})},"M"),le=o(t=>{let e=t?.error;return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0},"h"),Hs=o(()=>new B("LunoraClient: batch slot carried no error envelope"),"p"),zs=o((t,e)=>{let s=Ws(e);if(!(s===void 0||mt(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},"N"),Ct=o((t,e=Math.random)=>{let s=Math.min(ai*2**Math.max(t-1,0),$s);return Math.round(s*(.5+e()*.5))},"f"),ci=o(t=>t instanceof B||qs.has(t?.code??""),"T"),Vs=o((t,e,s)=>{let r=mt(t);return r!==void 0&&r>0?Math.min(r,$s):ci(t)?Ct(e,s):void 0},"v"),Gs=983040,Js=o(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"m"),Ys=new WeakSet,kt=o(t=>{let e=new y("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 Ys.add(e),e},"U"),we=o(t=>t instanceof Error&&Ys.has(t),"b");var Xs=o((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present?Y(i.value):void 0;return()=>{let a=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!a.present?!0:Y(a.value)===n}},"c");var Tt=500,ui=o(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}},"We"),Zs=o((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"te");new TextDecoder;var hi=new TextEncoder,di=o(t=>ks(hi.encode(JSON.stringify(t))),"je"),li="x-lunora-expect-subject",fi=o(t=>di({subject:t}),"ze"),er=Symbol.for("lunora:session-change"),pi="lunora:session-change",mi="better-auth.message",yi="signout",cr=o(()=>{let t=globalThis,e=t[er];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[er]=e),e},"de"),bi=o(()=>"document"in globalThis,"Xe"),gi=o(async()=>{let t=[];for(let e of cr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"Ze"),vi=o((t,e)=>{if(t!==mi||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===yi}catch{return!1}},"et"),Si=o(t=>{let e=[],s=o(()=>{gi().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(pi):void 0}catch{r=void 0}if(r!==void 0){let n=r;n.addEventListener("message",a=>{a.data?.type==="lunora:session-change"&&a.data.tab!==t&&s()}),e.push(()=>{n.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let n=o(a=>{vi(a.key,a.newValue)&&s()},"i");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"tt"),wi=o(t=>{let e=cr();return e.listeners.add(t),e.detach===void 0&&bi()&&(e.detach=Si(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"st"),re=class{static{o(this,"O")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[s]=e;for(let r of this.listeners)try{r(s)}catch{}}clear(){this.listeners.clear()}},Ci=o(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:n}=t,a=s>0&&e>0,c=0,u,h=!1,d=!1,l=o(()=>{u!==void 0&&(clearInterval(u),u=void 0,h=!1,i())},"u"),f=o(m=>{if(u!==void 0){if(!m){l();return}h||(h=!0,i()),r()}},"f"),p=o(()=>{d||(d=!0,n().then(f).finally(()=>{d=!1}).catch(()=>{}))},"p");return{isPolling:o(()=>u!==void 0&&h,"isPolling"),noteFailedOpen:o(()=>{c+=1,!(!a||u!==void 0||c<e)&&(u=setInterval(p,s),i(),p())},"noteFailedOpen"),noteOpen:o(()=>{c=0,l()},"noteOpen"),stop:l}},"rt"),ki="/_lunora/rpc",Et="/_lunora/rpc-batch",Ti="/_lunora/ws",It=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"D"),Ce=o(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"F"),tr=Symbol("lunora.unmergeableDelta"),Ei=o((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"at"),Ii="lunora-ping",Oi=3e4,Ri=1e4,Ai=5e3,Pi=3,Fi=250,Mi=5e3,xi=64,Li=3,Qi=1e4,_i=8,Di="/_lunora/admin/shard-traffic",Ui="/_lunora/admin/scheduled",Ni="/_lunora/admin/scheduled/status",qi="/_lunora/admin/scheduled/ws",ji="/_lunora/admin/scheduled/cancel",sr="/_lunora/admin/scheduled/dead",Ki="/_lunora/admin/scheduled/dead/retry",Bi="/_lunora/admin/scheduled/dead/cancel",$i="/_lunora/admin/workflows/instances",Wi="/_lunora/admin/workflows/instance",Hi="/_lunora/admin/workflows/status",Ot="/_lunora/admin/storage",zi="/_lunora/admin/storage/url",Vi="/_lunora/admin/storage/buckets",Gi="/_lunora/admin/functions",Ji="/_lunora/admin/cron-jobs",Yi="/_lunora/admin/cron-jobs/run",Xi="/_lunora/admin/openapi",Zi="/_lunora/admin/openrpc",en="/_lunora/admin/global/tables",tn="/_lunora/admin/global/table",sn="/_lunora/admin/global/facet",rn="/_lunora/admin/vector/indexes",nn="/_lunora/admin/vector/query",an="/_lunora/admin/logs/archive",on="/_lunora/admin/kv/namespaces",cn="/_lunora/admin/kv/keys",Rt="/_lunora/admin/kv/value",un="/_lunora/admin/auth/users",hn="/_lunora/admin/auth/sessions",dn="/_lunora/admin/auth/users/create",ln="/_lunora/admin/auth/users/role",fn="/_lunora/admin/auth/users/ban",pn="/_lunora/admin/auth/users/unban",mn="/_lunora/admin/auth/users/password",yn="/_lunora/admin/auth/users/remove",bn="/_lunora/admin/auth/users/impersonate",gn="/_lunora/admin/auth/sessions/revoke",vn="/_lunora/admin/auth/sessions/revoke-all",Sn="/_lunora/admin/auth/capabilities",wn="/_lunora/admin/auth/users/update",Cn="/_lunora/admin/auth/accounts",kn="/_lunora/admin/auth/accounts/unlink",Tn="/_lunora/admin/auth/passkeys",En="/_lunora/admin/auth/passkeys/delete",In="/_lunora/admin/auth/two-factor/disable",On="/_lunora/admin/auth/organizations",Rn="/_lunora/admin/auth/organizations/members",An="/_lunora/admin/auth/organizations/invitations",Pn="/_lunora/admin/auth/organizations/members/remove",Fn="/_lunora/admin/auth/organizations/invitations/cancel",Mn="/_lunora/admin/auth/config",xn="/_lunora/admin/auth/sign-up-invitations",Ln="/_lunora/admin/auth/sign-up-invitations/create",Qn="/_lunora/admin/auth/sign-up-invitations/revoke",_n="/_lunora/admin/auth/organizations/create",Dn="/_lunora/admin/auth/organizations/update",Un="/_lunora/admin/auth/organizations/remove",Nn="/_lunora/admin/auth/organizations/members/add",qn="/_lunora/admin/auth/organizations/members/invite",jn="/_lunora/admin/auth/organizations/members/role",Kn="/_lunora/admin/auth/organizations/teams",Bn="/_lunora/admin/auth/organizations/teams/create",$n="/_lunora/admin/auth/organizations/teams/update",Wn="/_lunora/admin/auth/organizations/teams/remove",Hn="/_lunora/admin/auth/organizations/teams/members",zn="/_lunora/admin/auth/organizations/teams/members/add",Vn="/_lunora/admin/auth/organizations/teams/members/remove",Gn="/_lunora/admin/auth/organizations/roles",Jn="/_lunora/admin/auth/organizations/roles/create",Yn="/_lunora/admin/auth/organizations/roles/update",Xn="/_lunora/admin/auth/organizations/roles/remove",Zn="/api/auth",ea="/get-session",At=o(t=>t==="connected"||t==="polling","W"),ta=o((t,e,s)=>t!==null||e&&s===null,"Hs"),rr=o(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"ne"),ee=o((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"C"),R=o((t,e)=>{let s=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&s.set(i,String(n));let r=s.toString();return r===""?t:`${t}?${r}`},"S"),sa=[Rs],g=o(t=>t??"","l"),ur=o((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}},"ue"),ra=o(t=>{let{code:e,messageText:s}=ur(t,"stream error");return e===void 0?new Error(s):new y(e,s)},"xs"),ir=o(t=>{let{code:e,messageText:s}=ur(t,"subscription error");return{message:s,...e===void 0?{}:{code:e}}},"ae");function Pt(t){if(t!==void 0)return e=>{t(e)}}o(Pt,"$");var te=o((t,e)=>{for(let s of t)try{s(e)}catch{}},"k"),ia=new TextDecoder,na=o(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return ia.decode(t)},"Bs"),Q=o((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"g"),Lt=o(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,t.data!==void 0)try{e.data=S(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"z"),nr=o((t,e)=>{let s=Lt(t),r=zs(s,e);return r!==void 0&&(s.data=r),s},"oe"),se=o((t,e)=>{try{return E(t)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${r}`,s instanceof Error?{cause:s}:void 0)}},"w"),aa=1e4,ar=o(async t=>{let e=new AbortController,s,r=new Promise((i,n)=>{s=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},aa)});try{return await Promise.race([t(e.signal),r])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(s)}},"ce"),or=o(t=>{try{return E(t),!0}catch{return!1}},"he"),Ft=o(t=>"args"in t?{...t,args:S(t.args)}:t,"j"),hr=o(t=>{let e=le(t);return e===void 0?Hs():Lt(e)},"le"),oa=o((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;let i=r.body;s[r.id]=i!==void 0&&"error"in i?{error:hr(i),ok:!1}:{ok:!0,value:S(i?.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"Ds"),Mt=o((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"G"),ca=Promise.resolve(),xt=class t{static{o(this,"fe")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new P;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;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 re;statusListeners=new re;tokenExpiredListeners=new re;identityChangeListeners=new re;retiredIdentities=0;authRefusalNotifiedFor;mutationSettledListeners=new re;pendingChangeListeners=new re;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??ee(rr(e.url),Ti),this.wsToken=e.wsToken;let s=e.authBasePath??Zn;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??Is(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Oi,this.connectTimeoutMs=e.connectTimeoutMs??Ri,this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??Ai,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Pi,this.defaultConnectionContext=e.connectionContext,this.persistence=Ns(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Es(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new je,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=ca),this.offlineQueue=new We(e.offlineQueue,{onEvict:o((r,i)=>{this.emitItemSettled(r,"rejected",i)},"onEvict"),onSizeChange:o(r=>{this.pendingChangeListeners.emit(r)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${He()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=wi(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),c=this.isKnownNobody();this.authToken=e,this.applySubject(e,s);let u=this.identityFingerprint();u!==i&&(!r&&e!==null&&n?(this.restampQueuedIdentity(i,u),this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&n&&!c?(this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),ta(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(a),r&&this.authTokenListeners.emit(e),(u!==i||r||a)&&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){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"}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 y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=r?.shardKey??"",a=this.identityFingerprint(),c,u,h;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o(d=>{c=d},"onMutationAck")})}catch(d){if(!we(d))throw d;h=d}if(c!==void 0&&c>(this.clientWatermarks.get(a??"")?.get(n)??0)){let d=this.clientWatermarks.get(a??"");d===void 0&&(Zs(this.clientWatermarks,_i),d=new Map,this.clientWatermarks.set(a??"",d)),d.set(n,c)}if(h!==void 0)throw h;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(ee(this.url,`${this.authBasePath}${ea}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let n=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,n,r),n}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.bounceShardSockets())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=g(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=g(s.shardKey),i={context:e},n=this.connectionContextHolders.get(r);n?n.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let a=!1;return()=>{if(a)return;a=!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)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=g(r.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let a=n.get(e),c=a===void 0;if(a||(a=new Set,n.set(e,a)),a.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&Q(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(s)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(r.shardKey);d&&Q(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,s,r={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey);i&&Q(i,{data:se(s??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let n of r){let a=this.connections.get(n);e.push({confirmedMutationWatermark:s?.get(n)??0,hasSocket:a?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,a)=>(n.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((n,a)=>n.functionPath.localeCompare(a.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 Xs(this,e,s,r)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){if(!this.readyResolved)return;let i=Y(s),n=ae(e,i,r),a=this.hydratedQueryCache.get(n);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=P.key(e,s,r),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,s,r={}){let{value:i}=await this.runMutation(e,s,r);return i}canQueueOffline(e){let{wasEverConnected:s}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(s||this.offlineQueue.queueBeforeFirstConnect)}async action(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),n=r.toArgs??(d=>({rows:d})),a=s.length,c=0,u=0,h=0;for(let d=0;d<a;d+=i){let l=s.slice(d,d+i),f=h,{committed:p}=await this.runMutation(e,n(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(f)}`},shardKey:r.shardKey});h+=1,c+=l.length,p&&(u+=l.length),r.onProgress?.({done:c,total:a})}return{chunks:h,imported:u,queued:c-u}}async shardTraffic(e){this.assertOpen();let s=await this.adminFetch(Di,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch(Ui,"GET")).records??[]).map(e=>Ft(e))}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(Ni,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(ji,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await ui(async e=>await this.adminFetch(e===void 0?sr:`${sr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>Ft(e))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Ki,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Bi,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.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 this.adminFetch(`${$i}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}}async getWorkflowInstance(e){this.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await this.adminFetch(`${Wi}?${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??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Hi,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=ee(rr(this.url),qi),r=wt(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,a=!1,c=o(()=>{a||this.closed||(n=setTimeout(d,r.next()))},"a"),u=o(f=>{if(a||this.WebSocketImpl===void 0)return;let p=f===void 0?s:`${s}?token=${encodeURIComponent(f)}`;this.openManagedSocket(i,p,this.connectTimeoutMs,{onClose:o(()=>{c()},"onClose"),onMessage:o(m=>{let b;try{b=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(r.reset(),e(b.records.map(w=>Ft(w))))},"onMessage")})},"o"),h=o(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"h"),d=o(()=>{if(a||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}u(f)},"d");d();let l=o(()=>{a=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close(),i.socket=void 0},"u");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Gi,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Ji,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let s=await this.adminFetch(Yi,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Xi,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Zi,"GET")}async listStorageObjects(e={}){this.assertOpen();let s=R(Ot,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await this.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}}async deleteStorageObject(e,s){this.assertOpen();let r=`${Ot}?key=${encodeURIComponent(e)}${It(s?.bucket)}`,i=await this.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Vi,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let s=`${Ot}?key=${encodeURIComponent(e.key)}${It(e.bucket)}`,r=await this.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}}async signedStorageUrl(e,s){this.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${zi}?key=${encodeURIComponent(e)}${i}${It(s?.bucket)}`,a=await this.adminFetch(n,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(en,"GET")}async readGlobalTablePage(e){this.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(E(e.filters))),S(await this.adminFetch(`${tn}?${s.toString()}`,"GET"))}async facetGlobalColumn(e){this.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(E(e.filters))),S(await this.adminFetch(`${sn}?${s.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(rn,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(nn,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let s=await this.adminFetch(an,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(on,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let s=R(cn,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(s,"GET")}async getKvValue(e){this.assertOpen();let s=R(Rt,{key:e.key,namespace:e.namespace});return await this.adminFetch(s,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(Rt,"PUT",e)}async deleteKvKey(e){this.assertOpen();let s=R(Rt,{key:e.key,namespace:e.namespace});await this.adminFetch(s,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let s=R(un,{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 await this.adminFetch(dn,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(ln,"POST",e)}async banAuthUser(e){return await this.adminFetch(fn,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(pn,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(mn,"POST",e)}async removeAuthUser(e){await this.adminFetch(yn,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(bn,"POST",e)}async revokeAuthSession(e){await this.adminFetch(gn,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(vn,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(Sn,"GET")}async updateAuthUser(e){return await this.adminFetch(wn,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(R(Cn,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(kn,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(R(Tn,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(En,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(In,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(R(On,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let s=R(Rn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){let s=R(An,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){let s=R(xn,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(Ln,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(Qn,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(Pn,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(Fn,"POST",e)}async getAuthConfig(){return await this.adminFetch(Mn,"GET")}async createAuthOrganization(e){return await this.adminFetch(_n,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(Dn,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(Un,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(Nn,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(qn,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(jn,"POST",e)}async listAuthOrgTeams(e){let s=R(Kn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(Bn,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch($n,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Wn,"POST",e)}async listAuthOrgTeamMembers(e){let s=R(Hn,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(zn,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Vn,"POST",e)}async listAuthOrgRoles(e){let s=R(Gn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Jn,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Yn,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Xn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=R(hn,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){this.assertOpen();let n=s??{},a=P.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(a),u=Pt(r),h=Pt(i.onError),d=Pt(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=Y(n),m=this.takeHydratedCache(e.__lunoraRef,p,i.shardKey);c={acked:!1,args:n,argsKey:p,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,wireArgs:se(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(a,m)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(P.keyOf(l)),this.subscriptions.remove(l))}}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:a}=r;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:se(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new y("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=r,a=s??{},{handle:c,iterable:u}=Be({maxBuffer:r.maxBuffer,onCancel:o(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:se(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n,started:!1};this.streams.set(i,l);let f=h?.wsState==="open"&&Q(h,d);if(l.started=f,!f&&h===void 0)return this.streams.delete(i),c.fail(new y("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=xi;){let p=h.pendingStreams.shift()?.id,m=p?this.streams.get(p):void 0;m&&(m.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(p))}h.pendingStreams.push(d)}return u}httpStream(e,s,r={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return xs(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new y("INTERNAL","LunoraClient is closed")}followsAnotherTab(){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 y("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}teardownConnection(e){e.polling.stop();let s=g(e.shardKey);for(let[r,i]of this.streams)g(i.shardKey)===s&&(i.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(r));if(e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new Ke({channelName:e,onBecomeLeader:o(()=>{for(let s of this.subscriptions.all())this.ensureSocket(s.shardKey),this.queueResubscribe(s);for(let s of this.queuedOfflineShardKeys)this.ensureSocket(s);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:o(()=>{for(let[s,r]of this.connections)this.teardownConnection(r),this.connections.delete(s);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:o((s,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;let i=s==="connected"&&this.leaderStatus!=="connected"||s==="polling"&&this.leaderStatus!=="connected"&&this.leaderStatus!=="polling";this.leaderStatus=s,s==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},"onConnectionStatus"),onSubscriptionData:o((s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;let c=this.subscriptions.get(s);c&&(c.serverBase=r,this.dropCacheSeed(s),i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),$e(c,i)),V(c,X(r,c.optimisticLayers)))},"onSubscriptionData"),onLeaderClaimAnswered:o(()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onLeaderClaimAnswered"),onSubscriptionError:o((s,r,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;let n=this.subscriptions.get(s);n&&te(n.errorCallbacks,r)},"onSubscriptionError"),onSubscriptionSettled:o((s,r,i,n,a,c)=>{if(c!==void 0&&c!==this.identityFingerprint())return;let u=this.subscriptions.get(s);if(u){this.ackAndAdvanceCursor(u,r,i),n!==void 0&&a===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let h of u.checkpointCallbacks)h({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(ee(this.url,Et),{body:JSON.stringify({calls:e.map((c,u)=>({args:se(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let n;try{n=await r.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let a=le(n);if(!r.ok||a!==void 0&&!n.results)throw a!==void 0?Lt(a):new y("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let c of n.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return oa(n.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=s,n=r.mutationId??He(),a=r.replayBaseline===void 0?this.baselineCursorFor(r.shardKey):r.replayBaseline??void 0,{confirms:c,rollbacks:u}=this.applyOptimisticUpdates(e.__lunoraRef,i,r.shardKey,r.optimistic);r.optimisticUpdate&&this.applyOptimisticUpdate(r.optimisticUpdate,s,r.shardKey,u,c);let h=this.offlineFlushes.get(g(r.shardKey));h!==void 0&&await h;let{hasSocket:d,polling:l,wasEverConnected:f,wsState:p}=this.connectionGateState(r.shardKey),{queueBeforeFirstConnect:m}=this.offlineQueue,b=f||m,w=this.WebSocketImpl!==void 0&&b,k=p==="connecting"&&b&&!l,F=p!=="open"&&!d&&w&&!l,_=w&&r.replayBaseline===void 0&&this.hasPendingWriteAhead(r.shardKey),N=o(async()=>this.enqueueOfflineMutation(e,i,r.shardKey,a,n,u,c,r.precondition,r.mutationId),"V");if(F||k||_)return N();let D;try{let $=await this.rpc(e.__lunoraRef,i,r.shardKey,{baselineSeq:a,captureBookmark:!0,...Mt(r.replayIdentity,this.authToken),mutationId:n,onCommitCursor:o(M=>{D=M},"onCommitCursor")});for(let M of c)M(D);return{committed:!0,value:$}}catch($){if(l&&w&&$ instanceof TypeError&&or(i))return N();throw this.settleFailedDirectWrite($,D,c,u),$}}settleFailedDirectWrite(e,s,r,i){if(this.noteIdentityMismatch(e),we(e)){for(let n of r)n(s);return}Ce(i)}async enqueueOfflineMutation(e,s,r,i,n,a,c,u,h){let d=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let l=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:h??`${this.clientId}:${String(l)}`,identity:d,mutationId:l,...a.length>0&&{onRejected:o(()=>{Ce(a)},"onRejected")},shardKey:r})}catch(f){throw Ce(a),f instanceof Error?f:new Error(String(f))}for(let f of c)f(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((l,f)=>{let p={args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,clientId:this.clientId,identity:d,precondition:u,onCommit:o(m=>{for(let b of c)b(m)},"onCommit"),reject:o(m=>{this.queuedIdentities.delete(n),we(m)||Ce(a),f(m instanceof Error?m:new Error(String(m)))},"reject"),resolve:l,shardKey:r};this.offlineQueue.enqueue(p),this.queuedOfflineShardKeys.add(r),p.id!==void 0&&this.queuedIdentities.set(p.id,d)})}}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=o(()=>{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(ae(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(vt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let n=s.get(r);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(ae(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),V(e,X(s.value,e.optimisticLayers)))}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,V(r,X(void 0,r.optimisticLayers))),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=ae(e,s,r),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=ae(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=ae(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:s,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},Fi))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"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&&(or(c.args)?r.push(c):te(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=Qs(),n=this.identityFingerprint(),a;try{a=await ar(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(let[c,u]of r.entries()){let h=a[c];if(h!==void 0){if(!h.ok){te(u.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:E(h.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await ar(async s=>e(ee(this.url,Et),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let n=[],a=[];if(!i)return{confirms:n,rollbacks:a};let c=P.key(e,s,r),u=this.subscriptions.get(c);if(u){let h=gt(u,i);h&&(n.push(h.confirm),a.push(h.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,s,r,i,n){let{confirms:a,rollbacks:c,store:u}=Ds(this.subscriptions,r);try{e(u,s)}catch{Ce(c);return}i.push(...c),n.push(...a)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!Q(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let r="idle";return this.leaderStatus==="connected"?r="open":this.leaderStatus==="connecting"&&(r="connecting"),{hasSocket:!1,polling:this.leaderStatus==="polling",wasEverConnected:this.leaderWasEverConnected,wsState:r}}let s=this.getConnection(e);return{hasSocket:s?.socket!==void 0,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??!1,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:Ci({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:o(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:o(()=>{this.emitConnectionStatus()},"onStateChange"),poll:o(async()=>this.pollSubscriptions(e),"poll")}),reconnect:wt(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(s,r)),r}wsUrlFor(e,s){let r=[];if(e!==void 0&&r.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&r.push(`token=${encodeURIComponent(s)}`),r.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${r.join("&")}`}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[li]=fi(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(r.authorization=`Bearer ${n}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(r["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(r["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let a=this.bookmark.get();a&&(r["x-d1-bookmark"]=a)}return r}async rpc(e,s,r,i={}){if(!this.fetchImpl)throw new B("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,r),a=await this.fetchImpl(ee(this.url,ki),{body:JSON.stringify({args:se(s,`args for '${e}'`),functionPath:e,shardKey:r}),headers:n,method:"POST"});if(i.captureBookmark){let d=a.headers.get("x-d1-bookmark");d&&this.bookmark.set(d)}let c;try{c=await a.json()}catch{throw de(a.status,a.statusText,a.headers.get("retry-after"))}let u=c;if(typeof u!="object"||u===null||Array.isArray(u))throw de(a.status,a.statusText,a.headers.get("retry-after"));let h=le(c);if(h!==void 0)throw nr(h,a.headers.get("retry-after"));if(!a.ok)throw de(a.status,a.statusText,a.headers.get("retry-after"));i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.learnDefaultShardKey(a,r),this.recordShardCursor(r,c.commitCursor);try{return S(c.result)}catch(d){throw kt(d)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let a=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:a?(c=r,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(r),n["content-type"]="application/json");let u=await this.fetchImpl(ee(this.url,e),{body:c,headers:n,method:s}),h;try{h=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let d=le(h);if(d!==void 0){let l=new Error(d.message??"admin request failed");throw l.code=d.code,l}if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return h}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));Q(e,{caps:sa,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())g(s.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);if(!(s.wsState==="open"||s.wsState==="connecting")){if(s.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(s,e,this.wsToken).catch(()=>{});return}this.openSocket(s,e,this.wsToken)}}async openSocketWithProvidedToken(e,s,r){let i;try{i=await r()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,s,i)}openManagedSocket(e,s,r,i){let{WebSocketImpl:n}=this;if(n===void 0)throw new y("INTERNAL","no WebSocket implementation available");let a=new n(s);e.socket=a;let c=o(()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===a&&(e.socket=void 0)},"a"),u=o(h=>{c(),i.onClose(h)},"o");r>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===a){try{a.close()}catch{}u()}},r)),a.addEventListener("open",()=>{if(e.socket===a){e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now();try{i.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}this.startHeartbeat(e,u)}}),a.addEventListener("message",h=>{if(e.socket===a){e.lastFrameAt=Date.now();try{i.onMessage(h)}catch(d){console.error("[lunora] server frame handler threw",d)}}}),a.addEventListener("close",h=>{e.socket===a&&u(h)}),a.addEventListener("error",()=>{e.socket===a&&u()})}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,this.openManagedSocket(e,this.wsUrlFor(s,r),this.connectTimeoutMs,{onClose:o(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:o(i=>{e.retired!==!0&&this.handleServerMessage(i.data,s)},"onMessage"),onOpen:o(()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Mi),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(s),this.clearResubscribeQueue(e);for(let n of this.subscriptions.all())g(n.shardKey)===g(s)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:a,type:c}of n)Q(e,{id:a,type:c})}this.flushPendingStreams(e);let i=this.whisperHandlers.get(g(s));if(i)for(let n of i.keys())Q(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(s).catch(()=>{})},"onOpen")}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;let s=e.pendingStreams;e.pendingStreams=[];for(let r of s){let i=Q(e,r)?this.streams.get(String(r.id)):void 0;i&&(i.started=!0)}}cancelStream(e,s){let r=this.getConnection(s),i=this.streams.get(e);r&&(r.pendingStreams=r.pendingStreams?.filter(n=>n.id!==e),!Q(r,{id:e,type:"unsubscribe"})&&i?.durable===!0&&i.started&&r.pendingUnsubscribes.push({id:e,type:"unsubscribe"})),this.streams.delete(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),this.stopHeartbeat(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(g(n.shardKey)!==g(e.shardKey)||s.has(i))){if(n.durable){let a={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),a];continue}n.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}startHeartbeat(e,s){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;let{socket:r}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{r.close()}catch{}s();return}try{r.send(Ii)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){let s=g(e);for(let r of this.subscriptions.all())g(r.shardKey)===s&&(r.acked=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribePending.size<Li;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribePending.set(s.id,setTimeout(()=>{this.releaseResubscribeSlot(e,s.id)},Qi))}}releaseResubscribeSlot(e,s){let r=e.resubscribePending.get(s);r!==void 0&&(clearTimeout(r),e.resubscribePending.delete(s),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(let s of e.resubscribePending.values())clearTimeout(s);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.acked)return!1;let r=e.serverCursor!==void 0&&e.serverBase!==void 0;return Q(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...r?{sinceSeq:e.serverCursor}:{},...r&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&Q(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=na(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}if(i.type!=="error"&&this.getConnection(s)?.reconnect.reset(),typeof i.id=="string"){let n=this.getConnection(s);n&&this.releaseResubscribeSlot(n,i.id)}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:a,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof a=="number"&&(h.generation=a),h.durable=!0),h?.handle.push(S(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.handlePokePart(i,s);break}case"pokeStart":{this.handlePokeStart(i,s);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(ra(e)),this.streams.delete(s);return}let i=s===void 0?void 0:this.subscriptions.getById(s);if(i){let a=ir(e),c=this.identityFingerprint(),u=P.keyOf(i);te(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,a,c);return}let n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&te(n.errorCallbacks,ir(e))}pokeBufferKey(e,s){return`${g(e)}\0${s}`}handlePokeStart(e,s){Zs(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(s,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}handlePokePart(e,s){let r=this.pokeBuffers.get(this.pokeBufferKey(s,e.pokeId));if(!r)return;let i=[];try{for(let c of e.rowsPatch)i.push(c.value===void 0?c:{...c,value:S(c.value)})}catch(c){r.undecodable.set(e.shapeId,c);return}let n=r.parts.get(e.shapeId)??[];for(let c of i)n.push(c);r.parts.set(e.shapeId,n),e.lastMutationId!==void 0&&r.lastMutationId.set(e.shapeId,e.lastMutationId);let a=e.baseCheckpoint??r.baseCheckpoint;a!==void 0&&r.bases.set(e.shapeId,a),e.reset===!0&&r.resets.add(e.shapeId)}handlePokeEnd(e,s){let r=this.pokeBufferKey(s,e.pokeId),i=this.pokeBuffers.get(r);if(i){this.pokeBuffers.delete(r);for(let[n,a]of i.undecodable){let c=this.shapeSubscriptions.get(n);c&&te(c.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${a instanceof Error?a.message:String(a)}`})}for(let n of i.parts.keys()){let a=this.shapeSubscriptions.get(n);a&&!i.undecodable.has(n)&&this.applyPokePart(a,i,e)}}}applyPokePart(e,s,r){let i=s.parts.get(e.id)??[],n=s.resets.has(e.id),a=s.bases.get(e.id),c=s.epoch!==void 0&&e.serverEpoch!==void 0&&s.epoch!==e.serverEpoch,u=a!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==a;if(!n&&(c||u)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}n&&e.rows.clear(),Ei(e.rows,i),r.checkpoint!==void 0&&(e.serverCursor=r.checkpoint),r.epoch!==void 0&&(e.serverEpoch=r.epoch);let h=s.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){let s=[...e.rows.values()];for(let r of e.callbacks)try{r(s)}catch{}}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i)return;let n;try{n=this.resolveDataPayload(e,i)}catch(a){te(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${a instanceof Error?a.message:String(a)}`});return}if(n===tr){this.resnapshotSubscription(i);return}if(i.serverBase=n,this.dropCacheSeed(P.keyOf(i)),e.cursor!==void 0&&(i.serverCursor=e.cursor),e.epoch!==void 0&&(i.serverEpoch=e.epoch),e.lastMutationId!==void 0){i.lastMutationId=Math.max(i.lastMutationId??0,e.lastMutationId);for(let a of i.checkpointCallbacks)a({checkpoint:i.serverCursor,mutationId:i.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(i),$e(i,i.serverCursor),s!==void 0&&_s(i,s),V(i,X(n,i.optimisticLayers)),this.tabCoordinator?.isLeader()){let a=P.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(a,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,e.cursor,e.epoch)}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s){this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&(s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId));for(let r of s.checkpointCallbacks)r({checkpoint:s.serverCursor,mutationId:s.lastMutationId});if(this.tabCoordinator?.isLeader()){let r=P.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,s,r){e.acked=!0,(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),$e(e,e.serverCursor)&&V(e,X(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,s){if("data"in e&&e.data!==void 0)return S(e.data);let r=S(e.delta);return As(r)?s.serverBase===void 0?r:Ps(s.serverBase,r)??tr:r}dispatchWhisper(e,s){let r=this.whisperHandlers.get(g(s))?.get(e.topic);if(!r)return;let i=S(e.data);for(let n of r)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.streams.delete(e);return}let r=this.subscriptions.getById(e);r&&(r.acked=!1,te(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(s=>{Z(this.onPersistenceError,"remove",s,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);s^=n,s=Math.imul(s,16777619),r=Math.imul(r,33)+n}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&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)}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}rejectQueuedForIdentityChange(e){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.replayIdentityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let n=s??"",a=this.clientWatermarks.get(n);if(a===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)a.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.revokeCacheSeededValues();for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,V(e,X(void 0,e.optimisticLayers));for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e);this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=g(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&At(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&this.offlineFlushes.delete(s)}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let d of r){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",l)}let i=g(e),n=this.offlineQueue.drain(d=>g(d.shardKey)===i);if(n.length===0)return;let a=[],c=[];for(let d of n){let l=this.replayGateVerdict(d);l==="send"?a.push(d):l==="hold"&&c.push(d)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),a.length===0){this.scheduleRateLimitedRetry(e);return}let u=this.encodableOrSettleTerminal(a);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let h=[];for(let d=0;d<u.length;d+=Tt){let l=u.slice(d,d+Tt),f=await this.replayBatched(l,e,s);if(h.push(...f.requeue),f.stop){h.push(...u.slice(d+Tt));break}}h.length>0&&this.offlineQueue.requeue(h),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,Ct(i))})}noteReplayRetryDelay(e,s){let r=g(e),i=this.replayRetryState.get(r),n=(i?.attempts??0)+1,a=Vs(s,n);this.replayRetryState.set(r,{attempts:n,delayMs:a===void 0?i?.delayMs:Math.max(i?.delayMs??0,a)})}scheduleRateLimitedRetry(e){let s=g(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let n=this.replayRetryTimers.get(s);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{se(r.args,`args for '${r.functionPath}'`),s.push(r)}catch(i){this.settleReplayTerminal(r,i instanceof Error?i:new Error(String(i)))}return s}replayGateVerdict(e){let s=this.stampOf(e);if(s===void 0)return this.queuedIdentities.delete(e.id??""),"send";let r=this.replayIdentityVerdict(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){if(this.noteIdentityMismatch(e))return!0;if(Ks(e)){let r=this.hashToken(s??"");return s===this.authToken&&this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}return Bs(e)}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let n=e[i];if(!n)continue;let a;try{let c=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:r,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...Mt(n.identity,r),mutationId:n.id,onCommitCursor:o(u=>{a=u},"onCommitCursor")});this.settleReplaySuccess(n,c,a)}catch(c){if(we(c)){this.settleReplayUndecodable(n,c,a);continue}if(!this.shouldRequeueReplayFailure(c,r)){this.settleReplayTerminal(n,c);continue}this.noteReplayRetryDelay(s,c),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,d)=>({args:se(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:d,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&Js(i)>Gs)return await this.replayBatchedHalves(e,s,r);let n;try{n=await this.fetchImpl(ee(this.url,Et),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...Mt(e.find(h=>h.identity!==void 0)?.identity,r)}),method:"POST"})}catch{return{requeue:e,stop:!0}}let a=n.headers.get("x-d1-bookmark");if(a&&this.bookmark.set(a),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let c,u=n.headers.get("retry-after");try{c=await n.json()}catch{return this.settleWholeBatchError(e,de(n.status,n.statusText,u),s,r)}if(!c.results){let h=le(c),d=h===void 0?de(n.status,n.statusText,u):nr(h,u);return this.settleWholeBatchError(e,d,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof B||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s),{requeue:e,stop:!0};for(let n of e)this.settleReplayTerminal(n,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),s,r);if(n.stop)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};let a=await this.replayBatched(e.slice(i),s,r);return{requeue:[...n.requeue,...a.requeue],stop:a.stop}}settleReplayBatchSlots(e,s,r,i){let n=new Map;for(let c of s)typeof c.id=="number"&&c.body!==void 0&&n.set(c.id,c.body);let a=[];for(let[c,u]of e.entries()){let h=n.get(c);if(h===void 0)a.push(u);else if("error"in h){let d=hr(h);this.shouldRequeueReplayFailure(d,i)?(this.noteReplayRetryDelay(r,d),a.push(u)):this.settleReplayTerminal(u,d)}else this.settleReplayBatchResult(u,h)}return a}settleReplayBatchResult(e,s){let r;try{r=S(s.result)}catch(i){this.settleReplayUndecodable(e,kt(i),s.commitCursor);return}this.settleReplaySuccess(e,r,s.commitCursor)}};var dr=L(Dt(),1),lr=L(ie(),1);var ua=o(()=>{let t=(0,dr.c)(4),e=ht(),s,r,i;return t[0]!==e?(s=o(n=>e.onConnectionStatus(()=>{n()}),"o"),r=o(()=>e.connectionStatus(),"e"),i=o(()=>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,lr.useSyncExternalStore)(s,r,i)},"S");export{xt as a,br as b,rt as c,Rr as d,Lr as e,ht as f,ua as g};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as je}from"./chunk-EA2JKR5D.js";import{a as he}from"./chunk-IMOHEGMV.js";import{d as Ne,f as ke,g as we,k as oe}from"./chunk-V3VJAA4D.js";import{a as V}from"./chunk-5WJXVZMZ.js";import{a as Pe}from"./chunk-EJSI4PMU.js";import"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import{W as ye}from"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import{a as B}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as ve}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as $e}from"./chunk-4ZEL6BYL.js";import{f as F}from"./chunk-
|
|
1
|
+
import{a as je}from"./chunk-EA2JKR5D.js";import{a as he}from"./chunk-IMOHEGMV.js";import{d as Ne,f as ke,g as we,k as oe}from"./chunk-V3VJAA4D.js";import{a as V}from"./chunk-5WJXVZMZ.js";import{a as Pe}from"./chunk-EJSI4PMU.js";import"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import{W as ye}from"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import{a as B}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as ve}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as $e}from"./chunk-4ZEL6BYL.js";import{f as F}from"./chunk-PG7XHMUR.js";import"./chunk-FSRSK4LY.js";import{d as be}from"./chunk-5ICUJ4IA.js";import{a as U}from"./chunk-FKVZRPV5.js";import{d as M,e as Se,f as se,g as ie,h as le,m as Ie,p as Oe,s as ae}from"./chunk-PTZD7RUZ.js";import{a as u,d as z,e as ue,f as te,g as re,i as fe}from"./chunk-YKXDMIHQ.js";var Ge=z(te(),1),xe=z(ue(),1);var Y=z(te(),1);var X=z(ue(),1);var C=z(re(),1);var Ve=se($e.listTables),Xe=["react","client","cli"],Ye={action:"action",mutation:"mutation",query:"query"},Te=u(t=>{let e=t.indexOf(":");return e===-1?{file:"",fn:t}:{file:t.slice(0,e),fn:t.slice(e+1)}},"Q"),Ze=u(({file:t,fn:e,kind:a})=>`await client.${Ye[a]}(api.${t}.${e}, { /* args */ });`,"ie"),et=u(t=>{let e=`api.${t.file}.${t.fn}`;switch(t.kind){case"action":return`const { call: ${t.fn} } = useAction(${e});`;case"mutation":return`const ${t.fn} = useMutation(${e});`;default:return`const data = useQuery(${e}, { /* args */ });`}},"se"),tt=u(({file:t,fn:e})=>`lunora run ${t}:${e} --args '{ }'`,"oe"),rt=u(t=>["// Read rows",`const rows = await ctx.db.query("${t}").collect();`,"","// Insert a row",`const id = await ctx.db.insert("${t}", { /* fields */ });`,"","// Generated types",`type Row = Doc<"${t}">;`,`type RowId = Id<"${t}">;`].join(`
|
|
2
2
|
`),"ce"),at=u((t,e)=>{switch(t){case"cli":return tt(e);case"client":return Ze(e);default:return et(e)}},"re"),Ce=u(t=>{let e=(0,Y.c)(19),{code:a,label:r,testId:n}=t,s=M(),o;e[0]!==a?(o=u(()=>{ae(a)},"c"),e[0]=a,e[1]=o):o=e[1];let i=o,d;e[2]!==r?(d=(0,C.jsx)("span",{className:"text-xs font-medium text-muted-foreground",children:r}),e[2]=r,e[3]=d):d=e[3];let m=`${n}-copy`,l;e[4]!==s?(l=s("Copy"),e[4]=s,e[5]=l):l=e[5];let c;e[6]!==i||e[7]!==m||e[8]!==l?(c=(0,C.jsx)(B,{"data-testid":m,onClick:i,size:"xs",type:"button",variant:"ghost",children:l}),e[6]=i,e[7]=m,e[8]=l,e[9]=c):c=e[9];let f;e[10]!==d||e[11]!==c?(f=(0,C.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[d,c]}),e[10]=d,e[11]=c,e[12]=f):f=e[12];let h;e[13]!==a||e[14]!==n?(h=(0,C.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs","data-testid":n,children:a}),e[13]=a,e[14]=n,e[15]=h):h=e[15];let g;return e[16]!==f||e[17]!==h?(g=(0,C.jsxs)("div",{className:"flex flex-col gap-1.5",children:[f,h]}),e[16]=f,e[17]=h,e[18]=g):g=e[18],g},"U"),nt=u(t=>{let e=(0,Y.c)(46),{file:a,fn:r,kind:n}=t,s=M(),[o,i]=(0,X.useState)("react"),d,m,l;if(e[0]!==a||e[1]!==r||e[2]!==n||e[3]!==s||e[4]!==o){let w={file:a,fn:r,kind:n},j;e[8]!==s?(j=s("CLI"),e[8]=s,e[9]=j):j=e[9];let O;e[10]!==s?(O=s("Client"),e[10]=s,e[11]=O):O=e[11];let S;e[12]!==s?(S=s("React"),e[12]=s,e[13]=S):S=e[13];let T;e[14]!==j||e[15]!==O||e[16]!==S?(T={cli:j,client:O,react:S},e[14]=j,e[15]=O,e[16]=S,e[17]=T):T=e[17],l=T;let A;e[18]===Symbol.for("react.memo_cache_sentinel")?(A=u(R=>{i(R.currentTarget.dataset.tab)},"B"),e[18]=A):A=e[18],d=A,m=at(o,w),e[0]=a,e[1]=r,e[2]=n,e[3]=s,e[4]=o,e[5]=d,e[6]=m,e[7]=l}else d=e[5],m=e[6],l=e[7];let c=m,f=`api.${a}.${r}`,h;e[19]!==f?(h=(0,C.jsx)("h2",{className:"font-mono text-sm font-semibold text-foreground","data-testid":"api-fn-title",children:f}),e[19]=f,e[20]=h):h=e[20];let g;e[21]!==n||e[22]!==s?(g=s("Call this {kind} from your app.",{kind:n}),e[21]=n,e[22]=s,e[23]=g):g=e[23];let x;e[24]!==g?(x=(0,C.jsx)("p",{className:"text-xs text-muted-foreground",children:g}),e[24]=g,e[25]=x):x=e[25];let y;e[26]!==h||e[27]!==x?(y=(0,C.jsxs)("div",{children:[h,x]}),e[26]=h,e[27]=x,e[28]=y):y=e[28];let N;e[29]!==s?(N=s("Snippet flavour"),e[29]=s,e[30]=N):N=e[30];let v;e[31]!==d||e[32]!==o||e[33]!==l?(v=Xe.map(w=>(0,C.jsx)(B,{"aria-selected":o===w,"data-tab":w,"data-testid":`api-tab-${w}`,onClick:d,role:"tab",size:"xs",type:"button",variant:o===w?"default":"outline",children:l[w]},w)),e[31]=d,e[32]=o,e[33]=l,e[34]=v):v=e[34];let b;e[35]!==N||e[36]!==v?(b=(0,C.jsx)("div",{"aria-label":N,className:"flex gap-1.5","data-testid":"api-tabs",role:"tablist",children:v}),e[35]=N,e[36]=v,e[37]=b):b=e[37];let I=l[o],P=`api-snippet-${o}`,$;e[38]!==c||e[39]!==I||e[40]!==P?($=(0,C.jsx)(Ce,{code:c,label:I,testId:P}),e[38]=c,e[39]=I,e[40]=P,e[41]=$):$=e[41];let k;return e[42]!==$||e[43]!==y||e[44]!==b?(k=(0,C.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"api-fn-doc",children:[y,b,$]}),e[42]=$,e[43]=y,e[44]=b,e[45]=k):k=e[45],k},"de"),ot=u(t=>{let e=(0,Y.c)(19),{name:a}=t,r=M(),n;e[0]!==a?(n=rt(a),e[0]=a,e[1]=n):n=e[1];let s=n,o;e[2]!==a?(o=(0,C.jsx)("h2",{className:"font-mono text-sm font-semibold text-foreground","data-testid":"api-table-title",children:a}),e[2]=a,e[3]=o):o=e[3];let i;e[4]!==r?(i=r("Read and write this table through the typed data model."),e[4]=r,e[5]=i):i=e[5];let d;e[6]!==i?(d=(0,C.jsx)("p",{className:"text-xs text-muted-foreground",children:i}),e[6]=i,e[7]=d):d=e[7];let m;e[8]!==o||e[9]!==d?(m=(0,C.jsxs)("div",{children:[o,d]}),e[8]=o,e[9]=d,e[10]=m):m=e[10];let l;e[11]!==r?(l=r("Data model"),e[11]=r,e[12]=l):l=e[12];let c;e[13]!==s||e[14]!==l?(c=(0,C.jsx)(Ce,{code:s,label:l,testId:"api-snippet-table"}),e[13]=s,e[14]=l,e[15]=c):c=e[15];let f;return e[16]!==m||e[17]!==c?(f=(0,C.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"api-table-doc",children:[m,c]}),e[16]=m,e[17]=c,e[18]=f):f=e[18],f},"fe"),_e=u(t=>{let e=(0,Y.c)(8),{active:a,label:r,onSelect:n,testId:s,value:o}=t,i;e[0]!==n||e[1]!==o?(i=u(()=>{n(o)},"m"),e[0]=n,e[1]=o,e[2]=i):i=e[2];let d=i,m=a?"page":void 0,l;return e[3]!==r||e[4]!==d||e[5]!==m||e[6]!==s?(l=(0,C.jsx)("button",{"aria-current":m,className:"w-full truncate rounded-md px-2 py-1 text-start font-mono text-xs text-muted-foreground outline-none transition-colors hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:bg-sidebar-accent aria-[current=page]:bg-sidebar-accent aria-[current=page]:font-medium aria-[current=page]:text-foreground","data-testid":s,onClick:d,type:"button",children:r}),e[3]=r,e[4]=d,e[5]=m,e[6]=s,e[7]=l):l=e[7],l},"G"),st=u(t=>{let e=new Map;for(let a of t){let{file:r,fn:n}=Te(a.path),s=e.get(r)??[];s.push({fn:n,kind:a.kind,path:a.path}),e.set(r,s)}return[...e.entries()].map(([a,r])=>({file:a,items:r.toSorted((n,s)=>n.fn.localeCompare(s.fn))})).toSorted((a,r)=>a.file.localeCompare(r.file))},"pe"),Ae=u(t=>{let e=(0,Y.c)(58),{functions:a,initialShardKey:r}=t,n=M(),s=F(),[o,i]=(0,X.useState)(null),[d,m]=(0,X.useState)(null),l,c;e[0]!==s||e[1]!==r?(l=u(()=>{let R=!1;return s.query(Ve,{},ie(r??"")).then(_=>(R||i(_),_)).catch(()=>{R||i([])}),()=>{R=!0}},"o"),c=[s,r],e[0]=s,e[1]=r,e[2]=l,e[3]=c):(l=e[2],c=e[3]),(0,X.useEffect)(l,c);let f,h,g,x,y,N,v,b,I,P;if(e[4]!==a||e[5]!==d||e[6]!==n||e[7]!==o){let R=a??[],_=st(R),L=(o??[]).map(it).toSorted(lt),E;e[18]===Symbol.for("react.memo_cache_sentinel")?(E=u(q=>{m({kind:"fn",path:q})},"P"),e[18]=E):E=e[18];let W=E,Q;e[19]===Symbol.for("react.memo_cache_sentinel")?(Q=u(q=>{m({kind:"table",name:q})},"j"),e[19]=Q):Q=e[19];let Qe=Q;h=d?.kind==="fn"?R.find(q=>q.path===d.path):void 0,f=R.length>0||L.length>0,g=h===void 0?void 0:Te(h.path),I="grid min-h-0 gap-6 md:grid-cols-[16rem_minmax(0,1fr)]",P="lunora-api-docs",e[20]!==n?(x=n("API resources"),e[20]=n,e[21]=x):x=e[21],y="flex flex-col gap-4 overflow-y-auto",N="api-rail";let ne;e[22]!==d||e[23]!==n?(ne=u(q=>(0,C.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,C.jsx)("span",{className:"px-2 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:q.file||n("(root)")}),q.items.map(ee=>(0,C.jsx)(_e,{active:d?.kind==="fn"&&d.path===ee.path,label:ee.fn,onSelect:W,testId:`api-rail-fn-${ee.path}`,value:ee.path},ee.path))]},q.file),"q"),e[22]=d,e[23]=n,e[24]=ne):ne=e[24],v=_.map(ne),b=L.length>0&&(0,C.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,C.jsx)("span",{className:"px-2 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:n("Tables")}),L.map(q=>(0,C.jsx)(_e,{active:d?.kind==="table"&&d.name===q,label:q,onSelect:Qe,testId:`api-rail-table-${q}`,value:q},q))]}),e[4]=a,e[5]=d,e[6]=n,e[7]=o,e[8]=f,e[9]=h,e[10]=g,e[11]=x,e[12]=y,e[13]=N,e[14]=v,e[15]=b,e[16]=I,e[17]=P}else f=e[8],h=e[9],g=e[10],x=e[11],y=e[12],N=e[13],v=e[14],b=e[15],I=e[16],P=e[17];let $;e[25]!==f||e[26]!==n?($=!f&&(0,C.jsx)("p",{className:"px-2 text-xs text-muted-foreground","data-testid":"api-rail-empty",children:n("No functions or tables to document yet.")}),e[25]=f,e[26]=n,e[27]=$):$=e[27];let k;e[28]!==$||e[29]!==x||e[30]!==y||e[31]!==N||e[32]!==v||e[33]!==b?(k=(0,C.jsxs)("nav",{"aria-label":x,className:y,"data-testid":N,children:[v,b,$]}),e[28]=$,e[29]=x,e[30]=y,e[31]=N,e[32]=v,e[33]=b,e[34]=k):k=e[34];let w;e[35]!==d||e[36]!==n?(w=d===null&&(0,C.jsx)(U,{description:n("Select a function or table to see how to call it from your app."),testId:"api-empty",title:n("API usage snippets")}),e[35]=d,e[36]=n,e[37]=w):w=e[37];let j;e[38]!==d?.kind||e[39]!==h||e[40]!==g?(j=d?.kind==="fn"&&h!==void 0&&g!==void 0&&(0,C.jsx)(nt,{file:g.file,fn:g.fn,kind:h.kind},h.path),e[38]=d?.kind,e[39]=h,e[40]=g,e[41]=j):j=e[41];let O;e[42]!==d?.kind||e[43]!==h||e[44]!==n?(O=d?.kind==="fn"&&h===void 0&&(0,C.jsx)(U,{testId:"api-empty",title:n("API usage snippets")}),e[42]=d?.kind,e[43]=h,e[44]=n,e[45]=O):O=e[45];let S;e[46]!==d?(S=d?.kind==="table"&&(0,C.jsx)(ot,{name:d.name}),e[46]=d,e[47]=S):S=e[47];let T;e[48]!==w||e[49]!==j||e[50]!==O||e[51]!==S?(T=(0,C.jsxs)("div",{className:"min-w-0",children:[w,j,O,S]}),e[48]=w,e[49]=j,e[50]=O,e[51]=S,e[52]=T):T=e[52];let A;return e[53]!==k||e[54]!==T||e[55]!==I||e[56]!==P?(A=(0,C.jsxs)("div",{className:I,"data-testid":P,children:[k,T]}),e[53]=k,e[54]=T,e[55]=I,e[56]=P,e[57]=A):A=e[57],A},"ke");function it(t){return t.name}u(it,"ue");function lt(t,e){return t.localeCompare(e)}u(lt,"me");var We=z(te(),1);var K=z(te(),1),J=z(ue(),1);var p=z(re(),1);var pe=u(function(t,e,a){let r=(0,K.c)(15),n;r[0]===Symbol.for("react.memo_cache_sentinel")?(n={kind:"loading"},r[0]=n):n=r[0];let[s,o]=(0,J.useState)(n),i;r[1]!==e?(i=u(async()=>e(),"a"),r[1]=e,r[2]=i):i=r[2];let d=(0,J.useEffectEvent)(i),m;r[3]!==a?(m=u(g=>a(g),"d"),r[3]=a,r[4]=m):m=r[4];let l=(0,J.useEffectEvent)(m),c;r[5]!==l||r[6]!==d||r[7]!==t?(c=u(()=>{if(t!==void 0)return;let g=!1;return d().then(x=>(g||o(l(x)),x)).catch(x=>{g||o({kind:"error",message:le(x)})}),()=>{g=!0}},"u"),r[5]=l,r[6]=d,r[7]=t,r[8]=c):c=r[8];let f;r[9]!==t?(f=[t],r[9]=t,r[10]=f):f=r[10],(0,J.useEffect)(c,f);let h;return r[11]!==a||r[12]!==s||r[13]!==t?(h=t===void 0?s:a(t),r[11]=a,r[12]=s,r[13]=t,r[14]=h):h=r[14],h},"Ot"),dt=u(t=>typeof t=="number"?"number":typeof t=="boolean"?"boolean":"string","Oe"),Je=u(t=>{if(t.enum!==void 0&&t.enum.length>0)return t.enum;if(t.anyOf!==void 0&&t.anyOf.length>0&&t.anyOf.every(e=>e.const!==void 0))return t.anyOf.map(e=>e.const)},"Z"),ce=u(t=>t===void 0?"any":t.const!==void 0?JSON.stringify(t.const):t.enum!==void 0&&t.enum.length>0?t.enum.map(e=>JSON.stringify(e)).join(" | "):t.anyOf!==void 0&&t.anyOf.length>0?t.anyOf.map(e=>ce(e)).join(" | "):t.type==="array"?`array<${ce(t.items)}>`:t.type??"any","F"),ct=u(t=>{let e=Je(t);return e!==void 0?t.type??dt(e[0]):ce(t)},"$e"),pt=u(t=>{let e=Je(t);return e===void 0?void 0:e.map(a=>JSON.stringify(a)).join(" | ")},"Te"),mt=u(t=>{let e=[];t.minimum!==void 0?e.push(`${String(t.minimum)} \u2264`):t.exclusiveMinimum!==void 0&&e.push(`${String(t.exclusiveMinimum)} <`);let a=e.length>0;e.push("value"),t.maximum!==void 0?e.push(`\u2264 ${String(t.maximum)}`):t.exclusiveMaximum!==void 0&&e.push(`< ${String(t.exclusiveMaximum)}`);let r=e.length>(a?2:1);return a||r?e.join(" "):void 0},"Ee"),ut=u(t=>{if(t.type==="object"&&t.properties!==void 0)return t;if(t.type==="array"&&t.items?.type==="object"&&t.items.properties!==void 0)return t.items},"Ce"),Z=u(t=>{if(t===void 0)return null;if(t.const!==void 0)return t.const;if(t.enum!==void 0&&t.enum.length>0)return t.enum[0];if(t.anyOf!==void 0&&t.anyOf.length>0)return Z(t.anyOf[0]);switch(t.type){case"array":return[];case"boolean":return!1;case"number":return 0;case"object":{let e={};for(let[a,r]of Object.entries(t.properties??{}))e[a]=Z(r);return e}case"string":return"";default:return null}},"D"),de=u(t=>{let e=(0,K.c)(7),{label:a,value:r}=t,n;e[0]!==a?(n=(0,p.jsx)("span",{className:"text-muted-foreground",children:a}),e[0]=a,e[1]=n):n=e[1];let s;e[2]!==r?(s=(0,p.jsx)("span",{className:"text-foreground",children:r}),e[2]=r,e[3]=s):s=e[3];let o;return e[4]!==n||e[5]!==s?(o=(0,p.jsxs)("span",{className:"inline-flex items-center gap-1 rounded border border-border px-1.5 py-0.5 font-mono text-[10px]",children:[n,s]}),e[4]=n,e[5]=s,e[6]=o):o=e[6],o},"K"),ft=u(t=>{let e=(0,K.c)(40),{name:a,required:r,schema:n}=t,s=M(),o;e[0]!==n?(o=mt(n),e[0]=n,e[1]=o):o=e[1];let i=o,d;e[2]!==n?(d=pt(n),e[2]=n,e[3]=d):d=e[3];let m=d,l=n["x-lunora-table"],c=n.format!==void 0||i!==void 0||m!==void 0||l!==void 0,f;e[4]!==n?(f=ut(n),e[4]=n,e[5]=f):f=e[5];let h=f,g=r?"*":"?",x;e[6]!==g?(x=(0,p.jsx)("span",{className:"text-muted-foreground",children:g}),e[6]=g,e[7]=x):x=e[7];let y;e[8]!==a||e[9]!==x?(y=(0,p.jsxs)("span",{className:"font-mono text-foreground",children:[a,x]}),e[8]=a,e[9]=x,e[10]=y):y=e[10];let N;e[11]!==n?(N=ct(n),e[11]=n,e[12]=N):N=e[12];let v;e[13]!==N?(v=(0,p.jsx)("span",{className:"font-mono text-muted-foreground",children:N}),e[13]=N,e[14]=v):v=e[14];let b;e[15]!==y||e[16]!==v?(b=(0,p.jsxs)("div",{className:"flex items-baseline gap-2",children:[y,v]}),e[15]=y,e[16]=v,e[17]=b):b=e[17];let I;e[18]!==n.description?(I=n.description!==void 0&&(0,p.jsx)("p",{className:"max-w-prose text-muted-foreground",children:n.description}),e[18]=n.description,e[19]=I):I=e[19];let P;e[20]!==c||e[21]!==i||e[22]!==l||e[23]!==n.format||e[24]!==s||e[25]!==m?(P=c&&(0,p.jsxs)("div",{className:"flex flex-wrap gap-1",children:[n.format!==void 0&&(0,p.jsx)(de,{label:s("Format"),value:n.format}),i!==void 0&&(0,p.jsx)(de,{label:s("Range"),value:i}),m!==void 0&&(0,p.jsx)(de,{label:s("Value in"),value:m}),l!==void 0&&(0,p.jsx)(de,{label:s("relation"),value:l})]}),e[20]=c,e[21]=i,e[22]=l,e[23]=n.format,e[24]=s,e[25]=m,e[26]=P):P=e[26];let $;e[27]!==I||e[28]!==P||e[29]!==b?($=(0,p.jsxs)("div",{className:"flex flex-col gap-1 py-2",children:[b,I,P]}),e[27]=I,e[28]=P,e[29]=b,e[30]=$):$=e[30];let k=$;if(h===void 0){let S;return e[31]!==k?(S=(0,p.jsx)("div",{className:"border-b border-border/50 last:border-b-0",children:k}),e[31]=k,e[32]=S):S=e[32],S}let w;e[33]!==k?(w=(0,p.jsx)("summary",{className:"cursor-pointer marker:text-muted-foreground",children:k}),e[33]=k,e[34]=w):w=e[34];let j;e[35]!==h?(j=(0,p.jsx)("div",{className:"mb-2 ml-2 border-l border-border pl-3",children:(0,p.jsx)(Me,{schema:h})}),e[35]=h,e[36]=j):j=e[36];let O;return e[37]!==w||e[38]!==j?(O=(0,p.jsxs)("details",{className:"border-b border-border/50 last:border-b-0",children:[w,j]}),e[37]=w,e[38]=j,e[39]=O):O=e[39],O},"Ae"),Me=u(t=>{let e=(0,K.c)(7),{schema:a}=t,r;e[0]!==a.required?(r=new Set(a.required),e[0]=a.required,e[1]=r):r=e[1];let n=r,s;e[2]!==a.properties?(s=Object.entries(a.properties??{}),e[2]=a.properties,e[3]=s):s=e[3];let o=s,i;return e[4]!==n||e[5]!==o?(i=(0,p.jsx)("div",{className:"flex flex-col",children:o.map(d=>{let[m,l]=d;return(0,p.jsx)(ft,{name:m,required:n.has(m),schema:l},m)})}),e[4]=n,e[5]=o,e[6]=i):i=e[6],i},"ee"),Re=u(t=>{let e=(0,K.c)(10),{schema:a,testId:r}=t;if(a?.type!=="object"||Object.keys(a.properties??{}).length===0){let o;e[0]!==a?(o=ce(a),e[0]=a,e[1]=o):o=e[1];let i;return e[2]!==o||e[3]!==r?(i=(0,p.jsx)("p",{className:"font-mono text-xs text-muted-foreground","data-testid":r,children:o}),e[2]=o,e[3]=r,e[4]=i):i=e[4],i}let n;e[5]!==a?(n=(0,p.jsx)(Me,{schema:a}),e[5]=a,e[6]=n):n=e[6];let s;return e[7]!==n||e[8]!==r?(s=(0,p.jsx)("div",{className:"text-xs","data-testid":r,children:n}),e[7]=n,e[8]=r,e[9]=s):s=e[9],s},"G"),ht=["curl","javascript","lunora"],gt={lunora:"Lunora",curl:"cURL",javascript:"JavaScript"},xt=u(t=>`api.${t.replaceAll(/[/:]/g,".")}`,"Ie"),bt=u(t=>{let e=Z(t.argsSchema)??{};return t.functionPath===void 0?e:{args:e,functionPath:t.functionPath}},"Pe"),vt=u((t,e,a)=>{let r=`${a}${e.httpPath}`,n=JSON.stringify(bt(e),void 0,2),s=JSON.stringify(Z(e.argsSchema)??{},void 0,2);switch(t){case"curl":{let o=e.method!=="GET"&&e.method!=="HEAD",i=[`curl -X ${e.method} ${JSON.stringify(r)}`];return o&&i.push(' -H "Content-Type: application/json"',` -d '${n}'`),i.join(` \\
|
|
3
3
|
`)}case"lunora":return e.functionPath===void 0?`await fetch(${JSON.stringify(e.httpPath)}, { method: ${JSON.stringify(e.method)} });`:`import { useLunora } from "@lunora/react";
|
|
4
4
|
import { api } from "./_generated/api";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as H}from"./chunk-LCRAEP3B.js";import"./chunk-UXXDN6Z3.js";import{a as F}from"./chunk-66UGPQVC.js";import{a as I}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import"./chunk-225VJ77I.js";import{b as $}from"./chunk-
|
|
1
|
+
import{a as H}from"./chunk-LCRAEP3B.js";import"./chunk-UXXDN6Z3.js";import{a as F}from"./chunk-66UGPQVC.js";import{a as I}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import"./chunk-225VJ77I.js";import{b as $}from"./chunk-FZ5ZSUA2.js";import{f as S}from"./chunk-PG7XHMUR.js";import"./chunk-FSRSK4LY.js";import"./chunk-5ICUJ4IA.js";import{a as B}from"./chunk-FKVZRPV5.js";import{a as L,b as O,c as E,d as k,e as n,f as l}from"./chunk-HEAQVSNS.js";import{a as j,e as z}from"./chunk-WUWBZPUK.js";import{d as C,p as R,t as T}from"./chunk-PTZD7RUZ.js";import{a as f,d as y,e as D,f as G,g as J}from"./chunk-YKXDMIHQ.js";var P=y(G(),1);var Q=y(D(),1);var s=y(J(),1);var w=200,se=f(()=>{let e=(0,P.c)(28),d=S(),a=C(),[i,q]=(0,Q.useState)(0),p;e[0]!==i?(p=["lunora-auth-sessions",w,i],e[0]=i,e[1]=p):p=e[1];let x;e[2]!==d||e[3]!==i?(x=f(()=>d.listAuthSessions({limit:w,offset:i}),"p"),e[2]=d,e[3]=i,e[4]=x):x=e[4];let r=$(p,x),{error:g}=r,t=r.data?.rows??null,N;e[5]!==r?(N=f(()=>{r.refetch()},"b"),e[5]=r,e[6]=N):N=e[6],F(N,!0);let v;e[7]!==d||e[8]!==r?(v=f(o=>{R((async()=>{await d.revokeAuthSession({sessionId:o}),r.refetch()})())},"g"),e[7]=d,e[8]=r,e[9]=v):v=e[9];let b=v,c;e[10]!==g?(c=g!==null&&(0,s.jsx)("p",{className:"text-sm text-destructive","data-testid":"auth-sessions-error",role:"alert",children:g}),e[10]=g,e[11]=c):c=e[11];let m;e[12]!==t||e[13]!==a?(m=t!==null&&t.length===0&&(0,s.jsx)(B,{testId:"auth-sessions-empty",title:a("No active sessions.")}),e[12]=t,e[13]=a,e[14]=m):m=e[14];let h;e[15]!==b||e[16]!==t||e[17]!==a?(h=t!==null&&t.length>0&&(0,s.jsx)(j,{className:"overflow-hidden py-0",children:(0,s.jsx)(z,{className:"px-0",children:(0,s.jsxs)(L,{"data-testid":"auth-sessions-table",children:[(0,s.jsx)(O,{children:(0,s.jsxs)(k,{children:[(0,s.jsx)(n,{children:a("user")}),(0,s.jsx)(n,{children:a("expires")}),(0,s.jsx)(n,{children:a("ip")}),(0,s.jsx)(n,{children:a("user agent")}),(0,s.jsx)(n,{children:a("impersonated by")}),(0,s.jsx)(n,{"aria-label":a("Actions")})]})}),(0,s.jsx)(E,{children:t.map(o=>(0,s.jsxs)(k,{"data-testid":`auth-session-${o.id}`,children:[(0,s.jsx)(l,{className:"font-mono text-xs",children:o.userId}),(0,s.jsx)(l,{className:"text-muted-foreground tabular-nums",children:T(o.expiresAt)}),(0,s.jsx)(l,{children:o.ipAddress??""}),(0,s.jsx)(l,{className:"max-w-40 truncate",children:o.userAgent??""}),(0,s.jsx)(l,{className:"font-mono text-xs",children:o.impersonatedBy??""}),(0,s.jsx)(l,{children:(0,s.jsx)(I,{"data-testid":`auth-session-revoke-${o.id}`,onClick:f(()=>{b(o.id)},"onClick"),size:"xs",type:"button",variant:"ghost",children:a("Revoke")})})]},o.id))})]})})}),e[15]=b,e[16]=t,e[17]=a,e[18]=h):h=e[18];let u;e[19]!==i||e[20]!==t||e[21]!==r.data?.total?(u=t!==null&&(0,s.jsx)(H,{count:t.length,offset:i,onOffsetChange:q,pageSize:w,prefix:"auth-sessions",total:r.data?.total}),e[19]=i,e[20]=t,e[21]=r.data?.total,e[22]=u):u=e[22];let A;return e[23]!==c||e[24]!==m||e[25]!==h||e[26]!==u?(A=(0,s.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"auth-sessions",children:[c,m,h,u]}),e[23]=c,e[24]=m,e[25]=h,e[26]=u,e[27]=A):A=e[27],A},"ee");export{se as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as g}from"./chunk-
|
|
1
|
+
import{b as g}from"./chunk-CCHE3AP7.js";import"./chunk-ZVJOW25X.js";import"./chunk-ULIQFBZU.js";import"./chunk-46EQO6E7.js";import"./chunk-35DM4JJG.js";import{a as f}from"./chunk-4ZEL6BYL.js";import{c as m}from"./chunk-FZ5ZSUA2.js";import"./chunk-PG7XHMUR.js";import"./chunk-FSRSK4LY.js";import"./chunk-5ICUJ4IA.js";import"./chunk-HEAQVSNS.js";import"./chunk-WUWBZPUK.js";import{d as p}from"./chunk-PTZD7RUZ.js";import{a as r,d as h,f as S,g as A}from"./chunk-YKXDMIHQ.js";var R=h(S(),1);var k=h(A(),1);var _=r((e,s)=>({"admin-token-weak":e("Weak admin token"),"auth-secret-weak":e("Weak auth secret"),"cookies-insecure":e("Session cookies are not Secure"),"cors-wildcard-credentials":e("Wildcard CORS with credentials"),"csrf-disabled":e("CSRF/origin guard is off"),"dev-args-unredacted":e("Request log keeps un-redacted args"),"security-headers-disabled":e("Security headers are off"),"ws-gate-open":e("User subscriptions are ungated")})[s.kind],"k"),w=r(e=>Array.isArray(e.findings)?e.findings:[],"g"),b=r(e=>({"admin-token-weak":"LUNORA_ADMIN_TOKEN","auth-secret-weak":"AUTH_SECRET","cookies-insecure":"BETTER_AUTH_URL","cors-wildcard-credentials":"LUNORA_ALLOWED_ORIGINS","csrf-disabled":"LUNORA_SECURITY_CSRF","dev-args-unredacted":"request log","security-headers-disabled":"LUNORA_SECURITY_HEADERS","ws-gate-open":"LUNORA_WS_BEARER"})[e.kind],"S"),E=r((e,s)=>({"admin-token-weak":e("Your admin token is {length} characters \u2014 use at least {min} for a brute-force-resistant secret.",{length:s.detail?.length,min:s.detail?.min}),"auth-secret-weak":e("Your auth secret is {length} characters \u2014 use at least {min} (e.g. `openssl rand -hex 32`) to sign sessions safely.",{length:s.detail?.length,min:s.detail?.min}),"cookies-insecure":e("BETTER_AUTH_URL is a plaintext http:// origin, so session cookies cannot be Secure and ride in cleartext. Serve auth over https:// in production."),"cors-wildcard-credentials":e("LUNORA_ALLOWED_ORIGINS includes a wildcard while credentials are allowed \u2014 browsers reject this and it defeats the allowlist. Name explicit origins instead of *."),"csrf-disabled":e("LUNORA_SECURITY_CSRF is off, so cross-origin state-changing cookie requests are not blocked. Re-enable it in production to keep mutations un-forgeable."),"dev-args-unredacted":e("This worker reports a development environment, so the request log stores raw args and identity. Confirm it isn't a mislabeled production deploy."),"security-headers-disabled":e("LUNORA_SECURITY_HEADERS is off, so HSTS, CSP, nosniff, and frame-options are not applied. Re-enable the baseline headers in production."),"ws-gate-open":e("LUNORA_WS_BEARER is unset, so the WebSocket upgrade gate is open: anyone who can reach the worker can open a socket and run ordinary user subscriptions. Admin subscriptions are unaffected \u2014 they need the admin token. Set it if subscribers should present a shared credential.")})[s.kind],"A"),O=r(()=>{let e=(0,R.c)(8),s=p(),i;e[0]===Symbol.for("react.memo_cache_sentinel")?(i={},e[0]=i):i=e[0];let{data:a,error:d,errorSource:c}=m(f.getSecurityAudit,i),n;if(e[1]!==a||e[2]!==s){let u=a===void 0?null:w(a);n=u===null?null:u.map(t=>({description:E(s,t),entity:b(t),issueType:_(s,t),key:t.kind,level:t.level})),e[1]=a,e[2]=s,e[3]=n}else n=e[3];let l=n,o;return e[4]!==d||e[5]!==c||e[6]!==l?(o=(0,k.jsx)(g,{error:d,errorSource:c,rows:l,testId:"lunora-security-advisor"}),e[4]=d,e[5]=c,e[6]=l,e[7]=o):o=e[7],o},"T");export{O as default};
|