@lunora/studio 1.0.0-alpha.324 → 1.0.0-alpha.326
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 +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.mjs +1 -1
- package/dist/mount.d.mts +1 -1
- package/dist/mount.d.ts +1 -1
- package/dist/mount.mjs +1 -1
- package/dist/packem_chunks/AdvisorHealthPanel.mjs +1 -1
- package/dist/packem_chunks/ApiTab.mjs +1 -1
- package/dist/packem_chunks/AuditPanel.mjs +1 -1
- package/dist/packem_chunks/DeploymentHealthPanel.mjs +1 -1
- package/dist/packem_chunks/ExportImportPanel.mjs +1 -1
- package/dist/packem_chunks/FileBrowser.mjs +1 -1
- package/dist/packem_chunks/FunctionRunner.mjs +1 -1
- package/dist/packem_chunks/FunctionStatsPanel.mjs +1 -1
- package/dist/packem_chunks/HealthPanel.mjs +1 -1
- package/dist/packem_chunks/InsightsPanel.mjs +1 -1
- package/dist/packem_chunks/LogsPanel.mjs +1 -1
- package/dist/packem_chunks/MailPanel.mjs +1 -1
- package/dist/packem_chunks/MetricsPanel.mjs +1 -1
- package/dist/packem_chunks/NotificationsPanel.mjs +1 -1
- package/dist/packem_chunks/PitrPanel.mjs +1 -1
- package/dist/packem_chunks/SchemaViewer.mjs +1 -1
- package/dist/packem_chunks/SecurityAdvisorPanel.mjs +1 -1
- package/dist/packem_chunks/SettingsPanel.mjs +1 -1
- package/dist/packem_chunks/SqlEditorPanel.mjs +1 -1
- package/dist/packem_chunks/TableEditor.mjs +1 -1
- package/dist/packem_chunks/agents-panel.mjs +1 -1
- package/dist/packem_chunks/ai-usage-panel.mjs +1 -1
- package/dist/packem_chunks/analytics-panel.mjs +1 -1
- package/dist/packem_chunks/architecture-panel.mjs +1 -1
- package/dist/packem_chunks/auth-audit-panel.mjs +1 -1
- package/dist/packem_chunks/auth-config-panel.mjs +1 -1
- package/dist/packem_chunks/auth-sessions-panel.mjs +1 -1
- package/dist/packem_chunks/containers-panel.mjs +1 -1
- package/dist/packem_chunks/dashboards-panel.mjs +1 -1
- package/dist/packem_chunks/evals-panel.mjs +1 -1
- package/dist/packem_chunks/fanout-panel.mjs +1 -1
- package/dist/packem_chunks/flags-panel.mjs +1 -1
- package/dist/packem_chunks/issues-panel.mjs +1 -1
- package/dist/packem_chunks/kv-browser.mjs +1 -1
- package/dist/packem_chunks/log-drains-panel.mjs +1 -1
- package/dist/packem_chunks/migrations-route.mjs +1 -1
- package/dist/packem_chunks/organizations-panel.mjs +1 -1
- package/dist/packem_chunks/payments-panel.mjs +1 -1
- package/dist/packem_chunks/permissions-panel.mjs +1 -1
- package/dist/packem_chunks/privacy-requests-panel.mjs +1 -1
- package/dist/packem_chunks/queues-panel.mjs +1 -1
- package/dist/packem_chunks/reactors-panel.mjs +1 -1
- package/dist/packem_chunks/rls-panel.mjs +1 -1
- package/dist/packem_chunks/schedule-panel.mjs +1 -1
- package/dist/packem_chunks/storage-rules-panel.mjs +1 -1
- package/dist/packem_chunks/subscriptions-panel.mjs +1 -1
- package/dist/packem_chunks/sync-client-panel.mjs +1 -1
- package/dist/packem_chunks/traces-panel.mjs +1 -1
- package/dist/packem_chunks/users-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/{ApiDocsPanel-fhDlZGE4.mjs → ApiDocsPanel-6yZaaxch.mjs} +1 -1
- package/dist/packem_shared/{ApiReferencePanel-nAf8tNRr.mjs → ApiReferencePanel-mwEK_vL7.mjs} +1 -1
- package/dist/packem_shared/{CommandPalette-D9ZY-qQd.mjs → CommandPalette-CcTVGQvw.mjs} +1 -1
- package/dist/packem_shared/{DataBrowser-E68QfaST.mjs → DataBrowser-B6xr6S3s.mjs} +1 -1
- package/dist/packem_shared/{GlobalDataBrowser-DhObcZDY.mjs → GlobalDataBrowser-DlBYI85g.mjs} +1 -1
- package/dist/packem_shared/{HomePanel-CUuYsApa.mjs → HomePanel-DBUgY2yE.mjs} +1 -1
- package/dist/packem_shared/{MigrationsPanel-C2kb3oL-.mjs → MigrationsPanel-_H327LDl.mjs} +1 -1
- package/dist/packem_shared/{OpenRpcReferencePanel-BxEr49D9.mjs → OpenRpcReferencePanel-DJg4AbuZ.mjs} +1 -1
- package/dist/packem_shared/{ScheduledJobs-BZNcYWBP.mjs → ScheduledJobs-CscRWLW-.mjs} +1 -1
- package/dist/packem_shared/{Studio-CZjQXFHC.mjs → Studio-s4EbmwaL.mjs} +1 -1
- package/dist/packem_shared/{StudioApp-C9ENwcOH.mjs → StudioApp-D1e2uc7_.mjs} +1 -1
- package/dist/packem_shared/{advisor-view-y4cW5JcX.mjs → advisor-view-kg9uZT7H.mjs} +1 -1
- package/dist/packem_shared/{app.d-D7vL0y8y.d.mts → app.d-D45VvUTx.d.mts} +2 -0
- package/dist/packem_shared/{app.d-D7vL0y8y.d.ts → app.d-D45VvUTx.d.ts} +2 -0
- package/dist/packem_shared/{data-grid-DIiNmDR9.mjs → data-grid-XIuWrWDy.mjs} +1 -1
- package/dist/packem_shared/{diagram-export-panel-D5CVNJkp.mjs → diagram-export-panel-DrYRni_b.mjs} +1 -1
- package/dist/packem_shared/{error-alert-DAsOWnCL.mjs → error-alert-Dr4RMEID.mjs} +1 -1
- package/dist/packem_shared/{grid-features-OVIMIQan.mjs → grid-features-6mTvrzgT.mjs} +1 -1
- package/dist/packem_shared/{home-panel-BcE8S2Nn.mjs → home-panel-CKbpgpz9.mjs} +1 -1
- package/dist/packem_shared/{internal-Df43vQI0.mjs → internal-S7SDbbPa.mjs} +2 -2
- package/dist/packem_shared/{log-line-CICyJ_kc.mjs → log-line-DP0b3YT5.mjs} +1 -1
- package/dist/packem_shared/{recording-client-CyFiAE2l.mjs → recording-client-BbX9ql7w.mjs} +1 -1
- package/dist/packem_shared/{reference-view-CIHyURU6.mjs → reference-view-DNdYDPow.mjs} +1 -1
- package/dist/packem_shared/{schema-diagram-C5oilX7l.mjs → schema-diagram-DKBYRWsL.mjs} +1 -1
- package/dist/packem_shared/{sql-result-table-DyK762_A.mjs → sql-result-table-B7g48CHO.mjs} +1 -1
- package/dist/packem_shared/{studio-fK2DTLde.mjs → studio-BTM7dITm.mjs} +1 -1
- package/dist/packem_shared/{table-list-sidebar-DkPO_Qtz.mjs → table-list-sidebar-DcvrtBkE.mjs} +1 -1
- package/dist/packem_shared/{use-admin-query-tlBof8Yg.mjs → use-admin-query-B2jU5P5u.mjs} +1 -1
- package/dist/packem_shared/{use-admin-spec-Bir7V68L.mjs → use-admin-spec-CISwmdXM.mjs} +1 -1
- package/dist/packem_shared/{use-async-submit-CZqCMTJ_.mjs → use-async-submit-CgvRHgaD.mjs} +1 -1
- package/dist/packem_shared/{use-auth-config-Z_n4ABCI.mjs → use-auth-config-B9w5-1-p.mjs} +1 -1
- package/dist/packem_shared/{use-open-trace-DMVhpnyG.mjs → use-open-trace-CUyoDXjN.mjs} +1 -1
- package/dist/packem_shared/{use-sql-assistant-CZydTzd5.mjs → use-sql-assistant-CK6G1ycr.mjs} +1 -1
- package/dist/standalone/{chunk-YVR4SEPU.js → chunk-2EYOYWS2.js} +1 -1
- package/dist/standalone/{chunk-OSGXNEFA.js → chunk-2G3B5PAO.js} +1 -1
- package/dist/standalone/{chunk-ZJQI4C3A.js → chunk-2PZ4MP3G.js} +1 -1
- package/dist/standalone/{chunk-2VA5S3IA.js → chunk-2QXJTBVX.js} +1 -1
- package/dist/standalone/{chunk-6HLARDYO.js → chunk-2W67FQCF.js} +1 -1
- package/dist/standalone/{chunk-4Y5AFETG.js → chunk-33YIKGW6.js} +1 -1
- package/dist/standalone/{chunk-WP2AS7SZ.js → chunk-3I6JC6NL.js} +1 -1
- package/dist/standalone/{chunk-WJHMDTV2.js → chunk-4LAD57XQ.js} +1 -1
- package/dist/standalone/{chunk-RBAD4SMG.js → chunk-52YTJ556.js} +1 -1
- package/dist/standalone/chunk-5CNRDILP.js +1 -0
- package/dist/standalone/{chunk-HJHSQPHW.js → chunk-5OMZCVRF.js} +1 -1
- package/dist/standalone/{chunk-MGEACGEE.js → chunk-6LU7UD32.js} +1 -1
- package/dist/standalone/{chunk-2QLSWJDL.js → chunk-6TILEHRA.js} +1 -1
- package/dist/standalone/{chunk-CUJGTNYR.js → chunk-6Z2A2P2U.js} +1 -1
- package/dist/standalone/{chunk-2H5IXFGR.js → chunk-7AEDQPBM.js} +1 -1
- package/dist/standalone/{chunk-SNJ5HRZO.js → chunk-7FY6RTSD.js} +1 -1
- package/dist/standalone/{chunk-POKVFO6Q.js → chunk-7JYYC4A5.js} +1 -1
- package/dist/standalone/{chunk-OX6JWCPF.js → chunk-7QP56XBQ.js} +1 -1
- package/dist/standalone/{chunk-NDGHCEE3.js → chunk-7TF3N4ZD.js} +1 -1
- package/dist/standalone/{chunk-4K6CXILB.js → chunk-AKHBJSQO.js} +1 -1
- package/dist/standalone/{chunk-MJ3SSK6L.js → chunk-AQFI2GWT.js} +1 -1
- package/dist/standalone/{chunk-QSUWAGXH.js → chunk-B74YABQU.js} +1 -1
- package/dist/standalone/chunk-BDYCZHD2.js +9 -0
- package/dist/standalone/{chunk-MRJB4FPI.js → chunk-CQ3UUCD2.js} +1 -1
- package/dist/standalone/{chunk-22TUDRBR.js → chunk-CUEZLEQO.js} +1 -1
- package/dist/standalone/{chunk-HOGQLP3J.js → chunk-D6ZXOSCM.js} +1 -1
- package/dist/standalone/{chunk-SV764LKQ.js → chunk-D746I7ZX.js} +1 -1
- package/dist/standalone/{chunk-KU3IXE36.js → chunk-DGHWBHUF.js} +1 -1
- package/dist/standalone/{chunk-Z6THFOLU.js → chunk-DSYUT6DA.js} +1 -1
- package/dist/standalone/{chunk-TIQ7OBZJ.js → chunk-DVX5J34S.js} +1 -1
- package/dist/standalone/{chunk-7AF3FZCB.js → chunk-E7Q7NE77.js} +1 -1
- package/dist/standalone/{chunk-MTGFTTXO.js → chunk-FBGCQYRO.js} +1 -1
- package/dist/standalone/{chunk-JZGTSH2C.js → chunk-FCVKROK5.js} +1 -1
- package/dist/standalone/{chunk-2JH7ZYVY.js → chunk-G26RQPDL.js} +1 -1
- package/dist/standalone/{chunk-F3UUFO2C.js → chunk-GH24P7D2.js} +1 -1
- package/dist/standalone/{chunk-MB5JGSN6.js → chunk-HC4J57UZ.js} +1 -1
- package/dist/standalone/{chunk-6YQ3RTCB.js → chunk-HTGHQYIG.js} +1 -1
- package/dist/standalone/{chunk-OM3B3V47.js → chunk-HXLPQMQY.js} +1 -1
- package/dist/standalone/{chunk-VFL7VJWF.js → chunk-HYKN42SO.js} +1 -1
- package/dist/standalone/{chunk-XHRKNCCI.js → chunk-I23ULEUU.js} +1 -1
- package/dist/standalone/{chunk-OH7DVC7S.js → chunk-IBXENKTW.js} +1 -1
- package/dist/standalone/{chunk-EXYBVVHU.js → chunk-JM4M6D6X.js} +1 -1
- package/dist/standalone/{chunk-W3LXMSGC.js → chunk-JOQMVPGT.js} +1 -1
- package/dist/standalone/{chunk-3OHVDOV5.js → chunk-K67NQCL7.js} +1 -1
- package/dist/standalone/{chunk-U4YBJ4OW.js → chunk-KC67FFZF.js} +1 -1
- package/dist/standalone/{chunk-SB4443ME.js → chunk-KGWOEE3Y.js} +1 -1
- package/dist/standalone/{chunk-7RAYXTNN.js → chunk-LCYDNUTU.js} +1 -1
- package/dist/standalone/{chunk-SQ2LCZBH.js → chunk-LWE4JQGT.js} +1 -1
- package/dist/standalone/{chunk-ESSG4L6C.js → chunk-MNXBTILQ.js} +1 -1
- package/dist/standalone/{chunk-R6PJYMJT.js → chunk-MRWBB3N3.js} +1 -1
- package/dist/standalone/{chunk-WFNUMMDF.js → chunk-MZB4M3O4.js} +2 -2
- package/dist/standalone/{chunk-R4ILI46D.js → chunk-N5VW6ADU.js} +1 -1
- package/dist/standalone/{chunk-HER5A45F.js → chunk-NFCRD6DB.js} +1 -1
- package/dist/standalone/{chunk-OK35SLOW.js → chunk-O3YOPOFI.js} +1 -1
- package/dist/standalone/{chunk-QZRKA2E4.js → chunk-O4AU6G7Z.js} +1 -1
- package/dist/standalone/{chunk-5WOMOENH.js → chunk-OGNEIWHN.js} +1 -1
- package/dist/standalone/{chunk-JNBWPXNV.js → chunk-OJVA6YJI.js} +1 -1
- package/dist/standalone/{chunk-XTQR2C6N.js → chunk-OKX7I64M.js} +1 -1
- package/dist/standalone/{chunk-4WD4XGC3.js → chunk-OMN44W6V.js} +1 -1
- package/dist/standalone/{chunk-6MFVEI7C.js → chunk-OTQSYE6X.js} +1 -1
- package/dist/standalone/{chunk-HM57YJY5.js → chunk-OVVRMPVR.js} +1 -1
- package/dist/standalone/{chunk-WAX5WY6F.js → chunk-P2NSASR2.js} +1 -1
- package/dist/standalone/{chunk-EEDIMNRC.js → chunk-PKHFMUAX.js} +1 -1
- package/dist/standalone/{chunk-RDJCY5PQ.js → chunk-PWH4FCFR.js} +1 -1
- package/dist/standalone/{chunk-DSIY2CMT.js → chunk-PYNRIX74.js} +1 -1
- package/dist/standalone/{chunk-JL6LEVHQ.js → chunk-RU4O6ZXP.js} +1 -1
- package/dist/standalone/{chunk-UDMY3BMT.js → chunk-SEODHPIF.js} +1 -1
- package/dist/standalone/{chunk-3YH5TM3G.js → chunk-UQAMQR4Q.js} +1 -1
- package/dist/standalone/{chunk-Z22BDS6N.js → chunk-VASJTDMU.js} +1 -1
- package/dist/standalone/{chunk-DL6TTBE6.js → chunk-VST2VNEU.js} +1 -1
- package/dist/standalone/{chunk-NW6FNJ4L.js → chunk-W3QVYZMI.js} +1 -1
- package/dist/standalone/{chunk-ICU56FBP.js → chunk-WGU2LV5D.js} +1 -1
- package/dist/standalone/chunk-WS7WNXF3.js +15 -0
- package/dist/standalone/{chunk-PIMTWCRD.js → chunk-X2YHVCMH.js} +1 -1
- package/dist/standalone/{chunk-NDTQTKDX.js → chunk-X472RKFD.js} +1 -1
- package/dist/standalone/{chunk-VKURTWDH.js → chunk-XBZGJ7I6.js} +1 -1
- package/dist/standalone/{chunk-NYHYH5Z5.js → chunk-XD6XP3QZ.js} +1 -1
- package/dist/standalone/{chunk-6QTAHSDD.js → chunk-ZQ4C2DMJ.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +5 -5
- package/dist/standalone/chunk-BOYS4DOC.js +0 -9
- package/dist/standalone/chunk-KLTGKTSL.js +0 -1
- package/dist/standalone/chunk-N7LJO732.js +0 -15
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{a as es,d as b}from"./chunk-N7LJO732.js";import{a as n,d as D,e as ee,f as ts,g as ot}from"./chunk-I26MS5PJ.js";var kr=/["\\\u0000-\u001F\uD800-\uDFFF]/,ss=n(t=>kr.test(t)?JSON.stringify(t):`"${t}"`,"y"),Tr=n(t=>Number.isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":Object.is(t,-0)?"-0":void 0,"p"),Er=n((t,e)=>{let s=Object.getPrototypeOf(t);if(s!==null&&s!==Object.prototype){let c=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${c} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let r=t,i=Object.keys(r).sort(),o="{",a=!0;for(let c of i){let u=r[c];u!==void 0&&(a?a=!1:o+=",",o+=ss(c),o+=":",o+=e(u))}return`${o}}`},"u"),ye=n(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"){let e=Tr(t);if(e!==void 0)return e}return typeof t=="string"?ss(t):t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${Array.from({length:t.length},(e,s)=>ye(t[s])).join(",")}]`:Er(t,ye)},"c");var Re=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"e");var Ae=n(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"f"),Ir=n(t=>{let e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)s[r]=e.codePointAt(r)??0;return s},"l"),O="$lunora.wire$",Fe=64,Pe=1024,Or="__proto__",Rr=/^-?\d+$/,rs={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},is={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},at=n((t,e,s)=>{e===Or?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):t[e]=s},"y");var Ar=n(t=>{let e=t.toString();if(e.length>Pe)throw new RangeError(`wire-codec: over-long bigint (max ${String(Pe)} digits)`);return[O,"bigint",e]},"T"),Fr=n(t=>Number.isNaN(t)?[O,"nan"]:t===1/0?[O,"inf"]:t===-1/0?[O,"-inf"]:t,"j"),Pr=n((t,e)=>{let s=e(Object.fromEntries(Object.keys(t).map(o=>[o,t[o]]))),r=t,i=[O,"error",String(r.name),String(r.message),s];return t.cause!==void 0&&i.push(e(t.cause)),i},"R"),Mr=n(t=>{let e=t.constructor.name,s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return e==="Uint8Array"?[O,"bytes",Ae(s)]:[O,"bytes",Ae(s),e]},"S"),xr=n((t,e)=>t instanceof Date?[O,"date",e(t.getTime())]:t instanceof Error?Pr(t,e):t instanceof URL?[O,"url",t.href]:t instanceof Map?[O,"map",[...t.entries()].map(([s,r])=>[e(s),e(r)])]:t instanceof Set?[O,"set",[...t].map(s=>e(s))]:t instanceof ArrayBuffer?[O,"bytes",Ae(new Uint8Array(t)),"ArrayBuffer"]:ArrayBuffer.isView(t)?Mr(t):void 0,"U"),Lr=n((t,e)=>{let s=t.map(r=>e(r));return s.length>0&&s[0]===O?[O,"arr",s]:s},"I"),_r=n((t,e)=>{let s={};for(let r of Object.keys(t)){let i=t[r];i!==void 0&&at(s,r,e(i))}return s},"B"),W=n((t,e=0)=>{if(e>Fe)throw new RangeError(`wire-codec: value nesting exceeds the ${String(Fe)}-level limit`);if(t===void 0)return[O,"undefined"];if(t===null)return t;if(typeof t=="bigint")return Ar(t);if(typeof t=="number")return Fr(t);if(typeof t!="object")return t;let s=n(i=>W(i,e+1),"t"),r=xr(t,s);if(r!==void 0)return r;if(Array.isArray(t))return Lr(t,s);if(!Re(t)){let i=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${i} over the Lunora wire \u2014 only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}return _r(t,s)},"m"),Qr=n(t=>{let e=t[2];if(typeof e!="string"||e.length>Pe||!Rr.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(Pe)} digits)`);return BigInt(e)},"N"),Dr=n((t,e)=>{let s=e(t[2]);if(typeof s!="number")throw new TypeError("wire-codec: malformed date \u2014 epoch must be a number");return new Date(s)},"_"),Ur=n((t,e)=>{let s=t[2];return new Map(s.map(r=>{if(!Array.isArray(r)||r.length!==2)throw new TypeError("wire-codec: malformed map entry \u2014 expected a [key, value] pair");return[e(r[0]),e(r[1])]}))},"$"),Kr=n(t=>{let e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed url \u2014 href must be a string");return new URL(e)},"k"),Nr=n((t,e)=>{let s=t[2],r=t[3];if(typeof s!="string"||typeof r!="string")throw new TypeError("wire-codec: malformed error \u2014 name and message must be strings");let i=(Object.hasOwn(is,s)?is[s]:void 0)??Error,o=new i(r);o.name!==s&&Object.defineProperty(o,"name",{configurable:!0,value:s,writable:!0});let a=e(t[4]);if(a===null||typeof a!="object"||Array.isArray(a))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let[c,u]of Object.entries(a))at(o,c,u);return t.length>5&&Object.defineProperty(o,"cause",{configurable:!0,value:e(t[5]),writable:!0}),o},"P"),qr=n(t=>{let e=t[2];if(typeof e!="string")throw new TypeError("wire-codec: malformed bytes \u2014 payload must be a base64 string");let s=Ir(e);if(Ae(s)!==e)throw new TypeError("wire-codec: malformed bytes \u2014 payload must be canonical padded base64");let r=t[3]??"Uint8Array";if(r==="ArrayBuffer")return s.buffer.byteLength===s.byteLength?s.buffer:new Uint8Array(s).buffer;let i=Object.hasOwn(rs,r)?rs[r]:void 0;return i?new i(new Uint8Array(s).buffer):s},"D"),jr=n((t,e)=>{switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(s=>e(s));case"bigint":return Qr(t);case"bytes":return qr(t);case"date":return Dr(t,e);case"error":return Nr(t,e);case"inf":return 1/0;case"map":return Ur(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(s=>e(s)));case"undefined":return;case"url":return Kr(t);default:return t.map(s=>e(s))}},"C"),Br=n((t,e)=>{let s={};for(let r of Object.keys(t))at(s,r,e(t[r]));return s},"L"),T=n((t,e=0)=>{if(e>Fe)throw new RangeError(`wire-codec: value nesting exceeds the ${String(Fe)}-level limit`);if(t===null||typeof t!="object")return t;let s=n(r=>T(r,e+1),"t");if(Array.isArray(t)){let r=t;return r[0]===O?jr(r,s):r.map(i=>s(i))}return Br(t,s)},"A"),Wr=n(t=>{try{let e=T(JSON.parse(t));return Re(e)?e:void 0}catch{return}},"F");var N=n(t=>ye(W(t)),"a");var ae=D(ee(),1),ns=D(ot(),1);var be=ae.createContext(void 0),ge=n(t=>{let e=ae.useContext(be);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),ct=n(({client:t,children:e})=>(ae.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,ns.jsx)(be.Provider,{value:t,children:e})),"QueryClientProvider");var U=class{static{n(this,"Subscribable")}constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(t){return this.listeners.add(t),this.onSubscribe(),()=>{this.listeners.delete(t),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var $r=class extends U{static{n(this,"FocusManager")}#e;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=n(()=>t(),"listener");return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#e!==t&&(this.#e=t,this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},ce=new $r;var Hr={setTimeout:n((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:n(t=>clearTimeout(t),"clearTimeout"),setInterval:n((t,e)=>setInterval(t,e),"setInterval"),clearInterval:n(t=>clearInterval(t),"clearInterval")},zr=class{static{n(this,"TimeoutManager")}#e=Hr;#t=!1;setTimeoutProvider(t){this.#e=t}setTimeout(t,e){return this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},$=new zr;function os(t){setTimeout(t,0)}n(os,"systemSetTimeoutZero");var ht=typeof window>"u"||"Deno"in globalThis;function E(){}n(E,"noop");function us(t,e){return typeof t=="function"?t(e):t}n(us,"functionalUpdate");function ve(t){return typeof t=="number"&&t>=0&&t!==1/0}n(ve,"isValidTimeout");function Me(t,e){return Math.max(t+(e||0)-Date.now(),0)}n(Me,"timeUntilStale");function q(t,e){return typeof t=="function"?t(e):t}n(q,"resolveStaleTime");function M(t,e){return typeof t=="function"?t(e):t}n(M,"resolveQueryBoolean");function xe(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:o,queryKey:a,stale:c}=t;if(a){if(r){if(e.queryHash!==Se(a,e.options))return!1}else if(!te(e.queryKey,a))return!1}if(s!=="all"){let u=e.isActive();if(s==="active"&&!u||s==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||o&&!o(e))}n(xe,"matchQuery");function Le(t,e){let{exact:s,status:r,predicate:i,mutationKey:o}=t;if(o){if(!e.options.mutationKey)return!1;if(s){if(H(e.options.mutationKey)!==H(o))return!1}else if(!te(e.options.mutationKey,o))return!1}return!(r&&e.state.status!==r||i&&!i(e))}n(Le,"matchMutation");function Se(t,e){return(e?.queryKeyHashFn||H)(t)}n(Se,"hashQueryKeyByOptions");function H(t){return JSON.stringify(t,(e,s)=>ut(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}n(H,"hashKey");function te(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){for(let r=0;r<e.length;r++)if(!te(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!te(t[r],e[r]))return!1;return!0}return!1}n(te,"partialMatchKey");var Gr=Object.prototype.hasOwnProperty;function dt(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=as(t)&&as(e);if(!r&&!(ut(t)&&ut(e)))return e;let o=(r?t:Object.keys(t)).length,a=r?e:Object.keys(e),c=a.length,u=r?new Array(c):{},d=0;for(let h=0;h<c;h++){let l=r?h:a[h],f=t[l],p=e[l];if(f===p){u[l]=f,(r?h<o:Gr.call(t,l))&&d++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){u[l]=p;continue}let m=dt(f,p,s+1);u[l]=m,m===f&&d++}return o===c&&d===o?t:u}n(dt,"replaceEqualDeep");function ue(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let s in t)if(t[s]!==e[s])return!1;return!0}n(ue,"shallowEqualObjects");function as(t){return Array.isArray(t)&&t.length===Object.keys(t).length}n(as,"isPlainArray");function ut(t){if(!cs(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!cs(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}n(ut,"isPlainObject");function cs(t){return Object.prototype.toString.call(t)==="[object Object]"}n(cs,"hasObjectPrototype");function hs(t){return new Promise(e=>{$.setTimeout(e,t)})}n(hs,"sleep");function we(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?dt(t,e):e}n(we,"replaceData");function Vr(t){return t}n(Vr,"keepPreviousData");function ds(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}n(ds,"addToEnd");function ls(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}n(ls,"addToStart");var he=Symbol();function _e(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===he?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}n(_e,"ensureQueryFn");function de(t,e){return typeof t=="function"?t(...e):!!t}n(de,"shouldThrowError");function fs(t,e,s){let r=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:n(()=>(i??=e(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i),"get")}),t}n(fs,"addConsumeAwareSignal");var z=(()=>{let t=n(()=>ht,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function Ce(){let t,e,s=new Promise((i,o)=>{t=i,e=o});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return n(r,"finalize"),s.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},s.reject=i=>{r({status:"rejected",reason:i}),e(i)},s}n(Ce,"pendingThenable");var ps=os;function Jr(){let t=[],e=0,s=n(c=>{c()},"notifyFn"),r=n(c=>{c()},"batchNotifyFn"),i=ps,o=n(c=>{e?t.push(c):i(()=>{s(c)})},"schedule"),a=n(()=>{let c=t;t=[],c.length&&i(()=>{r(()=>{c.forEach(u=>{s(u)})})})},"flush");return{batch:n(c=>{let u;e++;try{u=c()}finally{e--,e||a()}return u},"batch"),batchCalls:n(c=>(...u)=>{o(()=>{c(...u)})},"batchCalls"),schedule:o,setNotifyFunction:n(c=>{s=c},"setNotifyFunction"),setBatchNotifyFunction:n(c=>{r=c},"setBatchNotifyFunction"),setScheduler:n(c=>{i=c},"setScheduler")}}n(Jr,"createNotifyManager");var S=Jr();var Yr=class extends U{static{n(this,"OnlineManager")}#e=!0;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=n(()=>t(!0),"onlineListener"),s=n(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(s=>{s(t)}))}isOnline(){return this.#e}},le=new Yr;function Xr(t){return Math.min(1e3*2**t,3e4)}n(Xr,"defaultRetryDelay");function lt(t){return(t??"online")==="online"?le.isOnline():!0}n(lt,"canFetch");var Qe=class extends Error{static{n(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function De(t){let e=!1,s=0,r,i=Ce(),o=n(()=>i.status!=="pending","isResolved"),a=n(y=>{if(!o()){let v=new Qe(y);f(v),t.onCancel?.(v)}},"cancel"),c=n(()=>{e=!0},"cancelRetry"),u=n(()=>{e=!1},"continueRetry"),d=n(()=>ce.isFocused()&&(t.networkMode==="always"||le.isOnline())&&t.canRun(),"canContinue"),h=n(()=>lt(t.networkMode)&&t.canRun(),"canStart"),l=n(y=>{o()||(r?.(),i.resolve(y))},"resolve"),f=n(y=>{o()||(r?.(),i.reject(y))},"reject"),p=n(()=>new Promise(y=>{r=n(v=>{(o()||d())&&y(v)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,o()||t.onContinue?.()}),"pause"),m=n(()=>{if(o())return;let y,v=s===0?t.initialPromise:void 0;try{y=v??t.fn()}catch(w){y=Promise.reject(w)}Promise.resolve(y).then(l).catch(w=>{if(o())return;let k=t.retry??(z.isServer()?0:3),I=t.retryDelay??Xr,C=typeof I=="function"?I(s,w):I,x=k===!0||typeof k=="number"&&s<k||typeof k=="function"&&k(s,w);if(e||!x){f(w);return}s++,t.onFail?.(s,w),hs(C).then(()=>d()?void 0:p()).then(()=>{e?f(w):m()})})},"run");return{promise:i,status:n(()=>i.status,"status"),cancel:a,continue:n(()=>(r?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:h,start:n(()=>(h()?m():p().then(m),i),"start")}}n(De,"createRetryer");var Ue=class{static{n(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ve(this.gcTime)&&(this.#e=$.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(z.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&($.clearTimeout(this.#e),this.#e=void 0)}};function ys(t){return{onFetch:n((e,s)=>{let r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,o=e.state.data?.pages||[],a=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,d=n(async()=>{let h=!1,l=n(m=>{fs(m,()=>e.signal,()=>h=!0)},"addSignalProperty"),f=_e(e.options,e.fetchOptions),p=n(async(m,y,v)=>{if(h)return Promise.reject(e.signal.reason);if(y==null&&m.pages.length)return Promise.resolve(m);let k=n(()=>{let P={client:e.client,queryKey:e.queryKey,pageParam:y,direction:v?"backward":"forward",meta:e.options.meta};return l(P),P},"createQueryFnContext")(),I=await f(k),{maxPages:C}=e.options,x=v?ls:ds;return{pages:x(m.pages,I,C),pageParams:x(m.pageParams,y,C)}},"fetchPage");if(i&&o.length){let m=i==="backward",y=m?Zr:ms,v={pages:o,pageParams:a},w=y(r,v);c=await p(v,w,m)}else{let m=t??o.length;do{let y=u===0?a[0]??r.initialPageParam:ms(r,c);if(u>0&&y==null)break;c=await p(c,y),u++}while(u<m)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s):e.fetchFn=d},"onFetch")}}n(ys,"infiniteQueryBehavior");function ms(t,{pages:e,pageParams:s}){let r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,s[r],s):void 0}n(ms,"getNextPageParam");function Zr(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}n(Zr,"getPreviousPageParam");var vs=class extends Ue{static{n(this,"Query")}#e;#t;#s;#r;#n;#i;#a;#o;constructor(t){super(),this.#o=!1,this.#a=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#n=t.client,this.#r=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=gs(this.options),this.state=t.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#i?.promise}setOptions(t){if(this.options={...this.#a,...t},t?._type&&(this.#e=t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=gs(this.options);e.data!==void 0&&(this.setState(bs(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=we(this.state.data,t,this.options);return this.#c({data:s,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),s}setState(t){this.#c({type:"setState",state:t})}cancel(t){let e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(E).catch(E):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>M(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===he||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>q(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!Me(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#i&&(this.#o||this.#h()?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}#h(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#c({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#i?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(d=>d.options.queryFn);u&&this.setOptions(u.options)}let s=new AbortController,r=n(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:n(()=>(this.#o=!0,s.signal),"get")})},"addSignalProperty"),i=n(()=>{let u=_e(this.options,e),h=n(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(l),l},"createQueryFnContext")();return this.#o=!1,this.options.persister?this.options.persister(u,h,this):u(h)},"fetchFn"),a=n(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(u),u},"createFetchContext")();(this.#e==="infinite"?ys(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:"fetch",meta:a.fetchOptions?.meta}),this.#i=De({initialPromise:e?.initialPromise,fn:a.fetchFn,onCancel:n(u=>{u instanceof Qe&&u.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},"onCancel"),onFail:n((u,d)=>{this.#c({type:"failed",failureCount:u,error:d})},"onFail"),onPause:n(()=>{this.#c({type:"pause"})},"onPause"),onContinue:n(()=>{this.#c({type:"continue"})},"onContinue"),retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:n(()=>!0,"canRun")});try{let u=await this.#i.start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),this.#r.config.onSuccess?.(u,this),this.#r.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Qe){if(u.silent)return this.#i.promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw this.#c({type:"error",error:u}),this.#r.config.onError?.(u,this),this.#r.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=n(s=>{switch(t.type){case"failed":return{...s,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...ft(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...bs(t.data,t.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#s=t.manual?r:void 0,r;case"error":let i=t.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...t.state}}},"reducer");this.state=e(this.state),S.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:t})})}};function ft(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:lt(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}n(ft,"fetchState");function bs(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}n(bs,"successState");function gs(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,s=e!==void 0,r=s?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}n(gs,"getDefaultState");var mt=class extends U{static{n(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#o=null,this.#a=Ce(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#a;#o;#h;#c;#p;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ss(this.#t,this.options)?this.#f():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return pt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return pt(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#w(),this.#t.removeObserver(this)}setOptions(t){let e=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof M(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#C(),this.#t.setOptions(this.options),e._defaulted&&!ue(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&ws(this.#t,s,this.options,e)&&this.#f(),this.updateResult(),r&&(this.#t!==s||M(this.options.enabled,this.#t)!==M(e.enabled,this.#t)||q(this.options.staleTime,this.#t)!==q(e.staleTime,this.#t))&&this.#y();let i=this.#b();r&&(this.#t!==s||M(this.options.enabled,this.#t)!==M(e.enabled,this.#t)||i!==this.#u)&&this.#g(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return ti(this,s)&&(this.#r=s,this.#i=this.options,this.#n=this.#t.state),s}getCurrentResult(){return this.#r}trackResult(t,e){return new Proxy(t,{get:n((s,r)=>(this.trackProp(r),e?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#a.status==="pending"&&this.#a.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r)),"get")})}trackProp(t){this.#m.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let e=this.#e.defaultQueryOptions(t),s=this.#e.getQueryCache().build(this.#e,e);return s.fetch().then(()=>this.createResult(s,e))}fetch(t){return this.#f({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#f(t){this.#C();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(E)),e}#y(){this.#S();let t=q(this.options.staleTime,this.#t);if(z.isServer()||this.#r.isStale||!ve(t))return;let s=Me(this.#r.dataUpdatedAt,t)+1;this.#d=$.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#g(t){this.#w(),this.#u=t,!(z.isServer()||M(this.options.enabled,this.#t)===!1||!ve(this.#u)||this.#u===0)&&(this.#l=$.setInterval(()=>{(this.options.refetchIntervalInBackground||ce.isFocused())&&this.#f()},this.#u))}#v(){this.#y(),this.#g(this.#b())}#S(){this.#d!==void 0&&($.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&($.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let s=this.#t,r=this.options,i=this.#r,o=this.#n,a=this.#i,u=t!==s?t.state:this.#s,{state:d}=t,h={...d},l=!1,f;if(e._optimisticResults){let A=this.hasListeners(),K=!A&&Ss(t,e),Z=A&&ws(t,s,e,r);(K||Z)&&(h={...h,...ft(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:p,errorUpdatedAt:m,status:y}=h;f=h.data;let v=!1;if(e.placeholderData!==void 0&&f===void 0&&y==="pending"){let A;i?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(A=i.data,v=!0):A=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,A!==void 0&&(y="success",f=we(i?.data,A,e),l=!0)}if(e.select&&f!==void 0&&!v)if(i&&f===o?.data&&e.select===this.#h)f=this.#c;else try{this.#h=e.select,f=e.select(f),f=we(i?.data,f,e),this.#c=f,this.#o=null}catch(A){this.#o=A}this.#o&&(p=this.#o,f=this.#c,m=Date.now(),y="error");let w=h.fetchStatus==="fetching",k=y==="pending",I=y==="error",C=k&&w,x=f!==void 0,R={status:y,fetchStatus:h.fetchStatus,isPending:k,isSuccess:y==="success",isError:I,isInitialLoading:C,isLoading:C,data:f,dataUpdatedAt:h.dataUpdatedAt,error:p,errorUpdatedAt:m,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:w,isRefetching:w&&!k,isLoadingError:I&&!x,isPaused:h.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:I&&x,isStale:yt(t,e),refetch:this.refetch,promise:this.#a,isEnabled:M(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=R.data!==void 0,K=R.status==="error"&&!A,Z=n(Oe=>{K?Oe.reject(R.error):A&&Oe.resolve(R.data)},"finalizeThenableIfPossible"),Zt=n(()=>{let Oe=this.#a=R.promise=Ce();Z(Oe)},"recreateThenable"),Ie=this.#a;switch(Ie.status){case"pending":t.queryHash===s.queryHash&&Z(Ie);break;case"fulfilled":(K||R.data!==Ie.value)&&Zt();break;case"rejected":(!K||R.error!==Ie.reason)&&Zt();break}}return R}updateResult(){let t=this.#r,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#i=this.options,this.#n.data!==void 0&&(this.#p=this.#t),ue(e,t))return;this.#r=e;let s=n(()=>{if(!t)return!0;let{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#m.size)return!0;let o=new Set(i??this.#m);return this.options.throwOnError&&o.add("error"),Object.keys(this.#r).some(a=>{let c=a;return this.#r[c]!==t[c]&&o.has(c)})},"shouldNotifyListeners");this.#k({listeners:s()})}#C(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#s=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#k(t){S.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function ei(t,e){return M(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&M(e.retryOnMount,t)===!1)}n(ei,"shouldLoadOnMount");function Ss(t,e){return ei(t,e)||t.state.data!==void 0&&pt(t,e,e.refetchOnMount)}n(Ss,"shouldFetchOnMount");function pt(t,e,s){if(M(e.enabled,t)!==!1&&q(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&yt(t,e)}return!1}n(pt,"shouldFetchOn");function ws(t,e,s,r){return(t!==e||M(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&yt(t,s)}n(ws,"shouldFetchOptionally");function yt(t,e){return M(e.enabled,t)!==!1&&t.isStaleByTime(q(e.staleTime,t))}n(yt,"isStale");function ti(t,e){return!ue(t.getCurrentResult(),e)}n(ti,"shouldAssignObserverCurrentProperties");var Cs=class extends Ue{static{n(this,"Mutation")}#e;#t;#s;#r;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#s=t.mutationCache,this.#t=[],this.state=t.state||bt(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(t){let e=n(()=>{this.#n({type:"continue"})},"onContinue"),s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=De({fn:n(()=>this.options.mutationFn?this.options.mutationFn(t,s):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:n((o,a)=>{this.#n({type:"failed",failureCount:o,error:a})},"onFail"),onPause:n(()=>{this.#n({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:n(()=>this.#s.canRun(this),"canRun")});let r=this.state.status==="pending",i=!this.#r.canStart();try{if(r)e();else{this.#n({type:"pending",variables:t,isPaused:i}),this.#s.config.onMutate&&await this.#s.config.onMutate(t,this,s);let a=await this.options.onMutate?.(t,s);a!==this.state.context&&this.#n({type:"pending",context:a,variables:t,isPaused:i})}let o=await this.#r.start();return await this.#s.config.onSuccess?.(o,t,this.state.context,this,s),await this.options.onSuccess?.(o,t,this.state.context,s),await this.#s.config.onSettled?.(o,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(o,null,t,this.state.context,s),this.#n({type:"success",data:o}),o}catch(o){try{await this.#s.config.onError?.(o,t,this.state.context,this,s)}catch(a){Promise.reject(a)}try{await this.options.onError?.(o,t,this.state.context,s)}catch(a){Promise.reject(a)}try{await this.#s.config.onSettled?.(void 0,o,this.state.variables,this.state.context,this,s)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,o,t,this.state.context,s)}catch(a){Promise.reject(a)}throw this.#n({type:"error",error:o}),o}finally{this.#s.runNext(this)}}#n(t){let e=n(s=>{switch(t.type){case"failed":return{...s,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...s,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:t.error,failureCount:s.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),S.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(t)}),this.#s.notify({mutation:this,type:"updated",action:t})})}};function bt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}n(bt,"getDefaultState");var ks=class extends U{static{n(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(t,e,s){let r=new Cs({client:t,mutationCache:this,mutationId:++this.#s,options:t.defaultMutationOptions(e),state:s});return this.add(r),r}add(t){this.#e.add(t);let e=Ke(t);if(typeof e=="string"){let s=this.#t.get(e);s?s.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=Ke(t);if(typeof e=="string"){let s=this.#t.get(e);if(s)if(s.length>1){let r=s.indexOf(t);r!==-1&&s.splice(r,1)}else s[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=Ke(t);if(typeof e=="string"){let r=this.#t.get(e)?.find(i=>i.state.status==="pending");return!r||r===t}else return!0}runNext(t){let e=Ke(t);return typeof e=="string"?this.#t.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){S.batch(()=>{this.#e.forEach(t=>{this.notify({type:"removed",mutation:t})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(t){let e={exact:!0,...t};return this.getAll().find(s=>Le(e,s))}findAll(t={}){return this.getAll().filter(e=>Le(t,e))}notify(t){S.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return S.batch(()=>Promise.all(t.map(e=>e.continue().catch(E))))}};function Ke(t){return t.options.scope?.id}n(Ke,"scopeFor");var gt=class extends U{static{n(this,"MutationObserver")}#e;#t=void 0;#s;#r;constructor(t,e){super(),this.#e=t,this.setOptions(e),this.bindMethods(),this.#n()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(t){let e=this.options;this.options=this.#e.defaultMutationOptions(t),ue(this.options,e)||this.#e.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#s,observer:this}),e?.mutationKey&&this.options.mutationKey&&H(e.mutationKey)!==H(this.options.mutationKey)?this.reset():this.#s?.state.status==="pending"&&this.#s.setOptions(this.options)}onUnsubscribe(){this.hasListeners()||this.#s?.removeObserver(this)}onMutationUpdate(t){this.#n(),this.#i(t)}getCurrentResult(){return this.#t}reset(){this.#s?.removeObserver(this),this.#s=void 0,this.#n(),this.#i()}mutate(t,e){return this.#r=e,this.#s?.removeObserver(this),this.#s=this.#e.getMutationCache().build(this.#e,this.options),this.#s.addObserver(this),this.#s.execute(t)}#n(){let t=this.#s?.state??bt();this.#t={...t,isPending:t.status==="pending",isSuccess:t.status==="success",isError:t.status==="error",isIdle:t.status==="idle",mutate:this.mutate,reset:this.reset}}#i(t){S.batch(()=>{if(this.#r&&this.hasListeners()){let e=this.#t.variables,s=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(t?.type==="success"){try{this.#r.onSuccess?.(t.data,e,s,r)}catch(i){Promise.reject(i)}try{this.#r.onSettled?.(t.data,null,e,s,r)}catch(i){Promise.reject(i)}}else if(t?.type==="error"){try{this.#r.onError?.(t.error,e,s,r)}catch(i){Promise.reject(i)}try{this.#r.onSettled?.(void 0,t.error,e,s,r)}catch(i){Promise.reject(i)}}}this.listeners.forEach(e=>{e(this.#t)})})}};var Ts=class extends U{static{n(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,s){let r=e.queryKey,i=e.queryHash??Se(r,e),o=this.get(i);return o||(o=new vs({client:t,queryKey:r,queryHash:i,options:t.defaultQueryOptions(e),state:s,defaultOptions:t.getQueryDefaults(r)}),this.add(o)),o}add(t){this.#e.has(t.queryHash)||(this.#e.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let e=this.#e.get(t.queryHash);e&&(t.destroy(),e===t&&this.#e.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){S.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return this.#e.get(t)}getAll(){return[...this.#e.values()]}find(t){let e={exact:!0,...t};return this.getAll().find(s=>xe(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>xe(t,s)):e}notify(t){S.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){S.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){S.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var vt=class{static{n(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#a;#o;constructor(t={}){this.#e=t.queryCache||new Ts,this.#t=t.mutationCache||new ks,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#a=ce.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#o=le.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#a?.(),this.#a=void 0,this.#o?.(),this.#o=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),s=this.#e.build(this,e),r=s.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&s.isStaleByTime(q(e.staleTime,s))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:s})=>{let r=s.data;return[e,r]})}setQueryData(t,e,s){let r=this.defaultQueryOptions({queryKey:t}),o=this.#e.get(r.queryHash)?.state.data,a=us(e,o);if(a!==void 0)return this.#e.build(this,r).setData(a,{...s,manual:!0})}setQueriesData(t,e,s){return S.batch(()=>this.#e.findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,s)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;S.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){let s=this.#e;return S.batch(()=>(s.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let s={revert:!0,...e},r=S.batch(()=>this.#e.findAll(t).map(i=>i.cancel(s)));return Promise.all(r).then(E).catch(E)}invalidateQueries(t,e={}){return S.batch(()=>(this.#e.findAll(t).forEach(s=>{s.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let s={...e,cancelRefetch:e.cancelRefetch??!0},r=S.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let o=i.fetch(void 0,s);return s.throwOnError||(o=o.catch(E)),i.state.fetchStatus==="paused"?Promise.resolve():o}));return Promise.all(r).then(E)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let s=this.#e.build(this,e);return s.isStaleByTime(q(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(E).catch(E)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(E).catch(E)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return le.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#s}setDefaultOptions(t){this.#s=t}setQueryDefaults(t,e){this.#r.set(H(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{te(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set(H(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{te(t,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#s.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=Se(e.queryKey,e)),e.refetchOnReconnect===void 0&&(e.refetchOnReconnect=e.networkMode!=="always"),e.throwOnError===void 0&&(e.throwOnError=!!e.suspense),!e.networkMode&&e.persister&&(e.networkMode="offlineFirst"),e.queryFn===he&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#s.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var se=D(ee(),1);var ke=D(ee(),1),si=D(ot(),1);function ri(){let t=!1;return{clearReset:n(()=>{t=!1},"clearReset"),reset:n(()=>{t=!0},"reset"),isReset:n(()=>t,"isReset")}}n(ri,"createValue");var ii=ke.createContext(ri()),Es=n(()=>ke.useContext(ii),"useQueryErrorResetBoundary");var Is=D(ee(),1);var Os=n((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?de(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),Rs=n(t=>{Is.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),As=n(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||de(s,[t.error,r])),"getHasError");var Ne=D(ee(),1);var Fs=Ne.createContext(!1),Ps=n(()=>Ne.useContext(Fs),"useIsRestoring"),Sh=Fs.Provider;var Ms=n(t=>{if(t.suspense){let s=n(i=>i==="static"?i:Math.max(i??1e3,1e3),"clamp"),r=t.staleTime;t.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},"ensureSuspenseTimers"),xs=n((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),Ls=n((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),St=n((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function _s(t,e,s){let r=Ps(),i=Es(),o=ge(s),a=o.defaultQueryOptions(t);o.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let c=o.getQueryCache().get(a.queryHash),u=t.subscribed!==!1;a._optimisticResults=r?"isRestoring":u?"optimistic":void 0,Ms(a),Os(a,i,c),Rs(i);let d=!o.getQueryCache().get(a.queryHash),[h]=se.useState(()=>new e(o,a)),l=h.getOptimisticResult(a),f=!r&&u;if(se.useSyncExternalStore(se.useCallback(p=>{let m=f?h.subscribe(S.batchCalls(p)):E;return h.updateResult(),m},[h,f]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),se.useEffect(()=>{h.setOptions(a)},[a,h]),Ls(a,l))throw St(a,h,i);if(As({result:l,errorResetBoundary:i,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw l.error;return o.getDefaultOptions().queries?._experimental_afterQuery?.(a,l),a.experimental_prefetchInRender&&!z.isServer()&&xs(l,r)&&(d?St(a,h,i):c?.promise)?.catch(E).finally(()=>{h.updateResult()}),a.notifyOnChangeProps?l:h.trackResult(l)}n(_s,"useBaseQuery");function ni(t,e){return _s(t,mt,e)}n(ni,"useQuery");var J=D(ee(),1);function oi(t,e){let s=ge(e),[r]=J.useState(()=>new gt(s,t));J.useEffect(()=>{r.setOptions(t)},[r,t]);let i=J.useSyncExternalStore(J.useCallback(a=>r.subscribe(S.batchCalls(a)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),o=J.useCallback((a,c)=>{r.mutate(a,c).catch(E)},[r]);if(i.error&&de(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:o,mutateAsync:i.mutate}}n(oi,"useMutation");var Us=D(ts(),1);var L=D(ee(),1);var qe=n(t=>N(t),"o");var je=D(ot(),1);var Qs=n(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"Q"),Ct=class{static{n(this,"A")}constructor(e){this.client=e}client;entries=new Map;pushes=new Map;samples=new Map;identityWatched=new Set;listening=!1;hasConsumers(e){return this.entries.has(qe(e))}openSnapshotSample(e){let s=qe(e);return this.samples.set(s,(this.samples.get(s)??0)+1),{key:s,pushes:this.pushes.get(s)??0}}closeSnapshotSample(e){let s=(this.samples.get(e.key)??1)-1,r=(this.pushes.get(e.key)??0)===e.pushes;return s>0?(this.samples.set(e.key,s),r):(this.samples.delete(e.key),this.entries.has(e.key)||this.pushes.delete(e.key),r)}clearOnIdentityChange(e){this.listenForIdentityChange(),this.identityWatched.add(e)}stopClearingOnIdentityChange(e){this.identityWatched.delete(e)}subscribeIdentityEpoch=n(e=>(this.listenForIdentityChange(),this.client.onIdentityChange(e)),"subscribeIdentityEpoch");listenForIdentityChange(){this.listening||(this.listening=!0,this.client.onIdentityChange(()=>{for(let e of this.identityWatched)this.clearQueries(e)}))}clearQueries(e){let s=e.getQueryCache();for(let r of s.findAll({queryKey:["lunora"]}))Qs(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}attach(e,s,r,i,o,a={}){let c=qe(s),u=this.entries.get(c);if(!u){u={errorCallbacks:new Set,refCount:0,unsubscribe:void 0},this.entries.set(c,u);let l=u;try{u.unsubscribe=this.client.subscribe(r,i,f=>{if(this.pushes.set(c,(this.pushes.get(c)??0)+1),f===void 0){Qs(e.getQueryCache().find({exact:!0,queryKey:s}));return}e.setQueryData(s,f)},{onError:n(f=>{for(let p of l.errorCallbacks)p(f)},"onError"),shardKey:o})}catch(f){throw this.entries.delete(c),f}}u.refCount+=1;let{onError:d}=a;d&&u.errorCallbacks.add(d);let h=!1;return()=>{if(h)return;h=!0;let l=this.entries.get(c);l&&(l.refCount-=1,d&&l.errorCallbacks.delete(d),l.refCount<=0&&(l.unsubscribe?.(),this.entries.delete(c)))}}},Ds=new WeakMap,wt=n(t=>{let e=Ds.get(t);return e||(e=new Ct(t),Ds.set(t,e)),e},"I"),Ks=(0,L.createContext)(null),ai=(0,L.createContext)(!1),ci=n(()=>new vt({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"q"),ui=n(t=>{let e=(0,Us.c)(20),{children:s,client:r,queryClient:i}=t,o=(0,L.use)(be),a;e[0]!==o||e[1]!==i?(a=n(()=>i??o??ci(),"d"),e[0]=o,e[1]=i,e[2]=a):a=e[2];let[c]=(0,L.useState)(a),u=i??o??c,d,h;e[3]!==r||e[4]!==u?(d=n(()=>{wt(r).clearOnIdentityChange(u)},"u"),h=[r,u],e[3]=r,e[4]=u,e[5]=d,e[6]=h):(d=e[5],h=e[6]),(0,L.useEffect)(d,h);let l=(0,L.useRef)(r),f,p;e[7]!==r||e[8]!==u?(f=n(()=>{l.current!==r&&(wt(l.current).stopClearingOnIdentityChange(u),l.current=r,wt(r).clearQueries(u),u.invalidateQueries({queryKey:["lunora"]}))},"o"),p=[r,u],e[7]=r,e[8]=u,e[9]=f,e[10]=p):(f=e[9],p=e[10]),(0,L.useEffect)(f,p);let[m]=(0,L.useState)(r),y=r!==m,v;e[11]!==s||e[12]!==y?(v=(0,je.jsx)(ai,{value:y,children:s}),e[11]=s,e[12]=y,e[13]=v):v=e[13];let w;e[14]!==r||e[15]!==v?(w=(0,je.jsx)(Ks,{value:r,children:v}),e[14]=r,e[15]=v,e[16]=w):w=e[16];let k=w;if(o===u)return k;let I;return e[17]!==k||e[18]!==u?(I=(0,je.jsx)(ct,{client:u,children:k}),e[17]=k,e[18]=u,e[19]=I):I=e[19],I},"V");var kt=n(()=>{let t=(0,L.use)(Ks);if(!t)throw new b("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"_");var _=n(t=>new Promise((e,s)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{s(t.error??new Error("IndexedDB request failed"))})}),"c"),Be=n((t,e,s,r)=>{let i;return()=>i||(i=new Promise((o,a)=>{let c=t.open(e,s);c.addEventListener("upgradeneeded",()=>{r(c.result)}),c.addEventListener("success",()=>{o(c.result)}),c.addEventListener("error",()=>{a(c.error??new Error("IndexedDB open failed"))})}),i)},"E"),We=n((t,e)=>async(s,r)=>{let i=(await t()).transaction(e,s),o=await r(i.objectStore(e));return await new Promise((a,c)=>{i.addEventListener("complete",()=>{a()}),i.addEventListener("error",()=>{c(i.error??new Error("IndexedDB transaction failed"))}),i.addEventListener("abort",()=>{c(i.error??new Error("IndexedDB transaction aborted"))})}),o},"u");var oe=n((t,e,s)=>`${t}::${e}::${s??""}`,"T"),hi=500,di=n((t,e)=>{if(!Number.isInteger(t)||t<1)throw new b("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var li="lunora-query-cache",fi="query-cache",Ns="by_ts",pi=1,mi=n((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let s=t.databaseName??li,r=t.storeName??fi,i=di(t.maxEntries??hi,"createIndexedDbQueryCache"),o=Be(e,s,pi,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(Ns,"ts",{unique:!1})}),a=We(o,r),c=n(async u=>{let d=await _(u.count())-i;d<=0||await new Promise((h,l)=>{let f=u.index(Ns).openCursor();f.addEventListener("success",()=>{let p=f.result;if(!p||d<=0){h();return}p.delete(),d-=1,p.continue()}),f.addEventListener("error",()=>{l(f.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:n(async()=>{await a("readwrite",u=>_(u.clear()))},"clear"),load:n(async()=>a("readonly",u=>_(u.getAll())),"load"),put:n(async(u,d)=>{await a("readwrite",async h=>{await _(h.put({...d,key:u})),await c(h)})},"put"),remove:n(async u=>{await a("readwrite",d=>_(d.delete(u)))},"remove")}},"N"),qs=n(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return mi()}},"L");var js=n(()=>{let t=null;return{get:n(()=>t,"get"),set:n(e=>{t=e},"set")}},"r");var $e=class{static{n(this,"u")}values=new Map;subscribers=new Map;get(e){return this.values.has(e.key)?this.values.get(e.key):e.defaultValue}set(e,s){if(s===void 0){this.reset(e);return}this.values.set(e.key,s),this.notify(e.key,s)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}clear(){this.values.clear(),this.subscribers.clear()}subscribe(e,s){let r=this.subscribers.get(e.key);return r||(r=new Set,this.subscribers.set(e.key,r)),r.add(s),()=>{r.delete(s),r.size===0&&this.subscribers.delete(e.key)}}notify(e,s){let r=this.subscribers.get(e);if(r)for(let i of r)try{i(s)}catch{}}};var Bs=0,yi="lunora-bridge",bi=1e3,gi=3e3,He=class{static{n(this,"l")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(Bs+=1,this.tabId=`tab_${String(Bs)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??bi,this.leaderTimeout=e.leaderTimeout??gi,this.onBecomeLeader=e.onBecomeLeader,this.onStopBeingLeader=e.onStopBeingLeader,this.onConnectionStatus=e.onConnectionStatus,this.onSubscriptionData=e.onSubscriptionData,this.onLeaderClaimAnswered=e.onLeaderClaimAnswered,this.onSubscriptionError=e.onSubscriptionError,this.onSubscriptionSettled=e.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(e.channelName??yi),this.bc.addEventListener("message",s=>{this.handleMessage(s.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(e,s,r,i,o){this.leader&&this.broadcast({type:"subscription-data",tabId:this.tabId,key:e,data:s,...r===void 0?{}:{cursor:r},...i===void 0?{}:{epoch:i},...o===void 0?{}:{identity:o}})}broadcastSubscriptionError(e,s,r){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:s,...r===void 0?{}:{identity:r}})}broadcastSubscriptionSettled(e,s,r,i,o,a){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...s===void 0?{}:{cursor:s},...r===void 0?{}:{epoch:r},...i===void 0?{}:{lastMutationId:i},...o===void 0?{}:{clientId:o},...a===void 0?{}:{identity:a}})}broadcastConnectionStatus(e,s){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...s===void 0?{}:{identity:s}})}broadcast(e){this.bc?.postMessage(e)}handleMessage(e){switch(e.type){case"claim-leadership":{this.handleClaimLeadership(e);break}case"connection-status":{if(this.leader||e.tabId===this.tabId)break;this.onConnectionStatus?.(e.status,e.identity);break}case"heartbeat":{this.handleHeartbeat(e);break}case"subscription-data":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionData?.(e.key,e.data,e.cursor,e.epoch,e.identity);break}case"subscription-error":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionError?.(e.key,e.error,e.identity);break}case"subscription-settled":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionSettled?.(e.key,e.cursor,e.epoch,e.lastMutationId,e.clientId,e.identity);break}case"yield-leadership":{this.knownLeader===e.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(e){if(e.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&e.tabId<this.tabId&&(this.knownLeader=e.tabId,this.lastHeartbeat=e.ts)}}handleHeartbeat(e){if(e.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(e);return}this.lastHeartbeat=e.ts,this.knownLeader=e.tabId}}resolveLeaderVsLeaderTieBreak(e){e.tabId<this.tabId?(this.leader=!1,this.knownLeader=e.tabId,this.lastHeartbeat=e.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!(!this.running||this.leader)){if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}};var vi=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"y"),Tt="_id",Et="_creationTime",It="page",Ws="pageDelta",Si=n(t=>{if(Array.isArray(t))return t;if(vi(t)&&Array.isArray(t[It]))return t[It]},"g"),wi=n(t=>{let e;for(let s of t){let r=s[Et];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"A"),Ci=n((t,e)=>{let s=e[Et];if(typeof s!="number")return t.length;let r=wi(t);for(let[i,o]of t.entries()){let a=o[Et];if(typeof a=="number"&&(r?a<s:a>s))return i}return t.length},"x"),ki=n(t=>{if(typeof t!="object"||t===null)return;let e=t[Tt];return typeof e=="string"?e:void 0},"b"),Ti=n(t=>{if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.key=="string"&&typeof e.table=="string"&&(e.op==="insert"||e.op==="update"||e.op==="delete")},"D"),Ei=n((t,e)=>{let s=[];for(let u of t){if(ki(u)===void 0)return;s.push(u)}let{key:r,op:i,row:o}=e;if(i==="delete"){let u=s.filter(d=>d[Tt]!==r);return u.length===s.length?[...s]:u}if(o===void 0)return;let a=[...s],c=s.findIndex(u=>u[Tt]===r);return c===-1?a.splice(Ci(s,o),0,o):a[c]=o,a},"E"),Ii=n((t,e)=>{let s=Si(t);if(s===void 0)return;let r=Ei(s,e);return r===void 0||Array.isArray(t)?r:{...t,[It]:r}},"I"),Ot=Symbol("lunora.unmergeableDelta"),$s=n((t,e)=>{if("data"in t&&t.data!==void 0)return T(t.data);let s=T(t.delta);return Ti(s)?e===void 0?s:Ii(e,s)??Ot:s},"P");var bd=new Set(Object.keys(es)),G=class extends b{static{n(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var ze=n(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),Rt=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),Ge=n(t=>Rt.has(t?.code??""),"u");var Te=n((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,o=0;return{next(){let a=Math.min(r,s*2**o);if(o+=1,!i)return a;let c=a/2;return Math.floor(c+e()*(a-c))},reset(){o=0}}},"s");var Oi=1024,Ve=n(t=>{let e=t.maxBuffer??Oi,s=[],r=[],i=!1,o,a=!1,c=n(()=>{let h=r.shift();if(!h)return!1;if(o)return h.reject(o),!0;if(s.length>0){let l=s.shift();return h.resolve({done:!1,value:l}),!0}return i?(h.resolve({done:!0,value:void 0}),!0):(r.unshift(h),!1)},"u"),u={complete(){if(!(i||o))for(i=!0;c(););},fail(h){if(!(i||o)){for(o=h,s.length=0;c(););t.onFail?.()}},push(h){if(!(i||o||a)){if(s.length>=e){u.fail(new b("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}s.push(h),c()}}},d=n(()=>{if(!a){a=!0,i=!0,s.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:d,[Symbol.asyncIterator](){return{next(){if(o)return Promise.reject(o);if(s.length>0){let h=s.shift();return Promise.resolve({done:!1,value:h})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((h,l)=>{r.push({reject:l,resolve:h})})},return(){return d(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var Je=/^ /u,Ri=/^\d+$/u,Ai=2147483647,Fi=10,Pi=1e3,Hs=n(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"R"),Mi=n(t=>{let e="",s,r,i=[];for(let o of t.split(`
|
|
2
|
-
`))if(o.startsWith("event:"))e=o.slice(6).replace(Je,"");else if(o.startsWith("data:"))i.push(o.slice(5).replace(Je,""));else if(o.startsWith("id:")){let a=o.slice(3).replace(Je,"");a.includes("\0")||(s=a)}else if(o.startsWith("retry:")){let a=o.slice(6).replace(Je,"");Ri.test(a)&&Number.isSafeInteger(Number(a))&&(r=Math.min(Number(a),Ai))}return{data:i.join(`
|
|
3
|
-
`),event:e,id:s,retry:r}},"x"),xi=n((t,e,s)=>{let r=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),d=r[u];if(d===void 0)throw new b("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(Hs(d))}).join("/"),o=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&o.set(c,Hs(u));let a=o.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${a===""?"":`?${a}`}`},"B"),Li=n((t,e)=>{if(t.event==="complete")return e.complete(),!0;if(t.event==="error"){let s={};try{s=JSON.parse(t.data)}catch{}let r=typeof s.message=="string"?s.message:"stream error",i=typeof s.code=="string"?s.code:"HTTP_STREAM_ERROR",o=new b(i,r);return typeof s.why=="string"&&(o.why=s.why),e.fail(o),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(T(JSON.parse(t.data)))}catch{return e.fail(new b("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"k"),_i=n(async(t,e,s)=>{let r=t.getReader(),i=new TextDecoder,o="",a=!1,c=n(h=>{let l=a?`\r${h}`:h;a=l.endsWith("\r"),a&&(l=l.slice(0,-1)),o+=l.replaceAll(`\r
|
|
4
|
-
`,`
|
|
5
|
-
`)},"h"),u=n(()=>{let h=o.indexOf(`
|
|
6
|
-
|
|
7
|
-
`);for(;h!==-1;){let l=Mi(o.slice(0,h));if(o=o.slice(h+2),s.onFrame?.(),l.id!==void 0&&s.onId?.(l.id),l.retry!==void 0&&s.onRetry?.(l.retry),Li(l,e))return!0;h=o.indexOf(`
|
|
8
|
-
|
|
9
|
-
`)}return!1},"c"),d=n(()=>r.cancel().then(()=>{},()=>{}),"f");try{for(;;){let{done:h,value:l}=await r.read();if(h)break;if(c(i.decode(l,{stream:!0})),u())return await d(),!0}return c(i.decode()),u()}catch(h){throw await d(),h}},"F"),Qi=n(async(t,e)=>{e.aborted||await new Promise(s=>{let r,i=n(()=>{clearTimeout(r),s()},"o");r=setTimeout(()=>{e.removeEventListener("abort",i),s()},t),e.addEventListener("abort",i,{once:!0})})},"W"),Di=n((t,e)=>{if(typeof t!="object"||t===null)return;let{code:s,error:r,why:i}=t;if(!(typeof s!="string"||typeof r!="string"))return new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${e.toString()}, ${s}): ${r}`,{status:e,why:typeof i=="string"?i:void 0})},"j"),Ui=n(async(t,e)=>{let s,r=new Promise(o=>{s=setTimeout(()=>{o(void 0)},Pi)}),i=t.json().catch(o=>{if(e.aborted)throw o});try{return await Promise.race([i,r])}finally{clearTimeout(s),await t.body?.cancel().catch(()=>{})}},"D"),Ki=n((t,e)=>{let s=Object.entries(t??{}).filter(([r])=>e===void 0||r.toLowerCase()!=="last-event-id");return{accept:"text/event-stream",...Object.fromEntries(s),...e===void 0?{}:{"last-event-id":e}}},"U"),zs=n(t=>t instanceof Error&&"code"in t?t:new b("HTTP_STREAM_TRANSPORT",t instanceof Error?t.message:String(t),{cause:t}),"_"),Gs=n((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new b("INTERNAL","httpStream: no `fetch` implementation available");let i=xi(t,e??{},s.baseUrl??""),o=new AbortController,a;s.signal&&(s.signal.aborted?o.abort():(a=n(()=>{o.abort()},"s"),s.signal.addEventListener("abort",a,{once:!0})));let c=n(()=>{a&&s.signal?.removeEventListener("abort",a)},"h"),{handle:u,iterable:d}=Ve({maxBuffer:s.maxBuffer,onCancel:n(()=>{o.abort()},"onCancel"),onFail:n(()=>{o.abort()},"onFail")}),h=s.reconnect??!1,l=Te(),{lastEventId:f}=s,p,m=0,y=n(()=>{l.reset(),m=0},"g"),v={},w=n(C=>{try{C()}catch(x){throw v.value={error:x},x}},"b"),k={onFrame:y,onId:n(C=>{w(()=>s.onEventId?.(C)),f=C},"onId"),onRetry:n(C=>{w(()=>s.onRetry?.(C)),p=C},"onRetry")},I=n(async()=>{let C=Ki(s.headers,f),x=new b("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame");try{let P=await r(i,{headers:C,method:t.method,signal:o.signal});if(!P.ok){let R=await Ui(P,o.signal);u.fail(Di(R,P.status)??new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${P.status.toString()})`,{status:P.status}));return}if(!P.body){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}return{completed:await _i(P.body,u,k),error:x}}catch(P){if(o.signal.aborted){u.complete();return}if(v.value){let{error:R}=v.value;u.fail(R instanceof Error?R:new b("HTTP_STREAM_CALLBACK","httpStream: an onEventId/onRetry callback threw"));return}return{completed:!1,error:zs(P)}}},"P");return(async()=>{try{for(;;){if(o.signal.aborted){u.complete();return}let C=await I();if(!C)return;if(C.completed||!h||m>=Fi){C.completed||u.fail(C.error);return}m+=1,await Qi(p??l.next(),o.signal)}}finally{c()}})().catch(C=>{if(o.signal.aborted){u.complete();return}u.fail(zs(C))}),d},"X");var Ye=n(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"a"),At=n(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"h"),j=n((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"$"),F=n((t,e)=>{let s=new URLSearchParams;for(let[i,o]of Object.entries(e))o!==void 0&&o!==""&&s.set(i,String(o));let r=s.toString();return r===""?t:`${t}?${r}`},"d"),Ni="http://same-origin.invalid",Ft=n(t=>new URL(t,Ni),"p"),qi=/^[a-z][a-z\d+.-]*:/iu,Pt=n((t,e)=>{if(qi.test(e))return t.toString();let s=`${t.pathname}${t.search}${t.hash}`;return e.startsWith("//")?`//${t.host}${s}`:s},"S");var Q=class t{static{n(this,"t")}static key(e,s,r){return`${e}::${N(s)}::${r??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){let s=t.keyOf(e);this.byKey.get(s)===e&&this.byKey.delete(s),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}};function Xe(t){if(t!==void 0)return e=>{t(e)}}n(Xe,"b");var Y=n((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var Mt=0,Vs=n(()=>Mt,"h"),ji=n((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),Js=n((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),re=n((t,e)=>{Js(t,ji(e,t.optimisticLayers))},"y"),xt=n((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),Js(t,s);let o=n(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),a=n(()=>{re(t,t.serverBase)},"s");return{confirm:n(c=>{if(c===void 0){o();return}r.commitCursor=c,Mt+=1,r.acknowledgedAt=Mt,t.serverCursor!==void 0&&t.serverCursor>=c&&o()&&a()},"confirm"),rollback:n(()=>{i||(i=!0,o(),a())},"rollback")}},"g"),Ze=n((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let s=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(r=>r.commitCursor===void 0||r.commitCursor>e),t.optimisticLayers.length!==s},"k"),Ys=n((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),fe=n(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),Xs=n((t,e)=>{let s=[],r=[],i=n((o,a)=>t.get(Q.key(o,a,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:n(o=>{let a=[];for(let c of t.all())c.fn.__lunoraRef===o.__lunoraRef&&(c.shardKey??"")===(e??"")&&a.push({args:c.args,value:c.lastValue});return a},"getAllQueries"),getQuery:n((o,a)=>i(o.__lunoraRef,a??{})?.lastValue,"getQuery"),setQuery:n((o,a,c)=>{let u=i(o.__lunoraRef,a??{});if(!u)return;let d=xt(u,()=>c);d&&(s.push(d.confirm),r.push(d.rollback))},"setQuery")}}},"_");var Lt=n(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let s=Date.parse(t);if(Number.isNaN(s))return;let r=s-Date.now();return r>0?r:void 0},"u"),Bi=n((t,e)=>{let s=Lt(e);if(!(s===void 0||ze(t)!==void 0))return t.data===void 0?{retryAfterMs:s}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:s}:void 0},"v"),Zs=n(t=>t.why===void 0?{}:{why:t.why},"m"),pe=n(t=>{let e=t?.error;if(typeof e!="object"||e===null||Array.isArray(e))return;let{why:s,...r}=e;return typeof s=="string"?{...r,why:s}:r},"y"),Wi=n(()=>new G("LunoraClient: batch slot carried no error envelope"),"l"),er=n((t,e)=>{let s=t.error,r=typeof s?.code=="string"?s.code:void 0,i=typeof s?.message=="string"?s.message:void 0;return{code:r,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"n"),tr=n(t=>{let{code:e,messageText:s}=er(t,"stream error"),r=t.error?.why,i=e===void 0?new Error(s):new b(e,s);return typeof r=="string"&&(i.why=r),i},"g"),_t=n(t=>{let{code:e,messageText:s}=er(t,"subscription error"),r=t.error?.why;return{message:s,...e===void 0?{}:{code:e},...typeof r=="string"?{why:r}:{}}},"E"),et=n(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,t.data!==void 0)try{e.data=T(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),typeof t.why=="string"&&(e.why=t.why),e},"i"),Qt=n((t,e)=>{let s=et(t),r=Bi(s,e);return r!==void 0&&(s.data=r),s},"b"),tt=n(t=>{let e=pe(t);return e===void 0?Wi():et(e)},"A");var sr=0,$i=n(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();sr+=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)}_${sr.toString(36)}_${t}`},"d"),Dt=n((t,e)=>t!==void 0&&e!==t,"f"),rt=$i,ie=n((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"o"),st=class{static{n(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??=rt(),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=>{ie(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 ie(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(Dt(this.version,a.version)){this.persistence.remove(a.id).catch(c=>{ie(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:n(()=>{},"reject"),resolve:n(()=>{},"resolve"),shardKey:a.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),o=new Set;for(let a of s)i.has(a)&&o.add(a.shardKey);return[...o]}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 o={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,o).catch(a=>{ie(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){ie(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=>{ie(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 Hi="lunora-outbox",zi="offline-mutations",Ut="by_id",Gi=n((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new b("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??Hi,r=t.storeName??zi,i=Be(e,s,1,a=>{a.objectStoreNames.contains(r)||a.createObjectStore(r,{autoIncrement:!0}).createIndex(Ut,"id",{unique:!0})}),o=We(i,r);return{append:n(async a=>{await o("readwrite",c=>_(c.add(a)))},"append"),clear:n(async()=>{await o("readwrite",a=>_(a.clear()))},"clear"),load:n(async()=>o("readonly",a=>_(a.getAll())),"load"),remove:n(async a=>{await o("readwrite",async c=>{let u=await _(c.index(Ut).getKey(a));u!==void 0&&await _(c.delete(u))})},"remove"),replace:n(async a=>{await o("readwrite",async c=>{let u=await _(c.index(Ut).getKey(a.id));u!==void 0&&await _(c.put(a,u))})},"replace")}},"w"),rr=n((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return Gi()}},"b");var ir=n((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),o=i.present?N(i.value):void 0;return()=>{let a=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!a.present?!0:N(a.value)===o}},"c");var Kt=500,lr=n((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"Ce"),X="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",Vi=n(t=>{let e="",s=0,r=t.length-2;for(;s<r;s+=3){let o=t[s]<<16|t[s+1]<<8|t[s+2];e+=X.charAt(o>>18&63)+X.charAt(o>>12&63)+X.charAt(o>>6&63)+X.charAt(o&63)}let i=t.length-s;if(i===1){let o=t[s]<<16;e+=X.charAt(o>>18&63)+X.charAt(o>>12&63)}else if(i===2){let o=t[s]<<16|t[s+1]<<8;e+=X.charAt(o>>18&63)+X.charAt(o>>12&63)+X.charAt(o>>6&63)}return e},"ot");new TextDecoder;var Ji=new TextEncoder,Yi=n(t=>Vi(Ji.encode(JSON.stringify(t))),"ct"),Xi="x-lunora-expect-subject",Zi=n(t=>Yi({subject:t}),"ht"),nr=Symbol.for("lunora:session-change"),en="lunora:session-change",tn="better-auth.message",sn="signout",fr=n(()=>{let t=globalThis,e=t[nr];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[nr]=e),e},"we"),rn=n(()=>"document"in globalThis,"pt"),nn=n(async()=>{let t=[];for(let e of fr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"mt"),on=n((t,e)=>{if(t!==tn||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===sn}catch{return!1}},"yt"),an=n(t=>{let e=[],s=n(()=>{nn().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(en):void 0}catch{r=void 0}if(r!==void 0){let o=r;o.addEventListener("message",a=>{a.data?.type==="lunora:session-change"&&a.data.tab!==t&&s()}),e.push(()=>{o.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let o=n(a=>{on(a.key,a.newValue)&&s()},"n");i.addEventListener("storage",o),e.push(()=>{i.removeEventListener?.("storage",o)})}return()=>{for(let o of e)o()}},"St"),cn=n(t=>{let e=fr();return e.listeners.add(t),e.detach===void 0&&rn()&&(e.detach=an(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"bt"),un="/_lunora/rpc",Nt="/_lunora/rpc-batch",qt="/_lunora/ws",hn="/_lunora/admin/shard-traffic",dn="/_lunora/admin/scheduled",ln="/_lunora/admin/scheduled/status",fn="/_lunora/admin/scheduled/ws",pn="/_lunora/admin/scheduled/cancel",or="/_lunora/admin/scheduled/dead",mn="/_lunora/admin/scheduled/dead/retry",yn="/_lunora/admin/scheduled/dead/cancel",bn="/_lunora/admin/workflows/instances",gn="/_lunora/admin/workflows/instance",vn="/_lunora/admin/workflows/status",Jt="/_lunora/admin/storage",Sn="/_lunora/admin/storage/url",wn="/_lunora/admin/storage/buckets",Cn="/_lunora/admin/functions",kn="/_lunora/admin/cron-jobs",Tn="/_lunora/admin/cron-jobs/run",En="/_lunora/admin/architecture",In="/_lunora/admin/openapi",On="/_lunora/admin/openrpc",Rn="/_lunora/admin/global/tables",An="/_lunora/admin/global/table",Fn="/_lunora/admin/global/facet",Pn="/_lunora/admin/vector/indexes",Mn="/_lunora/admin/vector/query",xn="/_lunora/admin/logs/archive",Ln="/_lunora/admin/kv/namespaces",_n="/_lunora/admin/kv/keys",Yt="/_lunora/admin/kv/value",Qn="/_lunora/admin/auth/users",Dn="/_lunora/admin/auth/sessions",Un="/_lunora/admin/auth/users/create",Kn="/_lunora/admin/auth/users/role",Nn="/_lunora/admin/auth/users/ban",qn="/_lunora/admin/auth/users/unban",jn="/_lunora/admin/auth/users/password",Bn="/_lunora/admin/auth/users/remove",Wn="/_lunora/admin/auth/users/impersonate",$n="/_lunora/admin/auth/sessions/revoke",Hn="/_lunora/admin/auth/sessions/revoke-all",zn="/_lunora/admin/auth/capabilities",Gn="/_lunora/admin/auth/users/update",Vn="/_lunora/admin/auth/accounts",Jn="/_lunora/admin/auth/accounts/unlink",Yn="/_lunora/admin/auth/passkeys",Xn="/_lunora/admin/auth/passkeys/delete",Zn="/_lunora/admin/auth/two-factor/disable",eo="/_lunora/admin/auth/organizations",to="/_lunora/admin/auth/organizations/members",so="/_lunora/admin/auth/organizations/invitations",ro="/_lunora/admin/auth/organizations/members/remove",io="/_lunora/admin/auth/organizations/invitations/cancel",no="/_lunora/admin/auth/config",oo="/_lunora/admin/auth/sign-up-invitations",ao="/_lunora/admin/auth/sign-up-invitations/create",co="/_lunora/admin/auth/sign-up-invitations/revoke",uo="/_lunora/admin/auth/organizations/create",ho="/_lunora/admin/auth/organizations/update",lo="/_lunora/admin/auth/organizations/remove",fo="/_lunora/admin/auth/organizations/members/add",po="/_lunora/admin/auth/organizations/members/invite",mo="/_lunora/admin/auth/organizations/members/role",yo="/_lunora/admin/auth/organizations/teams",bo="/_lunora/admin/auth/organizations/teams/create",go="/_lunora/admin/auth/organizations/teams/update",vo="/_lunora/admin/auth/organizations/teams/remove",So="/_lunora/admin/auth/organizations/teams/members",wo="/_lunora/admin/auth/organizations/teams/members/add",Co="/_lunora/admin/auth/organizations/teams/members/remove",ko="/_lunora/admin/auth/organizations/roles",To="/_lunora/admin/auth/organizations/roles/create",Eo="/_lunora/admin/auth/organizations/roles/update",Io="/_lunora/admin/auth/organizations/roles/remove",Oo="/api/auth",Ro="/get-session",Ao="lunora-ping",Fo=n(async t=>(t.assertOpen(),(await t.adminFetch(Cn,"GET")).functions??[]),"Bs"),Po=n(async t=>(t.assertOpen(),(await t.adminFetch(kn,"GET")).jobs??[]),"Ds"),Mo=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Tn,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"Qs"),xo=n(async t=>(t.assertOpen(),await t.adminFetch(In,"GET")),"Ws"),Lo=n(async t=>(t.assertOpen(),await t.adminFetch(En,"GET")),"qs"),_o=n(async t=>(t.assertOpen(),await t.adminFetch(On,"GET")),"Ks"),Qo=n(async t=>(t.assertOpen(),await t.adminFetch(Rn,"GET")),"js"),Do=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(W(e.filters))),T(await t.adminFetch(`${An}?${s.toString()}`,"GET"))},"Gs"),Uo=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(W(e.filters))),T(await t.adminFetch(`${Fn}?${s.toString()}`,"GET"))},"$s"),Ko=n(async t=>(t.assertOpen(),(await t.adminFetch(Ln,"GET")).namespaces??[]),"Vs"),No=n(async(t,e)=>{t.assertOpen();let s=F(_n,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"zs"),qo=n(async(t,e)=>{t.assertOpen();let s=F(Yt,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"Js"),jo=n(async(t,e)=>{t.assertOpen(),await t.adminFetch(Yt,"PUT",e)},"Ys"),Bo=n(async(t,e)=>{t.assertOpen();let s=F(Yt,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"Xs"),Wo=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(hn,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"Zs"),$o=n(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(xn,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"er"),Ho=n(async t=>{let e=[],s;for(;;){let r=await t(s);if(e.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return e;if(r.cursor===s)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");s=r.cursor}},"tr"),Xt=n(t=>"args"in t?{...t,args:T(t.args)}:t,"oe"),zo=n(async t=>(t.assertOpen(),((await t.adminFetch(dn,"GET")).records??[]).map(e=>Xt(e))),"sr"),Go=n(async t=>{t.assertOpen();let e=await t.adminFetch(ln,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"rr"),Vo=n(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(pn,"POST",{id:e})).cancelled===!0}),"ir"),Jo=n(async t=>(t.assertOpen(),(await Ho(async e=>await t.adminFetch(e===void 0?or:`${or}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>Xt(e))),"nr"),Yo=n(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(mn,"POST",{id:e})).retried===!0}),"or"),Xo=n(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(yn,"POST",{id:e})).removed===!0}),"ar"),Zo=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({name:e.name});e.status!==void 0&&s.set("status",e.status),e.page!==void 0&&s.set("page",String(e.page)),e.perPage!==void 0&&s.set("perPage",String(e.perPage));let r=await t.adminFetch(`${bn}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"cr"),ea=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${gn}?${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??[]}},"dr"),ta=n(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(vn,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"hr"),sa=n(async(t,e={})=>{t.assertOpen();let s=F(Jt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await t.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}},"ur"),ra=n(async(t,e,s)=>{t.assertOpen();let r=`${Jt}?key=${encodeURIComponent(e)}${Ye(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"lr"),ia=n(async t=>(t.assertOpen(),(await t.adminFetch(wn,"GET")).buckets??[]),"fr"),na=n(async(t,e)=>{t.assertOpen();let s=`${Jt}?key=${encodeURIComponent(e.key)}${Ye(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"pr"),oa=n(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,o=`${Sn}?key=${encodeURIComponent(e)}${i}${Ye(s?.bucket)}`,a=await t.adminFetch(o,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url},"mr"),aa=n(async t=>(t.assertOpen(),(await t.adminFetch(Pn,"GET")).indexes??[]),"yr"),ca=n(async(t,e)=>(t.assertOpen(),(await t.adminFetch(Mn,"POST",e)).matches??[]),"Sr"),V=n((t,e)=>{try{return W(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)}},"C"),ar=n(t=>{try{return W(t),!0}catch{return!1}},"be"),pr=n(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Ee"),ua=n((t,e)=>{let s=Array.from({length:e});for(let r of t){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;if(!pr(r.body)){s[r.id]={error:tt({}),ok:!1};continue}let i=r.body;s[r.id]="error"in i?{error:tt(i),ok:!1}:{ok:!0,value:T(i.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"br"),jt=n((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"z"),ha=3e4,da=1e4,la=5e3,fa=3,pa=250,cr=5e3,ma=5e3,ya=64,ba=3,ga=1e4,va=8,Bt=n(t=>t==="connected"||t==="polling","J"),g=n(t=>t??"","l"),B=n((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"v"),Sa=n(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)B(t,s)},"Or"),wa=new TextDecoder,Ca=n(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return wa.decode(t)},"Pr"),ne=class{static{n(this,"R")}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()}},me=n(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"F"),ka=n((t,e,s)=>{me(t),!(e<=0)&&(t.heartbeatTimer=setInterval(()=>{if(!t.socket)return;let{socket:r}=t;if(Date.now()-t.lastFrameAt>e*2.5){try{r.close()}catch{}s();return}try{r.send(Ao)}catch{}},e))},"Fr"),ur=n((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:o,heartbeatIntervalMs:a}=s;if(i===void 0)throw new b("INTERNAL","no WebSocket implementation available");let c=new i(e);t.socket=c;let u=n(()=>{me(t),t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.socket===c&&(t.socket=void 0)},"c"),d=n(h=>{u(),r.onClose(h)},"d");o>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}d()}},o)),c.addEventListener("open",()=>{if(t.socket===c){t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now();try{r.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}t.socket===c&&ka(t,a,d)}}),c.addEventListener("message",h=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(h)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),c.addEventListener("close",h=>{t.socket===c&&d(h)}),c.addEventListener("error",()=>{t.socket===c&&d()})},"ve"),Ta=n(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:o}=t,a=s>0&&e>0,c=0,u,d=!1,h=!1,l=n(()=>{u!==void 0&&(clearInterval(u),u=void 0,d=!1,i())},"u"),f=n(m=>{if(u!==void 0){if(!m){l();return}d||(d=!0,i()),r()}},"m"),p=n(()=>{h||(h=!0,o().then(f).finally(()=>{h=!1}).catch(()=>{}))},"f");return{isPolling:n(()=>u!==void 0&&d,"isPolling"),noteFailedOpen:n(()=>{c+=1,!(!a||u!==void 0||c<e)&&(u=setInterval(p,s),i(),p())},"noteFailedOpen"),noteOpen:n(()=>{c=0,l()},"noteOpen"),stop:l}},"Lr"),Ea=1e4,hr=n(async t=>{let e=new AbortController,s,r=new Promise((i,o)=>{s=setTimeout(()=>{e.abort(),o(new TypeError("LunoraClient: poll timed out"))},Ea)});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)}},"Te"),mr=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Ia=n(t=>{if(t instanceof G)return!0;let e=t?.code;return e===void 0||mr.has(e)||Rt.has(e)},"Hr"),yr=6e4,Oa=1e3,Ra={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Ee=n((t,e,s)=>{let r=Lt(s),i=r===void 0?void 0:{retryAfterMs:r},o=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new G(o,i):new b(Ra[t]??"BAD_REQUEST",o,{data:i})},"H"),$t=n((t,e=Math.random)=>{let s=Math.min(Oa*2**Math.max(t-1,0),yr);return Math.round(s*(.5+e()*.5))},"ee"),Aa=n(t=>t instanceof G||mr.has(t?.code??""),"xr"),Fa=n((t,e,s)=>{let r=ze(t);return r!==void 0&&r>0?Math.min(r,yr):Aa(t)?$t(e,s):void 0},"Br"),Pa=983040,Ma=n(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Qr"),br=new WeakSet,gr=n(t=>{let e=new b("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) \u2014 ${t instanceof Error?t.message:String(t)}`,{cause:t});return br.add(e),e},"Oe"),it=n(t=>t instanceof Error&&br.has(t),"B"),xa=n(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&pr(s.body)&&e.set(s.id,s.body);return e},"Wr"),La=n(t=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:tt(t),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:T(t.result)}}catch(e){return{commitCursor:t.commitCursor,error:gr(e),kind:"undecodable"}}},"qr"),Wt=n((t,e)=>`${g(t)}\0${e}`,"Y"),_a=n((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"Kr"),Ht=class{static{n(this,"jr")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){lr(this.buffers,this.maxBuffers),this.buffers.set(Wt(e,s.pokeId),{baseCheckpoint:s.baseCheckpoint,bases:new Map,epoch:s.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}part(e,s){let r=this.buffers.get(Wt(e,s.pokeId));if(!r)return;let i=[];try{for(let c of s.rowsPatch)i.push(c.value===void 0?c:{...c,value:T(c.value)})}catch(c){r.undecodable.set(s.shapeId,c);return}let o=r.parts.get(s.shapeId)??[];for(let c of i)o.push(c);r.parts.set(s.shapeId,o),s.lastMutationId!==void 0&&r.lastMutationId.set(s.shapeId,s.lastMutationId);let a=s.baseCheckpoint??r.baseCheckpoint;a!==void 0&&r.bases.set(s.shapeId,a),s.reset===!0&&r.resets.add(s.shapeId)}end(e,s){let r=Wt(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},Qa=n((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),o=e.bases.get(t.id),a=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=o!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==o;if(!i&&(a||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,"reseed";i&&t.rows.clear(),_a(t.rows,r),s.checkpoint!==void 0&&(t.serverCursor=s.checkpoint),s.epoch!==void 0&&(t.serverEpoch=s.epoch);let u=e.lastMutationId.get(t.id);return u!==void 0&&(t.lastMutationId=u),"applied"},"Gr"),dr=n(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"ke"),Da=n((t,e)=>{for(let[s,r]of e.undecodable){let i=t.get(s);i&&Y(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${r instanceof Error?r.message:String(r)}`})}},"$r"),zt=n((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"te"),Gt=n((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"se"),vr=n((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Re"),nt=n((t,e)=>t!==void 0&&t!==e,"D"),Ua=n((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","Vr"),Ka=n(t=>{for(let e of t.activeSubscriptions())t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"zr"),Na=n(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1},"Jr"),qa=n((t,e,s)=>{if(nt(s,t.identityFingerprint()))return;let r=t.leader,i=Ua(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&t.flushOfflineQueues()},"Yr"),ja=n(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"Xr"),Ba=n((t,e,s,r,i,o)=>{if(nt(o,t.identityFingerprint()))return;let a=t.subscription(e);a&&(t.dropCacheSeed(e),vr(a,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&Ze(a,r),re(a,s))},"Zr"),Wa=n((t,e,s,r)=>{if(nt(r,t.identityFingerprint()))return;let i=t.subscription(e);i&&Y(i.errorCallbacks,s)},"ei"),$a=n((t,e,s,r,i,o,a)=>{if(nt(a,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&o===t.clientIdentifier()&&zt(c,i),Gt(c))},"ti"),Ha=n((t,e,s)=>t!==null||e&&s===null,"si"),za=[Ws],Ga=100,Sr=1e4,Va=n(async(t,e,s,r)=>{let i=new AbortController,o=setTimeout(()=>{i.abort()},Sr);try{let a=await t(e,{body:s,credentials:"include",headers:r,method:"POST",signal:i.signal});return await a.text(),a.status}finally{clearTimeout(o)}},"ni"),Ja=Promise.resolve(),Vt=class t{static{n(this,"Fe")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;adminHost={adminFetch:n((...e)=>this.adminFetch(...e),"adminFetch"),assertOpen:n(()=>{this.assertOpen()},"assertOpen")};clientQueryStore;wsToken;wsTokenGeneration=0;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new Q;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new ne;statusListeners=new ne;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new ne;identityChangeListeners=new ne;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new ne;pendingChangeListeners=new ne;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Ht(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??j(At(e.url),qt),this.wsToken=e.wsToken;let s=e.authBasePath??Oo;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??js(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ha,this.connectTimeoutMs=e.connectTimeoutMs??da,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??la,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??fa,this.defaultConnectionContext=e.connectionContext,this.persistence=rr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=qs(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new $e,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=Ja),this.offlineQueue=new st(e.offlineQueue,{onEvict:n((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onSizeChange:n(r=>{this.pendingChangeListeners.emit(r)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${rt()}`,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=cn(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),o=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),u=this.authToken;this.authToken=e,this.applySubject(e,s);let d=this.identityFingerprint();d!==i&&(!r&&e!==null&&o?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&o&&!c?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(u,e),Ha(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(a),r&&this.authTokenListeners.emit(e),(d!==i||r||a)&&this.offlineQueue.size>0&&Bt(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){let s=this.identityVerdict(e);if(s!=="match")return{verdict:s};let r=Object.freeze({});return this.replayCredentials.set(r,{authToken:this.authToken,stamp:e}),{credential:r,verdict:s}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,s,r){let i=r?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new b("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let o=r?.shardKey??"",a=this.identityFingerprint(),c,u,d;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:n(h=>{c=h},"onMutationAck")})}catch(h){if(!it(h))throw h;d=h}if(c!==void 0&&c>(this.clientWatermarks.get(a??"")?.get(o)??0)){let h=this.clientWatermarks.get(a??"");h===void 0&&(lr(this.clientWatermarks,va),h=new Map,this.clientWatermarks.set(a??"",h)),h.set(o,c)}if(d!==void 0)throw d;return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;let e={},s=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let r=this.sessionProbeGeneration;try{let i=await this.fetchImpl(j(this.url,`${this.authBasePath}${Ro}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let o=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,o,r),o}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.wsTokenGeneration+=1,this.resetRoomSends(),this.bounceShardSockets())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=g(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r),e===void 0&&this.releaseIdleShard(s.shardKey)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=g(s.shardKey),i={context:e},o=this.connectionContextHolders.get(r);o?o.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),this.releaseIdleShard(s.shardKey)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=g(r.shardKey),o=this.whisperHandlers.get(i);o||(o=new Map,this.whisperHandlers.set(i,o));let a=o.get(e),c=a===void 0;if(a||(a=new Set,o.set(e,a)),a.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&this.sendWhisperJoin(u,i,e)}return()=>{let u=this.whisperHandlers.get(i),d=u?.get(e);if(!d?.delete(s)||d.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let h=this.getConnection(r.shardKey);h&&B(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(r.shardKey)}}subscribeLiveTopic(e){let{onError:s,onEvent:r,shardKey:i,stream:o,topic:a}=e;if(a.length===0)throw new b("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;let c=`ws-live-${String(this.nextLiveSocketId)}`,u=g(i),d=`/live/${o}/control`,h=this.whisperSubscribe(a,()=>{},{shardKey:i}),l=n(()=>{let y=h;h=void 0,y?.()},"m"),f=this.liveSocketGrants.get(u);f===void 0&&(f=new Map,this.liveSocketGrants.set(u,f)),f.set(c,{onError:s,onEvent:r,release:l,stream:o,topic:a});let p=this.getConnection(i)?.connectionId;p!==void 0&&this.grantWhenJoined(i,c,p);let m=!1;return()=>{if(m)return;m=!0;let y=this.liveSocketGrants.get(u),v=y?.delete(c)===!0;y?.size===0&&this.liveSocketGrants.delete(u);let w=this.getConnection(i)?.connectionId;v&&w!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:w,stream:o,subscriptionId:c,topic:a}),l()}}whisper(e,s,r={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,V(s??null,`whisper data for topic '${e}'`),r)}connectRoom(e,s,r={}){let i=`room:${e.name}`,o=this.whisperSubscribe(i,f=>{s.onMessage(f)},r),a=!1,c=[],u=n(()=>{c.length=0},"c"),d=n(()=>{for(;c.length>0&&this.roomSendsAdmitted(r.shardKey);){if(!this.sendEncodedWhisper(i,c[0],r))return;c.shift()}},"d"),h=g(r.shardKey),l=this.roomFlushes.get(h)??new Set;return l.add(d),this.roomFlushes.set(h,l),this.roomIdentityResets.add(u),{close:n(()=>{a=!0,c.length=0,l.delete(d),l.size===0&&this.roomFlushes.delete(h),this.roomIdentityResets.delete(u),o()},"close"),send:n(f=>{if(a||this.closed||this.WebSocketImpl===void 0)return!1;let p=V(f,`room message for '${i}'`),m=typeof structuredClone=="function"?structuredClone(p):JSON.parse(JSON.stringify(p));return d(),c.length===0&&this.roomSendsAdmitted(r.shardKey)&&this.sendEncodedWhisper(i,m,r)?!0:c.length>=Ga?!1:(c.push(m),!0)},"send")}}connectWebSocket(e,s,r={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),send:n(()=>{},"send")};let i=n(c=>{try{c?.()}catch(u){console.error("[lunora] socket route handler threw",u)}},"r"),o,a=this.openSupplementarySocket(this.supplementaryUrl(e),{onClose:n(()=>{clearTimeout(o),i(s.onClose)},"onClose"),onMessage:n(c=>{let u;try{u=JSON.parse(typeof c.data=="string"?c.data:"")}catch{return}u.type==="message"&&(a.resetBackoff(),i(()=>{s.onMessage(T(u.data))}))},"onMessage"),onOpen:n(()=>{clearTimeout(o);let c=a.socket();o=setTimeout(()=>{a.socket()===c&&a.resetBackoff()},cr),i(s.onOpen)},"onOpen"),shardKey:r.shardKey});return{close:n(()=>{clearTimeout(o),a.close()},"close"),send:n(c=>{let u=JSON.stringify(V(c,`socket message for '${e}'`)),d=a.socket();if(d!==void 0)try{d.send(u)}catch{}},"send")}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let o of r){let a=this.connections.get(o);e.push({confirmedMutationWatermark:s?.get(o)??0,hasSocket:a?.socket!==void 0,shardKey:o===""?void 0:o,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}let i=this.subscriptions.all().map(o=>({acked:o.acked,functionPath:o.fn.__lunoraRef,id:o.id,kind:"query",lastMutationId:o.lastMutationId,pendingOptimisticLayers:o.optimisticLayers.length,serverCursor:o.serverCursor,shardKey:o.shardKey,subscriberCount:o.callbacks.size}));for(let o of this.shapeSubscriptions.values())i.push({acked:o.serverCursor!==void 0,functionPath:`shape:${o.name}`,id:o.id,kind:"shape",lastMutationId:o.lastMutationId,pendingOptimisticLayers:0,rowCount:o.rows.size,serverCursor:o.serverCursor,shardKey:o.shardKey,subscriberCount:o.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((o,a)=>(o.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((o,a)=>o.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 ir(this,e,s,r)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,N(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=oe(e,s,r),o=this.hydratedQueryCache.get(i);if(o!==void 0)return this.cachedQueryMatchesIdentity(o)?o.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=Q.key(e,s,r),o=this.subscriptions.get(i);return{present:o!==void 0,value:o?.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)),o=r.toArgs??(h=>({rows:h})),a=s.length,c=0,u=0,d=0;for(let h=0;h<a;h+=i){let l=s.slice(h,h+i),f=d,{committed:p}=await this.runMutation(e,o(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(f)}`},shardKey:r.shardKey});d+=1,c+=l.length,p&&(u+=l.length),r.onProgress?.({done:c,total:a})}return{chunks:d,imported:u,queued:c-u}}async shardTraffic(e){return Wo(this.adminHost,e)}async listScheduledJobs(){return zo(this.adminHost)}async schedulerStatus(){return Go(this.adminHost)}async cancelScheduledJob(e){return Vo(this.adminHost,e)}async listDeadJobs(){return Jo(this.adminHost)}async retryDeadJob(e){return Yo(this.adminHost,e)}async removeDeadJob(e){return Xo(this.adminHost,e)}async listWorkflowInstances(e){return Zo(this.adminHost,e)}async getWorkflowInstance(e){return ea(this.adminHost,e)}async setWorkflowInstanceStatus(e){return ta(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=this.openSupplementarySocket(j(At(this.url),fn),{onMessage:n(r=>{let i;try{i=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(s.resetBackoff(),e(i.records.map(o=>Xt(o))))},"onMessage")});return s.close}async listFunctions(){return Fo(this.adminHost)}async getCronJobs(){return Po(this.adminHost)}async runCronJob(e){return Mo(this.adminHost,e)}async fetchOpenApi(){return xo(this.adminHost)}async fetchArchitecture(){return Lo(this.adminHost)}async fetchOpenRpc(){return _o(this.adminHost)}async listStorageObjects(e={}){return sa(this.adminHost,e)}async deleteStorageObject(e,s){return ra(this.adminHost,e,s)}async listStorageBuckets(){return ia(this.adminHost)}async uploadStorageObject(e){return na(this.adminHost,e)}async signedStorageUrl(e,s){return oa(this.adminHost,e,s)}async listGlobalTables(){return Qo(this.adminHost)}async readGlobalTablePage(e){return Do(this.adminHost,e)}async facetGlobalColumn(e){return Uo(this.adminHost,e)}async listVectorIndexes(){return aa(this.adminHost)}async queryVectorIndex(e){return ca(this.adminHost,e)}async queryLogArchive(e={}){return $o(this.adminHost,e)}async listKvNamespaces(){return Ko(this.adminHost)}async listKvKeys(e){return No(this.adminHost,e)}async getKvValue(e){return qo(this.adminHost,e)}async putKvValue(e){return jo(this.adminHost,e)}async deleteKvKey(e){return Bo(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();let s=F(Qn,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(s,"GET")}async createAuthUser(e){return this.assertOpen(),await this.adminFetch(Un,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(Kn,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(Nn,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(qn,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(jn,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(Bn,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(Wn,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch($n,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(Hn,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(zn,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(Gn,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(F(Vn,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(Jn,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(F(Yn,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(Xn,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(Zn,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(F(eo,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();let s=F(to,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.assertOpen();let s=F(so,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();let s=F(oo,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(ao,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(co,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(ro,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(io,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(no,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(uo,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ho,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(lo,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(fo,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(po,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(mo,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();let s=F(yo,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(bo,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(go,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(vo,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();let s=F(So,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(wo,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(Co,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();let s=F(ko,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(To,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Eo,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(Io,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=F(Dn,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){this.assertOpen();let o=s??{},a=Q.key(e.__lunoraRef,o,i.shardKey),c=this.subscriptions.get(a),u=Xe(r),d=Xe(i.onError),h=Xe(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=N(o),m=this.takeHydratedCache(e.__lunoraRef,p,i.shardKey);c={acked:!1,args:o,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:V(o,`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),d&&c.errorCallbacks.add(d),h&&c.checkpointCallbacks.add(h),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),d&&l.errorCallbacks.delete(d),h&&l.checkpointCallbacks.delete(h),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(Q.keyOf(l)),this.subscriptions.remove(l),this.releaseIdleShard(l.shardKey))}}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError: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()}`,o={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:V(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,o),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(o),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(o.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(o.shardKey)}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new b("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:o}=r,a=s??{},{handle:c,iterable:u}=Ve({maxBuffer:r.maxBuffer,onCancel:n(()=>{this.cancelStream(i,o)},"onCancel")});this.ensureSocket(o);let d=this.getConnection(o),h={id:i,query:{args:V(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:o},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:h,shardKey:o};this.streams.set(i,l);let f=d?.wsState==="open"&&B(d,h);if(!f&&d===void 0)return this.forgetStream(i),c.fail(new b("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=ya;){let p=d.pendingStreams.shift()?.id,m=p?this.streams.get(p):void 0;m&&(m.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(p))}d.pendingStreams.push(h)}return u}httpStream(e,s,r={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return Gs(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0;for(let e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new b("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear(),this.supplementaryBounces.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new b("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let s=e.leaderTabId;return s!==void 0&&s!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new b("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){let s=n(r=>g(r)===e,"t");return this.subscriptions.all().some(r=>s(r.shardKey))||[...this.shapeSubscriptions.values()].some(r=>s(r.shardKey))||[...this.streams.values()].some(r=>s(r.shardKey))||this.whisperHandlers.has(e)||this.connectionContexts.has(e)||this.connectionContextHolders.has(e)||this.offlineFlushes.has(e)||this.offlineQueue.hasPending(r=>s(r.shardKey))}releaseIdleShard(e){let s=g(e),r=this.connections.get(s);this.closed||s===""||r===void 0||(clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.idleTimer=void 0,!(this.closed||this.connections.get(s)!==r||this.shardInUse(s))&&(r.wasEverConnected&&this.idleClosedShards.add(s),this.teardownConnection(r),this.connections.delete(s),this.emitConnectionStatus())},ma))}forgetStream(e){let s=this.streams.get(e);this.streams.delete(e),s&&this.releaseIdleShard(s.shardKey)}teardownConnection(e){e.polling.stop();let s=g(e.shardKey);for(let[i,o]of this.streams)g(o.shardKey)===s&&(o.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,me(e);let{socket:r}=e;if(r){e.socket=void 0;try{r.close()}catch{}}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,s={activeSubscriptions:n(()=>this.subscriptions.all(),"activeSubscriptions"),broadcastStatus:n((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:n(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:n(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:n(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:n(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:n(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:n(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:n(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:n(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:n(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:n(()=>this.clientId,"clientIdentifier"),dropCacheSeed:n(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:n((r,i,o)=>{this.ackAndAdvanceCursor(r,i,o)},"ackAndAdvanceCursor"),subscription:n(r=>this.subscriptions.get(r),"subscription")};return new He({channelName:e,onBecomeLeader:n(()=>{Ka(s)},"onBecomeLeader"),onStopBeingLeader:n(()=>{Na(s)},"onStopBeingLeader"),onConnectionStatus:n((r,i)=>{qa(s,r,i)},"onConnectionStatus"),onSubscriptionData:n((r,i,o,a,c)=>{Ba(s,r,i,o,a,c)},"onSubscriptionData"),onLeaderClaimAnswered:n(()=>{ja(s)},"onLeaderClaimAnswered"),onSubscriptionError:n((r,i,o)=>{Wa(s,r,i,o)},"onSubscriptionError"),onSubscriptionSettled:n((r,i,o,a,c,u)=>{$a(s,r,i,o,a,c,u)},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(j(this.url,Nt),{body:JSON.stringify({calls:e.map((c,u)=>({args:V(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 o;try{o=await r.json()}catch{throw new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let a=pe(o);if(!r.ok||a!==void 0&&!o.results)throw a!==void 0?et(a):new b("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let c of o.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return ua(o.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=s,o=r.mutationId??rt(),a=this.takeReplayCredential(r.replayCredential),c=r.replayBaseline===void 0?this.baselineCursorFor(r.shardKey):r.replayBaseline??void 0,{confirms:u,rollbacks:d}=this.applyOptimisticUpdates(e.__lunoraRef,i,r.shardKey,r.optimistic);r.optimisticUpdate&&this.applyOptimisticUpdate(r.optimisticUpdate,s,r.shardKey,d,u);let h=this.offlineFlushes.get(g(r.shardKey));h!==void 0&&await h;let{hasSocket:l,idleClosed:f,polling:p,wasEverConnected:m,wsState:y}=this.connectionGateState(r.shardKey),{queueBeforeFirstConnect:v}=this.offlineQueue,w=m||v,k=this.WebSocketImpl!==void 0&&w,I=p||f,C=y==="connecting"&&w&&!I,x=y!=="open"&&!l&&k&&!I,P=k&&r.replayBaseline===void 0&&this.hasPendingWriteAhead(r.shardKey),R=n(async()=>this.enqueueOfflineMutation(e,i,r.shardKey,c,o,d,u,r.precondition,r.mutationId,a?.stamp),"ae");if(x||C||P)return R();let A;try{let K=await this.rpc(e.__lunoraRef,i,r.shardKey,{baselineSeq:c,captureBookmark:!0,...a?.flags,mutationId:o,onCommitCursor:n(Z=>{A=Z},"onCommitCursor")});for(let Z of u)Z(A);return{committed:!0,value:K}}catch(K){if(I&&k&&K instanceof TypeError&&ar(i))return R();throw this.settleFailedDirectWrite(K,A,u,d,a?.flags.authToken),K}}settleFailedDirectWrite(e,s,r,i,o){if(this.noteIdentityMismatch(e),o!==void 0&&this.noteReplayAuthRefusal(e,o),it(e)){for(let a of r)a(s);return}fe(i)}async enqueueOfflineMutation(e,s,r,i,o,a,c,u,d,h){let l=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;let f=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(f)}`,identity:l,mutationId:f,...a.length>0&&{onRejected:n(()=>{fe(a)},"onRejected")},shardKey:r})}catch(p){throw fe(a),p instanceof Error?p:new Error(String(p))}for(let p of c)p(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((f,p)=>{let m={args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:o,clientId:this.clientId,identity:l,precondition:u,onCommit:n(y=>{for(let v of c)v(y)},"onCommit"),reject:n(y=>{this.queuedIdentities.delete(o),it(y)||fe(a),p(y instanceof Error?y:new Error(String(y))),this.releaseIdleShard(r)},"reject"),resolve:f,shardKey:r};this.offlineQueue.enqueue(m),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),m.id!==void 0&&this.queuedIdentities.set(m.id,l)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=g(e);return this.offlineQueue.hasPending(r=>g(r.shardKey)===s)}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let s of e)this.queuedOfflineShardKeys.add(s),this.ensureSocket(s)}catch{}}hydrateAsOutboxLeader(){let e=n(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),s=globalThis.navigator?.locks;if(!s){e();return}s.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(r=>{if(this.closed){r();return}this.outboxLeaderRelease=r}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),s=new Map;for(let r of this.subscriptions.all())s.set(oe(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(Dt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let o=s.get(r);if(o&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(o,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),re(e,s.value))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let s=this.cacheSeededQueries.get(e);s!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,s))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,s]of this.cacheSeededQueries){let r=this.subscriptions.get(e);r!==void 0&&(r.serverBase=void 0,r.serverCursor=void 0,r.serverEpoch=void 0,re(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=oe(e,s,r),o=this.hydratedQueryCache.get(i);if(!(o===void 0||!this.cachedQueryMatchesIdentity(o)))return this.hydratedQueryCache.delete(i),o}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.hydratedQueryCache.get(s);r!==void 0&&this.cachedQueryMatchesIdentity(r)&&(this.hydratedQueryCache.delete(s),this.seedSubscriptionFromCache(e,r))}}persistQueryValue(e){let s=e.serverBase;if(!this.queryCache||s===void 0)return;let r=oe(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,o=i===void 0?this.identityFingerprint():i;o===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:o,serverCursor:e.serverCursor,ts:Date.now(),value:s,...o===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(()=>{})},pa))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(s=>s.wsState==="open")?"connected":e.some(s=>s.polling.isPolling())?"polling":e.some(s=>s.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let s=g(e),r;for(let i of this.subscriptions.all())g(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}async pollSubscriptions(e){let s=g(e),r=[];for(let c of this.subscriptions.all())g(c.shardKey)===s&&(ar(c.args)?r.push(c):Y(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(r.length===0)return this.probeOrigin();let i=Vs(),o=this.identityFingerprint(),a;try{a=await hr(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()!==o)return!0;for(let[c,u]of r.entries()){let d=a[c];if(d!==void 0){if(!d.ok){Y(u.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:W(d.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await hr(async s=>e(j(this.url,Nt),{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 o=[],a=[];if(!i)return{confirms:o,rollbacks:a};let c=Q.key(e,s,r),u=this.subscriptions.get(c);if(u){let d=xt(u,i);d&&(o.push(d.confirm),a.push(d.rollback))}return{confirms:o,rollbacks:a}}applyOptimisticUpdate(e,s,r,i,o){let{confirms:a,rollbacks:c,store:u}=Xs(this.subscriptions,r);try{e(u,s)}catch{fe(c);return}i.push(...c),o.push(...a)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!B(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let i="idle";return this.leader.status==="connected"?i="open":this.leader.status==="connecting"&&(i="connecting"),{hasSocket:!1,idleClosed:!1,polling:this.leader.status==="polling",wasEverConnected:this.leader.wasEverConnected,wsState:i}}let s=this.getConnection(e),r=s===void 0&&this.idleClosedShards.has(g(e));return{hasSocket:s?.socket!==void 0,idleClosed:r,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??r,wsState:s?.wsState??"idle"}}getOrCreateConnection(e){let s=g(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Ta({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:n(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:n(()=>{this.emitConnectionStatus()},"onStateChange"),poll:n(async()=>this.pollSubscriptions(e),"poll")}),reconnect:Te(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}openSupplementarySocket(e,s){if(this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),resetBackoff:n(()=>{},"resetBackoff"),socket:n(()=>{},"socket")};let r=Te(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},o,a=!1,c=n(()=>{a||this.closed||(o=setTimeout(h,r.next()))},"o"),u=n(p=>{a||this.WebSocketImpl===void 0||ur(i,this.wsUrlFor(s.shardKey,p,e),this.managedSocketOptions,{onClose:n(()=>{c(),s.onClose?.()},"onClose"),onMessage:s.onMessage,...s.onOpen===void 0?{}:{onOpen:s.onOpen}})},"c"),d=n(async p=>{let m=this.wsTokenGeneration,y;try{y=await p()}catch{c();return}if(m!==this.wsTokenGeneration){h();return}u(y)},"d"),h=n(()=>{if(a||this.WebSocketImpl===void 0)return;let{wsToken:p}=this;if(typeof p=="function"){d(p).catch(()=>{});return}u(p)},"h");h();let l=n(()=>{a=!0,o!==void 0&&(clearTimeout(o),o=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),me(i);let{socket:p}=i;i.socket=void 0;try{p?.close()}catch{}},"u");this.adminSocketTeardowns.add(l);let f=n(()=>{let{socket:p}=i;if(p!==void 0){i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),me(i);try{p.close()}catch{}s.onClose?.(),c()}},"m");return this.supplementaryBounces.add(f),{close:n(()=>{l(),this.adminSocketTeardowns.delete(l),this.supplementaryBounces.delete(f)},"close"),resetBackoff:n(()=>{r.reset()},"resetBackoff"),socket:n(()=>i.socket,"socket")}}supplementaryUrl(e){let s=Ft(this.wsUrl),r=s.pathname.endsWith(qt)?s.pathname.slice(0,-qt.length):s.pathname;return s.pathname=j(r,e),Pt(s,this.wsUrl)}wsUrlFor(e,s,r=this.wsUrl){if(e===void 0&&s===void 0)return r;let i=Ft(r),o=new Set([...e===void 0?[]:["shard"],...s===void 0?[]:["token"]]),a=[...i.searchParams].filter(([c])=>!o.has(c)).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);return e!==void 0&&a.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&a.push(`token=${encodeURIComponent(s)}`),i.search=a.join("&"),Pt(i,r)}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[Xi]=Zi(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let o=e.authToken===void 0?this.authToken:e.authToken;if(o&&(r.authorization=`Bearer ${o}`),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 G("LunoraClient: no `fetch` implementation available");let o=this.rpcRequestHeaders(i,r),a=i.authToken===void 0?this.authToken:i.authToken,c=await this.fetchImpl(j(this.url,un),{body:JSON.stringify({args:V(s,`args for '${e}'`),functionPath:e,shardKey:r}),headers:o,method:"POST"});if(i.captureBookmark){let l=c.headers.get("x-d1-bookmark");l&&this.bookmark.set(l)}let u;try{u=await c.json()}catch{throw Ee(c.status,c.statusText,c.headers.get("retry-after"))}let d=u;if(typeof d!="object"||d===null||Array.isArray(d))throw Ee(c.status,c.statusText,c.headers.get("retry-after"));let h=pe(u);if(h!==void 0)throw Qt(h,c.headers.get("retry-after"));if(!c.ok)throw Ee(c.status,c.statusText,c.headers.get("retry-after"));i.onMutationAck?.(u.lastMutationId),i.onCommitCursor?.(u.commitCursor),this.noteCredentialAccepted(a),this.learnDefaultShardKey(c,r),this.recordShardCursor(r,u.commitCursor);try{return T(u.result)}catch(l){throw gr(l)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let o={};this.authToken&&(o.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&&(o["content-type"]=i)):(c=JSON.stringify(r),o["content-type"]="application/json");let u=await this.fetchImpl(j(this.url,e),{body:c,headers:o,method:s}),d;try{d=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let h=pe(d);if(h!==void 0){let l=new Error(h.message??"admin request failed");throw Object.assign(l,{code:h.code},Zs(h)),l}if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return d}effectiveConnectionContext(e){let s=this.connectionContextHolders.get(e);return s&&s.length>0?s[s.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let s=this.connections.get(e);s?.wsState==="open"&&this.sendConnectEnvelope(s)}sendConnectEnvelope(e){let s=this.effectiveConnectionContext(g(e.shardKey));B(e,{caps:za,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())g(s.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);if(!(s.wsState==="open"||s.wsState==="connecting")){if(s.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(s,e,this.wsToken).catch(()=>{});return}this.openSocket(s,e,this.wsToken)}}async openSocketWithProvidedToken(e,s,r){let i=this.wsTokenGeneration,o;try{o=await r()}catch{this.handleDisconnect(e);return}if(!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0)){if(i!==this.wsTokenGeneration){typeof this.wsToken=="function"?await this.openSocketWithProvidedToken(e,s,this.wsToken):this.openSocket(e,s,this.wsToken);return}this.openSocket(e,s,o)}}openSocket(e,s,r){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),r===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,ur(e,this.wsUrlFor(s,r),this.managedSocketOptions,{onClose:n(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:n(i=>{e.retired!==!0&&this.handleServerMessage(i.data,s)},"onMessage"),onOpen:n(()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},cr),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(s),this.clearResubscribeQueue(e);for(let a of this.subscriptions.all())g(a.shardKey)===g(s)&&this.queueResubscribe(a);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let a=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:c,type:u}of a)B(e,{id:c,type:u});this.releaseIdleShard(s)}Sa(e);let i=g(s),o=this.whisperHandlers.get(i);if(this.dropWhisperJoinWaiters(i),this.whisperJoins.set(i,new Map),o)for(let a of o.keys())this.sendWhisperJoin(e,i,a);e.roomsRejoined=!0,this.releaseRoomSends(s),this.flushOfflineQueue(s).catch(()=>{})},"onOpen")}))}cancelStream(e,s){let r=this.getConnection(s);r&&(r.pendingStreams=r.pendingStreams?.filter(i=>i.id!==e),B(r,{id:e,type:"unsubscribe"})),this.forgetStream(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),me(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(g(e.shardKey)),this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,o]of this.streams)if(!(g(o.shardKey)!==g(e.shardKey)||s.has(i))){if(o.durable){let a={...o.message,...o.generation===void 0?{}:{generation:o.generation},sinceChunk:o.lastSeq};o.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),a];continue}o.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}markShardPendingAck(e){let s=g(e);for(let r of this.subscriptions.all())g(r.shardKey)===s&&(r.acked=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribePending.size<ba;){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)},ga))}}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 B(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"&&B(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=Ca(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 o=this.getConnection(s);o&&this.releaseResubscribeSlot(o,i.id)}switch(i.type){case"ack":{let o=this.subscriptions.getById(i.id);o&&(o.acked=!0);return}case"chunk":{let{data:o,generation:a,id:c,seq:u}=i,d=this.streams.get(c);d&&typeof u=="number"&&(d.lastSeq=u,typeof a=="number"&&(d.generation=a),d.durable=!0),d?.handle.push(T(o));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s),this.adoptSocketConnectionId(i,s),this.confirmShardIdentity(s);break}case"live":{this.dispatchLive(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.pokeAssembler.part(s,i);break}case"pokeStart":{this.pokeAssembler.start(s,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(g(s),i.topic);break}}}handleErrorMessage(e){let s=e.error?.code;if(s==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}if(s==="STREAM_ID_IN_USE")return;let{id:r}=e,i=r===void 0?void 0:this.streams.get(r);if(i&&r!==void 0){i.handle.fail(tr(e)),this.forgetStream(r);return}let o=r===void 0?void 0:this.subscriptions.getById(r);if(o){let c=_t(e),u=this.identityFingerprint(),d=Q.keyOf(o);Y(o.errorCallbacks,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,c,u);return}let a=r===void 0?void 0:this.shapeSubscriptions.get(r);a&&Y(a.errorCallbacks,_t(e))}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){Da(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let o=this.shapeSubscriptions.get(i);o&&!r.undecodable.has(i)&&this.applyPokePart(o,r,e)}}}applyPokePart(e,s,r){let i=Qa(e,s,r);if(dr(e),i==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i)return;let o;try{o=$s(e,i.serverBase)}catch(a){Y(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(o===Ot){this.resnapshotSubscription(i);return}if(this.dropCacheSeed(Q.keyOf(i)),vr(i,o,{cursor:e.cursor,epoch:e.epoch}),e.lastMutationId!==void 0&&(zt(i,e.lastMutationId),Gt(i,!0)),this.persistQueryValue(i),Ze(i,i.serverCursor),s!==void 0&&Ys(i,s),re(i,o),this.tabCoordinator?.isLeader()){let a=Q.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(a,o,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&&zt(s,e.lastMutationId),Gt(s),this.tabCoordinator?.isLeader())){let r=Q.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){e.acked=!0,(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),Ze(e,e.serverCursor)&&re(e,e.serverBase))}adoptSocketConnectionId(e,s){let r=this.getConnection(s);if(!(r===void 0||typeof e.connectionId!="string")){r.connectionId=e.connectionId,r.whisperAck=e.whisperAck===!0;for(let i of this.liveSocketGrants.get(g(s))?.keys()??[])this.grantWhenJoined(s,i,e.connectionId)}}grantWhenJoined(e,s,r){let i=g(e),o=this.liveSocketGrants.get(i)?.get(s);if(o===void 0)return;let{stream:a,topic:c}=o,u=n(()=>{this.liveSocketGrants.get(i)?.get(s)===void 0||this.getConnection(e)?.connectionId!==r||this.postLiveControl(`/live/${a}/control`,e,{action:"subscribe",connectionId:r,stream:a,subscriptionId:s,topic:c},d=>{this.refuseLiveGrant(e,s,d,r)})},"c");this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,c,u):u()}sendWhisperJoin(e,s,r){let i=this.whisperJoinState(s,r);i.pending+=1,i.joined=!1,B(e,{topic:r,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,s){let r=this.whisperJoins.get(e)?.get(s);if(r!==void 0&&(r.pending=Math.max(0,r.pending-1),!(r.pending>0))){r.joined=!0;for(let i of r.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,s)}}releaseWhisperJoin(e,s){if(this.whisperHandlers.get(e)?.has(s)===!0)return;let r=this.whisperJoins.get(e),i=r?.get(s);if(!(r===void 0||i===void 0||i.pending>0)){for(let o of i.waiters.splice(0))clearTimeout(o.timer);r.delete(s),r.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,s,r){let i=this.whisperJoinState(e,s);if(i.joined){r();return}let o={run:r,timer:void 0};o.timer=setTimeout(()=>{i.waiters=i.waiters.filter(a=>a!==o),r()},Sr),i.waiters.push(o)}dropWhisperJoinWaiters(e){for(let s of this.whisperJoins.get(e)?.values()??[])for(let r of s.waiters.splice(0))clearTimeout(r.timer)}whisperJoinState(e,s){let r=this.whisperJoins.get(e);r===void 0&&(r=new Map,this.whisperJoins.set(e,r));let i=r.get(s);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},r.set(s,i)),i}refuseLiveGrant(e,s,r,i){let o=g(e),a=this.liveSocketGrants.get(o),c=a?.get(s);a===void 0||c===void 0||this.getConnection(e)?.connectionId!==i||(a.delete(s),a.size===0&&this.liveSocketGrants.delete(o),c.release(),c.onError?.({status:r,topic:c.topic}))}postLiveControl(e,s,r,i){let{fetchImpl:o}=this;if(!o)return;let a=JSON.stringify(s===void 0?r:{...r,shardKey:s}),c=this.rpcRequestHeaders({},s);this.liveControlChain=this.liveControlChain.then(()=>Va(o,j(this.url,e),a,c)).then(u=>{u>=400&&u<500&&u!==404&&u!==401&&i?.(u)}).catch(()=>{})}dispatchLive(e,s){let r=this.liveSocketGrants.get(g(s));if(!r)return;let i=T(e.data);for(let o of r.values())if(!(o.stream!==e.stream||o.topic!==e.topic))try{o.onEvent(i)}catch{}}dispatchWhisper(e,s){let r=this.whisperHandlers.get(g(s))?.get(e.topic);if(!r)return;let i=T(e.data);for(let o of r)try{o(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.forgetStream(e);return}let r=this.subscriptions.getById(e);r&&(r.acked=!1,Y(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(s=>{ie(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 o=e.charCodeAt(i);s^=o,s=Math.imul(s,16777619),r=Math.imul(r,33)+o}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&&Bt(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,s,r){if(!(this.closed||this.authToken!==e||r!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(s?.id??null,r);return}s!==null&&this.setAuthToken(e,s.id)}}adoptCookieSubject(e,s){return this.closed||this.authToken!==null||s<this.identityAnsweredAt?!1:(this.identityAnsweredAt=s,this.identitySettled=!0,this.setAuthToken(null,e),!0)}sendEncodedWhisper(e,s,r){this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey),o=i!==void 0&&B(i,{data:s,topic:e,type:"whisper"});return this.releaseIdleShard(r.shardKey),o}roomSendsAdmitted(e){let s=this.getConnection(e);return s?.wsState==="open"&&s.retired!==!0&&s.identityConfirmed===!0&&s.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(let s of this.roomFlushes.get(g(e))??[])s()}confirmShardIdentity(e){let s=this.getConnection(e);s!==void 0&&(s.identityConfirmed=!0),this.releaseRoomSends(e)}handleIdentityFrame(e,s){let r=this.getConnection(s)?.identityQuestion,{subject:i}=e;r===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,r)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,s){if(s!==void 0){this.authSubject=s,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return s===void 0?e.identity:s}warnRefreshWithoutSubject(e,s){e===null||s===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let o=new Error("offline mutation discarded: auth identity changed before replay");o.code="OFFLINE_IDENTITY_CHANGED",i.reject(o),this.emitItemSettled(i,"rejected",o)}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 o=s??"",a=this.clientWatermarks.get(o);if(a===void 0)this.clientWatermarks.set(o,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.resetRoomSends(),this.revokeCacheSeededValues();for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,re(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,dr(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()}resetRoomSends(){for(let e of this.roomIdentityResets)e()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}for(let e of this.supplementaryBounces)e()}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=g(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:o}=this;try{await this.drainOfflineQueue(e,o)}catch{}!this.closed&&this.authToken!==o&&this.offlineQueue.size>0&&Bt(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&(this.offlineFlushes.delete(s),this.releaseIdleShard(e))}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",l)}let i=g(e),o=this.offlineQueue.drain(h=>g(h.shardKey)===i);if(o.length===0)return;let a=[],c=[];for(let h of o){let l=this.replayGateVerdict(h);l==="send"?a.push(h):l==="hold"&&c.push(h)}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 d=[];for(let h=0;h<u.length;h+=Kt){let l=u.slice(h,h+Kt),f=await this.replayBatched(l,e,s);if(d.push(...f.requeue),f.stop){d.push(...u.slice(h+Kt));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=g(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,$t(i))})}noteReplayRetryDelay(e,s,r){let i=g(e),o=this.replayRetryState.get(i),a=(o?.attempts??0)+1,c=Fa(s,a)??(r===null&&Ge(s)?$t(a):void 0);this.replayRetryState.set(i,{attempts:a,delayMs:c===void 0?o?.delayMs:Math.max(o?.delayMs??0,c)})}scheduleRateLimitedRetry(e){let s=g(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let o=this.replayRetryTimers.get(s);o!==void 0&&clearTimeout(o),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{V(r.args,`args for '${r.functionPath}'`),s.push(r)}catch(i){this.settleReplayTerminal(r,i instanceof Error?i:new Error(String(i)))}return s}identityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let s=this.identityFingerprint();return s===null&&this.identityUnresolved()?"unknown":e===s||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":s===null?"unknown":"mismatch"}replayGateVerdict(e){let s=this.stampOf(e);if(s===void 0)return this.queuedIdentities.delete(e.id??""),"send";let r=this.identityVerdict(s);if(r==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),r==="match")return"send";this.unpersist(e.id);let i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.resolve(s),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,s){let r=e.headers.get("x-lunora-shard-key");if(r===null||s!==void 0||this.defaultShardKey===r)return;this.defaultShardKey=r;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,s){if(typeof s!="number")return;let r=this.cursorKeyFor(e);this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,s))}shouldRequeueReplayFailure(e,s){return this.noteIdentityMismatch(e)?!0:this.noteReplayAuthRefusal(e,s)||Ia(e)}noteReplayAuthRefusal(e,s){if(!Ge(e))return!1;let r=this.hashToken(s??"");return s===this.authToken&&this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}noteCredentialAccepted(e){this.authRefusalNotifiedFor!==void 0&&this.authRefusalNotifiedFor===this.hashToken(e??"")&&(this.authRefusalNotifiedFor=void 0)}takeReplayCredential(e){if(e===void 0)return;let s=this.replayCredentials.get(e);if(s===void 0)throw new TypeError("LunoraClient: `replayCredential` must come from this client's `replayIdentityVerdict`, and is single use");return this.replayCredentials.delete(e),{flags:{authToken:s.authToken,...jt(s.stamp,s.authToken)},stamp:s.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let o=e[i];if(!o)continue;let a;try{let c=await this.rpc(o.functionPath,o.args,o.shardKey,{authToken:r,baselineSeq:o.baselineSeq,captureBookmark:!0,clientId:o.clientId??this.clientId,...jt(o.identity,r),mutationId:o.id,onCommitCursor:n(u=>{a=u},"onCommitCursor")});this.settleReplaySuccess(o,c,a)}catch(c){if(it(c)){this.settleReplayUndecodable(o,c,a);continue}if(!this.shouldRequeueReplayFailure(c,r)){this.settleReplayTerminal(o,c);continue}this.noteReplayRetryDelay(s,c,r),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,s,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let i=JSON.stringify({calls:e.map((d,h)=>({args:V(d.args,`args for '${d.functionPath}'`),baselineSeq:d.baselineSeq,functionPath:d.functionPath,id:h,clientId:d.clientId??this.clientId,mutationId:d.id,shardKey:d.shardKey}))});if(e.length>1&&Ma(i)>Pa)return await this.replayBatchedHalves(e,s,r);let o;try{o=await this.fetchImpl(j(this.url,Nt),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...jt(e.find(d=>d.identity!==void 0)?.identity,r)}),method:"POST"})}catch{return{requeue:e,stop:!0}}let a=o.headers.get("x-d1-bookmark");if(a&&this.bookmark.set(a),o.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let c,u=o.headers.get("retry-after");try{c=await o.json()}catch{return this.settleWholeBatchError(e,Ee(o.status,o.statusText,u),s,r)}if(!c.results){let d=pe(c),h=d===void 0?Ee(o.status,o.statusText,u):Qt(d,u);return this.settleWholeBatchError(e,h,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof G||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:e,stop:!0};for(let o of e)this.settleReplayTerminal(o,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),o=await this.replayBatched(e.slice(0,i),s,r);if(o.stop)return{requeue:[...o.requeue,...e.slice(i)],stop:!0};let a=await this.replayBatched(e.slice(i),s,r);return{requeue:[...o.requeue,...a.requeue],stop:a.stop}}settleReplayBatchSlots(e,s,r,i){let o=xa(s),a=[],c=!1,u=!1;for(let[d,h]of e.entries()){let l=La(o.get(d));switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(h,l.value,l.commitCursor);break}case"errored":{u||=Ge(l.error),this.shouldRequeueReplayFailure(l.error,i)?(this.noteReplayRetryDelay(r,l.error,i),a.push(h)):this.settleReplayTerminal(h,l.error);break}case"unanswered":{a.push(h);break}default:c=!0,this.settleReplayUndecodable(h,l.error,l.commitCursor)}}return c&&!u&&this.noteCredentialAccepted(i),a}};var wr=D(ts(),1),Cr=D(ee(),1);var Ya=n(()=>{let t=(0,wr.c)(4),e=kt(),s,r,i;return t[0]!==e?(s=n(o=>e.onConnectionStatus(()=>{o()}),"o"),r=n(()=>e.connectionStatus(),"e"),i=n(()=>e.connectionStatus(),"s"),t[0]=e,t[1]=s,t[2]=r,t[3]=i):(s=t[1],r=t[2],i=t[3]),(0,Cr.useSyncExternalStore)(s,r,i)},"S");export{ye as a,Re as b,W as c,T as d,Wr as e,Vt as f,Vr as g,ge as h,ni as i,oi as j,ui as k,kt as l,Ya as m};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as Q}from"./chunk-FPI7AMQJ.js";import{a as x}from"./chunk-37WYCOQ2.js";import{a as H}from"./chunk-YVR4SEPU.js";import{b as G}from"./chunk-ZKJS6EBE.js";import"./chunk-RGMVGZV4.js";import{i as z}from"./chunk-E4PXACVL.js";import"./chunk-MVWZMWPD.js";import"./chunk-7Y3SY37W.js";import{a as h}from"./chunk-7G4Z6Q7X.js";import"./chunk-3YXASVTP.js";import"./chunk-AUAECCXB.js";import{b as k}from"./chunk-Q6ED4KUL.js";import"./chunk-BOMPSVRC.js";import{a as U}from"./chunk-4ZEL6BYL.js";import{c as w,d as D,l as K}from"./chunk-BOYS4DOC.js";import"./chunk-QAQDMS6R.js";import"./chunk-N7LJO732.js";import{d as _,e as B,f as P,h as W,m as q,p as E,t as M}from"./chunk-HJHSQPHW.js";import{a as s,d as J,e as le,g as ce}from"./chunk-I26MS5PJ.js";var i=J(le(),1);var e=J(ce(),1);var ue=s(r=>r.kind==="id"?r.table===void 0?"id":`id<${r.table}>`:r.kind==="array"?r.element===void 0?"array":`${r.element}[]`:r.kind,"le"),me=s(r=>r===void 0||r.length===0?"()":`(${r.map(o=>`${o.name}${o.optional?"?":""}: ${ue(o)}`).join(", ")})`,"ce"),fe=s(r=>{switch(r){case"array":return[];case"bigint":return w(0n);case"boolean":return!1;case"bytes":return w(new ArrayBuffer(0));case"number":return 0;case"object":case"record":return{};default:return""}},"ue"),pe=s(r=>{let o={};for(let a of r??[])a.optional||(o[a.name]=fe(a.kind));return JSON.stringify(o,void 0,2)},"me"),he=P(U.runAs),xe=10,ge=s(r=>r===void 0?"undefined":JSON.stringify(r,q,2),"pe"),Re=s(({functions:r,runAsIdentity:o=!1}={})=>{let a=_(),u=K(),[V,X]=(0,i.useState)(null),[I,Y]=(0,i.useState)(null),g=r??V??[],[S,F]=(0,i.useState)(""),[m,b]=(0,i.useState)("{}"),[c,$]=(0,i.useState)(""),[f,Z]=(0,i.useState)(""),[v,p]=(0,i.useState)("idle"),[ee,y]=(0,i.useState)(void 0),[C,N]=(0,i.useState)(null),[A,te]=(0,i.useState)([]);(0,i.useEffect)(()=>{if(r!==void 0)return;let t=!1;return u.listFunctions().then(d=>(t||X(d),d)).catch(d=>{t||Y(W(d))}),()=>{t=!0}},[u,r]);let R=S===""?g[0]?.path??"":S,n=g.find(t=>t.path===R),re=s(async()=>{if(!n)return;let t;try{t=m.trim()===""?{}:D(JSON.parse(m))}catch(l){p("error"),y(void 0),N(a("Invalid JSON args: {message}",{message:l.message}));return}let d={__lunoraRef:n.path},L=c.trim()===""?{}:{shardKey:c.trim()},O=o?f.trim():"",T=s(l=>{te(j=>[{argsText:m,at:Date.now(),id:(j[0]?.id??0)+1,kind:n.kind,path:n.path,shardKey:c,status:l},...j].slice(0,xe))},"$");p("running"),N(null);try{let l=O===""?await B(u,n.kind,d,t,L):await u.query(he,{args:t,functionPath:n.path,userId:O},L);G(c),y(l),p("success"),T("success")}catch(l){y(void 0),N(l.message),p("error"),T("error")}},"M"),ae=s(t=>{F(t.path),b(t.argsText),$(t.shardKey)},"P"),se=s(t=>{F(t.target.value)},"z"),ne=s(t=>{b(t.target.value)},"W"),ie=s(t=>{Z(t.target.value)},"q"),oe=s(()=>{E(re())},"H"),de=s(()=>{b(pe(n?.args))},"V");return(0,e.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-function-runner",children:[I!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"function-discover-error",role:"alert",children:I}),(0,e.jsxs)("div",{className:"flex flex-col gap-4 rounded-xl border border-border bg-card p-4",children:[(0,e.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,e.jsx)(x,{htmlFor:"function-select",children:a("Function")}),(0,e.jsx)("select",{"aria-label":a("Function"),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50","data-testid":"function-select",id:"function-select",onChange:se,value:R,children:g.map(t=>(0,e.jsxs)("option",{value:t.path,children:[t.path," (",t.kind,")"]},t.path))}),n!==void 0&&(0,e.jsxs)("p",{className:"text-xs text-muted-foreground",children:[(0,e.jsx)("span",{className:"mr-1.5 font-medium",children:a("Signature")}),(0,e.jsx)("code",{className:"font-mono","data-testid":"function-signature",children:me(n.args)})]})]}),(0,e.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,e.jsx)(x,{htmlFor:"args-input",children:a("Arguments")}),(0,e.jsx)(h,{"data-testid":"prefill-button",disabled:n===void 0,onClick:de,size:"xs",type:"button",variant:"ghost",children:a("Prefill")})]}),(0,e.jsx)(Q,{"aria-label":a("Arguments"),className:"font-mono text-xs","data-testid":"args-input",id:"args-input",onChange:ne,value:m})]}),(0,e.jsx)(H,{onChange:$,testId:"shard-input",value:c}),o&&(0,e.jsxs)("div",{className:"flex flex-col gap-1.5","data-testid":"run-as-field",children:[(0,e.jsx)(x,{htmlFor:"run-as-input",children:a("Run as identity (userId)")}),(0,e.jsx)(z,{"aria-label":a("Run as identity (userId)"),className:"font-mono text-xs","data-testid":"run-as-input",id:"run-as-input",onChange:ie,placeholder:a("Leave empty to run as admin"),value:f}),(0,e.jsx)("p",{className:"text-[11px] text-muted-foreground",children:a("Dev only: runs the function as this user so you can test auth and RLS. Forged over the admin gate.")})]}),(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)(h,{"data-testid":"run-button",disabled:v==="running"||n===void 0,onClick:oe,type:"button",children:a("Run")}),n!==void 0&&(0,e.jsx)(k,{variant:"outline",children:n.kind}),o&&f.trim()!==""&&(0,e.jsx)(k,{"data-testid":"run-as-badge",variant:"secondary",children:a("as {userId}",{userId:f.trim()})})]})]}),v==="error"&&C!==null&&(0,e.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs text-destructive","data-testid":"error",role:"alert",children:C}),v==="success"&&(0,e.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs","data-testid":"result",children:ge(ee)}),A.length>0&&(0,e.jsx)("ul",{className:"flex flex-col overflow-hidden rounded-xl border border-border","data-testid":"fn-history",children:A.map((t,d)=>(0,e.jsxs)("li",{className:"flex flex-wrap items-center gap-2 border-b border-border px-3 py-2 text-sm last:border-b-0","data-testid":"fn-history-row",children:[(0,e.jsx)("span",{className:t.status==="success"?"text-success":"text-destructive","data-testid":`fn-history-status-${d.toString()}`,children:t.status==="success"?"\u2713":"\u2717"})," ",(0,e.jsxs)("span",{className:"font-mono text-xs",children:[t.path," (",t.kind,")"]})," ",(0,e.jsx)("time",{className:"text-xs text-muted-foreground",children:M(t.at)})," ",(0,e.jsx)(h,{className:"ml-auto","data-testid":`fn-history-load-${d.toString()}`,onClick:s(()=>{ae(t)},"onClick"),size:"xs",type:"button",variant:"ghost",children:a("Load")})]},t.id))})]})},"$e");export{Re as FunctionRunner};
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import{a}from"./chunk-I26MS5PJ.js";var r="https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-5xx-errors/",n="https://developers.cloudflare.com/support/troubleshooting/http-status-codes/cloudflare-1xxx-errors/",f=/string or blob too big/iu,l={BAD_REQUEST:{status:400,title:"Bad request"},UNAUTHORIZED:{status:401,title:"Unauthorized"},FORBIDDEN:{status:403,title:"Forbidden"},NOT_FOUND:{status:404,title:"Not found"},DELIVERY_FENCED:{status:409,title:"Delivery authorization changed",hint:"The operation may have committed. Retry with the same transport key; a committed result from an older authority epoch returns DELIVERY_RECEIPT_FENCED. Do not automatically retry with a new transport key."},DELIVERY_RECEIPT_FENCED:{status:409,title:"Committed receipt authorization changed",hint:"The operation committed, but its stored result belongs to an older authority epoch. Do not automatically retry with a new transport ID. Recover through the application's durable operation key under current authorization."},CONFLICT:{hint:["Another write changed this row while your mutation was running (optimistic concurrency conflict).","","Re-read the row and retry the mutation with the fresh value. Lunora serializes a DO's mutations, so a persistent conflict usually means the handler conflicts **with itself** (e.g. a trigger or cascade touching the same row) \u2014 split that work rather than adding a retry loop."],status:409,title:"Conflict"},NOT_UNIQUE:{hint:["`.unique()` matched more than one document \u2014 it expects the query to identify at most one row.","","- If several matches are legitimate, use `.first()` (take one) or `.collect()` (take all) instead.","- Otherwise tighten the query (e.g. filter on a unique/indexed field) so it can only match one row."],status:400,title:"Query matched more than one document"},VALIDATION_ERROR:{status:400,title:"Validation failed"},TOO_MANY_REQUESTS:{status:429,title:"Too many requests"},UNPROCESSABLE:{status:422,title:"Unprocessable"},NOT_IMPLEMENTED:{status:501,title:"Not implemented"},FUNCTION_NOT_FOUND:{status:404,title:"Function not found"},METHOD_NOT_ALLOWED:{status:405,title:"Method not allowed"},PAYLOAD_TOO_LARGE:{status:413,title:"Payload too large"},INTERNAL:{internal:!0,status:500,title:"Internal error"},INTERNAL_SERVER_ERROR:{internal:!0,status:500,title:"Internal error"},RPC_FAILED:{internal:!0,status:500,title:"Internal error"},COUNT_RLS_UNSUPPORTED:{status:422,title:"count() is unsupported under an RLS policy"},MASK_UNSUPPORTED:{status:422,title:"Aggregation over a masked column is unsupported"},RELATION_PREDICATE_UNSUPPORTED:{status:422,title:"Relation predicate is unsupported in a write policy"},RLS_REQUIRED:{hint:["This table is secure-by-default: it has no `.public()` marker and no RLS policy resolved for the caller, so the read fails closed.","","Add a read policy with `.rls(...)`, or mark the table `.public()` if it is intentionally world-readable."],status:403,title:"RLS policy required"},RUN_DEPTH_EXCEEDED:{internal:!0,status:500,title:"Run depth exceeded"},RUN_KIND_FORBIDDEN:{status:500,title:"Function kind may not be composed from a query"},TRANSACTION_LIMIT_EXCEEDED:{hint:["A single mutation may only read and write a bounded amount before it is stopped.","","Narrow the read with an index (`.withIndex(...)`) instead of scanning the table, or split the write across several mutations \u2014 for a large backfill use `defineMigration` + `lunora migrate up`, which batches and checkpoints for you.","","The ceilings are deliberately conservative \u2014 they exist to stop one request taking down the whole shard. A deployment that genuinely needs bigger transactions can raise them by overriding the `transactionLimits()` seam on its generated shard class."],status:413,title:"Transaction limit exceeded"},MIGRATION_NOT_FOUND:{status:404,title:"Data migration not found"},MIGRATION_DRIFT:{hint:["An applied SQL migration is never re-run, so the runner stopped before applying anything.","","- **Its text changed after it ran:** revert the edit and put the change in a new migration. If the edit is inert (a comment, whitespace, line endings), record the new hash with the `UPDATE` the message prints.","- **Tracking rows predate versions and match no migration:** set each row's `version` with the `UPDATE` the message prints, so the runner can tell what already ran."],status:409,title:"Migration drift"},UNKNOWN_TABLE:{status:404,title:"Unknown table"},GLOBAL_TABLE_NOT_EDITABLE:{status:400,title:"Global table is not editable"},SHARD_ERROR:{status:503,title:"Shard error"},SHARD_UNAVAILABLE:{status:503,title:"Shard unavailable"},SHARD_TIMEOUT:{status:504,title:"Shard timeout"},SHARD_HTTP_ERROR:{status:502,title:"Shard HTTP error"},SUBSCRIPTION_PERSIST_FAILED:{status:500,title:"Subscription persist failed"},TOO_MANY_SUBSCRIPTIONS:{status:429,title:"Too many subscriptions"},OFFLINE_IDENTITY_CHANGED:{status:409,title:"Offline identity changed"},IDENTITY_MISMATCH:{hint:["A write queued offline was replayed on a session that now belongs to someone else (a sign-out, or another user's sign-in, while it waited), so the worker refused it rather than commit it as them.","","`@lunora/client` re-resolves the session on this refusal and settles the write itself. If every replay is refused while the same user stays signed in, your worker's `resolveIdentity` returns a different `userId` than better-auth's `user.id`, or the RPC request carries no session cookie."],status:409,title:"Session changed since the write was queued"},CODEGEN_DIAGNOSTIC:{status:500,title:"Codegen diagnostic"},JURISDICTION_MOVE:{hint:["The schema declares `.jurisdiction(...)` and the project has DO-backed auth (`.auth({ namespace })`). Pinning the auth object to the jurisdiction resolves it to a new, empty one: every user, account and session stays in the unpinned object until copied across. Voice sessions are pinned without an acknowledgement: they store nothing, and their transcripts are rows in the already-pinned shards.","",'Acknowledge with `.jurisdiction("eu", { pinAuth: true })` and deploy, then copy the auth tables across with the `__lunora_admin__:copyAuthToJurisdiction` admin op and, once the counts check out, purge the unpinned copy with `__lunora_admin__:purgeUnpinnedAuth` (see [Pinning auth and voice](/docs/concepts/data-residency#pinning-auth-and-voice)). For D1-mode auth the acknowledgement changes nothing.'],status:422,title:"Unacknowledged jurisdiction move"},SCHEMA_SNAPSHOT_PARSE:{status:500,title:"Schema snapshot parse error"},ENV_INVALID:{internal:!0,status:500,title:"Invalid environment"},X402_FACILITATOR_ERROR:{internal:!0,status:502,title:"Payment facilitator error"},AUTH_HEADERS_MISSING:{internal:!0,status:500,title:"Auth headers missing"},PRIVACY_COVERAGE:{status:500,title:"Privacy coverage check failed"},PRIVACY_REQUEST_OPEN:{status:409,title:"A privacy request is already open"},PRIVACY_SESSION_NOT_FRESH:{status:403,title:"Recent sign-in required"},EMAIL_DOMAIN_BLOCKED:{hint:["This address's domain is on the disposable/throwaway blocklist (or your configured deny-list).","","Sign up with a permanent mailbox. To tune the policy, pass `blockDisposable` / `allowDomains` / `denyDomains` in the `EmailGateConfig` you hand `assertEmailAllowed` / `classifyEmail` / `emailGateMiddleware` (`@lunora/auth/email-guard`)."],status:400,title:"Email domain not allowed"},EMAIL_UNDELIVERABLE:{hint:["The address's domain publishes no MX (or fallback A/AAAA) records, so it can't receive mail.","","Check for a typo in the domain. MX verification is opt-in (`mx: true`) and needs DNS \u2014 leave it off on the edge path if DNS is unavailable."],status:400,title:"Email domain cannot receive mail"},ANALYTICS_SQL_QUERY_ERROR:{status:502,title:"Analytics SQL query error"},BROWSER_RUN_ERROR:{status:502,title:"Browser Run API error"},BROWSER_TOO_MANY_REDIRECTS:{status:502,title:"Too many redirects"},R2_SQL_ERROR:{status:502,title:"R2 SQL API error"},WORKFLOWS_REST_ERROR:{status:502,title:"Cloudflare Workflows REST API error"},CONFIG_INVALID:{internal:!0,status:500,title:"Payment configuration invalid"},CURRENCY_MISMATCH:{status:400,title:"Currency mismatch"},PROVIDER_ERROR:{status:502,title:"Payment provider error"},WEBHOOK_EVENT_ID_MISSING:{status:400,title:"Webhook event id missing"},WEBHOOK_SIGNATURE_INVALID:{status:400,title:"Webhook signature invalid"},WEBHOOK_TIMESTAMP_INVALID:{status:400,title:"Webhook timestamp outside tolerance"},ADMIN_FORBIDDEN:{status:403,title:"Admin access forbidden"},ADMIN_TOKEN_NOT_CONFIGURED:{status:400,title:"Admin token not configured"},AUTH_MIGRATOR_UNSUPPORTED:{hint:["better-auth migrates only through its Kysely adapter, so `ensureMigrated` / `compileMigrationsSql` need the raw D1 binding as `database` \u2014 a custom adapter (`lunoraD1Adapter`, `lunoraAuthAdapter`, `lunoraDoAdapter`) cannot be migrated through, and neither can an absent `database`.","","Build a SECOND, migration-only instance over the raw binding \u2014 `createMigrationAuth({ ...options, database: env.DB })` (from `@lunora/auth/migrate`) \u2014 and hand that one to `ensureMigrated`. Keep the adapter on the instance that serves requests: the adapter exists to dodge a dev-runner hang in `$context`, which the migration instance never resolves.","","To compile the SQL off-platform (`compileMigrationsSql`), diff against an empty local database \u2014 `new DatabaseSync(':memory:')` from `node:sqlite` \u2014 rather than passing no `database` at all."],status:500,title:"Auth migrator cannot drive the configured database"},AUTH_NOT_CONFIGURED:{status:400,title:"Auth admin not configured"},AUTH_OP_NOT_SUPPORTED:{status:400,title:"Auth admin operation not supported"},AUTH_CIMD_FETCH_NOT_PUBLIC:{hint:'Add "global_fetch_strictly_public" to "compatibility_flags" in wrangler.jsonc, so CIMD metadata fetches cannot reach private addresses. `lunora doctor` reports it as `cimd-fetch-not-strictly-public`.',status:500,title:"CIMD transport needs the global_fetch_strictly_public flag"},AUTH_MCP_RESOURCE_AMBIGUOUS:{hint:'Use `mcp` from "@lunora/auth/plugins" (not `@better-auth/mcp`) and pass the plugin object as is: it records its `resource`, which the worker needs to serve the protected-resource metadata when the provider names several resources.',status:500,title:"MCP resource cannot be told apart from the provider's other resources"},AUTH_MCP_RESOURCE_INVALID:{hint:"Pass `resource` to `requireMcpAuth` (and `mcp()`) as the absolute URL of the MCP route, e.g. `https://app.example.com/mcp`: issued tokens are audience-bound to it.",status:500,title:"MCP resource missing or not an absolute URL"},MCP_STEP_UP_MISCONFIGURED:{hint:"Give `createAuthedMcpFetchHandler`'s `stepUp` a non-empty `scope` (such as `lunora:write`) and a `challenge` (`createInsufficientScopeError` from `@lunora/auth/plugins`), or leave `stepUp` out.",status:500,title:"MCP step-up misconfigured"},BACKUP_NOT_CONFIGURED:{status:500,title:"Scheduled backup not configured"},BACKUP_RETENTION_NOT_CONFIGURED:{hint:["`lunora backup prune` removes snapshots past the retention window, and this worker has no window: set `backupRetain` (how many to keep) and `backupCron` (which decides whose snapshots retention owns) on `createWorker`.","","Nothing was deleted. A default is deliberately not invented here \u2014 retention deleting on its own is exactly what this command exists to replace."],status:400,title:"Backup retention window not configured"},BACKUP_TOO_LARGE:{hint:["The scheduled backup is assembled inside the Worker isolate, so it caps the snapshot it will build. Nothing was written.","","The cap is on the NDJSON, not on peak memory: the export fan-out resolves every shard's rows before the first row is encoded, so a snapshot under the cap can still exhaust the isolate. It is set well below the isolate's limit for that reason.","","Narrow the snapshot with `backupTables`, or take this backup off-platform with `lunora backup create --bucket`, which runs on a machine rather than in an isolate. Backing up more often does not help \u2014 every run is a full snapshot."],status:507,title:"Backup too large to assemble in a Worker"},CRON_JOBS_NOT_CONFIGURED:{status:400,title:"Cron jobs not configured"},CRON_JOB_NOT_FOUND:{status:404,title:"Cron job not found"},EXPORT_SHARD_FAILED:{hint:["One or more shards failed to export, so the snapshot would have been short. Nothing is written when this fires \u2014 a partial export must never be mistaken for a complete one.","","The message names each failed shard key and its error. Re-run the export once those shards are reachable; a shard that fails repeatedly is usually over the per-request memory budget, which `backupTables` narrows."],status:502,title:"Export failed on one or more shards"},EXPORT_TAP_NOT_CONFIGURED:{status:400,title:"Export tap not configured"},FUNCTIONS_NOT_CONFIGURED:{status:400,title:"Functions registry not configured"},GLOBALS_NOT_CONFIGURED:{status:400,title:"Global-table introspector not configured"},ID_COLLISION:{hint:["The imported row carries an `_id` that is already held by a DIFFERENT table in this shard. Ids are per-table, so inserting it would leave two tables claiming one id and make a later lookup resolve to whichever one it reached first.","","This is reported per row rather than aborting the import: the remaining rows still apply. Re-mint the id on the source side, or import that table into a shard that does not already hold it."],status:409,title:"Document id already belongs to another table"},KV_NOT_CONFIGURED:{status:400,title:"KV introspector not configured"},MIGRATION_ID_REQUIRED:{status:400,title:"Migration id required"},PITR_UNAVAILABLE:{status:409,title:"Point-in-time recovery unavailable"},SCHEDULER_NOT_CONFIGURED:{status:400,title:"Scheduler not configured"},STORAGE_CHECKSUM_MISMATCH:{hint:["The upload body did not match the declared `expectedSize` or `expectedSha256`, so nothing was written \u2014 this check fails closed.","","Re-read the bytes from the source export and retry the transfer. A persistent mismatch means the source blob is corrupt or truncated; fix the export rather than bypassing the check."],status:400,title:"Storage checksum mismatch"},STORAGE_DELETE_NOT_CONFIGURED:{status:400,title:"Storage delete not configured"},STORAGE_DOWNLOAD_NOT_CONFIGURED:{hint:["`GET /_lunora/admin/storage/object` needs a `storageDownload` function on the worker. The generated app worker wires it up; a hand-written `createWorker({ ... })` has to pass `(key, opts) => pick(opts?.bucket).download(key)` \u2014 forwarding `opts.bucket` to the right bucket, and wrapping rather than passing `createStorage(...).download` itself, whose second parameter is a byte range.","","Without it a bucket-backed `lunora backup restore --bucket` cannot read the snapshot. The object is still readable out of band with `wrangler r2 object get`."],status:400,title:"Storage download not configured"},STORAGE_NOT_CONFIGURED:{status:400,title:"Storage not configured"},STORAGE_OBJECT_NOT_FOUND:{status:404,title:"Storage object not found"},STORAGE_UPLOAD_NOT_CONFIGURED:{status:400,title:"Storage upload not configured"},STORAGE_URL_NOT_CONFIGURED:{status:400,title:"Storage signed URL not configured"},AI_UNKNOWN_IMAGE_MODEL:{status:400,title:"Unknown image model"},RAG_DIMENSION_MISMATCH:{hint:["A stored vector and the query embedding have different widths, so they cannot be compared.","","This is what changing a RAG index's `embeddingModel` (or a provider's `dimensions` option) without reindexing looks like. Either put the previous model back, or reindex the namespace under the new one \u2014 bump `embeddingModelVersion` so the index rebuilds instead of mixing widths."],status:409,title:"Embedding dimension mismatch"},VECTORS_NOT_CONFIGURED:{status:400,title:"Vector index introspector not configured"},VECTOR_QUERY_UNSUPPORTED:{status:400,title:"Vector index querying not enabled"},WORKFLOWS_NOT_CONFIGURED:{status:501,title:"Workflows not configured"},AUTH_AUDIT_NOT_CONFIGURED:{status:400,title:"Auth audit reader not configured"},AUTH_AUDIT_READ_FAILED:{internal:!0,status:500,title:"Auth audit read failed"},AUTH_MOVE_NOT_CONFIGURED:{hint:"The copy needs DO-backed auth (`.auth({ namespace })`) pinned with `.jurisdiction(\u2026, { pinAuth: true })`, and the auth object's `internalSecret` set.",status:400,title:"Auth jurisdiction move not configured"},AUTH_MOVE_TARGET_NOT_EMPTY:{hint:"The pinned auth object holds users the copy did not write (someone signed up there), so copying into it would merge two user bases. Pass `force: true` to copy anyway: a copied row that collides with one of the pinned object's rows is left out and counted under `conflicts`.",status:409,title:"Pinned auth object is not empty"},AUTH_MOVE_CONFLICT:{hint:"A copied row has the same key or unique value (such as an email) as a row the pinned auth object holds on its own, or the pinned object changed a row the source changed too. Nothing from that page was written. Pass `force: true` to keep the pinned object's rows and count the collisions under `conflicts`.",status:409,title:"Auth copy conflict"},AUTH_MOVE_SOURCE_CHANGED:{hint:"The un-pinned auth object changed after the copy read it (an update, a delete, or a new row), for example during a gradual rollout or a rollback. Run the copy again: it reconciles the changed tables. Then purge.",status:409,title:"Un-pinned auth object changed since the copy"},AUTH_MOVE_SOURCE_PURGED:{hint:"The un-pinned auth object was already purged. Its tables may exist again (a rollback served requests there), but they hold only rows written since, so the copy refuses rather than read them as deletions and remove the pinned object's users. Nothing is left to copy.",status:409,title:"Un-pinned auth object already purged"},AUTH_MOVE_INCOMPLETE:{hint:"Run `__lunora_admin__:copyAuthToJurisdiction` until it answers `done: true`, check the per-table counts, then purge.",status:409,title:"Auth copy not finished"},AUTH_MOVE_FAILED:{hint:"The message names the step, the table and the class of the SQLite error; the auth object's log has the full error. The copy resumes where it stopped once the cause is fixed.",status:500,title:"Auth jurisdiction move failed"},CRON_EXPR_INVALID:{status:500,title:"Invalid cron expression"},CRON_EXPR_NOT_STATIC:{status:500,title:"Cron expression is not statically analyzable"},CRON_JOB_FAILED:{internal:!0,status:500,title:"Cron job failed"},CRON_NAME_NOT_STATIC:{status:500,title:"Cron job name is not statically analyzable"},CRON_NON_STATIC_FN:{status:500,title:"Cron function reference is not statically analyzable"},CRON_NON_STATIC_VALUE:{status:500,title:"Cron value is not statically analyzable"},CRON_SCHEDULE_INVALID:{status:500,title:"Invalid cron schedule"},CRON_SCHEDULE_NOT_STATIC:{status:500,title:"Cron schedule is not statically analyzable"},DUPLICATE_CRON_NAME:{status:500,title:"Duplicate cron job name"},DUPLICATE_AGENT_CLASS:{status:500,title:"Duplicate agent generated class name"},DUPLICATE_AGENT_NAME:{status:500,title:"Duplicate agent name"},DUPLICATE_MIGRATION_ID:{status:500,title:"Duplicate migration id"},DUPLICATE_QUEUE_BINDING:{status:500,title:"Duplicate queue binding"},DUPLICATE_QUEUE_NAME:{status:500,title:"Duplicate queue name"},DUPLICATE_ROOM_NAME:{status:500,title:"Duplicate room name"},ROOM_NAME_NOT_LITERAL:{status:500,title:"Room name is not a string literal"},DUPLICATE_SOCKET_PATH:{status:500,title:"Duplicate socket route path"},SOCKET_AUTH_NOT_LITERAL:{status:500,title:"Socket route auth is not a literal boolean"},SOCKET_PATH_INVALID:{status:500,title:"Socket route path is not a plain URL path"},SOCKET_PATH_NOT_LITERAL:{status:500,title:"Socket route path is not a string literal"},LIVE_STREAM_DUPLICATE:{status:500,title:"Duplicate live stream id or export name"},LIVE_STREAM_NOT_EXPORTED:{status:500,title:"Live stream is not a named export"},LIVE_STREAM_NOT_LITERAL:{status:500,title:"Live stream declaration is not a literal"},LIVE_TOPIC_INVALID:{status:500,title:"Live topic name or key field is not allowed"},DUPLICATE_WORKFLOW_CLASS:{status:500,title:"Duplicate workflow generated class name"},MIGRATION_ID_NOT_STATIC:{status:500,title:"Migration id is not statically analyzable"},NAMESPACE_COLLISION:{status:500,title:"Function namespace collision"},BAD_ROW:{status:400,title:"Malformed import row"},BAD_SUBSCRIPTION_ARGS:{status:400,title:"Invalid subscription arguments"},BATCH_LIMIT_EXCEEDED:{status:400,title:"Batch limit exceeded"},CROSS_SHARD_RANK_UNSUPPORTED:{status:400,title:"Cross-shard rank() is unsupported"},DISPATCH_UNAUTHENTICATED:{hint:"The scheduler could not authenticate to the worker. Check that `LUNORA_SCHEDULER_SECRET` matches on both sides, or that `LUNORA_ADMIN_TOKEN` is set and current.",status:403,title:"Dispatch caller not authenticated"},DISPATCH_IN_PROGRESS:{hint:"A dispatch with this idempotency id is still running on the shard. Retry it; once the first attempt settles the same id is served from the replay cache.",status:409,title:"Dispatch already in progress"},FORBIDDEN_FANOUT:{status:403,title:"Fan-out forbidden"},GLOBAL_SEARCH_SCORES_UNSUPPORTED:{status:400,title:"collectWithScores() is unsupported on a global table"},FORBIDDEN_ORIGIN:{status:403,title:"Origin forbidden"},FORBIDDEN_SHARD:{status:403,title:"Shard access forbidden"},FORBIDDEN_TOPIC:{status:403,title:"Live topic publish forbidden"},LIVE_CONTROL_SUPERSEDED:{status:409,title:"A later live control call already applied"},GLOBAL_NOT_CONFIGURED:{status:400,title:"Global table import not configured"},INVALID_INPUT:{status:400,title:"Invalid input"},INVALID_SCHEDULE_ID:{status:400,title:"Invalid schedule id"},RATE_LIMITED:{status:429,title:"Rate limited"},REPLICA_NOT_READY:{status:421,title:"Replica not caught up"},REPLICA_READ_ONLY:{status:421,title:"Replica is read-only"},SEARCH_INDEX_BUILDING:{status:503,title:"Search index is still building"},SERVICE_UNAVAILABLE:{status:503,title:"Service unavailable"},SHAPE_MEMORY_TABLE:{status:400,title:"Shape over a memory table is unsupported"},SHAPE_CROSS_SHARD_JOIN:{status:400,title:"Shape cross-shard join is unsupported"},SHAPE_RELATION_PREDICATE:{status:400,title:"Shape filtered by a relation is unsupported"},UNAUTHENTICATED:{status:401,title:"Unauthenticated"},WIRE_DECODE_FAILED:{status:502,title:"Could not decode a server frame"},WIRE_ENCODE_FAILED:{status:500,title:"Could not encode a return value"},UNKNOWN_COLUMN:{status:404,title:"Unknown column"},CDC_LOG_TRIMMED:{status:409,title:"CDC log trimmed"},CDC_TIMELINE_FORKED:{status:409,title:"CDC timeline forked"},CDC_PAYLOAD_COMPACTED:{status:409,title:"CDC payloads compacted"},EXPIRED:{status:404,title:"Session expired"},LIVE_CONNECTION_LIMIT:{status:503,title:"Live connection limit reached"},LIVE_CONNECTION_NOT_FOUND:{status:404,title:"Live connection not found"},LIVE_STREAMS_UNSUPPORTED:{status:501,title:"Live streams are not served by this worker"},NESTED_TRANSACTION:{internal:!0,status:500,title:"Nested transaction"},OUT_OF_ORDER:{status:409,title:"Out-of-order mutation"},SHAPE_GLOBAL_TOO_LARGE:{status:413,title:"Global shape too large"},SHAPE_NOT_FOUND:{status:404,title:"Shape not found"},SHAPE_REQUIRES_CDC:{status:409,title:"Shape requires change-data-capture"},SQL_UNAVAILABLE:{internal:!0,status:500,title:"SQL storage unavailable"},STREAM_ID_IN_USE:{status:409,title:"Stream id already in use"},STREAM_INTERRUPTED:{status:503,title:"Durable stream interrupted"},STREAM_TOO_LONG:{status:507,title:"Durable stream exceeded its chunk ceiling"},SUBSCRIPTION_RESULT_TOO_LARGE:{status:413,title:"Subscription result too large"},TOKEN_EXPIRED:{hint:["The caller's credential verified but its expiry has passed. The worker refuses an HTTP call with this code before it runs; a shard drops a socket with close code `4001` and the same code.","","It is a refusal of the credential, not of the call: `@lunora/client` holds a queued write, fires `onTokenExpired`, and re-sends it after `setAuthToken`. The held write survives the refresh only if you pass the same `subject` (the user id) with the new token, `setAuthToken(freshToken, user.id)`; without one a refresh reads as a user switch and the write is rejected `OFFLINE_IDENTITY_CHANGED`. Under a cookie session there is no token to replace: renew the cookie and the write is re-sent on a backoff. The worker can only tell expired from anonymous if your `resolveIdentity` returns the identity with its past `exp` (or `expiresAtMs`), or throws a `LunoraError` with this code. Returning `null` runs the call anonymous."],status:401,title:"Authentication token expired"},TOO_MANY_LIVE_TOPICS:{status:429,title:"Too many live topics"},TOO_MANY_STREAMS:{status:429,title:"Too many streams"},TOO_MANY_WHISPER_TOPICS:{hint:"Reuse a stable set of whisper topic names, or reconnect \u2014 the per-socket verdict memo is in-memory, so a new connection starts empty. Leaving a topic does not free its entry.",status:429,title:"Too many whisper topics"},UNKNOWN_ADMIN_OP:{status:404,title:"Unknown admin operation"},SOCKET_TAG_BUDGET_EXCEEDED:{status:400,title:"Socket tag budget exceeded"},RELAY_CANNOT_SEED:{status:500,title:"Relay cannot seed"},RELAY_MISCONFIGURED:{status:500,title:"Relay misconfigured"},RELAY_SEED_FAILED:{status:502,title:"Relay seed failed"},RELAY_SHAPE_UNROUTABLE:{status:500,title:"Relay shape unroutable"},MISCONFIGURED:{internal:!0,status:500,title:"Worker misconfigured"},LUNORA_RUNTIME_UNAVAILABLE:{status:500,title:"Lunora runtime unavailable"},INTERNAL_ERROR:{internal:!0,status:500,title:"Internal error"},BROWSER_TIMEOUT:{status:504,title:"Browser operation timed out"},CLIENT_CLOSED:{status:400,title:"Client is closed"},HTTP_STREAM_BAD_CHUNK:{status:502,title:"Malformed HTTP stream chunk"},HTTP_STREAM_CALLBACK:{status:500,title:"HTTP stream callback threw"},HTTP_STREAM_INTERRUPTED:{status:502,title:"HTTP stream interrupted"},HTTP_STREAM_MISSING_PARAM:{status:400,title:"HTTP stream missing path parameter"},HTTP_STREAM_NO_BODY:{status:502,title:"HTTP stream response has no body"},HTTP_STREAM_STATUS:{status:502,title:"HTTP stream request failed"},HTTP_STREAM_TRANSPORT:{status:502,title:"HTTP stream transport error"},STREAM_BACKPRESSURE:{status:429,title:"Stream backpressure"},STREAM_DISCONNECTED:{status:503,title:"Stream disconnected"},STREAM_QUEUE_OVERFLOW:{status:429,title:"Stream queue overflow"},UNKNOWN_MUTATION_FN:{status:404,title:"Unknown mutation function"},LOCAL_DEPENDENCY_MISSING:{hint:["The command Lunora tried to run is not on your PATH, so nothing ran.","","Install it (or put it on PATH) and retry \u2014 `wrangler` ships as a dependency of a Lunora app, so `pnpm install` usually fixes that one; `git` and `docker` are installed separately."],status:500,title:"Required local tool not found"}},c=a(e=>Object.hasOwn(l,e)?l[e]:void 0,"h");var m=[{body:["A single row exceeded the storage engine's per-row ceiling \u2014 2 MB on a Durable Object's SQLite, and 2,000,000 bytes on D1.","","The limit is on the STORED bytes, which are UTF-8: a document of multi-byte text (CJK, emoji) costs up to 3x its character count. `v.bytes()` and `v.bigint()` columns cost more again on a shard-local table, where the row stores both a SQL-comparable projection and the original.","","Keep the large payload out of the row and store a reference to it:","","```ts","const key = `uploads/${crypto.randomUUID()}`;","await ctx.storage.uploads.put(key, bytes);",'await ctx.db.insert("documents", { storageKey: key, title });',"```","","R2 has no practical object-size ceiling, and the row stays small enough to read, index, and replicate."].join(`
|
|
2
|
-
`),header:"Row too large for the storage engine",id:"lunora-row-too-big",test:a(e=>f.test(e),"test")},{body:["Lunora codegen couldn't find a schema to generate from.","","Create `lunora/schema.ts` exporting a `defineSchema(...)` call:","","```ts",'import { defineSchema, defineTable, v } from "@lunora/server";',"","export default defineSchema({"," messages: defineTable({ body: v.string() }),","});","```","","Or run `lunora init` to scaffold Lunora (a sample `lunora/schema.ts` included) into your app."].join(`
|
|
3
|
-
`),header:"No Lunora schema found",id:"lunora-schema-missing",test:a(e=>e.includes("defineSchema() not found")||e.includes("schema.ts not found at"),"test")},{body:["`defineSchema(...)` must be called with an **inline object literal** mapping table names to `defineTable(...)`:","","```ts","export default defineSchema({"," todos: defineTable({ title: v.string(), done: v.boolean() }),","});","```","","Codegen reads the schema statically, so it can't follow a variable or a spread \u2014 pass the object literal directly."].join(`
|
|
4
|
-
`),header:"`defineSchema()` needs an inline object literal",id:"lunora-schema-not-object-literal",test:a(e=>e.includes("defineSchema() expects an object literal"),"test")},{body:["This table name collides with a built-in `ctx.db` member, so the generated client can't expose it.","","Rename the table to anything that isn't a `ctx.db` member (the error names the one it hit) \u2014 e.g. `userAccounts` instead of `insert`, or `pageViews` instead of `count`."].join(`
|
|
5
|
-
`),header:"Table name is reserved",id:"lunora-table-reserved",test:a(e=>e.includes("is reserved")&&e.includes("ctx.db"),"test")},{body:["Two tables resolve to the same name \u2014 usually a base table and a schema **extension** both defining it.","","Rename one of them, or drop the duplicate from the extension. Each table name must be unique across `defineSchema(...)` and every `.extend(...)`."].join(`
|
|
6
|
-
`),header:"Duplicate table name",id:"lunora-table-duplicate",test:a(e=>e.includes("already exists")&&e.includes(".extend("),"test")},{body:['`.jurisdiction(...)` accepts only a **string literal** of `"eu"`, `"us"`, or `"fedramp"`:',"","```ts",'defineSchema({ /* \u2026 */ }).jurisdiction("eu");',"```"].join(`
|
|
7
|
-
`),header:"Invalid `.jurisdiction(...)` value",id:"lunora-jurisdiction",test:a(e=>e.includes("unknown jurisdiction")||e.includes("jurisdiction")&&e.includes('"eu", "us", or "fedramp"'),"test")},{body:["The `unique` flag on an index must be a **literal** `true` or `false`, not a computed value \u2014 codegen needs to read it statically:","","```ts",'defineTable({ email: v.string() }).index("by_email", ["email"], { unique: true });',"```"].join(`
|
|
8
|
-
`),header:"`unique` must be a literal",id:"lunora-unique-literal",test:a(e=>e.includes("must be a literal")&&e.includes("unique"),"test")},{body:["A declared container/workflow class isn't re-exported by your worker entry, so `wrangler deploy` would reject it.","","Add the generated re-export shown in the error to your worker entry (e.g. `src/index.ts`):","","```ts",'export * from "./lunora/_generated/containers";',"```"].join(`
|
|
9
|
-
`),header:"Binding not exported by your worker entry",id:"lunora-worker-entry-export-gap",test:a(e=>e.includes("not exported by your worker entry"),"test")},{body:["A row with the same value already exists in a `unique` index.","","- If you meant to upsert, use `ctx.db.<table>().upsert(...)` (or `.patch(...)` an existing row) instead of `.insert(...)`.",`- Otherwise pick a value that isn't already taken, and consider surfacing a friendly "already exists" message to the user.`].join(`
|
|
10
|
-
`),header:"Unique constraint violation",id:"lunora-runtime-unique",test:a(e=>e.includes("unique constraint violation on"),"test")},{body:l.CONFLICT.hint.join(`
|
|
11
|
-
`),header:"Optimistic concurrency conflict",id:"lunora-runtime-occ",test:a(e=>e.includes("optimistic concurrency conflict"),"test")}],u=[{causes:"the origin returned an empty, unknown, or malformed response Cloudflare couldn't interpret (often an origin crash or an oversized response header)",code:"520",docsUrl:r,family:"5xx",fix:"check your origin's logs for a crash, ensure it returns a valid HTTP response, and keep response headers under the size limit",summary:"Cloudflare got an unknown/empty response from your origin web server.",title:"Web server returns an unknown error"},{causes:"the origin refused the connection \u2014 the web server is down, or a firewall is blocking Cloudflare's IP ranges",code:"521",docsUrl:r,family:"5xx",fix:"confirm the origin process is running and allowlist Cloudflare's published IP ranges in your firewall/security groups",summary:"Cloudflare could not connect to your origin because it refused the connection.",title:"Web server is down"},{causes:"Cloudflare could not establish a TCP connection to the origin in time \u2014 the origin is overloaded, a firewall is dropping packets, or the origin IP is wrong",code:"522",docsUrl:r,family:"5xx",fix:"verify the origin is reachable and not overloaded, and that the DNS record points at the correct origin IP",summary:"The connection to your origin timed out before it was established.",title:"Connection timed out"},{causes:"Cloudflare cannot route to the origin at all \u2014 a bad DNS record, an origin IP that changed, or invalid routing",code:"523",docsUrl:r,family:"5xx",fix:"verify the DNS A/AAAA record points at a reachable origin IP and that no upstream network is blocking Cloudflare",summary:"Cloudflare could not reach your origin server.",title:"Origin is unreachable"},{causes:"Cloudflare made a TCP connection but the origin did not return an HTTP response within 100 seconds \u2014 a slow handler or long-running request",code:"524",docsUrl:r,family:"5xx",fix:"speed up the slow origin handler, or move long work off the request path into a background job (a Durable Object, Queue, or Workflow)",summary:"Cloudflare connected to your origin but it did not respond in time.",title:"A timeout occurred"},{causes:"the TLS handshake between Cloudflare and the origin failed \u2014 a missing/invalid origin certificate, or a cipher/SNI mismatch under Full (Strict) SSL",code:"525",docsUrl:r,family:"5xx",fix:"install a valid certificate on the origin and align your Cloudflare SSL/TLS mode with the origin's certificate setup",summary:"The SSL handshake with your origin failed.",title:"SSL handshake failed"},{causes:"Cloudflare could not validate the origin's certificate under Full (Strict) SSL \u2014 it is expired, self-signed, or issued for the wrong hostname",code:"526",docsUrl:r,family:"5xx",fix:"install a valid, publicly-trusted certificate on the origin (or use a Cloudflare Origin CA cert), matching the request hostname",summary:"Cloudflare could not validate your origin's SSL certificate.",title:"Invalid SSL certificate"},{causes:"a DNS record points at a Cloudflare IP or another prohibited address instead of your real origin",code:"1000",docsUrl:n,family:"1xxx",fix:"point the DNS record at your real origin IP, not a Cloudflare-owned or loopback address",summary:"DNS points to a prohibited IP.",title:"DNS points to prohibited IP"},{causes:"Cloudflare could not resolve the requested hostname \u2014 a Worker fetched an unresolvable host, or a DNS record is misconfigured",code:"1001",docsUrl:n,family:"1xxx",fix:"check the hostname you're requesting and the DNS records for the zone resolve to a valid origin",summary:"Cloudflare could not resolve the origin DNS.",title:"DNS resolution error"},{causes:"a Worker or DNS record targets a restricted IP (for example a Cloudflare-owned or loopback address)",code:"1002",docsUrl:n,family:"1xxx",fix:"change the Worker fetch target or DNS record to a valid, non-restricted origin address",summary:"DNS points to a prohibited IP (Worker/restricted).",title:"DNS points to a prohibited IP"},{causes:"the visitor's IP was blocked by an IP Access Rule, WAF rule, or security configuration on the zone",code:"1006",docsUrl:n,family:"1xxx",fix:"review the zone's Firewall/WAF and IP Access Rules to see why the address was banned, and adjust if it was blocked in error",summary:"Access denied: the visitor's IP has been banned.",title:"Access denied: your IP has been banned"},{causes:"your Worker threw an unhandled JavaScript exception during the request",code:"1101",docsUrl:n,family:"1xxx",fix:"reproduce with `wrangler tail` (or the Workers Logs / Studio Logs panel) to get the stack trace, then handle the throwing code path",summary:"A Worker threw a JavaScript exception.",title:"Worker threw a JavaScript exception"},{causes:"the Worker used more CPU time than a single invocation is allowed \u2014 usually a hot loop or heavy synchronous work",code:"1102",docsUrl:n,family:"1xxx",fix:"reduce per-request CPU (optimize hot loops, avoid heavy synchronous work) or offload the heavy work to a Durable Object, Queue, or Workflow",summary:"A Worker exceeded its CPU-time resource limit.",title:"Worker exceeded resource limits"}],d=a(e=>e!==void 0&&e>="0"&&e<="9","l"),g=a((e,t)=>{for(let o=e.indexOf(t);o!==-1;o=e.indexOf(t,o+t.length))if(!d(e[o-1])&&!d(e[o+t.length]))return!0;return!1},"_"),A=a((e,t)=>{for(let o of[`error ${t}`,`error: ${t}`])for(let i=e.indexOf(o);i!==-1;i=e.indexOf(o,i+o.length))if(!d(e[i+o.length]))return!0;return!1},"E"),O=/error|cloudflare/iu,p=a(e=>({body:[e.summary,"",`**Likely cause:** ${e.causes}.`,"",`**Fix:** ${e.fix}.`,"",`See [Cloudflare's ${e.family} error docs](${e.docsUrl}).`].join(`
|
|
12
|
-
`),header:`Cloudflare Error ${e.code}: ${e.title}`,id:`cloudflare-error-${e.code}`}),"c"),E=a(e=>{if(!O.test(e))return;let t=e.toLowerCase(),o=t.includes("error"),i=t.includes("cloudflare");if(o){for(let s of u)if(A(t,s.code))return p(s)}if(i){for(let s of u)if(g(t,s.code))return p(s)}},"f"),R=a(e=>(typeof e=="string"?e:e.join(`
|
|
13
|
-
`)).split(`
|
|
14
|
-
`).filter(t=>!t.startsWith("```")).join(`
|
|
15
|
-
`).replaceAll(/\*\*(.+?)\*\*/gu,"$1").replaceAll(/`([^`]+)`/gu,"$1"),"A"),_=a(e=>{for(let t of m)if(t.test(e))return{body:t.body,header:t.header,id:t.id}},"u"),y=a(e=>_(e)??E(e),"O");var T=Symbol.for("@lunora/errors/LunoraError"),h=class e extends Error{static{a(this,"s")}static[Symbol.hasInstance](t){return this!==e?Function.prototype[Symbol.hasInstance].call(this,t):typeof t=="object"&&t!==null&&t[T]===!0}type="VisulimaError";hint;title;loc;code;status;docsUrl;data;why;constructor(t,o,i={}){let s=c(t);super(o??t,i.cause===void 0?void 0:{cause:i.cause}),this.name=i.name??"LunoraError",this.hint=i.hint??s?.hint,this.title=i.title??s?.title,this.loc=i.location,this.code=t,this.status=i.status??s?.status??500,this.docsUrl=i.docsUrl??s?.docsUrl,this.data=i.data,this.why=i.why,Object.defineProperty(this,T,{value:!0}),i.internal!==void 0&&Object.defineProperty(this,"internal",{value:i.internal})}};export{l as a,R as b,y as c,h as d};
|