@lunora/studio 1.0.0-alpha.331 → 1.0.0-alpha.333

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/index.mjs +1 -1
  2. package/dist/mount.mjs +1 -1
  3. package/dist/packem_shared/{StudioApp-BG3kyQ-I.mjs → StudioApp-CUxEVr__.mjs} +1 -1
  4. package/dist/standalone/{chunk-EFXC3EHZ.js → chunk-2CDRWAL6.js} +1 -1
  5. package/dist/standalone/{chunk-F4HMMGVL.js → chunk-2VIGYW3S.js} +1 -1
  6. package/dist/standalone/{chunk-RNVXXJBN.js → chunk-2YEDTLGD.js} +1 -1
  7. package/dist/standalone/{chunk-2GYGUDJS.js → chunk-357O3FBE.js} +1 -1
  8. package/dist/standalone/{chunk-QMECH2OK.js → chunk-3TL6EMCG.js} +1 -1
  9. package/dist/standalone/{chunk-J2OLAMJR.js → chunk-3ZVTL2VM.js} +1 -1
  10. package/dist/standalone/{chunk-J4BVPEXN.js → chunk-4RDTHNCM.js} +1 -1
  11. package/dist/standalone/{chunk-KDF7XOVW.js → chunk-544PMJL6.js} +1 -1
  12. package/dist/standalone/{chunk-NSNRU3CH.js → chunk-5V4REVOK.js} +1 -1
  13. package/dist/standalone/{chunk-5ZCMUHYK.js → chunk-6JMKSAOS.js} +1 -1
  14. package/dist/standalone/{chunk-U2ACS5ID.js → chunk-6M5R5VXY.js} +1 -1
  15. package/dist/standalone/{chunk-JKOBTLQU.js → chunk-6T6JFHWU.js} +1 -1
  16. package/dist/standalone/{chunk-CHF23IX6.js → chunk-7NGFZ7OK.js} +1 -1
  17. package/dist/standalone/{chunk-3O4QTTSY.js → chunk-CMAPNVCT.js} +1 -1
  18. package/dist/standalone/{chunk-M45NNDDU.js → chunk-CWVYS5LB.js} +1 -1
  19. package/dist/standalone/{chunk-AH56E26M.js → chunk-DCD562KJ.js} +1 -1
  20. package/dist/standalone/{chunk-VFAP6A6G.js → chunk-DMEGDUGQ.js} +1 -1
  21. package/dist/standalone/{chunk-B475OGG2.js → chunk-DVCBS7Z6.js} +1 -1
  22. package/dist/standalone/{chunk-FZJY5QLO.js → chunk-ESQNSJEK.js} +1 -1
  23. package/dist/standalone/{chunk-K73JDHTM.js → chunk-F2JMVU2F.js} +1 -1
  24. package/dist/standalone/{chunk-22MSJQDH.js → chunk-GBAQ5M7Y.js} +1 -1
  25. package/dist/standalone/{chunk-XVE6WFB4.js → chunk-HNMSVHPM.js} +1 -1
  26. package/dist/standalone/{chunk-KARIZQ65.js → chunk-I5PK6SLS.js} +1 -1
  27. package/dist/standalone/{chunk-BDAZK3QX.js → chunk-I5U5LU6L.js} +1 -1
  28. package/dist/standalone/{chunk-5QXC7TAH.js → chunk-I6VQ56RO.js} +1 -1
  29. package/dist/standalone/{chunk-NBYAGXMZ.js → chunk-IHAUHNTM.js} +1 -1
  30. package/dist/standalone/{chunk-2KXU4RFA.js → chunk-IWF4IWJT.js} +1 -1
  31. package/dist/standalone/{chunk-ENRGUWYC.js → chunk-JPEXFCD7.js} +1 -1
  32. package/dist/standalone/{chunk-4DPZVEBK.js → chunk-KLDGZ5FU.js} +1 -1
  33. package/dist/standalone/{chunk-JYPEPARL.js → chunk-KNYZMZPY.js} +1 -1
  34. package/dist/standalone/chunk-KPRNLQKZ.js +7 -0
  35. package/dist/standalone/{chunk-XDWPHAV6.js → chunk-KQ7RUNQV.js} +1 -1
  36. package/dist/standalone/{chunk-HXO6YGKL.js → chunk-KTJR54TW.js} +1 -1
  37. package/dist/standalone/{chunk-VESZYIB4.js → chunk-KU2V3NDJ.js} +1 -1
  38. package/dist/standalone/{chunk-G3ZNPPY3.js → chunk-L5ZKGZHX.js} +1 -1
  39. package/dist/standalone/{chunk-B3SX5SBI.js → chunk-LSNLFUZ6.js} +1 -1
  40. package/dist/standalone/{chunk-4NSXTCPY.js → chunk-MBW5C5GU.js} +1 -1
  41. package/dist/standalone/{chunk-BOGUQHYU.js → chunk-NGPK5RSU.js} +1 -1
  42. package/dist/standalone/{chunk-LVCMJJQO.js → chunk-NQNI4E56.js} +1 -1
  43. package/dist/standalone/{chunk-TBEEPT5P.js → chunk-OOQHMMNK.js} +1 -1
  44. package/dist/standalone/{chunk-TRUA26Q4.js → chunk-PPXPRPMU.js} +1 -1
  45. package/dist/standalone/{chunk-34HRTSIP.js → chunk-PRQKA5BT.js} +1 -1
  46. package/dist/standalone/{chunk-KC67JOVJ.js → chunk-QA5RUU7W.js} +1 -1
  47. package/dist/standalone/{chunk-ZBHXISOD.js → chunk-QTDX7WSP.js} +1 -1
  48. package/dist/standalone/{chunk-MMCREWVL.js → chunk-QYPMUUYF.js} +1 -1
  49. package/dist/standalone/{chunk-4ZPDCXIA.js → chunk-R7SRERCX.js} +1 -1
  50. package/dist/standalone/{chunk-CLXX5RVY.js → chunk-RGUL4AQZ.js} +1 -1
  51. package/dist/standalone/{chunk-SHY25BCU.js → chunk-TNF67D54.js} +1 -1
  52. package/dist/standalone/{chunk-5XSZGYSM.js → chunk-UHCFEXE5.js} +1 -1
  53. package/dist/standalone/{chunk-WDGITBC6.js → chunk-UJTSGF6S.js} +1 -1
  54. package/dist/standalone/{chunk-QMENQICE.js → chunk-UUESQ5A2.js} +1 -1
  55. package/dist/standalone/{chunk-T6XTWQC2.js → chunk-V5JA533L.js} +1 -1
  56. package/dist/standalone/{chunk-ZVXBXVS3.js → chunk-V6IC22GP.js} +1 -1
  57. package/dist/standalone/{chunk-YCQP3TYK.js → chunk-VKSSPTTK.js} +1 -1
  58. package/dist/standalone/{chunk-ZWLIXZWR.js → chunk-WDWGLJNK.js} +1 -1
  59. package/dist/standalone/{chunk-GPNP4QSZ.js → chunk-X4MAMXRE.js} +1 -1
  60. package/dist/standalone/{chunk-K3ST3XOT.js → chunk-XSVQZ5JW.js} +1 -1
  61. package/dist/standalone/{chunk-WAJZ4QKG.js → chunk-YF3GD7OV.js} +1 -1
  62. package/dist/standalone/{chunk-6UKEJNM5.js → chunk-YXTJSSB4.js} +1 -1
  63. package/dist/standalone/{chunk-VNBONC2Q.js → chunk-ZODHG66O.js} +1 -1
  64. package/dist/standalone/{chunk-HQPW3EZF.js → chunk-ZVGDUDHN.js} +1 -1
  65. package/dist/standalone/studio.js +2 -2
  66. package/package.json +5 -5
  67. package/dist/standalone/chunk-X6XAMP4E.js +0 -7
@@ -0,0 +1,7 @@
1
+ import{a as ns,d as b}from"./chunk-NRAAYZ4C.js";import{a as n,d as D,e as te,f as as,g as ut}from"./chunk-I26MS5PJ.js";var Pr=/["\\\u0000-\u001F\uD800-\uDFFF]/,os=n(t=>Pr.test(t)?JSON.stringify(t):`"${t}"`,"c"),Mr=n(t=>Number.isNaN(t)?"nan":t===1/0?"inf":t===-1/0?"-inf":Object.is(t,-0)?"-0":void 0,"b"),Lr=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(),a="{",o=!0;for(let c of i){let u=r[c];u!==void 0&&(o?o=!1:a+=",",a+=os(c),a+=":",a+=e(u))}return`${a}}`},"u"),ge=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=="function"||typeof t=="symbol")throw new TypeError(`stableStringify: cannot use a ${typeof t} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported`);if(typeof t=="number"){let e=Mr(t);if(e!==void 0)return e}return typeof t=="string"?os(t):t===null||typeof t!="object"?JSON.stringify(t):Array.isArray(t)?`[${Array.from({length:t.length},(e,s)=>ge(t[s])).join(",")}]`:Lr(t,ge)},"y");var Me=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"e");var Le=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"),xr=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"),F="$lunora.wire$",xe=64,Qe=1024,Qr="__proto__",_r=/^-?\d+$/,cs={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},us={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},ht=n((t,e,s)=>{e===Qr?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,value:s,writable:!0}):t[e]=s},"y");var Dr=n(t=>{let e=t.toString();if(e.length>Qe)throw new RangeError(`wire-codec: over-long bigint (max ${String(Qe)} digits)`);return[F,"bigint",e]},"T"),Ur=n(t=>Number.isNaN(t)?[F,"nan"]:t===1/0?[F,"inf"]:t===-1/0?[F,"-inf"]:t,"j"),Kr=n((t,e)=>{let s=e(Object.fromEntries(Object.keys(t).map(a=>[a,t[a]]))),r=t,i=[F,"error",String(r.name),String(r.message),s];return t.cause!==void 0&&i.push(e(t.cause)),i},"R"),Nr=n(t=>{let e=t.constructor.name,s=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);return e==="Uint8Array"?[F,"bytes",Le(s)]:[F,"bytes",Le(s),e]},"S"),qr=n((t,e)=>t instanceof Date?[F,"date",e(t.getTime())]:t instanceof Error?Kr(t,e):t instanceof URL?[F,"url",t.href]:t instanceof Map?[F,"map",[...t.entries()].map(([s,r])=>[e(s),e(r)])]:t instanceof Set?[F,"set",[...t].map(s=>e(s))]:t instanceof ArrayBuffer?[F,"bytes",Le(new Uint8Array(t)),"ArrayBuffer"]:ArrayBuffer.isView(t)?Nr(t):void 0,"U"),jr=n((t,e)=>{let s=t.map(r=>e(r));return s.length>0&&s[0]===F?[F,"arr",s]:s},"I"),Wr=n((t,e)=>{let s={};for(let r of Object.keys(t)){let i=t[r];i!==void 0&&ht(s,r,e(i))}return s},"B"),B=n((t,e=0)=>{if(e>xe)throw new RangeError(`wire-codec: value nesting exceeds the ${String(xe)}-level limit`);if(t===void 0)return[F,"undefined"];if(t===null)return t;if(typeof t=="bigint")return Dr(t);if(typeof t=="number")return Ur(t);if(typeof t!="object")return t;let s=n(i=>B(i,e+1),"t"),r=qr(t,s);if(r!==void 0)return r;if(Array.isArray(t))return jr(t,s);if(!Me(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 Wr(t,s)},"m"),Br=n(t=>{let e=t[2];if(typeof e!="string"||e.length>Qe||!_r.test(e))throw new RangeError(`wire-codec: invalid or over-long bigint (max ${String(Qe)} digits)`);return BigInt(e)},"N"),$r=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)},"_"),Hr=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])]}))},"$"),Gr=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"),zr=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(us,s)?us[s]:void 0)??Error,a=new i(r);a.name!==s&&Object.defineProperty(a,"name",{configurable:!0,value:s,writable:!0});let o=e(t[4]);if(o===null||typeof o!="object"||Array.isArray(o))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let[c,u]of Object.entries(o))ht(a,c,u);return t.length>5&&Object.defineProperty(a,"cause",{configurable:!0,value:e(t[5]),writable:!0}),a},"P"),Vr=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=xr(e);if(Le(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(cs,r)?cs[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 Br(t);case"bytes":return Vr(t);case"date":return $r(t,e);case"error":return zr(t,e);case"inf":return 1/0;case"map":return Hr(t,e);case"nan":return Number.NaN;case"set":return new Set(t[2].map(s=>e(s)));case"undefined":return;case"url":return Gr(t);default:return t.map(s=>e(s))}},"C"),Yr=n((t,e)=>{let s={};for(let r of Object.keys(t))ht(s,r,e(t[r]));return s},"L"),T=n((t,e=0)=>{if(e>xe)throw new RangeError(`wire-codec: value nesting exceeds the ${String(xe)}-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]===F?Jr(r,s):r.map(i=>s(i))}return Yr(t,s)},"A"),Xr=n(t=>{try{let e=T(JSON.parse(t));return Me(e)?e:void 0}catch{return}},"F");var N=n(t=>ge(B(t)),"a");var ce=D(te(),1),hs=D(ut(),1);var ve=ce.createContext(void 0),Se=n(t=>{let e=ce.useContext(ve);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),dt=n(({client:t,children:e})=>(ce.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,hs.jsx)(ve.Provider,{value:t,children:e})),"QueryClientProvider");var K=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 Zr=class extends K{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"}},ue=new Zr;var ei={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")},ti=class{static{n(this,"TimeoutManager")}#e=ei;#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 ti;function ds(t){setTimeout(t,0)}n(ds,"systemSetTimeoutZero");var pt=typeof window>"u"||"Deno"in globalThis;function E(){}n(E,"noop");function fs(t,e){return typeof t=="function"?t(e):t}n(fs,"functionalUpdate");function we(t){return typeof t=="number"&&t>=0&&t!==1/0}n(we,"isValidTimeout");function _e(t,e){return Math.max(t+(e||0)-Date.now(),0)}n(_e,"timeUntilStale");function q(t,e){return typeof t=="function"?t(e):t}n(q,"resolveStaleTime");function L(t,e){return typeof t=="function"?t(e):t}n(L,"resolveQueryBoolean");function De(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:c}=t;if(o){if(r){if(e.queryHash!==Ce(o,e.options))return!1}else if(!se(e.queryKey,o))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||a&&!a(e))}n(De,"matchQuery");function Ue(t,e){let{exact:s,status:r,predicate:i,mutationKey:a}=t;if(a){if(!e.options.mutationKey)return!1;if(s){if(H(e.options.mutationKey)!==H(a))return!1}else if(!se(e.options.mutationKey,a))return!1}return!(r&&e.state.status!==r||i&&!i(e))}n(Ue,"matchMutation");function Ce(t,e){return(e?.queryKeyHashFn||H)(t)}n(Ce,"hashQueryKeyByOptions");function H(t){return JSON.stringify(t,(e,s)=>lt(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}n(H,"hashKey");function se(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(!se(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!se(t[r],e[r]))return!1;return!0}return!1}n(se,"partialMatchKey");var si=Object.prototype.hasOwnProperty;function ft(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=ls(t)&&ls(e);if(!r&&!(lt(t)&&lt(e)))return e;let a=(r?t:Object.keys(t)).length,o=r?e:Object.keys(e),c=o.length,u=r?new Array(c):{},d=0;for(let h=0;h<c;h++){let l=r?h:o[h],p=t[l],f=e[l];if(p===f){u[l]=p,(r?h<a:si.call(t,l))&&d++;continue}if(p===null||f===null||typeof p!="object"||typeof f!="object"){u[l]=f;continue}let y=ft(p,f,s+1);u[l]=y,y===p&&d++}return a===c&&d===a?t:u}n(ft,"replaceEqualDeep");function he(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(he,"shallowEqualObjects");function ls(t){return Array.isArray(t)&&t.length===Object.keys(t).length}n(ls,"isPlainArray");function lt(t){if(!ps(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!ps(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}n(lt,"isPlainObject");function ps(t){return Object.prototype.toString.call(t)==="[object Object]"}n(ps,"hasObjectPrototype");function ms(t){return new Promise(e=>{$.setTimeout(e,t)})}n(ms,"sleep");function ke(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?ft(t,e):e}n(ke,"replaceData");function ri(t){return t}n(ri,"keepPreviousData");function ys(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}n(ys,"addToEnd");function bs(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}n(bs,"addToStart");var de=Symbol();function Ke(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===de?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}n(Ke,"ensureQueryFn");function le(t,e){return typeof t=="function"?t(...e):!!t}n(le,"shouldThrowError");function gs(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(gs,"addConsumeAwareSignal");var G=(()=>{let t=n(()=>pt,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function Te(){let t,e,s=new Promise((i,a)=>{t=i,e=a});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(Te,"pendingThenable");var vs=ds;function ii(){let t=[],e=0,s=n(c=>{c()},"notifyFn"),r=n(c=>{c()},"batchNotifyFn"),i=vs,a=n(c=>{e?t.push(c):i(()=>{s(c)})},"schedule"),o=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||o()}return u},"batch"),batchCalls:n(c=>(...u)=>{a(()=>{c(...u)})},"batchCalls"),schedule:a,setNotifyFunction:n(c=>{s=c},"setNotifyFunction"),setBatchNotifyFunction:n(c=>{r=c},"setBatchNotifyFunction"),setScheduler:n(c=>{i=c},"setScheduler")}}n(ii,"createNotifyManager");var C=ii();var ni=class extends K{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}},pe=new ni;function ai(t){return Math.min(1e3*2**t,3e4)}n(ai,"defaultRetryDelay");function mt(t){return(t??"online")==="online"?pe.isOnline():!0}n(mt,"canFetch");var Ne=class extends Error{static{n(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function qe(t){let e=!1,s=0,r,i=Te(),a=n(()=>i.status!=="pending","isResolved"),o=n(m=>{if(!a()){let g=new Ne(m);p(g),t.onCancel?.(g)}},"cancel"),c=n(()=>{e=!0},"cancelRetry"),u=n(()=>{e=!1},"continueRetry"),d=n(()=>ue.isFocused()&&(t.networkMode==="always"||pe.isOnline())&&t.canRun(),"canContinue"),h=n(()=>mt(t.networkMode)&&t.canRun(),"canStart"),l=n(m=>{a()||(r?.(),i.resolve(m))},"resolve"),p=n(m=>{a()||(r?.(),i.reject(m))},"reject"),f=n(()=>new Promise(m=>{r=n(g=>{(a()||d())&&m(g)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,a()||t.onContinue?.()}),"pause"),y=n(()=>{if(a())return;let m,g=s===0?t.initialPromise:void 0;try{m=g??t.fn()}catch(S){m=Promise.reject(S)}Promise.resolve(m).then(l).catch(S=>{if(a())return;let k=t.retry??(G.isServer()?0:3),I=t.retryDelay??ai,w=typeof I=="function"?I(s,S):I,O=k===!0||typeof k=="number"&&s<k||typeof k=="function"&&k(s,S);if(e||!O){p(S);return}s++,t.onFail?.(s,S),ms(w).then(()=>d()?void 0:f()).then(()=>{e?p(S):y()})})},"run");return{promise:i,status:n(()=>i.status,"status"),cancel:o,continue:n(()=>(r?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:h,start:n(()=>(h()?y():f().then(y),i),"start")}}n(qe,"createRetryer");var je=class{static{n(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),we(this.gcTime)&&(this.#e=$.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(G.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&($.clearTimeout(this.#e),this.#e=void 0)}};function ws(t){return{onFetch:n((e,s)=>{let r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,a=e.state.data?.pages||[],o=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,d=n(async()=>{let h=!1,l=n(y=>{gs(y,()=>e.signal,()=>h=!0)},"addSignalProperty"),p=Ke(e.options,e.fetchOptions),f=n(async(y,m,g)=>{if(h)return Promise.reject(e.signal.reason);if(m==null&&y.pages.length)return Promise.resolve(y);let k=n(()=>{let ee={client:e.client,queryKey:e.queryKey,pageParam:m,direction:g?"backward":"forward",meta:e.options.meta};return l(ee),ee},"createQueryFnContext")(),I=await p(k),{maxPages:w}=e.options,O=g?bs:ys;return{pages:O(y.pages,I,w),pageParams:O(y.pageParams,m,w)}},"fetchPage");if(i&&a.length){let y=i==="backward",m=y?oi:Ss,g={pages:a,pageParams:o},S=m(r,g);c=await f(g,S,y)}else{let y=t??a.length;do{let m=u===0?o[0]??r.initialPageParam:Ss(r,c);if(u>0&&m==null)break;c=await f(c,m),u++}while(u<y)}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(ws,"infiniteQueryBehavior");function Ss(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(Ss,"getNextPageParam");function oi(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}n(oi,"getPreviousPageParam");var Ts=class extends je{static{n(this,"Query")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t){super(),this.#a=!1,this.#o=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=ks(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.#o,...t},t?._type&&(this.#e=t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=ks(this.options);e.data!==void 0&&(this.setState(Cs(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=ke(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=>L(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===de||!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:!_e(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.#a||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.#a=!0,s.signal),"get")})},"addSignalProperty"),i=n(()=>{let u=Ke(this.options,e),h=n(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,h,this):u(h)},"fetchFn"),o=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"?ws(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#c({type:"fetch",meta:o.fetchOptions?.meta}),this.#i=qe({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:n(u=>{u instanceof Ne&&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:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.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 Ne){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,...yt(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...Cs(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),C.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:t})})}};function yt(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:mt(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}n(yt,"fetchState");function Cs(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}n(Cs,"successState");function ks(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(ks,"getDefaultState");var gt=class extends K{static{n(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=Te(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#o;#a;#h;#c;#f;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Es(this.#t,this.options)?this.#p():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return bt(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return bt(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 L(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&&!he(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&Is(this.#t,s,this.options,e)&&this.#p(),this.updateResult(),r&&(this.#t!==s||L(this.options.enabled,this.#t)!==L(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||L(this.options.enabled,this.#t)!==L(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 ui(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.#o.status==="pending"&&this.#o.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.#p({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#p(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(G.isServer()||this.#r.isStale||!we(t))return;let s=_e(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,!(G.isServer()||L(this.options.enabled,this.#t)===!1||!we(this.#u)||this.#u===0)&&(this.#l=$.setInterval(()=>{(this.options.refetchIntervalInBackground||ue.isFocused())&&this.#p()},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,a=this.#n,o=this.#i,u=t!==s?t.state:this.#s,{state:d}=t,h={...d},l=!1,p;if(e._optimisticResults){let A=this.hasListeners(),R=!A&&Es(t,e),V=A&&Is(t,s,e,r);(R||V)&&(h={...h,...yt(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:f,errorUpdatedAt:y,status:m}=h;p=h.data;let g=!1;if(e.placeholderData!==void 0&&p===void 0&&m==="pending"){let A;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(A=i.data,g=!0):A=typeof e.placeholderData=="function"?e.placeholderData(this.#f?.state.data,this.#f):e.placeholderData,A!==void 0&&(m="success",p=ke(i?.data,A,e),l=!0)}if(e.select&&p!==void 0&&!g)if(i&&p===a?.data&&e.select===this.#h)p=this.#c;else try{this.#h=e.select,p=e.select(p),p=ke(i?.data,p,e),this.#c=p,this.#a=null}catch(A){this.#a=A}this.#a&&(f=this.#a,p=this.#c,y=Date.now(),m="error");let S=h.fetchStatus==="fetching",k=m==="pending",I=m==="error",w=k&&S,O=p!==void 0,M={status:m,fetchStatus:h.fetchStatus,isPending:k,isSuccess:m==="success",isError:I,isInitialLoading:w,isLoading:w,data:p,dataUpdatedAt:h.dataUpdatedAt,error:f,errorUpdatedAt:y,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:S,isRefetching:S&&!k,isLoadingError:I&&!O,isPaused:h.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:I&&O,isStale:vt(t,e),refetch:this.refetch,promise:this.#o,isEnabled:L(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let A=M.data!==void 0,R=M.status==="error"&&!A,V=n(Pe=>{R?Pe.reject(M.error):A&&Pe.resolve(M.data)},"finalizeThenableIfPossible"),is=n(()=>{let Pe=this.#o=M.promise=Te();V(Pe)},"recreateThenable"),Fe=this.#o;switch(Fe.status){case"pending":t.queryHash===s.queryHash&&V(Fe);break;case"fulfilled":(R||M.data!==Fe.value)&&is();break;case"rejected":(!R||M.error!==Fe.reason)&&is();break}}return M}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.#f=this.#t),he(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 a=new Set(i??this.#m);return this.options.throwOnError&&a.add("error"),Object.keys(this.#r).some(o=>{let c=o;return this.#r[c]!==t[c]&&a.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){C.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function ci(t,e){return L(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&L(e.retryOnMount,t)===!1)}n(ci,"shouldLoadOnMount");function Es(t,e){return ci(t,e)||t.state.data!==void 0&&bt(t,e,e.refetchOnMount)}n(Es,"shouldFetchOnMount");function bt(t,e,s){if(L(e.enabled,t)!==!1&&q(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&vt(t,e)}return!1}n(bt,"shouldFetchOn");function Is(t,e,s,r){return(t!==e||L(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&vt(t,s)}n(Is,"shouldFetchOptionally");function vt(t,e){return L(e.enabled,t)!==!1&&t.isStaleByTime(q(e.staleTime,t))}n(vt,"isStale");function ui(t,e){return!he(t.getCurrentResult(),e)}n(ui,"shouldAssignObserverCurrentProperties");var Os=class extends je{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||St(),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=qe({fn:n(()=>this.options.mutationFn?this.options.mutationFn(t,s):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:n((a,o)=>{this.#n({type:"failed",failureCount:a,error:o})},"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 o=await this.options.onMutate?.(t,s);o!==this.state.context&&this.#n({type:"pending",context:o,variables:t,isPaused:i})}let a=await this.#r.start();return await this.#s.config.onSuccess?.(a,t,this.state.context,this,s),await this.options.onSuccess?.(a,t,this.state.context,s),await this.#s.config.onSettled?.(a,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(a,null,t,this.state.context,s),this.#n({type:"success",data:a}),a}catch(a){try{await this.#s.config.onError?.(a,t,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onError?.(a,t,this.state.context,s)}catch(o){Promise.reject(o)}try{await this.#s.config.onSettled?.(void 0,a,this.state.variables,this.state.context,this,s)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,a,t,this.state.context,s)}catch(o){Promise.reject(o)}throw this.#n({type:"error",error:a}),a}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),C.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(t)}),this.#s.notify({mutation:this,type:"updated",action:t})})}};function St(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}n(St,"getDefaultState");var Rs=class extends K{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 Os({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=We(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=We(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=We(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=We(t);return typeof e=="string"?this.#t.get(e)?.find(r=>r!==t&&r.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){C.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=>Ue(e,s))}findAll(t={}){return this.getAll().filter(e=>Ue(t,e))}notify(t){C.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return C.batch(()=>Promise.all(t.map(e=>e.continue().catch(E))))}};function We(t){return t.options.scope?.id}n(We,"scopeFor");var wt=class extends K{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),he(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??St();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){C.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 As=class extends K{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??Ce(r,e),a=this.get(i);return a||(a=new Ts({client:t,queryKey:r,queryHash:i,options:t.defaultQueryOptions(e),state:s,defaultOptions:t.getQueryDefaults(r)}),this.add(a)),a}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(){C.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=>De(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>De(t,s)):e}notify(t){C.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){C.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){C.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var Ct=class{static{n(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new As,this.#t=t.mutationCache||new Rs,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=ue.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=pe.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=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}),a=this.#e.get(r.queryHash)?.state.data,o=fs(e,a);if(o!==void 0)return this.#e.build(this,r).setData(o,{...s,manual:!0})}setQueriesData(t,e,s){return C.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;C.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){let s=this.#e;return C.batch(()=>(s.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let s={revert:!0,...e},r=C.batch(()=>this.#e.findAll(t).map(i=>i.cancel(s)));return Promise.all(r).then(E).catch(E)}invalidateQueries(t,e={}){return C.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=C.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let a=i.fetch(void 0,s);return s.throwOnError||(a=a.catch(E)),i.state.fetchStatus==="paused"?Promise.resolve():a}));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 pe.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=>{se(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=>{se(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=Ce(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===de&&(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 re=D(te(),1);var Ee=D(te(),1),hi=D(ut(),1);function di(){let t=!1;return{clearReset:n(()=>{t=!1},"clearReset"),reset:n(()=>{t=!0},"reset"),isReset:n(()=>t,"isReset")}}n(di,"createValue");var li=Ee.createContext(di()),Fs=n(()=>Ee.useContext(li),"useQueryErrorResetBoundary");var Ps=D(te(),1);var Ms=n((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?le(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),Ls=n(t=>{Ps.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),xs=n(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||le(s,[t.error,r])),"getHasError");var Be=D(te(),1);var Qs=Be.createContext(!1),_s=n(()=>Be.useContext(Qs),"useIsRestoring"),Eh=Qs.Provider;var Ds=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"),Us=n((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),Ks=n((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),kt=n((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function Ns(t,e,s){let r=_s(),i=Fs(),a=Se(s),o=a.defaultQueryOptions(t);a.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=a.getQueryCache().get(o.queryHash),u=t.subscribed!==!1;o._optimisticResults=r?"isRestoring":u?"optimistic":void 0,Ds(o),Ms(o,i,c),Ls(i);let d=!a.getQueryCache().get(o.queryHash),[h]=re.useState(()=>new e(a,o)),l=h.getOptimisticResult(o),p=!r&&u;if(re.useSyncExternalStore(re.useCallback(f=>{let y=p?h.subscribe(C.batchCalls(f)):E;return h.updateResult(),y},[h,p]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),re.useEffect(()=>{h.setOptions(o)},[o,h]),Ks(o,l))throw kt(o,h,i);if(xs({result:l,errorResetBoundary:i,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw l.error;return a.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!G.isServer()&&Us(l,r)&&(d?kt(o,h,i):c?.promise)?.catch(E).finally(()=>{h.updateResult()}),o.notifyOnChangeProps?l:h.trackResult(l)}n(Ns,"useBaseQuery");function pi(t,e){return Ns(t,gt,e)}n(pi,"useQuery");var J=D(te(),1);function fi(t,e){let s=Se(e),[r]=J.useState(()=>new wt(s,t));J.useEffect(()=>{r.setOptions(t)},[r,t]);let i=J.useSyncExternalStore(J.useCallback(o=>r.subscribe(C.batchCalls(o)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=J.useCallback((o,c)=>{r.mutate(o,c).catch(E)},[r]);if(i.error&&le(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}n(fi,"useMutation");var Ws=D(as(),1);var x=D(te(),1);var $e=n(t=>N(t),"o");var He=D(ut(),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"),Et=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($e(e))}openSnapshotSample(e){let s=$e(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,a,o={}){let c=$e(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,p=>{if(this.pushes.set(c,(this.pushes.get(c)??0)+1),p===void 0){qs(e.getQueryCache().find({exact:!0,queryKey:s}));return}e.setQueryData(s,p)},{onError:n(p=>{for(let f of l.errorCallbacks)f(p)},"onError"),shardKey:a})}catch(p){throw this.entries.delete(c),p}}u.refCount+=1;let{onError:d}=o;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)))}}},js=new WeakMap,Tt=n(t=>{let e=js.get(t);return e||(e=new Et(t),js.set(t,e)),e},"I"),Bs=(0,x.createContext)(null),mi=(0,x.createContext)(!1),yi=n(()=>new Ct({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"q"),bi=n(t=>{let e=(0,Ws.c)(20),{children:s,client:r,queryClient:i}=t,a=(0,x.use)(ve),o;e[0]!==a||e[1]!==i?(o=n(()=>i??a??yi(),"d"),e[0]=a,e[1]=i,e[2]=o):o=e[2];let[c]=(0,x.useState)(o),u=i??a??c,d,h;e[3]!==r||e[4]!==u?(d=n(()=>{Tt(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,x.useEffect)(d,h);let l=(0,x.useRef)(r),p,f;e[7]!==r||e[8]!==u?(p=n(()=>{l.current!==r&&(Tt(l.current).stopClearingOnIdentityChange(u),l.current=r,Tt(r).clearQueries(u),u.invalidateQueries({queryKey:["lunora"]}))},"o"),f=[r,u],e[7]=r,e[8]=u,e[9]=p,e[10]=f):(p=e[9],f=e[10]),(0,x.useEffect)(p,f);let[y]=(0,x.useState)(r),m=r!==y,g;e[11]!==s||e[12]!==m?(g=(0,He.jsx)(mi,{value:m,children:s}),e[11]=s,e[12]=m,e[13]=g):g=e[13];let S;e[14]!==r||e[15]!==g?(S=(0,He.jsx)(Bs,{value:r,children:g}),e[14]=r,e[15]=g,e[16]=S):S=e[16];let k=S;if(a===u)return k;let I;return e[17]!==k||e[18]!==u?(I=(0,He.jsx)(dt,{client:u,children:k}),e[17]=k,e[18]=u,e[19]=I):I=e[19],I},"V");var It=n(()=>{let t=(0,x.use)(Bs);if(!t)throw new b("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"_");var Q=n(t=>new Promise((e,s)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{s(t.error??new Error("IndexedDB request failed"))})}),"c"),Ge=n((t,e,s,r)=>{let i;return()=>{if(i)return i;let a=new Promise((o,c)=>{let u=t.open(e,s);u.addEventListener("upgradeneeded",()=>{r(u.result)}),u.addEventListener("success",()=>{o(u.result)}),u.addEventListener("error",()=>{c(u.error??new Error("IndexedDB open failed"))})});return i=a,a.catch(()=>{i===a&&(i=void 0)}),a}},"E"),ze=n((t,e)=>async(s,r)=>{let i=(await t()).transaction(e,s),a=await r(i.objectStore(e));return await new Promise((o,c)=>{i.addEventListener("complete",()=>{o()}),i.addEventListener("error",()=>{c(i.error??new Error("IndexedDB transaction failed"))}),i.addEventListener("abort",()=>{c(i.error??new Error("IndexedDB transaction aborted"))})}),a},"u");var ne=n((t,e,s)=>`${t}::${e}::${s??""}`,"T"),gi=500,vi=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 Si="lunora-query-cache",wi="query-cache",$s="by_ts",Ci=1,ki=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??Si,r=t.storeName??wi,i=vi(t.maxEntries??gi,"createIndexedDbQueryCache"),a=Ge(e,s,Ci,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex($s,"ts",{unique:!1})}),o=ze(a,r),c=n(async u=>{let d=await Q(u.count())-i;d<=0||await new Promise((h,l)=>{let p=u.index($s).openCursor();p.addEventListener("success",()=>{let f=p.result;if(!f||d<=0){h();return}f.delete(),d-=1,f.continue()}),p.addEventListener("error",()=>{l(p.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:n(async()=>{await o("readwrite",u=>Q(u.clear()))},"clear"),load:n(async()=>o("readonly",u=>Q(u.getAll())),"load"),put:n(async(u,d)=>{await o("readwrite",async h=>{await Q(h.put({...d,key:u})),await c(h)})},"put"),remove:n(async u=>{await o("readwrite",d=>Q(d.delete(u)))},"remove")}},"N"),Hs=n(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return ki()}},"L");var Gs=n(()=>{let t=null;return{get:n(()=>t,"get"),set:n(e=>{t=e},"set")}},"r");var Ve=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 zs=0,Ti="lunora-bridge",Ei=1e3,Ii=3e3,Je=class{static{n(this,"l")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;pendingData=new Map;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(zs+=1,this.tabId=`tab_${String(zs)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??Ei,this.leaderTimeout=e.leaderTimeout??Ii,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??Ti),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,a){this.leader&&(this.pendingData.size===0&&queueMicrotask(()=>{this.flushPendingData()}),this.pendingData.set(e,{type:"subscription-data",tabId:this.tabId,key:e,data:s,...r===void 0?{}:{cursor:r},...i===void 0?{}:{epoch:i},...a===void 0?{}:{identity:a}}))}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,a,o){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},...a===void 0?{}:{clientId:a},...o===void 0?{}:{identity:o}})}broadcastConnectionStatus(e,s){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...s===void 0?{}:{identity:s}})}broadcast(e){this.flushPendingData(),this.bc?.postMessage(e)}flushPendingData(){if(this.pendingData.size===0)return;let e=[...this.pendingData.values()];if(this.pendingData.clear(),!!this.leader)for(let s of e)this.bc?.postMessage(s)}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 Oi=n(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"y"),Ot="_id",Rt="_creationTime",At="page",Vs="pageDelta",Ri=n(t=>{if(Array.isArray(t))return t;if(Oi(t)&&Array.isArray(t[At]))return t[At]},"g"),Ai=n(t=>{let e;for(let s of t){let r=s[Rt];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"A"),Fi=n((t,e)=>{let s=e[Rt];if(typeof s!="number")return t.length;let r=Ai(t);for(let[i,a]of t.entries()){let o=a[Rt];if(typeof o=="number"&&(r?o<s:o>s))return i}return t.length},"x"),Pi=n(t=>{if(typeof t!="object"||t===null)return;let e=t[Ot];return typeof e=="string"?e:void 0},"b"),Mi=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"),Li=n((t,e)=>{let s=[];for(let u of t){if(Pi(u)===void 0)return;s.push(u)}let{key:r,op:i,row:a}=e;if(i==="delete"){let u=s.filter(d=>d[Ot]!==r);return u.length===s.length?[...s]:u}if(a===void 0)return;let o=[...s],c=s.findIndex(u=>u[Ot]===r);return c===-1?o.splice(Fi(s,a),0,a):o[c]=a,o},"E"),xi=n((t,e)=>{let s=Ri(t);if(s===void 0)return;let r=Li(s,e);return r===void 0||Array.isArray(t)?r:{...t,[At]:r}},"I"),Ft=Symbol("lunora.unmergeableDelta"),Js=n((t,e)=>{if("data"in t&&t.data!==void 0)return T(t.data);let s=T(t.delta);return Mi(s)?e===void 0?s:xi(e,s)??Ft:s},"P");var Cd=new Set(Object.keys(ns)),U=class extends b{static{n(this,"R")}constructor(e,s){super("INTERNAL",e,{data:s})}};var Ye=n(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"f"),Pt=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED"]),Ie=n(t=>Pt.has(t?.code??""),"u");var Oe=n((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,a=0;return{next(){let o=Math.min(r,s*2**a);if(a+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){a=0}}},"s");var Qi=1024,Xe=n(t=>{let e=t.maxBuffer??Qi,s=[],r=[],i=!1,a,o=!1,c=n(()=>{let h=r.shift();if(!h)return!1;if(a)return h.reject(a),!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||a))for(i=!0;c(););},fail(h){if(!(i||a)){for(a=h,s.length=0;c(););t.onFail?.()}},push(h){if(!(i||a||o)){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(!o){o=!0,i=!0,s.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:d,[Symbol.asyncIterator](){return{next(){if(a)return Promise.reject(a);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 fe=n(t=>t.reason??Object.assign(new Error("The operation was aborted"),{name:"AbortError"}),"c"),ae=n(async(t,e,s,r=()=>new U(`LunoraClient: request timed out after ${t.toString()}ms`))=>{if(e?.aborted)throw fe(e);let i=new AbortController,a=[],o=new Promise((u,d)=>{if(t>0){let h=setTimeout(()=>{d(r()),i.abort()},t);a.push(()=>{clearTimeout(h)})}if(e){let h=n(()=>{i.abort(),d(fe(e))},"a");e.addEventListener("abort",h,{once:!0}),a.push(()=>{e.removeEventListener("abort",h)})}}),c=s(i.signal);c.catch(()=>{});try{return await Promise.race([c,o])}finally{for(let u of a)u()}},"m"),Mt=n(async(t,e)=>{if(e===void 0)return t;if(e.aborted)throw t.catch(()=>{}),fe(e);let s=n(()=>{},"o"),r=new Promise((i,a)=>{s=n(()=>{a(fe(e))},"o"),e.addEventListener("abort",s,{once:!0})});t.catch(()=>{});try{return await Promise.race([t,r])}finally{e.removeEventListener("abort",s)}},"E"),Ys=n(async(t,e)=>!Number.isFinite(e)||e<=0?t.read():ae(e,void 0,async()=>t.read(),()=>new b("STREAM_IDLE",`stream received nothing for ${e.toString()}ms`)),"y");var Ze=/^ /u,_i=/^\d+$/u,Di=2147483647,Ui=10,Ki=1e3,Xs=n(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"M"),Ni=n(t=>{let e="",s,r,i=[];for(let a of t.split(`
2
+ `))if(a.startsWith("event:"))e=a.slice(6).replace(Ze,"");else if(a.startsWith("data:"))i.push(a.slice(5).replace(Ze,""));else if(a.startsWith("id:")){let o=a.slice(3).replace(Ze,"");o.includes("\0")||(s=o)}else if(a.startsWith("retry:")){let o=a.slice(6).replace(Ze,"");_i.test(o)&&Number.isSafeInteger(Number(o))&&(r=Math.min(Number(o),Di))}return{data:i.join(`
3
+ `),event:e,id:s,retry:r}},"j"),qi=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(Xs(d))}).join("/"),a=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&a.set(c,Xs(u));let o=a.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${o===""?"":`?${o}`}`},"D"),ji=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",a=new b(i,r);return typeof s.why=="string"&&(a.why=s.why),e.fail(a),!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},"U"),er=n((t,e)=>{let s="",r=!1,i=n(o=>{let c=r?`\r${o}`:o;r=c.endsWith("\r"),r&&(c=c.slice(0,-1)),s+=c.replaceAll(`\r
4
+ `,`
5
+ `)},"s"),a=n(()=>{let o=s.indexOf(`
6
+
7
+ `);if(o===-1)return"empty";let c=Ni(s.slice(0,o));return s=s.slice(o+2),e.onFrame?.(),c.id!==void 0&&e.onId?.(c.id),c.retry!==void 0&&e.onRetry?.(c.retry),ji(c,t)?"terminal":"dispatched"},"r");return{append:i,drain:n(()=>{for(;;){let o=a();if(o==="empty")return!1;if(o==="terminal")return!0}},"drain"),next:a}},"O"),Wi=n(async(t,e,s,r,i=0)=>{let a=t.getReader(),o=new TextDecoder,c=er(e,s),u=n(()=>a.cancel().then(()=>{},()=>{}),"a");try{for(;;){let{done:d,value:h}=await Ys(a,i);if(d)break;if(c.append(o.decode(h,{stream:!0})),c.drain())return await u(),!0}return c.append(o.decode()),c.drain()}catch(d){throw r.abort(),u().catch(()=>{}),d}},"J"),tr=n(async(t,e)=>{e.aborted||await new Promise(s=>{let r,i=n(()=>{clearTimeout(r),s()},"s");r=setTimeout(()=>{e.removeEventListener("abort",i),s()},t),e.addEventListener("abort",i,{once:!0})})},"N"),Bi=n(async(t,e,s,r)=>{let i=er(e,s);try{i.append(await t.text())}catch(a){throw r.abort(),a}for(;;){if(r.signal.aborted)return!1;let a=i.next();if(a==="empty")return!1;if(a==="terminal")return!0;await tr(0,r.signal)}},"Y"),$i=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})},"q"),Hi=n(async(t,e)=>{let s,r=new Promise(a=>{s=setTimeout(()=>{a(void 0)},Ki)}),i=t.json().catch(a=>{if(e.aborted)throw a});try{return await Promise.race([i,r])}finally{clearTimeout(s),await t.body?.cancel().catch(()=>{})}},"K"),Gi=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}}},"X"),Zs=n(t=>t instanceof Error&&"code"in t?t:new b("HTTP_STREAM_TRANSPORT",t instanceof Error?t.message:String(t),{cause:t}),"P"),sr=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=qi(t,e??{},s.baseUrl??""),a=new AbortController,o;s.signal&&(s.signal.aborted?a.abort():(o=n(()=>{a.abort()},"i"),s.signal.addEventListener("abort",o,{once:!0})));let c=n(()=>{o&&s.signal?.removeEventListener("abort",o)},"c"),{handle:u,iterable:d}=Xe({maxBuffer:s.maxBuffer,onCancel:n(()=>{a.abort()},"onCancel"),onFail:n(()=>{a.abort()},"onFail")}),h=s.reconnect??!1,l=Oe(),{lastEventId:p}=s,f,y=0,m=n(()=>{l.reset(),y=0},"x"),g={},S=n(w=>{try{w()}catch(O){throw g.value={error:O},O}},"g"),k={onFrame:m,onId:n(w=>{S(()=>s.onEventId?.(w)),p=w},"onId"),onRetry:n(w=>{S(()=>s.onRetry?.(w)),f=w},"onRetry")},I=n(async()=>{let w=Gi(s.headers,p),O=new b("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"),ee=n(R=>{if(a.signal.aborted){u.complete();return}return{completed:R,error:O}},"_"),M=new AbortController,A=n(()=>{M.abort()},"A");a.signal.addEventListener("abort",A,{once:!0});try{let R=await r(i,{headers:w,method:t.method,signal:M.signal});if(!R.ok){let V=await Hi(R,a.signal);u.fail($i(V,R.status)??new b("HTTP_STREAM_STATUS",`httpStream: request failed (status ${R.status.toString()})`,{status:R.status}));return}if(!R.body){if(typeof R.text!="function"){u.fail(new b("HTTP_STREAM_NO_BODY","httpStream: response exposes neither a body stream nor a text() read"));return}return ee(await Bi(R,u,k,M))}return ee(await Wi(R.body,u,k,M,s.idleTimeoutMs))}catch(R){if(a.signal.aborted){u.complete();return}if(g.value){let{error:V}=g.value;u.fail(V instanceof Error?V:new b("HTTP_STREAM_CALLBACK","httpStream: an onEventId/onRetry callback threw"));return}return{completed:!1,error:Zs(R)}}finally{a.signal.removeEventListener("abort",A)}},"L");return(async()=>{try{for(;;){if(a.signal.aborted){u.complete();return}let w=await I();if(!w)return;if(w.completed||!h||y>=Ui){w.completed||u.fail(w.error);return}y+=1,await tr(f??l.next(),a.signal)}}finally{c()}})().catch(w=>{if(a.signal.aborted){u.complete();return}u.fail(Zs(w))}),d},"ee");var et=n(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"a"),Lt=n(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"h"),j=n((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"$"),P=n((t,e)=>{let s=new URLSearchParams;for(let[i,a]of Object.entries(e))a!==void 0&&a!==""&&s.set(i,String(a));let r=s.toString();return r===""?t:`${t}?${r}`},"d"),zi="http://same-origin.invalid",xt=n(t=>new URL(t,zi),"p"),Vi=/^[a-z][a-z\d+.-]*:/iu,Qt=n((t,e)=>{if(Vi.test(e))return t.toString();let s=`${t.pathname}${t.search}${t.hash}`;return e.startsWith("//")?`//${t.host}${s}`:s},"S");var _=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 tt(t){if(t!==void 0)return e=>{t(e)}}n(tt,"b");var Y=n((t,e)=>{for(let s of t)try{s(e)}catch{}},"d");var _t=0,rr=n(()=>_t,"h"),Ji=n((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),ir=n((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),ie=n((t,e)=>{ir(t,Ji(e,t.optimisticLayers))},"y"),Dt=n((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),ir(t,s);let a=n(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"l"),o=n(()=>{ie(t,t.serverBase)},"s");return{confirm:n(c=>{if(c===void 0){a();return}r.commitCursor=c,_t+=1,r.acknowledgedAt=_t,t.serverCursor!==void 0&&t.serverCursor>=c&&a()&&o()},"confirm"),rollback:n(()=>{i||(i=!0,a(),o())},"rollback")}},"g"),st=n((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let s=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(r=>r.commitCursor===void 0||r.commitCursor>e),t.optimisticLayers.length!==s},"k"),nr=n((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"b"),oe=n(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"v"),ar=n((t,e)=>{let s=[],r=[],i=n((a,o)=>t.get(_.key(a,o,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:n(a=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===a.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:n((a,o)=>i(a.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:n((a,o,c)=>{let u=i(a.__lunoraRef,o??{});if(!u)return;let d=Dt(u,()=>c);d&&(s.push(d.confirm),r.push(d.rollback))},"setQuery")}}},"_");var Ut=n(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let s=Date.parse(t);if(Number.isNaN(s))return;let r=s-Date.now();return r>0?r:void 0},"f"),Yi=n((t,e)=>{let s=Ut(e);if(!(s===void 0||Ye(t)!==void 0))return t.data===void 0?{retryAfterMs:s}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:s}:void 0},"v"),me=n(t=>{let e=t?.error;if(typeof e!="object"||e===null||Array.isArray(e))return;let{why:s,...r}=e;return typeof s=="string"?{...r,why:s}:r},"l"),Kt=n(()=>new U("LunoraClient: batch slot carried no error envelope"),"p"),or=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"),cr=n(t=>{let{code:e,messageText:s}=or(t,"stream error"),r=t.error?.why,i=e===void 0?new Error(s):new b(e,s);return typeof r=="string"&&(i.why=r),i},"h"),Nt=n(t=>{let{code:e,messageText:s}=or(t,"subscription error"),r=t.error?.why;return{message:s,...e===void 0?{}:{code:e},...typeof r=="string"?{why:r}:{}}},"w"),Xi=Symbol.for("lunora.serverVerdict"),Re=n(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,e[Xi]=!0,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=Re(t),r=Yi(s,e);return r!==void 0&&(s.data=r),s},"b"),rt=n(t=>{let e=me(t);return e===void 0?Kt():Re(e)},"A");var ur=0,Zi=n(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();ur+=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)}_${ur.toString(36)}_${t}`},"d"),jt=n((t,e)=>t!==void 0&&e!==t,"f"),nt=Zi,ye=n((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"h"),it=class{static{n(this,"p")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;onReplayingChange;version;items=[];replayingIds=new Set;appending=new Map;unsettled=new Map;unpersisted=new Set;constructor(e={},s={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=s.persistence,this.onEvict=s.onEvict,this.onSizeChange=s.onSizeChange,this.onReplayingChange=s.onReplayingChange,this.version=s.version}get size(){return this.items.length}get replaying(){return this.replayingIds.size}enqueue(e){let s=e;s.id??=nt();let r=this.items.length;for(;s.issueSeq!==void 0&&r>0&&(this.items[r-1]?.issueSeq??-1)>s.issueSeq;)r-=1;this.items.splice(r,0,s),this.unsettled.set(s.id,s),this.persist(this.recordOf(s,s.id)),this.evictOverflow(),this.notifySize()}discard(e){this.unsettled.delete(e),this.unpersisted.delete(e),this.replayingIds.delete(e)&&this.onReplayingChange?.();let{persistence:s}=this;s&&(this.appending.get(e)??Promise.resolve()).then(async()=>s.remove(e)).catch(r=>{ye(this.onPersistenceError,"remove",r,e)})}flushUnpersisted(){for(let e of this.unpersisted){let s=this.unsettled.get(e);s&&!this.appending.has(e)&&this.persist(this.recordOf(s,e))}}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(o){throw ye(this.onPersistenceError,"load",o),o}let s=[],r=new Set(this.items.map(o=>o.id));for(let o of e)if(!r.has(o.id)){if(jt(this.version,o.version)){this.persistence.remove(o.id).catch(c=>{ye(this.onPersistenceError,"remove",c,o.id)});continue}r.add(o.id),s.push({args:o.args,baselineSeq:o.baselineSeq,clientId:o.clientId,functionPath:o.functionPath,id:o.id,identity:o.identity,reject:n(()=>{},"reject"),resolve:n(()=>{},"resolve"),shardKey:o.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),a=new Set;for(let o of s)i.has(o)&&a.add(o.shardKey);return[...a]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;!this.persistence||i===void 0||this.rewriteStamp(i,this.recordOf(r,i)).catch(a=>{ye(this.onPersistenceError,"replace",a,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.markReplaying(i),this.notifySize(),i}let s=[],r=[];for(let i of this.items)(e(i)?s:r).push(i);return this.items.length=0,this.items.push(...r),this.markReplaying(s),this.notifySize(),s}requeue(e){if(e.length!==0){for(let s of e)s.id!==void 0&&this.replayingIds.delete(s.id);this.items.unshift(...e),this.notifySize()}}drainConflict(){let e=[],s=[];for(let r of this.items)if(r.precondition!==void 0&&!r.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",r.reject(i),e.push(r)}else s.push(r);return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of new Set([...this.items,...this.unsettled.values()])){let s=new Error("CLIENT_CLOSED"),r=e.id??"",i=n(o=>{s.code="CLIENT_CLOSED",s.persisted=o,e.reject(s)},"s"),a=this.appending.get(r);this.replayingIds.has(r)?i(!1):a===void 0?i(this.persistence!==void 0&&!this.unpersisted.has(r)):a.catch(()=>!1).then(i).catch(()=>{})}this.items.length=0,this.replayingIds.clear(),this.unsettled.clear(),this.unpersisted.clear(),this.notifySize()}recordOf(e,s){return{args:e.args,...e.baselineSeq===void 0?{}:{baselineSeq:e.baselineSeq},clientId:e.clientId,functionPath:e.functionPath,id:s,identity:e.identity,shardKey:e.shardKey,...this.version===void 0?{}:{version:this.version}}}persist(e){let{persistence:s}=this;if(!s)return;let r=(async()=>{try{return await s.append(e),this.unpersisted.delete(e.id),!0}catch(i){return this.unsettled.has(e.id)&&this.unpersisted.add(e.id),ye(this.onPersistenceError,"append",i,e.id),!1}})();this.appending.set(e.id,r),r.finally(()=>{this.appending.get(e.id)===r&&this.appending.delete(e.id)}).catch(()=>{})}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await this.appending.get(e),await r.replace(s)}catch(i){ye(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.discard(e.id);let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}markReplaying(e){for(let s of e)s.id!==void 0&&this.replayingIds.add(s.id)}notifySize(){this.onSizeChange?.(this.items.length)}};var en="lunora-outbox",tn="offline-mutations",Wt="by_id",sn=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??en,r=t.storeName??tn,i=Ge(e,s,1,o=>{o.objectStoreNames.contains(r)||o.createObjectStore(r,{autoIncrement:!0}).createIndex(Wt,"id",{unique:!0})}),a=ze(i,r);return{append:n(async o=>{await a("readwrite",c=>Q(c.add(o)))},"append"),clear:n(async()=>{await a("readwrite",o=>Q(o.clear()))},"clear"),load:n(async()=>a("readonly",o=>Q(o.getAll())),"load"),remove:n(async o=>{await a("readwrite",async c=>{let u=await Q(c.index(Wt).getKey(o));u!==void 0&&await Q(c.delete(u))})},"remove"),replace:n(async o=>{await a("readwrite",async c=>{let u=await Q(c.index(Wt).getKey(o.id));u!==void 0&&await Q(c.put(o,u))})},"replace")}},"w"),hr=n((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return sn()}},"b");var dr=n((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),a=i.present?N(i.value):void 0;return()=>{let o=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!o.present?!0:N(o.value)===a}},"c");var Bt=500,Sr=n((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"_e"),X="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",nn=n(t=>{let e="",s=0,r=t.length-2;for(;s<r;s+=3){let a=t[s]<<16|t[s+1]<<8|t[s+2];e+=X.charAt(a>>18&63)+X.charAt(a>>12&63)+X.charAt(a>>6&63)+X.charAt(a&63)}let i=t.length-s;if(i===1){let a=t[s]<<16;e+=X.charAt(a>>18&63)+X.charAt(a>>12&63)}else if(i===2){let a=t[s]<<16|t[s+1]<<8;e+=X.charAt(a>>18&63)+X.charAt(a>>12&63)+X.charAt(a>>6&63)}return e},"Tt");new TextDecoder;var an=new TextEncoder,on=n(t=>nn(an.encode(JSON.stringify(t))),"Ct"),cn="x-lunora-expect-subject",un=n(t=>on({subject:t}),"Et"),lr=Symbol.for("lunora:session-change"),hn="lunora:session-change",dn="better-auth.message",ln="signout",wr=n(()=>{let t=globalThis,e=t[lr];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[lr]=e),e},"Ie"),pn=n(()=>"document"in globalThis,"Ot"),fn=n(async()=>{let t=[];for(let e of wr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"Rt"),mn=n((t,e)=>{if(t!==dn||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===ln}catch{return!1}},"Pt"),yn=n(t=>{let e=[],s=n(()=>{fn().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(hn):void 0}catch{r=void 0}if(r!==void 0){let a=r;a.addEventListener("message",o=>{o.data?.type==="lunora:session-change"&&o.data.tab!==t&&s()}),e.push(()=>{a.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let a=n(o=>{mn(o.key,o.newValue)&&s()},"r");i.addEventListener("storage",a),e.push(()=>{i.removeEventListener?.("storage",a)})}return()=>{for(let a of e)a()}},"Ft"),bn=n(t=>{let e=wr();return e.listeners.add(t),e.detach===void 0&&pn()&&(e.detach=yn(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"Lt"),gn="/_lunora/rpc",$t="/_lunora/rpc-batch",Ht="/_lunora/ws",vn="/_lunora/admin/shard-traffic",Sn="/_lunora/admin/scheduled",wn="/_lunora/admin/scheduled/status",Cn="/_lunora/admin/scheduled/ws",kn="/_lunora/admin/scheduled/cancel",pr="/_lunora/admin/scheduled/dead",Tn="/_lunora/admin/scheduled/dead/retry",En="/_lunora/admin/scheduled/dead/cancel",In="/_lunora/admin/workflows/instances",On="/_lunora/admin/workflows/instance",Rn="/_lunora/admin/workflows/status",ts="/_lunora/admin/storage",An="/_lunora/admin/storage/url",Fn="/_lunora/admin/storage/buckets",Pn="/_lunora/admin/functions",Mn="/_lunora/admin/cron-jobs",Ln="/_lunora/admin/cron-jobs/run",xn="/_lunora/admin/architecture",Qn="/_lunora/admin/openapi",_n="/_lunora/admin/openrpc",Dn="/_lunora/admin/global/tables",Un="/_lunora/admin/global/table",Kn="/_lunora/admin/global/facet",Nn="/_lunora/admin/vector/indexes",qn="/_lunora/admin/vector/query",jn="/_lunora/admin/logs/archive",Wn="/_lunora/admin/kv/namespaces",Bn="/_lunora/admin/kv/keys",ss="/_lunora/admin/kv/value",$n="/_lunora/admin/auth/users",Hn="/_lunora/admin/auth/sessions",Gn="/_lunora/admin/auth/users/create",zn="/_lunora/admin/auth/users/role",Vn="/_lunora/admin/auth/users/ban",Jn="/_lunora/admin/auth/users/unban",Yn="/_lunora/admin/auth/users/password",Xn="/_lunora/admin/auth/users/remove",Zn="/_lunora/admin/auth/users/impersonate",ea="/_lunora/admin/auth/sessions/revoke",ta="/_lunora/admin/auth/sessions/revoke-all",sa="/_lunora/admin/auth/capabilities",ra="/_lunora/admin/auth/users/update",ia="/_lunora/admin/auth/accounts",na="/_lunora/admin/auth/accounts/unlink",aa="/_lunora/admin/auth/passkeys",oa="/_lunora/admin/auth/passkeys/delete",ca="/_lunora/admin/auth/two-factor/disable",ua="/_lunora/admin/auth/organizations",ha="/_lunora/admin/auth/organizations/members",da="/_lunora/admin/auth/organizations/invitations",la="/_lunora/admin/auth/organizations/members/remove",pa="/_lunora/admin/auth/organizations/invitations/cancel",fa="/_lunora/admin/auth/config",ma="/_lunora/admin/auth/sign-up-invitations",ya="/_lunora/admin/auth/sign-up-invitations/create",ba="/_lunora/admin/auth/sign-up-invitations/revoke",ga="/_lunora/admin/auth/organizations/create",va="/_lunora/admin/auth/organizations/update",Sa="/_lunora/admin/auth/organizations/remove",wa="/_lunora/admin/auth/organizations/members/add",Ca="/_lunora/admin/auth/organizations/members/invite",ka="/_lunora/admin/auth/organizations/members/role",Ta="/_lunora/admin/auth/organizations/teams",Ea="/_lunora/admin/auth/organizations/teams/create",Ia="/_lunora/admin/auth/organizations/teams/update",Oa="/_lunora/admin/auth/organizations/teams/remove",Ra="/_lunora/admin/auth/organizations/teams/members",Aa="/_lunora/admin/auth/organizations/teams/members/add",Fa="/_lunora/admin/auth/organizations/teams/members/remove",Pa="/_lunora/admin/auth/organizations/roles",Ma="/_lunora/admin/auth/organizations/roles/create",La="/_lunora/admin/auth/organizations/roles/update",xa="/_lunora/admin/auth/organizations/roles/remove",Qa="/api/auth",_a="/get-session",Da="lunora-ping",Ua=n(async t=>(t.assertOpen(),(await t.adminFetch(Pn,"GET")).functions??[]),"ei"),Ka=n(async t=>(t.assertOpen(),(await t.adminFetch(Mn,"GET")).jobs??[]),"ti"),Na=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(Ln,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}},"si"),qa=n(async t=>(t.assertOpen(),await t.adminFetch(Qn,"GET")),"ii"),ja=n(async t=>(t.assertOpen(),await t.adminFetch(xn,"GET")),"ni"),Wa=n(async t=>(t.assertOpen(),await t.adminFetch(_n,"GET")),"ri"),Ba=n(async t=>(t.assertOpen(),await t.adminFetch(Dn,"GET")),"oi"),$a=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(B(e.filters))),T(await t.adminFetch(`${Un}?${s.toString()}`,"GET"))},"ai"),Ha=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(B(e.filters))),T(await t.adminFetch(`${Kn}?${s.toString()}`,"GET"))},"ci"),Ga=n(async t=>(t.assertOpen(),(await t.adminFetch(Wn,"GET")).namespaces??[]),"di"),za=n(async(t,e)=>{t.assertOpen();let s=P(Bn,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await t.adminFetch(s,"GET")},"hi"),Va=n(async(t,e)=>{t.assertOpen();let s=P(ss,{key:e.key,namespace:e.namespace});return await t.adminFetch(s,"GET")},"ui"),Ja=n(async(t,e)=>{t.assertOpen(),await t.adminFetch(ss,"PUT",e)},"li"),Ya=n(async(t,e)=>{t.assertOpen();let s=P(ss,{key:e.key,namespace:e.namespace});await t.adminFetch(s,"DELETE")},"fi"),Xa=n(async(t,e)=>{t.assertOpen();let s=await t.adminFetch(vn,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}},"pi"),Za=n(async(t,e={})=>{t.assertOpen();let s=await t.adminFetch(jn,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}},"mi"),eo=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}},"yi"),rs=n(t=>"args"in t?{...t,args:T(t.args)}:t,"ae"),to=n(async t=>(t.assertOpen(),((await t.adminFetch(Sn,"GET")).records??[]).map(e=>rs(e))),"Si"),so=n(async t=>{t.assertOpen();let e=await t.adminFetch(wn,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}},"bi"),ro=n(async(t,e)=>(t.assertOpen(),{cancelled:(await t.adminFetch(kn,"POST",{id:e})).cancelled===!0}),"vi"),io=n(async t=>(t.assertOpen(),(await eo(async e=>await t.adminFetch(e===void 0?pr:`${pr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>rs(e))),"gi"),no=n(async(t,e)=>(t.assertOpen(),{retried:(await t.adminFetch(Tn,"POST",{id:e})).retried===!0}),"Ti"),ao=n(async(t,e)=>(t.assertOpen(),{removed:(await t.adminFetch(En,"POST",{id:e})).removed===!0}),"ki"),oo=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(`${In}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}},"Ci"),co=n(async(t,e)=>{t.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await t.adminFetch(`${On}?${s.toString()}`,"GET");return{createdOn:r.createdOn,endedOn:r.endedOn,error:r.error,id:r.id??e.id,output:r.output,params:r.params,startedOn:r.startedOn,status:r.status??"unknown",steps:r.steps??[]}},"wi"),uo=n(async(t,e)=>(t.assertOpen(),{status:(await t.adminFetch(Rn,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}),"Ei"),ho=n(async(t,e={})=>{t.assertOpen();let s=P(ts,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await t.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}},"Ai"),lo=n(async(t,e,s)=>{t.assertOpen();let r=`${ts}?key=${encodeURIComponent(e)}${et(s?.bucket)}`,i=await t.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}},"_i"),po=n(async t=>(t.assertOpen(),(await t.adminFetch(Fn,"GET")).buckets??[]),"Ii"),fo=n(async(t,e)=>{t.assertOpen();let s=`${ts}?key=${encodeURIComponent(e.key)}${et(e.bucket)}`,r=await t.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}},"Oi"),mo=n(async(t,e,s)=>{t.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,a=`${An}?key=${encodeURIComponent(e)}${i}${et(s?.bucket)}`,o=await t.adminFetch(a,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url},"Ri"),yo=n(async t=>(t.assertOpen(),(await t.adminFetch(Nn,"GET")).indexes??[]),"Pi"),bo=n(async(t,e)=>(t.assertOpen(),(await t.adminFetch(qn,"POST",e)).matches??[]),"Fi"),z=n((t,e)=>{try{return B(t)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${r}`,s instanceof Error?{cause:s}:void 0)}},"A"),Vt=n(t=>{try{return B(t),!0}catch{return!1}},"ee"),Cr=n(t=>t!==null&&typeof t=="object"&&("error"in t||"result"in t),"Oe"),go=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(!Cr(r.body)){s[r.id]={error:rt({}),ok:!1};continue}let i=r.body;s[r.id]="error"in i?{error:rt(i),ok:!1}:{ok:!0,value:T(i.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"Li"),Gt=n((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"J"),at=n(t=>t==="connected"||t==="polling","q"),v=n(t=>t??"","l"),W=n((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"k"),vo=n(t=>{if(!t.pendingStreams||t.pendingStreams.length===0)return;let e=t.pendingStreams;t.pendingStreams=[];for(let s of e)W(t,s)},"Mi"),So=new TextDecoder,wo=n(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return So.decode(t)},"Ui"),Z=class{static{n(this,"R")}listeners=new Set;get size(){return this.listeners.size}add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[s]=e;for(let r of this.listeners)try{r(s)}catch{}}clear(){this.listeners.clear()}},be=n(t=>{t.heartbeatTimer!==void 0&&(clearInterval(t.heartbeatTimer),t.heartbeatTimer=void 0)},"H"),Co=n((t,e,s)=>{be(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(Da)}catch{}},e))},"Ni"),fr=n((t,e,s,r)=>{let{WebSocketImpl:i,connectTimeoutMs:a,heartbeatIntervalMs:o}=s;if(i===void 0)throw new b("INTERNAL","no WebSocket implementation available");let c=new i(e);t.socket=c;let u=n(()=>{be(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)},"h");a>0&&(t.connectTimer=setTimeout(()=>{if(t.connectTimer=void 0,t.socket===c){try{c.close()}catch{}d()}},a)),c.addEventListener("open",()=>{if(t.socket===c){t.connectTimer!==void 0&&(clearTimeout(t.connectTimer),t.connectTimer=void 0),t.lastFrameAt=Date.now();try{r.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}t.socket===c&&Co(t,o,d)}}),c.addEventListener("message",h=>{if(t.socket===c){t.lastFrameAt=Date.now();try{r.onMessage(h)}catch(l){console.error("[lunora] server frame handler threw",l)}}}),c.addEventListener("close",h=>{t.socket===c&&d(h)}),c.addEventListener("error",()=>{t.socket===c&&d()})},"Te"),ko=n(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:a}=t,o=s>0&&e>0,c=0,u,d=!1,h=!1,l=n(()=>{u!==void 0&&(clearInterval(u),u=void 0,d=!1,i())},"u"),p=n(y=>{if(u!==void 0){if(!y){l();return}d||(d=!0,i()),r()}},"f"),f=n(()=>{h||(h=!0,a().then(p).finally(()=>{h=!1}).catch(()=>{}))},"p");return{isPolling:n(()=>u!==void 0&&d,"isPolling"),noteFailedOpen:n(()=>{c+=1,!(!o||u!==void 0||c<e)&&(u=setInterval(f,s),i(),f())},"noteFailedOpen"),noteOpen:n(()=>{c=0,l()},"noteOpen"),stop:l}},"Wi"),To=1e4,mr=n(async t=>ae(To,void 0,t,()=>new TypeError("LunoraClient: poll timed out")),"ke"),kr=new Set(["DELIVERY_FENCED","RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),yr=n(t=>{if(t instanceof U)return!0;let e=t?.code;return e===void 0||kr.has(e)||Pt.has(e)},"Ce"),Eo=1e3,Tr=6e4,Io={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Ae=n((t,e,s)=>{let r=Ut(s),i=r===void 0?void 0:{retryAfterMs:r},a=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new U(a,i):new b(Io[t]??"BAD_REQUEST",a,{data:i})},"W"),Jt=n((t,e=Math.random)=>{let s=Math.min(Eo*2**Math.max(t-1,0),Tr);return Math.round(s*(.5+e()*.5))},"te"),Oo=n(t=>{let e=t?.code;return t instanceof U||e===void 0||kr.has(e)},"Qi"),Ro=n((t,e,s)=>{let r=Ye(t);return r!==void 0&&r>0?Math.min(r,Tr):Oo(t)?Jt(e,s):void 0},"qi"),Ao=983040,Fo=n(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Gi"),Er=new WeakSet,Ir=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 Er.add(e),e},"Le"),ot=n(t=>t instanceof Error&&Er.has(t),"K"),Po=n(t=>{let e=new Map;for(let s of t)typeof s.id=="number"&&Cr(s.body)&&e.set(s.id,s.body);return e},"ji"),Mo=n(t=>{if(t===void 0)return{kind:"unanswered"};if("error"in t)return{error:rt(t),kind:"errored"};try{return{commitCursor:t.commitCursor,kind:"committed",value:T(t.result)}}catch(e){return{commitCursor:t.commitCursor,error:Ir(e),kind:"undecodable"}}},"$i"),zt=n((t,e)=>`${v(t)}\0${e}`,"Y"),Lo=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)},"Vi"),Yt=class{static{n(this,"zi")}constructor(e){this.maxBuffers=e}maxBuffers;buffers=new Map;start(e,s){Sr(this.buffers,this.maxBuffers),this.buffers.set(zt(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(zt(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 a=r.parts.get(s.shapeId)??[];for(let c of i)a.push(c);r.parts.set(s.shapeId,a),s.lastMutationId!==void 0&&r.lastMutationId.set(s.shapeId,s.lastMutationId);let o=s.baseCheckpoint??r.baseCheckpoint;o!==void 0&&r.bases.set(s.shapeId,o),s.reset===!0&&r.resets.add(s.shapeId)}end(e,s){let r=zt(e,s),i=this.buffers.get(r);return i&&this.buffers.delete(r),i}clear(){this.buffers.clear()}},xo=n((t,e,s)=>{let r=e.parts.get(t.id)??[],i=e.resets.has(t.id),a=e.bases.get(t.id),o=e.epoch!==void 0&&t.serverEpoch!==void 0&&e.epoch!==t.serverEpoch,c=a!==void 0&&t.serverCursor!==void 0&&t.serverCursor!==a;if(!i&&(o||c))return t.rows.clear(),t.serverCursor=void 0,t.serverEpoch=void 0,t.answered=!1,"reseed";i&&t.rows.clear(),Lo(t.rows,r),t.answered=!0,s.checkpoint!==void 0&&(t.serverCursor=s.checkpoint),s.epoch!==void 0&&(t.serverEpoch=s.epoch);let u=e.lastMutationId.get(t.id);return u!==void 0&&(t.lastMutationId=u),"applied"},"Ji"),br=n(t=>{let e=[...t.rows.values()];for(let s of t.callbacks)try{s(e)}catch{}},"we"),Qo=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)}`})}},"Yi"),Xt=n((t,e)=>{t.lastMutationId=Math.max(t.lastMutationId??0,e)},"se"),Zt=n((t,e=!1)=>{for(let s of t.checkpointCallbacks)s({checkpoint:t.serverCursor,mutationId:t.lastMutationId,...e&&{rowsFollow:!0}})},"ie"),Or=n((t,e,s)=>{t.serverBase=e,s.cursor!==void 0&&(t.serverCursor=s.cursor),s.epoch!==void 0&&(t.serverEpoch=s.epoch)},"Me"),_o=n((t,e)=>e.cursor!==void 0&&t.serverCursor!==void 0&&t.serverBase!==void 0&&e.epoch!==void 0&&e.epoch===t.serverEpoch&&e.cursor<t.serverCursor,"Xi"),ct=n((t,e)=>t!==void 0&&t!==e,"G"),Do=n((t,e)=>e==="connected"&&t!=="connected"||e==="polling"&&t!=="connected"&&t!=="polling","Zi"),Uo=n(t=>{for(let e of t.activeSubscriptions())e.valueReceived=!1,t.ensureSocket(e.shardKey),t.queueResubscribe(e);for(let e of t.activeShapes())e.answered=!1,t.ensureSocket(e.shardKey);for(let e of t.queuedShardKeys())t.ensureSocket(e);t.broadcastStatus(t.computeStatus(),t.identityFingerprint()),t.emitConnectionStatus()},"en"),Ko=n(t=>{t.closeConnections();let e=t.leader;e.status=void 0,e.wasEverConnected=!1;for(let s of t.activeSubscriptions())s.acked=!1,s.valueReceived=!1;for(let s of t.activeShapes())s.answered=!1;t.emitConnectionStatus()},"tn"),No=n((t,e,s)=>{if(ct(s,t.identityFingerprint()))return;let r=t.leader,i=Do(r.status,e);r.status=e,e==="connected"&&(r.wasEverConnected=!0),t.emitConnectionStatus(),i&&t.flushOfflineQueues()},"sn"),qo=n(t=>{t.isLeader()&&t.broadcastStatus(t.computeStatus(),t.identityFingerprint())},"nn"),jo=n((t,e,s,r,i,a)=>{if(ct(a,t.identityFingerprint()))return;let o=t.subscription(e);if(!o)return;t.dropCacheSeed(e);let c=!o.valueReceived;o.valueReceived=!0,Or(o,s,r===void 0?{}:{cursor:r,epoch:i}),r!==void 0&&st(o,r),ie(o,s),c&&t.emitConnectionStatus()},"rn"),Wo=n((t,e,s,r)=>{if(ct(r,t.identityFingerprint()))return;let i=t.subscription(e);if(i){let a=!i.valueReceived;i.valueReceived=!0,Y(i.errorCallbacks,s),a&&t.emitConnectionStatus()}},"on"),Bo=n((t,e,s,r,i,a,o)=>{if(ct(o,t.identityFingerprint()))return;let c=t.subscription(e);c&&(t.ackAndAdvanceCursor(c,s,r),i!==void 0&&a===t.clientIdentifier()&&Xt(c,i),Zt(c))},"an"),$o=n((t,e,s)=>t!==null||e&&s===null,"cn"),Ho=n(t=>t.sensitive===!0,"dn"),Go=n((t,e)=>{if(!Ho(t))return e;if(e.onlineOnly===!1)throw new b("BAD_REQUEST",`'${t.__lunoraRef}' takes a sensitive argument and is always online-only; onlineOnly: false is not allowed`);return{...e,onlineOnly:!0}},"hn"),zo=[Vs],Vo=100,Rr=1e4,Jo=1e4,Yo=n((t,e)=>{let s,r=new Promise((a,o)=>{s=setTimeout(()=>{o(new Error("ws ticket mint timed out"))},e)}),i=(async()=>t())();return Promise.race([i,r]).finally(()=>{clearTimeout(s)})},"pn"),gr=n(async t=>typeof t=="function"?await t():t,"Ee"),Xo=n(async(t,e,s,r)=>{let i=new AbortController,a=setTimeout(()=>{i.abort()},Rr);try{let o=await t(e,{body:s,credentials:"include",headers:r,method:"POST",signal:i.signal});return await o.text(),o.status}finally{clearTimeout(a)}},"mn"),vr=n((t,e)=>new b("OFFLINE_NOT_QUEUED",`'${t}' is online-only and the connection is not live, so it was not queued`,{cause:e}),"Ae"),Zo=n((t,e)=>t instanceof TypeError&&Vt(e),"yn"),ec=n((t,e,s,r)=>e||t===!0&&s&&!r,"Sn"),tc=Promise.resolve(),es=class t{static{n(this,"Ue")}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;wsTicket;wsCredentialGeneration=0;refusedCredentialGeneration;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;rpcTimeoutMs;managedSocketOptions;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;mutationIssueCounter=0;persistence;persistenceVersion;releasePageHideFlush;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new _;tabCoordinator;leader={status:void 0,wasEverConnected:!1};connections=new Map;idleClosedShards=new Set;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new Z;statusListeners=new Z;roomFlushes=new Map;roomIdentityResets=new Set;tokenExpiredListeners=new Z;identityChangeListeners=new Z;retiredIdentities=0;authRefusalNotifiedFor;replayCredentials=new WeakMap;mutationSettledListeners=new Z;pendingChangeListeners=new Z;syncStatusListeners=new Z;lastSyncStatus;whisperHandlers=new Map;liveSocketGrants=new Map;liveControlChain=Promise.resolve();whisperJoins=new Map;nextLiveSocketId=0;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;supplementaryBounces=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayAttempts=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeAssembler=new Yt(t.MAX_POKE_BUFFERS);nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??j(Lt(e.url),Ht),this.wsToken=e.wsToken,this.wsTicket=e.wsTicket;let s=e.authBasePath??Qa;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??Gs(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??3e4,this.connectTimeoutMs=e.connectTimeoutMs??1e4,this.rpcTimeoutMs=e.rpcTimeoutMs??3e4,this.managedSocketOptions={connectTimeoutMs:this.connectTimeoutMs,heartbeatIntervalMs:this.heartbeatIntervalMs,WebSocketImpl:this.WebSocketImpl},this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??5e3,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??3,this.defaultConnectionContext=e.connectionContext,this.persistence=hr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Hs(e.queryCache),this.clientQueryStore=new Ve,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=tc),this.offlineQueue=new it(e.offlineQueue,{onEvict:n((r,i)=>{this.emitItemSettled(r,"rejected",i),this.releaseIdleShard(r.shardKey)},"onEvict"),onReplayingChange:n(()=>{this.emitSyncStatus()},"onReplayingChange"),onSizeChange:n(r=>{this.pendingChangeListeners.emit(r),this.emitSyncStatus()},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${nt()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.installPageHideFlush(),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=bn(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),a=this.authSubject===void 0||this.subjectToken===this.authToken,o=this.subjectAwaitingReconfirm(),c=this.isKnownNobody(),u=this.authToken;this.authToken=e,this.applySubject(e,s);let d=this.identityFingerprint();d!==i&&(!r&&e!==null&&a?(this.restampQueuedIdentity(i,d),this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&a&&!c?(this.restampWatermarks(i,d),this.restampConnectionIdentity(i,d),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),this.warnRefreshWithoutSubject(u,e),$o(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(o),r&&this.authTokenListeners.emit(e),(d!==i||r||o)&&this.offlineQueue.size>0&&at(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){let s=this.identityVerdict(e);if(s!=="match")return{verdict:s};let r=Object.freeze({});return this.replayCredentials.set(r,{authToken:this.authToken,stamp:e}),{credential:r,verdict:s}}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,s,r){let i=r?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new b("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let a=r?.shardKey??"",o=this.identityFingerprint(),c,u,d;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:n(h=>{c=h},"onMutationAck")})}catch(h){if(!ot(h))throw h;d=h}if(c!==void 0&&c>(this.clientWatermarks.get(o??"")?.get(a)??0)){let h=this.clientWatermarks.get(o??"");h===void 0&&(Sr(this.clientWatermarks,8),h=new Map,this.clientWatermarks.set(o??"",h)),h.set(a,c)}if(d!==void 0)throw d;return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}identityEpoch(){return this.retiredIdentities}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;let e={},s=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let r=this.sessionProbeGeneration;try{let i=await this.fetchImpl(j(this.url,`${this.authBasePath}${_a}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let a=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,a,r),a}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.applyWsCredentialChange())}setWsTicket(e){this.wsTicket!==e&&(this.wsTicket=e,this.applyWsCredentialChange())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=v(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=v(s.shardKey),i={context:e},a=this.connectionContextHolders.get(r);a?a.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let o=!1;return()=>{if(o)return;o=!0;let c=this.connectionContextHolders.get(r);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(r),this.refreshConnectionContext(r),this.releaseIdleShard(s.shardKey)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=v(r.shardKey),a=this.whisperHandlers.get(i);a||(a=new Map,this.whisperHandlers.set(i,a));let o=a.get(e),c=o===void 0;if(o||(o=new Set,a.set(e,o)),o.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&this.sendWhisperJoin(u,i,e)}return()=>{let u=this.whisperHandlers.get(i),d=u?.get(e);if(!d?.delete(s)||d.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let h=this.getConnection(r.shardKey);h&&W(h,{topic:e,type:"whisper_unsubscribe"}),this.releaseWhisperJoin(i,e),this.releaseIdleShard(r.shardKey)}}subscribeLiveTopic(e){let{onError:s,onEvent:r,shardKey:i,stream:a,topic:o}=e;if(o.length===0)throw new b("INTERNAL","LunoraClient: subscribeLiveTopic needs a non-empty topic");this.nextLiveSocketId+=1;let c=`ws-live-${String(this.nextLiveSocketId)}`,u=v(i),d=`/live/${a}/control`,h=this.whisperSubscribe(o,()=>{},{shardKey:i}),l=n(()=>{let m=h;h=void 0,m?.()},"f"),p=this.liveSocketGrants.get(u);p===void 0&&(p=new Map,this.liveSocketGrants.set(u,p)),p.set(c,{onError:s,onEvent:r,release:l,stream:a,topic:o});let f=this.getConnection(i)?.connectionId;f!==void 0&&this.grantWhenJoined(i,c,f);let y=!1;return()=>{if(y)return;y=!0;let m=this.liveSocketGrants.get(u),g=m?.delete(c)===!0;m?.size===0&&this.liveSocketGrants.delete(u);let S=this.getConnection(i)?.connectionId;g&&S!==void 0&&this.postLiveControl(d,i,{action:"unsubscribe",connectionId:S,stream:a,subscriptionId:c,topic:o}),l()}}whisper(e,s,r={}){return this.assertLeaderOwnedSurface("whisper"),this.sendEncodedWhisper(e,z(s??null,`whisper data for topic '${e}'`),r)}connectRoom(e,s,r={}){let i=`room:${e.name}`,a=this.whisperSubscribe(i,p=>{s.onMessage(p)},r),o=!1,c=[],u=n(()=>{c.length=0},"c"),d=n(()=>{for(;c.length>0&&this.roomSendsAdmitted(r.shardKey);){if(!this.sendEncodedWhisper(i,c[0],r))return;c.shift()}},"h"),h=v(r.shardKey),l=this.roomFlushes.get(h)??new Set;return l.add(d),this.roomFlushes.set(h,l),this.roomIdentityResets.add(u),{close:n(()=>{o=!0,c.length=0,l.delete(d),l.size===0&&this.roomFlushes.delete(h),this.roomIdentityResets.delete(u),a()},"close"),send:n(p=>{if(o||this.closed||this.WebSocketImpl===void 0)return!1;let f=z(p,`room message for '${i}'`),y=typeof structuredClone=="function"?structuredClone(f):JSON.parse(JSON.stringify(f));return d(),c.length===0&&this.roomSendsAdmitted(r.shardKey)&&this.sendEncodedWhisper(i,y,r)?!0:c.length>=Vo?!1:(c.push(y),!0)},"send")}}connectWebSocket(e,s,r={}){if(this.assertLeaderOwnedSurface("connectWebSocket"),this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),send:n(()=>{},"send")};let i=n(c=>{try{c?.()}catch(u){console.error("[lunora] socket route handler threw",u)}},"i"),a,o=this.openSupplementarySocket(this.supplementaryUrl(e),{onClose:n(()=>{clearTimeout(a),i(s.onClose)},"onClose"),onMessage:n(c=>{let u;try{u=JSON.parse(typeof c.data=="string"?c.data:"")}catch{return}u.type==="message"&&(o.resetBackoff(),i(()=>{s.onMessage(T(u.data))}))},"onMessage"),onOpen:n(()=>{clearTimeout(a);let c=o.socket();a=setTimeout(()=>{o.socket()===c&&o.resetBackoff()},5e3),i(s.onOpen)},"onOpen"),shardKey:r.shardKey});return{close:n(()=>{clearTimeout(a),o.close()},"close"),send:n(c=>{let u=JSON.stringify(z(c,`socket message for '${e}'`)),d=o.socket();if(d!==void 0)try{d.send(u)}catch{}},"send")}}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}syncStatus(){let e=this.computeStatus(),s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader(),r=0;for(let a of this.subscriptions.all())(s||this.connectionGateState(a.shardKey).polling?a.valueReceived:a.acked)||(r+=1);for(let a of this.shapeSubscriptions.values())a.answered||(r+=1);let i=this.offlineQueue.size+this.offlineQueue.replaying;return{connection:e,pendingSubscriptions:r,pendingWrites:i,synced:at(e)&&r===0&&i===0}}onSyncStatus(e){let s=this.syncStatusListeners.add(e),r=this.syncStatus();return this.lastSyncStatus=r,e(r),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let a of r){let o=this.connections.get(a);e.push({confirmedMutationWatermark:s?.get(a)??0,hasSocket:o?.socket!==void 0,shardKey:a===""?void 0:a,wasEverConnected:o?.wasEverConnected??!1,wsState:o?.wsState??"idle"})}let i=this.subscriptions.all().map(a=>({acked:a.acked,functionPath:a.fn.__lunoraRef,id:a.id,kind:"query",lastMutationId:a.lastMutationId,pendingOptimisticLayers:a.optimisticLayers.length,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size}));for(let a of this.shapeSubscriptions.values())i.push({acked:a.answered,functionPath:`shape:${a.name}`,id:a.id,kind:"shape",lastMutationId:a.lastMutationId,pendingOptimisticLayers:0,rowCount:a.rows.size,serverCursor:a.serverCursor,shardKey:a.shardKey,subscriberCount:a.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((a,o)=>(a.shardKey??"").localeCompare(o.shardKey??"")),subscriptions:i.toSorted((a,o)=>a.functionPath.localeCompare(o.functionPath))}}onPendingChange(e){let s=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),s}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,s){this.clientQueryStore.set(e,s)}subscribeClientQuery(e,s){return this.clientQueryStore.subscribe(e,s)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,s,r){return dr(this,e,s,r)}whenReady(e={}){return e.signal===void 0?this.readyPromise:Mt(this.readyPromise,e.signal)}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){return this.peekHydratedQueryByKey(e,N(s),r)}peekHydratedQueryByKey(e,s,r){if(!this.readyResolved)return;let i=ne(e,s,r),a=this.hydratedQueryCache.get(i);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=_.key(e,s,r),a=this.subscriptions.get(i);return{present:a!==void 0,value:a?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,signal:r.signal})}async batch(e){return ae(this.rpcTimeoutMs,void 0,async s=>this.sendBatch(e,s))}async mutation(e,s,r={}){if(r.signal?.aborted)throw fe(r.signal);let{value:i}=await Mt(this.runMutation(e,s,r),r.signal);return i}canQueueOffline(e){let{wasEverConnected:s}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(s||this.offlineQueue.queueBeforeFirstConnect)}async action(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,captureBookmark:!0,signal:r.signal,unbounded:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),a=r.toArgs??(h=>({rows:h})),o=s.length,c=0,u=0,d=0;for(let h=0;h<o;h+=i){let l=s.slice(h,h+i),p=d,{committed:f}=await this.runMutation(e,a(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(p)}`},shardKey:r.shardKey});d+=1,c+=l.length,f&&(u+=l.length),r.onProgress?.({done:c,total:o})}return{chunks:d,imported:u,queued:c-u}}async shardTraffic(e){return Xa(this.adminHost,e)}async listScheduledJobs(){return to(this.adminHost)}async schedulerStatus(){return so(this.adminHost)}async cancelScheduledJob(e){return ro(this.adminHost,e)}async listDeadJobs(){return io(this.adminHost)}async retryDeadJob(e){return no(this.adminHost,e)}async removeDeadJob(e){return ao(this.adminHost,e)}async listWorkflowInstances(e){return oo(this.adminHost,e)}async getWorkflowInstance(e){return co(this.adminHost,e)}async setWorkflowInstanceStatus(e){return uo(this.adminHost,e)}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=this.openSupplementarySocket(j(Lt(this.url),Cn),{onMessage:n(r=>{let i;try{i=JSON.parse(typeof r.data=="string"?r.data:"")}catch{return}i.type==="jobs"&&Array.isArray(i.records)&&(s.resetBackoff(),e(i.records.map(a=>rs(a))))},"onMessage")});return s.close}async listFunctions(){return Ua(this.adminHost)}async getCronJobs(){return Ka(this.adminHost)}async runCronJob(e){return Na(this.adminHost,e)}async fetchOpenApi(){return qa(this.adminHost)}async fetchArchitecture(){return ja(this.adminHost)}async fetchOpenRpc(){return Wa(this.adminHost)}async listStorageObjects(e={}){return ho(this.adminHost,e)}async deleteStorageObject(e,s){return lo(this.adminHost,e,s)}async listStorageBuckets(){return po(this.adminHost)}async uploadStorageObject(e){return fo(this.adminHost,e)}async signedStorageUrl(e,s){return mo(this.adminHost,e,s)}async listGlobalTables(){return Ba(this.adminHost)}async readGlobalTablePage(e){return $a(this.adminHost,e)}async facetGlobalColumn(e){return Ha(this.adminHost,e)}async listVectorIndexes(){return yo(this.adminHost)}async queryVectorIndex(e){return bo(this.adminHost,e)}async queryLogArchive(e={}){return Za(this.adminHost,e)}async listKvNamespaces(){return Ga(this.adminHost)}async listKvKeys(e){return za(this.adminHost,e)}async getKvValue(e){return Va(this.adminHost,e)}async putKvValue(e){return Ja(this.adminHost,e)}async deleteKvKey(e){return Ya(this.adminHost,e)}async listAuthUsers(e={}){this.assertOpen();let s=P($n,{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(Gn,"POST",e)}async setAuthUserRole(e){return this.assertOpen(),await this.adminFetch(zn,"POST",e)}async banAuthUser(e){return this.assertOpen(),await this.adminFetch(Vn,"POST",e)}async unbanAuthUser(e){return this.assertOpen(),await this.adminFetch(Jn,"POST",e)}async setAuthUserPassword(e){this.assertOpen(),await this.adminFetch(Yn,"POST",e)}async removeAuthUser(e){this.assertOpen(),await this.adminFetch(Xn,"POST",e)}async impersonateAuthUser(e){return this.assertOpen(),await this.adminFetch(Zn,"POST",e)}async revokeAuthSession(e){this.assertOpen(),await this.adminFetch(ea,"POST",e)}async revokeAuthUserSessions(e){this.assertOpen(),await this.adminFetch(ta,"POST",e)}async getAuthCapabilities(){return this.assertOpen(),await this.adminFetch(sa,"GET")}async updateAuthUser(e){return this.assertOpen(),await this.adminFetch(ra,"POST",e)}async listAuthAccounts(e){return this.assertOpen(),await this.adminFetch(P(ia,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){this.assertOpen(),await this.adminFetch(na,"POST",e)}async listAuthPasskeys(e){return this.assertOpen(),await this.adminFetch(P(aa,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){this.assertOpen(),await this.adminFetch(oa,"POST",e)}async disableAuthTwoFactor(e){this.assertOpen(),await this.adminFetch(ca,"POST",e)}async listAuthOrganizations(e={}){return this.assertOpen(),await this.adminFetch(P(ua,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){this.assertOpen();let s=P(ha,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){this.assertOpen();let s=P(da,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){this.assertOpen();let s=P(ma,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return this.assertOpen(),await this.adminFetch(ya,"POST",e)}async revokeAuthSignUpInvitation(e){this.assertOpen(),await this.adminFetch(ba,"POST",e)}async removeAuthOrgMember(e){this.assertOpen(),await this.adminFetch(la,"POST",e)}async cancelAuthOrgInvitation(e){this.assertOpen(),await this.adminFetch(pa,"POST",e)}async getAuthConfig(){return this.assertOpen(),await this.adminFetch(fa,"GET")}async createAuthOrganization(e){return this.assertOpen(),await this.adminFetch(ga,"POST",e)}async updateAuthOrganization(e){return this.assertOpen(),await this.adminFetch(va,"POST",e)}async deleteAuthOrganization(e){this.assertOpen(),await this.adminFetch(Sa,"POST",e)}async addAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(wa,"POST",e)}async inviteAuthOrgMember(e){return this.assertOpen(),await this.adminFetch(Ca,"POST",e)}async setAuthOrgMemberRole(e){return this.assertOpen(),await this.adminFetch(ka,"POST",e)}async listAuthOrgTeams(e){this.assertOpen();let s=P(Ta,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Ea,"POST",e)}async updateAuthOrgTeam(e){return this.assertOpen(),await this.adminFetch(Ia,"POST",e)}async removeAuthOrgTeam(e){this.assertOpen(),await this.adminFetch(Oa,"POST",e)}async listAuthOrgTeamMembers(e){this.assertOpen();let s=P(Ra,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return this.assertOpen(),await this.adminFetch(Aa,"POST",e)}async removeAuthOrgTeamMember(e){this.assertOpen(),await this.adminFetch(Fa,"POST",e)}async listAuthOrgRoles(e){this.assertOpen();let s=P(Pa,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(Ma,"POST",e)}async updateAuthOrgRole(e){return this.assertOpen(),await this.adminFetch(La,"POST",e)}async deleteAuthOrgRole(e){this.assertOpen(),await this.adminFetch(xa,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=P(Hn,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){if(this.assertOpen(),i.signal?.aborted)return()=>{};let a=s??{},o=_.key(e.__lunoraRef,a,i.shardKey),c=this.subscriptions.get(o),u=tt(r),d=tt(i.onError),h=tt(i.onCheckpoint);if(!c){this.nextSubId+=1;let y=`sub_${this.nextSubId.toString()}`,m=N(a),g=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);c={acked:!1,args:a,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:y,lastValue:g?.value,optimisticLayers:[],serverBase:g?.value,serverCursor:g?.serverCursor,shardKey:i.shardKey,valueReceived:!1,wireArgs:z(a,`args for '${e.__lunoraRef}'`),...g?.serverEpoch===void 0?{}:{serverEpoch:g.serverEpoch}},this.subscriptions.add(c),this.emitSyncStatus(),g!==void 0&&this.cacheSeededQueries.set(o,g)}if(c.callbacks.add(u),d&&c.errorCallbacks.add(d),h&&c.checkpointCallbacks.add(h),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c,p=!1,f=n(()=>{if(!p&&(p=!0,i.signal?.removeEventListener("abort",f),l.callbacks.delete(u),d&&l.errorCallbacks.delete(d),h&&l.checkpointCallbacks.delete(h),l.callbacks.size===0)){this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(_.keyOf(l)),this.subscriptions.remove(l);let y=this.getConnection(l.shardKey);y&&this.settleSubscribeWatchdog(y,l.id),this.releaseIdleShard(l.shardKey),this.emitSyncStatus()}},"p");return i.signal?.addEventListener("abort",f,{once:!0}),i.signal?.aborted&&f(),f}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:o}=r;return o!==void 0&&queueMicrotask(()=>{o({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,a={answered:!1,args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:z(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,a),this.emitSyncStatus(),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(a),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(a.shardKey,i,"shape_unsubscribe"),this.releaseIdleShard(a.shardKey),this.emitSyncStatus()}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new b("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:a}=r,o=s??{},{handle:c,iterable:u}=Xe({maxBuffer:r.maxBuffer,onCancel:n(()=>{this.cancelStream(i,a)},"onCancel")});this.ensureSocket(a);let d=this.getConnection(a),h={id:i,query:{args:z(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:a},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:h,shardKey:a};this.streams.set(i,l);let p=d?.wsState==="open"&&W(d,h);if(!p&&d===void 0)return this.forgetStream(i),c.fail(new b("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!p){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=64;){let f=d.pendingStreams.shift()?.id,y=f?this.streams.get(f):void 0;y&&(y.handle.fail(new b("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.forgetStream(f))}d.pendingStreams.push(h)}return u}httpStream(e,s,r={}){if(this.closed)throw new b("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return sr(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0;for(let e of this.whisperJoins.keys())this.dropWhisperJoinWaiters(e);this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.releasePageHideFlush?.(),this.releasePageHideFlush=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new b("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear(),this.supplementaryBounces.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.syncStatusListeners.clear(),this.whisperHandlers.clear(),this.liveSocketGrants.clear(),this.roomFlushes.clear(),this.roomIdentityResets.clear(),this.shapeSubscriptions.clear(),this.pokeAssembler.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new b("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let s=e.leaderTabId;return s!==void 0&&s!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new b("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}shardInUse(e){let s=n(r=>v(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=v(e),r=this.connections.get(s);this.closed||s===""||r===void 0||(clearTimeout(r.idleTimer),r.idleTimer=setTimeout(()=>{r.idleTimer=void 0,!(this.closed||this.connections.get(s)!==r||this.shardInUse(s))&&(r.wasEverConnected&&this.idleClosedShards.add(s),this.teardownConnection(r),this.connections.delete(s),this.emitConnectionStatus())},5e3))}forgetStream(e){let s=this.streams.get(e);this.streams.delete(e),s&&this.releaseIdleShard(s.shardKey)}teardownConnection(e){e.polling.stop();let s=v(e.shardKey);for(let[i,a]of this.streams)v(a.shardKey)===s&&(a.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(i));e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),clearTimeout(e.idleTimer),e.idleTimer=void 0,be(e);let{socket:r}=e;if(r){e.socket=void 0;try{r.close()}catch{}}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`,s={activeShapes:n(()=>[...this.shapeSubscriptions.values()],"activeShapes"),activeSubscriptions:n(()=>this.subscriptions.all(),"activeSubscriptions"),broadcastStatus:n((r,i)=>this.tabCoordinator?.broadcastConnectionStatus(r,i),"broadcastStatus"),closeConnections:n(()=>{for(let[r,i]of this.connections)this.teardownConnection(i),this.connections.delete(r)},"closeConnections"),computeStatus:n(()=>this.computeStatus(),"computeStatus"),emitConnectionStatus:n(()=>{this.emitConnectionStatus()},"emitConnectionStatus"),ensureSocket:n(r=>{this.ensureSocket(r)},"ensureSocket"),flushOfflineQueues:n(()=>{this.flushAllOfflineQueues()},"flushOfflineQueues"),identityFingerprint:n(()=>this.identityFingerprint(),"identityFingerprint"),isLeader:n(()=>this.tabCoordinator?.isLeader()===!0,"isLeader"),leader:this.leader,queueResubscribe:n(r=>{this.queueResubscribe(r)},"queueResubscribe"),queuedShardKeys:n(()=>this.queuedOfflineShardKeys,"queuedShardKeys"),clientIdentifier:n(()=>this.clientId,"clientIdentifier"),dropCacheSeed:n(r=>{this.dropCacheSeed(r)},"dropCacheSeed"),ackAndAdvanceCursor:n((r,i,a)=>{this.ackAndAdvanceCursor(r,i,a)},"ackAndAdvanceCursor"),subscription:n(r=>this.subscriptions.get(r),"subscription")};return new Je({channelName:e,onBecomeLeader:n(()=>{Uo(s)},"onBecomeLeader"),onStopBeingLeader:n(()=>{Ko(s)},"onStopBeingLeader"),onConnectionStatus:n((r,i)=>{No(s,r,i)},"onConnectionStatus"),onSubscriptionData:n((r,i,a,o,c)=>{jo(s,r,i,a,o,c)},"onSubscriptionData"),onLeaderClaimAnswered:n(()=>{qo(s)},"onLeaderClaimAnswered"),onSubscriptionError:n((r,i,a)=>{Wo(s,r,i,a)},"onSubscriptionError"),onSubscriptionSettled:n((r,i,a,o,c,u)=>{Bo(s,r,i,a,o,c,u)},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(j(this.url,$t),{body:JSON.stringify({calls:e.map((c,u)=>({args:z(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let a;try{a=await r.json()}catch{throw new b("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let o=me(a);if(!r.ok||o!==void 0&&!a.results)throw o!==void 0?Re(o):new b("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let c of a.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return go(a.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=Go(e,r),a=s,o=i.mutationId??nt();this.mutationIssueCounter+=1;let c=this.mutationIssueCounter,u=this.takeReplayCredential(i.replayCredential),d=this.composedBaselineFor(i.replayBaseline,i.shardKey);this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i);let{confirms:h,rollbacks:l}=this.applyOptimisticUpdates(e.__lunoraRef,a,i.shardKey,i.optimistic);this.applyOptionalOptimisticUpdate(i.optimisticUpdate,s,i.shardKey,l,h);let p=i.onlineOnly?void 0:this.offlineFlushes.get(v(i.shardKey));p!==void 0&&await p;let{httpFirst:f,midReconnect:y,shouldQueueOffline:m,socketDown:g}=this.writeQueueGate(i.shardKey),S=!i.onlineOnly&&m&&i.replayBaseline===void 0&&this.hasPendingWriteAhead(i.shardKey),k=n(async(w=!1)=>this.enqueueOfflineMutation(e,a,i.shardKey,d,o,l,h,w?void 0:i.precondition,i.mutationId,u?.stamp,w,c),"v");if(this.refuseOnlineOnlyWhenDown(e.__lunoraRef,i,l),g||y||S)return k();let I;try{let w=await this.rpc(e.__lunoraRef,a,i.shardKey,{baselineSeq:d,captureBookmark:!0,...u?.flags,mutationId:o,onCommitCursor:n(O=>{I=O},"onCommitCursor")});for(let O of h)O(I);return{committed:!0,value:w}}catch(w){let O=Zo(w,a),ee=f&&m&&O,M=this.ownSocketOpen(i.shardKey);if(m&&!i.onlineOnly&&this.fetchImpl!==void 0&&!this.outbox&&i.replayBaseline===void 0&&(w instanceof TypeError||w instanceof U)&&Vt(a)){let A=k(!0);return this.noteHeldRetryDelay(i.shardKey),this.scheduleRateLimitedRetry(i.shardKey),A}throw this.settleFailedDirectWrite(w,I,h,l,u?.flags.authToken),ec(i.onlineOnly,ee,O,M)?vr(e.__lunoraRef,w):w}}refuseOnlineOnlyWhenDown(e,s,r=[]){if(!s.onlineOnly)return;let i=this.writeQueueGate(s.shardKey);if(i.socketDown||i.midReconnect)throw oe(r),vr(e)}ownSocketOpen(e){return this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()?!1:this.writeQueueGate(e).socketOpen}writeQueueGate(e){let{hasSocket:s,idleClosed:r,polling:i,wasEverConnected:a,wsState:o}=this.connectionGateState(e),{queueBeforeFirstConnect:c}=this.offlineQueue,u=a||c,d=this.WebSocketImpl!==void 0&&u,h=i||r;return{httpFirst:h,midReconnect:o==="connecting"&&u&&!h,shouldQueueOffline:d,socketDown:o!=="open"&&!s&&d&&!h,socketOpen:o==="open"}}settleFailedDirectWrite(e,s,r,i,a){if(this.noteIdentityMismatch(e),a!==void 0&&this.noteReplayAuthRefusal(e,a),ot(e)){for(let o of r)o(s);return}oe(i)}async enqueueOfflineMutation(e,s,r,i,a,o,c,u,d,h,l,p){let f=h===void 0?this.identityFingerprint():h;if(this.outbox){this.outboxMutationCounter+=1;let y=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:d??`${this.clientId}:${String(y)}`,identity:f,mutationId:y,...o.length>0&&{onRejected:n(()=>{oe(o)},"onRejected")},shardKey:r})}catch(m){throw oe(o),m instanceof Error?m:new Error(String(m))}for(let m of c)m(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((y,m)=>{let g={ambiguousSend:l,args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:a,issueSeq:p,clientId:this.clientId,identity:f,precondition:u,onCommit:n(S=>{for(let k of c)k(S)},"onCommit"),reject:n(S=>{this.queuedIdentities.delete(a),ot(S)||oe(o),m(S instanceof Error?S:new Error(String(S))),this.releaseIdleShard(r)},"reject"),resolve:y,shardKey:r};this.offlineQueue.enqueue(g),this.queuedOfflineShardKeys.add(r),this.ensureSocket(r),g.id!==void 0&&this.queuedIdentities.set(g.id,f)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=v(e);return this.offlineQueue.hasPending(r=>v(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(ne(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(jt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let a=s.get(r);if(a&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(a,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(ne(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),ie(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,ie(r,void 0)),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=ne(e,s,r),a=this.hydratedQueryCache.get(i);if(!(a===void 0||!this.cachedQueryMatchesIdentity(a)))return this.hydratedQueryCache.delete(i),a}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=ne(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=ne(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,a=i===void 0?this.identityFingerprint():i;a===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:a,serverCursor:e.serverCursor,ts:Date.now(),value:s,...a===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},250))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}installPageHideFlush(){let e=globalThis;if(!this.persistence&&!this.queryCache||!("document"in globalThis)||typeof e.addEventListener!="function")return;let s=n(()=>{this.offlineQueue.flushUnpersisted(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.flushQueryCacheWrites().catch(()=>{}))},"t"),r=n(()=>{e.document?.visibilityState==="hidden"&&s()},"s");e.addEventListener("pagehide",s),e.document?.addEventListener("visibilitychange",r),this.releasePageHideFlush=()=>{e.removeEventListener?.("pagehide",s),e.document?.removeEventListener("visibilitychange",r)}}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leader.status??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(s=>s.wsState==="open")?"connected":e.some(s=>s.polling.isPolling())?"polling":e.some(s=>s.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let s=v(e),r;for(let i of this.subscriptions.all())v(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}composedBaselineFor(e,s){return e===void 0?this.baselineCursorFor(s):e??void 0}async pollSubscriptions(e){let s=v(e),r=[];for(let c of this.subscriptions.all())v(c.shardKey)===s&&(Vt(c.args)?r.push(c):(this.markQueryRejected(c,!0),Y(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"})));if(r.length===0)return this.probeOrigin();let i=rr(),a=this.identityFingerprint(),o;try{o=await mr(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==a)return!0;for(let[c,u]of r.entries()){let d=o[c];if(d!==void 0){if(!d.ok){this.markQueryRejected(u,!0),Y(u.errorCallbacks,{code:d.error.code,message:d.error.message});continue}this.handleDataMessage({data:B(d.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await mr(async s=>e(j(this.url,$t),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitSyncStatus(){if(this.syncStatusListeners.size===0)return;let e=this.syncStatus(),s=this.lastSyncStatus;s?.connection===e.connection&&s.pendingSubscriptions===e.pendingSubscriptions&&s.pendingWrites===e.pendingWrites&&s.synced===e.synced||(this.lastSyncStatus=e,this.syncStatusListeners.emit(e))}emitConnectionStatus(){let e=this.computeStatus();this.emitSyncStatus(),e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let a=[],o=[];if(!i)return{confirms:a,rollbacks:o};let c=_.key(e,s,r),u=this.subscriptions.get(c);if(u){let d=Dt(u,i);d&&(a.push(d.confirm),o.push(d.rollback))}return{confirms:a,rollbacks:o}}applyOptionalOptimisticUpdate(e,s,r,i,a){e&&this.applyOptimisticUpdate(e,s,r,i,a)}applyOptimisticUpdate(e,s,r,i,a){let{confirms:o,rollbacks:c,store:u}=ar(this.subscriptions,r);try{e(u,s)}catch{oe(c);return}i.push(...c),a.push(...o)}getConnection(e){return this.connections.get(v(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!W(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(v(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=v(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:ko({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:n(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:n(()=>{this.emitConnectionStatus()},"onStateChange"),poll:n(async()=>this.pollSubscriptions(e),"poll")}),reconnect:Oe(this.reconnectOptions),reconnectTimer:void 0,resubscribeQueue:[],resubscribeSlots:new Set,shardKey:e,socket:void 0,stableTimer:void 0,unackedWatchdogs:new Map,wasEverConnected:this.idleClosedShards.delete(s),wsState:"idle"},this.connections.set(s,r)),r}openSupplementarySocket(e,s){if(this.WebSocketImpl===void 0||this.closed)return{close:n(()=>{},"close"),resetBackoff:n(()=>{},"resetBackoff"),socket:n(()=>{},"socket")};let r=Oe(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},a,o=!1,c=n(()=>{o||this.closed||(a=setTimeout(p,r.next()))},"o"),u=n(m=>{o||this.WebSocketImpl===void 0||fr(i,this.wsUrlFor(s.shardKey,m,e),this.managedSocketOptions,{onClose:n(()=>{c(),s.onClose?.()},"onClose"),onMessage:s.onMessage,...s.onOpen===void 0?{}:{onOpen:s.onOpen}})},"c"),d=0,h,l=n(async m=>{let g=this.wsCredentialGeneration;d+=1;let S=d,k;h=g;try{k=await Yo(m,Jo)}catch{S===d&&(h=void 0,c());return}if(S===d){if(h=void 0,g!==this.wsCredentialGeneration){p();return}u(k)}},"u"),p=n(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsTicket:m}=this;if(typeof m=="function"){l(m).catch(()=>{});return}u(m)},"f");p();let f=n(()=>{o=!0,a!==void 0&&(clearTimeout(a),a=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),be(i);let{socket:m}=i;i.socket=void 0;try{m?.close()}catch{}},"p");this.adminSocketTeardowns.add(f);let y=n(()=>{let{socket:m}=i;if(m===void 0){h!==void 0&&h!==this.wsCredentialGeneration&&(d+=1,h=void 0,p());return}i.socket=void 0,i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),be(i);try{m.close()}catch{}s.onClose?.(),c()},"y");return this.supplementaryBounces.add(y),{close:n(()=>{f(),this.adminSocketTeardowns.delete(f),this.supplementaryBounces.delete(y)},"close"),resetBackoff:n(()=>{r.reset()},"resetBackoff"),socket:n(()=>i.socket,"socket")}}supplementaryUrl(e){let s=xt(this.wsUrl),r=s.pathname.endsWith(Ht)?s.pathname.slice(0,-Ht.length):s.pathname;return s.pathname=j(r,e),Qt(s,this.wsUrl)}wsUrlFor(e,s,r=this.wsUrl){let i=xt(r);if(e===void 0&&s===void 0&&!i.searchParams.has("token"))return r;let a=new Set([...e===void 0?[]:["shard"],"token"]),o=[...i.searchParams].filter(([c])=>!a.has(c)).map(([c,u])=>`${encodeURIComponent(c)}=${encodeURIComponent(u)}`);return e!==void 0&&o.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&o.push(`token=${encodeURIComponent(s)}`),i.search=o.join("&"),Qt(i,r)}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[cn]=un(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let a=e.authToken===void 0?this.authToken:e.authToken;if(a&&(r.authorization=`Bearer ${a}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(r["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(r["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let o=this.bookmark.get();o&&(r["x-d1-bookmark"]=o)}return r}async rpc(e,s,r,i={}){let{fetchImpl:a}=this;if(!a)throw new U("LunoraClient: no `fetch` implementation available");let o=this.rpcRequestHeaders(i,r),c=i.authToken===void 0?this.authToken:i.authToken,u=JSON.stringify({args:z(s,`args for '${e}'`),functionPath:e,shardKey:r}),{body:d,response:h}=await ae(i.unbounded?0:this.rpcTimeoutMs,i.signal,async f=>{let y=await a(j(this.url,gn),{body:u,headers:o,method:"POST",signal:f});try{return{body:await y.json(),response:y}}catch{return{body:void 0,response:y}}});if(i.captureBookmark){let f=h.headers.get("x-d1-bookmark");f&&this.bookmark.set(f)}if(d===void 0)throw Ae(h.status,h.statusText,h.headers.get("retry-after"));let l=d;if(typeof l!="object"||l===null||Array.isArray(l))throw Ae(h.status,h.statusText,h.headers.get("retry-after"));let p=me(d);if(p!==void 0)throw qt(p,h.headers.get("retry-after"));if(!h.ok)throw Ae(h.status,h.statusText,h.headers.get("retry-after"));i.onMutationAck?.(d.lastMutationId),i.onCommitCursor?.(d.commitCursor),this.noteCredentialAccepted(c),this.learnDefaultShardKey(h,r),this.recordShardCursor(r,d.commitCursor);try{return T(d.result)}catch(f){throw Ir(f)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new b("INTERNAL","LunoraClient: no `fetch` implementation available");let a={};this.authToken&&(a.authorization=`Bearer ${this.authToken}`);let o=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:o?(c=r,i!==void 0&&(a["content-type"]=i)):(c=JSON.stringify(r),a["content-type"]="application/json");let u=await this.fetchImpl(j(this.url,e),{body:c,headers:a,method:s}),d;try{d=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let h=me(d);if(h!==void 0)throw Re({...h,message:h.message??"admin request failed"});if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new b("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return d}effectiveConnectionContext(e){let s=this.connectionContextHolders.get(e);return s&&s.length>0?s[s.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let s=this.connections.get(e);s?.wsState==="open"&&this.sendConnectEnvelope(s)}sendConnectEnvelope(e){let s=this.effectiveConnectionContext(v(e.shardKey));W(e,{caps:zo,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s},...e.sessionToken===void 0?{}:{token:e.sessionToken}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())v(s.shardKey)===v(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);s.wsState==="open"||s.wsState==="connecting"||(s.wsState="connecting",this.emitConnectionStatus(),this.startShardSocket(s,e).catch(()=>{this.handleDisconnect(s)}))}applyWsCredentialChange(){this.wsCredentialGeneration+=1,this.resetRoomSends(),this.bounceShardSockets()}async startShardSocket(e,s){let{wsToken:r,wsTicket:i}=this;if(typeof r=="function"||typeof i=="function"){await this.openSocketWithProvidedCredentials(e,s);return}this.openSocket(e,s,{session:r,ticket:i})}async openSocketWithProvidedCredentials(e,s){let r=this.wsCredentialGeneration,i=Symbol("ws-token-attempt"),a;e.providerAttempt=i;try{a=await ae(this.connectTimeoutMs,void 0,async()=>({session:await gr(this.wsToken),ticket:await gr(this.wsTicket)}),()=>new Error("LunoraClient: ws credential provider timed out"))}catch{e.providerAttempt===i&&(e.providerAttempt=void 0,this.handleDisconnect(e));return}if(e.providerAttempt===i&&(e.providerAttempt=void 0,!(this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0))){if(r!==this.wsCredentialGeneration){await this.startShardSocket(e,s);return}this.openSocket(e,s,a)}}openSocket(e,s,r){if(this.WebSocketImpl===void 0)return;e.providerAttempt=void 0,e.identity=this.identityFingerprint(),r.ticket===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.sessionToken=r.session,e.retired=!1;let i=this.wsCredentialGeneration;fr(e,this.wsUrlFor(s,r.ticket),this.managedSocketOptions,{onClose:n(a=>{a?.code===4003&&e.polling.noteFailedOpen(),a?.code===4001?this.notifyTokenExpired():a?.code===4003&&a.reason!=="connect deadline"&&i===this.wsCredentialGeneration&&this.refusedCredentialGeneration!==i&&(this.refusedCredentialGeneration=i,this.notifyTokenExpired()),this.handleDisconnect(e)},"onClose"),onMessage:n(a=>{e.retired!==!0&&this.handleServerMessage(a.data,s)},"onMessage"),onOpen:n(()=>{e.wsState="open",e.wasEverConnected=!0,e.identityConfirmed=!1,e.connectionId=void 0,e.roomsRejoined=!1,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},5e3),this.sendConnectEnvelope(e),this.markShardPendingAck(s,!0),this.emitConnectionStatus(),this.clearResubscribeQueue(e);for(let c of this.subscriptions.all())v(c.shardKey)===v(s)&&this.queueResubscribe(c);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let c=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:u,type:d}of c)W(e,{id:u,type:d});this.releaseIdleShard(s)}vo(e);let a=v(s),o=this.whisperHandlers.get(a);if(this.dropWhisperJoinWaiters(a),this.whisperJoins.set(a,new Map),o)for(let c of o.keys())this.sendWhisperJoin(e,a,c);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),W(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(),be(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",e.connectionId=void 0,e.whisperAck=void 0,this.dropWhisperJoinWaiters(v(e.shardKey)),this.markShardPendingAck(e.shardKey),this.emitConnectionStatus(),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,a]of this.streams)if(!(v(a.shardKey)!==v(e.shardKey)||s.has(i))){if(a.durable){let o={...a.message,...a.generation===void 0?{}:{generation:a.generation},sinceChunk:a.lastSeq};a.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}a.handle.fail(new b("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.forgetStream(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}markShardPendingAck(e,s=!1){let r=v(e);for(let i of this.subscriptions.all())v(i.shardKey)===r&&(i.acked=!1,s&&(i.valueReceived=!1));for(let i of this.shapeSubscriptions.values())v(i.shardKey)===r&&(i.answered=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribeSlots.size<3;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribeSlots.add(s.id)}}settleSubscribeWatchdog(e,s){clearTimeout(e.unackedWatchdogs.get(s)),e.unackedWatchdogs.delete(s),e.resubscribeSlots.delete(s)&&this.drainResubscribeQueue(e)}clearResubscribeQueue(e){for(let s of e.unackedWatchdogs.values())clearTimeout(s);e.unackedWatchdogs.clear(),e.resubscribeSlots.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e,s=!1){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.acked)return!1;let i=e.serverCursor!==void 0&&e.serverBase!==void 0,a=W(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"});return a&&!s&&this.armUnackedWatchdog(r,e),a}armUnackedWatchdog(e,s){clearTimeout(e.unackedWatchdogs.get(s.id)),e.unackedWatchdogs.set(s.id,setTimeout(()=>{!s.acked&&this.subscriptions.getById(s.id)===s&&this.sendSubscribeIfOpen(s,!0),this.settleSubscribeWatchdog(e,s.id)},1e4))}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&W(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=wo(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}if(i.type!=="error"&&this.getConnection(s)?.reconnect.reset(),typeof i.id=="string"){let a=this.getConnection(s);if(a){let{id:o}=i;this.settleSubscribeWatchdog(a,o)}}switch(i.type){case"ack":{let a=this.subscriptions.getById(i.id);a&&this.ackAndAdvanceCursor(a,void 0,void 0);return}case"chunk":{let{data:a,generation:o,id:c,seq:u}=i,d=this.streams.get(c);d&&typeof u=="number"&&(d.lastSeq=u,typeof o=="number"&&(d.generation=o),d.durable=!0),d?.handle.push(T(a));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s),this.adoptSocketConnectionId(i,s),this.confirmShardIdentity(s);break}case"live":{this.dispatchLive(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.pokeAssembler.part(s,i);break}case"pokeStart":{this.pokeAssembler.start(s,i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}case"whisper_subscribed":{this.acknowledgeWhisperJoin(v(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(cr(e)),this.forgetStream(r);return}let a=r===void 0?void 0:this.subscriptions.getById(r);if(a){let c=Nt(e),u=this.identityFingerprint(),d=_.keyOf(a);this.markQueryRejected(a),Y(a.errorCallbacks,c),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(d,c,u);return}let o=r===void 0?void 0:this.shapeSubscriptions.get(r);o&&(o.answered||(o.answered=!0,this.emitSyncStatus()),Y(o.errorCallbacks,Nt(e)))}markQueryRejected(e,s=this.tabCoordinator!==void 0&&!this.tabCoordinator.isLeader()||this.connectionGateState(e.shardKey).polling){let r=s?"valueReceived":"acked";e[r]||(e[r]=!0,this.emitSyncStatus())}handlePokeEnd(e,s){let r=this.pokeAssembler.end(s,e.pokeId);if(r){Qo(this.shapeSubscriptions,r);for(let i of r.parts.keys()){let a=this.shapeSubscriptions.get(i);a&&!r.undecodable.has(i)&&this.applyPokePart(a,r,e)}}}applyPokePart(e,s,r){let i=e.answered,a=xo(e,s,r);if(e.answered!==i&&this.emitSyncStatus(),br(e),a==="reseed"){this.sendShapeSubscribeIfOpen(e);return}e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,this.emitSyncStatus(),console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i||e.type==="data"&&_o(i,e))return;let a;try{a=Js(e,i.serverBase)}catch(c){Y(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${c instanceof Error?c.message:String(c)}`});return}if(a===Ft){this.resnapshotSubscription(i);return}this.dropCacheSeed(_.keyOf(i));let o=s!==void 0&&!i.valueReceived;if(Or(i,a,{cursor:e.cursor,epoch:e.epoch}),o&&(i.valueReceived=!0,this.emitSyncStatus()),e.lastMutationId!==void 0&&(Xt(i,e.lastMutationId),Zt(i,!0)),this.persistQueryValue(i),st(i,i.serverCursor),s!==void 0&&nr(i,s),ie(i,a),this.tabCoordinator?.isLeader()){let c=_.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(c,a,i.serverCursor,i.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,e.cursor,e.epoch)}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s&&(this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&Xt(s,e.lastMutationId),Zt(s),this.tabCoordinator?.isLeader())){let r=_.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}ackAndAdvanceCursor(e,s,r){let i=!e.acked;e.acked=!0,i&&this.emitSyncStatus(),(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),st(e,e.serverCursor)&&ie(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(v(s))?.keys()??[])this.grantWhenJoined(s,i,e.connectionId)}}grantWhenJoined(e,s,r){let i=v(e),a=this.liveSocketGrants.get(i)?.get(s);if(a===void 0)return;let{stream:o,topic:c}=a,u=n(()=>{this.liveSocketGrants.get(i)?.get(s)===void 0||this.getConnection(e)?.connectionId!==r||this.postLiveControl(`/live/${o}/control`,e,{action:"subscribe",connectionId:r,stream:o,subscriptionId:s,topic:c},d=>{this.refuseLiveGrant(e,s,d,r)})},"c");this.getConnection(e)?.whisperAck===!0?this.whenWhisperJoined(i,c,u):u()}sendWhisperJoin(e,s,r){let i=this.whisperJoinState(s,r);i.pending+=1,i.joined=!1,W(e,{topic:r,type:"whisper_subscribe"})}acknowledgeWhisperJoin(e,s){let r=this.whisperJoins.get(e)?.get(s);if(r!==void 0&&(r.pending=Math.max(0,r.pending-1),!(r.pending>0))){r.joined=!0;for(let i of r.waiters.splice(0))clearTimeout(i.timer),i.run();this.releaseWhisperJoin(e,s)}}releaseWhisperJoin(e,s){if(this.whisperHandlers.get(e)?.has(s)===!0)return;let r=this.whisperJoins.get(e),i=r?.get(s);if(!(r===void 0||i===void 0||i.pending>0)){for(let a of i.waiters.splice(0))clearTimeout(a.timer);r.delete(s),r.size===0&&this.whisperJoins.delete(e)}}whenWhisperJoined(e,s,r){let i=this.whisperJoinState(e,s);if(i.joined){r();return}let a={run:r,timer:void 0};a.timer=setTimeout(()=>{i.waiters=i.waiters.filter(o=>o!==a),r()},Rr),i.waiters.push(a)}dropWhisperJoinWaiters(e){for(let s of this.whisperJoins.get(e)?.values()??[])for(let r of s.waiters.splice(0))clearTimeout(r.timer)}whisperJoinState(e,s){let r=this.whisperJoins.get(e);r===void 0&&(r=new Map,this.whisperJoins.set(e,r));let i=r.get(s);return i===void 0&&(i={joined:!1,pending:0,waiters:[]},r.set(s,i)),i}refuseLiveGrant(e,s,r,i){let a=v(e),o=this.liveSocketGrants.get(a),c=o?.get(s);o===void 0||c===void 0||this.getConnection(e)?.connectionId!==i||(o.delete(s),o.size===0&&this.liveSocketGrants.delete(a),c.release(),c.onError?.({status:r,topic:c.topic}))}postLiveControl(e,s,r,i){let{fetchImpl:a}=this;if(!a)return;let o=JSON.stringify(s===void 0?r:{...r,shardKey:s}),c=this.rpcRequestHeaders({},s);this.liveControlChain=this.liveControlChain.then(()=>Xo(a,j(this.url,e),o,c)).then(u=>{u>=400&&u<500&&u!==404&&u!==401&&i?.(u)}).catch(()=>{})}dispatchLive(e,s){let r=this.liveSocketGrants.get(v(s));if(!r)return;let i=T(e.data);for(let a of r.values())if(!(a.stream!==e.stream||a.topic!==e.topic))try{a.onEvent(i)}catch{}}dispatchWhisper(e,s){let r=this.whisperHandlers.get(v(s))?.get(e.topic);if(!r)return;let i=T(e.data);for(let a of r)try{a(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.forgetStream(e);return}let r=this.subscriptions.getById(e);r&&(r.acked=!1,this.emitSyncStatus(),Y(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&(this.replayAttempts.delete(e),this.offlineQueue.discard(e))}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let a=e.charCodeAt(i);s^=a,s=Math.imul(s,16777619),r=Math.imul(r,33)+a}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&at(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,s,r){if(!(this.closed||this.authToken!==e||r!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(s?.id??null,r);return}s!==null&&this.setAuthToken(e,s.id)}}adoptCookieSubject(e,s){return this.closed||this.authToken!==null||s<this.identityAnsweredAt?!1:(this.identityAnsweredAt=s,this.identitySettled=!0,this.setAuthToken(null,e),!0)}sendEncodedWhisper(e,s,r){this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey),a=i!==void 0&&W(i,{data:s,topic:e,type:"whisper"});return this.releaseIdleShard(r.shardKey),a}roomSendsAdmitted(e){let s=this.getConnection(e);return s?.wsState==="open"&&s.retired!==!0&&s.identityConfirmed===!0&&s.roomsRejoined===!0}releaseRoomSends(e){if(this.roomSendsAdmitted(e))for(let s of this.roomFlushes.get(v(e))??[])s()}confirmShardIdentity(e){let s=this.getConnection(e);s!==void 0&&(s.identityConfirmed=!0,s.polling.noteOpen()),this.releaseRoomSends(e)}handleIdentityFrame(e,s){let r=this.getConnection(s)?.identityQuestion,{subject:i}=e;r===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,r)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,s){if(s!==void 0){this.authSubject=s,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return s===void 0?e.identity:s}warnRefreshWithoutSubject(e,s){e===null||s===null||this.authSubject!==void 0||this.authRefusalNotifiedFor!==this.hashToken(e)||console.warn("[lunora] setAuthToken replaced a token that was just refused for a queued write, with no subject: without one a refresh reads as a user switch, so the held writes were discarded (OFFLINE_IDENTITY_CHANGED). Pass the user id, e.g. setAuthToken(token, user.id), to keep them across a refresh.")}rejectQueuedForIdentityChange(e){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.identityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let a=new Error("offline mutation discarded: auth identity changed before replay");a.code="OFFLINE_IDENTITY_CHANGED",i.reject(a),this.emitItemSettled(i,"rejected",a)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let a=s??"",o=this.clientWatermarks.get(a);if(o===void 0)this.clientWatermarks.set(a,i);else for(let[c,u]of i)o.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.resetRoomSends(),this.revokeCacheSeededValues();for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,e.valueReceived=!1,ie(e,void 0);for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,e.answered=!1,br(e);this.emitSyncStatus(),this.bounceShardSockets(),this.retiredIdentities+=1,this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}resetRoomSends(){for(let e of this.roomIdentityResets)e()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}else e.providerAttempt!==void 0&&this.startShardSocket(e,e.shardKey).catch(()=>{this.handleDisconnect(e)});for(let e of this.supplementaryBounces)e()}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=v(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:a}=this;try{await this.drainOfflineQueue(e,a)}catch{}!this.closed&&this.authToken!==a&&this.offlineQueue.size>0&&at(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&(this.offlineFlushes.delete(s),this.releaseIdleShard(e))}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",l)}let i=v(e),a=this.offlineQueue.drain(h=>v(h.shardKey)===i);if(a.length===0)return;let o=[],c=[];for(let h of a){let l=this.replayGateVerdict(h);l==="send"?o.push(h):l==="hold"&&c.push(h)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),o.length===0){this.scheduleRateLimitedRetry(e);return}let u=this.encodableOrSettleTerminal(o);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let d=[];for(let h=0;h<u.length;h+=Bt){let l=u.slice(h,h+Bt),p=await this.replayBatched(l,e,s);if(d.push(...p.requeue),p.stop||p.requeue.length>0){d.push(...u.slice(h+Bt));break}}d.length>0&&this.offlineQueue.requeue(d),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=v(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,Jt(i))})}noteReplayRetryDelay(e,s,r){let i=v(e),a=this.replayRetryState.get(i),o=(a?.attempts??0)+1,c=Ro(s,o)??(r===null&&Ie(s)?Jt(o):void 0);this.replayRetryState.set(i,{attempts:o,delayMs:c===void 0?a?.delayMs:Math.max(a?.delayMs??0,c)})}scheduleRateLimitedRetry(e){let s=v(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let a=this.replayRetryTimers.get(s);a!==void 0&&clearTimeout(a),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{z(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)||yr(e)}noteReplayAuthRefusal(e,s){if(!Ie(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,...Gt(s.stamp,s.authToken)},stamp:s.stamp}}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}spendsLastReplayAttempt(e,s){if(e.id===void 0)return!1;let r=s?.code;if(e.ambiguousSend!==!0||Ie(s)||r==="RATE_LIMITED"||r==="TOO_MANY_REQUESTS"||!yr(s))return!1;let i=(this.replayAttempts.get(e.id)??0)+1;return this.replayAttempts.set(e.id,i),i>=5}keepUnexhaustedAmbiguousWrites(e,s){return e.filter(r=>r.ambiguousSend===!0&&this.spendsLastReplayAttempt(r,s)?(this.settleReplayTerminal(r,s),!1):!0)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let a=e[i];if(!a)continue;let o;try{let c=await this.rpc(a.functionPath,a.args,a.shardKey,{authToken:r,baselineSeq:a.baselineSeq,captureBookmark:!0,clientId:a.clientId??this.clientId,...Gt(a.identity,r),mutationId:a.id,onCommitCursor:n(u=>{o=u},"onCommitCursor")});this.settleReplaySuccess(a,c,o)}catch(c){if(ot(c)){this.settleReplayUndecodable(a,c,o);continue}if(!this.shouldRequeueReplayFailure(c,r)||this.spendsLastReplayAttempt(a,c)){this.settleReplayTerminal(a,c);continue}this.noteReplayRetryDelay(s,c,r),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,s,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let i=JSON.stringify({calls:e.map((h,l)=>({args:z(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:l,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&Fo(i)>Ao)return await this.replayBatchedHalves(e,s,r);let{fetchImpl:a}=this,o,c;try{({payload:c,response:o}=await ae(this.rpcTimeoutMs,void 0,async h=>{let l=await a(j(this.url,$t),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...Gt(e.find(p=>p.identity!==void 0)?.identity,r)}),method:"POST",signal:h});if(l.status===413&&e.length>1)return{payload:void 0,response:l};try{return{payload:await l.json(),response:l}}catch{return{payload:void 0,response:l}}}))}catch(h){return this.noteReplayRetryDelay(s,h,r),{requeue:this.keepUnexhaustedAmbiguousWrites(e,h),stop:!0}}let u=o.headers.get("x-d1-bookmark");if(u&&this.bookmark.set(u),o.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let d=o.headers.get("retry-after");if(!c)return this.settleWholeBatchError(e,Ae(o.status,o.statusText,d),s,r);if(!Array.isArray(c.results)){let h=me(c),l=h===void 0?Ae(o.status,o.statusText,d):qt(h,d);return this.settleWholeBatchError(e,l,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof U||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s,i),{requeue:this.keepUnexhaustedAmbiguousWrites(e,s),stop:!0};for(let a of e)this.settleReplayTerminal(a,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),a=await this.replayBatched(e.slice(0,i),s,r);if(a.stop||a.requeue.length>0)return{requeue:[...a.requeue,...e.slice(i)],stop:!0};let o=await this.replayBatched(e.slice(i),s,r);return{requeue:[...a.requeue,...o.requeue],stop:o.stop}}settleReplayBatchSlots(e,s,r,i){let a=Po(s),o=[],c=!1,u=!1;for(let[d,h]of e.entries()){let l=Mo(a.get(d));switch(l.kind){case"committed":{c=!0,this.settleReplaySuccess(h,l.value,l.commitCursor);break}case"errored":{u||=Ie(l.error),this.shouldRequeueReplayFailure(l.error,i)&&!this.spendsLastReplayAttempt(h,l.error)?(this.noteReplayRetryDelay(r,l.error,i),o.push(h)):this.settleReplayTerminal(h,l.error);break}case"unanswered":{let p=Kt();if(this.spendsLastReplayAttempt(h,p)){this.settleReplayTerminal(h,p);break}this.noteReplayRetryDelay(r,p,i),o.push(h);break}default:c=!0,this.settleReplayUndecodable(h,l.error,l.commitCursor)}}return c&&!u&&this.noteCredentialAccepted(i),o}};var Ar=D(as(),1),Fr=D(te(),1);var sc=n(()=>{let t=(0,Ar.c)(4),e=It(),s,r,i;return t[0]!==e?(s=n(a=>e.onConnectionStatus(()=>{a()}),"o"),r=n(()=>e.connectionStatus(),"e"),i=n(()=>e.connectionStatus(),"s"),t[0]=e,t[1]=s,t[2]=r,t[3]=i):(s=t[1],r=t[2],i=t[3]),(0,Fr.useSyncExternalStore)(s,r,i)},"S");export{ge as a,Me as b,B as c,T as d,Xr as e,es as f,ri as g,Se as h,pi as i,fi as j,bi as k,It as l,sc as m};
@@ -1 +1 @@
1
- import{a as re}from"./chunk-EWMBX5N2.js";import{a as X}from"./chunk-R6U22RSY.js";import{a as V}from"./chunk-7Q256NLI.js";import"./chunk-ZKJS6EBE.js";import"./chunk-RGMVGZV4.js";import"./chunk-E4PXACVL.js";import"./chunk-MVWZMWPD.js";import"./chunk-7Y3SY37W.js";import{a as R}from"./chunk-7G4Z6Q7X.js";import"./chunk-3YXASVTP.js";import"./chunk-AUAECCXB.js";import{b as O}from"./chunk-Q6ED4KUL.js";import"./chunk-BOMPSVRC.js";import{a as Y}from"./chunk-4ZPDCXIA.js";import"./chunk-NCPW7WHO.js";import"./chunk-CLXX5RVY.js";import"./chunk-55UGUCQ6.js";import{a as Q}from"./chunk-4ZEL6BYL.js";import{c as J}from"./chunk-ZBHXISOD.js";import"./chunk-X6XAMP4E.js";import"./chunk-QAQDMS6R.js";import"./chunk-NRAAYZ4C.js";import{a as G}from"./chunk-RWVIV3U7.js";import{a as Z,b as ee,c as te,d as P,e as n,f as o}from"./chunk-HCTJKP5J.js";import{a as U,e as W}from"./chunk-2IKDEUCX.js";import{d as z,u as H}from"./chunk-74IYYDDI.js";import{a as l,d as B,e as de,f as me,g as he,i as L}from"./chunk-I26MS5PJ.js";var se=B(me(),1),le=B(de(),1);var t=B(he(),1);var ue={action:"outline",mutation:"default",query:"secondary"},ae=l(r=>r<1e3?`${r<10?r.toFixed(1):Math.round(r).toString()}ms`:`${(r/1e3).toFixed(2)}s`,"q"),fe=l(r=>r.calls===0?"\u2014":r.errors===0?"0":`${r.errors.toString()} (${(r.errors/r.calls*100).toFixed(1)}%)`,"de"),pe=l(r=>{let e=r.conflicts??0;return r.calls===0?"\u2014":e===0?"0":`${e.toString()} (${(e/r.calls*100).toFixed(1)}%)`},"me"),xe={calls:l((r,e)=>e.calls-r.calls,"calls"),recent:l((r,e)=>e.lastCalledAt-r.lastCalledAt,"recent"),slowest:l((r,e)=>e.maxDurationMs-r.maxDurationMs,"slowest")},Ee=l(r=>{let e=(0,se.c)(47),{functions:K,initialShardKey:ne}=r,s=z(),{queryShardKey:_,setShardKey:N,shardKey:v}=X(ne),[i,oe]=(0,le.useState)("recent"),w;e[0]===Symbol.for("react.memo_cache_sentinel")?(w={},e[0]=w):w=e[0];let C;e[1]!==_?(C={live:!0,shardKey:_},e[1]=_,e[2]=C):C=e[2];let{data:ie,error:c,errorSource:S,liveError:b}=J(Q.getFunctionStats,w,C),k=ie?.functions??null,$;e[3]!==K?($=new Map((K??[]).map(ge)),e[3]=K,e[4]=$):$=e[4];let T=$,F;e[5]===Symbol.for("react.memo_cache_sentinel")?(F=l(M=>{oe(M.currentTarget.dataset.sort)},"E"),e[5]=F):F=e[5];let ce=F,I;if(e[6]!==c||e[7]!==S||e[8]!==T||e[9]!==b||e[10]!==N||e[11]!==v||e[12]!==i||e[13]!==k||e[14]!==s){let M=k===null?[]:k.toSorted(xe[i]),d;e[16]!==s?(d=s("Recent"),e[16]=s,e[17]=d):d=e[17];let m;e[18]!==d?(m={key:"recent",label:d},e[18]=d,e[19]=m):m=e[19];let h;e[20]!==s?(h=s("Most called"),e[20]=s,e[21]=h):h=e[21];let u;e[22]!==h?(u={key:"calls",label:h},e[22]=h,e[23]=u):u=e[23];let f;e[24]!==s?(f=s("Slowest"),e[24]=s,e[25]=f):f=e[25];let p;e[26]!==f?(p={key:"slowest",label:f},e[26]=f,e[27]=p):p=e[27];let A;e[28]!==p||e[29]!==m||e[30]!==u?(A=[m,u,p],e[28]=p,e[29]=m,e[30]=u,e[31]=A):A=e[31];let j=A,x;e[32]!==N||e[33]!==v?(x=(0,t.jsx)(V,{onChange:N,testId:"fs-shard-input",value:v}),e[32]=N,e[33]=v,e[34]=x):x=e[34];let g;e[35]!==b?(g=(0,t.jsx)(re,{message:b,prefix:"fs"}),e[35]=b,e[36]=g):g=e[36];let y;e[37]!==j||e[38]!==i?(y=(0,t.jsx)("div",{className:"ml-auto flex items-center gap-1",role:"group",children:j.map(a=>(0,t.jsx)(R,{"data-sort":a.key,"data-testid":`fs-sort-${a.key}`,onClick:ce,size:"sm",type:"button",variant:i===a.key?"secondary":"ghost",children:a.label},a.key))}),e[37]=j,e[38]=i,e[39]=y):y=e[39];let D;e[40]!==x||e[41]!==g||e[42]!==y?(D=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[x,g,y]}),e[40]=x,e[41]=g,e[42]=y,e[43]=D):D=e[43];let E;e[44]!==c||e[45]!==S?(E=c!==null&&(0,t.jsx)(Y,{error:S,testId:"fs-error"}),e[44]=c,e[45]=S,e[46]=E):E=e[46],I=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-function-stats",children:[D,E,k!==null&&M.length===0&&c===null&&(0,t.jsx)(G,{description:s("Per-function call counts, error rates, and latency land here after your first request."),icon:(0,t.jsxs)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:[(0,t.jsx)("path",{d:"M3 3v18h18"}),(0,t.jsx)("path",{d:"M7 14l4-4 3 3 5-6"})]}),testId:"fs-empty",title:s("No functions have run on this shard yet.")}),M.length>0&&(0,t.jsx)(U,{className:"overflow-hidden py-0",children:(0,t.jsx)(W,{className:"px-0",children:(0,t.jsxs)(Z,{"data-testid":"fs-table",children:[(0,t.jsx)(ee,{children:(0,t.jsxs)(P,{children:[(0,t.jsx)(n,{children:s("function")}),(0,t.jsx)(n,{children:s("kind")}),(0,t.jsx)(n,{className:"text-right",children:s("calls")}),(0,t.jsx)(n,{className:"text-right",children:s("errors")}),(0,t.jsx)(n,{className:"text-right",children:s("conflicts")}),(0,t.jsx)(n,{className:"text-right",children:s("avg")}),(0,t.jsx)(n,{className:"text-right",children:s("max")}),(0,t.jsx)(n,{children:s("last run")}),(0,t.jsx)(n,{children:s("last error")})]})}),(0,t.jsx)(te,{children:M.map(a=>{let q=T.get(a.path);return(0,t.jsxs)(P,{"data-testid":`fs-row-${a.path}`,children:[(0,t.jsx)(o,{className:"font-medium",children:a.path}),(0,t.jsx)(o,{children:q===void 0?(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"}):(0,t.jsx)(O,{variant:ue[q],children:q})}),(0,t.jsx)(o,{className:"text-right tabular-nums",children:a.calls}),(0,t.jsx)(o,{className:L("text-right tabular-nums",a.errors>0&&"text-destructive"),children:fe(a)}),(0,t.jsx)(o,{className:L("text-right tabular-nums",(a.conflicts??0)>0&&"text-warning"),children:pe(a)}),(0,t.jsx)(o,{className:"text-right tabular-nums",children:a.calls===0?"\u2014":ae(a.totalDurationMs/a.calls)}),(0,t.jsx)(o,{className:"text-right tabular-nums",children:a.calls===0?"\u2014":ae(a.maxDurationMs)}),(0,t.jsx)(o,{className:"text-muted-foreground",children:H(a.lastCalledAt,"\u2014")}),(0,t.jsx)(o,{className:"max-w-[24ch] truncate text-destructive",title:a.lastErrorMessage??void 0,children:a.lastErrorMessage??(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})})]},a.path)})})]})})})]}),e[6]=c,e[7]=S,e[8]=T,e[9]=b,e[10]=N,e[11]=v,e[12]=i,e[13]=k,e[14]=s,e[15]=I}else I=e[15];return I},"Ae");function ge(r){return[r.path,r.kind]}l(ge,"fe");export{Ee as FunctionStatsPanel};
1
+ import{a as re}from"./chunk-EWMBX5N2.js";import{a as X}from"./chunk-R6U22RSY.js";import{a as V}from"./chunk-7Q256NLI.js";import"./chunk-ZKJS6EBE.js";import"./chunk-RGMVGZV4.js";import"./chunk-E4PXACVL.js";import"./chunk-MVWZMWPD.js";import"./chunk-7Y3SY37W.js";import{a as R}from"./chunk-7G4Z6Q7X.js";import"./chunk-3YXASVTP.js";import"./chunk-AUAECCXB.js";import{b as O}from"./chunk-Q6ED4KUL.js";import"./chunk-BOMPSVRC.js";import{a as Y}from"./chunk-R7SRERCX.js";import"./chunk-NCPW7WHO.js";import"./chunk-RGUL4AQZ.js";import"./chunk-55UGUCQ6.js";import{a as Q}from"./chunk-4ZEL6BYL.js";import{c as J}from"./chunk-QTDX7WSP.js";import"./chunk-KPRNLQKZ.js";import"./chunk-QAQDMS6R.js";import"./chunk-NRAAYZ4C.js";import{a as G}from"./chunk-RWVIV3U7.js";import{a as Z,b as ee,c as te,d as P,e as n,f as o}from"./chunk-HCTJKP5J.js";import{a as U,e as W}from"./chunk-2IKDEUCX.js";import{d as z,u as H}from"./chunk-74IYYDDI.js";import{a as l,d as B,e as de,f as me,g as he,i as L}from"./chunk-I26MS5PJ.js";var se=B(me(),1),le=B(de(),1);var t=B(he(),1);var ue={action:"outline",mutation:"default",query:"secondary"},ae=l(r=>r<1e3?`${r<10?r.toFixed(1):Math.round(r).toString()}ms`:`${(r/1e3).toFixed(2)}s`,"q"),fe=l(r=>r.calls===0?"\u2014":r.errors===0?"0":`${r.errors.toString()} (${(r.errors/r.calls*100).toFixed(1)}%)`,"de"),pe=l(r=>{let e=r.conflicts??0;return r.calls===0?"\u2014":e===0?"0":`${e.toString()} (${(e/r.calls*100).toFixed(1)}%)`},"me"),xe={calls:l((r,e)=>e.calls-r.calls,"calls"),recent:l((r,e)=>e.lastCalledAt-r.lastCalledAt,"recent"),slowest:l((r,e)=>e.maxDurationMs-r.maxDurationMs,"slowest")},Ee=l(r=>{let e=(0,se.c)(47),{functions:K,initialShardKey:ne}=r,s=z(),{queryShardKey:_,setShardKey:N,shardKey:v}=X(ne),[i,oe]=(0,le.useState)("recent"),w;e[0]===Symbol.for("react.memo_cache_sentinel")?(w={},e[0]=w):w=e[0];let C;e[1]!==_?(C={live:!0,shardKey:_},e[1]=_,e[2]=C):C=e[2];let{data:ie,error:c,errorSource:S,liveError:b}=J(Q.getFunctionStats,w,C),k=ie?.functions??null,$;e[3]!==K?($=new Map((K??[]).map(ge)),e[3]=K,e[4]=$):$=e[4];let T=$,F;e[5]===Symbol.for("react.memo_cache_sentinel")?(F=l(M=>{oe(M.currentTarget.dataset.sort)},"E"),e[5]=F):F=e[5];let ce=F,I;if(e[6]!==c||e[7]!==S||e[8]!==T||e[9]!==b||e[10]!==N||e[11]!==v||e[12]!==i||e[13]!==k||e[14]!==s){let M=k===null?[]:k.toSorted(xe[i]),d;e[16]!==s?(d=s("Recent"),e[16]=s,e[17]=d):d=e[17];let m;e[18]!==d?(m={key:"recent",label:d},e[18]=d,e[19]=m):m=e[19];let h;e[20]!==s?(h=s("Most called"),e[20]=s,e[21]=h):h=e[21];let u;e[22]!==h?(u={key:"calls",label:h},e[22]=h,e[23]=u):u=e[23];let f;e[24]!==s?(f=s("Slowest"),e[24]=s,e[25]=f):f=e[25];let p;e[26]!==f?(p={key:"slowest",label:f},e[26]=f,e[27]=p):p=e[27];let A;e[28]!==p||e[29]!==m||e[30]!==u?(A=[m,u,p],e[28]=p,e[29]=m,e[30]=u,e[31]=A):A=e[31];let j=A,x;e[32]!==N||e[33]!==v?(x=(0,t.jsx)(V,{onChange:N,testId:"fs-shard-input",value:v}),e[32]=N,e[33]=v,e[34]=x):x=e[34];let g;e[35]!==b?(g=(0,t.jsx)(re,{message:b,prefix:"fs"}),e[35]=b,e[36]=g):g=e[36];let y;e[37]!==j||e[38]!==i?(y=(0,t.jsx)("div",{className:"ml-auto flex items-center gap-1",role:"group",children:j.map(a=>(0,t.jsx)(R,{"data-sort":a.key,"data-testid":`fs-sort-${a.key}`,onClick:ce,size:"sm",type:"button",variant:i===a.key?"secondary":"ghost",children:a.label},a.key))}),e[37]=j,e[38]=i,e[39]=y):y=e[39];let D;e[40]!==x||e[41]!==g||e[42]!==y?(D=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[x,g,y]}),e[40]=x,e[41]=g,e[42]=y,e[43]=D):D=e[43];let E;e[44]!==c||e[45]!==S?(E=c!==null&&(0,t.jsx)(Y,{error:S,testId:"fs-error"}),e[44]=c,e[45]=S,e[46]=E):E=e[46],I=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-function-stats",children:[D,E,k!==null&&M.length===0&&c===null&&(0,t.jsx)(G,{description:s("Per-function call counts, error rates, and latency land here after your first request."),icon:(0,t.jsxs)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:[(0,t.jsx)("path",{d:"M3 3v18h18"}),(0,t.jsx)("path",{d:"M7 14l4-4 3 3 5-6"})]}),testId:"fs-empty",title:s("No functions have run on this shard yet.")}),M.length>0&&(0,t.jsx)(U,{className:"overflow-hidden py-0",children:(0,t.jsx)(W,{className:"px-0",children:(0,t.jsxs)(Z,{"data-testid":"fs-table",children:[(0,t.jsx)(ee,{children:(0,t.jsxs)(P,{children:[(0,t.jsx)(n,{children:s("function")}),(0,t.jsx)(n,{children:s("kind")}),(0,t.jsx)(n,{className:"text-right",children:s("calls")}),(0,t.jsx)(n,{className:"text-right",children:s("errors")}),(0,t.jsx)(n,{className:"text-right",children:s("conflicts")}),(0,t.jsx)(n,{className:"text-right",children:s("avg")}),(0,t.jsx)(n,{className:"text-right",children:s("max")}),(0,t.jsx)(n,{children:s("last run")}),(0,t.jsx)(n,{children:s("last error")})]})}),(0,t.jsx)(te,{children:M.map(a=>{let q=T.get(a.path);return(0,t.jsxs)(P,{"data-testid":`fs-row-${a.path}`,children:[(0,t.jsx)(o,{className:"font-medium",children:a.path}),(0,t.jsx)(o,{children:q===void 0?(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"}):(0,t.jsx)(O,{variant:ue[q],children:q})}),(0,t.jsx)(o,{className:"text-right tabular-nums",children:a.calls}),(0,t.jsx)(o,{className:L("text-right tabular-nums",a.errors>0&&"text-destructive"),children:fe(a)}),(0,t.jsx)(o,{className:L("text-right tabular-nums",(a.conflicts??0)>0&&"text-warning"),children:pe(a)}),(0,t.jsx)(o,{className:"text-right tabular-nums",children:a.calls===0?"\u2014":ae(a.totalDurationMs/a.calls)}),(0,t.jsx)(o,{className:"text-right tabular-nums",children:a.calls===0?"\u2014":ae(a.maxDurationMs)}),(0,t.jsx)(o,{className:"text-muted-foreground",children:H(a.lastCalledAt,"\u2014")}),(0,t.jsx)(o,{className:"max-w-[24ch] truncate text-destructive",title:a.lastErrorMessage??void 0,children:a.lastErrorMessage??(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})})]},a.path)})})]})})})]}),e[6]=c,e[7]=S,e[8]=T,e[9]=b,e[10]=N,e[11]=v,e[12]=i,e[13]=k,e[14]=s,e[15]=I}else I=e[15];return I},"Ae");function ge(r){return[r.path,r.kind]}l(ge,"fe");export{Ee as FunctionStatsPanel};
@@ -1 +1 @@
1
- import{a as He}from"./chunk-CGQMJYCW.js";import{a as Se}from"./chunk-37WYCOQ2.js";import{a as Ge}from"./chunk-J2OLAMJR.js";import{a as qe}from"./chunk-LXCVA5SP.js";import{i as Ue}from"./chunk-E4PXACVL.js";import"./chunk-MVWZMWPD.js";import"./chunk-7Y3SY37W.js";import{a as $e}from"./chunk-7G4Z6Q7X.js";import"./chunk-3YXASVTP.js";import"./chunk-AUAECCXB.js";import{b as Ze}from"./chunk-Q6ED4KUL.js";import"./chunk-BOMPSVRC.js";import{a as je}from"./chunk-4ZEL6BYL.js";import{l as Ke}from"./chunk-X6XAMP4E.js";import"./chunk-QAQDMS6R.js";import"./chunk-NRAAYZ4C.js";import{d as Pe,f as Fe,g as me,h as Ce,i as Oe,q as Re}from"./chunk-74IYYDDI.js";import{a as s,d as Me,e as ot,f as at,g as lt}from"./chunk-I26MS5PJ.js";var De=Me(at(),1);var m=Me(ot(),1);var r=Me(lt(),1);var ze=Fe(je.getPitrBookmark),st=Fe(je.pitrRestore),nt=/^\d+$/u,Je=s(ie=>{let e=ie.trim(),h=nt.test(e)?Number(e):Date.parse(e),l=new Date(h);return Number.isNaN(l.getTime())?void 0:{epochMs:h,iso:l.toISOString()}},"De"),it=s(ie=>{let e=(0,De.c)(9),{text:h}=ie,l=Pe();if(h.trim()==="")return null;let t,o,p;if(e[0]!==l||e[1]!==h){let y=Je(h);t="font-mono text-xs text-muted-foreground",o="pitr-time-resolved",p=y===void 0?l("Not a time \u2014 use epoch-ms or ISO 8601."):l("Resolves to {instant} (a date-time without an offset is read in this browser's time zone; a bare date is UTC)",{instant:y.iso}),e[0]=l,e[1]=h,e[2]=t,e[3]=o,e[4]=p}else t=e[2],o=e[3],p=e[4];let N;return e[5]!==t||e[6]!==o||e[7]!==p?(N=(0,r.jsx)("p",{className:t,"data-testid":o,children:p}),e[5]=t,e[6]=o,e[7]=p,e[8]=N):N=e[8],N},"lt"),vt=s(ie=>{let e=(0,De.c)(140),{initialShardKey:h}=ie,l=Ke(),t=Pe(),o=h??"",p=He(o),[N,y]=(0,m.useState)(null),[f,Qe]=(0,m.useState)(""),[ce,Ee]=(0,m.useState)(null),[c,We]=(0,m.useState)(""),[b,Xe]=(0,m.useState)(!1),[i,Ye]=(0,m.useState)(null),[ue,w]=(0,m.useState)(null),[de,I]=(0,m.useState)(!1),[C,Ve]=(0,m.useState)(!1),pe;e[0]!==l||e[1]!==o?(pe=s(async a=>{I(!0),w(null);let d;try{d={current:(await l.query(ze,{},me(o))).current,error:null,unavailable:!1}}catch(n){let g=n;d={current:null,error:Ce(g),unavailable:Oe(g)==="PITR_UNAVAILABLE"}}a?.aborted!==!0&&(d.error===null?y(d.current):w(d.error),Ve(d.unavailable),I(!1))},"fe"),e[0]=l,e[1]=o,e[2]=pe):pe=e[2];let x=pe,he,fe;e[3]!==x?(he=s(()=>{let a=new AbortController;return Re(x(a.signal)),()=>{a.abort()}},"ue"),fe=[x],e[3]=x,e[4]=he,e[5]=fe):(he=e[4],fe=e[5]),(0,m.useEffect)(he,fe);let be;e[6]!==l||e[7]!==o?(be=s(async()=>{let a=await l.query(ze,{},me(o));y(a.current)},"he"),e[6]=l,e[7]=o,e[8]=be):be=e[8],Ge(be,!C);let xe;e[9]===Symbol.for("react.memo_cache_sentinel")?(xe=s(a=>{Qe(a.target.value)},"be"),e[9]=xe):xe=e[9];let et=xe,ke;e[10]===Symbol.for("react.memo_cache_sentinel")?(ke=s(a=>{We(a.target.value)},"xe"),e[10]=ke):ke=e[10];let tt=ke,Ne;e[11]===Symbol.for("react.memo_cache_sentinel")?(Ne=s(a=>{Xe(a.target.checked)},"ke"),e[11]=Ne):Ne=e[11];let rt=Ne,ve,R,u,k,v,ge;if(e[12]!==c||e[13]!==l||e[14]!==ce||e[15]!==x||e[16]!==o||e[17]!==p||e[18]!==t||e[19]!==f){u=Je(f),R=s(()=>{if(u===void 0)return;let d=o;Re((async()=>{I(!0),w(null);let n;try{n={result:await l.query(ze,{time:u.epochMs},me(d))}}catch(g){n={error:Ce(g)}}p.current===d&&("result"in n?(Ee(n.result.forTime===void 0?null:{bookmark:n.result.forTime,shard:d}),y(n.result.current)):(Ee(null),w(n.error)),I(!1))})())},"C"),v=ce?.shard===o?ce.bookmark:null;let a;e[26]!==l||e[27]!==x||e[28]!==o?(a=s(d=>{Re((async()=>{I(!0),w(null);try{let n=await l.mutation(st,d,me(o));Ye(n),await x()}catch(n){let g=n;w(Ce(g)),Oe(g)==="PITR_UNAVAILABLE"&&Ve(!0)}I(!1)})())},"o"),e[26]=l,e[27]=x,e[28]=o,e[29]=a):a=e[29],k=a,ve=c.trim()!==""||u!==void 0,ge=t("Restore {shard} to {target}?",{shard:o===""?t("root"):o,target:c.trim()===""?u?.iso??"":t("the given bookmark")}),e[12]=c,e[13]=l,e[14]=ce,e[15]=x,e[16]=o,e[17]=p,e[18]=t,e[19]=f,e[20]=ve,e[21]=R,e[22]=u,e[23]=k,e[24]=v,e[25]=ge}else ve=e[20],R=e[21],u=e[22],k=e[23],v=e[24],ge=e[25];let Te=ge,ye;e[30]!==c||e[31]!==u?.epochMs||e[32]!==b||e[33]!==k?(ye=s(()=>{let a=b?{restart:!0}:{};c.trim()===""?a.time=u?.epochMs:a.bookmark=c.trim(),k(a)},"Ne"),e[30]=c,e[31]=u?.epochMs,e[32]=b,e[33]=k,e[34]=ye):ye=e[34];let Be=ye,we;e[35]!==b||e[36]!==i||e[37]!==k?(we=s(()=>{i!==null&&k(b?{bookmark:i.undoBookmark,restart:!0}:{bookmark:i.undoBookmark})},"ye"),e[35]=b,e[36]=i,e[37]=k,e[38]=we):we=e[38];let Ae=we,S;e[39]!==t?(S=t("Shard"),e[39]=t,e[40]=S):S=e[40];let T;e[41]!==o||e[42]!==t?(T=o===""?t("root"):o,e[41]=o,e[42]=t,e[43]=T):T=e[43];let B;e[44]!==T?(B=(0,r.jsx)("span",{className:"font-mono",children:T}),e[44]=T,e[45]=B):B=e[45];let A;e[46]!==S||e[47]!==B?(A=(0,r.jsx)("div",{className:"flex flex-wrap items-center gap-3",children:(0,r.jsxs)("span",{className:"text-xs text-muted-foreground",children:[S,": ",B]})}),e[46]=S,e[47]=B,e[48]=A):A=e[48];let _;e[49]!==t?(_=t("In-place recovery to any moment in the last 30 days. For older or portable recovery, use the snapshot backup tier."),e[49]=t,e[50]=_):_=e[50];let L;e[51]!==_?(L=(0,r.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"pitr-note",children:_}),e[51]=_,e[52]=L):L=e[52];let M;e[53]!==ue?(M=ue!==null&&(0,r.jsx)("p",{className:"text-sm text-destructive","data-testid":"pitr-error",role:"alert",children:ue}),e[53]=ue,e[54]=M):M=e[54];let P;e[55]!==t?(P=t("Current bookmark"),e[55]=t,e[56]=P):P=e[56];let U;e[57]!==P?(U=(0,r.jsx)("h3",{className:"mb-2 text-sm font-semibold",children:P}),e[57]=P,e[58]=U):U=e[58];let F;e[59]!==N?(F=N??(0,r.jsx)("span",{className:"text-muted-foreground",children:"\u2014"}),e[59]=N,e[60]=F):F=e[60];let O;e[61]!==F?(O=(0,r.jsx)("p",{className:"font-mono text-xs break-all text-muted-foreground","data-testid":"pitr-current",children:F}),e[61]=F,e[62]=O):O=e[62];let j;e[63]!==U||e[64]!==O?(j=(0,r.jsxs)("section",{className:"rounded-xl border border-border bg-card p-3 shadow-xs",children:[U,O]}),e[63]=U,e[64]=O,e[65]=j):j=e[65];let q;e[66]!==t?(q=t("Restore"),e[66]=t,e[67]=q):q=e[67];let z;e[68]!==q?(z=(0,r.jsx)("h3",{className:"text-sm font-semibold",children:q}),e[68]=q,e[69]=z):z=e[69];let D;e[70]!==t?(D=t("Time (ISO or epoch-ms, last 30 days)"),e[70]=t,e[71]=D):D=e[71];let E;e[72]!==D?(E=(0,r.jsx)(Se,{htmlFor:"pitr-time",children:D}),e[72]=D,e[73]=E):E=e[73];let V;e[74]!==f?(V=(0,r.jsx)(Ue,{"data-testid":"pitr-time",id:"pitr-time",onChange:et,placeholder:"2026-06-01T00:00:00.000Z",value:f}),e[74]=f,e[75]=V):V=e[75];let _e=de||C||u===void 0,K;e[76]!==t?(K=t("Preview"),e[76]=t,e[77]=K):K=e[77];let Z;e[78]!==R||e[79]!==_e||e[80]!==K?(Z=(0,r.jsx)($e,{"data-testid":"pitr-preview",disabled:_e,onClick:R,size:"sm",type:"button",variant:"outline",children:K}),e[78]=R,e[79]=_e,e[80]=K,e[81]=Z):Z=e[81];let $;e[82]!==V||e[83]!==Z?($=(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[V,Z]}),e[82]=V,e[83]=Z,e[84]=$):$=e[84];let G;e[85]!==f?(G=(0,r.jsx)(it,{text:f}),e[85]=f,e[86]=G):G=e[86];let H;e[87]!==v||e[88]!==t?(H=v!==null&&(0,r.jsxs)("p",{className:"font-mono text-xs break-all text-muted-foreground","data-testid":"pitr-preview-bookmark",children:[t("Bookmark for that time"),": ",v]}),e[87]=v,e[88]=t,e[89]=H):H=e[89];let J;e[90]!==E||e[91]!==$||e[92]!==G||e[93]!==H?(J=(0,r.jsxs)("div",{className:"flex flex-col gap-1",children:[E,$,G,H]}),e[90]=E,e[91]=$,e[92]=G,e[93]=H,e[94]=J):J=e[94];let Q;e[95]!==t?(Q=t("Or an explicit bookmark (wins over time)"),e[95]=t,e[96]=Q):Q=e[96];let W;e[97]!==Q?(W=(0,r.jsx)(Se,{htmlFor:"pitr-bookmark",children:Q}),e[97]=Q,e[98]=W):W=e[98];let X;e[99]!==t?(X=t("bookmark string"),e[99]=t,e[100]=X):X=e[100];let Y;e[101]!==c||e[102]!==X?(Y=(0,r.jsx)(Ue,{"data-testid":"pitr-bookmark",id:"pitr-bookmark",onChange:tt,placeholder:X,value:c}),e[101]=c,e[102]=X,e[103]=Y):Y=e[103];let ee;e[104]!==W||e[105]!==Y?(ee=(0,r.jsxs)("div",{className:"flex flex-col gap-1",children:[W,Y]}),e[104]=W,e[105]=Y,e[106]=ee):ee=e[106];let te;e[107]!==b?(te=(0,r.jsx)("input",{checked:b,className:"size-4 accent-primary","data-testid":"pitr-restart",id:"pitr-restart",onChange:rt,type:"checkbox"}),e[107]=b,e[108]=te):te=e[108];let re;e[109]!==t?(re=t("Restart the shard now so recovery applies immediately"),e[109]=t,e[110]=re):re=e[110];let oe;e[111]!==te||e[112]!==re?(oe=(0,r.jsxs)(Se,{className:"flex items-center gap-2 text-xs font-normal text-muted-foreground",htmlFor:"pitr-restart",children:[te,re]}),e[111]=te,e[112]=re,e[113]=oe):oe=e[113];let Le=de||C||!ve,ae;e[114]!==t?(ae=t("Restore"),e[114]=t,e[115]=ae):ae=e[115];let le;e[116]!==Te||e[117]!==Be||e[118]!==Le||e[119]!==ae?(le=(0,r.jsx)("div",{children:(0,r.jsx)(qe,{confirmLabel:Te,disabled:Le,onConfirm:Be,testId:"pitr-restore",children:ae})}),e[116]=Te,e[117]=Be,e[118]=Le,e[119]=ae,e[120]=le):le=e[120];let se;e[121]!==z||e[122]!==J||e[123]!==ee||e[124]!==oe||e[125]!==le?(se=(0,r.jsxs)("section",{className:"flex flex-col gap-3 rounded-xl border border-border bg-card p-3 shadow-xs",children:[z,J,ee,oe,le]}),e[121]=z,e[122]=J,e[123]=ee,e[124]=oe,e[125]=le,e[126]=se):se=e[126];let ne;e[127]!==de||e[128]!==Ae||e[129]!==i||e[130]!==t||e[131]!==C?(ne=i!==null&&(0,r.jsxs)("section",{className:"flex flex-col gap-2 rounded-xl border border-border bg-card p-3 shadow-xs","data-testid":"pitr-result",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("h3",{className:"text-sm font-semibold",children:t("Restore armed")}),(0,r.jsx)(Ze,{variant:i.restarted?"destructive":"secondary",children:i.restarted?t("restarted now"):t("on next restart")})]}),(0,r.jsxs)("p",{className:"font-mono text-xs break-all text-muted-foreground",children:[t("Restored to"),": ",i.restoredTo]}),(0,r.jsxs)("p",{className:"font-mono text-xs break-all text-muted-foreground","data-testid":"pitr-undo-bookmark",children:[t("Undo bookmark"),": ",i.undoBookmark]}),(0,r.jsx)("div",{children:(0,r.jsx)(qe,{confirmLabel:t("Confirm undo"),disabled:de||C,onConfirm:Ae,testId:"pitr-undo",children:t("Undo restore")})})]}),e[127]=de,e[128]=Ae,e[129]=i,e[130]=t,e[131]=C,e[132]=ne):ne=e[132];let Ie;return e[133]!==A||e[134]!==L||e[135]!==M||e[136]!==j||e[137]!==se||e[138]!==ne?(Ie=(0,r.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-pitr",children:[A,L,M,j,se,ne]}),e[133]=A,e[134]=L,e[135]=M,e[136]=j,e[137]=se,e[138]=ne,e[139]=Ie):Ie=e[139],Ie},"Nt");export{vt as PitrPanel};
1
+ import{a as He}from"./chunk-CGQMJYCW.js";import{a as Se}from"./chunk-37WYCOQ2.js";import{a as Ge}from"./chunk-3ZVTL2VM.js";import{a as qe}from"./chunk-LXCVA5SP.js";import{i as Ue}from"./chunk-E4PXACVL.js";import"./chunk-MVWZMWPD.js";import"./chunk-7Y3SY37W.js";import{a as $e}from"./chunk-7G4Z6Q7X.js";import"./chunk-3YXASVTP.js";import"./chunk-AUAECCXB.js";import{b as Ze}from"./chunk-Q6ED4KUL.js";import"./chunk-BOMPSVRC.js";import{a as je}from"./chunk-4ZEL6BYL.js";import{l as Ke}from"./chunk-KPRNLQKZ.js";import"./chunk-QAQDMS6R.js";import"./chunk-NRAAYZ4C.js";import{d as Pe,f as Fe,g as me,h as Ce,i as Oe,q as Re}from"./chunk-74IYYDDI.js";import{a as s,d as Me,e as ot,f as at,g as lt}from"./chunk-I26MS5PJ.js";var De=Me(at(),1);var m=Me(ot(),1);var r=Me(lt(),1);var ze=Fe(je.getPitrBookmark),st=Fe(je.pitrRestore),nt=/^\d+$/u,Je=s(ie=>{let e=ie.trim(),h=nt.test(e)?Number(e):Date.parse(e),l=new Date(h);return Number.isNaN(l.getTime())?void 0:{epochMs:h,iso:l.toISOString()}},"De"),it=s(ie=>{let e=(0,De.c)(9),{text:h}=ie,l=Pe();if(h.trim()==="")return null;let t,o,p;if(e[0]!==l||e[1]!==h){let y=Je(h);t="font-mono text-xs text-muted-foreground",o="pitr-time-resolved",p=y===void 0?l("Not a time \u2014 use epoch-ms or ISO 8601."):l("Resolves to {instant} (a date-time without an offset is read in this browser's time zone; a bare date is UTC)",{instant:y.iso}),e[0]=l,e[1]=h,e[2]=t,e[3]=o,e[4]=p}else t=e[2],o=e[3],p=e[4];let N;return e[5]!==t||e[6]!==o||e[7]!==p?(N=(0,r.jsx)("p",{className:t,"data-testid":o,children:p}),e[5]=t,e[6]=o,e[7]=p,e[8]=N):N=e[8],N},"lt"),vt=s(ie=>{let e=(0,De.c)(140),{initialShardKey:h}=ie,l=Ke(),t=Pe(),o=h??"",p=He(o),[N,y]=(0,m.useState)(null),[f,Qe]=(0,m.useState)(""),[ce,Ee]=(0,m.useState)(null),[c,We]=(0,m.useState)(""),[b,Xe]=(0,m.useState)(!1),[i,Ye]=(0,m.useState)(null),[ue,w]=(0,m.useState)(null),[de,I]=(0,m.useState)(!1),[C,Ve]=(0,m.useState)(!1),pe;e[0]!==l||e[1]!==o?(pe=s(async a=>{I(!0),w(null);let d;try{d={current:(await l.query(ze,{},me(o))).current,error:null,unavailable:!1}}catch(n){let g=n;d={current:null,error:Ce(g),unavailable:Oe(g)==="PITR_UNAVAILABLE"}}a?.aborted!==!0&&(d.error===null?y(d.current):w(d.error),Ve(d.unavailable),I(!1))},"fe"),e[0]=l,e[1]=o,e[2]=pe):pe=e[2];let x=pe,he,fe;e[3]!==x?(he=s(()=>{let a=new AbortController;return Re(x(a.signal)),()=>{a.abort()}},"ue"),fe=[x],e[3]=x,e[4]=he,e[5]=fe):(he=e[4],fe=e[5]),(0,m.useEffect)(he,fe);let be;e[6]!==l||e[7]!==o?(be=s(async()=>{let a=await l.query(ze,{},me(o));y(a.current)},"he"),e[6]=l,e[7]=o,e[8]=be):be=e[8],Ge(be,!C);let xe;e[9]===Symbol.for("react.memo_cache_sentinel")?(xe=s(a=>{Qe(a.target.value)},"be"),e[9]=xe):xe=e[9];let et=xe,ke;e[10]===Symbol.for("react.memo_cache_sentinel")?(ke=s(a=>{We(a.target.value)},"xe"),e[10]=ke):ke=e[10];let tt=ke,Ne;e[11]===Symbol.for("react.memo_cache_sentinel")?(Ne=s(a=>{Xe(a.target.checked)},"ke"),e[11]=Ne):Ne=e[11];let rt=Ne,ve,R,u,k,v,ge;if(e[12]!==c||e[13]!==l||e[14]!==ce||e[15]!==x||e[16]!==o||e[17]!==p||e[18]!==t||e[19]!==f){u=Je(f),R=s(()=>{if(u===void 0)return;let d=o;Re((async()=>{I(!0),w(null);let n;try{n={result:await l.query(ze,{time:u.epochMs},me(d))}}catch(g){n={error:Ce(g)}}p.current===d&&("result"in n?(Ee(n.result.forTime===void 0?null:{bookmark:n.result.forTime,shard:d}),y(n.result.current)):(Ee(null),w(n.error)),I(!1))})())},"C"),v=ce?.shard===o?ce.bookmark:null;let a;e[26]!==l||e[27]!==x||e[28]!==o?(a=s(d=>{Re((async()=>{I(!0),w(null);try{let n=await l.mutation(st,d,me(o));Ye(n),await x()}catch(n){let g=n;w(Ce(g)),Oe(g)==="PITR_UNAVAILABLE"&&Ve(!0)}I(!1)})())},"o"),e[26]=l,e[27]=x,e[28]=o,e[29]=a):a=e[29],k=a,ve=c.trim()!==""||u!==void 0,ge=t("Restore {shard} to {target}?",{shard:o===""?t("root"):o,target:c.trim()===""?u?.iso??"":t("the given bookmark")}),e[12]=c,e[13]=l,e[14]=ce,e[15]=x,e[16]=o,e[17]=p,e[18]=t,e[19]=f,e[20]=ve,e[21]=R,e[22]=u,e[23]=k,e[24]=v,e[25]=ge}else ve=e[20],R=e[21],u=e[22],k=e[23],v=e[24],ge=e[25];let Te=ge,ye;e[30]!==c||e[31]!==u?.epochMs||e[32]!==b||e[33]!==k?(ye=s(()=>{let a=b?{restart:!0}:{};c.trim()===""?a.time=u?.epochMs:a.bookmark=c.trim(),k(a)},"Ne"),e[30]=c,e[31]=u?.epochMs,e[32]=b,e[33]=k,e[34]=ye):ye=e[34];let Be=ye,we;e[35]!==b||e[36]!==i||e[37]!==k?(we=s(()=>{i!==null&&k(b?{bookmark:i.undoBookmark,restart:!0}:{bookmark:i.undoBookmark})},"ye"),e[35]=b,e[36]=i,e[37]=k,e[38]=we):we=e[38];let Ae=we,S;e[39]!==t?(S=t("Shard"),e[39]=t,e[40]=S):S=e[40];let T;e[41]!==o||e[42]!==t?(T=o===""?t("root"):o,e[41]=o,e[42]=t,e[43]=T):T=e[43];let B;e[44]!==T?(B=(0,r.jsx)("span",{className:"font-mono",children:T}),e[44]=T,e[45]=B):B=e[45];let A;e[46]!==S||e[47]!==B?(A=(0,r.jsx)("div",{className:"flex flex-wrap items-center gap-3",children:(0,r.jsxs)("span",{className:"text-xs text-muted-foreground",children:[S,": ",B]})}),e[46]=S,e[47]=B,e[48]=A):A=e[48];let _;e[49]!==t?(_=t("In-place recovery to any moment in the last 30 days. For older or portable recovery, use the snapshot backup tier."),e[49]=t,e[50]=_):_=e[50];let L;e[51]!==_?(L=(0,r.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"pitr-note",children:_}),e[51]=_,e[52]=L):L=e[52];let M;e[53]!==ue?(M=ue!==null&&(0,r.jsx)("p",{className:"text-sm text-destructive","data-testid":"pitr-error",role:"alert",children:ue}),e[53]=ue,e[54]=M):M=e[54];let P;e[55]!==t?(P=t("Current bookmark"),e[55]=t,e[56]=P):P=e[56];let U;e[57]!==P?(U=(0,r.jsx)("h3",{className:"mb-2 text-sm font-semibold",children:P}),e[57]=P,e[58]=U):U=e[58];let F;e[59]!==N?(F=N??(0,r.jsx)("span",{className:"text-muted-foreground",children:"\u2014"}),e[59]=N,e[60]=F):F=e[60];let O;e[61]!==F?(O=(0,r.jsx)("p",{className:"font-mono text-xs break-all text-muted-foreground","data-testid":"pitr-current",children:F}),e[61]=F,e[62]=O):O=e[62];let j;e[63]!==U||e[64]!==O?(j=(0,r.jsxs)("section",{className:"rounded-xl border border-border bg-card p-3 shadow-xs",children:[U,O]}),e[63]=U,e[64]=O,e[65]=j):j=e[65];let q;e[66]!==t?(q=t("Restore"),e[66]=t,e[67]=q):q=e[67];let z;e[68]!==q?(z=(0,r.jsx)("h3",{className:"text-sm font-semibold",children:q}),e[68]=q,e[69]=z):z=e[69];let D;e[70]!==t?(D=t("Time (ISO or epoch-ms, last 30 days)"),e[70]=t,e[71]=D):D=e[71];let E;e[72]!==D?(E=(0,r.jsx)(Se,{htmlFor:"pitr-time",children:D}),e[72]=D,e[73]=E):E=e[73];let V;e[74]!==f?(V=(0,r.jsx)(Ue,{"data-testid":"pitr-time",id:"pitr-time",onChange:et,placeholder:"2026-06-01T00:00:00.000Z",value:f}),e[74]=f,e[75]=V):V=e[75];let _e=de||C||u===void 0,K;e[76]!==t?(K=t("Preview"),e[76]=t,e[77]=K):K=e[77];let Z;e[78]!==R||e[79]!==_e||e[80]!==K?(Z=(0,r.jsx)($e,{"data-testid":"pitr-preview",disabled:_e,onClick:R,size:"sm",type:"button",variant:"outline",children:K}),e[78]=R,e[79]=_e,e[80]=K,e[81]=Z):Z=e[81];let $;e[82]!==V||e[83]!==Z?($=(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[V,Z]}),e[82]=V,e[83]=Z,e[84]=$):$=e[84];let G;e[85]!==f?(G=(0,r.jsx)(it,{text:f}),e[85]=f,e[86]=G):G=e[86];let H;e[87]!==v||e[88]!==t?(H=v!==null&&(0,r.jsxs)("p",{className:"font-mono text-xs break-all text-muted-foreground","data-testid":"pitr-preview-bookmark",children:[t("Bookmark for that time"),": ",v]}),e[87]=v,e[88]=t,e[89]=H):H=e[89];let J;e[90]!==E||e[91]!==$||e[92]!==G||e[93]!==H?(J=(0,r.jsxs)("div",{className:"flex flex-col gap-1",children:[E,$,G,H]}),e[90]=E,e[91]=$,e[92]=G,e[93]=H,e[94]=J):J=e[94];let Q;e[95]!==t?(Q=t("Or an explicit bookmark (wins over time)"),e[95]=t,e[96]=Q):Q=e[96];let W;e[97]!==Q?(W=(0,r.jsx)(Se,{htmlFor:"pitr-bookmark",children:Q}),e[97]=Q,e[98]=W):W=e[98];let X;e[99]!==t?(X=t("bookmark string"),e[99]=t,e[100]=X):X=e[100];let Y;e[101]!==c||e[102]!==X?(Y=(0,r.jsx)(Ue,{"data-testid":"pitr-bookmark",id:"pitr-bookmark",onChange:tt,placeholder:X,value:c}),e[101]=c,e[102]=X,e[103]=Y):Y=e[103];let ee;e[104]!==W||e[105]!==Y?(ee=(0,r.jsxs)("div",{className:"flex flex-col gap-1",children:[W,Y]}),e[104]=W,e[105]=Y,e[106]=ee):ee=e[106];let te;e[107]!==b?(te=(0,r.jsx)("input",{checked:b,className:"size-4 accent-primary","data-testid":"pitr-restart",id:"pitr-restart",onChange:rt,type:"checkbox"}),e[107]=b,e[108]=te):te=e[108];let re;e[109]!==t?(re=t("Restart the shard now so recovery applies immediately"),e[109]=t,e[110]=re):re=e[110];let oe;e[111]!==te||e[112]!==re?(oe=(0,r.jsxs)(Se,{className:"flex items-center gap-2 text-xs font-normal text-muted-foreground",htmlFor:"pitr-restart",children:[te,re]}),e[111]=te,e[112]=re,e[113]=oe):oe=e[113];let Le=de||C||!ve,ae;e[114]!==t?(ae=t("Restore"),e[114]=t,e[115]=ae):ae=e[115];let le;e[116]!==Te||e[117]!==Be||e[118]!==Le||e[119]!==ae?(le=(0,r.jsx)("div",{children:(0,r.jsx)(qe,{confirmLabel:Te,disabled:Le,onConfirm:Be,testId:"pitr-restore",children:ae})}),e[116]=Te,e[117]=Be,e[118]=Le,e[119]=ae,e[120]=le):le=e[120];let se;e[121]!==z||e[122]!==J||e[123]!==ee||e[124]!==oe||e[125]!==le?(se=(0,r.jsxs)("section",{className:"flex flex-col gap-3 rounded-xl border border-border bg-card p-3 shadow-xs",children:[z,J,ee,oe,le]}),e[121]=z,e[122]=J,e[123]=ee,e[124]=oe,e[125]=le,e[126]=se):se=e[126];let ne;e[127]!==de||e[128]!==Ae||e[129]!==i||e[130]!==t||e[131]!==C?(ne=i!==null&&(0,r.jsxs)("section",{className:"flex flex-col gap-2 rounded-xl border border-border bg-card p-3 shadow-xs","data-testid":"pitr-result",children:[(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)("h3",{className:"text-sm font-semibold",children:t("Restore armed")}),(0,r.jsx)(Ze,{variant:i.restarted?"destructive":"secondary",children:i.restarted?t("restarted now"):t("on next restart")})]}),(0,r.jsxs)("p",{className:"font-mono text-xs break-all text-muted-foreground",children:[t("Restored to"),": ",i.restoredTo]}),(0,r.jsxs)("p",{className:"font-mono text-xs break-all text-muted-foreground","data-testid":"pitr-undo-bookmark",children:[t("Undo bookmark"),": ",i.undoBookmark]}),(0,r.jsx)("div",{children:(0,r.jsx)(qe,{confirmLabel:t("Confirm undo"),disabled:de||C,onConfirm:Ae,testId:"pitr-undo",children:t("Undo restore")})})]}),e[127]=de,e[128]=Ae,e[129]=i,e[130]=t,e[131]=C,e[132]=ne):ne=e[132];let Ie;return e[133]!==A||e[134]!==L||e[135]!==M||e[136]!==j||e[137]!==se||e[138]!==ne?(Ie=(0,r.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-pitr",children:[A,L,M,j,se,ne]}),e[133]=A,e[134]=L,e[135]=M,e[136]=j,e[137]=se,e[138]=ne,e[139]=Ie):Ie=e[139],Ie},"Nt");export{vt as PitrPanel};