@lunora/studio 1.0.0-alpha.157 → 1.0.0-alpha.158

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 (75) hide show
  1. package/dist/index.mjs +1 -1
  2. package/dist/packem_chunks/ExportImportPanel.mjs +1 -1
  3. package/dist/packem_chunks/SqlEditorPanel.mjs +1 -1
  4. package/dist/packem_chunks/TableEditor.mjs +1 -1
  5. package/dist/packem_chunks/payments-panel.mjs +1 -1
  6. package/dist/packem_shared/{DataBrowser-FiF2tNdq.mjs → DataBrowser-DIbS5LdO.mjs} +1 -1
  7. package/dist/packem_shared/wire-codec-Bk4XZGE4.mjs +1 -0
  8. package/dist/standalone/{chunk-Y4S6PSQJ.js → chunk-2R6A5EW3.js} +1 -1
  9. package/dist/standalone/{chunk-3SCT7QG7.js → chunk-3AZM3E32.js} +1 -1
  10. package/dist/standalone/{chunk-HETDJ4ZA.js → chunk-4R4TLEW4.js} +1 -1
  11. package/dist/standalone/{chunk-YVNA6TPB.js → chunk-4RPIDBYG.js} +1 -1
  12. package/dist/standalone/chunk-4U4NQF6Z.js +11 -0
  13. package/dist/standalone/{chunk-KEXRHVLN.js → chunk-4VIIFF27.js} +1 -1
  14. package/dist/standalone/{chunk-SZD6O7K2.js → chunk-4XET6RVK.js} +1 -1
  15. package/dist/standalone/{chunk-57JVL7N6.js → chunk-54DXA67B.js} +1 -1
  16. package/dist/standalone/{chunk-KJGAW36O.js → chunk-5YW4HMKS.js} +1 -1
  17. package/dist/standalone/{chunk-CNBQXYLI.js → chunk-6WU5TU4K.js} +1 -1
  18. package/dist/standalone/{chunk-6BI6AL3F.js → chunk-6XDE6XBT.js} +1 -1
  19. package/dist/standalone/{chunk-M2KEQODB.js → chunk-75WY42CK.js} +1 -1
  20. package/dist/standalone/{chunk-BFPZHZ5M.js → chunk-7J3BP6A2.js} +1 -1
  21. package/dist/standalone/{chunk-BNMKGBRO.js → chunk-A7STWYAF.js} +1 -1
  22. package/dist/standalone/{chunk-L2PBRJ7G.js → chunk-AFQFZUSP.js} +1 -1
  23. package/dist/standalone/{chunk-VVIGMZZI.js → chunk-ALA3CMOP.js} +2 -2
  24. package/dist/standalone/{chunk-ENE4N6ZV.js → chunk-B4Y5TD2V.js} +1 -1
  25. package/dist/standalone/{chunk-LPTEXH2G.js → chunk-C4JJO35X.js} +1 -1
  26. package/dist/standalone/{chunk-T3NZUPJT.js → chunk-CCTHN7Y5.js} +1 -1
  27. package/dist/standalone/{chunk-UAA6K2G3.js → chunk-DKZVR6OX.js} +1 -1
  28. package/dist/standalone/{chunk-CJMZSHN3.js → chunk-EEARNRS4.js} +1 -1
  29. package/dist/standalone/{chunk-NJSJI7SX.js → chunk-EESOT5SI.js} +1 -1
  30. package/dist/standalone/{chunk-7VYWS2FY.js → chunk-ENAJ7ZGF.js} +1 -1
  31. package/dist/standalone/{chunk-3BOMO6FO.js → chunk-FINSZ5UO.js} +1 -1
  32. package/dist/standalone/{chunk-FFSMP4KF.js → chunk-GOWMX76X.js} +1 -1
  33. package/dist/standalone/{chunk-MAIRKGBC.js → chunk-HO2JCLD3.js} +1 -1
  34. package/dist/standalone/{chunk-BHRODRCE.js → chunk-HTNMN5BE.js} +1 -1
  35. package/dist/standalone/{chunk-M5ITKPZN.js → chunk-JAO5VFWP.js} +1 -1
  36. package/dist/standalone/{chunk-4YPDEUPJ.js → chunk-KHD4GTIN.js} +1 -1
  37. package/dist/standalone/{chunk-BI3WYQT4.js → chunk-KW5HOSVL.js} +1 -1
  38. package/dist/standalone/{chunk-JXZBR6KQ.js → chunk-LAYMTAJV.js} +1 -1
  39. package/dist/standalone/{chunk-ZUFIKCHC.js → chunk-LFB3N7PK.js} +1 -1
  40. package/dist/standalone/{chunk-BF4ANX7Y.js → chunk-LWEYPOIZ.js} +1 -1
  41. package/dist/standalone/{chunk-7SPAXZ55.js → chunk-MQ42VLOS.js} +1 -1
  42. package/dist/standalone/{chunk-YMWPOBTZ.js → chunk-MTCI2I76.js} +1 -1
  43. package/dist/standalone/{chunk-IBCJ44SS.js → chunk-OUEBKYP6.js} +1 -1
  44. package/dist/standalone/{chunk-PEC7L2M2.js → chunk-PBDVZTOX.js} +1 -1
  45. package/dist/standalone/{chunk-CXNY45A3.js → chunk-PH5MPNFE.js} +1 -1
  46. package/dist/standalone/{chunk-J2REGA6E.js → chunk-RGFVCR5I.js} +1 -1
  47. package/dist/standalone/{chunk-B7IXABRK.js → chunk-RUS2PBWB.js} +1 -1
  48. package/dist/standalone/chunk-RZNN2EJU.js +15 -0
  49. package/dist/standalone/{chunk-Q2XPCZNR.js → chunk-S4OCAMLF.js} +1 -1
  50. package/dist/standalone/{chunk-2GUY4BYT.js → chunk-SAYKLOOF.js} +1 -1
  51. package/dist/standalone/{chunk-HMRLSE2Y.js → chunk-SC4UPHXM.js} +1 -1
  52. package/dist/standalone/{chunk-ODULTMQE.js → chunk-TAPHCTSY.js} +1 -1
  53. package/dist/standalone/{chunk-FAIPFZHS.js → chunk-TF32L7YZ.js} +1 -1
  54. package/dist/standalone/{chunk-RBUZXGW4.js → chunk-TIQWHHFJ.js} +1 -1
  55. package/dist/standalone/{chunk-7SA3C6AD.js → chunk-U34AMIA7.js} +1 -1
  56. package/dist/standalone/{chunk-D722YMVG.js → chunk-UOKSBFK6.js} +1 -1
  57. package/dist/standalone/{chunk-WO3CKCCK.js → chunk-UVMBAAA6.js} +1 -1
  58. package/dist/standalone/{chunk-O3OLYWXH.js → chunk-V7GKCAFR.js} +1 -1
  59. package/dist/standalone/{chunk-KHIJLXVN.js → chunk-X6EMHQ2B.js} +1 -1
  60. package/dist/standalone/{chunk-M55KXW5Z.js → chunk-XCJ4YXJG.js} +1 -1
  61. package/dist/standalone/{chunk-Y7BODRFB.js → chunk-XR7EQN5W.js} +1 -1
  62. package/dist/standalone/{chunk-73S4ZMSC.js → chunk-XY5FPTLJ.js} +1 -1
  63. package/dist/standalone/{chunk-VHFBBAB3.js → chunk-Y4TVOZQP.js} +1 -1
  64. package/dist/standalone/chunk-YOB2X3FZ.js +1 -0
  65. package/dist/standalone/{chunk-EFXL7F5E.js → chunk-Z2GX4OZF.js} +1 -1
  66. package/dist/standalone/{chunk-JXCWNZ7T.js → chunk-ZC46MF52.js} +1 -1
  67. package/dist/standalone/{chunk-MMYETC7K.js → chunk-ZKJTX5ET.js} +1 -1
  68. package/dist/standalone/{chunk-X6XVQUHD.js → chunk-ZM3EAFOC.js} +2 -2
  69. package/dist/standalone/{chunk-PBMIQYWZ.js → chunk-ZT2XSTH3.js} +1 -1
  70. package/dist/standalone/studio.js +1 -1
  71. package/package.json +6 -6
  72. package/dist/packem_shared/wire-codec-DnslZGxC.mjs +0 -1
  73. package/dist/standalone/chunk-ET6VU4YM.js +0 -11
  74. package/dist/standalone/chunk-FMRAZ6MD.js +0 -15
  75. package/dist/standalone/chunk-XAG625PN.js +0 -1
@@ -0,0 +1,11 @@
1
+ import{a as Ct,d as p}from"./chunk-RZNN2EJU.js";import{a as o,d as A,e as V,f as kt,g as je}from"./chunk-YKXDMIHQ.js";var L=class{static{o(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 Fr=class extends L{static{o(this,"FocusManager")}#e;#t;#r;constructor(){super(),this.#r=t=>{if(typeof window<"u"&&window.addEventListener){let e=o(()=>t(),"listener");return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#r=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"}},ee=new Fr;var xr={setTimeout:o((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:o(t=>clearTimeout(t),"clearTimeout"),setInterval:o((t,e)=>setInterval(t,e),"setInterval"),clearInterval:o(t=>clearInterval(t),"clearInterval")},_r=class{static{o(this,"TimeoutManager")}#e=xr;#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)}},Q=new _r;function Tt(t){setTimeout(t,0)}o(Tt,"systemSetTimeoutZero");var He=typeof window>"u"||"Deno"in globalThis;function w(){}o(w,"noop");function Ot(t,e){return typeof t=="function"?t(e):t}o(Ot,"functionalUpdate");function ae(t){return typeof t=="number"&&t>=0&&t!==1/0}o(ae,"isValidTimeout");function ve(t,e){return Math.max(t+(e||0)-Date.now(),0)}o(ve,"timeUntilStale");function _(t,e){return typeof t=="function"?t(e):t}o(_,"resolveStaleTime");function E(t,e){return typeof t=="function"?t(e):t}o(E,"resolveQueryBoolean");function ge(t,e){let{type:r="all",exact:s,fetchStatus:i,predicate:n,queryKey:a,stale:c}=t;if(a){if(s){if(e.queryHash!==oe(a,e.options))return!1}else if(!q(e.queryKey,a))return!1}if(r!=="all"){let u=e.isActive();if(r==="active"&&!u||r==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||n&&!n(e))}o(ge,"matchQuery");function Se(t,e){let{exact:r,status:s,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(r){if(G(e.options.mutationKey)!==G(n))return!1}else if(!q(e.options.mutationKey,n))return!1}return!(s&&e.state.status!==s||i&&!i(e))}o(Se,"matchMutation");function oe(t,e){return(e?.queryKeyHashFn||G)(t)}o(oe,"hashQueryKeyByOptions");function G(t){return JSON.stringify(t,(e,r)=>$e(r)?Object.keys(r).sort().reduce((s,i)=>(s[i]=r[i],s),{}):r)}o(G,"hashKey");function q(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 s=0;s<e.length;s++)if(!q(t[s],e[s]))return!1;return!0}let r=Object.keys(e);for(let s of r)if(!q(t[s],e[s]))return!1;return!0}return!1}o(q,"partialMatchKey");var Lr=Object.prototype.hasOwnProperty;function ze(t,e,r=0){if(t===e)return t;if(r>500)return e;let s=Et(t)&&Et(e);if(!s&&!($e(t)&&$e(e)))return e;let n=(s?t:Object.keys(t)).length,a=s?e:Object.keys(e),c=a.length,u=s?new Array(c):{},h=0;for(let d=0;d<c;d++){let l=s?d:a[d],f=t[l],m=e[l];if(f===m){u[l]=f,(s?d<n:Lr.call(t,l))&&h++;continue}if(f===null||m===null||typeof f!="object"||typeof m!="object"){u[l]=m;continue}let y=ze(f,m,r+1);u[l]=y,y===f&&h++}return n===c&&h===n?t:u}o(ze,"replaceEqualDeep");function we(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let r in t)if(t[r]!==e[r])return!1;return!0}o(we,"shallowEqualObjects");function Et(t){return Array.isArray(t)&&t.length===Object.keys(t).length}o(Et,"isPlainArray");function $e(t){if(!It(t))return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(!It(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}o($e,"isPlainObject");function It(t){return Object.prototype.toString.call(t)==="[object Object]"}o(It,"hasObjectPrototype");function Rt(t){return new Promise(e=>{Q.setTimeout(e,t)})}o(Rt,"sleep");function ce(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?ze(t,e):e}o(ce,"replaceData");function Qr(t){return t}o(Qr,"keepPreviousData");function Pt(t,e,r=0){let s=[...t,e];return r&&s.length>r?s.slice(1):s}o(Pt,"addToEnd");function At(t,e,r=0){let s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}o(At,"addToStart");var te=Symbol();function Ce(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===te?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}o(Ce,"ensureQueryFn");function ke(t,e){return typeof t=="function"?t(...e):!!t}o(ke,"shouldThrowError");function Mt(t,e,r){let s=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:o(()=>(i??=e(),s||(s=!0,i.aborted?r():i.addEventListener("abort",r,{once:!0})),i),"get")}),t}o(Mt,"addConsumeAwareSignal");var D=(()=>{let t=o(()=>He,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function ue(){let t,e,r=new Promise((i,n)=>{t=i,e=n});r.status="pending",r.catch(()=>{});function s(i){Object.assign(r,i),delete r.resolve,delete r.reject}return o(s,"finalize"),r.resolve=i=>{s({status:"fulfilled",value:i}),t(i)},r.reject=i=>{s({status:"rejected",reason:i}),e(i)},r}o(ue,"pendingThenable");var Ft=Tt;function Dr(){let t=[],e=0,r=o(c=>{c()},"notifyFn"),s=o(c=>{c()},"batchNotifyFn"),i=Ft,n=o(c=>{e?t.push(c):i(()=>{r(c)})},"schedule"),a=o(()=>{let c=t;t=[],c.length&&i(()=>{s(()=>{c.forEach(u=>{r(u)})})})},"flush");return{batch:o(c=>{let u;e++;try{u=c()}finally{e--,e||a()}return u},"batch"),batchCalls:o(c=>(...u)=>{n(()=>{c(...u)})},"batchCalls"),schedule:n,setNotifyFunction:o(c=>{r=c},"setNotifyFunction"),setBatchNotifyFunction:o(c=>{s=c},"setBatchNotifyFunction"),setScheduler:o(c=>{i=c},"setScheduler")}}o(Dr,"createNotifyManager");var v=Dr();var Ur=class extends L{static{o(this,"OnlineManager")}#e=!0;#t;#r;constructor(){super(),this.#r=t=>{if(typeof window<"u"&&window.addEventListener){let e=o(()=>t(!0),"onlineListener"),r=o(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",r)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#r=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(r=>{r(t)}))}isOnline(){return this.#e}},re=new Ur;function Nr(t){return Math.min(1e3*2**t,3e4)}o(Nr,"defaultRetryDelay");function We(t){return(t??"online")==="online"?re.isOnline():!0}o(We,"canFetch");var Te=class extends Error{static{o(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Ee(t){let e=!1,r=0,s,i=ue(),n=o(()=>i.status!=="pending","isResolved"),a=o(b=>{if(!n()){let C=new Te(b);f(C),t.onCancel?.(C)}},"cancel"),c=o(()=>{e=!0},"cancelRetry"),u=o(()=>{e=!1},"continueRetry"),h=o(()=>ee.isFocused()&&(t.networkMode==="always"||re.isOnline())&&t.canRun(),"canContinue"),d=o(()=>We(t.networkMode)&&t.canRun(),"canStart"),l=o(b=>{n()||(s?.(),i.resolve(b))},"resolve"),f=o(b=>{n()||(s?.(),i.reject(b))},"reject"),m=o(()=>new Promise(b=>{s=o(C=>{(n()||h())&&b(C)},"continueFn"),t.onPause?.()}).then(()=>{s=void 0,n()||t.onContinue?.()}),"pause"),y=o(()=>{if(n())return;let b,C=r===0?t.initialPromise:void 0;try{b=C??t.fn()}catch(k){b=Promise.reject(k)}Promise.resolve(b).then(l).catch(k=>{if(n())return;let x=t.retry??(D.isServer()?0:3),U=t.retryDelay??Nr,z=typeof U=="function"?U(r,k):U,W=x===!0||typeof x=="number"&&r<x||typeof x=="function"&&x(r,k);if(e||!W){f(k);return}r++,t.onFail?.(r,k),Rt(z).then(()=>h()?void 0:m()).then(()=>{e?f(k):y()})})},"run");return{promise:i,status:o(()=>i.status,"status"),cancel:a,continue:o(()=>(s?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:d,start:o(()=>(d()?y():m().then(y),i),"start")}}o(Ee,"createRetryer");var Ie=class{static{o(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ae(this.gcTime)&&(this.#e=Q.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(D.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(Q.clearTimeout(this.#e),this.#e=void 0)}};function _t(t){return{onFetch:o((e,r)=>{let s=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,n=e.state.data?.pages||[],a=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,h=o(async()=>{let d=!1,l=o(y=>{Mt(y,()=>e.signal,()=>d=!0)},"addSignalProperty"),f=Ce(e.options,e.fetchOptions),m=o(async(y,b,C)=>{if(d)return Promise.reject(e.signal.reason);if(b==null&&y.pages.length)return Promise.resolve(y);let x=o(()=>{let Be={client:e.client,queryKey:e.queryKey,pageParam:b,direction:C?"backward":"forward",meta:e.options.meta};return l(Be),Be},"createQueryFnContext")(),U=await f(x),{maxPages:z}=e.options,W=C?At:Pt;return{pages:W(y.pages,U,z),pageParams:W(y.pageParams,b,z)}},"fetchPage");if(i&&n.length){let y=i==="backward",b=y?qr:xt,C={pages:n,pageParams:a},k=b(s,C);c=await m(C,k,y)}else{let y=t??n.length;do{let b=u===0?a[0]??s.initialPageParam:xt(s,c);if(u>0&&b==null)break;c=await m(c,b),u++}while(u<y)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(h,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r):e.fetchFn=h},"onFetch")}}o(_t,"infiniteQueryBehavior");function xt(t,{pages:e,pageParams:r}){let s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,r[s],r):void 0}o(xt,"getNextPageParam");function qr(t,{pages:e,pageParams:r}){return e.length>0?t.getPreviousPageParam?.(e[0],e,r[0],r):void 0}o(qr,"getPreviousPageParam");var Dt=class extends Ie{static{o(this,"Query")}#e;#t;#r;#s;#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.#s=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=Qt(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=Qt(this.options);e.data!==void 0&&(this.setState(Lt(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(t,e){let r=ce(this.state.data,t,this.options);return this.#c({data:r,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),r}setState(t){this.#c({type:"setState",state:t})}cancel(t){let e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(w).catch(w):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=>E(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===te||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>_(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:!ve(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.#s.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.#s.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(h=>h.options.queryFn);u&&this.setOptions(u.options)}let r=new AbortController,s=o(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:o(()=>(this.#a=!0,r.signal),"get")})},"addSignalProperty"),i=o(()=>{let u=Ce(this.options,e),d=o(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return s(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,d,this):u(d)},"fetchFn"),a=o(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return s(u),u},"createFetchContext")();(this.#e==="infinite"?_t(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#r=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:"fetch",meta:a.fetchOptions?.meta}),this.#i=Ee({initialPromise:e?.initialPromise,fn:a.fetchFn,onCancel:o(u=>{u instanceof Te&&u.revert&&this.setState({...this.#r,fetchStatus:"idle"}),r.abort()},"onCancel"),onFail:o((u,h)=>{this.#c({type:"failed",failureCount:u,error:h})},"onFail"),onPause:o(()=>{this.#c({type:"pause"})},"onPause"),onContinue:o(()=>{this.#c({type:"continue"})},"onContinue"),retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:o(()=>!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.#s.config.onSuccess?.(u,this),this.#s.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Te){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.#s.config.onError?.(u,this),this.#s.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=o(r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Ve(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Lt(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#r=t.manual?s:void 0,s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}},"reducer");this.state=e(this.state),v.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:t})})}};function Ve(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:We(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}o(Ve,"fetchState");function Lt(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}o(Lt,"successState");function Qt(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,r=e!==void 0,s=r?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:r?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}o(Qt,"getDefaultState");var Je=class extends L{static{o(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=ue(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#r=void 0;#s=void 0;#n;#i;#o;#a;#h;#c;#p;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Ut(this.#t,this.options)?this.#f():this.updateResult(),this.#g())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ge(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ge(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,r=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 E(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&&!we(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let s=this.hasListeners();s&&Nt(this.#t,r,this.options,e)&&this.#f(),this.updateResult(),s&&(this.#t!==r||E(this.options.enabled,this.#t)!==E(e.enabled,this.#t)||_(this.options.staleTime,this.#t)!==_(e.staleTime,this.#t))&&this.#y();let i=this.#b();s&&(this.#t!==r||E(this.options.enabled,this.#t)!==E(e.enabled,this.#t)||i!==this.#u)&&this.#v(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),r=this.createResult(e,t);return Br(this,r)&&(this.#s=r,this.#i=this.options,this.#n=this.#t.state),r}getCurrentResult(){return this.#s}trackResult(t,e){return new Proxy(t,{get:o((r,s)=>(this.trackProp(s),e?.(s),s==="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(r,s)),"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),r=this.#e.getQueryCache().build(this.#e,e);return r.fetch().then(()=>this.createResult(r,e))}fetch(t){return this.#f({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#f(t){this.#C();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(w)),e}#y(){this.#S();let t=_(this.options.staleTime,this.#t);if(D.isServer()||this.#s.isStale||!ae(t))return;let r=ve(this.#s.dataUpdatedAt,t)+1;this.#d=Q.setTimeout(()=>{this.#s.isStale||this.updateResult()},r)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(t){this.#w(),this.#u=t,!(D.isServer()||E(this.options.enabled,this.#t)===!1||!ae(this.#u)||this.#u===0)&&(this.#l=Q.setInterval(()=>{(this.options.refetchIntervalInBackground||ee.isFocused())&&this.#f()},this.#u))}#g(){this.#y(),this.#v(this.#b())}#S(){this.#d!==void 0&&(Q.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&(Q.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let r=this.#t,s=this.options,i=this.#s,n=this.#n,a=this.#i,u=t!==r?t.state:this.#r,{state:h}=t,d={...h},l=!1,f;if(e._optimisticResults){let P=this.hasListeners(),ne=!P&&Ut(t,e),me=P&&Nt(t,r,e,s);(ne||me)&&(d={...d,...Ve(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:b}=d;f=d.data;let C=!1;if(e.placeholderData!==void 0&&f===void 0&&b==="pending"){let P;i?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(P=i.data,C=!0):P=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,P!==void 0&&(b="success",f=ce(i?.data,P,e),l=!0)}if(e.select&&f!==void 0&&!C)if(i&&f===n?.data&&e.select===this.#h)f=this.#c;else try{this.#h=e.select,f=e.select(f),f=ce(i?.data,f,e),this.#c=f,this.#a=null}catch(P){this.#a=P}this.#a&&(m=this.#a,f=this.#c,y=Date.now(),b="error");let k=d.fetchStatus==="fetching",x=b==="pending",U=b==="error",z=x&&k,W=f!==void 0,N={status:b,fetchStatus:d.fetchStatus,isPending:x,isSuccess:b==="success",isError:U,isInitialLoading:z,isLoading:z,data:f,dataUpdatedAt:d.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:k,isRefetching:k&&!x,isLoadingError:U&&!W,isPaused:d.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:U&&W,isStale:Xe(t,e),refetch:this.refetch,promise:this.#o,isEnabled:E(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let P=N.data!==void 0,ne=N.status==="error"&&!P,me=o(be=>{ne?be.reject(N.error):P&&be.resolve(N.data)},"finalizeThenableIfPossible"),wt=o(()=>{let be=this.#o=N.promise=ue();me(be)},"recreateThenable"),ye=this.#o;switch(ye.status){case"pending":t.queryHash===r.queryHash&&me(ye);break;case"fulfilled":(ne||N.data!==ye.value)&&wt();break;case"rejected":(!ne||N.error!==ye.reason)&&wt();break}}return N}updateResult(){let t=this.#s,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#i=this.options,this.#n.data!==void 0&&(this.#p=this.#t),we(e,t))return;this.#s=e;let r=o(()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!this.#m.size)return!0;let n=new Set(i??this.#m);return this.options.throwOnError&&n.add("error"),Object.keys(this.#s).some(a=>{let c=a;return this.#s[c]!==t[c]&&n.has(c)})},"shouldNotifyListeners");this.#k({listeners:r()})}#C(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#r=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#g()}#k(t){v.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Kr(t,e){return E(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&E(e.retryOnMount,t)===!1)}o(Kr,"shouldLoadOnMount");function Ut(t,e){return Kr(t,e)||t.state.data!==void 0&&Ge(t,e,e.refetchOnMount)}o(Ut,"shouldFetchOnMount");function Ge(t,e,r){if(E(e.enabled,t)!==!1&&_(e.staleTime,t)!=="static"){let s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&Xe(t,e)}return!1}o(Ge,"shouldFetchOn");function Nt(t,e,r,s){return(t!==e||E(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&Xe(t,r)}o(Nt,"shouldFetchOptionally");function Xe(t,e){return E(e.enabled,t)!==!1&&t.isStaleByTime(_(e.staleTime,t))}o(Xe,"isStale");function Br(t,e){return!we(t.getCurrentResult(),e)}o(Br,"shouldAssignObserverCurrentProperties");var qt=class extends Ie{static{o(this,"Mutation")}#e;#t;#r;#s;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#r=t.mutationCache,this.#t=[],this.state=t.state||jr(),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.#r.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#r.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#r.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(t){let e=o(()=>{this.#n({type:"continue"})},"onContinue"),r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=Ee({fn:o(()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:o((n,a)=>{this.#n({type:"failed",failureCount:n,error:a})},"onFail"),onPause:o(()=>{this.#n({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:o(()=>this.#r.canRun(this),"canRun")});let s=this.state.status==="pending",i=!this.#s.canStart();try{if(s)e();else{this.#n({type:"pending",variables:t,isPaused:i}),this.#r.config.onMutate&&await this.#r.config.onMutate(t,this,r);let a=await this.options.onMutate?.(t,r);a!==this.state.context&&this.#n({type:"pending",context:a,variables:t,isPaused:i})}let n=await this.#s.start();return await this.#r.config.onSuccess?.(n,t,this.state.context,this,r),await this.options.onSuccess?.(n,t,this.state.context,r),await this.#r.config.onSettled?.(n,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(n,null,t,this.state.context,r),this.#n({type:"success",data:n}),n}catch(n){try{await this.#r.config.onError?.(n,t,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onError?.(n,t,this.state.context,r)}catch(a){Promise.reject(a)}try{await this.#r.config.onSettled?.(void 0,n,this.state.variables,this.state.context,this,r)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,n,t,this.state.context,r)}catch(a){Promise.reject(a)}throw this.#n({type:"error",error:n}),n}finally{this.#r.runNext(this)}}#n(t){let e=o(r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,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{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),v.batch(()=>{this.#t.forEach(r=>{r.onMutationUpdate(t)}),this.#r.notify({mutation:this,type:"updated",action:t})})}};function jr(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}o(jr,"getDefaultState");var Kt=class extends L{static{o(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#r=0}#e;#t;#r;build(t,e,r){let s=new qt({client:t,mutationCache:this,mutationId:++this.#r,options:t.defaultMutationOptions(e),state:r});return this.add(s),s}add(t){this.#e.add(t);let e=Oe(t);if(typeof e=="string"){let r=this.#t.get(e);r?r.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=Oe(t);if(typeof e=="string"){let r=this.#t.get(e);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=Oe(t);if(typeof e=="string"){let s=this.#t.get(e)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let e=Oe(t);return typeof e=="string"?this.#t.get(e)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){v.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(r=>Se(e,r))}findAll(t={}){return this.getAll().filter(e=>Se(t,e))}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return v.batch(()=>Promise.all(t.map(e=>e.continue().catch(w))))}};function Oe(t){return t.options.scope?.id}o(Oe,"scopeFor");var Bt=class extends L{static{o(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,r){let s=e.queryKey,i=e.queryHash??oe(s,e),n=this.get(i);return n||(n=new Dt({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(e),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(n)),n}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(){v.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(r=>ge(e,r))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(r=>ge(t,r)):e}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){v.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){v.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var Ye=class{static{o(this,"QueryClient")}#e;#t;#r;#s;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new Bt,this.#t=t.mutationCache||new Kt,this.#r=t.defaultOptions||{},this.#s=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=ee.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=re.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),r=this.#e.build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(_(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:r})=>{let s=r.data;return[e,s]})}setQueryData(t,e,r){let s=this.defaultQueryOptions({queryKey:t}),n=this.#e.get(s.queryHash)?.state.data,a=Ot(e,n);if(a!==void 0)return this.#e.build(this,s).setData(a,{...r,manual:!0})}setQueriesData(t,e,r){return v.batch(()=>this.#e.findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;v.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){let r=this.#e;return v.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let r={revert:!0,...e},s=v.batch(()=>this.#e.findAll(t).map(i=>i.cancel(r)));return Promise.all(s).then(w).catch(w)}invalidateQueries(t,e={}){return v.batch(()=>(this.#e.findAll(t).forEach(r=>{r.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let r={...e,cancelRefetch:e.cancelRefetch??!0},s=v.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,r);return r.throwOnError||(n=n.catch(w)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(s).then(w)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let r=this.#e.build(this,e);return r.isStaleByTime(_(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(w).catch(w)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(w).catch(w)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return re.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(t){this.#r=t}setQueryDefaults(t,e){this.#s.set(G(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#s.values()],r={};return e.forEach(s=>{q(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){this.#n.set(G(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],r={};return e.forEach(s=>{q(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#r.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=oe(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===te&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#r.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var K=A(V(),1);var se=A(V(),1),jt=A(je(),1);var he=se.createContext(void 0),Ze=o(t=>{let e=se.useContext(he);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),et=o(({client:t,children:e})=>(se.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,jt.jsx)(he.Provider,{value:t,children:e})),"QueryClientProvider");var de=A(V(),1),$r=A(je(),1);function Hr(){let t=!1;return{clearReset:o(()=>{t=!1},"clearReset"),reset:o(()=>{t=!0},"reset"),isReset:o(()=>t,"isReset")}}o(Hr,"createValue");var zr=de.createContext(Hr()),$t=o(()=>de.useContext(zr),"useQueryErrorResetBoundary");var Ht=A(V(),1);var zt=o((t,e,r)=>{let s=r?.state.error&&typeof t.throwOnError=="function"?ke(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),Wt=o(t=>{Ht.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),Vt=o(({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(i&&t.data===void 0||ke(r,[t.error,s])),"getHasError");var Re=A(V(),1);var Gt=Re.createContext(!1),Jt=o(()=>Re.useContext(Gt),"useIsRestoring"),co=Gt.Provider;var Xt=o(t=>{if(t.suspense){let r=o(i=>i==="static"?i:Math.max(i??1e3,1e3),"clamp"),s=t.staleTime;t.staleTime=typeof s=="function"?(...i)=>r(s(...i)):r(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},"ensureSuspenseTimers"),Yt=o((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),Zt=o((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),tt=o((t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()}),"fetchOptimistic");function er(t,e,r){let s=Jt(),i=$t(),n=Ze(r),a=n.defaultQueryOptions(t);n.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let c=n.getQueryCache().get(a.queryHash),u=t.subscribed!==!1;a._optimisticResults=s?"isRestoring":u?"optimistic":void 0,Xt(a),zt(a,i,c),Wt(i);let h=!n.getQueryCache().get(a.queryHash),[d]=K.useState(()=>new e(n,a)),l=d.getOptimisticResult(a),f=!s&&u;if(K.useSyncExternalStore(K.useCallback(m=>{let y=f?d.subscribe(v.batchCalls(m)):w;return d.updateResult(),y},[d,f]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),K.useEffect(()=>{d.setOptions(a)},[a,d]),Zt(a,l))throw tt(a,d,i);if(Vt({result:l,errorResetBoundary:i,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw l.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(a,l),a.experimental_prefetchInRender&&!D.isServer()&&Yt(l,s)&&(h?tt(a,d,i):c?.promise)?.catch(w).finally(()=>{d.updateResult()}),a.notifyOnChangeProps?l:d.trackResult(l)}o(er,"useBaseQuery");function Wr(t,e){return er(t,Je,e)}o(Wr,"useQuery");var tr=A(kt(),1);var J=A(V(),1),rt=A(je(),1);var rr=(0,J.createContext)(null),Vr=o(()=>new Ye({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"Q"),Gr=o(t=>{let e=(0,tr.c)(9),{children:r,client:s,queryClient:i}=t,n=(0,J.use)(he),a;e[0]!==n||e[1]!==i?(a=o(()=>i??n??Vr(),"o"),e[0]=n,e[1]=i,e[2]=a):a=e[2];let[c]=(0,J.useState)(a),u=i??n??c,h;e[3]!==r||e[4]!==s?(h=(0,rt.jsx)(rr,{value:s,children:r}),e[3]=r,e[4]=s,e[5]=h):h=e[5];let d=h;if(n===u)return d;let l;return e[6]!==d||e[7]!==u?(l=(0,rt.jsx)(et,{client:u,children:d}),e[6]=d,e[7]=u,e[8]=l):l=e[8],l},"b"),st=o(()=>{let t=(0,J.use)(rr);if(!t)throw new p("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var Pe=o(t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},"m"),Jr=o(t=>{let e=atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s+=1)r[s]=e.codePointAt(s)??0;return r},"A"),T="$lunora.wire$",Ae="__proto__",sr={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},ir={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},it=o(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"l"),O=o((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[T,"undefined"];if(t===null)return null;let r=typeof t;if(r==="bigint")return[T,"bigint",t.toString()];if(r==="number"){let n=t;return Number.isNaN(n)?[T,"nan"]:n===1/0?[T,"inf"]:n===-1/0?[T,"-inf"]:n}if(r!=="object")return t;if(t instanceof Date)return[T,"date",O(t.getTime(),e+1)];if(t instanceof Error){let n=t,a={};for(let u of Object.keys(n)){if(n[u]===void 0)continue;let h=O(n[u],e+1);u===Ae?Object.defineProperty(a,u,{configurable:!0,enumerable:!0,value:h,writable:!0}):a[u]=h}let c=[T,"error",String(n.name),String(n.message),a];return n.cause!==void 0&&c.push(O(n.cause,e+1)),c}if(t instanceof URL)return[T,"url",t.href];if(t instanceof Map)return[T,"map",[...t.entries()].map(([n,a])=>[O(n,e+1),O(a,e+1)])];if(t instanceof Set)return[T,"set",[...t].map(n=>O(n,e+1))];if(t instanceof ArrayBuffer)return[T,"bytes",Pe(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){let n=t,a=n.constructor.name,c=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return a==="Uint8Array"?[T,"bytes",Pe(c)]:[T,"bytes",Pe(c),a]}if(Array.isArray(t)){let n=t.map(a=>O(a,e+1));return n.length>0&&n[0]===T?[T,"arr",n]:n}if(!it(t)){let n=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${n} 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`)}let s=t,i={};for(let n of Object.keys(s)){let a=s[n];if(a===void 0)continue;let c=O(a,e+1);n===Ae?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"b"),S=o((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===null||typeof t!="object")return t;if(Array.isArray(t)){if(t[0]===T)switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(i=>S(i,e+1));case"bigint":{let i=t[2];if(typeof i!="string"||i.length>1024||!/^-?\d+$/.test(i))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(i)}case"date":{let i=S(t[2],e+1);if(typeof i!="number")throw new TypeError("wire-codec: malformed date \u2014 epoch must be a number");return new Date(i)}case"map":{let i=t[2];return new Map(i.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry \u2014 expected a [key, value] pair");return[S(n[0],e+1),S(n[1],e+1)]}))}case"set":return new Set(t[2].map(i=>S(i,e+1)));case"url":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed url \u2014 href must be a string");return new URL(i)}case"error":{let i=t[2],n=t[3];if(typeof i!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error \u2014 name and message must be strings");let a=(Object.hasOwn(ir,i)?ir[i]:void 0)??Error,c=new a(n);c.name!==i&&Object.defineProperty(c,"name",{configurable:!0,value:i,writable:!0});let u=S(t[4],e+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let h of Object.keys(u))h===Ae?Object.defineProperty(c,h,{configurable:!0,enumerable:!0,value:u[h],writable:!0}):c[h]=u[h];return t.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:S(t[5],e+1),writable:!0}),c}case"bytes":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed bytes \u2014 payload must be a base64 string");let n=Jr(i);if(Pe(n)!==i)throw new TypeError("wire-codec: malformed bytes \u2014 payload must be canonical padded base64");let a=t[3]??"Uint8Array";if(a==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;let c=Object.hasOwn(sr,a)?sr[a]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return t.map(i=>S(i,e+1))}return t.map(i=>S(i,e+1))}let r=t,s={};for(let i of Object.keys(r)){let n=S(r[i],e+1);i===Ae?Object.defineProperty(s,i,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[i]=n}return s},"y");var R=o(t=>new Promise((e,r)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{r(t.error??new Error("IndexedDB request failed"))})}),"c"),Me=o((t,e,r,s)=>{let i;return()=>i||(i=new Promise((n,a)=>{let c=t.open(e,r);c.addEventListener("upgradeneeded",()=>{s(c.result)}),c.addEventListener("success",()=>{n(c.result)}),c.addEventListener("error",()=>{a(c.error??new Error("IndexedDB open failed"))})}),i)},"E"),Fe=o((t,e)=>async(r,s)=>{let i=(await t()).transaction(e,r),n=await s(i.objectStore(e));return await new Promise((a,c)=>{i.addEventListener("complete",()=>{a()}),i.addEventListener("error",()=>{c(i.error??new Error("IndexedDB transaction failed"))}),i.addEventListener("abort",()=>{c(i.error??new Error("IndexedDB transaction aborted"))})}),n},"u");var le=o((t,e,r)=>`${t}::${e}::${r??""}`,"T"),Xr=500,Yr=o((t,e)=>{if(!Number.isInteger(t)||t<1)throw new p("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var Zr="lunora-query-cache",es="query-cache",nr="by_ts",ts=1,rs=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new p("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let r=t.databaseName??Zr,s=t.storeName??es,i=Yr(t.maxEntries??Xr,"createIndexedDbQueryCache"),n=Me(e,r,ts,u=>{u.objectStoreNames.contains(s)||u.createObjectStore(s,{keyPath:"key"}).createIndex(nr,"ts",{unique:!1})}),a=Fe(n,s),c=o(async u=>{let h=await R(u.count())-i;h<=0||await new Promise((d,l)=>{let f=u.index(nr).openCursor();f.addEventListener("success",()=>{let m=f.result;if(!m||h<=0){d();return}m.delete(),h-=1,m.continue()}),f.addEventListener("error",()=>{l(f.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:o(async()=>{await a("readwrite",u=>R(u.clear()))},"clear"),load:o(async()=>a("readonly",u=>R(u.getAll())),"load"),put:o(async(u,h)=>{await a("readwrite",async d=>{await R(d.put({...h,key:u})),await c(d)})},"put"),remove:o(async u=>{await a("readwrite",h=>R(h.delete(u)))},"remove")}},"N"),ar=o(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return rs()}},"L");var or=o(()=>{let t=null;return{get:o(()=>t,"get"),set:o(e=>{t=e},"set")}},"r");var xe=class{static{o(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,r){if(r===void 0){this.reset(e);return}this.values.set(e.key,r),this.notify(e.key,r)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}clear(){this.values.clear(),this.subscribers.clear()}subscribe(e,r){let s=this.subscribers.get(e.key);return s||(s=new Set,this.subscribers.set(e.key,s)),s.add(r),()=>{s.delete(r),s.size===0&&this.subscribers.delete(e.key)}}notify(e,r){let s=this.subscribers.get(e);if(s)for(let i of s)try{i(r)}catch{}}};var cr=0,ss="lunora-bridge",is=1e3,ns=3e3,_e=class{static{o(this,"l")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(cr+=1,this.tabId=`tab_${String(cr)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??is,this.leaderTimeout=e.leaderTimeout??ns,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??ss),this.bc.addEventListener("message",r=>{this.handleMessage(r.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,r,s,i,n){this.leader&&this.broadcast({type:"subscription-data",tabId:this.tabId,key:e,data:r,...s===void 0?{}:{cursor:s},...i===void 0?{}:{epoch:i},...n===void 0?{}:{identity:n}})}broadcastSubscriptionError(e,r,s){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:r,...s===void 0?{}:{identity:s}})}broadcastSubscriptionSettled(e,r,s,i,n,a){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...r===void 0?{}:{cursor:r},...s===void 0?{}:{epoch:s},...i===void 0?{}:{lastMutationId:i},...n===void 0?{}:{clientId:n},...a===void 0?{}:{identity:a}})}broadcastConnectionStatus(e,r){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...r===void 0?{}:{identity:r}})}broadcast(e){this.bc?.postMessage(e)}handleMessage(e){switch(e.type){case"claim-leadership":{this.handleClaimLeadership(e);break}case"connection-status":{if(this.leader||e.tabId===this.tabId)break;this.onConnectionStatus?.(e.status,e.identity);break}case"heartbeat":{this.handleHeartbeat(e);break}case"subscription-data":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionData?.(e.key,e.data,e.cursor,e.epoch,e.identity);break}case"subscription-error":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionError?.(e.key,e.error,e.identity);break}case"subscription-settled":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionSettled?.(e.key,e.cursor,e.epoch,e.lastMutationId,e.clientId,e.identity);break}case"yield-leadership":{this.knownLeader===e.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(e){if(e.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&e.tabId<this.tabId&&(this.knownLeader=e.tabId,this.lastHeartbeat=e.ts)}}handleHeartbeat(e){if(e.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(e);return}this.lastHeartbeat=e.ts,this.knownLeader=e.tabId}}resolveLeaderVsLeaderTieBreak(e){e.tabId<this.tabId?(this.leader=!1,this.knownLeader=e.tabId,this.lastHeartbeat=e.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!(!this.running||this.leader)){if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}};var nt="_id",at="_creationTime",ot="page",ur="pageDelta",as=o(t=>{if(Array.isArray(t))return t;if(it(t)&&Array.isArray(t[ot]))return t[ot]},"y"),os=o(t=>{let e;for(let r of t){let s=r[at];if(typeof s=="number"){if(e!==void 0){if(s<e)return!0;if(s>e)return!1}e=s}}return!1},"l"),cs=o((t,e)=>{let r=e[at];if(typeof r!="number")return t.length;let s=os(t);for(let[i,n]of t.entries()){let a=n[at];if(typeof a=="number"&&(s?a<r:a>r))return i}return t.length},"x"),us=o(t=>{if(typeof t!="object"||t===null)return;let e=t[nt];return typeof e=="string"?e:void 0},"A"),hr=o(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")},"b"),hs=o((t,e)=>{let r=[];for(let u of t){if(us(u)===void 0)return;r.push(u)}let{key:s,op:i,row:n}=e;if(i==="delete"){let u=r.filter(h=>h[nt]!==s);return u.length===r.length?[...r]:u}if(n===void 0)return;let a=[...r],c=r.findIndex(u=>u[nt]===s);return c===-1?a.splice(cs(r,n),0,n):a[c]=n,a},"I"),dr=o((t,e)=>{let r=as(t);if(r===void 0)return;let s=hs(r,e);return s===void 0||Array.isArray(t)?s:{...t,[ot]:s}},"E");var Zo=new Set(Object.keys(Ct)),B=class extends p{static{o(this,"E")}constructor(e,r){super("INTERNAL",e,{data:r})}};var ct=o(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"u");var ds=1024,Le=o(t=>{let e=t.maxBuffer??ds,r=[],s=[],i=!1,n,a=!1,c=o(()=>{let d=s.shift();if(!d)return!1;if(n)return d.reject(n),!0;if(r.length>0){let l=r.shift();return d.resolve({done:!1,value:l}),!0}return i?(d.resolve({done:!0,value:void 0}),!0):(s.unshift(d),!1)},"u"),u={complete(){if(!(i||n))for(i=!0;c(););},fail(d){if(!(i||n))for(n=d,r.length=0;c(););},push(d){if(!(i||n||a)){if(r.length>=e){u.fail(new p("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}r.push(d),c()}}},h=o(()=>{if(!a){a=!0,i=!0,r.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:h,[Symbol.asyncIterator](){return{next(){if(n)return Promise.reject(n);if(r.length>0){let d=r.shift();return Promise.resolve({done:!1,value:d})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((d,l)=>{s.push({reject:l,resolve:d})})},return(){return h(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var lr=/^ /u,fr=o(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"h"),ls=o(t=>{let e="",r=[];for(let s of t.split(`
2
+ `))s.startsWith("event:")?e=s.slice(6).replace(lr,""):s.startsWith("data:")&&r.push(s.slice(5).replace(lr,""));return{data:r.join(`
3
+ `),event:e}},"u"),fs=o((t,e,r)=>{let s=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),h=s[u];if(h===void 0)throw new p("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(fr(h))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,fr(u));let a=n.toString();return`${r.endsWith("/")?r.slice(0,-1):r}${i}${a===""?"":`?${a}`}`},"S"),ps=o((t,e)=>{if(t.event==="complete")return e.complete(),!0;if(t.event==="error"){let r={};try{r=JSON.parse(t.data)}catch{}let s=typeof r.message=="string"?r.message:"stream error",i=typeof r.code=="string"?r.code:"HTTP_STREAM_ERROR";return e.fail(new p(i,s)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(JSON.parse(t.data))}catch{return e.fail(new p("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"T"),ms=o(async(t,e)=>{let r=t.getReader(),s=new TextDecoder,i="",n=o(()=>{let a=i.indexOf(`
4
+
5
+ `);for(;a!==-1;){let c=ls(i.slice(0,a));if(i=i.slice(a+2),ps(c,e))return!0;a=i.indexOf(`
6
+
7
+ `)}return!1},"i");for(;;){let{done:a,value:c}=await r.read();if(a)break;if(i+=s.decode(c,{stream:!0}).replaceAll(`\r
8
+ `,`
9
+ `),n()){await r.cancel().catch(()=>{});return}}i+=s.decode().replaceAll(`\r
10
+ `,`
11
+ `),n()||e.fail(new p("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"E"),pr=o((t,e,r={})=>{let s=r.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!s)throw new p("INTERNAL","httpStream: no `fetch` implementation available");let i=fs(t,e??{},r.baseUrl??""),n=new AbortController,a;r.signal&&(r.signal.aborted?n.abort():(a=o(()=>{n.abort()},"s"),r.signal.addEventListener("abort",a,{once:!0})));let c=o(()=>{a&&r.signal?.removeEventListener("abort",a)},"d"),{handle:u,iterable:h}=Le({maxBuffer:r.maxBuffer,onCancel:o(()=>{n.abort()},"onCancel")});return(async()=>{try{let d=await s(i,{headers:{accept:"text/event-stream",...r.headers},method:t.method,signal:n.signal});if(!d.ok){await d.body?.cancel().catch(()=>{}),u.fail(new p("HTTP_STREAM_STATUS",`httpStream: request failed (status ${d.status.toString()})`,{status:d.status}));return}if(!d.body){u.fail(new p("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await ms(d.body,u)}finally{c()}})().catch(d=>{if(n.signal.aborted){u.complete();return}if(d instanceof Error&&"code"in d){u.fail(d);return}u.fail(new p("HTTP_STREAM_TRANSPORT",d instanceof Error?d.message:String(d),{cause:d}))}),h},"w");var ys=/["\\\u0000-\u001F\uD800-\uDFFF]/,mr=o(t=>ys.test(t)?JSON.stringify(t):`"${t}"`,"y"),ut=o(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return mr(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let a="[";for(let c=0;c<t.length;c++)c>0&&(a+=","),a+=ut(t[c]);return a+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let a=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${a} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let r=t,s=Object.keys(r).sort(),i="{",n=!0;for(let a of s){let c=r[a];c!==void 0&&(n?n=!1:i+=",",i+=mr(a),i+=":",i+=ut(c))}return i+"}"},"i"),j=o(t=>ut(O(t)),"u");var M=class t{static{o(this,"r")}static key(e,r,s){return`${e}::${j(r)}::${s??""}`}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 r=t.keyOf(e);this.byKey.get(r)===e&&this.byKey.delete(r),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}};var ie=o((t,e)=>{let r=t;for(let s of e)try{r=s.transform(r)}catch{}return r},"p"),X=o((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let r of t.callbacks)try{r(e)}catch{}}},"u"),ht=o((t,e)=>{let r;try{r=e(t.lastValue)}catch{return}let s={id:Symbol("optimistic"),transform:e};t.optimisticLayers.push(s),X(t,r);let i=o(()=>{let a=t.optimisticLayers.findIndex(c=>c.id===s.id);return a===-1?!1:(t.optimisticLayers.splice(a,1),!0)},"c"),n=o(()=>{X(t,ie(t.serverBase,t.optimisticLayers))},"a");return{confirm:o(a=>{if(a===void 0){i();return}s.commitCursor=a,t.serverCursor!==void 0&&t.serverCursor>=a&&i()&&n()},"confirm"),rollback:o(()=>{i()&&n()},"rollback")}},"y"),Qe=o((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let r=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(s=>s.commitCursor===void 0||s.commitCursor>e),t.optimisticLayers.length!==r},"h"),yr=o((t,e)=>{let r=[],s=[],i=o((n,a)=>t.get(M.key(n,a,e)),"c");return{confirms:r,rollbacks:s,store:{getAllQueries:o(n=>{let a=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&a.push({args:c.args,value:c.lastValue});return a},"getAllQueries"),getQuery:o((n,a)=>i(n.__lunoraRef,a??{})?.lastValue,"getQuery"),setQuery:o((n,a,c)=>{let u=i(n.__lunoraRef,a??{});if(!u)return;let h=ht(u,()=>c);h&&(r.push(h.confirm),s.push(h.rollback))},"setQuery")}}},"L");var br=0,bs=o(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();br+=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)}_${br.toString(36)}_${t}`},"d"),dt=o((t,e)=>t!==void 0&&e!==t,"f"),Ue=bs,$=o((t,e,r,s)=>{if(t)try{t({error:r,mutationId:s,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,r)},"o"),De=class{static{o(this,"m")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},r={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=r.persistence,this.onEvict=r.onEvict,this.onSizeChange=r.onSizeChange,this.version=r.version}get size(){return this.items.length}enqueue(e){let r=e;r.id??=Ue(),this.items.push(r),this.persistence?.append({args:r.args,clientId:r.clientId,functionPath:r.functionPath,id:r.id,identity:r.identity,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{$(this.onPersistenceError,"append",s,r.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(a){throw $(this.onPersistenceError,"load",a),a}let r=[],s=new Set(this.items.map(a=>a.id));for(let a of e)if(!s.has(a.id)){if(dt(this.version,a.version)){this.persistence.remove(a.id).catch(c=>{$(this.onPersistenceError,"remove",c,a.id)});continue}s.add(a.id),r.push({args:a.args,clientId:a.clientId,functionPath:a.functionPath,id:a.id,identity:a.identity,reject:o(()=>{},"reject"),resolve:o(()=>{},"resolve"),shardKey:a.shardKey})}this.items.unshift(...r),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let a of r)i.has(a)&&n.add(a.shardKey);return[...n]}restampIdentity(e,r){for(let s of this.items){if(s.identity!==e)continue;s.identity=r;let{id:i}=s;if(!this.persistence||i===void 0)continue;let n={args:s.args,clientId:s.clientId,functionPath:s.functionPath,id:i,identity:r,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(a=>{$(this.onPersistenceError,"replace",a,i)})}}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.notifySize(),i}let r=[],s=[];for(let i of this.items)(e(i)?r:s).push(i);return this.items.length=0,this.items.push(...s),this.notifySize(),r}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],r=[];for(let s of this.items)if(s.precondition!==void 0&&!s.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",s.reject(i),e.push(s)}else r.push(s);return e.length>0&&(this.items.length=0,this.items.push(...r),this.notifySize()),e}clear(){for(let e of this.items){let r=new Error("CLIENT_CLOSED");r.code="CLIENT_CLOSED",e.reject(r)}this.items.length=0,this.notifySize()}async rewriteStamp(e,r){let s=this.persistence;if(s)try{await s.replace(r)}catch(i){$(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(s=>{$(this.onPersistenceError,"remove",s,e.id)});let r=new Error("offline queue overflow");r.code="OFFLINE_QUEUE_OVERFLOW",e.reject(r),this.onEvict?.(e,r)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var vs="lunora-outbox",gs="offline-mutations",lt="by_id",Ss=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new p("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let r=t.databaseName??vs,s=t.storeName??gs,i=Me(e,r,1,a=>{a.objectStoreNames.contains(s)||a.createObjectStore(s,{autoIncrement:!0}).createIndex(lt,"id",{unique:!0})}),n=Fe(i,s);return{append:o(async a=>{await n("readwrite",c=>R(c.add(a)))},"append"),clear:o(async()=>{await n("readwrite",a=>R(a.clear()))},"clear"),load:o(async()=>n("readonly",a=>R(a.getAll())),"load"),remove:o(async a=>{await n("readwrite",async c=>{let u=await R(c.index(lt).getKey(a));u!==void 0&&await R(c.delete(u))})},"remove"),replace:o(async a=>{await n("readwrite",async c=>{let u=await R(c.index(lt).getKey(a.id));u!==void 0&&await R(c.put(a,u))})},"replace")}},"w"),vr=o((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return Ss()}},"b");var ft=o((t={},e=Math.random)=>{let r=t.initialDelayMs??250,s=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let a=Math.min(s,r*2**n);if(n+=1,!i)return a;let c=a/2;return Math.floor(c+e()*(a-c))},reset(){n=0}}},"s");var gr=o((t,e,r,s)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s),n=i.present?j(i.value):void 0;return()=>{let a=t.peekActiveQuerySnapshot(e.__lunoraRef,r,s);return!i.present||!a.present?!0:j(a.value)===n}},"c");var pt=500,ws=o(async t=>{let e=[],r;for(;;){let s=await t(r);if(e.push(...Array.isArray(s.records)?s.records:[]),s.truncated!==!0||typeof s.cursor!="string"||s.cursor.length===0)return e;if(s.cursor===r)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");r=s.cursor}},"ke"),Sr=o((t,e)=>{if(t.size<e)return;let r=t.keys().next().value;r!==void 0&&t.delete(r)},"j"),Z=class{static{o(this,"E")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[r]=e;for(let s of this.listeners)try{s(r)}catch{}}clear(){this.listeners.clear()}},Ke=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),Cs=o(t=>{if(t instanceof B)return!0;let e=t?.code;return e===void 0||Ke.has(e)},"Ce"),Or=6e4,ks=1e3,Rr=o(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let r=Date.parse(t);if(Number.isNaN(r))return;let s=r-Date.now();return s>0?s:void 0},"se"),Ts={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},Ne=o((t,e,r)=>{let s=Rr(r),i=s===void 0?void 0:{retryAfterMs:s},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new B(n,i):new p(Ts[t]??"BAD_REQUEST",n,{data:i})},"M"),Es=o((t,e)=>{let r=Rr(e);if(!(r===void 0||ct(t)!==void 0))return t.data===void 0?{retryAfterMs:r}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:r}:void 0},"_e"),Is=o((t,e=Math.random)=>{let r=Math.min(ks*2**Math.max(t-1,0),Or);return Math.round(r*(.5+e()*.5))},"Ae"),Os=o(t=>t instanceof B||Ke.has(t?.code??""),"Ie"),Rs=o((t,e,r)=>{let s=ct(t);return s!==void 0&&s>0?Math.min(s,Or):Os(t)?Is(e,r):void 0},"Oe"),Ps=983040,As=o(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"Pe"),Ms="/_lunora/rpc",wr="/_lunora/rpc-batch",Fs="/_lunora/ws",mt=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"x"),qe=o(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"H"),Cr=Symbol("lunora.unmergeableDelta"),xs=o((t,e)=>{for(let r of e)r.op==="delete"?t.delete(r.key):r.value!==void 0&&t.set(r.key,r.value)},"Fe"),_s="lunora-ping",Ls=3e4,Qs=1e4,Ds=250,Us=5e3,Ns=64,qs=8,Ks="/_lunora/admin/shard-traffic",Bs="/_lunora/admin/scheduled",js="/_lunora/admin/scheduled/status",$s="/_lunora/admin/scheduled/ws",Hs="/_lunora/admin/scheduled/cancel",kr="/_lunora/admin/scheduled/dead",zs="/_lunora/admin/scheduled/dead/retry",Ws="/_lunora/admin/scheduled/dead/cancel",Vs="/_lunora/admin/workflows/instances",Gs="/_lunora/admin/workflows/instance",Js="/_lunora/admin/workflows/status",yt="/_lunora/admin/storage",Xs="/_lunora/admin/storage/url",Ys="/_lunora/admin/storage/buckets",Zs="/_lunora/admin/functions",ei="/_lunora/admin/cron-jobs",ti="/_lunora/admin/cron-jobs/run",ri="/_lunora/admin/openapi",si="/_lunora/admin/openrpc",ii="/_lunora/admin/global/tables",ni="/_lunora/admin/global/table",ai="/_lunora/admin/global/facet",oi="/_lunora/admin/vector/indexes",ci="/_lunora/admin/vector/query",ui="/_lunora/admin/logs/archive",hi="/_lunora/admin/kv/namespaces",di="/_lunora/admin/kv/keys",bt="/_lunora/admin/kv/value",li="/_lunora/admin/auth/users",fi="/_lunora/admin/auth/sessions",pi="/_lunora/admin/auth/users/create",mi="/_lunora/admin/auth/users/role",yi="/_lunora/admin/auth/users/ban",bi="/_lunora/admin/auth/users/unban",vi="/_lunora/admin/auth/users/password",gi="/_lunora/admin/auth/users/remove",Si="/_lunora/admin/auth/users/impersonate",wi="/_lunora/admin/auth/sessions/revoke",Ci="/_lunora/admin/auth/sessions/revoke-all",ki="/_lunora/admin/auth/capabilities",Ti="/_lunora/admin/auth/users/update",Ei="/_lunora/admin/auth/accounts",Ii="/_lunora/admin/auth/accounts/unlink",Oi="/_lunora/admin/auth/passkeys",Ri="/_lunora/admin/auth/passkeys/delete",Pi="/_lunora/admin/auth/two-factor/disable",Ai="/_lunora/admin/auth/organizations",Mi="/_lunora/admin/auth/organizations/members",Fi="/_lunora/admin/auth/organizations/invitations",xi="/_lunora/admin/auth/organizations/members/remove",_i="/_lunora/admin/auth/organizations/invitations/cancel",Li="/_lunora/admin/auth/config",Qi="/_lunora/admin/auth/sign-up-invitations",Di="/_lunora/admin/auth/sign-up-invitations/create",Ui="/_lunora/admin/auth/sign-up-invitations/revoke",Ni="/_lunora/admin/auth/organizations/create",qi="/_lunora/admin/auth/organizations/update",Ki="/_lunora/admin/auth/organizations/remove",Bi="/_lunora/admin/auth/organizations/members/add",ji="/_lunora/admin/auth/organizations/members/invite",$i="/_lunora/admin/auth/organizations/members/role",Hi="/_lunora/admin/auth/organizations/teams",zi="/_lunora/admin/auth/organizations/teams/create",Wi="/_lunora/admin/auth/organizations/teams/update",Vi="/_lunora/admin/auth/organizations/teams/remove",Gi="/_lunora/admin/auth/organizations/teams/members",Ji="/_lunora/admin/auth/organizations/teams/members/add",Xi="/_lunora/admin/auth/organizations/teams/members/remove",Yi="/_lunora/admin/auth/organizations/roles",Zi="/_lunora/admin/auth/organizations/roles/create",en="/_lunora/admin/auth/organizations/roles/update",tn="/_lunora/admin/auth/organizations/roles/remove",rn="/api/auth",sn="/get-session",Tr=o(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"Y"),Y=o((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"C"),I=o((t,e)=>{let r=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&r.set(i,String(n));let s=r.toString();return s===""?t:`${t}?${s}`},"p"),nn=[ur],g=o(t=>t??"","l"),Pr=o((t,e)=>{let r=t.error,s=typeof r?.code=="string"?r.code:void 0,i=typeof r?.message=="string"?r.message:void 0;return{code:s,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"re"),an=o(t=>{let{code:e,messageText:r}=Pr(t,"stream error");return e===void 0?new Error(r):new p(e,r)},"as"),Er=o(t=>{let{code:e,messageText:r}=Pr(t,"subscription error");return{message:r,...e===void 0?{}:{code:e}}},"X");function vt(t){if(t!==void 0)return e=>{t(e)}}o(vt,"K");var fe=o((t,e)=>{for(let r of t)try{r(e)}catch{}},"_"),on=new TextDecoder,cn=o(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return on.decode(t)},"cs"),F=o((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"b"),pe=o(t=>{let e=new Error(t.message??"request failed");return e.code=t.code,t.data!==void 0&&(e.data=S(t.data)),t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"A"),Ir=o((t,e)=>{let r=pe(t),s=Es(r,e);return s!==void 0&&(r.data=s),r},"Z"),H=o((t,e)=>{try{return O(t)}catch(r){let s=r instanceof Error?r.message:String(r);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${s}`,r instanceof Error?{cause:r}:void 0)}},"v"),gt=o(t=>"args"in t?{...t,args:S(t.args)}:t,"W"),un=o((t,e)=>{let r=Array.from({length:e});for(let s of t){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;let i=s.body;r[s.id]=i&&"error"in i&&i.error?{error:pe(i.error),ok:!1}:{ok:!0,value:S(i?.result)}}return r.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},"hs"),hn=Promise.resolve(),St=class t{static{o(this,"ie")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,r){return{defaultValue:r,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new M;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new Z;statusListeners=new Z;tokenExpiredListeners=new Z;mutationSettledListeners=new Z;pendingChangeListeners=new Z;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??Y(Tr(e.url),Fs),this.wsToken=e.wsToken;let r=e.authBasePath??rn;this.authBasePath=r.endsWith("/")?r.slice(0,-1):r,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??or(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Ls,this.connectTimeoutMs=e.connectTimeoutMs??Qs,this.defaultConnectionContext=e.connectionContext,this.persistence=vr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=ar(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new xe,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=hn),this.offlineQueue=new De(e.offlineQueue,{onEvict:o((s,i)=>{this.emitItemSettled(s,"rejected",i)},"onEvict"),onSizeChange:o(s=>{this.pendingChangeListeners.emit(s)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${Ue()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(e,r){let s=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken;this.authToken=e,r!==void 0?(this.authSubject=r,this.subjectToken=e):e===null&&(this.authSubject=void 0,this.subjectToken=null);let a=this.identityFingerprint();if(a!==i&&(!s&&n?(this.restampQueuedIdentity(i,a),this.restampWatermarks(i,a),this.restampConnectionIdentity(i,a)):this.rejectQueuedForIdentityChange(i),this.tabCoordinator)){let c=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),c&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(e),this.offlineQueue.size>0&&this.computeStatus()==="connected"&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}replayIdentityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let r=this.identityFingerprint();return e===r||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":r===null?"unknown":"mismatch"}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,r,s){let i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=s?.shardKey??"",a=this.identityFingerprint(),c,u=await this.rpc(e,r,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o(h=>{c=h},"onMutationAck")});if(c!==void 0&&c>(this.clientWatermarks.get(a??"")?.get(n)??0)){let h=this.clientWatermarks.get(a??"");h===void 0&&(Sr(this.clientWatermarks,qs),h=new Map,this.clientWatermarks.set(a??"",h)),h.set(n,c)}return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;let e={},r=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`);try{let s=await this.fetchImpl(Y(this.url,`${this.authBasePath}${sn}`),{credentials:"include",headers:e,method:"GET"});if(!s.ok)return null;let i=(await s.json())?.user??null;return this.adoptResolvedSubject(r,i),i}catch{return null}}setWsToken(e){if(this.wsToken!==e){this.wsToken=e;for(let r of this.connections.values())if(r.socket)try{r.socket.close()}catch{}}}setConnectionContext(e,r={}){this.assertLeaderOwnedSurface("setConnectionContext");let s=g(r.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,r={}){if(this.followsAnotherTab())return()=>{};let s=g(r.shardKey),i={context:e},n=this.connectionContextHolders.get(s);n?n.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let a=!1;return()=>{if(a)return;a=!0;let c=this.connectionContextHolders.get(s);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(e,r,s={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=g(s.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let a=n.get(e),c=a===void 0;if(a||(a=new Set,n.set(e,a)),a.add(r),this.ensureSocket(s.shardKey),c){let u=this.getConnection(s.shardKey);u&&F(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(r)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(s.shardKey);d&&F(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,r,s={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(s.shardKey);let i=this.getConnection(s.shardKey);i&&F(i,{data:H(r??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let r=this.statusListeners.add(e);return e(this.computeStatus()),r}pendingCount(){return this.offlineQueue.size}debug(){let e=[],r=this.clientWatermarks.get(this.identityFingerprint()??""),s=new Set([...this.connections.keys(),...r?.keys()??[]]);for(let n of s){let a=this.connections.get(n);e.push({confirmedMutationWatermark:r?.get(n)??0,hasSocket:a?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,a)=>(n.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((n,a)=>n.functionPath.localeCompare(a.functionPath))}}onPendingChange(e){let r=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),r}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,r){this.clientQueryStore.set(e,r)}subscribeClientQuery(e,r){return this.clientQueryStore.subscribe(e,r)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,r,s){return gr(this,e,r,s)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,r,s){if(!this.readyResolved)return;let i=j(r),n=le(e,i,s),a=this.hydratedQueryCache.get(n);if(a!==void 0)return a.identity===this.identityFingerprint()?a.value:void 0}peekActiveQuerySnapshot(e,r,s){let i=M.key(e,r,s),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(Y(this.url,wr),{body:JSON.stringify({calls:e.map((n,a)=>({args:H(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:a,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=r.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await r.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}if(!r.ok||i.error&&!i.results)throw i.error?pe(i.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let n of i.results??[]){let a=n.body?.commitCursor;typeof n.id=="number"&&typeof a=="number"&&this.recordShardCursor(e[n.id]?.shardKey,a)}return un(i.results??[],e.length)}async mutation(e,r,s={}){this.assertOpen();let i=r,n=s.mutationId??Ue(),{confirms:a,rollbacks:c}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,r,s.shardKey,c,a);let u=this.offlineFlushes.get(g(s.shardKey));u!==void 0&&await u;let{hasSocket:h,wasEverConnected:d,wsState:l}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:f}=this.offlineQueue,m=d||f,y=this.WebSocketImpl!==void 0&&m;if(l!=="open"&&!h&&y||l==="connecting"&&m)return this.enqueueOfflineMutation(e,i,s.shardKey,n,c,a,s.precondition);try{let b,C=await this.rpc(e.__lunoraRef,i,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:o(k=>{b=k},"onCommitCursor")});for(let k of a)k(b);return C}catch(b){throw qe(c),b}}async action(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,r,s={}){this.assertOpen();let i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(h=>({rows:h})),a=r.length,c=0,u=0;for(let h=0;h<a;h+=i){let d=r.slice(h,h+i),l=u;await this.mutation(e,n(d),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(l)}`},shardKey:s.shardKey}),u+=1,c+=d.length,s.onProgress?.({done:c,total:a})}return{chunks:u,imported:c}}async shardTraffic(e){this.assertOpen();let r=await this.adminFetch(Ks,"POST",{table:e});return{failed:r.failed??0,ok:r.ok??0,shards:r.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch(Bs,"GET")).records??[]).map(e=>gt(e))}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(js,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(Hs,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await ws(async e=>await this.adminFetch(e===void 0?kr:`${kr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>gt(e))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(zs,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Ws,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();let r=new URLSearchParams({name:e.name});e.status!==void 0&&r.set("status",e.status),e.page!==void 0&&r.set("page",String(e.page)),e.perPage!==void 0&&r.set("perPage",String(e.perPage));let s=await this.adminFetch(`${Vs}?${r.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();let r=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${Gs}?${r.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Js,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let r=Y(Tr(this.url),$s),s=ft(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,a=!1,c=o(()=>{a||this.closed||(n=setTimeout(d,s.next()))},"o"),u=o(f=>{if(a||this.WebSocketImpl===void 0)return;let m=f===void 0?r:`${r}?token=${encodeURIComponent(f)}`;this.openManagedSocket(i,m,this.connectTimeoutMs,{onClose:o(()=>{c()},"onClose"),onMessage:o(y=>{try{let b=JSON.parse(typeof y.data=="string"?y.data:"");b.type==="jobs"&&Array.isArray(b.records)&&(s.reset(),e(b.records.map(C=>gt(C))))}catch{}},"onMessage")})},"c"),h=o(async f=>{let m;try{m=await f()}catch{c();return}u(m)},"h"),d=o(()=>{if(a||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}u(f)},"d");d();let l=o(()=>{a=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close(),i.socket=void 0},"u");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Zs,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(ei,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let r=await this.adminFetch(ti,"POST",{name:e});return{name:r.name??e,ran:r.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(ri,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(si,"GET")}async listStorageObjects(e={}){this.assertOpen();let r=I(yt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(r,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,r){this.assertOpen();let s=`${yt}?key=${encodeURIComponent(e)}${mt(r?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Ys,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let r=`${yt}?key=${encodeURIComponent(e.key)}${mt(e.bucket)}`,s=await this.adminFetch(r,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,r){this.assertOpen();let s=r?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Xs}?key=${encodeURIComponent(e)}${i}${mt(r?.bucket)}`,a=await this.adminFetch(n,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(ii,"GET")}async readGlobalTablePage(e){this.assertOpen();let r=new URLSearchParams({table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(O(e.filters))),S(await this.adminFetch(`${ni}?${r.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();let r=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(O(e.filters))),S(await this.adminFetch(`${ai}?${r.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(oi,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(ci,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let r=await this.adminFetch(ui,"POST",e);return{nextCursor:r.nextCursor,rows:r.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(hi,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let r=I(di,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(r,"GET")}async getKvValue(e){this.assertOpen();let r=I(bt,{key:e.key,namespace:e.namespace});return await this.adminFetch(r,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(bt,"PUT",e)}async deleteKvKey(e){this.assertOpen();let r=I(bt,{key:e.key,namespace:e.namespace});await this.adminFetch(r,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let r=I(li,{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(r,"GET")}async createAuthUser(e){return await this.adminFetch(pi,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(mi,"POST",e)}async banAuthUser(e){return await this.adminFetch(yi,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(bi,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(vi,"POST",e)}async removeAuthUser(e){await this.adminFetch(gi,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Si,"POST",e)}async revokeAuthSession(e){await this.adminFetch(wi,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(Ci,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(ki,"GET")}async updateAuthUser(e){return await this.adminFetch(Ti,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(I(Ei,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(Ii,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(I(Oi,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(Ri,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(Pi,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(I(Ai,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let r=I(Mi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthOrgInvitations(e){let r=I(Fi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthSignUpInvitations(e={}){let r=I(Qi,{limit:e.limit,offset:e.offset});return await this.adminFetch(r,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(Di,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(Ui,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(xi,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(_i,"POST",e)}async getAuthConfig(){return await this.adminFetch(Li,"GET")}async createAuthOrganization(e){return await this.adminFetch(Ni,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(qi,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(Ki,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(Bi,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(ji,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch($i,"POST",e)}async listAuthOrgTeams(e){let r=I(Hi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(zi,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(Wi,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Vi,"POST",e)}async listAuthOrgTeamMembers(e){let r=I(Gi,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(r,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(Ji,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Xi,"POST",e)}async listAuthOrgRoles(e){let r=I(Yi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Zi,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(en,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(tn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let r=I(fi,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(r,"GET")}subscribe(e,r,s,i={}){this.assertOpen();let n=r??{},a=M.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(a),u=vt(s),h=vt(i.onError),d=vt(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,m=j(n),y=this.takeHydratedCache(e.__lunoraRef,m,i.shardKey);c={acked:!1,args:n,argsKey:m,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:y?.value,optimisticLayers:[],serverBase:y?.value,serverCursor:y?.serverCursor,shardKey:i.shardKey,wireArgs:H(n,`args for '${e.__lunoraRef}'`),...y?.serverEpoch===void 0?{}:{serverEpoch:y.serverEpoch}},this.subscriptions.add(c)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.subscriptions.remove(l))}}subscribeShape(e,r,s={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:a}=s;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([r]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:H(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(e,r,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,a=r??{},{handle:c,iterable:u}=Le({maxBuffer:s.maxBuffer,onCancel:o(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:H(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:s.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n,started:!1};this.streams.set(i,l);let f=h?.wsState==="open"&&F(h,d);if(l.started=f,!f&&h===void 0)return this.streams.delete(i),c.fail(new p("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=Ns;){let m=h.pendingStreams.shift()?.id,y=m?this.streams.get(m):void 0;y&&(y.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(m))}h.pendingStreams.push(d)}return u}httpStream(e,r,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return pr(e,r,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new p("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let r=e.leaderTabId;return r!==void 0&&r!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new p("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}teardownConnection(e){let r=g(e.shardKey);for(let[s,i]of this.streams)g(i.shardKey)===r&&(i.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(s));if(e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearConnectionTimers(e),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new _e({channelName:e,onBecomeLeader:o(()=>{for(let r of this.subscriptions.all())this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(r);for(let r of this.queuedOfflineShardKeys)this.ensureSocket(r);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:o(()=>{for(let[r,s]of this.connections)this.teardownConnection(s),this.connections.delete(r);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:o((r,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;let i=r==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=r,r==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},"onConnectionStatus"),onSubscriptionData:o((r,s,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;let c=this.subscriptions.get(r);c&&(c.serverBase=s,i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),Qe(c,i)),X(c,ie(s,c.optimisticLayers)))},"onSubscriptionData"),onLeaderClaimAnswered:o(()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onLeaderClaimAnswered"),onSubscriptionError:o((r,s,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;let n=this.subscriptions.get(r);n&&fe(n.errorCallbacks,s)},"onSubscriptionError"),onSubscriptionSettled:o((r,s,i,n,a,c)=>{if(c!==void 0&&c!==this.identityFingerprint())return;let u=this.subscriptions.get(r);if(u){this.ackAndAdvanceCursor(u,s,i),n!==void 0&&a===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let h of u.checkpointCallbacks)h({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async enqueueOfflineMutation(e,r,s,i,n,a,c){let u=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let h=this.outboxMutationCounter;try{await this.outbox.enqueue({args:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(h)}`,identity:u,mutationId:h,shardKey:s})}catch(d){throw qe(n),d instanceof Error?d:new Error(String(d))}for(let d of a)d(void 0);return}return new Promise((h,d)=>{let l={args:r,functionPath:e.__lunoraRef,liveAwaiter:!0,id:i,clientId:this.clientId,identity:u,precondition:c,onCommit:o(f=>{for(let m of a)m(f)},"onCommit"),reject:o(f=>{this.queuedIdentities.delete(i),qe(n),d(f instanceof Error?f:new Error(String(f)))},"reject"),resolve:h,shardKey:s};this.offlineQueue.enqueue(l),this.queuedOfflineShardKeys.add(s),l.id!==void 0&&this.queuedIdentities.set(l.id,u)})}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let r of e)this.queuedOfflineShardKeys.add(r),this.ensureSocket(r)}catch{}}hydrateAsOutboxLeader(){let e=o(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),r=globalThis.navigator?.locks;if(!r){e();return}r.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),r=new Map;for(let s of this.subscriptions.all())r.set(le(s.fn.__lunoraRef,s.argsKey,s.shardKey),s);for(let{key:s,...i}of e){if(dt(this.persistenceVersion,i.version)){this.queryCache.remove(s).catch(()=>{});continue}let n=r.get(s);if(n){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(s,i)}}catch{}}seedSubscriptionFromCache(e,r){e.serverBase!==void 0||e.lastValue!==void 0||r.identity!==this.identityFingerprint()||(e.serverBase=r.value,e.serverCursor=r.serverCursor,r.serverEpoch!==void 0&&(e.serverEpoch=r.serverEpoch),X(e,ie(r.value,e.optimisticLayers)))}takeHydratedCache(e,r,s){let i=le(e,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.hydratedQueryCache.delete(i),n.identity===this.identityFingerprint()?n:void 0}persistQueryValue(e){let r=e.serverBase;if(!this.queryCache||r===void 0)return;let s=le(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity;this.pendingCacheWrites.set(s,{identity:i===void 0?this.identityFingerprint():i,serverCursor:e.serverCursor,ts:Date.now(),value:r,...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},Ds)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let r=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(r.map(async([s,i])=>e.put(s,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(r=>r.wsState==="open")?"connected":e.some(r=>r.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,r,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:r})}applyOptimisticUpdates(e,r,s,i){let n=[],a=[];if(!i)return{confirms:n,rollbacks:a};let c=M.key(e,r,s),u=this.subscriptions.get(c);if(u){let h=ht(u,i);h&&(n.push(h.confirm),a.push(h.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,r,s,i,n){let{confirms:a,rollbacks:c,store:u}=yr(this.subscriptions,s);try{e(u,r)}catch{qe(c);return}i.push(...c),n.push(...a)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,r,s){let i=this.getConnection(e);i&&!F(i,{id:r,type:s})&&i.pendingUnsubscribes.push({id:r,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}let r=this.getConnection(e);return{hasSocket:r?.socket!==void 0,wasEverConnected:r?.wasEverConnected??!1,wsState:r?.wsState??"idle"}}getOrCreateConnection(e){let r=g(e),s=this.connections.get(r);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:ft(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(r,s)),s}wsUrlFor(e,r){let s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),r!==void 0&&s.push(`token=${encodeURIComponent(r)}`),s.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${s.join("&")}`}rpcRequestHeaders(e,r){let s={"content-type":"application/json"},i=this.shardCursors.get(this.cursorKeyFor(r));if(i!==void 0&&(s["x-lunora-min-seq"]=i.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.attachBookmark){let n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,r,s,i={}){if(!this.fetchImpl)throw new B("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,s),a=await this.fetchImpl(Y(this.url,Ms),{body:JSON.stringify({args:H(r,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){let u=a.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await a.json()}catch{throw Ne(a.status,a.statusText,a.headers.get("retry-after"))}if("error"in c)throw Ir(c.error,a.headers.get("retry-after"));if(!a.ok)throw Ne(a.status,a.statusText,a.headers.get("retry-after"));return i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.learnDefaultShardKey(a,s),this.recordShardCursor(s,c.commitCursor),S(c.result)}async adminFetch(e,r,s,i){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let a=s instanceof ArrayBuffer||s instanceof Blob,c;s===void 0?c=void 0:a?(c=s,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(s),n["content-type"]="application/json");let u=await this.fetchImpl(Y(this.url,e),{body:c,headers:n,method:r}),h;try{h=await u.json()}catch{let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${d})`)}if(typeof h=="object"&&h!==null&&"error"in h){let d=h.error,l=new Error(d.message??"admin request failed");throw l.code=d.code,l}if(!u.ok){let d=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${d})`)}return h}effectiveConnectionContext(e){let r=this.connectionContextHolders.get(e);return r&&r.length>0?r[r.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let r=this.connections.get(e);r?.wsState==="open"&&this.sendConnectEnvelope(r)}sendConnectEnvelope(e){let r=this.effectiveConnectionContext(g(e.shardKey));F(e,{caps:nn,clientId:this.clientId,id:"connect",type:"connect",...r===void 0?{}:{context:r}})}resendShapeSubscriptions(e){for(let r of this.shapeSubscriptions.values())g(r.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(r)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let r=this.getOrCreateConnection(e);if(!(r.wsState==="open"||r.wsState==="connecting")){if(r.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(r,e,this.wsToken).catch(()=>{});return}this.openSocket(r,e,this.wsToken)}}async openSocketWithProvidedToken(e,r,s){let i;try{i=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,r,i)}openManagedSocket(e,r,s,i){let{WebSocketImpl:n}=this;if(n===void 0)throw new p("INTERNAL","no WebSocket implementation available");let a=new n(r);e.socket=a;let c=o(()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===a&&(e.socket=void 0)},"o"),u=o(h=>{c(),i.onClose(h)},"c");s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===a){try{a.close()}catch{}u()}},s)),a.addEventListener("open",()=>{if(e.socket===a){e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now();try{i.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}this.startHeartbeat(e,u)}}),a.addEventListener("message",h=>{if(e.socket===a){e.lastFrameAt=Date.now();try{i.onMessage(h)}catch(d){console.error("[lunora] server frame handler threw",d)}}}),a.addEventListener("close",h=>{e.socket===a&&u(h)}),a.addEventListener("error",()=>{e.socket===a&&u()})}openSocket(e,r,s){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),this.openManagedSocket(e,this.wsUrlFor(r,s),this.connectTimeoutMs,{onClose:o(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:o(i=>{this.handleServerMessage(i.data,r)},"onMessage"),onOpen:o(()=>{e.wsState="open",e.wasEverConnected=!0,clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Us),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(r);for(let n of this.subscriptions.all())g(n.shardKey)===g(r)&&this.sendSubscribeIfOpen(n);if(this.resendShapeSubscriptions(r),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:a,type:c}of n)F(e,{id:a,type:c})}this.flushPendingStreams(e);let i=this.whisperHandlers.get(g(r));if(i)for(let n of i.keys())F(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(r).catch(()=>{})},"onOpen")}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;let r=e.pendingStreams;e.pendingStreams=[];for(let s of r){let i=F(e,s)?this.streams.get(String(s.id)):void 0;i&&(i.started=!0)}}cancelStream(e,r){let s=this.getConnection(r),i=this.streams.get(e);s&&(s.pendingStreams=s.pendingStreams?.filter(n=>n.id!==e),!F(s,{id:e,type:"unsubscribe"})&&i?.durable===!0&&i.started&&s.pendingUnsubscribes.push({id:e,type:"unsubscribe"})),this.streams.delete(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;this.stopHeartbeat(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey);let r=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(g(n.shardKey)!==g(e.shardKey)||r.has(i))){if(n.durable){let a={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),a];continue}n.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(i)}if(this.WebSocketImpl===void 0)return;let s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,r){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;let{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}r();return}try{s.send(_s)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){let r=g(e);for(let s of this.subscriptions.all())g(s.shardKey)===r&&(s.acked=!1)}sendSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.acked)return;let s=e.fn.__lunoraTable??e.fn.__lunoraRef,i=e.serverCursor!==void 0&&e.serverBase!==void 0;F(r,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:s,...i?{sinceSeq:e.serverCursor}:{},...i&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);r?.wsState==="open"&&F(r,{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,r){let s=cn(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}switch(i.type!=="error"&&this.getConnection(r)?.reconnect.reset(),i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:a,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof a=="number"&&(h.generation=a),h.durable=!0),h?.handle.push(S(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"pokeEnd":{this.handlePokeEnd(i,r);break}case"pokePart":{this.handlePokePart(i,r);break}case"pokeStart":{this.handlePokeStart(i,r);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,r);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:r}=e,s=r===void 0?void 0:this.streams.get(r);if(s&&r!==void 0){s.handle.fail(an(e)),this.streams.delete(r);return}let i=r===void 0?void 0:this.subscriptions.getById(r);if(i){let a=Er(e),c=this.identityFingerprint(),u=M.keyOf(i);fe(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,a,c);return}let n=r===void 0?void 0:this.shapeSubscriptions.get(r);n&&fe(n.errorCallbacks,Er(e))}pokeBufferKey(e,r){return`${g(e)}\0${r}`}handlePokeStart(e,r){Sr(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(r,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set})}handlePokePart(e,r){let s=this.pokeBuffers.get(this.pokeBufferKey(r,e.pokeId));if(!s)return;let i=s.parts.get(e.shapeId)??[];for(let a of e.rowsPatch)i.push(a.value===void 0?a:{...a,value:S(a.value)});s.parts.set(e.shapeId,i),e.lastMutationId!==void 0&&s.lastMutationId.set(e.shapeId,e.lastMutationId);let n=e.baseCheckpoint??s.baseCheckpoint;n!==void 0&&s.bases.set(e.shapeId,n),e.reset===!0&&s.resets.add(e.shapeId)}handlePokeEnd(e,r){let s=this.pokeBufferKey(r,e.pokeId),i=this.pokeBuffers.get(s);if(i){this.pokeBuffers.delete(s);for(let n of i.parts.keys()){let a=this.shapeSubscriptions.get(n);a&&this.applyPokePart(a,i,e)}}}applyPokePart(e,r,s){let i=r.parts.get(e.id)??[],n=r.resets.has(e.id),a=r.bases.get(e.id),c=r.epoch!==void 0&&e.serverEpoch!==void 0&&r.epoch!==e.serverEpoch,u=a!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==a;if(!n&&(c||u)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}n&&e.rows.clear(),xs(e.rows,i),s.checkpoint!==void 0&&(e.serverCursor=s.checkpoint),s.epoch!==void 0&&(e.serverEpoch=s.epoch);let h=r.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){let r=[...e.rows.values()];for(let s of e.callbacks)try{s(r)}catch{}}handleDataMessage(e){let{id:r}=e,s=r?this.subscriptions.getById(r):void 0;if(!s)return;let i;try{i=this.resolveDataPayload(e,s)}catch(n){fe(s.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${n instanceof Error?n.message:String(n)}`});return}if(i===Cr){this.resnapshotSubscription(s);return}if(s.serverBase=i,e.cursor!==void 0&&(s.serverCursor=e.cursor),e.epoch!==void 0&&(s.serverEpoch=e.epoch),e.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId);for(let n of s.checkpointCallbacks)n({checkpoint:s.serverCursor,mutationId:s.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(s),Qe(s,s.serverCursor),X(s,ie(i,s.optimisticLayers)),this.tabCoordinator?.isLeader()){let n=M.keyOf(s);this.tabCoordinator.broadcastSubscriptionData(n,i,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let r=this.subscriptions.getById(e.id);r&&this.ackAndAdvanceCursor(r,e.cursor,e.epoch)}handleSettledMessage(e){let r=this.subscriptions.getById(e.id);if(r){this.ackAndAdvanceCursor(r,e.cursor,e.epoch),e.lastMutationId!==void 0&&(r.lastMutationId=Math.max(r.lastMutationId??0,e.lastMutationId));for(let s of r.checkpointCallbacks)s({checkpoint:r.serverCursor,mutationId:r.lastMutationId});if(this.tabCoordinator?.isLeader()){let s=M.keyOf(r);this.tabCoordinator.broadcastSubscriptionSettled(s,r.serverCursor,r.serverEpoch,r.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,r,s){e.acked=!0,(r!==void 0&&r!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(r!==void 0&&(e.serverCursor=r),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),Qe(e,e.serverCursor)&&X(e,ie(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,r){if("data"in e&&e.data!==void 0)return S(e.data);let s=S(e.delta);return hr(s)?r.serverBase===void 0?s:dr(r.serverBase,s)??Cr:s}dispatchWhisper(e,r){let s=this.whisperHandlers.get(g(r))?.get(e.topic);if(!s)return;let i=S(e.data);for(let n of s)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let r=this.streams.get(e);if(r){r.handle.complete(),this.streams.delete(e);return}let s=this.subscriptions.getById(e);s&&(s.acked=!1,fe(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(r=>{$(this.onPersistenceError,"remove",r,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 r=2166136261,s=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);r^=n,r=Math.imul(r,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(r>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let r=this.authToken;return r===null?!1:this.hashToken(r)===e}adoptResolvedSubject(e,r){this.closed||r===null||this.authToken!==e||this.setAuthToken(e,r.id)}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let r=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return r===void 0?e.identity:r}rejectQueuedForIdentityChange(e){let r=this.offlineQueue.drain(),s=[];for(let i of r){if(this.replayIdentityVerdict(this.stampOf(i))!=="mismatch"){s.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(s),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,r){for(let s of this.connections.values())s.identity===e&&(s.identity=r)}restampQueuedIdentity(e,r){for(let[s,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,r);this.offlineQueue.restampIdentity(e,r)}restampWatermarks(e,r){let s=e??"",i=this.clientWatermarks.get(s);if(i===void 0)return;this.clientWatermarks.delete(s);let n=r??"",a=this.clientWatermarks.get(n);if(a===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)a.set(c,u)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let r=g(e),s=this.offlineFlushes.get(r);if(s===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(s??Promise.resolve());try{await this.drainOfflineQueue(e)}catch{}})();this.offlineFlushes.set(r,i),await i,this.offlineFlushes.get(r)===i&&this.offlineFlushes.delete(r)}async drainOfflineQueue(e){let r=this.offlineQueue.drainConflict();for(let h of r){this.unpersist(h.id),this.queuedIdentities.delete(h.id??"");let d=new Error("offline mutation skipped: precondition failed before replay");d.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(h,"rejected",d)}let s=g(e),i=this.offlineQueue.drain(h=>g(h.shardKey)===s);if(i.length===0)return;let n=[],a=[];for(let h of i){let d=this.replayGateVerdict(h);d==="send"?n.push(h):d==="hold"&&a.push(h)}if(this.offlineQueue.requeue(a),a.length>0&&this.subjectAwaitingReconfirm()&&this.getCurrentUser().catch(()=>{}),n.length===0)return;let c=this.encodableOrSettleTerminal(n);if(c.length===0)return;if(c.length===1){await this.replaySequential(c,e),this.scheduleRateLimitedRetry(e);return}let u=[];for(let h=0;h<c.length;h+=pt){let d=c.slice(h,h+pt),l=await this.replayBatched(d,e);if(u.push(...l.requeue),l.stop){u.push(...c.slice(h+pt));break}}u.length>0&&this.offlineQueue.requeue(u),this.scheduleRateLimitedRetry(e)}noteReplayRetryDelay(e,r){let s=g(e),i=this.replayRetryState.get(s),n=(i?.attempts??0)+1,a=Rs(r,n);this.replayRetryState.set(s,{attempts:n,delayMs:a===void 0?i?.delayMs:Math.max(i?.delayMs??0,a)})}scheduleRateLimitedRetry(e){let r=g(e),s=this.replayRetryState.get(r),i=s?.delayMs;if(s===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(r);return}s.delayMs=void 0;let n=this.replayRetryTimers.get(r);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(r,setTimeout(()=>{this.replayRetryTimers.delete(r),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let r=[];for(let s of e)try{H(s.args,`args for '${s.functionPath}'`),r.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return r}replayGateVerdict(e){let r=this.stampOf(e);if(r===void 0)return this.queuedIdentities.delete(e.id??""),"send";let s=this.replayIdentityVerdict(r);if(s==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),s==="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,r,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(r),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,r){let s=e.headers.get("x-lunora-shard-key");if(s===null||r!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,r){if(typeof r!="number")return;let s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r))}settleReplayTerminal(e,r){this.unpersist(e.id),e.reject(r),this.emitItemSettled(e,"rejected",r)}async replaySequential(e,r){for(let s=0;s<e.length;s+=1){let i=e[s];if(i)try{let n,a=await this.rpc(i.functionPath,i.args,i.shardKey,{captureBookmark:!0,clientId:i.clientId??this.clientId,mutationId:i.id,onCommitCursor:o(c=>{n=c},"onCommitCursor")});this.settleReplaySuccess(i,a,n)}catch(n){if(!Cs(n)){this.settleReplayTerminal(i,n);continue}this.noteReplayRetryDelay(r,n),this.offlineQueue.requeue(e.slice(s));return}}}async replayBatched(e,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let s=JSON.stringify({calls:e.map((u,h)=>({args:H(u.args,`args for '${u.functionPath}'`),functionPath:u.functionPath,id:h,clientId:u.clientId??this.clientId,mutationId:u.id,shardKey:u.shardKey}))});if(e.length>1&&As(s)>Ps)return await this.replayBatchedHalves(e,r);let i;try{i=await this.fetchImpl(Y(this.url,wr),{body:s,headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:e,stop:!0}}let n=i.headers.get("x-d1-bookmark");if(n&&this.bookmark.set(n),i.status===413&&e.length>1)return await this.replayBatchedHalves(e,r);let a,c=i.headers.get("retry-after");try{a=await i.json()}catch{return this.settleWholeBatchError(e,Ne(i.status,i.statusText,c),r)}if(!a.results){let u=a.error===void 0?Ne(i.status,i.statusText,c):Ir(a.error,c);return this.settleWholeBatchError(e,u,r)}return{requeue:this.settleReplayBatchSlots(e,a.results,r),stop:!1}}settleWholeBatchError(e,r,s){if(r instanceof B||r.code!==void 0&&Ke.has(r.code))return this.noteReplayRetryDelay(s,r),{requeue:e,stop:!0};for(let i of e)this.settleReplayTerminal(i,r);return{requeue:[],stop:!1}}async replayBatchedHalves(e,r){let s=Math.ceil(e.length/2),i=await this.replayBatched(e.slice(0,s),r);if(i.stop)return{requeue:[...i.requeue,...e.slice(s)],stop:!0};let n=await this.replayBatched(e.slice(s),r);return{requeue:[...i.requeue,...n.requeue],stop:n.stop}}settleReplayBatchSlots(e,r,s){let i=new Map;for(let a of r)typeof a.id=="number"&&a.body!==void 0&&i.set(a.id,a.body);let n=[];for(let[a,c]of e.entries()){let u=i.get(a);u===void 0?n.push(c):"error"in u?Ke.has(u.error.code)?(this.noteReplayRetryDelay(s,pe(u.error)),n.push(c)):this.settleReplayTerminal(c,pe(u.error)):this.settleReplaySuccess(c,S(u.result),u.commitCursor)}return n}};var Ar=A(kt(),1),Mr=A(V(),1);var dn=o(()=>{let t=(0,Ar.c)(4),e=st(),r,s,i;return t[0]!==e?(r=o(n=>e.onConnectionStatus(()=>{n()}),"o"),s=o(()=>e.connectionStatus(),"e"),i=o(()=>e.connectionStatus(),"c"),t[0]=e,t[1]=r,t[2]=s,t[3]=i):(r=t[1],s=t[2],i=t[3]),(0,Mr.useSyncExternalStore)(r,s,i)},"S");export{St as a,Qr as b,Ze as c,Wr as d,Gr as e,st as f,dn as g};
@@ -1 +1 @@
1
- import{b as me}from"./chunk-SUDJTC4S.js";import{a as $}from"./chunk-CJMZSHN3.js";import{a as ue}from"./chunk-BOTGXX4H.js";import"./chunk-3SCT7QG7.js";import"./chunk-5JDWLCSH.js";import"./chunk-PYT4RZJH.js";import{a as de}from"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import"./chunk-Y6CXU7T4.js";import"./chunk-4L4WTGN5.js";import{b as D}from"./chunk-NCCAMFB6.js";import"./chunk-25NFR6EB.js";import"./chunk-35DM4JJG.js";import{a as M}from"./chunk-4ZEL6BYL.js";import{c as ce}from"./chunk-6BI6AL3F.js";import{f as ne,g as oe}from"./chunk-ET6VU4YM.js";import"./chunk-FSRSK4LY.js";import"./chunk-FMRAZ6MD.js";import{a as A}from"./chunk-WUWBZPUK.js";import{d as T,f as j,g as Q,h as W,o as _,r as ie}from"./chunk-FODLDLE2.js";import{a as p,d as I,e as Ee,f as ae,g as le,i as E}from"./chunk-YKXDMIHQ.js";var Y=I(ae(),1);var f=I(Ee(),1);var fe=I(ae(),1);var B=I(le(),1);var Me={connected:"bg-success",connecting:"bg-warning",idle:"bg-muted-foreground",offline:"bg-destructive"},he=p(()=>{let t=(0,fe.c)(16),e=T(),a=oe(),s;e:switch(a){case"connected":{let o;t[0]!==e?(o=e("Connected"),t[0]=e,t[1]=o):o=t[1],s=o;break e}case"connecting":{let o;t[2]!==e?(o=e("Connecting\u2026"),t[2]=e,t[3]=o):o=t[3],s=o;break e}case"idle":{let o;t[4]!==e?(o=e("Idle"),t[4]=e,t[5]=o):o=t[5],s=o;break e}case"offline":{let o;t[6]!==e?(o=e("Offline"),t[6]=e,t[7]=o):o=t[7],s=o;break e}default:s=a}let l=Me[a],c;t[8]!==l?(c=E("size-2 rounded-full",l),t[8]=l,t[9]=c):c=t[9];let i;t[10]!==c?(i=(0,B.jsx)("span",{"aria-hidden":"true",className:c}),t[10]=c,t[11]=i):i=t[11];let n;return t[12]!==a||t[13]!==i||t[14]!==s?(n=(0,B.jsxs)("span",{"aria-live":"polite",className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground","data-status":a,"data-testid":"dash-connection",role:"status",children:[i,s]}),t[12]=a,t[13]=i,t[14]=s,t[15]=n):n=t[15],n},"T");var r=I(le(),1);var Ae={crit:"destructive",ok:"secondary",warn:"default"},U=p((t,e)=>e===0?"\u2014":`${(t/e*100).toFixed(1)}%`,"P"),X=p((t,e,a)=>Number.isNaN(t)?"ok":t>=a?"crit":t>=e?"warn":"ok","Q"),xe=.01,ve=.05,je=p(t=>{let e=(0,Y.c)(36),{errorCount:a,logsError:s,topErrors:l,worstFunctions:c}=t,i=T(),n;e[0]!==i?(n=i("Functions by error rate"),e[0]=i,e[1]=n):n=e[1];let o;e[2]!==n?(o=(0,r.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:n})}),e[2]=n,e[3]=o):o=e[3];let h;e[4]!==i||e[5]!==c?(h=c.length===0?(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-functions-empty",children:i("No function activity yet.")}):(0,r.jsx)("ul",{className:"divide-y divide-border",children:c.map(w=>(0,r.jsxs)("li",{className:"flex flex-wrap items-center justify-between gap-2 px-4 py-2 text-xs","data-testid":"hl-fn-row",children:[(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:w.path}),(0,r.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,r.jsx)("span",{className:"tabular-nums text-muted-foreground",children:i("{count} calls",{count:w.calls.toString()})}),(0,r.jsx)(D,{variant:Ae[X(w.errors/w.calls,xe,ve)],children:U(w.errors,w.calls)})]})]},w.path))}),e[4]=i,e[5]=c,e[6]=h):h=e[6];let g;e[7]!==o||e[8]!==h?(g=(0,r.jsxs)(A,{className:"gap-0 py-0","data-testid":"hl-functions",children:[o,h]}),e[7]=o,e[8]=h,e[9]=g):g=e[9];let b;e[10]!==i?(b=i("Recent errors"),e[10]=i,e[11]=b):b=e[11];let d;e[12]!==b?(d=(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:b}),e[12]=b,e[13]=d):d=e[13];let u=a>0?"destructive":"outline",x;e[14]!==a||e[15]!==u?(x=(0,r.jsx)(D,{"data-testid":"hl-error-count",variant:u,children:a}),e[14]=a,e[15]=u,e[16]=x):x=e[16];let v;e[17]!==d||e[18]!==x?(v=(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[d,x]}),e[17]=d,e[18]=x,e[19]=v):v=e[19];let k;e[20]!==s?(k=s!==null&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-destructive","data-testid":"hl-logs-error",role:"alert",children:s}),e[20]=s,e[21]=k):k=e[21];let S;e[22]!==s||e[23]!==i||e[24]!==l.length?(S=s===null&&l.length===0&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-errors-empty",children:i("No recent errors.")}),e[22]=s,e[23]=i,e[24]=l.length,e[25]=S):S=e[25];let q;e[26]!==l?(q=l.length>0&&(0,r.jsx)("ul",{className:"divide-y divide-border",children:l.map(Ce)}),e[26]=l,e[27]=q):q=e[27];let N;e[28]!==k||e[29]!==S||e[30]!==q||e[31]!==v?(N=(0,r.jsxs)(A,{className:"gap-0 py-0",children:[v,k,S,q]}),e[28]=k,e[29]=S,e[30]=q,e[31]=v,e[32]=N):N=e[32];let y;return e[33]!==N||e[34]!==g?(y=(0,r.jsxs)("div",{className:"grid gap-3 lg:grid-cols-2",children:[g,N]}),e[33]=N,e[34]=g,e[35]=y):y=e[35],y},"ye");function Ce(t,e){return(0,r.jsxs)("li",{className:"flex flex-col gap-0.5 px-4 py-2 text-xs","data-testid":"hl-error-row",children:[(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)("time",{className:"shrink-0 text-muted-foreground",children:ie(t.timestamp)}),t.functionPath!==void 0&&(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:t.functionPath})]}),(0,r.jsx)("span",{className:"text-destructive",children:t.message})]},`${t.timestamp.toString()}-${e.toString()}`)}p(Ce,"Te");var pe={completed:0,failed:2,in_progress:1},Ie=p(t=>{let e=0,a=0,s=0,l=0,c=!1,i=[];for(let{metrics:n}of t){if(n===null){l+=1;continue}s+=1,e+=n.requests,a+=n.errors,i.push(...n.history??[]),c||=n.historyTruncated===!0}return{errors:a,failed:l,history:i,historyTruncated:c,reachable:s,requests:e}},"Ae"),Te=p(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.path);if(l===void 0){e.set(s.path,{...s});continue}l.calls+=s.calls,l.errors+=s.errors,l.totalDurationMs+=s.totalDurationMs,l.scans=(l.scans??0)+(s.scans??0),l.maxDurationMs=Math.max(l.maxDurationMs,s.maxDurationMs),l.lastCalledAt=Math.max(l.lastCalledAt,s.lastCalledAt),(s.lastErrorAt??0)>(l.lastErrorAt??0)&&(l.lastErrorAt=s.lastErrorAt,l.lastErrorMessage=s.lastErrorMessage)}return[...e.values()]},"ke"),De=p(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.id);if(l===void 0){e.set(s.id,s);continue}let c=pe[s.status]-pe[l.status];(c>0||c===0&&(s.updatedAt??0)>(l.updatedAt??0))&&e.set(s.id,s)}return[...e.values()]},"Re"),Pe=j(M.getAuthMetrics),Fe=j(M.getFunctionStats),Le=j(M.getLogs),Re=j(M.getMetrics),ze=j(M.migrationStatus),Oe=5,ge=2e3,_e=5,$e=.1,Be=.3,He=1,Ue=50,Ge=p((t,e,a)=>t>=a?"crit":t>=e?"warn":"ok","Pe"),Ke=p(t=>{let e=new Map;for(let s of t??[]){let l=e.get(s.bucketMs)??{calls:0,errors:0};l.calls+=s.calls,l.errors+=s.errors,e.set(s.bucketMs,l)}let a=[...e.entries()].toSorted((s,l)=>s[0]-l[0]);return{errors:a.map(([,s])=>s.errors),requests:a.map(([,s])=>s.calls)}},"Ge"),Ve=p(t=>{let e=0,a=0;for(let l of t)l.status==="failed"?e+=1:l.status==="in_progress"&&(a+=1);let s="ok";return e>0?s="crit":a>0&&(s="warn"),{failed:e,level:s,running:a}},"Ve"),Je=p((t,e)=>t.failed>0?e("{count} failed",{count:t.failed.toString()}):t.running>0?e("{count} running",{count:t.running.toString()}):e("OK"),"Be"),be={crit:"bg-destructive",ok:"bg-success",warn:"bg-warning"},Ne={crit:"text-destructive",ok:"text-foreground",warn:"text-warning"},Qe={crit:"bg-destructive/10 text-destructive",ok:"bg-success/10 text-success",warn:"bg-warning/10 text-warning"},We=p(t=>t.includes("crit")?"crit":t.includes("warn")?"warn":"ok","Ke"),H=p(t=>{let e=(0,Y.c)(19),{chart:a,label:s,level:l,testId:c,value:i}=t,n=be[l],o;e[0]!==n?(o=E("size-1.5 shrink-0 rounded-full",n),e[0]=n,e[1]=o):o=e[1];let h;e[2]!==o?(h=(0,r.jsx)("span",{"aria-hidden":"true",className:o}),e[2]=o,e[3]=h):h=e[3];let g;e[4]!==s||e[5]!==h?(g=(0,r.jsxs)("span",{className:"flex items-center gap-1.5 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:[h,s]}),e[4]=s,e[5]=h,e[6]=g):g=e[6];let b=Ne[l],d;e[7]!==b?(d=E("truncate text-2xl font-semibold tabular-nums",b),e[7]=b,e[8]=d):d=e[8];let u;e[9]!==d||e[10]!==c||e[11]!==i?(u=(0,r.jsx)("span",{className:d,"data-testid":c,children:i}),e[9]=d,e[10]=c,e[11]=i,e[12]=u):u=e[12];let x;e[13]!==a||e[14]!==u?(x=(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[u,a]}),e[13]=a,e[14]=u,e[15]=x):x=e[15];let v;return e[16]!==g||e[17]!==x?(v=(0,r.jsx)(A,{className:"gap-0 py-0",children:(0,r.jsxs)("div",{className:"flex flex-col gap-2.5 p-4",children:[g,x]})}),e[16]=g,e[17]=x,e[18]=v):v=e[18],v},"U"),Xe=p(async(t,e,a)=>{let s=await Promise.all(a.map(d=>{let u=Q(d);return Promise.allSettled([t.query(Re,{},u),t.query(Fe,{},u),t.query(ze,{},u)])})),l=Q(e),c=typeof t.schedulerStatus=="function"?t.schedulerStatus():Promise.reject(new Error("scheduler status unavailable")),[i,n,o]=await Promise.allSettled([t.query(Le,{},l),t.query(Pe,{},l),c]),h=s.map(([d,u,x])=>({functions:u.status==="fulfilled"?u.value.functions:[],metrics:d.status==="fulfilled"?d.value:null,migrations:x.status==="fulfilled"?x.value.migrations:[]})),g=Ie(h),b=s[0]?.[0];return{auth:n.status==="fulfilled"?n.value:null,entries:i.status==="fulfilled"?i.value.entries:[],functions:Te(h.map(d=>d.functions)),logsError:i.status==="rejected"?W(i.reason):null,metricsError:g.reachable===0&&b?.status==="rejected"?W(b.reason):null,migrations:De(h.map(d=>d.migrations)),scheduler:o.status==="fulfilled"?o.value:null,totals:g}},"$e"),Ye=p(t=>{let e=t?.history??[];return{attempts:e.map(a=>a.attempts),failures:e.map(a=>a.failures)}},"ze"),xt=p(({initialShardKey:t})=>{let e=ne(),a=T(),[s,l]=(0,f.useState)([]),[c,i]=(0,f.useState)(null),[n,o]=(0,f.useState)(null),[h,g]=(0,f.useState)(null),[b,d]=(0,f.useState)([]),[u,x]=(0,f.useState)(null),[v,k]=(0,f.useState)(null),[S,q]=(0,f.useState)([]),[N]=(0,f.useState)(de),y=(0,f.useRef)(!1),w=(0,f.useRef)(!0);(0,f.useEffect)(()=>(w.current=!0,()=>{w.current=!1}),[]);let P=t??"",F=(0,f.useCallback)(async()=>{if(y.current)return;y.current=!0;let m=await Xe(e,P,me(P,N));if(!w.current){y.current=!1;return}o(m.totals),g(m.metricsError),d(m.functions),q(m.migrations),l(m.entries),i(m.logsError),x(m.auth),k(m.scheduler),y.current=!1},[e,N,P]);(0,f.useEffect)(()=>{_(F())},[F]);let G=(0,f.useRef)(0),C=(0,f.useRef)(null),we=p(()=>{let m=Date.now()-G.current;if(m>=ge){G.current=Date.now(),_(F());return}C.current===null&&(C.current=setTimeout(()=>{C.current=null,G.current=Date.now(),_(F())},ge-m))},"ue");(0,f.useEffect)(()=>()=>{C.current!==null&&clearTimeout(C.current)},[]);let{data:Z,liveError:ye}=ce(M.getMetrics,{},{live:!0,shardKey:P});(0,f.useEffect)(()=>{Z!==void 0&&we()},[Z]);let ee=s.filter(m=>m.level==="error"),ke=ee.slice(0,Oe),L=Ke(n?.history),te=Ye(u),Se=b.filter(m=>m.calls>0).toSorted((m,J)=>J.errors/J.calls-m.errors/m.calls||J.calls-m.calls).slice(0,_e),K=Ve(S),qe=n===null||n.requests===0?0:n.errors/n.requests,V=X(qe,xe,ve),re=u===null?"ok":X(u.failureRate,$e,Be),se=v===null?"ok":Ge(v.backlog,He,Ue),R=We([V,re,se,K.level]),z,O;return R==="crit"?(z=a("Critical"),O=a("One or more service levels are breached.")):R==="warn"?(z=a("Degraded"),O=a("Some service levels need attention.")):(z=a("All systems healthy"),O=a("All service levels are within target.")),(0,r.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-health",children:[(0,r.jsxs)(A,{className:"gap-0 py-0",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4 p-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:E("flex size-10 shrink-0 items-center justify-center rounded-full",Qe[R]),children:(0,r.jsx)("span",{className:E("size-3 rounded-full",be[R])})}),(0,r.jsxs)("div",{className:"grid leading-tight",children:[(0,r.jsx)("span",{className:"text-sm font-semibold text-foreground","data-testid":"hl-status",children:z}),(0,r.jsx)("span",{className:"text-[13px] text-muted-foreground",children:O})]})]}),(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-4",children:[(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Requests")}),(0,r.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[L.requests.length>=2&&(0,r.jsx)($,{ariaLabel:a("Requests over time"),className:"h-6 w-20 text-foreground",series:L.requests,testId:"hl-spark-requests"}),(0,r.jsx)("span",{className:"text-lg font-semibold tabular-nums text-foreground","data-testid":"hl-requests",children:(n?.requests??0).toString()})]})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Error rate")}),(0,r.jsx)("div",{className:E("text-lg font-semibold tabular-nums",Ne[V]),"data-testid":"hl-error-rate",children:n===null?"\u2014":U(n.errors,n.requests)})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(he,{}),(0,r.jsx)(ue,{message:ye,prefix:"hl"})]})]})]}),h!==null&&(0,r.jsx)("div",{className:"border-t border-border bg-destructive/5 px-4 py-2 text-sm text-destructive","data-testid":"hl-metrics-error",role:"alert",children:h}),h===null&&n?.historyTruncated===!0&&(0,r.jsx)("div",{className:"border-t border-border bg-warning/5 px-4 py-2 text-sm text-muted-foreground","data-testid":"hl-history-truncated",children:a("Showing a partial request/error history \u2014 one or more shards have more data than the trend chart can display.")})]}),(0,r.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4","data-testid":"hl-slo",children:[(0,r.jsx)(H,{chart:L.errors.length>=2?(0,r.jsx)($,{ariaLabel:a("Errors over time"),className:"h-7 w-20 text-destructive",series:L.errors,testId:"hl-spark-errors"}):void 0,label:a("Error rate"),level:V,testId:"hl-slo-errorrate",value:n===null?"\u2014":U(n.errors,n.requests)}),(0,r.jsx)(H,{chart:te.failures.length>=2?(0,r.jsx)($,{ariaLabel:a("Auth failures over time"),className:"h-7 w-20 text-destructive",series:te.failures,testId:"hl-spark-auth"}):void 0,label:a("Auth failures"),level:re,testId:"hl-slo-auth",value:u===null?"\u2014":U(u.failures,u.attempts)}),(0,r.jsx)(H,{label:a("Scheduler backlog"),level:se,testId:"hl-slo-backlog",value:v===null?"\u2014":v.backlog.toString()}),(0,r.jsx)(H,{label:a("Migrations"),level:K.level,testId:"hl-slo-migrations",value:Je(K,a)})]}),(0,r.jsx)(je,{errorCount:ee.length,logsError:c,topErrors:ke,worstFunctions:Se}),(0,r.jsxs)(A,{className:"gap-0 py-0",children:[(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:a("Shards seen")}),(0,r.jsx)(D,{"data-testid":"hl-shard-count",variant:"outline",children:N.length})]}),N.length>0&&(0,r.jsx)("ul",{className:"flex flex-wrap gap-1.5 p-4",children:N.map(m=>(0,r.jsx)("li",{"data-testid":"hl-shard",children:(0,r.jsx)(D,{variant:"secondary",children:m})},m))})]})]})},"ut");export{xt as HealthPanel};
1
+ import{b as me}from"./chunk-SUDJTC4S.js";import{a as $}from"./chunk-EEARNRS4.js";import{a as ue}from"./chunk-BOTGXX4H.js";import"./chunk-3AZM3E32.js";import"./chunk-5JDWLCSH.js";import"./chunk-PYT4RZJH.js";import{a as de}from"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import"./chunk-Y6CXU7T4.js";import"./chunk-4L4WTGN5.js";import{b as D}from"./chunk-NCCAMFB6.js";import"./chunk-25NFR6EB.js";import"./chunk-35DM4JJG.js";import{a as M}from"./chunk-4ZEL6BYL.js";import{c as ce}from"./chunk-6XDE6XBT.js";import{f as ne,g as oe}from"./chunk-4U4NQF6Z.js";import"./chunk-FSRSK4LY.js";import"./chunk-RZNN2EJU.js";import{a as A}from"./chunk-WUWBZPUK.js";import{d as T,f as j,g as Q,h as W,o as _,r as ie}from"./chunk-FODLDLE2.js";import{a as p,d as I,e as Ee,f as ae,g as le,i as E}from"./chunk-YKXDMIHQ.js";var Y=I(ae(),1);var f=I(Ee(),1);var fe=I(ae(),1);var B=I(le(),1);var Me={connected:"bg-success",connecting:"bg-warning",idle:"bg-muted-foreground",offline:"bg-destructive"},he=p(()=>{let t=(0,fe.c)(16),e=T(),a=oe(),s;e:switch(a){case"connected":{let o;t[0]!==e?(o=e("Connected"),t[0]=e,t[1]=o):o=t[1],s=o;break e}case"connecting":{let o;t[2]!==e?(o=e("Connecting\u2026"),t[2]=e,t[3]=o):o=t[3],s=o;break e}case"idle":{let o;t[4]!==e?(o=e("Idle"),t[4]=e,t[5]=o):o=t[5],s=o;break e}case"offline":{let o;t[6]!==e?(o=e("Offline"),t[6]=e,t[7]=o):o=t[7],s=o;break e}default:s=a}let l=Me[a],c;t[8]!==l?(c=E("size-2 rounded-full",l),t[8]=l,t[9]=c):c=t[9];let i;t[10]!==c?(i=(0,B.jsx)("span",{"aria-hidden":"true",className:c}),t[10]=c,t[11]=i):i=t[11];let n;return t[12]!==a||t[13]!==i||t[14]!==s?(n=(0,B.jsxs)("span",{"aria-live":"polite",className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground","data-status":a,"data-testid":"dash-connection",role:"status",children:[i,s]}),t[12]=a,t[13]=i,t[14]=s,t[15]=n):n=t[15],n},"T");var r=I(le(),1);var Ae={crit:"destructive",ok:"secondary",warn:"default"},U=p((t,e)=>e===0?"\u2014":`${(t/e*100).toFixed(1)}%`,"P"),X=p((t,e,a)=>Number.isNaN(t)?"ok":t>=a?"crit":t>=e?"warn":"ok","Q"),xe=.01,ve=.05,je=p(t=>{let e=(0,Y.c)(36),{errorCount:a,logsError:s,topErrors:l,worstFunctions:c}=t,i=T(),n;e[0]!==i?(n=i("Functions by error rate"),e[0]=i,e[1]=n):n=e[1];let o;e[2]!==n?(o=(0,r.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:n})}),e[2]=n,e[3]=o):o=e[3];let h;e[4]!==i||e[5]!==c?(h=c.length===0?(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-functions-empty",children:i("No function activity yet.")}):(0,r.jsx)("ul",{className:"divide-y divide-border",children:c.map(w=>(0,r.jsxs)("li",{className:"flex flex-wrap items-center justify-between gap-2 px-4 py-2 text-xs","data-testid":"hl-fn-row",children:[(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:w.path}),(0,r.jsxs)("span",{className:"flex shrink-0 items-center gap-2",children:[(0,r.jsx)("span",{className:"tabular-nums text-muted-foreground",children:i("{count} calls",{count:w.calls.toString()})}),(0,r.jsx)(D,{variant:Ae[X(w.errors/w.calls,xe,ve)],children:U(w.errors,w.calls)})]})]},w.path))}),e[4]=i,e[5]=c,e[6]=h):h=e[6];let g;e[7]!==o||e[8]!==h?(g=(0,r.jsxs)(A,{className:"gap-0 py-0","data-testid":"hl-functions",children:[o,h]}),e[7]=o,e[8]=h,e[9]=g):g=e[9];let b;e[10]!==i?(b=i("Recent errors"),e[10]=i,e[11]=b):b=e[11];let d;e[12]!==b?(d=(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:b}),e[12]=b,e[13]=d):d=e[13];let u=a>0?"destructive":"outline",x;e[14]!==a||e[15]!==u?(x=(0,r.jsx)(D,{"data-testid":"hl-error-count",variant:u,children:a}),e[14]=a,e[15]=u,e[16]=x):x=e[16];let v;e[17]!==d||e[18]!==x?(v=(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[d,x]}),e[17]=d,e[18]=x,e[19]=v):v=e[19];let k;e[20]!==s?(k=s!==null&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-destructive","data-testid":"hl-logs-error",role:"alert",children:s}),e[20]=s,e[21]=k):k=e[21];let S;e[22]!==s||e[23]!==i||e[24]!==l.length?(S=s===null&&l.length===0&&(0,r.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"hl-errors-empty",children:i("No recent errors.")}),e[22]=s,e[23]=i,e[24]=l.length,e[25]=S):S=e[25];let q;e[26]!==l?(q=l.length>0&&(0,r.jsx)("ul",{className:"divide-y divide-border",children:l.map(Ce)}),e[26]=l,e[27]=q):q=e[27];let N;e[28]!==k||e[29]!==S||e[30]!==q||e[31]!==v?(N=(0,r.jsxs)(A,{className:"gap-0 py-0",children:[v,k,S,q]}),e[28]=k,e[29]=S,e[30]=q,e[31]=v,e[32]=N):N=e[32];let y;return e[33]!==N||e[34]!==g?(y=(0,r.jsxs)("div",{className:"grid gap-3 lg:grid-cols-2",children:[g,N]}),e[33]=N,e[34]=g,e[35]=y):y=e[35],y},"ye");function Ce(t,e){return(0,r.jsxs)("li",{className:"flex flex-col gap-0.5 px-4 py-2 text-xs","data-testid":"hl-error-row",children:[(0,r.jsxs)("span",{className:"flex items-center gap-2",children:[(0,r.jsx)("time",{className:"shrink-0 text-muted-foreground",children:ie(t.timestamp)}),t.functionPath!==void 0&&(0,r.jsx)("span",{className:"truncate font-mono text-foreground",children:t.functionPath})]}),(0,r.jsx)("span",{className:"text-destructive",children:t.message})]},`${t.timestamp.toString()}-${e.toString()}`)}p(Ce,"Te");var pe={completed:0,failed:2,in_progress:1},Ie=p(t=>{let e=0,a=0,s=0,l=0,c=!1,i=[];for(let{metrics:n}of t){if(n===null){l+=1;continue}s+=1,e+=n.requests,a+=n.errors,i.push(...n.history??[]),c||=n.historyTruncated===!0}return{errors:a,failed:l,history:i,historyTruncated:c,reachable:s,requests:e}},"Ae"),Te=p(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.path);if(l===void 0){e.set(s.path,{...s});continue}l.calls+=s.calls,l.errors+=s.errors,l.totalDurationMs+=s.totalDurationMs,l.scans=(l.scans??0)+(s.scans??0),l.maxDurationMs=Math.max(l.maxDurationMs,s.maxDurationMs),l.lastCalledAt=Math.max(l.lastCalledAt,s.lastCalledAt),(s.lastErrorAt??0)>(l.lastErrorAt??0)&&(l.lastErrorAt=s.lastErrorAt,l.lastErrorMessage=s.lastErrorMessage)}return[...e.values()]},"ke"),De=p(t=>{let e=new Map;for(let a of t)for(let s of a){let l=e.get(s.id);if(l===void 0){e.set(s.id,s);continue}let c=pe[s.status]-pe[l.status];(c>0||c===0&&(s.updatedAt??0)>(l.updatedAt??0))&&e.set(s.id,s)}return[...e.values()]},"Re"),Pe=j(M.getAuthMetrics),Fe=j(M.getFunctionStats),Le=j(M.getLogs),Re=j(M.getMetrics),ze=j(M.migrationStatus),Oe=5,ge=2e3,_e=5,$e=.1,Be=.3,He=1,Ue=50,Ge=p((t,e,a)=>t>=a?"crit":t>=e?"warn":"ok","Pe"),Ke=p(t=>{let e=new Map;for(let s of t??[]){let l=e.get(s.bucketMs)??{calls:0,errors:0};l.calls+=s.calls,l.errors+=s.errors,e.set(s.bucketMs,l)}let a=[...e.entries()].toSorted((s,l)=>s[0]-l[0]);return{errors:a.map(([,s])=>s.errors),requests:a.map(([,s])=>s.calls)}},"Ge"),Ve=p(t=>{let e=0,a=0;for(let l of t)l.status==="failed"?e+=1:l.status==="in_progress"&&(a+=1);let s="ok";return e>0?s="crit":a>0&&(s="warn"),{failed:e,level:s,running:a}},"Ve"),Je=p((t,e)=>t.failed>0?e("{count} failed",{count:t.failed.toString()}):t.running>0?e("{count} running",{count:t.running.toString()}):e("OK"),"Be"),be={crit:"bg-destructive",ok:"bg-success",warn:"bg-warning"},Ne={crit:"text-destructive",ok:"text-foreground",warn:"text-warning"},Qe={crit:"bg-destructive/10 text-destructive",ok:"bg-success/10 text-success",warn:"bg-warning/10 text-warning"},We=p(t=>t.includes("crit")?"crit":t.includes("warn")?"warn":"ok","Ke"),H=p(t=>{let e=(0,Y.c)(19),{chart:a,label:s,level:l,testId:c,value:i}=t,n=be[l],o;e[0]!==n?(o=E("size-1.5 shrink-0 rounded-full",n),e[0]=n,e[1]=o):o=e[1];let h;e[2]!==o?(h=(0,r.jsx)("span",{"aria-hidden":"true",className:o}),e[2]=o,e[3]=h):h=e[3];let g;e[4]!==s||e[5]!==h?(g=(0,r.jsxs)("span",{className:"flex items-center gap-1.5 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:[h,s]}),e[4]=s,e[5]=h,e[6]=g):g=e[6];let b=Ne[l],d;e[7]!==b?(d=E("truncate text-2xl font-semibold tabular-nums",b),e[7]=b,e[8]=d):d=e[8];let u;e[9]!==d||e[10]!==c||e[11]!==i?(u=(0,r.jsx)("span",{className:d,"data-testid":c,children:i}),e[9]=d,e[10]=c,e[11]=i,e[12]=u):u=e[12];let x;e[13]!==a||e[14]!==u?(x=(0,r.jsxs)("div",{className:"flex items-center justify-between gap-3",children:[u,a]}),e[13]=a,e[14]=u,e[15]=x):x=e[15];let v;return e[16]!==g||e[17]!==x?(v=(0,r.jsx)(A,{className:"gap-0 py-0",children:(0,r.jsxs)("div",{className:"flex flex-col gap-2.5 p-4",children:[g,x]})}),e[16]=g,e[17]=x,e[18]=v):v=e[18],v},"U"),Xe=p(async(t,e,a)=>{let s=await Promise.all(a.map(d=>{let u=Q(d);return Promise.allSettled([t.query(Re,{},u),t.query(Fe,{},u),t.query(ze,{},u)])})),l=Q(e),c=typeof t.schedulerStatus=="function"?t.schedulerStatus():Promise.reject(new Error("scheduler status unavailable")),[i,n,o]=await Promise.allSettled([t.query(Le,{},l),t.query(Pe,{},l),c]),h=s.map(([d,u,x])=>({functions:u.status==="fulfilled"?u.value.functions:[],metrics:d.status==="fulfilled"?d.value:null,migrations:x.status==="fulfilled"?x.value.migrations:[]})),g=Ie(h),b=s[0]?.[0];return{auth:n.status==="fulfilled"?n.value:null,entries:i.status==="fulfilled"?i.value.entries:[],functions:Te(h.map(d=>d.functions)),logsError:i.status==="rejected"?W(i.reason):null,metricsError:g.reachable===0&&b?.status==="rejected"?W(b.reason):null,migrations:De(h.map(d=>d.migrations)),scheduler:o.status==="fulfilled"?o.value:null,totals:g}},"$e"),Ye=p(t=>{let e=t?.history??[];return{attempts:e.map(a=>a.attempts),failures:e.map(a=>a.failures)}},"ze"),xt=p(({initialShardKey:t})=>{let e=ne(),a=T(),[s,l]=(0,f.useState)([]),[c,i]=(0,f.useState)(null),[n,o]=(0,f.useState)(null),[h,g]=(0,f.useState)(null),[b,d]=(0,f.useState)([]),[u,x]=(0,f.useState)(null),[v,k]=(0,f.useState)(null),[S,q]=(0,f.useState)([]),[N]=(0,f.useState)(de),y=(0,f.useRef)(!1),w=(0,f.useRef)(!0);(0,f.useEffect)(()=>(w.current=!0,()=>{w.current=!1}),[]);let P=t??"",F=(0,f.useCallback)(async()=>{if(y.current)return;y.current=!0;let m=await Xe(e,P,me(P,N));if(!w.current){y.current=!1;return}o(m.totals),g(m.metricsError),d(m.functions),q(m.migrations),l(m.entries),i(m.logsError),x(m.auth),k(m.scheduler),y.current=!1},[e,N,P]);(0,f.useEffect)(()=>{_(F())},[F]);let G=(0,f.useRef)(0),C=(0,f.useRef)(null),we=p(()=>{let m=Date.now()-G.current;if(m>=ge){G.current=Date.now(),_(F());return}C.current===null&&(C.current=setTimeout(()=>{C.current=null,G.current=Date.now(),_(F())},ge-m))},"ue");(0,f.useEffect)(()=>()=>{C.current!==null&&clearTimeout(C.current)},[]);let{data:Z,liveError:ye}=ce(M.getMetrics,{},{live:!0,shardKey:P});(0,f.useEffect)(()=>{Z!==void 0&&we()},[Z]);let ee=s.filter(m=>m.level==="error"),ke=ee.slice(0,Oe),L=Ke(n?.history),te=Ye(u),Se=b.filter(m=>m.calls>0).toSorted((m,J)=>J.errors/J.calls-m.errors/m.calls||J.calls-m.calls).slice(0,_e),K=Ve(S),qe=n===null||n.requests===0?0:n.errors/n.requests,V=X(qe,xe,ve),re=u===null?"ok":X(u.failureRate,$e,Be),se=v===null?"ok":Ge(v.backlog,He,Ue),R=We([V,re,se,K.level]),z,O;return R==="crit"?(z=a("Critical"),O=a("One or more service levels are breached.")):R==="warn"?(z=a("Degraded"),O=a("Some service levels need attention.")):(z=a("All systems healthy"),O=a("All service levels are within target.")),(0,r.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-health",children:[(0,r.jsxs)(A,{className:"gap-0 py-0",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-4 p-4",children:[(0,r.jsxs)("div",{className:"flex items-center gap-3",children:[(0,r.jsx)("span",{"aria-hidden":"true",className:E("flex size-10 shrink-0 items-center justify-center rounded-full",Qe[R]),children:(0,r.jsx)("span",{className:E("size-3 rounded-full",be[R])})}),(0,r.jsxs)("div",{className:"grid leading-tight",children:[(0,r.jsx)("span",{className:"text-sm font-semibold text-foreground","data-testid":"hl-status",children:z}),(0,r.jsx)("span",{className:"text-[13px] text-muted-foreground",children:O})]})]}),(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-4",children:[(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Requests")}),(0,r.jsxs)("div",{className:"flex items-center justify-end gap-2",children:[L.requests.length>=2&&(0,r.jsx)($,{ariaLabel:a("Requests over time"),className:"h-6 w-20 text-foreground",series:L.requests,testId:"hl-spark-requests"}),(0,r.jsx)("span",{className:"text-lg font-semibold tabular-nums text-foreground","data-testid":"hl-requests",children:(n?.requests??0).toString()})]})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"text-end",children:[(0,r.jsx)("div",{className:"font-mono text-[10px] tracking-wide text-muted-foreground uppercase",children:a("Error rate")}),(0,r.jsx)("div",{className:E("text-lg font-semibold tabular-nums",Ne[V]),"data-testid":"hl-error-rate",children:n===null?"\u2014":U(n.errors,n.requests)})]}),(0,r.jsx)("span",{"aria-hidden":"true",className:"h-9 w-px bg-border"}),(0,r.jsxs)("div",{className:"flex items-center gap-2",children:[(0,r.jsx)(he,{}),(0,r.jsx)(ue,{message:ye,prefix:"hl"})]})]})]}),h!==null&&(0,r.jsx)("div",{className:"border-t border-border bg-destructive/5 px-4 py-2 text-sm text-destructive","data-testid":"hl-metrics-error",role:"alert",children:h}),h===null&&n?.historyTruncated===!0&&(0,r.jsx)("div",{className:"border-t border-border bg-warning/5 px-4 py-2 text-sm text-muted-foreground","data-testid":"hl-history-truncated",children:a("Showing a partial request/error history \u2014 one or more shards have more data than the trend chart can display.")})]}),(0,r.jsxs)("div",{className:"grid gap-3 sm:grid-cols-2 xl:grid-cols-4","data-testid":"hl-slo",children:[(0,r.jsx)(H,{chart:L.errors.length>=2?(0,r.jsx)($,{ariaLabel:a("Errors over time"),className:"h-7 w-20 text-destructive",series:L.errors,testId:"hl-spark-errors"}):void 0,label:a("Error rate"),level:V,testId:"hl-slo-errorrate",value:n===null?"\u2014":U(n.errors,n.requests)}),(0,r.jsx)(H,{chart:te.failures.length>=2?(0,r.jsx)($,{ariaLabel:a("Auth failures over time"),className:"h-7 w-20 text-destructive",series:te.failures,testId:"hl-spark-auth"}):void 0,label:a("Auth failures"),level:re,testId:"hl-slo-auth",value:u===null?"\u2014":U(u.failures,u.attempts)}),(0,r.jsx)(H,{label:a("Scheduler backlog"),level:se,testId:"hl-slo-backlog",value:v===null?"\u2014":v.backlog.toString()}),(0,r.jsx)(H,{label:a("Migrations"),level:K.level,testId:"hl-slo-migrations",value:Je(K,a)})]}),(0,r.jsx)(je,{errorCount:ee.length,logsError:c,topErrors:ke,worstFunctions:Se}),(0,r.jsxs)(A,{className:"gap-0 py-0",children:[(0,r.jsxs)("header",{className:"flex items-center justify-between gap-2 border-b border-border px-4 py-3",children:[(0,r.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:a("Shards seen")}),(0,r.jsx)(D,{"data-testid":"hl-shard-count",variant:"outline",children:N.length})]}),N.length>0&&(0,r.jsx)("ul",{className:"flex flex-wrap gap-1.5 p-4",children:N.map(m=>(0,r.jsx)("li",{"data-testid":"hl-shard",children:(0,r.jsx)(D,{variant:"secondary",children:m})},m))})]})]})},"ut");export{xt as HealthPanel};
@@ -1 +1 @@
1
- import{b as de}from"./chunk-UYEZR3BI.js";import{a as te,b as re,c as ne}from"./chunk-Q4CAKBWN.js";import"./chunk-OKG3HWSJ.js";import{b as Y}from"./chunk-NCCAMFB6.js";import"./chunk-25NFR6EB.js";import{a as ae}from"./chunk-NJSJI7SX.js";import"./chunk-ULIQFBZU.js";import"./chunk-7SPAXZ55.js";import"./chunk-35DM4JJG.js";import{a as ee}from"./chunk-4ZEL6BYL.js";import{c as Z}from"./chunk-6BI6AL3F.js";import"./chunk-ET6VU4YM.js";import"./chunk-FSRSK4LY.js";import"./chunk-FMRAZ6MD.js";import{a as le,b as oe,c as se,d as H,e as z,f as G}from"./chunk-HEAQVSNS.js";import{a as P,e as q}from"./chunk-WUWBZPUK.js";import{d as X}from"./chunk-FODLDLE2.js";import{a as g,d as W,f as ce,g as me}from"./chunk-YKXDMIHQ.js";var J=W(ce(),1);var t=W(me(),1);var ue={binding:"outline",secret:"destructive",var:"secondary"},pe=g((n,e)=>{if(n===void 0)return[];let u=[];return n.workerUrl!==void 0&&u.push({label:e("URL"),value:n.workerUrl}),n.environment!==void 0&&u.push({label:e("Environment"),value:n.environment}),n.deploymentId!==void 0&&u.push({label:e("Deployment"),value:n.deploymentId}),n.versionTag!==void 0&&u.push({label:e("Version"),value:n.versionTag}),u},"ce"),ie=g(n=>{let e=(0,J.c)(18),{modifier:u,name:r,label:p}=n,A=te(),x;e[0]!==r?(x=g(o=>{if(!["Escape","Tab"].includes(o.key)){if(o.shiftKey){o.preventDefault();return}o.preventDefault(),re(r,o.key)}},"b"),e[0]=r,e[1]=x):x=e[1];let i=x,c=`set-shortcut-${r}`,m;e[2]!==p?(m=(0,t.jsx)("dt",{className:"text-muted-foreground",children:p}),e[2]=p,e[3]=m):m=e[3];let h;e[4]!==u?(h=(0,t.jsx)("kbd",{className:"rounded border border-border px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground",children:u}),e[4]=u,e[5]=h):h=e[5];let l=`set-shortcut-input-${r}`,f=A[r],s;e[6]!==p||e[7]!==i||e[8]!==l||e[9]!==f?(s=(0,t.jsx)("input",{"aria-label":p,className:"h-7 w-12 rounded-md border border-border bg-background text-center font-mono text-xs uppercase outline-none focus-visible:border-ring","data-testid":l,onKeyDown:i,readOnly:!0,value:f}),e[6]=p,e[7]=i,e[8]=l,e[9]=f,e[10]=s):s=e[10];let a;e[11]!==h||e[12]!==s?(a=(0,t.jsxs)("dd",{className:"flex items-center gap-1.5",children:[h,s]}),e[11]=h,e[12]=s,e[13]=a):a=e[13];let d;return e[14]!==c||e[15]!==m||e[16]!==a?(d=(0,t.jsxs)("div",{className:"contents","data-testid":c,children:[m,a]}),e[14]=c,e[15]=m,e[16]=a,e[17]=d):d=e[17],d},"z"),Se=g(n=>{let e=(0,J.c)(85),{initialShardKey:u}=n,r=X(),p;e[0]===Symbol.for("react.memo_cache_sentinel")?(p={},e[0]=p):p=e[0];let A=u??"",x;e[1]!==A?(x={shardKey:A},e[1]=A,e[2]=x):x=e[2];let{data:i,error:c,errorSource:m,isLoading:h}=Z(ee.getSettings,p,x),l,f,s,a,d,o,b;if(e[3]!==c||e[4]!==m||e[5]!==i?.deploy||e[6]!==i?.settings||e[7]!==r){let Q=pe(i?.deploy,r),M;e[15]!==i?.settings?(M=i?.settings??[],e[15]=i?.settings,e[16]=M):M=e[16],l=M,f="flex flex-col gap-4",s="lunora-settings";let V;e[17]!==r?(V=r("Open in Cloudflare"),e[17]=r,e[18]=V):V=e[18],e[19]!==V?(a=(0,t.jsx)("div",{className:"flex flex-wrap items-center gap-3",children:(0,t.jsx)("a",{className:"text-sm text-primary underline-offset-4 hover:underline","data-testid":"set-cf-link",href:de,rel:"noreferrer",target:"_blank",children:V})}),e[19]=V,e[20]=a):a=e[20];let $;e[21]!==r?($=r("View-only \u2014 values are masked. Edit vars, secrets, and bindings in wrangler or the Cloudflare dashboard."),e[21]=r,e[22]=$):$=e[22],e[23]!==$?(d=(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"set-readonly-note",children:$}),e[23]=$,e[24]=d):d=e[24],e[25]!==c||e[26]!==m?(o=c!==null&&(0,t.jsx)(ae,{error:m,testId:"set-error"}),e[25]=c,e[26]=m,e[27]=o):o=e[27],b=Q.length>0&&(0,t.jsxs)(P,{className:"py-0","data-testid":"set-deploy",children:[(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:r("Deployment")})}),(0,t.jsx)(q,{className:"py-3",children:(0,t.jsx)("dl",{className:"grid grid-cols-[8rem_minmax(0,1fr)] gap-x-4 gap-y-1 text-sm",children:Q.map(he)})})]}),e[3]=c,e[4]=m,e[5]=i?.deploy,e[6]=i?.settings,e[7]=r,e[8]=l,e[9]=f,e[10]=s,e[11]=a,e[12]=d,e[13]=o,e[14]=b}else l=e[8],f=e[9],s=e[10],a=e[11],d=e[12],o=e[13],b=e[14];let y;e[28]!==r?(y=r("Keyboard shortcuts"),e[28]=r,e[29]=y):y=e[29];let v;e[30]!==y?(v=(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:y}),e[30]=y,e[31]=v):v=e[31];let N;e[32]!==r?(N=r("Reset"),e[32]=r,e[33]=N):N=e[33];let k;e[34]!==N?(k=(0,t.jsx)("button",{className:"rounded px-1 text-[11px] text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:text-foreground","data-testid":"set-shortcut-reset",onClick:ne,type:"button",children:N}),e[34]=N,e[35]=k):k=e[35];let w;e[36]!==v||e[37]!==k?(w=(0,t.jsxs)("header",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[v,k]}),e[36]=v,e[37]=k,e[38]=w):w=e[38];let C;e[39]!==r?(C=r("Command palette"),e[39]=r,e[40]=C):C=e[40];let S;e[41]!==C?(S=(0,t.jsx)(ie,{label:C,modifier:"\u2318/Ctrl",name:"palette"}),e[41]=C,e[42]=S):S=e[42];let T;e[43]!==r?(T=r("Operation console"),e[43]=r,e[44]=T):T=e[44];let D;e[45]!==T?(D=(0,t.jsx)(ie,{label:T,modifier:"Ctrl",name:"console"}),e[45]=T,e[46]=D):D=e[46];let _;e[47]!==S||e[48]!==D?(_=(0,t.jsxs)("dl",{className:"grid grid-cols-[10rem_minmax(0,1fr)] items-center gap-x-4 gap-y-2 text-sm",children:[S,D]}),e[47]=S,e[48]=D,e[49]=_):_=e[49];let E;e[50]!==r?(E=r("Stored in this browser. Focus a box and press a key to rebind it."),e[50]=r,e[51]=E):E=e[51];let I;e[52]!==E?(I=(0,t.jsx)("p",{className:"pt-3 text-xs text-muted-foreground",children:E}),e[52]=E,e[53]=I):I=e[53];let K;e[54]!==_||e[55]!==I?(K=(0,t.jsxs)(q,{className:"py-3",children:[_,I]}),e[54]=_,e[55]=I,e[56]=K):K=e[56];let O;e[57]!==w||e[58]!==K?(O=(0,t.jsxs)(P,{className:"py-0","data-testid":"set-preferences",children:[w,K]}),e[57]=w,e[58]=K,e[59]=O):O=e[59];let U;e[60]!==r?(U=r("Environment & bindings"),e[60]=r,e[61]=U):U=e[61];let j;e[62]!==U?(j=(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:U})}),e[62]=U,e[63]=j):j=e[63];let F;e[64]!==c||e[65]!==h||e[66]!==l.length||e[67]!==r?(F=c===null&&!h&&l.length===0&&(0,t.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"set-empty",children:r("No environment variables or bindings.")}),e[64]=c,e[65]=h,e[66]=l.length,e[67]=r,e[68]=F):F=e[68];let L;e[69]!==l||e[70]!==r?(L=l.length>0&&(0,t.jsx)(q,{className:"px-0 py-0",children:(0,t.jsxs)(le,{"data-testid":"set-table",children:[(0,t.jsx)(oe,{children:(0,t.jsxs)(H,{children:[(0,t.jsx)(z,{children:r("name")}),(0,t.jsx)(z,{children:r("kind")}),(0,t.jsx)(z,{children:r("value")})]})}),(0,t.jsx)(se,{children:l.map(fe)})]})}),e[69]=l,e[70]=r,e[71]=L):L=e[71];let R;e[72]!==j||e[73]!==F||e[74]!==L?(R=(0,t.jsxs)(P,{className:"py-0",children:[j,F,L]}),e[72]=j,e[73]=F,e[74]=L,e[75]=R):R=e[75];let B;return e[76]!==O||e[77]!==R||e[78]!==f||e[79]!==s||e[80]!==a||e[81]!==d||e[82]!==o||e[83]!==b?(B=(0,t.jsxs)("div",{className:f,"data-testid":s,children:[a,d,o,b,O,R]}),e[76]=O,e[77]=R,e[78]=f,e[79]=s,e[80]=a,e[81]=d,e[82]=o,e[83]=b,e[84]=B):B=e[84],B},"Ce");function he(n){return(0,t.jsxs)("div",{className:"contents","data-testid":"set-deploy-row",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:n.label}),(0,t.jsx)("dd",{className:"truncate font-mono text-xs",title:n.value,children:n.value})]},n.label)}g(he,"me");function fe(n){return(0,t.jsxs)(H,{"data-testid":"set-row",children:[(0,t.jsx)(G,{className:"font-mono text-xs font-medium",children:n.name}),(0,t.jsx)(G,{children:(0,t.jsx)(Y,{variant:ue[n.kind],children:n.bindingType??n.kind})}),(0,t.jsx)(G,{className:"max-w-[28ch] truncate font-mono text-xs text-muted-foreground",children:n.value??(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})})]},n.name)}g(fe,"fe");export{Se as SettingsPanel};
1
+ import{b as de}from"./chunk-UYEZR3BI.js";import{a as te,b as re,c as ne}from"./chunk-Q4CAKBWN.js";import"./chunk-OKG3HWSJ.js";import{b as Y}from"./chunk-NCCAMFB6.js";import"./chunk-25NFR6EB.js";import{a as ae}from"./chunk-EESOT5SI.js";import"./chunk-ULIQFBZU.js";import"./chunk-MQ42VLOS.js";import"./chunk-35DM4JJG.js";import{a as ee}from"./chunk-4ZEL6BYL.js";import{c as Z}from"./chunk-6XDE6XBT.js";import"./chunk-4U4NQF6Z.js";import"./chunk-FSRSK4LY.js";import"./chunk-RZNN2EJU.js";import{a as le,b as oe,c as se,d as H,e as z,f as G}from"./chunk-HEAQVSNS.js";import{a as P,e as q}from"./chunk-WUWBZPUK.js";import{d as X}from"./chunk-FODLDLE2.js";import{a as g,d as W,f as ce,g as me}from"./chunk-YKXDMIHQ.js";var J=W(ce(),1);var t=W(me(),1);var ue={binding:"outline",secret:"destructive",var:"secondary"},pe=g((n,e)=>{if(n===void 0)return[];let u=[];return n.workerUrl!==void 0&&u.push({label:e("URL"),value:n.workerUrl}),n.environment!==void 0&&u.push({label:e("Environment"),value:n.environment}),n.deploymentId!==void 0&&u.push({label:e("Deployment"),value:n.deploymentId}),n.versionTag!==void 0&&u.push({label:e("Version"),value:n.versionTag}),u},"ce"),ie=g(n=>{let e=(0,J.c)(18),{modifier:u,name:r,label:p}=n,A=te(),x;e[0]!==r?(x=g(o=>{if(!["Escape","Tab"].includes(o.key)){if(o.shiftKey){o.preventDefault();return}o.preventDefault(),re(r,o.key)}},"b"),e[0]=r,e[1]=x):x=e[1];let i=x,c=`set-shortcut-${r}`,m;e[2]!==p?(m=(0,t.jsx)("dt",{className:"text-muted-foreground",children:p}),e[2]=p,e[3]=m):m=e[3];let h;e[4]!==u?(h=(0,t.jsx)("kbd",{className:"rounded border border-border px-1.5 py-0.5 font-mono text-[11px] text-muted-foreground",children:u}),e[4]=u,e[5]=h):h=e[5];let l=`set-shortcut-input-${r}`,f=A[r],s;e[6]!==p||e[7]!==i||e[8]!==l||e[9]!==f?(s=(0,t.jsx)("input",{"aria-label":p,className:"h-7 w-12 rounded-md border border-border bg-background text-center font-mono text-xs uppercase outline-none focus-visible:border-ring","data-testid":l,onKeyDown:i,readOnly:!0,value:f}),e[6]=p,e[7]=i,e[8]=l,e[9]=f,e[10]=s):s=e[10];let a;e[11]!==h||e[12]!==s?(a=(0,t.jsxs)("dd",{className:"flex items-center gap-1.5",children:[h,s]}),e[11]=h,e[12]=s,e[13]=a):a=e[13];let d;return e[14]!==c||e[15]!==m||e[16]!==a?(d=(0,t.jsxs)("div",{className:"contents","data-testid":c,children:[m,a]}),e[14]=c,e[15]=m,e[16]=a,e[17]=d):d=e[17],d},"z"),Se=g(n=>{let e=(0,J.c)(85),{initialShardKey:u}=n,r=X(),p;e[0]===Symbol.for("react.memo_cache_sentinel")?(p={},e[0]=p):p=e[0];let A=u??"",x;e[1]!==A?(x={shardKey:A},e[1]=A,e[2]=x):x=e[2];let{data:i,error:c,errorSource:m,isLoading:h}=Z(ee.getSettings,p,x),l,f,s,a,d,o,b;if(e[3]!==c||e[4]!==m||e[5]!==i?.deploy||e[6]!==i?.settings||e[7]!==r){let Q=pe(i?.deploy,r),M;e[15]!==i?.settings?(M=i?.settings??[],e[15]=i?.settings,e[16]=M):M=e[16],l=M,f="flex flex-col gap-4",s="lunora-settings";let V;e[17]!==r?(V=r("Open in Cloudflare"),e[17]=r,e[18]=V):V=e[18],e[19]!==V?(a=(0,t.jsx)("div",{className:"flex flex-wrap items-center gap-3",children:(0,t.jsx)("a",{className:"text-sm text-primary underline-offset-4 hover:underline","data-testid":"set-cf-link",href:de,rel:"noreferrer",target:"_blank",children:V})}),e[19]=V,e[20]=a):a=e[20];let $;e[21]!==r?($=r("View-only \u2014 values are masked. Edit vars, secrets, and bindings in wrangler or the Cloudflare dashboard."),e[21]=r,e[22]=$):$=e[22],e[23]!==$?(d=(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"set-readonly-note",children:$}),e[23]=$,e[24]=d):d=e[24],e[25]!==c||e[26]!==m?(o=c!==null&&(0,t.jsx)(ae,{error:m,testId:"set-error"}),e[25]=c,e[26]=m,e[27]=o):o=e[27],b=Q.length>0&&(0,t.jsxs)(P,{className:"py-0","data-testid":"set-deploy",children:[(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:r("Deployment")})}),(0,t.jsx)(q,{className:"py-3",children:(0,t.jsx)("dl",{className:"grid grid-cols-[8rem_minmax(0,1fr)] gap-x-4 gap-y-1 text-sm",children:Q.map(he)})})]}),e[3]=c,e[4]=m,e[5]=i?.deploy,e[6]=i?.settings,e[7]=r,e[8]=l,e[9]=f,e[10]=s,e[11]=a,e[12]=d,e[13]=o,e[14]=b}else l=e[8],f=e[9],s=e[10],a=e[11],d=e[12],o=e[13],b=e[14];let y;e[28]!==r?(y=r("Keyboard shortcuts"),e[28]=r,e[29]=y):y=e[29];let v;e[30]!==y?(v=(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:y}),e[30]=y,e[31]=v):v=e[31];let N;e[32]!==r?(N=r("Reset"),e[32]=r,e[33]=N):N=e[33];let k;e[34]!==N?(k=(0,t.jsx)("button",{className:"rounded px-1 text-[11px] text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:text-foreground","data-testid":"set-shortcut-reset",onClick:ne,type:"button",children:N}),e[34]=N,e[35]=k):k=e[35];let w;e[36]!==v||e[37]!==k?(w=(0,t.jsxs)("header",{className:"flex items-center justify-between border-b border-border px-4 py-3",children:[v,k]}),e[36]=v,e[37]=k,e[38]=w):w=e[38];let C;e[39]!==r?(C=r("Command palette"),e[39]=r,e[40]=C):C=e[40];let S;e[41]!==C?(S=(0,t.jsx)(ie,{label:C,modifier:"\u2318/Ctrl",name:"palette"}),e[41]=C,e[42]=S):S=e[42];let T;e[43]!==r?(T=r("Operation console"),e[43]=r,e[44]=T):T=e[44];let D;e[45]!==T?(D=(0,t.jsx)(ie,{label:T,modifier:"Ctrl",name:"console"}),e[45]=T,e[46]=D):D=e[46];let _;e[47]!==S||e[48]!==D?(_=(0,t.jsxs)("dl",{className:"grid grid-cols-[10rem_minmax(0,1fr)] items-center gap-x-4 gap-y-2 text-sm",children:[S,D]}),e[47]=S,e[48]=D,e[49]=_):_=e[49];let E;e[50]!==r?(E=r("Stored in this browser. Focus a box and press a key to rebind it."),e[50]=r,e[51]=E):E=e[51];let I;e[52]!==E?(I=(0,t.jsx)("p",{className:"pt-3 text-xs text-muted-foreground",children:E}),e[52]=E,e[53]=I):I=e[53];let K;e[54]!==_||e[55]!==I?(K=(0,t.jsxs)(q,{className:"py-3",children:[_,I]}),e[54]=_,e[55]=I,e[56]=K):K=e[56];let O;e[57]!==w||e[58]!==K?(O=(0,t.jsxs)(P,{className:"py-0","data-testid":"set-preferences",children:[w,K]}),e[57]=w,e[58]=K,e[59]=O):O=e[59];let U;e[60]!==r?(U=r("Environment & bindings"),e[60]=r,e[61]=U):U=e[61];let j;e[62]!==U?(j=(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:U})}),e[62]=U,e[63]=j):j=e[63];let F;e[64]!==c||e[65]!==h||e[66]!==l.length||e[67]!==r?(F=c===null&&!h&&l.length===0&&(0,t.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"set-empty",children:r("No environment variables or bindings.")}),e[64]=c,e[65]=h,e[66]=l.length,e[67]=r,e[68]=F):F=e[68];let L;e[69]!==l||e[70]!==r?(L=l.length>0&&(0,t.jsx)(q,{className:"px-0 py-0",children:(0,t.jsxs)(le,{"data-testid":"set-table",children:[(0,t.jsx)(oe,{children:(0,t.jsxs)(H,{children:[(0,t.jsx)(z,{children:r("name")}),(0,t.jsx)(z,{children:r("kind")}),(0,t.jsx)(z,{children:r("value")})]})}),(0,t.jsx)(se,{children:l.map(fe)})]})}),e[69]=l,e[70]=r,e[71]=L):L=e[71];let R;e[72]!==j||e[73]!==F||e[74]!==L?(R=(0,t.jsxs)(P,{className:"py-0",children:[j,F,L]}),e[72]=j,e[73]=F,e[74]=L,e[75]=R):R=e[75];let B;return e[76]!==O||e[77]!==R||e[78]!==f||e[79]!==s||e[80]!==a||e[81]!==d||e[82]!==o||e[83]!==b?(B=(0,t.jsxs)("div",{className:f,"data-testid":s,children:[a,d,o,b,O,R]}),e[76]=O,e[77]=R,e[78]=f,e[79]=s,e[80]=a,e[81]=d,e[82]=o,e[83]=b,e[84]=B):B=e[84],B},"Ce");function he(n){return(0,t.jsxs)("div",{className:"contents","data-testid":"set-deploy-row",children:[(0,t.jsx)("dt",{className:"text-muted-foreground",children:n.label}),(0,t.jsx)("dd",{className:"truncate font-mono text-xs",title:n.value,children:n.value})]},n.label)}g(he,"me");function fe(n){return(0,t.jsxs)(H,{"data-testid":"set-row",children:[(0,t.jsx)(G,{className:"font-mono text-xs font-medium",children:n.name}),(0,t.jsx)(G,{children:(0,t.jsx)(Y,{variant:ue[n.kind],children:n.bindingType??n.kind})}),(0,t.jsx)(G,{className:"max-w-[28ch] truncate font-mono text-xs text-muted-foreground",children:n.value??(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})})]},n.name)}g(fe,"fe");export{Se as SettingsPanel};
@@ -1 +1 @@
1
- import{a as ke}from"./chunk-EA2JKR5D.js";import{a as A}from"./chunk-IMOHEGMV.js";import{a as Pe}from"./chunk-BOTGXX4H.js";import{a as be}from"./chunk-IABM4BFJ.js";import"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import{P as M}from"./chunk-46ZJ3TM4.js";import"./chunk-4L4WTGN5.js";import{a as T}from"./chunk-EBWXFG4H.js";import"./chunk-TGHH7ZFA.js";import"./chunk-5GFSKIB2.js";import{b as O}from"./chunk-NCCAMFB6.js";import"./chunk-25NFR6EB.js";import{a as ge}from"./chunk-NJSJI7SX.js";import"./chunk-ULIQFBZU.js";import"./chunk-7SPAXZ55.js";import"./chunk-35DM4JJG.js";import{a as Z}from"./chunk-4ZEL6BYL.js";import{c as ae}from"./chunk-6BI6AL3F.js";import{f as oe}from"./chunk-ET6VU4YM.js";import"./chunk-FSRSK4LY.js";import"./chunk-FMRAZ6MD.js";import{a as de}from"./chunk-FKVZRPV5.js";import{a as Ne,b as ve,c as we,d as ce,e as le,f as re}from"./chunk-HEAQVSNS.js";import{a as se,b as pe,c as fe,d as ue,e as ne}from"./chunk-WUWBZPUK.js";import{d as V,f as he,g as xe,h as ye,o as te}from"./chunk-FODLDLE2.js";import{a as d,d as ie,e as _e,f as Fe,g as Te}from"./chunk-YKXDMIHQ.js";var p=ie(_e(),1);var me=ie(Fe(),1);var t=ie(Te(),1);var Ce=["read","insert","update","delete"],Ae=d((e,a)=>({delete:e("Delete"),insert:e("Insert"),read:e("Read"),update:e("Update")})[a],"_e"),Ee=d(e=>{let a=new Set;for(let i of e?.advisories??[])if(i.name==="rls_uncovered_table"){let{table:s}=i.metadata;typeof s=="string"&&s!==""&&a.add(s)}return a},"Ie"),Re=d((e,a,i)=>{let s=new Map,l=d(n=>{let o=s.get(n);if(o!==void 0)return o;let f={cells:{delete:{},insert:{},read:{},update:{}},maskedColumns:new Set,table:n,uncovered:i.has(n)};return s.set(n,f),f},"l");for(let n of e)l(n.table).cells[n.on]={procedure:n.procedure};for(let n of a)l(n.table).maskedColumns.add(n.column);for(let n of i)l(n);return[...s.values()].toSorted((n,o)=>n.table.localeCompare(o.table))},"Ee"),$e=d(e=>{let a=(0,me.c)(17),i;a[0]!==e?(i=e===void 0?{}:e,a[0]=e,a[1]=i):i=a[1];let{onProbe:s}=i,l=V(),n,o;a[2]===Symbol.for("react.memo_cache_sentinel")?(n={},o={live:!0},a[2]=n,a[3]=o):(n=a[2],o=a[3]);let f=ae(Z.rlsPolicies,n,o),r;a[4]===Symbol.for("react.memo_cache_sentinel")?(r={},a[4]=r):r=a[4];let b=ae(Z.maskPolicies,r),x;a[5]===Symbol.for("react.memo_cache_sentinel")?(x={},a[5]=x):x=a[5];let g=ae(Z.getAdvisories,x),N;if(a[6]!==g.data||a[7]!==b.data||a[8]!==s||a[9]!==f||a[10]!==l){let v=null;f.data!==void 0&&(v=Array.isArray(f.data.policies)?f.data.policies:[]);let E=Array.isArray(b.data?.columns)?b.data.columns:[],j=g.data??null,{error:C,errorSource:w,liveError:S}=f,_=v===null?[]:Re(v,E,Ee(j)),k;a[12]!==S?(k=(0,t.jsx)("div",{className:"flex items-center justify-end",children:(0,t.jsx)(Pe,{message:S,prefix:"pm"})}),a[12]=S,a[13]=k):k=a[13];let u;a[14]!==C||a[15]!==w?(u=C!==null&&(0,t.jsx)(ge,{error:w,testId:"pm-error"}),a[14]=C,a[15]=w,a[16]=u):u=a[16],N=(0,t.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-permissions-matrix",children:[k,u,v!==null&&_.length===0?(0,t.jsx)(de,{description:l("Add a `definePolicy` and wire it through `.use(rls(...))` to populate this matrix."),testId:"pm-empty",title:l("No policy")}):(0,t.jsxs)(Ne,{"data-testid":"pm-table",children:[(0,t.jsx)(ve,{children:(0,t.jsxs)(ce,{children:[(0,t.jsx)(le,{children:l("Table")}),Ce.map(c=>(0,t.jsx)(le,{children:Ae(l,c)},c)),(0,t.jsx)(le,{children:l("Masked columns")})]})}),(0,t.jsx)(we,{children:_.map(c=>(0,t.jsxs)(ce,{"data-testid":`pm-row-${c.table}`,children:[(0,t.jsx)(re,{className:"font-mono text-xs",children:(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[c.table,c.uncovered&&(0,t.jsx)(O,{"data-testid":`pm-uncovered-${c.table}`,title:l("Uncovered \u2014 reachable without a policy"),variant:"destructive",children:l("Uncovered \u2014 reachable without a policy")})]})}),Ce.map(I=>{let y=c.cells[I];return(0,t.jsx)(re,{"data-testid":`pm-cell-${c.table}-${I}`,children:y.procedure===void 0?(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:l("No policy")}):(0,t.jsxs)("span",{className:"flex flex-col gap-1",children:[(0,t.jsx)(O,{variant:"secondary",children:l("Covered by {procedure}",{procedure:y.procedure})}),s!==void 0&&(0,t.jsx)(T,{className:"h-auto justify-start p-0 text-[11px]","data-testid":`pm-probe-${c.table}-${I}`,onClick:d(()=>{s(c.table,I,y.procedure??"")},"onClick"),size:"xs",type:"button",variant:"ghost",children:l("Probe this")})]})},I)}),(0,t.jsx)(re,{children:c.maskedColumns.size===0?(0,t.jsx)("span",{"aria-hidden":"true",className:"text-muted-foreground",children:"\u2014"}):(0,t.jsx)("span",{className:"flex flex-wrap gap-1",children:[...c.maskedColumns].map(ze)})})]},c.table))})]})]}),a[6]=g.data,a[7]=b.data,a[8]=s,a[9]=f,a[10]=l,a[11]=N}else N=a[11];return N},"Fe");function ze(e){return(0,t.jsx)(O,{variant:"outline",children:e},e)}d(ze,"Re");var Le=he(Z.runAs),Oe=d(()=>{let e=oe();return async({args:a,functionPath:i,shardKey:s="",userId:l})=>{if(l.trim()==="")return{kind:"invalid",message:"No identity to probe: enter the userId whose access you want to test."};let n=Le;try{return{kind:"allowed",value:await e.query(n,{args:a,functionPath:i,userId:l},xe(s))}}catch(o){return{kind:"denied",message:o instanceof Error?o.message:String(o)}}}},"Le"),je=d(e=>e===void 0?"undefined":JSON.stringify(e,null,2),"Me"),Me=d(({functions:e,prefill:a,runAsIdentity:i=!1}={})=>{let s=oe(),l=V(),n=Oe(),[o,f]=(0,p.useState)(null),[r,b]=(0,p.useState)(null),x=e??o??[],[g,N]=(0,p.useState)(""),[v,E]=(0,p.useState)("{}"),[j,C]=(0,p.useState)(""),[w,S]=(0,p.useState)(""),[_,k]=(0,p.useState)(!1),[u,c]=(0,p.useState)(null),[I,y]=(0,p.useState)(null),F=(0,p.useRef)(-1);(0,p.useEffect)(()=>{if(e!==void 0)return;let m=!1;return s.listFunctions().then(h=>(m||f(h),h)).catch(h=>{m||b(ye(h))}),()=>{m=!0}},[s,e]),(0,p.useEffect)(()=>{if(a===void 0||F.current===a.nonce)return;F.current=a.nonce;let m=a.functionPath;queueMicrotask(()=>{N(m),c(null)})},[a]);let P=g===""?x[0]?.path??"":g,R=d(async()=>{if(P==="")return;let m;try{m=v.trim()===""?{}:JSON.parse(v)}catch(h){y(l("Invalid JSON args: {message}",{message:h.message})),c(null);return}y(null),k(!0);try{let h=await n({args:m,functionPath:P,shardKey:j.trim(),userId:w.trim()});c(h)}finally{k(!1)}},"E"),$=d(()=>{te(R())},"F"),Y=d(m=>{N(m.target.value)},"Y"),z=d(m=>{E(m.target.value)},"R"),L=d(m=>{S(m.target.value)},"O");return(0,t.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-permissions-playground",children:[r!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"pp-discover-error",role:"alert",children:r}),!i&&(0,t.jsx)(de,{description:l("Dev only: runs the selected function as this user over the admin gate so you can test auth and RLS."),testId:"pp-gate",title:l("Set `runAsIdentity` to forge an identity and probe access.")}),(0,t.jsxs)("div",{className:"flex flex-col gap-3 rounded-md border border-border p-3",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(A,{htmlFor:"pp-function",children:l("Function")}),(0,t.jsx)("select",{"aria-label":l("Function"),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","data-testid":"pp-function",id:"pp-function",onChange:Y,value:P,children:x.map(m=>(0,t.jsxs)("option",{value:m.path,children:[m.path," (",m.kind,")"]},m.path))})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(A,{htmlFor:"pp-args",children:l("Arguments")}),(0,t.jsx)(ke,{"aria-label":l("Arguments"),className:"font-mono text-xs","data-testid":"pp-args",id:"pp-args",onChange:z,value:v})]}),(0,t.jsx)(be,{onChange:C,testId:"pp-shard",value:j}),(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(A,{htmlFor:"pp-user",children:l("Run as (userId)")}),(0,t.jsx)(M,{"aria-label":l("Identity (userId) to run as"),className:"font-mono text-xs","data-testid":"pp-user",id:"pp-user",onChange:L,placeholder:l("Required \u2014 the identity to probe as"),value:w})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(T,{"data-testid":"pp-run",disabled:!i||_||P==="",onClick:$,type:"button",children:l(_?"Probing\u2026":"Run probe")}),w.trim()!==""&&(0,t.jsx)(O,{"data-testid":"pp-as-badge",variant:"secondary",children:l("as {userId}",{userId:w.trim()})})]})]}),I!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"pp-args-error",role:"alert",children:I}),u!==null&&u.kind==="allowed"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"pp-outcome-allowed",children:[(0,t.jsx)(O,{variant:"secondary",children:l("Allowed")}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs","data-testid":"pp-result",children:je(u.value)})]}),u!==null&&u.kind==="invalid"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"pp-outcome-invalid",children:[(0,t.jsx)(O,{variant:"outline",children:l("Not run")}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"pp-invalid",role:"status",children:u.message})]}),u!==null&&u.kind==="denied"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"pp-outcome-denied",children:[(0,t.jsx)(O,{variant:"destructive",children:l("Denied")}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs text-destructive","data-testid":"pp-denied",role:"alert",children:u.message})]})]})},"$e"),qe="/__lunora/policy-scaffold",De={"already-wired":"That procedure already has an rls(...) policy wired in.","file-exists":"A policy file with that name already exists \u2014 pick another name or edit it by hand.","invalid-identifier":"Name, table, and policy-set must be plain identifiers (letters, digits, _ or $).","unknown-procedure":"No exported procedure was found at that file path.","unsupported-procedure-shape":"That procedure uses the bare query({\u2026}) form \u2014 convert it to the builder form (c.use(\u2026).query(\u2026)) before wiring RLS."},Ue=d(async e=>{let a=await fetch(qe,{body:JSON.stringify(e),headers:{"Content-Type":"application/json"},method:"POST"}),i=await a.json();if(i.needsManualEdit===!0)return{kind:"needs-manual-edit",message:i.message??"This change must be made by hand."};if(a.ok)return{diagnostics:i.diagnostics??[],kind:"ok",label:i.fileName??i.exportName??""};let s=i.error;return{kind:"error",message:s===void 0?`policy scaffold failed (${String(a.status)})`:De[s]??s}},"Ue"),Se={exportName:"",filePath:"",policyName:"",policies:"",tableName:""},Je=d(()=>{let e=(0,me.c)(69),a=V(),[i,s]=(0,p.useState)(null),[l,n]=(0,p.useState)(!1),[o,f]=(0,p.useState)(null),[r,b]=(0,p.useState)(Se),x;e[0]===Symbol.for("react.memo_cache_sentinel")?(x=d(ee=>{let G=ee.target.name,{value:Q}=ee.target;b(Ie=>({...Ie,[G]:Q}))},"h"),e[0]=x):x=e[0];let g=x,N;e[1]===Symbol.for("react.memo_cache_sentinel")?(N=d(()=>{s(null),b(Se)},"v"),e[1]=N):N=e[1];let v=N,E;e[2]===Symbol.for("react.memo_cache_sentinel")?(E=d(async ee=>{n(!0),f(null);try{let G=await Ue(ee);f(G),G.kind==="ok"&&v()}catch(G){let Q=G;f({kind:"error",message:Q instanceof Error?Q.message:String(Q)})}n(!1)},"I"),e[2]=E):E=e[2];let j=E,C;e[3]!==r.policyName||e[4]!==r.tableName?(C=d(()=>{te(j({kind:"scaffoldPolicy",name:r.policyName.trim(),table:r.tableName.trim()}))},"P"),e[3]=r.policyName,e[4]=r.tableName,e[5]=C):C=e[5];let w=C,S;e[6]!==r.exportName||e[7]!==r.filePath||e[8]!==r.policies?(S=d(()=>{te(j({exportName:r.exportName.trim(),filePath:r.filePath.trim(),kind:"wireRls",policies:r.policies.trim()}))},"w"),e[6]=r.exportName,e[7]=r.filePath,e[8]=r.policies,e[9]=S):S=e[9];let _=S,k;e[10]===Symbol.for("react.memo_cache_sentinel")?(k=d(()=>{f(null),s("scaffold")},"S"),e[10]=k):k=e[10];let u=k,c;e[11]===Symbol.for("react.memo_cache_sentinel")?(c=d(()=>{f(null),s("wire")},"d"),e[11]=c):c=e[11];let I=c,y;e[12]!==a?(y=a("Scaffold access rules"),e[12]=a,e[13]=y):y=e[13];let F;e[14]!==y?(F=(0,t.jsx)(fe,{children:y}),e[14]=y,e[15]=F):F=e[15];let P;e[16]!==a?(P=a("Writes a new deny-by-default policy file under lunora/, or wires one into a procedure, then reruns codegen. Local dev only."),e[16]=a,e[17]=P):P=e[17];let R;e[18]!==P?(R=(0,t.jsx)(ue,{children:P}),e[18]=P,e[19]=R):R=e[19];let $;e[20]!==R||e[21]!==F?($=(0,t.jsxs)(pe,{children:[F,R]}),e[20]=R,e[21]=F,e[22]=$):$=e[22];let Y=i==="scaffold"?"default":"outline",z;e[23]!==a?(z=a("New policy file"),e[23]=a,e[24]=z):z=e[24];let L;e[25]!==Y||e[26]!==z?(L=(0,t.jsx)(T,{"data-testid":"policy-scaffolder-new",onClick:u,size:"xs",type:"button",variant:Y,children:z}),e[25]=Y,e[26]=z,e[27]=L):L=e[27];let m=i==="wire"?"default":"outline",h;e[28]!==a?(h=a("Wire into a procedure"),e[28]=a,e[29]=h):h=e[29];let q;e[30]!==m||e[31]!==h?(q=(0,t.jsx)(T,{"data-testid":"policy-scaffolder-wire",onClick:I,size:"xs",type:"button",variant:m,children:h}),e[30]=m,e[31]=h,e[32]=q):q=e[32];let D;e[33]!==L||e[34]!==q?(D=(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[L,q]}),e[33]=L,e[34]=q,e[35]=D):D=e[35];let U;e[36]!==l||e[37]!==r.policyName||e[38]!==r.tableName||e[39]!==i||e[40]!==w||e[41]!==a?(U=i==="scaffold"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"policy-scaffolder-new-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(A,{htmlFor:"policy-scaffolder-name",children:a("Policy name")}),(0,t.jsx)(M,{"data-testid":"policy-scaffolder-name",id:"policy-scaffolder-name",name:"policyName",onChange:g,value:r.policyName})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(A,{htmlFor:"policy-scaffolder-table",children:a("Table name")}),(0,t.jsx)(M,{"data-testid":"policy-scaffolder-table",id:"policy-scaffolder-table",name:"tableName",onChange:g,value:r.tableName})]}),(0,t.jsx)(T,{"data-testid":"policy-scaffolder-create",disabled:l||r.policyName.trim()===""||r.tableName.trim()==="",onClick:w,size:"xs",type:"button",children:a(l?"Creating\u2026":"Create policy file")}),(0,t.jsx)(T,{onClick:v,size:"xs",type:"button",variant:"ghost",children:a("Cancel")})]}),e[36]=l,e[37]=r.policyName,e[38]=r.tableName,e[39]=i,e[40]=w,e[41]=a,e[42]=U):U=e[42];let J;e[43]!==l||e[44]!==r.exportName||e[45]!==r.filePath||e[46]!==r.policies||e[47]!==i||e[48]!==_||e[49]!==a?(J=i==="wire"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"policy-scaffolder-wire-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(A,{htmlFor:"policy-scaffolder-file",children:a("Procedure file path")}),(0,t.jsx)(M,{"data-testid":"policy-scaffolder-file",id:"policy-scaffolder-file",name:"filePath",onChange:g,value:r.filePath})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(A,{htmlFor:"policy-scaffolder-export",children:a("Exported procedure")}),(0,t.jsx)(M,{"data-testid":"policy-scaffolder-export",id:"policy-scaffolder-export",name:"exportName",onChange:g,value:r.exportName})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(A,{htmlFor:"policy-scaffolder-policies",children:a("Policy set identifier")}),(0,t.jsx)(M,{"data-testid":"policy-scaffolder-policies",id:"policy-scaffolder-policies",name:"policies",onChange:g,value:r.policies})]}),(0,t.jsx)(T,{"data-testid":"policy-scaffolder-apply",disabled:l||r.filePath.trim()===""||r.exportName.trim()===""||r.policies.trim()==="",onClick:_,size:"xs",type:"button",children:a(l?"Wiring\u2026":"Wire RLS")}),(0,t.jsx)(T,{onClick:v,size:"xs",type:"button",variant:"ghost",children:a("Cancel")})]}),e[43]=l,e[44]=r.exportName,e[45]=r.filePath,e[46]=r.policies,e[47]=i,e[48]=_,e[49]=a,e[50]=J):J=e[50];let W;e[51]!==o?(W=o?.kind==="error"&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive","data-testid":"policy-scaffolder-error",role:"alert",children:o.message}),e[51]=o,e[52]=W):W=e[52];let B;e[53]!==o?.kind||e[54]!==a?(B=o?.kind==="needs-manual-edit"&&(0,t.jsx)("p",{className:"mt-3 text-sm text-amber-600 dark:text-amber-500","data-testid":"policy-scaffolder-manual",role:"alert",children:a("This change must be made by hand \u2014 the scaffolder only adds new, deny-by-default rules.")}),e[53]=o?.kind,e[54]=a,e[55]=B):B=e[55];let H;e[56]!==o||e[57]!==a?(H=o?.kind==="ok"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-col gap-1","data-testid":"policy-scaffolder-ok",children:[(0,t.jsx)("p",{className:"text-sm text-emerald-600 dark:text-emerald-500",children:a("Scaffolded {label} and reran codegen. Fill in the `when` predicates before relying on it.",{label:o.label})}),o.diagnostics.length>0&&(0,t.jsx)("ul",{className:"flex flex-col gap-0.5","data-testid":"policy-scaffolder-diagnostics",children:o.diagnostics.map(We)})]}),e[56]=o,e[57]=a,e[58]=H):H=e[58];let K;e[59]!==D||e[60]!==U||e[61]!==J||e[62]!==W||e[63]!==B||e[64]!==H?(K=(0,t.jsxs)(ne,{children:[D,U,J,W,B,H]}),e[59]=D,e[60]=U,e[61]=J,e[62]=W,e[63]=B,e[64]=H,e[65]=K):K=e[65];let X;return e[66]!==$||e[67]!==K?(X=(0,t.jsxs)(se,{"data-testid":"policy-scaffolder",size:"sm",children:[$,K]}),e[66]=$,e[67]=K,e[68]=X):X=e[68],X},"je");function We(e){return(0,t.jsx)("li",{className:"font-mono text-[11px] text-destructive",children:e},e)}d(We,"Be");var st=d(({functions:e,runAsIdentity:a=!1,schemaEditable:i=!1}={})=>{let s=V(),[l,n]=(0,p.useState)(void 0),o=d((f,r,b)=>{b!==""&&n(x=>({functionPath:b,nonce:(x?.nonce??0)+1}))},"o");return(0,t.jsxs)("div",{className:"flex flex-col gap-8","data-testid":"lunora-permissions",children:[(0,t.jsxs)("section",{className:"flex flex-col gap-3",children:[(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:s("Permissions")})}),(0,t.jsx)($e,{onProbe:o})]}),(0,t.jsx)("section",{className:"flex flex-col gap-3",children:(0,t.jsxs)(se,{className:"gap-0 py-0",children:[(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:s("Probe")})}),(0,t.jsxs)(ne,{className:"px-4 py-4",children:[(0,t.jsx)("p",{className:"mb-3 text-sm text-muted-foreground",children:s("Pick a function and an identity, then run it to see the access outcome.")}),(0,t.jsx)(Me,{functions:e,prefill:l,runAsIdentity:a})]})]})}),i&&(0,t.jsx)("section",{className:"flex flex-col gap-2",children:(0,t.jsx)(Je,{})})]})},"nt");export{st as PermissionsPanel};
1
+ import{a as ke}from"./chunk-EA2JKR5D.js";import{a as A}from"./chunk-IMOHEGMV.js";import{a as Pe}from"./chunk-BOTGXX4H.js";import{a as be}from"./chunk-IABM4BFJ.js";import"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import{P as M}from"./chunk-46ZJ3TM4.js";import"./chunk-4L4WTGN5.js";import{a as T}from"./chunk-EBWXFG4H.js";import"./chunk-TGHH7ZFA.js";import"./chunk-5GFSKIB2.js";import{b as O}from"./chunk-NCCAMFB6.js";import"./chunk-25NFR6EB.js";import{a as ge}from"./chunk-EESOT5SI.js";import"./chunk-ULIQFBZU.js";import"./chunk-MQ42VLOS.js";import"./chunk-35DM4JJG.js";import{a as Z}from"./chunk-4ZEL6BYL.js";import{c as ae}from"./chunk-6XDE6XBT.js";import{f as oe}from"./chunk-4U4NQF6Z.js";import"./chunk-FSRSK4LY.js";import"./chunk-RZNN2EJU.js";import{a as de}from"./chunk-FKVZRPV5.js";import{a as Ne,b as ve,c as we,d as ce,e as le,f as re}from"./chunk-HEAQVSNS.js";import{a as se,b as pe,c as fe,d as ue,e as ne}from"./chunk-WUWBZPUK.js";import{d as V,f as he,g as xe,h as ye,o as te}from"./chunk-FODLDLE2.js";import{a as d,d as ie,e as _e,f as Fe,g as Te}from"./chunk-YKXDMIHQ.js";var p=ie(_e(),1);var me=ie(Fe(),1);var t=ie(Te(),1);var Ce=["read","insert","update","delete"],Ae=d((e,a)=>({delete:e("Delete"),insert:e("Insert"),read:e("Read"),update:e("Update")})[a],"_e"),Ee=d(e=>{let a=new Set;for(let i of e?.advisories??[])if(i.name==="rls_uncovered_table"){let{table:s}=i.metadata;typeof s=="string"&&s!==""&&a.add(s)}return a},"Ie"),Re=d((e,a,i)=>{let s=new Map,l=d(n=>{let o=s.get(n);if(o!==void 0)return o;let f={cells:{delete:{},insert:{},read:{},update:{}},maskedColumns:new Set,table:n,uncovered:i.has(n)};return s.set(n,f),f},"l");for(let n of e)l(n.table).cells[n.on]={procedure:n.procedure};for(let n of a)l(n.table).maskedColumns.add(n.column);for(let n of i)l(n);return[...s.values()].toSorted((n,o)=>n.table.localeCompare(o.table))},"Ee"),$e=d(e=>{let a=(0,me.c)(17),i;a[0]!==e?(i=e===void 0?{}:e,a[0]=e,a[1]=i):i=a[1];let{onProbe:s}=i,l=V(),n,o;a[2]===Symbol.for("react.memo_cache_sentinel")?(n={},o={live:!0},a[2]=n,a[3]=o):(n=a[2],o=a[3]);let f=ae(Z.rlsPolicies,n,o),r;a[4]===Symbol.for("react.memo_cache_sentinel")?(r={},a[4]=r):r=a[4];let b=ae(Z.maskPolicies,r),x;a[5]===Symbol.for("react.memo_cache_sentinel")?(x={},a[5]=x):x=a[5];let g=ae(Z.getAdvisories,x),N;if(a[6]!==g.data||a[7]!==b.data||a[8]!==s||a[9]!==f||a[10]!==l){let v=null;f.data!==void 0&&(v=Array.isArray(f.data.policies)?f.data.policies:[]);let E=Array.isArray(b.data?.columns)?b.data.columns:[],j=g.data??null,{error:C,errorSource:w,liveError:S}=f,_=v===null?[]:Re(v,E,Ee(j)),k;a[12]!==S?(k=(0,t.jsx)("div",{className:"flex items-center justify-end",children:(0,t.jsx)(Pe,{message:S,prefix:"pm"})}),a[12]=S,a[13]=k):k=a[13];let u;a[14]!==C||a[15]!==w?(u=C!==null&&(0,t.jsx)(ge,{error:w,testId:"pm-error"}),a[14]=C,a[15]=w,a[16]=u):u=a[16],N=(0,t.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-permissions-matrix",children:[k,u,v!==null&&_.length===0?(0,t.jsx)(de,{description:l("Add a `definePolicy` and wire it through `.use(rls(...))` to populate this matrix."),testId:"pm-empty",title:l("No policy")}):(0,t.jsxs)(Ne,{"data-testid":"pm-table",children:[(0,t.jsx)(ve,{children:(0,t.jsxs)(ce,{children:[(0,t.jsx)(le,{children:l("Table")}),Ce.map(c=>(0,t.jsx)(le,{children:Ae(l,c)},c)),(0,t.jsx)(le,{children:l("Masked columns")})]})}),(0,t.jsx)(we,{children:_.map(c=>(0,t.jsxs)(ce,{"data-testid":`pm-row-${c.table}`,children:[(0,t.jsx)(re,{className:"font-mono text-xs",children:(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[c.table,c.uncovered&&(0,t.jsx)(O,{"data-testid":`pm-uncovered-${c.table}`,title:l("Uncovered \u2014 reachable without a policy"),variant:"destructive",children:l("Uncovered \u2014 reachable without a policy")})]})}),Ce.map(I=>{let y=c.cells[I];return(0,t.jsx)(re,{"data-testid":`pm-cell-${c.table}-${I}`,children:y.procedure===void 0?(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:l("No policy")}):(0,t.jsxs)("span",{className:"flex flex-col gap-1",children:[(0,t.jsx)(O,{variant:"secondary",children:l("Covered by {procedure}",{procedure:y.procedure})}),s!==void 0&&(0,t.jsx)(T,{className:"h-auto justify-start p-0 text-[11px]","data-testid":`pm-probe-${c.table}-${I}`,onClick:d(()=>{s(c.table,I,y.procedure??"")},"onClick"),size:"xs",type:"button",variant:"ghost",children:l("Probe this")})]})},I)}),(0,t.jsx)(re,{children:c.maskedColumns.size===0?(0,t.jsx)("span",{"aria-hidden":"true",className:"text-muted-foreground",children:"\u2014"}):(0,t.jsx)("span",{className:"flex flex-wrap gap-1",children:[...c.maskedColumns].map(ze)})})]},c.table))})]})]}),a[6]=g.data,a[7]=b.data,a[8]=s,a[9]=f,a[10]=l,a[11]=N}else N=a[11];return N},"Fe");function ze(e){return(0,t.jsx)(O,{variant:"outline",children:e},e)}d(ze,"Re");var Le=he(Z.runAs),Oe=d(()=>{let e=oe();return async({args:a,functionPath:i,shardKey:s="",userId:l})=>{if(l.trim()==="")return{kind:"invalid",message:"No identity to probe: enter the userId whose access you want to test."};let n=Le;try{return{kind:"allowed",value:await e.query(n,{args:a,functionPath:i,userId:l},xe(s))}}catch(o){return{kind:"denied",message:o instanceof Error?o.message:String(o)}}}},"Le"),je=d(e=>e===void 0?"undefined":JSON.stringify(e,null,2),"Me"),Me=d(({functions:e,prefill:a,runAsIdentity:i=!1}={})=>{let s=oe(),l=V(),n=Oe(),[o,f]=(0,p.useState)(null),[r,b]=(0,p.useState)(null),x=e??o??[],[g,N]=(0,p.useState)(""),[v,E]=(0,p.useState)("{}"),[j,C]=(0,p.useState)(""),[w,S]=(0,p.useState)(""),[_,k]=(0,p.useState)(!1),[u,c]=(0,p.useState)(null),[I,y]=(0,p.useState)(null),F=(0,p.useRef)(-1);(0,p.useEffect)(()=>{if(e!==void 0)return;let m=!1;return s.listFunctions().then(h=>(m||f(h),h)).catch(h=>{m||b(ye(h))}),()=>{m=!0}},[s,e]),(0,p.useEffect)(()=>{if(a===void 0||F.current===a.nonce)return;F.current=a.nonce;let m=a.functionPath;queueMicrotask(()=>{N(m),c(null)})},[a]);let P=g===""?x[0]?.path??"":g,R=d(async()=>{if(P==="")return;let m;try{m=v.trim()===""?{}:JSON.parse(v)}catch(h){y(l("Invalid JSON args: {message}",{message:h.message})),c(null);return}y(null),k(!0);try{let h=await n({args:m,functionPath:P,shardKey:j.trim(),userId:w.trim()});c(h)}finally{k(!1)}},"E"),$=d(()=>{te(R())},"F"),Y=d(m=>{N(m.target.value)},"Y"),z=d(m=>{E(m.target.value)},"R"),L=d(m=>{S(m.target.value)},"O");return(0,t.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-permissions-playground",children:[r!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"pp-discover-error",role:"alert",children:r}),!i&&(0,t.jsx)(de,{description:l("Dev only: runs the selected function as this user over the admin gate so you can test auth and RLS."),testId:"pp-gate",title:l("Set `runAsIdentity` to forge an identity and probe access.")}),(0,t.jsxs)("div",{className:"flex flex-col gap-3 rounded-md border border-border p-3",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(A,{htmlFor:"pp-function",children:l("Function")}),(0,t.jsx)("select",{"aria-label":l("Function"),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","data-testid":"pp-function",id:"pp-function",onChange:Y,value:P,children:x.map(m=>(0,t.jsxs)("option",{value:m.path,children:[m.path," (",m.kind,")"]},m.path))})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(A,{htmlFor:"pp-args",children:l("Arguments")}),(0,t.jsx)(ke,{"aria-label":l("Arguments"),className:"font-mono text-xs","data-testid":"pp-args",id:"pp-args",onChange:z,value:v})]}),(0,t.jsx)(be,{onChange:C,testId:"pp-shard",value:j}),(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(A,{htmlFor:"pp-user",children:l("Run as (userId)")}),(0,t.jsx)(M,{"aria-label":l("Identity (userId) to run as"),className:"font-mono text-xs","data-testid":"pp-user",id:"pp-user",onChange:L,placeholder:l("Required \u2014 the identity to probe as"),value:w})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(T,{"data-testid":"pp-run",disabled:!i||_||P==="",onClick:$,type:"button",children:l(_?"Probing\u2026":"Run probe")}),w.trim()!==""&&(0,t.jsx)(O,{"data-testid":"pp-as-badge",variant:"secondary",children:l("as {userId}",{userId:w.trim()})})]})]}),I!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"pp-args-error",role:"alert",children:I}),u!==null&&u.kind==="allowed"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"pp-outcome-allowed",children:[(0,t.jsx)(O,{variant:"secondary",children:l("Allowed")}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs","data-testid":"pp-result",children:je(u.value)})]}),u!==null&&u.kind==="invalid"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"pp-outcome-invalid",children:[(0,t.jsx)(O,{variant:"outline",children:l("Not run")}),(0,t.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"pp-invalid",role:"status",children:u.message})]}),u!==null&&u.kind==="denied"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"pp-outcome-denied",children:[(0,t.jsx)(O,{variant:"destructive",children:l("Denied")}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs text-destructive","data-testid":"pp-denied",role:"alert",children:u.message})]})]})},"$e"),qe="/__lunora/policy-scaffold",De={"already-wired":"That procedure already has an rls(...) policy wired in.","file-exists":"A policy file with that name already exists \u2014 pick another name or edit it by hand.","invalid-identifier":"Name, table, and policy-set must be plain identifiers (letters, digits, _ or $).","unknown-procedure":"No exported procedure was found at that file path.","unsupported-procedure-shape":"That procedure uses the bare query({\u2026}) form \u2014 convert it to the builder form (c.use(\u2026).query(\u2026)) before wiring RLS."},Ue=d(async e=>{let a=await fetch(qe,{body:JSON.stringify(e),headers:{"Content-Type":"application/json"},method:"POST"}),i=await a.json();if(i.needsManualEdit===!0)return{kind:"needs-manual-edit",message:i.message??"This change must be made by hand."};if(a.ok)return{diagnostics:i.diagnostics??[],kind:"ok",label:i.fileName??i.exportName??""};let s=i.error;return{kind:"error",message:s===void 0?`policy scaffold failed (${String(a.status)})`:De[s]??s}},"Ue"),Se={exportName:"",filePath:"",policyName:"",policies:"",tableName:""},Je=d(()=>{let e=(0,me.c)(69),a=V(),[i,s]=(0,p.useState)(null),[l,n]=(0,p.useState)(!1),[o,f]=(0,p.useState)(null),[r,b]=(0,p.useState)(Se),x;e[0]===Symbol.for("react.memo_cache_sentinel")?(x=d(ee=>{let G=ee.target.name,{value:Q}=ee.target;b(Ie=>({...Ie,[G]:Q}))},"h"),e[0]=x):x=e[0];let g=x,N;e[1]===Symbol.for("react.memo_cache_sentinel")?(N=d(()=>{s(null),b(Se)},"v"),e[1]=N):N=e[1];let v=N,E;e[2]===Symbol.for("react.memo_cache_sentinel")?(E=d(async ee=>{n(!0),f(null);try{let G=await Ue(ee);f(G),G.kind==="ok"&&v()}catch(G){let Q=G;f({kind:"error",message:Q instanceof Error?Q.message:String(Q)})}n(!1)},"I"),e[2]=E):E=e[2];let j=E,C;e[3]!==r.policyName||e[4]!==r.tableName?(C=d(()=>{te(j({kind:"scaffoldPolicy",name:r.policyName.trim(),table:r.tableName.trim()}))},"P"),e[3]=r.policyName,e[4]=r.tableName,e[5]=C):C=e[5];let w=C,S;e[6]!==r.exportName||e[7]!==r.filePath||e[8]!==r.policies?(S=d(()=>{te(j({exportName:r.exportName.trim(),filePath:r.filePath.trim(),kind:"wireRls",policies:r.policies.trim()}))},"w"),e[6]=r.exportName,e[7]=r.filePath,e[8]=r.policies,e[9]=S):S=e[9];let _=S,k;e[10]===Symbol.for("react.memo_cache_sentinel")?(k=d(()=>{f(null),s("scaffold")},"S"),e[10]=k):k=e[10];let u=k,c;e[11]===Symbol.for("react.memo_cache_sentinel")?(c=d(()=>{f(null),s("wire")},"d"),e[11]=c):c=e[11];let I=c,y;e[12]!==a?(y=a("Scaffold access rules"),e[12]=a,e[13]=y):y=e[13];let F;e[14]!==y?(F=(0,t.jsx)(fe,{children:y}),e[14]=y,e[15]=F):F=e[15];let P;e[16]!==a?(P=a("Writes a new deny-by-default policy file under lunora/, or wires one into a procedure, then reruns codegen. Local dev only."),e[16]=a,e[17]=P):P=e[17];let R;e[18]!==P?(R=(0,t.jsx)(ue,{children:P}),e[18]=P,e[19]=R):R=e[19];let $;e[20]!==R||e[21]!==F?($=(0,t.jsxs)(pe,{children:[F,R]}),e[20]=R,e[21]=F,e[22]=$):$=e[22];let Y=i==="scaffold"?"default":"outline",z;e[23]!==a?(z=a("New policy file"),e[23]=a,e[24]=z):z=e[24];let L;e[25]!==Y||e[26]!==z?(L=(0,t.jsx)(T,{"data-testid":"policy-scaffolder-new",onClick:u,size:"xs",type:"button",variant:Y,children:z}),e[25]=Y,e[26]=z,e[27]=L):L=e[27];let m=i==="wire"?"default":"outline",h;e[28]!==a?(h=a("Wire into a procedure"),e[28]=a,e[29]=h):h=e[29];let q;e[30]!==m||e[31]!==h?(q=(0,t.jsx)(T,{"data-testid":"policy-scaffolder-wire",onClick:I,size:"xs",type:"button",variant:m,children:h}),e[30]=m,e[31]=h,e[32]=q):q=e[32];let D;e[33]!==L||e[34]!==q?(D=(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[L,q]}),e[33]=L,e[34]=q,e[35]=D):D=e[35];let U;e[36]!==l||e[37]!==r.policyName||e[38]!==r.tableName||e[39]!==i||e[40]!==w||e[41]!==a?(U=i==="scaffold"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"policy-scaffolder-new-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(A,{htmlFor:"policy-scaffolder-name",children:a("Policy name")}),(0,t.jsx)(M,{"data-testid":"policy-scaffolder-name",id:"policy-scaffolder-name",name:"policyName",onChange:g,value:r.policyName})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(A,{htmlFor:"policy-scaffolder-table",children:a("Table name")}),(0,t.jsx)(M,{"data-testid":"policy-scaffolder-table",id:"policy-scaffolder-table",name:"tableName",onChange:g,value:r.tableName})]}),(0,t.jsx)(T,{"data-testid":"policy-scaffolder-create",disabled:l||r.policyName.trim()===""||r.tableName.trim()==="",onClick:w,size:"xs",type:"button",children:a(l?"Creating\u2026":"Create policy file")}),(0,t.jsx)(T,{onClick:v,size:"xs",type:"button",variant:"ghost",children:a("Cancel")})]}),e[36]=l,e[37]=r.policyName,e[38]=r.tableName,e[39]=i,e[40]=w,e[41]=a,e[42]=U):U=e[42];let J;e[43]!==l||e[44]!==r.exportName||e[45]!==r.filePath||e[46]!==r.policies||e[47]!==i||e[48]!==_||e[49]!==a?(J=i==="wire"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"policy-scaffolder-wire-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(A,{htmlFor:"policy-scaffolder-file",children:a("Procedure file path")}),(0,t.jsx)(M,{"data-testid":"policy-scaffolder-file",id:"policy-scaffolder-file",name:"filePath",onChange:g,value:r.filePath})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(A,{htmlFor:"policy-scaffolder-export",children:a("Exported procedure")}),(0,t.jsx)(M,{"data-testid":"policy-scaffolder-export",id:"policy-scaffolder-export",name:"exportName",onChange:g,value:r.exportName})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(A,{htmlFor:"policy-scaffolder-policies",children:a("Policy set identifier")}),(0,t.jsx)(M,{"data-testid":"policy-scaffolder-policies",id:"policy-scaffolder-policies",name:"policies",onChange:g,value:r.policies})]}),(0,t.jsx)(T,{"data-testid":"policy-scaffolder-apply",disabled:l||r.filePath.trim()===""||r.exportName.trim()===""||r.policies.trim()==="",onClick:_,size:"xs",type:"button",children:a(l?"Wiring\u2026":"Wire RLS")}),(0,t.jsx)(T,{onClick:v,size:"xs",type:"button",variant:"ghost",children:a("Cancel")})]}),e[43]=l,e[44]=r.exportName,e[45]=r.filePath,e[46]=r.policies,e[47]=i,e[48]=_,e[49]=a,e[50]=J):J=e[50];let W;e[51]!==o?(W=o?.kind==="error"&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive","data-testid":"policy-scaffolder-error",role:"alert",children:o.message}),e[51]=o,e[52]=W):W=e[52];let B;e[53]!==o?.kind||e[54]!==a?(B=o?.kind==="needs-manual-edit"&&(0,t.jsx)("p",{className:"mt-3 text-sm text-amber-600 dark:text-amber-500","data-testid":"policy-scaffolder-manual",role:"alert",children:a("This change must be made by hand \u2014 the scaffolder only adds new, deny-by-default rules.")}),e[53]=o?.kind,e[54]=a,e[55]=B):B=e[55];let H;e[56]!==o||e[57]!==a?(H=o?.kind==="ok"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-col gap-1","data-testid":"policy-scaffolder-ok",children:[(0,t.jsx)("p",{className:"text-sm text-emerald-600 dark:text-emerald-500",children:a("Scaffolded {label} and reran codegen. Fill in the `when` predicates before relying on it.",{label:o.label})}),o.diagnostics.length>0&&(0,t.jsx)("ul",{className:"flex flex-col gap-0.5","data-testid":"policy-scaffolder-diagnostics",children:o.diagnostics.map(We)})]}),e[56]=o,e[57]=a,e[58]=H):H=e[58];let K;e[59]!==D||e[60]!==U||e[61]!==J||e[62]!==W||e[63]!==B||e[64]!==H?(K=(0,t.jsxs)(ne,{children:[D,U,J,W,B,H]}),e[59]=D,e[60]=U,e[61]=J,e[62]=W,e[63]=B,e[64]=H,e[65]=K):K=e[65];let X;return e[66]!==$||e[67]!==K?(X=(0,t.jsxs)(se,{"data-testid":"policy-scaffolder",size:"sm",children:[$,K]}),e[66]=$,e[67]=K,e[68]=X):X=e[68],X},"je");function We(e){return(0,t.jsx)("li",{className:"font-mono text-[11px] text-destructive",children:e},e)}d(We,"Be");var st=d(({functions:e,runAsIdentity:a=!1,schemaEditable:i=!1}={})=>{let s=V(),[l,n]=(0,p.useState)(void 0),o=d((f,r,b)=>{b!==""&&n(x=>({functionPath:b,nonce:(x?.nonce??0)+1}))},"o");return(0,t.jsxs)("div",{className:"flex flex-col gap-8","data-testid":"lunora-permissions",children:[(0,t.jsxs)("section",{className:"flex flex-col gap-3",children:[(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:s("Permissions")})}),(0,t.jsx)($e,{onProbe:o})]}),(0,t.jsx)("section",{className:"flex flex-col gap-3",children:(0,t.jsxs)(se,{className:"gap-0 py-0",children:[(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:s("Probe")})}),(0,t.jsxs)(ne,{className:"px-4 py-4",children:[(0,t.jsx)("p",{className:"mb-3 text-sm text-muted-foreground",children:s("Pick a function and an identity, then run it to see the access outcome.")}),(0,t.jsx)(Me,{functions:e,prefill:l,runAsIdentity:a})]})]})}),i&&(0,t.jsx)("section",{className:"flex flex-col gap-2",children:(0,t.jsx)(Je,{})})]})},"nt");export{st as PermissionsPanel};