@lunora/studio 1.0.0-alpha.91 → 1.0.0-alpha.93
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/packem_chunks/TableEditor.js +1 -1
- package/dist/packem_chunks/payments-panel.js +1 -1
- package/dist/packem_shared/{DataBrowser-BPRDaOHx.js → DataBrowser-H4oUFkPJ.js} +1 -1
- package/dist/packem_shared/wire-codec-DkrdsFXO.js +1 -0
- package/dist/standalone/{chunk-ZNMZQXWN.js → chunk-2O65JEMI.js} +1 -1
- package/dist/standalone/{chunk-RKGCSNAW.js → chunk-2OUIHY7G.js} +1 -1
- package/dist/standalone/{chunk-BCGEI67L.js → chunk-2T22UR7E.js} +1 -1
- package/dist/standalone/{chunk-WOEGO5M6.js → chunk-3DJ3IUUG.js} +1 -1
- package/dist/standalone/{chunk-QZGTDXV5.js → chunk-3KXDX76D.js} +1 -1
- package/dist/standalone/{chunk-ZKTWHB7Q.js → chunk-465RIA2L.js} +1 -1
- package/dist/standalone/chunk-5KCULF7S.js +11 -0
- package/dist/standalone/{chunk-J3FR2XBV.js → chunk-5TDGHWYU.js} +1 -1
- package/dist/standalone/{chunk-7QMX3D4D.js → chunk-6K46XGR5.js} +1 -1
- package/dist/standalone/{chunk-RHPP74O4.js → chunk-7ONX5YGW.js} +1 -1
- package/dist/standalone/{chunk-CRHCAN4W.js → chunk-7YJNH3RB.js} +1 -1
- package/dist/standalone/{chunk-ESEEVSPC.js → chunk-A3DBEJLO.js} +1 -1
- package/dist/standalone/{chunk-3XQMTTW2.js → chunk-ABYJC3LS.js} +1 -1
- package/dist/standalone/{chunk-6WWX4FJB.js → chunk-AQ4JNJF3.js} +1 -1
- package/dist/standalone/{chunk-XGMZESWC.js → chunk-BN4CIAXU.js} +1 -1
- package/dist/standalone/{chunk-XDEDCAYN.js → chunk-BNAMPDZ2.js} +1 -1
- package/dist/standalone/{chunk-XKKP2VFZ.js → chunk-D62SDRMM.js} +1 -1
- package/dist/standalone/{chunk-FBNRATNR.js → chunk-DBMFI2HC.js} +1 -1
- package/dist/standalone/{chunk-Q4AI6JRP.js → chunk-DMJDUC4L.js} +1 -1
- package/dist/standalone/{chunk-2QWHVQ6P.js → chunk-DYMO6MDG.js} +1 -1
- package/dist/standalone/{chunk-C6GLTSPO.js → chunk-G6GX5TVB.js} +1 -1
- package/dist/standalone/{chunk-4VEAVSAZ.js → chunk-GZMKPBTJ.js} +1 -1
- package/dist/standalone/{chunk-N233NOIN.js → chunk-JEZDJ7D6.js} +1 -1
- package/dist/standalone/{chunk-ZWSTXAG3.js → chunk-JYLYJT27.js} +1 -1
- package/dist/standalone/{chunk-2NX5QU44.js → chunk-KEVIGWKP.js} +1 -1
- package/dist/standalone/{chunk-ML5IJMH6.js → chunk-LZKU262J.js} +1 -1
- package/dist/standalone/{chunk-6XKVQES4.js → chunk-M7AWSDGY.js} +1 -1
- package/dist/standalone/chunk-MLT5MMMY.js +1 -0
- package/dist/standalone/{chunk-F3TP5L34.js → chunk-NNKN2XEZ.js} +1 -1
- package/dist/standalone/{chunk-NH3VWHCL.js → chunk-O3UMJLO3.js} +1 -1
- package/dist/standalone/{chunk-CUAGAM2B.js → chunk-OM36OEHZ.js} +1 -1
- package/dist/standalone/{chunk-BYIS2KWZ.js → chunk-PE7TI4TQ.js} +1 -1
- package/dist/standalone/{chunk-O2QUUHGF.js → chunk-PGVJE5F5.js} +1 -1
- package/dist/standalone/{chunk-IZ3ISXSM.js → chunk-QM4EXWKF.js} +1 -1
- package/dist/standalone/{chunk-QGA2HITH.js → chunk-QNHU4SKL.js} +1 -1
- package/dist/standalone/{chunk-LDYOCGEG.js → chunk-QXECM52Z.js} +1 -1
- package/dist/standalone/{chunk-LYQY7L72.js → chunk-SCKKQIAE.js} +1 -1
- package/dist/standalone/{chunk-6QKJ6JPJ.js → chunk-SKYFKPJC.js} +1 -1
- package/dist/standalone/{chunk-HKG5I64M.js → chunk-TITX6XEA.js} +1 -1
- package/dist/standalone/{chunk-CMP33R3N.js → chunk-TMNKNTC4.js} +1 -1
- package/dist/standalone/{chunk-NNRFDPSD.js → chunk-U6KDYJJC.js} +1 -1
- package/dist/standalone/{chunk-LUU4SDHW.js → chunk-UBIPFCOZ.js} +1 -1
- package/dist/standalone/{chunk-A7647FJE.js → chunk-UGU5GYDV.js} +1 -1
- package/dist/standalone/{chunk-QWJ4HKPY.js → chunk-UIGAA3GV.js} +1 -1
- package/dist/standalone/{chunk-4PLB4ZNI.js → chunk-VNQB6HY4.js} +1 -1
- package/dist/standalone/{chunk-AQT6EPZT.js → chunk-VVNQP4CI.js} +1 -1
- package/dist/standalone/{chunk-KUFAOKU3.js → chunk-WI4XINU2.js} +1 -1
- package/dist/standalone/{chunk-XXXMUP6L.js → chunk-YD5O2NWK.js} +1 -1
- package/dist/standalone/{chunk-ULYM26IH.js → chunk-YTWBHPAT.js} +1 -1
- package/dist/standalone/{chunk-7YXDJXNL.js → chunk-Z4AX76YZ.js} +1 -1
- package/dist/standalone/{chunk-LZH7RDRV.js → chunk-ZA5YIHZM.js} +1 -1
- package/dist/standalone/{chunk-4D7XIQ5Q.js → chunk-ZNAGZU6H.js} +1 -1
- package/dist/standalone/{chunk-XTEWLG3J.js → chunk-ZQPWVALL.js} +1 -1
- package/dist/standalone/{chunk-HWOD25QD.js → chunk-ZVAGD3FT.js} +1 -1
- package/dist/standalone/chunk-ZZJ7VUVZ.js +1 -0
- package/dist/standalone/studio.js +1 -1
- package/package.json +6 -6
- package/dist/packem_shared/wire-codec-BUrWLklj.js +0 -1
- package/dist/standalone/chunk-BENJFRZL.js +0 -1
- package/dist/standalone/chunk-DBWOWJYT.js +0 -11
- package/dist/standalone/chunk-FW75RYZU.js +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as fe}from"./chunk-LEDWUPXM.js";import"./chunk-2PJNAWB3.js";import{a as ie}from"./chunk-IC4L6G56.js";import{a as pe}from"./chunk-54MMVNPT.js";import"./chunk-BGBLQ563.js";import{R as de}from"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import{c as x}from"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import{b as ne}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as he}from"./chunk-
|
|
1
|
+
import{a as fe}from"./chunk-LEDWUPXM.js";import"./chunk-2PJNAWB3.js";import{a as ie}from"./chunk-IC4L6G56.js";import{a as pe}from"./chunk-54MMVNPT.js";import"./chunk-BGBLQ563.js";import{R as de}from"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import{c as x}from"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import{b as ne}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as he}from"./chunk-465RIA2L.js";import"./chunk-XXQUMVWH.js";import"./chunk-O3UMJLO3.js";import"./chunk-QLQADHFE.js";import{a as I}from"./chunk-VDW32UET.js";import{c as ue}from"./chunk-ZNAGZU6H.js";import{f as le}from"./chunk-5KCULF7S.js";import"./chunk-XBDKZZ67.js";import{a as ce}from"./chunk-XQCVZAGU.js";import{d as oe,f as Z,g as ee,h as te,o as ae,q as me,r as re}from"./chunk-IUYFXK4X.js";import"./chunk-XNGYYOLS.js";import{a as i,e as Y,f as ge,g as ve,h as Ne,j as se}from"./chunk-3XIESWL4.js";var t=Y(Ne(),1);var xe=Y(ve(),1);var N=Y(ge(),1);function ye({className:a,orientation:e="horizontal",...s}){return(0,t.jsx)(ie,{"data-slot":"separator",orientation:e,className:se("shrink-0 bg-border data-horizontal:h-px data-horizontal:w-full data-vertical:w-px data-vertical:self-stretch",a),...s})}i(ye,"xe");var we=/https?:\/\/[^\s"'<>)]+/i,be=i(a=>a===void 0?void 0:we.exec(a)?.[0],"ae"),y=i(a=>a===void 0?"":Array.isArray(a)?a.join(", "):a,"N"),Ce=i(a=>{if(a!==void 0)return be(a.html)??be(a.text)},"Ne"),ke=i((a,e)=>{let s=e.trim().toLowerCase();return s===""?a:a.filter(o=>`${o.subject} ${y(o.to)} ${y(o.cc)}`.toLowerCase().includes(s))},"ye"),Se=i((a,e)=>{if(a.length!==0)return a.find(s=>s.id===e)??a[0]},"we"),Te=Z(I.clearCapturedMail),Le=Z(I.sendTestMail),je=i(a=>{let e=(0,xe.c)(38),{limit:s}=a,o=le(),p;e[0]!==s?(p={limit:s},e[0]=s,e[1]=p):p=e[1];let{data:P,error:w,errorSource:C,isLoading:g,refetch:n}=ue(I.getCapturedMail,p),[k,f]=(0,N.useState)(null),[D,S]=(0,N.useState)(null),[v,l]=(0,N.useState)("html"),[c,W]=(0,N.useState)(""),b=P?.entries??[],r=w??k,u=w===null?k:C,T;e[2]!==o||e[3]!==n?(T=i(async()=>{f(null);try{await o.query(Te,{},ee("")),S(null),n()}catch(m){f(te(m))}},"S"),e[2]=o,e[3]=n,e[4]=T):T=e[4];let B=T,L;e[5]!==o||e[6]!==n?(L=i(async()=>{f(null);try{await o.query(Le,{},ee("")),n()}catch(m){f(te(m))}},"$"),e[5]=o,e[6]=n,e[7]=L):L=e[7];let R=L,j;e[8]!==n?(j=i(()=>{n()},"T"),e[8]=n,e[9]=j):j=e[9],pe(j,!0);let M;e[10]!==B?(M=i(()=>{ae(B())},"L"),e[10]=B,e[11]=M):M=e[11];let U=M,_;e[12]!==R?(_=i(()=>{ae(R())},"j"),e[12]=R,e[13]=_):_=e[13];let G=_,$;e[14]===Symbol.for("react.memo_cache_sentinel")?($=i(m=>{W(m.currentTarget.value)},"M"),e[14]=$):$=e[14];let J=$,z;e[15]===Symbol.for("react.memo_cache_sentinel")?(z=i(m=>{let{id:h}=m.currentTarget.dataset;h!==void 0&&S(h)},"_"),e[15]=z):z=e[15];let K=z,A;e[16]===Symbol.for("react.memo_cache_sentinel")?(A=i(m=>{let h=m.currentTarget.dataset.tab;(h==="headers"||h==="html"||h==="text")&&l(h)},"z"),e[16]=A):A=e[16];let Q=A,F=ke(b,c),O=Se(F,D),d=Ce(O),q;e[17]!==d?(q=i(()=>{d!==void 0&&me(d)},"O"),e[17]=d,e[18]=q):q=e[18];let V=q,E;e[19]!==d?(E=i(()=>{d!==void 0&&"window"in globalThis&&globalThis.window.open(d,"_blank","noopener")},"E"),e[19]=d,e[20]=E):E=e[20];let X=E,H;return e[21]!==b||e[22]!==r||e[23]!==u||e[24]!==c||e[25]!==g||e[26]!==d||e[27]!==U||e[28]!==V||e[29]!==J||e[30]!==X||e[31]!==K||e[32]!==Q||e[33]!==G||e[34]!==O||e[35]!==v||e[36]!==F?(H={entries:b,error:r,errorSource:u,filter:c,isLoading:g,link:d,onClear:U,onCopyLink:V,onFilterChange:J,onOpenLink:X,onSelectMessage:K,onSelectTab:Q,onSendTest:G,selected:O,tab:v,visible:F},e[21]=b,e[22]=r,e[23]=u,e[24]=c,e[25]=g,e[26]=d,e[27]=U,e[28]=V,e[29]=J,e[30]=X,e[31]=K,e[32]=Q,e[33]=G,e[34]=O,e[35]=v,e[36]=F,e[37]=H):H=e[37],H},"Se"),Me=`<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src data:; style-src 'unsafe-inline'; font-src data:">`,_e=i(a=>`${Me}${a}`,"Te"),Je=i(({limit:a=100})=>{let e=oe(),{entries:s,error:o,errorSource:p,filter:P,isLoading:w,link:C,onClear:g,onCopyLink:n,onFilterChange:k,onOpenLink:f,onSelectMessage:D,onSelectTab:S,onSendTest:v,selected:l,tab:c,visible:W}=je({limit:a}),b=i(r=>e(r==="html"?"HTML":r==="text"?"Plain text":"Headers"),"b");return(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"mail-panel",children:[(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,t.jsx)(x,{"data-testid":"mail-send-test",onClick:v,size:"sm",type:"button",variant:"outline",children:e("Send test")}),(0,t.jsx)(x,{"data-testid":"mail-clear",disabled:s.length===0,onClick:g,size:"sm",type:"button",variant:"outline",children:e("Clear inbox")}),s.length>0&&(0,t.jsx)(ne,{className:"ml-auto","data-testid":"mail-count",variant:"secondary",children:e("{count} messages",{count:s.length})})]}),o!==null&&(0,t.jsx)(he,{error:p,testId:"mail-error"}),o===null&&!w&&s.length===0&&(0,t.jsx)(ce,{description:e("Email your app sends in dev is captured here \u2014 nothing is delivered."),icon:(0,t.jsxs)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:[(0,t.jsx)("path",{d:"M4 5h16v14H4z"}),(0,t.jsx)("path",{d:"m4 6 8 6 8-6"})]}),testId:"mail-empty",title:e("No captured email.")}),s.length>0&&(0,t.jsxs)("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-[minmax(0,22rem)_1fr]","data-testid":"mail-reader",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,t.jsx)(de,{"aria-label":e("Search messages"),"data-testid":"mail-search",onChange:k,placeholder:e("Filter messages"),type:"search",value:P}),(0,t.jsx)(fe,{className:"max-h-[32rem] rounded-xl border border-border bg-card shadow-xs","data-testid":"mail-list",children:(0,t.jsx)("ul",{className:"divide-y",children:W.map(r=>{let u=r.id===l?.id;return(0,t.jsx)("li",{children:(0,t.jsxs)("button",{className:`flex w-full flex-col items-start gap-0.5 px-3 py-2 text-left text-sm hover:bg-muted/60 ${u?"bg-muted":""}`,"data-active":u,"data-id":r.id,"data-testid":"mail-list-item",onClick:D,type:"button",children:[(0,t.jsx)("span",{className:"w-full truncate font-medium",children:r.subject||e("(no subject)")}),(0,t.jsx)("span",{className:"w-full truncate text-xs text-muted-foreground",children:y(r.to)}),(0,t.jsx)("span",{className:"text-xs text-muted-foreground tabular-nums",children:re(r.capturedAt,"\u2014")})]})},r.id)})})})]}),l!==void 0&&(0,t.jsxs)("div",{className:"flex min-w-0 flex-col gap-3 rounded-xl border border-border bg-card p-4 shadow-xs","data-testid":"mail-detail",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,t.jsx)("h2",{className:"truncate text-base font-semibold","data-testid":"mail-subject",children:l.subject||e("(no subject)")}),(0,t.jsxs)("dl",{className:"grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 text-xs text-muted-foreground",children:[(0,t.jsx)("dt",{children:e("From")}),(0,t.jsx)("dd",{className:"truncate font-mono",children:l.from??"\u2014"}),(0,t.jsx)("dt",{children:e("To")}),(0,t.jsx)("dd",{className:"truncate font-mono",children:y(l.to)}),l.cc!==void 0&&l.cc.length>0&&(0,t.jsxs)(t.Fragment,{children:[(0,t.jsx)("dt",{children:e("Cc")}),(0,t.jsx)("dd",{className:"truncate font-mono",children:y(l.cc)})]}),(0,t.jsx)("dt",{children:e("Sent")}),(0,t.jsx)("dd",{className:"tabular-nums",children:re(l.capturedAt,"\u2014")})]})]}),(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2","data-testid":"mail-actions",children:[(0,t.jsx)(x,{"data-testid":"mail-copy-link",disabled:C===void 0,onClick:n,size:"sm",type:"button",variant:"outline",children:e("Copy link")}),(0,t.jsx)(x,{"data-testid":"mail-open-link",disabled:C===void 0,onClick:f,size:"sm",type:"button",variant:"outline",children:e("Open in new tab")})]}),(0,t.jsx)(ye,{}),(0,t.jsx)("div",{className:"flex items-center gap-1","data-testid":"mail-tabs",role:"tablist",children:["html","text","headers"].map(r=>(0,t.jsx)(x,{"aria-selected":c===r,"data-tab":r,"data-testid":`mail-tab-${r}`,onClick:S,role:"tab",size:"sm",type:"button",variant:c===r?"secondary":"ghost",children:b(r)},r))}),(0,t.jsxs)("div",{className:"min-h-[12rem]",children:[c==="html"&&(l.html===void 0?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:e("No HTML body.")}):(0,t.jsx)("iframe",{className:"h-[24rem] w-full rounded-md border bg-white","data-testid":"mail-preview-html",sandbox:"",srcDoc:_e(l.html),title:e("Email preview")})),c==="text"&&(l.text===void 0?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:e("No text body.")}):(0,t.jsx)("pre",{className:"overflow-auto whitespace-pre-wrap rounded-md border bg-muted/30 p-3 text-xs","data-testid":"mail-preview-text",children:l.text})),c==="headers"&&(l.headers===void 0||Object.keys(l.headers).length===0?(0,t.jsx)("p",{className:"text-sm text-muted-foreground",children:e("No headers.")}):(0,t.jsx)("pre",{className:"overflow-auto whitespace-pre-wrap rounded-md border bg-muted/30 p-3 text-xs","data-testid":"mail-preview-headers",children:Object.entries(l.headers).map(([r,u])=>`${r}: ${u}`).join(`
|
|
2
2
|
`)}))]})]})]})]})},"We");export{Je as MailPanel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as T}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as H}from"./chunk-
|
|
1
|
+
import{b as T}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as H}from"./chunk-465RIA2L.js";import"./chunk-XXQUMVWH.js";import"./chunk-O3UMJLO3.js";import"./chunk-QLQADHFE.js";import{a as B}from"./chunk-VDW32UET.js";import{c as z}from"./chunk-ZNAGZU6H.js";import"./chunk-5KCULF7S.js";import"./chunk-XBDKZZ67.js";import{a as G}from"./chunk-XQCVZAGU.js";import{a as M,b as U,c as $,d as P,e as d,f as c}from"./chunk-MIQTKZAR.js";import{a as C,e as E}from"./chunk-UZERI5YC.js";import{d as q}from"./chunk-IUYFXK4X.js";import"./chunk-XNGYYOLS.js";import{a as S,e as _,g as L,h as V}from"./chunk-3XIESWL4.js";var K=_(L(),1);var r=_(V(),1);var J=["read","insert","update","delete"],W=S((e,t)=>({delete:e("Delete"),insert:e("Insert"),read:e("Read"),update:e("Update")})[t],"q"),Q=S(e=>{let t=new Map;for(let a of e){let s=t.get(a.table)??{operations:new Set,procedures:new Set,table:a.table};s.operations.add(a.on),s.procedures.add(a.procedure),t.set(a.table,s)}return[...t.values()].toSorted((a,s)=>a.table.localeCompare(s.table))},"B"),ie=S(()=>{let e=(0,K.c)(49),t=q(),a;e[0]===Symbol.for("react.memo_cache_sentinel")?(a={},e[0]=a):a=e[0];let{data:s,error:R,errorSource:k}=z(B.rlsPolicies,a),p=s!==void 0,m,n,h,l,f,u,x,N,o;if(e[1]!==s||e[2]!==R||e[3]!==k||e[4]!==p||e[5]!==t){let F=Q(Array.isArray(s?.policies)?s.policies:[]),D;e[15]!==s?(D=Array.isArray(s?.roles)?s.roles:[],e[15]=s,e[16]=D):D=e[16],n=D,x="flex flex-col gap-6",N="lunora-rls-panel",e[17]!==R||e[18]!==k?(o=R!==null&&(0,r.jsx)(H,{error:k,testId:"rls-error"}),e[17]=R,e[18]=k,e[19]=o):o=e[19],u="flex flex-col gap-2",m=C,h="overflow-hidden py-0";let I;e[20]!==t?(I=t("Policies"),e[20]=t,e[21]=I):I=e[21],e[22]!==I?(l=(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:I})}),e[22]=I,e[23]=l):l=e[23],f=p&&F.length===0?(0,r.jsx)(G,{description:t("No `definePolicy` is wired through `.use(rls(...))` in this deployment. Add one to guard a table's rows."),testId:"rls-policies-empty",title:t("No policies defined")}):(0,r.jsx)(E,{className:"px-0",children:(0,r.jsxs)(M,{"data-testid":"rls-policies-table",children:[(0,r.jsx)(U,{children:(0,r.jsxs)(P,{children:[(0,r.jsx)(d,{children:t("Table")}),J.map(i=>(0,r.jsx)(d,{children:W(t,i)},i)),(0,r.jsx)(d,{children:t("Guarded by")})]})}),(0,r.jsx)($,{children:F.map(i=>(0,r.jsxs)(P,{"data-testid":`rls-table-${i.table}`,children:[(0,r.jsx)(c,{className:"font-mono text-xs",children:i.table}),J.map(O=>(0,r.jsx)(c,{children:i.operations.has(O)?(0,r.jsx)(T,{variant:"secondary",children:t("Guarded")}):(0,r.jsx)("span",{"aria-hidden":"true",className:"text-muted-foreground",children:"\u2014"})},O)),(0,r.jsx)(c,{className:"font-mono text-xs text-muted-foreground",children:[...i.procedures].join(", ")})]},i.table))})]})}),e[1]=s,e[2]=R,e[3]=k,e[4]=p,e[5]=t,e[6]=m,e[7]=n,e[8]=h,e[9]=l,e[10]=f,e[11]=u,e[12]=x,e[13]=N,e[14]=o}else m=e[6],n=e[7],h=e[8],l=e[9],f=e[10],u=e[11],x=e[12],N=e[13],o=e[14];let b;e[24]!==m||e[25]!==h||e[26]!==l||e[27]!==f?(b=(0,r.jsxs)(m,{className:h,children:[l,f]}),e[24]=m,e[25]=h,e[26]=l,e[27]=f,e[28]=b):b=e[28];let g;e[29]!==u||e[30]!==b?(g=(0,r.jsx)("section",{className:u,children:b}),e[29]=u,e[30]=b,e[31]=g):g=e[31];let y;e[32]!==t?(y=t("Roles"),e[32]=t,e[33]=y):y=e[33];let w;e[34]!==y?(w=(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:y})}),e[34]=y,e[35]=w):w=e[35];let v;e[36]!==p||e[37]!==n||e[38]!==t?(v=p&&n.length===0?(0,r.jsx)(G,{description:t("No `defineRole` is registered via `rls(policies, { roles })`. Roles back `ctx.auth.can(...)` permission checks."),testId:"rls-roles-empty",title:t("No roles defined")}):(0,r.jsx)(E,{className:"px-0",children:(0,r.jsxs)(M,{"data-testid":"rls-roles-table",children:[(0,r.jsx)(U,{children:(0,r.jsxs)(P,{children:[(0,r.jsx)(d,{children:t("Role")}),(0,r.jsx)(d,{children:t("Description")}),(0,r.jsx)(d,{children:t("Permissions")})]})}),(0,r.jsx)($,{children:n.map(Y)})]})}),e[36]=p,e[37]=n,e[38]=t,e[39]=v):v=e[39];let A;e[40]!==w||e[41]!==v?(A=(0,r.jsx)("section",{className:"flex flex-col gap-2",children:(0,r.jsxs)(C,{className:"overflow-hidden py-0",children:[w,v]})}),e[40]=w,e[41]=v,e[42]=A):A=e[42];let j;return e[43]!==A||e[44]!==x||e[45]!==N||e[46]!==o||e[47]!==g?(j=(0,r.jsxs)("div",{className:x,"data-testid":N,children:[o,g,A]}),e[43]=A,e[44]=x,e[45]=N,e[46]=o,e[47]=g,e[48]=j):j=e[48],j},"ae");function X(e){return(0,r.jsx)(T,{variant:"outline",children:e},e)}S(X,"H");function Y(e){return(0,r.jsxs)(P,{"data-testid":`rls-role-${e.name}`,children:[(0,r.jsx)(c,{className:"font-mono text-xs",children:e.name}),(0,r.jsx)(c,{className:"text-muted-foreground",children:e.description??""}),(0,r.jsx)(c,{children:e.permissions.length===0?(0,r.jsx)("span",{"aria-hidden":"true",className:"text-muted-foreground",children:"\u2014"}):(0,r.jsx)("span",{className:"flex flex-wrap gap-1",children:e.permissions.map(X)})})]},e.name)}S(Y,"L");export{ie as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as N}from"./chunk-EQZTSISX.js";import{a as z}from"./chunk-54MMVNPT.js";import{a as q}from"./chunk-3CWGJYBB.js";import{a as W}from"./chunk-RMN2JN4S.js";import"./chunk-GRL5MG3Z.js";import"./chunk-7T7UOTYK.js";import"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import"./chunk-2OUPA2WJ.js";import{b as R}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as B}from"./chunk-
|
|
1
|
+
import{a as N}from"./chunk-EQZTSISX.js";import{a as z}from"./chunk-54MMVNPT.js";import{a as q}from"./chunk-3CWGJYBB.js";import{a as W}from"./chunk-RMN2JN4S.js";import"./chunk-GRL5MG3Z.js";import"./chunk-7T7UOTYK.js";import"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import"./chunk-2OUPA2WJ.js";import{b as R}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as B}from"./chunk-465RIA2L.js";import"./chunk-XXQUMVWH.js";import"./chunk-O3UMJLO3.js";import"./chunk-QLQADHFE.js";import{a as L}from"./chunk-VDW32UET.js";import{c as E}from"./chunk-ZNAGZU6H.js";import"./chunk-5KCULF7S.js";import"./chunk-XBDKZZ67.js";import{a as A}from"./chunk-XQCVZAGU.js";import{a as H,b as O,c as U,d as K,e as T,f as D}from"./chunk-MIQTKZAR.js";import{a as _}from"./chunk-UZERI5YC.js";import{d as j}from"./chunk-IUYFXK4X.js";import"./chunk-XNGYYOLS.js";import{a as M,e as F,g as V,h as X}from"./chunk-3XIESWL4.js";var P=F(V(),1);var t=F(X(),1);var G=M(n=>`${n.toString()} ms`,"D"),Q=M(n=>n.totalConnections===0&&n.shapePoke.passes===0&&n.whisper.passes===0,"z"),J=M(n=>{let e=(0,P.c)(48),{counters:r,includeTiming:s,prefix:l,t:o,title:b}=n,k=`${l}-section`,p;e[0]!==b?(p=(0,t.jsx)("h3",{className:"text-sm font-medium text-foreground",children:b}),e[0]=b,e[1]=p):p=e[1];let a=`${l}-stats`,i;e[2]!==o?(i=o("Passes"),e[2]=o,e[3]=i):i=e[3];let I=`${l}-passes`,v;e[4]!==r.passes||e[5]!==i||e[6]!==I?(v=(0,t.jsx)(N,{label:i,testId:I,value:r.passes}),e[4]=r.passes,e[5]=i,e[6]=I,e[7]=v):v=e[7];let h;e[8]!==o?(h=o("Sockets iterated"),e[8]=o,e[9]=h):h=e[9];let x=`${l}-iterated`,c;e[10]!==r.socketsIterated||e[11]!==h||e[12]!==x?(c=(0,t.jsx)(N,{label:h,testId:x,value:r.socketsIterated}),e[10]=r.socketsIterated,e[11]=h,e[12]=x,e[13]=c):c=e[13];let d;e[14]!==o?(d=o("Delivered"),e[14]=o,e[15]=d):d=e[15];let y=`${l}-delivered`,m;e[16]!==r.socketsDelivered||e[17]!==d||e[18]!==y?(m=(0,t.jsx)(N,{label:d,testId:y,value:r.socketsDelivered}),e[16]=r.socketsDelivered,e[17]=d,e[18]=y,e[19]=m):m=e[19];let u;e[20]!==o?(u=o("Peak width"),e[20]=o,e[21]=u):u=e[21];let g=`${l}-peak`,f;e[22]!==r.peakSocketsIterated||e[23]!==u||e[24]!==g?(f=(0,t.jsx)(N,{label:u,testId:g,value:r.peakSocketsIterated}),e[22]=r.peakSocketsIterated,e[23]=u,e[24]=g,e[25]=f):f=e[25];let S;e[26]!==r.totalMs||e[27]!==s||e[28]!==l||e[29]!==o?(S=s&&(0,t.jsx)(N,{label:o("Total time"),testId:`${l}-total-ms`,value:G(r.totalMs)}),e[26]=r.totalMs,e[27]=s,e[28]=l,e[29]=o,e[30]=S):S=e[30];let C;e[31]!==r.maxMs||e[32]!==s||e[33]!==l||e[34]!==o?(C=s&&(0,t.jsx)(N,{label:o("Max time"),testId:`${l}-max-ms`,value:G(r.maxMs)}),e[31]=r.maxMs,e[32]=s,e[33]=l,e[34]=o,e[35]=C):C=e[35];let $;e[36]!==m||e[37]!==f||e[38]!==S||e[39]!==C||e[40]!==a||e[41]!==v||e[42]!==c?($=(0,t.jsxs)("dl",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3","data-testid":a,children:[v,c,m,f,S,C]}),e[36]=m,e[37]=f,e[38]=S,e[39]=C,e[40]=a,e[41]=v,e[42]=c,e[43]=$):$=e[43];let w;return e[44]!==k||e[45]!==$||e[46]!==p?(w=(0,t.jsxs)("section",{className:"flex flex-col gap-2","data-testid":k,children:[p,$]}),e[44]=k,e[45]=$,e[46]=p,e[47]=w):w=e[47],w},"F"),me=M(n=>{let e=(0,P.c)(31),{initialShardKey:r}=n,s=j(),{queryShardKey:l,setShardKey:o,shardKey:b}=q(r),k;e[0]===Symbol.for("react.memo_cache_sentinel")?(k={},e[0]=k):k=e[0];let p;e[1]!==l?(p={keepPreviousData:!0,shardKey:l},e[1]=l,e[2]=p):p=e[2];let{data:a,error:i,errorSource:I,refetch:v}=E(L.getFanoutMetrics,k,p);z(v,!0);let h;e[3]!==a?(h=a!==void 0&&Q(a),e[3]=a,e[4]=h):h=e[4];let x=h,c;e[5]!==o||e[6]!==b?(c=(0,t.jsx)(W,{onChange:o,testId:"fanout-shard-input",value:b}),e[5]=o,e[6]=b,e[7]=c):c=e[7];let d;e[8]!==a||e[9]!==s?(d=a!==void 0&&(0,t.jsxs)("div",{className:"ml-auto flex items-center gap-2 text-sm text-muted-foreground","data-testid":"fanout-count",children:[a.promoted&&(0,t.jsx)(R,{"data-testid":"fanout-promoted",variant:a.relayCount>=a.maxRelays?"destructive":"default",children:a.relayCount>=a.maxRelays?s("auto-scaled: {relayCount}/{maxRelays} relays (at ceiling)",{maxRelays:a.maxRelays,relayCount:a.relayCount}):s("auto-scaled: {relayCount}/{maxRelays} relays",{maxRelays:a.maxRelays,relayCount:a.relayCount})}),(0,t.jsx)(R,{variant:"secondary",children:s("{count} connections",{count:a.totalConnections})}),(0,t.jsx)(R,{variant:"secondary",children:s("peak {count} subscribers",{count:a.peakSubscribers})})]}),e[8]=a,e[9]=s,e[10]=d):d=e[10];let y;e[11]!==c||e[12]!==d?(y=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[c,d]}),e[11]=c,e[12]=d,e[13]=y):y=e[13];let m;e[14]!==i||e[15]!==I?(m=i!==null&&(0,t.jsx)(B,{error:I,testId:"fanout-error"}),e[14]=i,e[15]=I,e[16]=m):m=e[16];let u;e[17]!==i||e[18]!==x||e[19]!==s?(u=i===null&&x&&(0,t.jsx)(A,{description:s("Realtime fan-out cost and per-topic subscriber counts for this shard."),icon:(0,t.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,t.jsx)("path",{d:"M4 12h4l3 7 4-14 3 7h2"})}),testId:"fanout-empty",title:s("No fan-out activity yet.")}),e[17]=i,e[18]=x,e[19]=s,e[20]=u):u=e[20];let g;e[21]!==i||e[22]!==x||e[23]!==a||e[24]!==s?(g=i===null&&a!==void 0&&!x&&(0,t.jsxs)(t.Fragment,{children:[a.topics.length>0&&(0,t.jsxs)("section",{className:"flex flex-col gap-2","data-testid":"fanout-topics-section",children:[(0,t.jsx)("h3",{className:"text-sm font-medium text-foreground",children:s("Hot topics")}),(0,t.jsx)(_,{className:"overflow-hidden py-0",children:(0,t.jsxs)(H,{"data-testid":"fanout-topics-table",children:[(0,t.jsx)(O,{children:(0,t.jsxs)(K,{children:[(0,t.jsx)(T,{children:s("Topic")}),(0,t.jsx)(T,{children:s("Kind")}),(0,t.jsx)(T,{className:"text-right",children:s("Subscribers")})]})}),(0,t.jsx)(U,{children:a.topics.map(Y)})]})})]}),(0,t.jsxs)("section",{className:"flex flex-col gap-3","data-testid":"fanout-cost",children:[(0,t.jsx)("h2",{className:"text-sm font-medium text-muted-foreground",children:s("Fan-out cost since this instance woke")}),(0,t.jsx)(J,{counters:a.shapePoke,includeTiming:!0,prefix:"fanout-poke",t:s,title:s("Shape pokes")}),(0,t.jsx)(J,{counters:a.whisper,includeTiming:!1,prefix:"fanout-whisper",t:s,title:s("Whisper broadcasts")})]})]}),e[21]=i,e[22]=x,e[23]=a,e[24]=s,e[25]=g):g=e[25];let f;return e[26]!==y||e[27]!==m||e[28]!==u||e[29]!==g?(f=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"fanout-panel",children:[y,m,u,g]}),e[26]=y,e[27]=m,e[28]=u,e[29]=g,e[30]=f):f=e[30],f},"me");function Y(n){return(0,t.jsxs)(K,{"data-testid":"fanout-topic-row",children:[(0,t.jsx)(D,{className:"font-mono text-xs",children:n.topic}),(0,t.jsx)(D,{children:(0,t.jsx)(R,{variant:"outline",children:n.kind})}),(0,t.jsx)(D,{className:"text-right font-medium tabular-nums",children:n.subscribers})]},`${n.kind}:${n.topic}`)}M(Y,"G");export{me as default};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as D}from"./chunk-XXQUMVWH.js";import{a as O}from"./chunk-
|
|
1
|
+
import{a as D}from"./chunk-XXQUMVWH.js";import{a as O}from"./chunk-O3UMJLO3.js";import{b as q}from"./chunk-QLQADHFE.js";import{d as A,h as C,j as E,k as H}from"./chunk-IUYFXK4X.js";import{a as V}from"./chunk-XNGYYOLS.js";import{a as y,e as I,g as T,h as _}from"./chunk-3XIESWL4.js";var G=I(T(),1);var i=I(_(),1);var L=y(S=>{let e=(0,G.c)(38),{className:w,error:t,testId:N}=S,g=A(),r=q(),l,s,n,a,c,m,o,d;if(e[0]!==w||e[1]!==t||e[2]!==r||e[3]!==N){let j=E(t),h;e[12]!==t?(h=H(t),e[12]=t,e[13]=h):h=e[13],s=h;let x;e[14]!==t?(x=O(t),e[14]=t,e[15]=x):x=e[15];let k=x,v;e[16]!==r||e[17]!==k?(v=y(()=>{r?.openConsole({errorsOnly:!0,seq:k})},"x"),e[16]=r,e[17]=k,e[18]=v):v=e[18],n=v,l=D,a=w,c=N,m="destructive";let u;e[19]!==t?(u=C(t),e[19]=t,e[20]=u):u=e[20],e[21]!==u?(o=(0,i.jsx)("p",{className:"font-medium",children:u}),e[21]=u,e[22]=o):o=e[22],d=j===void 0?null:(0,i.jsx)("p",{className:"mt-1 whitespace-pre-wrap text-xs opacity-90",children:V(j)}),e[0]=w,e[1]=t,e[2]=r,e[3]=N,e[4]=l,e[5]=s,e[6]=n,e[7]=a,e[8]=c,e[9]=m,e[10]=o,e[11]=d}else l=e[4],s=e[5],n=e[6],a=e[7],c=e[8],m=e[9],o=e[10],d=e[11];let p;e[23]!==s?(p=s===void 0?null:(0,i.jsx)("a",{"aria-label":"View documentation for this error",className:"mt-1 inline-block text-xs underline",href:s,rel:"noreferrer",target:"_blank",children:"View error docs"}),e[23]=s,e[24]=p):p=e[24];let f;e[25]!==r||e[26]!==n||e[27]!==g?(f=r===void 0?null:(0,i.jsx)("button",{className:"mt-1 block text-xs underline outline-none focus-visible:ring-1 focus-visible:ring-ring","data-testid":"error-show-in-console",onClick:n,type:"button",children:g("Show in console")}),e[25]=r,e[26]=n,e[27]=g,e[28]=f):f=e[28];let b;return e[29]!==l||e[30]!==a||e[31]!==c||e[32]!==m||e[33]!==o||e[34]!==d||e[35]!==p||e[36]!==f?(b=(0,i.jsxs)(l,{className:a,testId:c,variant:m,children:[o,d,p,f]}),e[29]=l,e[30]=a,e[31]=c,e[32]=m,e[33]=o,e[34]=d,e[35]=p,e[36]=f,e[37]=b):b=e[37],b},"G");export{L as a};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import{c as l}from"./chunk-XNGYYOLS.js";import{a as o,e as P,f as $,g as lt,h as De}from"./chunk-3XIESWL4.js";var _=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 _{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"}},Y=new fr;var pr={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")},mr=class{static{o(this,"TimeoutManager")}#e=pr;#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)}},N=new mr;function ft(t){setTimeout(t,0)}o(ft,"systemSetTimeoutZero");var qe=typeof window>"u"||"Deno"in globalThis;function g(){}o(g,"noop");function yt(t,e){return typeof t=="function"?t(e):t}o(yt,"functionalUpdate");function ne(t){return typeof t=="number"&&t>=0&&t!==1/0}o(ne,"isValidTimeout");function me(t,e){return Math.max(t+(e||0)-Date.now(),0)}o(me,"timeUntilStale");function M(t,e){return typeof t=="function"?t(e):t}o(M,"resolveStaleTime");function I(t,e){return typeof t=="function"?t(e):t}o(I,"resolveQueryBoolean");function ye(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(ye,"matchQuery");function be(t,e){let{exact:r,status:s,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(r){if(H(e.options.mutationKey)!==H(n))return!1}else if(!q(e.options.mutationKey,n))return!1}return!(s&&e.state.status!==s||i&&!i(e))}o(be,"matchMutation");function oe(t,e){return(e?.queryKeyHashFn||H)(t)}o(oe,"hashQueryKeyByOptions");function H(t){return JSON.stringify(t,(e,r)=>Ue(r)?Object.keys(r).sort().reduce((s,i)=>(s[i]=r[i],s),{}):r)}o(H,"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 yr=Object.prototype.hasOwnProperty;function Be(t,e,r=0){if(t===e)return t;if(r>500)return e;let s=pt(t)&&pt(e);if(!s&&!(Ue(t)&&Ue(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):{},d=0;for(let h=0;h<c;h++){let f=s?h:a[h],p=t[f],m=e[f];if(p===m){u[f]=p,(s?h<n:yr.call(t,f))&&d++;continue}if(p===null||m===null||typeof p!="object"||typeof m!="object"){u[f]=m;continue}let y=Be(p,m,r+1);u[f]=y,y===p&&d++}return n===c&&d===n?t:u}o(Be,"replaceEqualDeep");function ve(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(ve,"shallowEqualObjects");function pt(t){return Array.isArray(t)&&t.length===Object.keys(t).length}o(pt,"isPlainArray");function Ue(t){if(!mt(t))return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(!mt(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}o(Ue,"isPlainObject");function mt(t){return Object.prototype.toString.call(t)==="[object Object]"}o(mt,"hasObjectPrototype");function bt(t){return new Promise(e=>{N.setTimeout(e,t)})}o(bt,"sleep");function ae(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?Be(t,e):e}o(ae,"replaceData");function br(t){return t}o(br,"keepPreviousData");function vt(t,e,r=0){let s=[...t,e];return r&&s.length>r?s.slice(1):s}o(vt,"addToEnd");function gt(t,e,r=0){let s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}o(gt,"addToStart");var Z=Symbol();function ge(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===Z?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}o(ge,"ensureQueryFn");function we(t,e){return typeof t=="function"?t(...e):!!t}o(we,"shouldThrowError");function wt(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(wt,"addConsumeAwareSignal");var Q=(()=>{let t=o(()=>qe,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function ce(){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(ce,"pendingThenable");var St=ft;function vr(){let t=[],e=0,r=o(c=>{c()},"notifyFn"),s=o(c=>{c()},"batchNotifyFn"),i=St,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(vr,"createNotifyManager");var v=vr();var gr=class extends _{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}},ee=new gr;function wr(t){return Math.min(1e3*2**t,3e4)}o(wr,"defaultRetryDelay");function Ke(t){return(t??"online")==="online"?ee.isOnline():!0}o(Ke,"canFetch");var Se=class extends Error{static{o(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Ce(t){let e=!1,r=0,s,i=ce(),n=o(()=>i.status!=="pending","isResolved"),a=o(b=>{if(!n()){let S=new Se(b);p(S),t.onCancel?.(S)}},"cancel"),c=o(()=>{e=!0},"cancelRetry"),u=o(()=>{e=!1},"continueRetry"),d=o(()=>Y.isFocused()&&(t.networkMode==="always"||ee.isOnline())&&t.canRun(),"canContinue"),h=o(()=>Ke(t.networkMode)&&t.canRun(),"canStart"),f=o(b=>{n()||(s?.(),i.resolve(b))},"resolve"),p=o(b=>{n()||(s?.(),i.reject(b))},"reject"),m=o(()=>new Promise(b=>{s=o(S=>{(n()||d())&&b(S)},"continueFn"),t.onPause?.()}).then(()=>{s=void 0,n()||t.onContinue?.()}),"pause"),y=o(()=>{if(n())return;let b,S=r===0?t.initialPromise:void 0;try{b=S??t.fn()}catch(E){b=Promise.reject(E)}Promise.resolve(b).then(f).catch(E=>{if(n())return;let F=t.retry??(Q.isServer()?0:3),D=t.retryDelay??wr,K=typeof D=="function"?D(r,E):D,j=F===!0||typeof F=="number"&&r<F||typeof F=="function"&&F(r,E);if(e||!j){p(E);return}r++,t.onFail?.(r,E),bt(K).then(()=>d()?void 0:m()).then(()=>{e?p(E):y()})})},"run");return{promise:i,status:o(()=>i.status,"status"),cancel:a,continue:o(()=>(s?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:h,start:o(()=>(h()?y():m().then(y),i),"start")}}o(Ce,"createRetryer");var ke=class{static{o(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ne(this.gcTime)&&(this.#e=N.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(Q.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(N.clearTimeout(this.#e),this.#e=void 0)}};function kt(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,d=o(async()=>{let h=!1,f=o(y=>{wt(y,()=>e.signal,()=>h=!0)},"addSignalProperty"),p=ge(e.options,e.fetchOptions),m=o(async(y,b,S)=>{if(h)return Promise.reject(e.signal.reason);if(b==null&&y.pages.length)return Promise.resolve(y);let F=o(()=>{let Qe={client:e.client,queryKey:e.queryKey,pageParam:b,direction:S?"backward":"forward",meta:e.options.meta};return f(Qe),Qe},"createQueryFnContext")(),D=await p(F),{maxPages:K}=e.options,j=S?gt:vt;return{pages:j(y.pages,D,K),pageParams:j(y.pageParams,b,K)}},"fetchPage");if(i&&n.length){let y=i==="backward",b=y?Sr:Ct,S={pages:n,pageParams:a},E=b(s,S);c=await m(S,E,y)}else{let y=t??n.length;do{let b=u===0?a[0]??s.initialPageParam:Ct(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?.(d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r):e.fetchFn=d},"onFetch")}}o(kt,"infiniteQueryBehavior");function Ct(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(Ct,"getNextPageParam");function Sr(t,{pages:e,pageParams:r}){return e.length>0?t.getPreviousPageParam?.(e[0],e,r[0],r):void 0}o(Sr,"getPreviousPageParam");var Tt=class extends ke{static{o(this,"Query")}#e;#t;#r;#s;#n;#i;#a;#o;constructor(t){super(),this.#o=!1,this.#a=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#n=t.client,this.#s=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=Et(this.options),this.state=t.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#i?.promise}setOptions(t){if(this.options={...this.#a,...t},t?._type&&(this.#e=t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Et(this.options);e.data!==void 0&&(this.setState(It(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(t,e){let r=ae(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(g).catch(g):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=>I(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Z||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>M(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!me(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#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.#o||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(d=>d.options.queryFn);u&&this.setOptions(u.options)}let r=new AbortController,s=o(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:o(()=>(this.#o=!0,r.signal),"get")})},"addSignalProperty"),i=o(()=>{let u=ge(this.options,e),h=o(()=>{let f={client:this.#n,queryKey:this.queryKey,meta:this.meta};return s(f),f},"createQueryFnContext")();return this.#o=!1,this.options.persister?this.options.persister(u,h,this):u(h)},"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"?kt(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=Ce({initialPromise:e?.initialPromise,fn:a.fetchFn,onCancel:o(u=>{u instanceof Se&&u.revert&&this.setState({...this.#r,fetchStatus:"idle"}),r.abort()},"onCancel"),onFail:o((u,d)=>{this.#c({type:"failed",failureCount:u,error:d})},"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 Se){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,...je(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...It(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 je(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ke(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}o(je,"fetchState");function It(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}o(It,"successState");function Et(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(Et,"getDefaultState");var He=class extends _{static{o(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#o=null,this.#a=ce(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#r=void 0;#s=void 0;#n;#i;#a;#o;#h;#c;#p;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Rt(this.#t,this.options)?this.#f():this.updateResult(),this.#g())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return $e(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return $e(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#w(),this.#S(),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 I(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&&!ve(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let s=this.hasListeners();s&&Ot(this.#t,r,this.options,e)&&this.#f(),this.updateResult(),s&&(this.#t!==r||I(this.options.enabled,this.#t)!==I(e.enabled,this.#t)||M(this.options.staleTime,this.#t)!==M(e.staleTime,this.#t))&&this.#y();let i=this.#b();s&&(this.#t!==r||I(this.options.enabled,this.#t)!==I(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 kr(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.#a.status==="pending"&&this.#a.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(g)),e}#y(){this.#w();let t=M(this.options.staleTime,this.#t);if(Q.isServer()||this.#s.isStale||!ne(t))return;let r=me(this.#s.dataUpdatedAt,t)+1;this.#d=N.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.#S(),this.#u=t,!(Q.isServer()||I(this.options.enabled,this.#t)===!1||!ne(this.#u)||this.#u===0)&&(this.#l=N.setInterval(()=>{(this.options.refetchIntervalInBackground||Y.isFocused())&&this.#f()},this.#u))}#g(){this.#y(),this.#v(this.#b())}#w(){this.#d!==void 0&&(N.clearTimeout(this.#d),this.#d=void 0)}#S(){this.#l!==void 0&&(N.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:d}=t,h={...d},f=!1,p;if(e._optimisticResults){let O=this.hasListeners(),ie=!O&&Rt(t,e),le=O&&Ot(t,r,e,s);(ie||le)&&(h={...h,...je(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:b}=h;p=h.data;let S=!1;if(e.placeholderData!==void 0&&p===void 0&&b==="pending"){let O;i?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(O=i.data,S=!0):O=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,O!==void 0&&(b="success",p=ae(i?.data,O,e),f=!0)}if(e.select&&p!==void 0&&!S)if(i&&p===n?.data&&e.select===this.#h)p=this.#c;else try{this.#h=e.select,p=e.select(p),p=ae(i?.data,p,e),this.#c=p,this.#o=null}catch(O){this.#o=O}this.#o&&(m=this.#o,p=this.#c,y=Date.now(),b="error");let E=h.fetchStatus==="fetching",F=b==="pending",D=b==="error",K=F&&E,j=p!==void 0,U={status:b,fetchStatus:h.fetchStatus,isPending:F,isSuccess:b==="success",isError:D,isInitialLoading:K,isLoading:K,data:p,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:E,isRefetching:E&&!F,isLoadingError:D&&!j,isPaused:h.fetchStatus==="paused",isPlaceholderData:f,isRefetchError:D&&j,isStale:ze(t,e),refetch:this.refetch,promise:this.#a,isEnabled:I(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let O=U.data!==void 0,ie=U.status==="error"&&!O,le=o(pe=>{ie?pe.reject(U.error):O&&pe.resolve(U.data)},"finalizeThenableIfPossible"),dt=o(()=>{let pe=this.#a=U.promise=ce();le(pe)},"recreateThenable"),fe=this.#a;switch(fe.status){case"pending":t.queryHash===r.queryHash&&le(fe);break;case"fulfilled":(ie||U.data!==fe.value)&&dt();break;case"rejected":(!ie||U.error!==fe.reason)&&dt();break}}return U}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),ve(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 Cr(t,e){return I(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&I(e.retryOnMount,t)===!1)}o(Cr,"shouldLoadOnMount");function Rt(t,e){return Cr(t,e)||t.state.data!==void 0&&$e(t,e,e.refetchOnMount)}o(Rt,"shouldFetchOnMount");function $e(t,e,r){if(I(e.enabled,t)!==!1&&M(e.staleTime,t)!=="static"){let s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&ze(t,e)}return!1}o($e,"shouldFetchOn");function Ot(t,e,r,s){return(t!==e||I(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&ze(t,r)}o(Ot,"shouldFetchOptionally");function ze(t,e){return I(e.enabled,t)!==!1&&t.isStaleByTime(M(e.staleTime,t))}o(ze,"isStale");function kr(t,e){return!ve(t.getCurrentResult(),e)}o(kr,"shouldAssignObserverCurrentProperties");var Pt=class extends ke{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||Ir(),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=Ce({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 Ir(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}o(Ir,"getDefaultState");var Lt=class extends _{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 Pt({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=Ie(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=Ie(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=Ie(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=Ie(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=>be(e,r))}findAll(t={}){return this.getAll().filter(e=>be(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(g))))}};function Ie(t){return t.options.scope?.id}o(Ie,"scopeFor");var At=class extends _{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 Tt({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=>ye(e,r))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(r=>ye(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 We=class{static{o(this,"QueryClient")}#e;#t;#r;#s;#n;#i;#a;#o;constructor(t={}){this.#e=t.queryCache||new At,this.#t=t.mutationCache||new Lt,this.#r=t.defaultOptions||{},this.#s=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#a=Y.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#o=ee.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#a?.(),this.#a=void 0,this.#o?.(),this.#o=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),r=this.#e.build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(M(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=yt(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(g).catch(g)}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(g)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(s).then(g)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let r=this.#e.build(this,e);return r.isStaleByTime(M(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(g).catch(g)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(g).catch(g)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return ee.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(H(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(H(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===Z&&(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 B=P($(),1);var te=P($(),1),Ft=P(De(),1);var ue=te.createContext(void 0),Ve=o(t=>{let e=te.useContext(ue);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),Ge=o(({client:t,children:e})=>(te.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,Ft.jsx)(ue.Provider,{value:t,children:e})),"QueryClientProvider");var he=P($(),1),Er=P(De(),1);function Tr(){let t=!1;return{clearReset:o(()=>{t=!1},"clearReset"),reset:o(()=>{t=!0},"reset"),isReset:o(()=>t,"isReset")}}o(Tr,"createValue");var Rr=he.createContext(Tr()),Mt=o(()=>he.useContext(Rr),"useQueryErrorResetBoundary");var xt=P($(),1);var _t=o((t,e,r)=>{let s=r?.state.error&&typeof t.throwOnError=="function"?we(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),Nt=o(t=>{xt.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),Qt=o(({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(i&&t.data===void 0||we(r,[t.error,s])),"getHasError");var Ee=P($(),1);var Dt=Ee.createContext(!1),Ut=o(()=>Ee.useContext(Dt),"useIsRestoring"),Oo=Dt.Provider;var qt=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"),Bt=o((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),Kt=o((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),Je=o((t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()}),"fetchOptimistic");function jt(t,e,r){let s=Ut(),i=Mt(),n=Ve(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,qt(a),_t(a,i,c),Nt(i);let d=!n.getQueryCache().get(a.queryHash),[h]=B.useState(()=>new e(n,a)),f=h.getOptimisticResult(a),p=!s&&u;if(B.useSyncExternalStore(B.useCallback(m=>{let y=p?h.subscribe(v.batchCalls(m)):g;return h.updateResult(),y},[h,p]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),B.useEffect(()=>{h.setOptions(a)},[a,h]),Kt(a,f))throw Je(a,h,i);if(Qt({result:f,errorResetBoundary:i,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw f.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(a,f),a.experimental_prefetchInRender&&!Q.isServer()&&Bt(f,s)&&(d?Je(a,h,i):c?.promise)?.catch(g).finally(()=>{h.updateResult()}),a.notifyOnChangeProps?f:h.trackResult(f)}o(jt,"useBaseQuery");function Or(t,e){return jt(t,He,e)}o(Or,"useQuery");var $t=P(lt(),1);var z=P($(),1),Xe=P(De(),1);var Ht=(0,z.createContext)(null),Pr=o(()=>new We({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"T"),Lr=o(t=>{let e=(0,$t.c)(9),{children:r,client:s,queryClient:i}=t,n=(0,z.use)(ue),a;e[0]!==n||e[1]!==i?(a=o(()=>i??n??Pr(),"i"),e[0]=n,e[1]=i,e[2]=a):a=e[2];let[c]=(0,z.useState)(a),u=i??n??c;if(!u)throw new l("INTERNAL","LunoraProvider: failed to resolve a QueryClient");let d;e[3]!==r||e[4]!==s?(d=(0,Xe.jsx)(Ht,{value:s,children:r}),e[3]=r,e[4]=s,e[5]=d):d=e[5];let h=d;if(n===u)return h;let f;return e[6]!==h||e[7]!==u?(f=(0,Xe.jsx)(Ge,{client:u,children:h}),e[6]=h,e[7]=u,e[8]=f):f=e[8],f},"b"),Ye=o(()=>{let t=(0,z.use)(Ht);if(!t)throw new l("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var zt=o(()=>{let t=null;return{get:o(()=>t,"get"),set:o(e=>{t=e},"set")}},"l");var Te=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)}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 Wt=0,Ar="lunora-bridge",Fr=1e3,Mr=3e3,Re=class{static{o(this,"c")}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;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(Wt+=1,this.tabId=`tab_${String(Wt)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??Fr,this.leaderTimeout=e.leaderTimeout??Mr,this.onBecomeLeader=e.onBecomeLeader,this.onStopBeingLeader=e.onStopBeingLeader,this.onConnectionStatus=e.onConnectionStatus,this.onSubscriptionData=e.onSubscriptionData,this.onSubscriptionError=e.onSubscriptionError,this.onSubscriptionSettled=e.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(e.channelName??Ar),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){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:r})}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);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()});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 Ze="_creationTime",xr=o(t=>{if(typeof t!="object"||t===null)return;let e=t._id;return typeof e=="string"?e:void 0},"p"),_r=o(t=>{let e;for(let r of t){let s=r[Ze];if(typeof s=="number"){if(e!==void 0){if(s<e)return!0;if(s>e)return!1}e=s}}return!1},"a"),Nr=o((t,e)=>{let r=e[Ze];if(typeof r!="number")return t.length;let s=_r(t);for(let[i,n]of t.entries()){let a=n[Ze];if(typeof a=="number"&&(s?a<r:a>r))return i}return t.length},"d"),Vt=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")},"y"),Gt=o((t,e)=>{if(!Array.isArray(t))return;let r=[];for(let u of t){if(xr(u)===void 0)return;r.push(u)}let{key:s,op:i,row:n}=e;if(i==="delete"){let u=r.filter(d=>d._id!==s);return u.length===r.length?[...r]:u}if(n===void 0)return;let a=r.findIndex(u=>u._id===s);if(a===-1){let u=[...r];return u.splice(Nr(r,n),0,n),u}let c=[...r];return c[a]=n,c},"g");var Qr=1024,Oe=o(t=>{let e=t.maxBuffer??Qr,r=[],s=[],i=!1,n,a=!1,c=o(()=>{let h=s.shift();if(!h)return!1;if(n)return h.reject(n),!0;if(r.length>0){let f=r.shift();return h.resolve({done:!1,value:f}),!0}return i?(h.resolve({done:!0,value:void 0}),!0):(s.unshift(h),!1)},"n"),u={complete(){if(!(i||n))for(i=!0;c(););},fail(h){if(!(i||n))for(n=h,r.length=0;c(););},push(h){if(!(i||n||a)){if(r.length>=e){u.fail(new l("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}r.push(h),c()}}},d=o(()=>{if(!a){a=!0,i=!0,r.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:d,[Symbol.asyncIterator](){return{next(){if(n)return Promise.reject(n);if(r.length>0){let h=r.shift();return Promise.resolve({done:!1,value:h})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((h,f)=>{s.push({reject:f,resolve:h})})},return(){return d(),Promise.resolve({done:!0,value:void 0})}}}}}},"d");var Jt=/^ /u,Xt=o(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"u"),Dr=o(t=>{let e="",r=[];for(let s of t.split(`
|
|
2
|
+
`))s.startsWith("event:")?e=s.slice(6).replace(Jt,""):s.startsWith("data:")&&r.push(s.slice(5).replace(Jt,""));return{data:r.join(`
|
|
3
|
+
`),event:e}},"p"),Ur=o((t,e,r)=>{let s=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),d=s[u];if(d===void 0)throw new l("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(Xt(d))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,Xt(u));let a=n.toString();return`${r.endsWith("/")?r.slice(0,-1):r}${i}${a===""?"":`?${a}`}`},"S"),qr=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 l(i,s)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(JSON.parse(t.data))}catch{return e.fail(new l("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"T"),Br=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=Dr(i.slice(0,a));if(i=i.slice(a+2),qr(c,e))return!0;a=i.indexOf(`
|
|
6
|
+
|
|
7
|
+
`)}return!1},"c");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 l("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"g"),Yt=o((t,e,r={})=>{let s=r.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!s)throw new l("INTERNAL","httpStream: no `fetch` implementation available");let i=Ur(t,e??{},r.baseUrl??""),n=new AbortController,a;r.signal&&(r.signal.aborted?n.abort():(a=o(()=>{n.abort()},"n"),r.signal.addEventListener("abort",a,{once:!0})));let c=o(()=>{a&&r.signal?.removeEventListener("abort",a)},"l"),{handle:u,iterable:d}=Oe({maxBuffer:r.maxBuffer,onCancel:o(()=>{n.abort()},"onCancel")});return(async()=>{try{let h=await s(i,{headers:{accept:"text/event-stream",...r.headers},method:t.method,signal:n.signal});if(!h.ok){await h.body?.cancel().catch(()=>{}),u.fail(new l("HTTP_STREAM_STATUS",`httpStream: request failed (status ${h.status.toString()})`,{status:h.status}));return}if(!h.body){u.fail(new l("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await Br(h.body,u)}finally{c()}})().catch(h=>{if(n.signal.aborted){u.complete();return}if(h instanceof Error&&"code"in h){u.fail(h);return}u.fail(new l("HTTP_STREAM_TRANSPORT",h instanceof Error?h.message:String(h),{cause:h}))}),d},"w");var et=o(t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},"b"),Kr=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},"g"),k="$lunora.wire$",tt="__proto__",Zt={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},er={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},jr=o(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"m"),T=o((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[k,"undefined"];if(t===null)return null;let r=typeof t;if(r==="bigint")return[k,"bigint",t.toString()];if(r==="number"){let n=t;return Number.isNaN(n)?[k,"nan"]:n===1/0?[k,"inf"]:n===-1/0?[k,"-inf"]:n}if(r!=="object")return t;if(t instanceof Date)return[k,"date",T(t.getTime(),e+1)];if(t instanceof Error){let n=t,a={};for(let u of Object.keys(n))n[u]!==void 0&&(a[u]=T(n[u],e+1));let c=[k,"error",n.name,n.message,a];return n.cause!==void 0&&c.push(T(n.cause,e+1)),c}if(t instanceof URL)return[k,"url",t.href];if(t instanceof Map)return[k,"map",[...t.entries()].map(([n,a])=>[T(n,e+1),T(a,e+1)])];if(t instanceof Set)return[k,"set",[...t].map(n=>T(n,e+1))];if(t instanceof ArrayBuffer)return[k,"bytes",et(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"?[k,"bytes",et(c)]:[k,"bytes",et(c),a]}if(Array.isArray(t)){let n=t.map(a=>T(a,e+1));return n.length>0&&n[0]===k?[k,"arr",n]:n}if(!jr(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=T(a,e+1);n===tt?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"s"),w=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]===k)switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(i=>w(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":return new Date(w(t[2],e+1));case"map":return new Map(t[2].map(([i,n])=>[w(i,e+1),w(n,e+1)]));case"set":return new Set(t[2].map(i=>w(i,e+1)));case"url":return new URL(t[2]);case"error":{let i=t[2],n=t[3],a=(Object.hasOwn(er,i)?er[i]:void 0)??Error,c=new a(n);c.name!==i&&Object.defineProperty(c,"name",{configurable:!0,value:i,writable:!0});let u=w(t[4],e+1);for(let d of Object.keys(u))d===tt?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:u[d],writable:!0}):c[d]=u[d];return t.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:w(t[5],e+1),writable:!0}),c}case"bytes":{let i=Kr(t[2]),n=t[3]??"Uint8Array";if(n==="ArrayBuffer")return i.buffer.byteLength===i.byteLength?i.buffer:i.slice().buffer;let a=Object.hasOwn(Zt,n)?Zt[n]:void 0;return a?new a(i.slice().buffer):i}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return t.map(i=>w(i,e+1))}return t.map(i=>w(i,e+1))}let r=t,s={};for(let i of Object.keys(r)){let n=w(r[i],e+1);i===tt?Object.defineProperty(s,i,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[i]=n}return s},"f");var $r=o((t,e)=>t<e?-1:t>e?1:0,"y"),rt=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(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(n=>rt(n)).join(",")}]`;let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let n=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} 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).toSorted($r),i=[];for(let n of s){let a=r[n];a!==void 0&&i.push(`${JSON.stringify(n)}:${rt(a)}`)}return`{${i.join(",")}}`},"n"),W=o(t=>rt(T(t)),"l");var x=class t{static{o(this,"y")}static key(e,r,s){return`${e}::${W(r)}::${s??""}`}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.key(e.fn.__lunoraRef,e.args,e.shardKey),e),this.byId.set(e.id,e)}remove(e){let r=t.key(e.fn.__lunoraRef,e.args,e.shardKey);this.byKey.get(r)===e&&this.byKey.delete(r),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}};var re=o((t,e)=>{let r=t;for(let s of e)try{r=s.transform(r)}catch{}return r},"m"),V=o((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let r of t.callbacks)try{r(e)}catch{}}},"u"),st=o((t,e)=>{let r;try{r=e(t.lastValue)}catch{return}let s={id:Symbol("optimistic"),transform:e};t.optimisticLayers.push(s),V(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)},"i"),n=o(()=>{V(t,re(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")}},"p"),Pe=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},"d"),tr=o((t,e)=>{let r=[],s=[],i=o((n,a)=>t.get(x.key(n,a,e)),"i");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 d=st(u,()=>c);d&&(r.push(d.confirm),s.push(d.rollback))},"setQuery")}}},"L");var rr=0,Hr=o(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();rr+=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)}_${rr.toString(36)}_${t}`},"a"),it=o((t,e)=>t!==void 0&&e!==t,"f"),Ae=Hr,se=o((t,e,r,s)=>{if(t){t({error:r,mutationId:s,operation:e});return}console.warn(`[lunora] offline-queue persistence ${e} failed`,r)},"h"),Le=class{static{o(this,"u")}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??=Ae(),this.items.push(r),this.persistence?.append({args:r.args,functionPath:r.functionPath,id:r.id,identity:r.identity,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{se(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(n){throw se(this.onPersistenceError,"load",n),n}let r=[];for(let n of e)if(!(this.items.some(a=>a.id===n.id)||r.some(a=>a.id===n.id))){if(it(this.version,n.version)){this.persistence.remove(n.id).catch(a=>{se(this.onPersistenceError,"remove",a,n.id)});continue}r.push({args:n.args,functionPath:n.functionPath,id:n.id,identity:n.identity,reject:o(()=>{},"reject"),resolve:o(()=>{},"resolve"),shardKey:n.shardKey})}this.items.unshift(...r),this.evictOverflow(),this.notifySize();let s=new Set(this.items),i=new Set;for(let n of r)s.has(n)&&i.add(n.shardKey);return[...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()}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(s=>{se(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 L=o(t=>new Promise((e,r)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{r(t.error??new Error("IndexedDB request failed"))})}),"i"),Fe=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)},"c"),Me=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},"E");var zr="lunora-outbox",Wr="offline-mutations",sr="by_id",Vr=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new l("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let r=t.databaseName??zr,s=t.storeName??Wr,i=Fe(e,r,1,a=>{a.objectStoreNames.contains(s)||a.createObjectStore(s,{autoIncrement:!0}).createIndex(sr,"id",{unique:!0})}),n=Me(i,s);return{append:o(async a=>{await n("readwrite",c=>L(c.add(a)))},"append"),clear:o(async()=>{await n("readwrite",a=>L(a.clear()))},"clear"),load:o(async()=>n("readonly",a=>L(a.getAll())),"load"),remove:o(async a=>{await n("readwrite",async c=>{let u=await L(c.index(sr).getKey(a));u!==void 0&&await L(c.delete(u))})},"remove")}},"x"),ir=o((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return Vr()}},"P");var xe=o((t,e,r)=>`${t}::${e}::${r??""}`,"k"),Gr=500;var Jr="lunora-query-cache",Xr="query-cache",nr="by_ts",Yr=1,Zr=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new l("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let r=t.databaseName??Jr,s=t.storeName??Xr,i=t.maxEntries??Gr,n=Fe(e,r,Yr,u=>{u.objectStoreNames.contains(s)||u.createObjectStore(s,{keyPath:"key"}).createIndex(nr,"ts",{unique:!1})}),a=Me(n,s),c=o(async u=>{let d=await L(u.count())-i;d<=0||await new Promise((h,f)=>{let p=u.index(nr).openCursor();p.addEventListener("success",()=>{let m=p.result;if(!m||d<=0){h();return}m.delete(),d-=1,m.continue()}),p.addEventListener("error",()=>{f(p.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:o(async()=>{await a("readwrite",u=>L(u.clear()))},"clear"),load:o(async()=>a("readonly",u=>L(u.getAll())),"load"),put:o(async(u,d)=>{await a("readwrite",async h=>{await L(h.put({...d,key:u})),await c(h)})},"put"),remove:o(async u=>{await a("readwrite",d=>L(d.delete(u)))},"remove")}},"I"),or=o(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return Zr()}},"N");var nt=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 ot=500,es=o((t,e)=>{if(t.size<e)return;let r=t.keys().next().value;r!==void 0&&t.delete(r)},"ot"),X=class{static{o(this,"C")}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()}},ts="/_lunora/rpc",ar="/_lunora/rpc-batch",rs="/_lunora/ws",at=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"P"),ct=o(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"M"),ss=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)},"ht"),is="lunora-ping",ns=3e4,os=1e4,as=250,cs=64,us="/_lunora/admin/shard-traffic",hs="/_lunora/admin/scheduled",ds="/_lunora/admin/scheduled/status",ls="/_lunora/admin/scheduled/ws",fs="/_lunora/admin/scheduled/cancel",ps="/_lunora/admin/scheduled/dead",ms="/_lunora/admin/scheduled/dead/retry",ys="/_lunora/admin/scheduled/dead/cancel",bs="/_lunora/admin/workflows/instances",vs="/_lunora/admin/workflows/instance",gs="/_lunora/admin/workflows/status",_e="/_lunora/admin/storage",ws="/_lunora/admin/storage/url",Ss="/_lunora/admin/storage/buckets",Cs="/_lunora/admin/functions",ks="/_lunora/admin/cron-jobs",Is="/_lunora/admin/cron-jobs/run",Es="/_lunora/admin/openapi",Ts="/_lunora/admin/openrpc",Rs="/_lunora/admin/global/tables",Os="/_lunora/admin/global/table",Ps="/_lunora/admin/global/facet",Ls="/_lunora/admin/vector/indexes",As="/_lunora/admin/vector/query",Fs="/_lunora/admin/logs/archive",Ms="/_lunora/admin/kv/namespaces",xs="/_lunora/admin/kv/keys",ut="/_lunora/admin/kv/value",_s="/_lunora/admin/auth/users",cr="/_lunora/admin/auth/sessions",Ns="/_lunora/admin/auth/users/create",Qs="/_lunora/admin/auth/users/role",Ds="/_lunora/admin/auth/users/ban",Us="/_lunora/admin/auth/users/unban",qs="/_lunora/admin/auth/users/password",Bs="/_lunora/admin/auth/users/remove",Ks="/_lunora/admin/auth/users/impersonate",js="/_lunora/admin/auth/sessions/revoke",$s="/_lunora/admin/auth/sessions/revoke-all",Hs="/_lunora/admin/auth/capabilities",zs="/_lunora/admin/auth/users/update",Ws="/_lunora/admin/auth/accounts",Vs="/_lunora/admin/auth/accounts/unlink",Gs="/_lunora/admin/auth/passkeys",Js="/_lunora/admin/auth/passkeys/delete",Xs="/_lunora/admin/auth/two-factor/disable",Ys="/_lunora/admin/auth/organizations",Zs="/_lunora/admin/auth/organizations/members",ei="/_lunora/admin/auth/organizations/invitations",ti="/_lunora/admin/auth/organizations/members/remove",ri="/_lunora/admin/auth/organizations/invitations/cancel",si="/_lunora/admin/auth/config",ii="/_lunora/admin/auth/organizations/create",ni="/_lunora/admin/auth/organizations/update",oi="/_lunora/admin/auth/organizations/remove",ai="/_lunora/admin/auth/organizations/members/add",ci="/_lunora/admin/auth/organizations/members/invite",ui="/_lunora/admin/auth/organizations/members/role",hi="/_lunora/admin/auth/organizations/teams",di="/_lunora/admin/auth/organizations/teams/create",li="/_lunora/admin/auth/organizations/teams/update",fi="/_lunora/admin/auth/organizations/teams/remove",pi="/_lunora/admin/auth/organizations/teams/members",mi="/_lunora/admin/auth/organizations/teams/members/add",yi="/_lunora/admin/auth/organizations/teams/members/remove",bi="/_lunora/admin/auth/organizations/roles",vi="/_lunora/admin/auth/organizations/roles/create",gi="/_lunora/admin/auth/organizations/roles/update",wi="/_lunora/admin/auth/organizations/roles/remove",Si="/api/auth",Ci="/get-session",ur=o(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"Q"),G=o((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"v"),A=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}`},"g"),C=o(t=>t??"","p"),ki=o(t=>{let e=t.error,r=typeof e?.code=="string"?e.code:void 0,s=typeof e?.message=="string"?e.message:void 0,i=(typeof t.message=="string"?t.message:void 0)??s??"stream error";return r===void 0?new Error(i):new l(r,i)},"Re"),hr=o(t=>{let e=t.error,r=typeof e?.code=="string"?e.code:void 0,s=typeof e?.message=="string"?e.message:void 0;return{message:(typeof t.message=="string"?t.message:void 0)??s??"subscription error",...r===void 0?{}:{code:r}}},"B"),Ne=o((t,e)=>{for(let r of t)try{r(e)}catch{}},"R"),Ii=new TextDecoder,Ei=o(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return Ii.decode(t)},"Ne"),R=o((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"f"),de=o(t=>{let e=new Error(t.message??"request failed");return e.code=t.code,t.data!==void 0&&(e.data=w(t.data)),t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"T"),J=o((t,e)=>{try{return T(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)}},"S"),Ti=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:de(i.error),ok:!1}:{ok:!0,value:w(i?.result)}}return r.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},"_e"),Ri=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Oi=Promise.resolve(),ht=class t{static{o(this,"z")}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;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new x;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new X;statusListeners=new X;tokenExpiredListeners=new X;mutationSettledListeners=new X;pendingChangeListeners=new X;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??G(ur(e.url),rs),this.wsToken=e.wsToken;let r=e.authBasePath??Si;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??zt(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??ns,this.connectTimeoutMs=e.connectTimeoutMs??os,this.defaultConnectionContext=e.connectionContext,this.persistence=ir(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=or(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Te,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=Oi),this.offlineQueue=new Le(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-${Ae()}`,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();this.authToken=e,r!==void 0&&(this.authSubject=r);let n=this.identityFingerprint();if(n!==i&&(s?this.rejectQueuedForIdentityChange():this.restampQueuedIdentity(i,n),this.tabCoordinator)){let a=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),a&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(e)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(e??"")??0}async callMutator(e,r,s){let i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new l("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=s?.shardKey??"",a,c=await this.rpc(e,r,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o(u=>{a=u},"onMutationAck")});return a!==void 0&&a>(this.clientWatermarks.get(n)??0)&&this.clientWatermarks.set(n,a),{applied:a===void 0||a===i,result:c}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;let e={};this.authToken&&(e.authorization=`Bearer ${this.authToken}`);try{let r=await this.fetchImpl(G(this.url,`${this.authBasePath}${Ci}`),{credentials:"include",headers:e,method:"GET"});return r.ok?(await r.json())?.user??null:null}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={}){let s=C(r.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,r={}){let s=C(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={}){let i=C(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&&R(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),d=u?.get(e);if(!d?.delete(r)||d.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let h=this.getConnection(s.shardKey);h&&R(h,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,r,s={}){this.ensureSocket(s.shardKey);let i=this.getConnection(s.shardKey);i&&R(i,{data:J(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=new Set([...this.connections.keys(),...this.clientWatermarks.keys()]);for(let i of r){let n=this.connections.get(i);e.push({confirmedMutationWatermark:this.clientWatermarks.get(i)??0,hasSocket:n?.socket!==void 0,shardKey:i===""?void 0:i,wasEverConnected:n?.wasEverConnected??!1,wsState:n?.wsState??"idle"})}let s=this.subscriptions.all().map(i=>({acked:i.acked,functionPath:i.fn.__lunoraRef,id:i.id,kind:"query",lastMutationId:i.lastMutationId,pendingOptimisticLayers:i.optimisticLayers.length,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size}));for(let i of this.shapeSubscriptions.values())s.push({acked:i.serverCursor!==void 0,functionPath:`shape:${i.name}`,id:i.id,kind:"shape",lastMutationId:i.lastMutationId,pendingOptimisticLayers:0,rowCount:i.rows.size,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((i,n)=>(i.shardKey??"").localeCompare(n.shardKey??"")),subscriptions:s.toSorted((i,n)=>i.functionPath.localeCompare(n.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){let i=this.peekActiveQueryValue(e.__lunoraRef,r,s),n=i===void 0?void 0:W(i);return()=>{let a=this.peekActiveQueryValue(e.__lunoraRef,r,s);return n===void 0&&a===void 0?!0:n===void 0||a===void 0?!1:W(a)===n}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,r,s){if(!this.readyResolved)return;let i=W(r),n=xe(e,i,s),a=this.hydratedQueryCache.get(n);if(a!==void 0)return a.identity===this.identityFingerprint()?a.value:void 0}peekActiveQueryValue(e,r,s){let i=x.key(e,r,s);return this.subscriptions.get(i)?.lastValue}async query(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");if(!this.fetchImpl)throw new l("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(G(this.url,ar),{body:JSON.stringify({calls:e.map((n,a)=>({args:J(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 l("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}if(!r.ok||i.error&&!i.results)throw i.error?de(i.error):new l("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);return Ti(i.results??[],e.length)}async mutation(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let i=r,n=s.mutationId??Ae(),{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{hasSocket:u,wasEverConnected:d,wsState:h}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:f}=this.offlineQueue,p=d||f,m=this.WebSocketImpl!==void 0&&p;if(h!=="open"&&!u&&m||h==="connecting"&&p)return this.enqueueOfflineMutation(e,i,s.shardKey,n,c,a,s.precondition);try{let y,b=await this.rpc(e.__lunoraRef,i,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:o(S=>{y=S},"onCommitCursor")});for(let S of a)S(y);return b}catch(y){throw ct(c),y}}async action(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return await this.rpc(e.__lunoraRef,r,s.shardKey)}async importRows(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(d=>({rows:d})),a=r.length,c=0,u=0;for(let d=0;d<a;d+=i){let h=r.slice(d,d+i),f=u;await this.mutation(e,n(h),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(f)}`},shardKey:s.shardKey}),u+=1,c+=h.length,s.onProgress?.({done:c,total:a})}return{chunks:u,imported:c}}async shardTraffic(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=await this.adminFetch(us,"POST",{table:e});return{failed:r.failed??0,ok:r.ok??0,shards:r.shards??[]}}async listScheduledJobs(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(hs,"GET")).records??[]}async schedulerStatus(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let e=await this.adminFetch(ds,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return{cancelled:(await this.adminFetch(fs,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(ps,"GET")).records??[]}async retryDeadJob(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return{retried:(await this.adminFetch(ms,"POST",{id:e})).retried===!0}}async removeDeadJob(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return{removed:(await this.adminFetch(ys,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");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(`${bs}?${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){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${vs}?${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){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return{status:(await this.adminFetch(gs,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");if(this.WebSocketImpl===void 0)return()=>{};let r=G(ur(this.url),ls),s=nt(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,a=!1,c=o(()=>{a||(n=setTimeout(h,s.next()))},"o"),u=o(f=>{if(a||this.WebSocketImpl===void 0)return;let p=f===void 0?r:`${r}?token=${encodeURIComponent(f)}`;this.openManagedSocket(i,p,this.connectTimeoutMs,{onClose:o(()=>{c()},"onClose"),onMessage:o(m=>{try{let y=JSON.parse(typeof m.data=="string"?m.data:"");y.type==="jobs"&&Array.isArray(y.records)&&e(y.records)}catch{}},"onMessage"),onOpen:o(()=>{s.reset()},"onOpen")})},"a"),d=o(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"c"),h=o(()=>{if(a||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){d(f).catch(()=>{});return}u(f)},"u");return h(),()=>{a=!0,n!==void 0&&clearTimeout(n),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close()}}async listFunctions(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(Cs,"GET")).functions??[]}async getCronJobs(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(ks,"GET")).jobs??[]}async runCronJob(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=await this.adminFetch(Is,"POST",{name:e});return{name:r.name??e,ran:r.ran===!0}}async fetchOpenApi(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return await this.adminFetch(Es,"GET")}async fetchOpenRpc(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return await this.adminFetch(Ts,"GET")}async listStorageObjects(e={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=new URLSearchParams;e.prefix!==void 0&&e.prefix!==""&&r.set("prefix",e.prefix),e.cursor!==void 0&&e.cursor!==""&&r.set("cursor",e.cursor),e.limit!==void 0&&r.set("limit",String(e.limit)),e.bucket!==void 0&&e.bucket!==""&&r.set("bucket",e.bucket);let s=r.toString(),i=s===""?_e:`${_e}?${s}`,n=await this.adminFetch(i,"GET");return{cursor:n.cursor,objects:n.objects??[]}}async deleteStorageObject(e,r){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let s=`${_e}?key=${encodeURIComponent(e)}${at(r?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted??!0,key:i.key??e}}async listStorageBuckets(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(Ss,"GET")).buckets??[]}async uploadStorageObject(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=`${_e}?key=${encodeURIComponent(e.key)}${at(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){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let s=r?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${ws}?key=${encodeURIComponent(e)}${i}${at(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(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return await this.adminFetch(Rs,"GET")}async readGlobalTablePage(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");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(e.filters)),await this.adminFetch(`${Os}?${r.toString()}`,"GET")}async facetGlobalColumn(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");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(e.filters)),await this.adminFetch(`${Ps}?${r.toString()}`,"GET")}async listVectorIndexes(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(Ls,"GET")).indexes??[]}async queryVectorIndex(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(As,"POST",e)).matches??[]}async queryLogArchive(e={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=await this.adminFetch(Fs,"POST",e);return{nextCursor:r.nextCursor,rows:r.rows??[]}}async listKvNamespaces(){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");return(await this.adminFetch(Ms,"GET")).namespaces??[]}async listKvKeys(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=A(xs,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(r,"GET")}async getKvValue(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=A(ut,{key:e.key,namespace:e.namespace});return await this.adminFetch(r,"GET")}async putKvValue(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");await this.adminFetch(ut,"PUT",e)}async deleteKvKey(e){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=A(ut,{key:e.key,namespace:e.namespace});await this.adminFetch(r,"DELETE")}async listAuthUsers(e={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=A(_s,{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(Ns,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(Qs,"POST",e)}async banAuthUser(e){return await this.adminFetch(Ds,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(Us,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(qs,"POST",e)}async removeAuthUser(e){await this.adminFetch(Bs,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Ks,"POST",e)}async revokeAuthSession(e){await this.adminFetch(js,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch($s,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(Hs,"GET")}async updateAuthUser(e){return await this.adminFetch(zs,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(A(Ws,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(Vs,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(A(Gs,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(Js,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(Xs,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(A(Ys,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let r=A(Zs,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthOrgInvitations(e){let r=A(ei,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async removeAuthOrgMember(e){await this.adminFetch(ti,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(ri,"POST",e)}async getAuthConfig(){return await this.adminFetch(si,"GET")}async createAuthOrganization(e){return await this.adminFetch(ii,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(ni,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(oi,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(ai,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(ci,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(ui,"POST",e)}async listAuthOrgTeams(e){let r=A(hi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(di,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(li,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(fi,"POST",e)}async listAuthOrgTeamMembers(e){let r=A(pi,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(r,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(mi,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(yi,"POST",e)}async listAuthOrgRoles(e){let r=A(bi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgRole(e){return await this.adminFetch(vi,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(gi,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(wi,"POST",e)}async listAuthSessions(e={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let r=new URLSearchParams;e.userId!==void 0&&e.userId!==""&&r.set("userId",e.userId),e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset));let s=r.toString();return await this.adminFetch(s===""?cr:`${cr}?${s}`,"GET")}subscribe(e,r,s,i={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");let n=r??{},a=x.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(a),u=s,d=i.onError;if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=W(n),m=this.takeHydratedCache(e.__lunoraRef,p,i.shardKey);c={acked:!1,args:n,argsKey:p,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c)}if(c.callbacks.add(u),d&&c.errorCallbacks.add(d),i.onCheckpoint&&c.checkpointCallbacks.add(i.onCheckpoint),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let h=c;return()=>{if(h.callbacks.delete(u),d&&h.errorCallbacks.delete(d),i.onCheckpoint&&h.checkpointCallbacks.delete(i.onCheckpoint),h.callbacks.size===0){let f=this.getConnection(h.shardKey);!(f&&R(f,{id:h.id,type:"unsubscribe"}))&&f&&f.pendingUnsubscribes.push({id:h.id,type:"unsubscribe"}),this.subscriptions.remove(h)}}}subscribeShape(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");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:J(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i);let a=this.getConnection(n.shardKey);!(a&&R(a,{id:i,type:"shape_unsubscribe"}))&&a&&a.pendingUnsubscribes.push({id:i,type:"shape_unsubscribe"})}}stream(e,r,s={}){if(this.closed)throw new l("INTERNAL","LunoraClient is closed");if(this.WebSocketImpl===void 0)throw new l("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}=Oe({maxBuffer:s.maxBuffer,onCancel:o(()=>{let f=this.getConnection(n);f&&R(f,{id:i,type:"unsubscribe"}),this.streams.delete(i)},"onCancel")});this.streams.set(i,{handle:c,shardKey:n}),this.ensureSocket(n);let d=this.getConnection(n),h={id:i,query:{args:J(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"};if(!(d?.wsState==="open"&&R(d,h))&&d){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=cs;){let f=d.pendingStreams.shift()?.id,p=f?this.streams.get(f):void 0;p&&(p.handle.fail(new l("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(f))}d.pendingStreams.push(h)}return u}httpStream(e,r,s={}){if(this.closed)throw new l("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new l("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return Yt(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 l("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);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.tabCoordinator?.stop(),this.tabCoordinator=void 0}teardownConnection(e){if(e.reconnectTimer!==void 0&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),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 Re({channelName:e,onBecomeLeader:o(()=>{for(let r of this.subscriptions.all())this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(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);if(!c)return;if(c.serverBase=s,i!==void 0){c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),Pe(c,i),V(c,c.optimisticLayers.length===0?s:re(s,c.optimisticLayers));return}let u=c.optimisticLayers.length===0?s:re(s,c.optimisticLayers);V(c,u)},"onSubscriptionData"),onSubscriptionError:o((r,s)=>{let i=this.subscriptions.get(r);i&&Ne(i.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 d of u.checkpointCallbacks)d({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 d=this.outboxMutationCounter;try{await this.outbox.enqueue({args:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(d)}`,identity:u,mutationId:d,shardKey:s})}catch(h){throw ct(n),h instanceof Error?h:new Error(String(h))}for(let h of a)h(void 0);return}return new Promise((d,h)=>{let f={args:r,functionPath:e.__lunoraRef,liveAwaiter:!0,id:i,identity:u,precondition:c,onCommit:o(p=>{for(let m of a)m(p)},"onCommit"),reject:o(p=>{this.queuedIdentities.delete(i),ct(n),h(p instanceof Error?p:new Error(String(p)))},"reject"),resolve:d,shardKey:s};this.offlineQueue.enqueue(f),this.queuedOfflineShardKeys.add(s),f.id!==void 0&&this.queuedIdentities.set(f.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(()=>{})},"t"),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();for(let{key:r,...s}of e){if(it(this.persistenceVersion,s.version)){this.queryCache.remove(r).catch(()=>{});continue}this.hydratedQueryCache.set(r,s)}}catch{}}takeHydratedCache(e,r,s){let i=xe(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=xe(e.fn.__lunoraRef,e.argsKey,e.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),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(()=>{})},as)}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(([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=x.key(e,r,s),u=this.subscriptions.get(c);if(u){let d=st(u,i);d&&(n.push(d.confirm),a.push(d.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,r,s,i,n){let{confirms:a,rollbacks:c,store:u}=tr(this.subscriptions,s);try{e(u,r)}catch{for(let d=c.length-1;d>=0;d-=1)c[d]?.();return}i.push(...c),n.push(...a)}getConnection(e){return this.connections.get(C(e))}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=C(e),s=this.connections.get(r);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:nt(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket: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){let r={"content-type":"application/json"};if(this.authToken&&(r.authorization=`Bearer ${this.authToken}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),e.clientId!==void 0&&(r["x-lunora-client-id"]=e.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.attachBookmark){let s=this.bookmark.get();s&&(r["x-d1-bookmark"]=s)}return r}async rpc(e,r,s,i={}){if(!this.fetchImpl)throw new l("INTERNAL","LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i),a=await this.fetchImpl(G(this.url,ts),{body:JSON.stringify({args:J(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{let u=a.statusText?` ${a.statusText}`:"";throw new l("INTERNAL",`LunoraClient: response was not JSON (status ${a.status.toString()}${u})`)}if("error"in c)throw de(c.error);if(!a.ok){let u=a.statusText?` ${a.statusText}`:"";throw new l("INTERNAL",`LunoraClient: request failed (status ${a.status.toString()}${u})`)}return i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),w(c.result)}async adminFetch(e,r,s,i){if(!this.fetchImpl)throw new l("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(G(this.url,e),{body:c,headers:n,method:r}),d;try{d=await u.json()}catch{let h=u.statusText?` ${u.statusText}`:"";throw new l("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${h})`)}if(typeof d=="object"&&d!==null&&"error"in d){let h=d.error,f=new Error(h.message??"admin request failed");throw f.code=h.code,f}if(!u.ok){let h=u.statusText?` ${u.statusText}`:"";throw new l("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${h})`)}return d}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(C(e.shardKey));R(e,{clientId:this.clientId,id:"connect",type:"connect",...r===void 0?{}:{context:r}})}resendShapeSubscriptions(e){for(let r of this.shapeSubscriptions.values())C(r.shardKey)===C(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 l("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(d=>{c(),i.onClose(d)},"a");s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===a){try{a.close()}catch{}u()}},s)),a.addEventListener("open",()=>{e.socket===a&&(e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now(),i.onOpen(),this.startHeartbeat(e,u))}),a.addEventListener("message",d=>{e.socket===a&&(e.lastFrameAt=Date.now(),i.onMessage(d))}),a.addEventListener("close",d=>{e.socket===a&&u(d)}),a.addEventListener("error",()=>{e.socket===a&&u()})}openSocket(e,r,s){this.WebSocketImpl!==void 0&&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,e.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(r);for(let n of this.subscriptions.all())C(n.shardKey)===C(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)R(e,{id:a,type:c})}if(e.pendingStreams&&e.pendingStreams.length>0){let n=e.pendingStreams;e.pendingStreams=[];for(let a of n)R(e,a)}let i=this.whisperHandlers.get(C(r));if(i)for(let n of i.keys())R(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(r).catch(()=>{})},"onOpen")})}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),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)C(n.shardKey)===C(e.shardKey)&&!r.has(i)&&(n.handle.fail(new l("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(is)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){let r=C(e);for(let s of this.subscriptions.all())C(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;R(r,{id:e.id,query:{args:T(e.args),functionPath:e.fn.__lunoraRef,table:s,...e.serverCursor===void 0?{}:{sinceSeq:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);r?.wsState==="open"&&R(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=Ei(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,id:a}=i;this.streams.get(a)?.handle.push(w(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);break}case"pokePart":{this.handlePokePart(i);break}case"pokeStart":{this.handlePokeStart(i);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(ki(e)),this.streams.delete(r);return}let i=r===void 0?void 0:this.subscriptions.getById(r);if(i){Ne(i.errorCallbacks,hr(e));return}let n=r===void 0?void 0:this.shapeSubscriptions.get(r);n&&Ne(n.errorCallbacks,hr(e))}handlePokeStart(e){es(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(e.pokeId,{baseCheckpoint:e.baseCheckpoint,epoch:e.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(e){let r=this.pokeBuffers.get(e.pokeId);if(!r)return;let s=r.parts.get(e.shapeId)??[];for(let i of e.rowsPatch)s.push(i.value===void 0?i:{...i,value:w(i.value)});r.parts.set(e.shapeId,s),e.lastMutationId!==void 0&&r.lastMutationId.set(e.shapeId,e.lastMutationId)}handlePokeEnd(e){let r=this.pokeBuffers.get(e.pokeId);if(r){this.pokeBuffers.delete(e.pokeId);for(let[s,i]of r.parts){let n=this.shapeSubscriptions.get(s);if(!n)continue;let a=r.epoch!==void 0&&n.serverEpoch!==void 0&&r.epoch!==n.serverEpoch,c=r.baseCheckpoint!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==r.baseCheckpoint;if(a||c){n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,this.emitShapeRows(n),this.sendShapeSubscribeIfOpen(n);continue}ss(n.rows,i),e.checkpoint!==void 0&&(n.serverCursor=e.checkpoint),e.epoch!==void 0&&(n.serverEpoch=e.epoch);let u=r.lastMutationId.get(s);u!==void 0&&(n.lastMutationId=u),this.emitShapeRows(n),n.onCheckpoint?.({checkpoint:n.serverCursor,mutationId:n.lastMutationId})}}}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=this.resolveDataPayload(e,s);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})}if(this.persistQueryValue(s),Pe(s,s.serverCursor),V(s,s.optimisticLayers.length===0?i:re(i,s.optimisticLayers)),this.tabCoordinator?.isLeader()){let n=x.key(s.fn.__lunoraRef,s.args,s.shardKey);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=e.lastMutationId);for(let s of r.checkpointCallbacks)s({checkpoint:r.serverCursor,mutationId:r.lastMutationId});if(this.tabCoordinator?.isLeader()){let s=x.key(r.fn.__lunoraRef,r.args,r.shardKey);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),Pe(e,e.serverCursor)&&V(e,re(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,r){if("data"in e&&e.data!==void 0)return w(e.data);let s=w(e.delta);if(Vt(s)&&r.serverBase!==void 0){let i=Gt(r.serverBase,s);if(i!==void 0)return i}return s}dispatchWhisper(e,r){let s=this.whisperHandlers.get(C(r))?.get(e.topic);if(!s)return;let i=w(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,Ne(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(r=>{se(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}rejectQueuedForIdentityChange(){let e=this.offlineQueue.drain();for(let r of e){this.queuedIdentities.delete(r.id??""),this.unpersist(r.id);let s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",r.reject(s),this.emitItemSettled(r,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(e,r){for(let[s,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,r)}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=this.offlineQueue.drainConflict();for(let d of r){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");let h=new Error("offline mutation skipped: precondition failed before replay");h.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",h)}let s=C(e),i=this.offlineQueue.drain(d=>C(d.shardKey)===s);if(i.length===0)return;let n=this.identityFingerprint(),a=[];for(let d of i)this.passesReplayIdentityGate(d,n)&&a.push(d);if(a.length===0)return;let c=this.encodableOrSettleTerminal(a);if(c.length===0)return;if(c.length===1){await this.replaySequential(c);return}let u=[];for(let d=0;d<c.length;d+=ot){let h=c.slice(d,d+ot),f=await this.replayBatched(h);if(u.push(...f.requeue),f.stop){u.push(...c.slice(d+ot));break}}u.length>0&&this.offlineQueue.requeue(u)}encodableOrSettleTerminal(e){let r=[];for(let s of e)try{J(s.args,`args for '${s.functionPath}'`),r.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return r}passesReplayIdentityGate(e,r){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id),i=s===void 0?e.identity:s;if(i!==void 0&&i!==r&&!this.isSameCredentialUnderTokenHash(i)){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);let n=new Error("offline mutation skipped: auth identity changed before replay");return n.code="OFFLINE_IDENTITY_CHANGED",e.reject(n),this.emitItemSettled(e,"rejected",n),!1}return this.queuedIdentities.delete(e.id??""),!0}settleReplaySuccess(e,r,s){this.unpersist(e.id),e.onCommit?.(s),e.resolve(r),this.emitItemSettled(e,"committed")}settleReplayTerminal(e,r){this.unpersist(e.id),e.reject(r),this.emitItemSettled(e,"rejected",r)}async replaySequential(e){for(let r=0;r<e.length;r+=1){let s=e[r];if(s)try{let i,n=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,mutationId:s.id,onCommitCursor:o(a=>{i=a},"onCommitCursor")});this.settleReplaySuccess(s,n,i)}catch(i){if(i.code!==void 0){this.settleReplayTerminal(s,i);continue}this.offlineQueue.requeue(e.slice(r));return}}}async replayBatched(e){if(!this.fetchImpl)return{requeue:e,stop:!0};let r;try{r=await this.fetchImpl(G(this.url,ar),{body:JSON.stringify({calls:e.map((n,a)=>({args:J(n.args,`args for '${n.functionPath}'`),functionPath:n.functionPath,id:a,mutationId:n.id,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:e,stop:!0}}let s=r.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await r.json()}catch{return{requeue:e,stop:!0}}if(!i.results){if(i.error){let n=de(i.error);for(let a of e)this.settleReplayTerminal(a,n);return{requeue:[],stop:!1}}return{requeue:e,stop:!0}}return{requeue:this.settleReplayBatchSlots(e,i.results),stop:!1}}settleReplayBatchSlots(e,r){let s=new Map;for(let n of r)typeof n.id=="number"&&n.body!==void 0&&s.set(n.id,n.body);let i=[];for(let[n,a]of e.entries()){let c=s.get(n);c===void 0?i.push(a):"error"in c?Ri.has(c.error.code)?i.push(a):this.settleReplayTerminal(a,de(c.error)):this.settleReplaySuccess(a,w(c.result),c.commitCursor)}return i}};var dr=P(lt(),1),lr=P($(),1);var Pi=o(()=>{let t=(0,dr.c)(4),e=Ye(),r,s,i;return t[0]!==e?(r=o(n=>e.onConnectionStatus(()=>{n()}),"n"),s=o(()=>e.connectionStatus(),"e"),i=o(()=>e.connectionStatus(),"r"),t[0]=e,t[1]=r,t[2]=s,t[3]=i):(r=t[1],s=t[2],i=t[3]),(0,lr.useSyncExternalStore)(r,s,i)},"f");export{ht as a,br as b,Ve as c,Or as d,Lr as e,Ye as f,Pi as g};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{b as h}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{b as S}from"./chunk-
|
|
1
|
+
import{b as h}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{b as S}from"./chunk-ZNAGZU6H.js";import{f as k}from"./chunk-5KCULF7S.js";import"./chunk-XBDKZZ67.js";import{a as y,e as A}from"./chunk-UZERI5YC.js";import{d as I}from"./chunk-IUYFXK4X.js";import"./chunk-XNGYYOLS.js";import{a as u,e as w,g as $,h as j}from"./chunk-3XIESWL4.js";var N=w($(),1);var a=w(j(),1);var z=[{key:"accounts",label:"Accounts"},{key:"admin",label:"Admin"},{key:"organization",label:"Organizations"},{key:"passkey",label:"Passkeys"},{key:"twoFactor",label:"Two-factor"}],v=u(e=>{if(e===void 0)return"\u2014";let i=[[86400,"d"],[3600,"h"],[60,"m"]];for(let[t,d]of i)if(e>=t&&e%t===0)return`${String(e/t)}${d}`;return`${String(e)}s`},"v"),g=u(e=>{let i=(0,N.c)(8),{children:t,heading:d,testId:r}=e,l;i[0]!==d?(l=(0,a.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,a.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:d})}),i[0]=d,i[1]=l):l=i[1];let n;i[2]!==t?(n=(0,a.jsx)(A,{className:"p-3",children:t}),i[2]=t,i[3]=n):n=i[3];let c;return i[4]!==l||i[5]!==n||i[6]!==r?(c=(0,a.jsxs)(y,{className:"gap-0 py-0","data-testid":r,children:[l,n]}),i[4]=l,i[5]=n,i[6]=r,i[7]=c):c=i[7],c},"h"),o=u(e=>{let i=(0,N.c)(7),{label:t,value:d}=e,r;i[0]!==t?(r=(0,a.jsx)("span",{className:"text-sm",children:t}),i[0]=t,i[1]=r):r=i[1];let l;i[2]!==d?(l=(0,a.jsx)("span",{className:"text-sm text-muted-foreground tabular-nums",children:d}),i[2]=d,i[3]=l):l=i[3];let n;return i[4]!==r||i[5]!==l?(n=(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-xl border border-border bg-card p-2 shadow-xs",children:[r,l]}),i[4]=r,i[5]=l,i[6]=n):n=i[6],n},"c"),T=u(()=>{let e=(0,N.c)(20),i=k(),t=I(),d;e[0]===Symbol.for("react.memo_cache_sentinel")?(d=["lunora-auth-config"],e[0]=d):d=e[0];let r;e[1]!==i?(r=u(()=>i.getAuthConfig(),"s"),e[1]=i,e[2]=r):r=e[2];let{data:l,error:n}=S(d,r),c;e[3]!==t?(c=u(s=>(0,a.jsx)(h,{variant:s?"success":"outline",children:t(s?"Enabled":"Disabled")}),"u"),e[3]=t,e[4]=c):c=e[4];let m=c,p;e[5]!==n?(p=n!==null&&(0,a.jsx)("p",{className:"px-4 py-8 text-center text-sm text-destructive","data-testid":"auth-config-error",role:"alert",children:n}),e[5]=n,e[6]=p):p=e[6];let f;e[7]!==l||e[8]!==n||e[9]!==t?(f=n===null&&l===void 0&&(0,a.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"auth-config-loading",children:t("Loading auth configuration\u2026")}),e[7]=l,e[8]=n,e[9]=t,e[10]=f):f=e[10];let x;e[11]!==l||e[12]!==n||e[13]!==m||e[14]!==t?(x=n===null&&l!==void 0&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(g,{heading:t("Enabled capabilities"),testId:"auth-config-capabilities",children:(0,a.jsx)("ul",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:z.map(s=>{let P=l.capabilities[s.key];return(0,a.jsxs)("li",{className:"flex items-center justify-between gap-2 rounded-xl border border-border bg-card p-2 shadow-xs","data-testid":`auth-config-cap-${s.key}`,children:[(0,a.jsx)("span",{className:"text-sm",children:t(s.label)}),m(P)]},s.key)})})}),(0,a.jsx)(g,{heading:t("Plugins"),testId:"auth-config-plugins",children:l.plugins.length===0?(0,a.jsx)("p",{className:"text-sm text-muted-foreground",children:t("No plugins enabled.")}):(0,a.jsx)("div",{className:"flex flex-wrap gap-2",children:l.plugins.map(L)})}),(0,a.jsx)(g,{heading:t("Sign-in methods"),testId:"auth-config-signin",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Email & password"),value:m(l.emailAndPassword)}),(0,a.jsx)(o,{label:t("Social providers"),value:l.socialProviders.length===0?t("None"):(0,a.jsx)("span",{className:"flex flex-wrap justify-end gap-1",children:l.socialProviders.map(q)})})]})}),l.organization.enabled&&(0,a.jsx)(g,{heading:t("Organizations"),testId:"auth-config-org",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Teams"),value:m(l.organization.teams)}),(0,a.jsx)(o,{label:t("Custom roles"),value:m(l.organization.roles)})]})}),(0,a.jsx)(g,{heading:t("Session policy"),testId:"auth-config-session",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Expires in"),value:v(l.session.expiresIn)}),(0,a.jsx)(o,{label:t("Refresh after"),value:v(l.session.updateAge)}),(0,a.jsx)(o,{label:t("Fresh window"),value:v(l.session.freshAge)}),(0,a.jsx)(o,{label:t("Cookie cache"),value:m(l.session.cookieCache===!0)})]})}),(0,a.jsx)(g,{heading:t("Rate limit"),testId:"auth-config-ratelimit",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Status"),value:m(l.rateLimit.enabled)}),l.rateLimit.enabled&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(o,{label:t("Max requests"),value:l.rateLimit.max??"\u2014"}),(0,a.jsx)(o,{label:t("Window"),value:v(l.rateLimit.window)})]})]})}),l.userFields.length>0&&(0,a.jsx)(g,{heading:t("Plugin user fields"),testId:"auth-config-user-fields",children:(0,a.jsx)("ul",{className:"flex flex-col gap-2",children:l.userFields.map(s=>(0,a.jsxs)("li",{className:"flex items-center justify-between gap-2 rounded-xl border border-border bg-card p-2 shadow-xs","data-testid":`auth-config-user-field-${s.name}`,children:[(0,a.jsxs)("span",{className:"flex flex-col",children:[(0,a.jsx)("span",{className:"font-mono text-xs",children:s.name}),s.plugin!==void 0&&(0,a.jsx)("span",{className:"text-[11px] text-muted-foreground",children:s.plugin})]}),(0,a.jsxs)("span",{className:"flex items-center gap-1",children:[(0,a.jsx)(h,{variant:"outline",children:s.type}),s.required&&(0,a.jsx)(h,{variant:"secondary",children:t("required")}),s.unique&&(0,a.jsx)(h,{variant:"secondary",children:t("unique")})]})]},s.name))})}),(0,a.jsx)(y,{className:"gap-0 py-0",children:(0,a.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground","data-testid":"auth-config-note",children:t("OAuth providers, email templates, and rate limits are configured at deploy time in the better-auth setup and aren't editable here. See the Mail tab for email output.")})})]}),e[11]=l,e[12]=n,e[13]=m,e[14]=t,e[15]=x):x=e[15];let b;return e[16]!==p||e[17]!==f||e[18]!==x?(b=(0,a.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"auth-config",children:[p,f,x]}),e[16]=p,e[17]=f,e[18]=x,e[19]=b):b=e[19],b},"M");function L(e){return(0,a.jsx)(h,{"data-testid":`auth-config-plugin-${e}`,variant:"outline",children:e},e)}u(L,"P");function q(e){return(0,a.jsx)(h,{"data-testid":`auth-config-provider-${e}`,variant:"outline",children:e},e)}u(q,"z");export{T as AuthConfigPanel};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as ye}from"./chunk-V53KNYRN.js";import{a as we}from"./chunk-AREBQI6D.js";import{a as Ne}from"./chunk-RMN2JN4S.js";import{b as pe}from"./chunk-GRL5MG3Z.js";import"./chunk-7T7UOTYK.js";import"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import{c as ge}from"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import"./chunk-6ST5ECQA.js";import{a as H}from"./chunk-VDW32UET.js";import{d as be}from"./chunk-
|
|
1
|
+
import{a as ye}from"./chunk-V53KNYRN.js";import{a as we}from"./chunk-AREBQI6D.js";import{a as Ne}from"./chunk-RMN2JN4S.js";import{b as pe}from"./chunk-GRL5MG3Z.js";import"./chunk-7T7UOTYK.js";import"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import{c as ge}from"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import"./chunk-6ST5ECQA.js";import{a as H}from"./chunk-VDW32UET.js";import{d as be}from"./chunk-ZNAGZU6H.js";import{f as xe}from"./chunk-5KCULF7S.js";import"./chunk-XBDKZZ67.js";import{a as ne,e as ie}from"./chunk-UZERI5YC.js";import{d as he,f as ce,g as de,h as ee,o as me}from"./chunk-IUYFXK4X.js";import{c as ae}from"./chunk-XNGYYOLS.js";import{a,e as se,f as ve,g as je,h as Ee}from"./chunk-3XIESWL4.js";var Se=se(je(),1);var b=se(ve(),1);var r=se(Ee(),1);var Ce=ce(H.exportShard),Oe=ce(H.importShard),Te=a(x=>x.map(e=>JSON.stringify(e)).join(`
|
|
2
2
|
`),"je"),Ae=a(x=>{let e=[],te=x.split(`
|
|
3
3
|
`);for(let[n,N]of te.entries()){let t=N.trim();if(t==="")continue;let o=JSON.parse(t);if(typeof o!="object"||o===null)throw new ae("INTERNAL",`line ${(n+1).toString()}: expected a { table, doc } object`);let h=o;if(typeof h.table!="string"||typeof h.doc!="object"||h.doc===null||Array.isArray(h.doc))throw new ae("INTERNAL",`line ${(n+1).toString()}: expected a { table, doc } object`);e.push(h)}return e},"$e"),Me=a(x=>{let e=(0,Se.c)(94),{initialShardKey:te}=x,n=xe(),N=be(),t=he(),[o,h]=(0,b.useState)(te??""),[l,ue]=(0,b.useState)(""),[d,K]=(0,b.useState)(!1),[Q,M]=(0,b.useState)(null),[i,re]=(0,b.useState)(null),[w,fe]=(0,b.useState)(null),V;e[0]!==n||e[1]!==o?(V=a(async()=>{K(!0),M(null),re(null);try{let c=await n.query(Ce,{},de(o));pe(o),ue(Te(c.rows)),fe(c.rows.length)}catch(c){M(ee(c))}K(!1)},"Q"),e[0]=n,e[1]=o,e[2]=V):V=e[2];let z=V,W;e[3]!==n||e[4]!==N||e[5]!==l||e[6]!==o||e[7]!==t?(W=a(async()=>{K(!0),M(null),re(null),fe(null);let c;try{c=Ae(l)}catch(s){M(t("Invalid NDJSON: {message}",{message:ee(s)})),K(!1);return}try{let s=await n.query(Oe,{rows:c},de(o));pe(o),re(s),N(H.readTablePage),N(H.listTables)}catch(s){M(ee(s))}K(!1)},"V"),e[3]=n,e[4]=N,e[5]=l,e[6]=o,e[7]=t,e[8]=W):W=e[8];let G=W,y,S,I,m,v,p,u,j,E,f,C;if(e[9]!==d||e[10]!==w||e[11]!==z||e[12]!==i||e[13]!==G||e[14]!==l||e[15]!==o||e[16]!==t){let c=i===null?0:Object.values(i.inserted).reduce(Le,0),s;e[28]!==z?(s=a(()=>{me(z())},"s"),e[28]=z,e[29]=s):s=e[29];let oe=s,Y;e[30]!==G?(Y=a(()=>{me(G())},"X"),e[30]=G,e[31]=Y):Y=e[31];let le=Y,Z;e[32]===Symbol.for("react.memo_cache_sentinel")?(Z=a(g=>{ue(g.target.value)},"Y"),e[32]=Z):Z=e[32];let Ie=Z;C="flex flex-col gap-4",I="lunora-export-import";let L;e[33]!==t?(L=t("Export"),e[33]=t,e[34]=L):L=e[34];let $;e[35]!==L?($=(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:L})}),e[35]=L,e[36]=$):$=e[36];let J;e[37]!==o?(J=(0,r.jsx)(Ne,{onChange:h,testId:"ei-shard-input",value:o}),e[37]=o,e[38]=J):J=e[38];let k;e[39]!==t?(k=t("Export"),e[39]=t,e[40]=k):k=e[40];let D;e[41]!==d||e[42]!==oe||e[43]!==k?(D=(0,r.jsx)(ge,{"data-testid":"ei-export",disabled:d,onClick:oe,type:"button",children:k}),e[41]=d,e[42]=oe,e[43]=k,e[44]=D):D=e[44];let _;e[45]!==J||e[46]!==D?(_=(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[J,D]}),e[45]=J,e[46]=D,e[47]=_):_=e[47];let q;e[48]!==w||e[49]!==t?(q=w!==null&&(0,r.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"ei-export-result",children:t("Exported {count} rows.",{count:w})}),e[48]=w,e[49]=t,e[50]=q):q=e[50];let B;e[51]!==_||e[52]!==q?(B=(0,r.jsxs)(ie,{className:"flex flex-col gap-3 p-4",children:[_,q]}),e[51]=_,e[52]=q,e[53]=B):B=e[53],e[54]!==$||e[55]!==B?(m=(0,r.jsxs)(ne,{className:"rounded-xl border border-border bg-card shadow-xs",children:[$,B]}),e[54]=$,e[55]=B,e[56]=m):m=e[56],S=ne,E="rounded-xl border border-border bg-card shadow-xs";let P;e[57]!==t?(P=t("Import"),e[57]=t,e[58]=P):P=e[58],e[59]!==P?(f=(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:P})}),e[59]=P,e[60]=f):f=e[60],y=ie,v="flex flex-col gap-3 p-4",e[61]!==l?(p=(0,r.jsx)(ye,{"aria-label":"NDJSON",className:"font-mono text-xs min-h-40 rounded-md","data-testid":"ei-ndjson",onChange:Ie,placeholder:'{"table":"messages","doc":{\u2026}}',value:l}),e[61]=l,e[62]=p):p=e[62];let R;e[63]!==t?(R=t("Import (writes rows)?"),e[63]=t,e[64]=R):R=e[64];let U;e[65]!==d||e[66]!==l?(U=d||l.trim()==="",e[65]=d,e[66]=l,e[67]=U):U=e[67];let F;e[68]!==t?(F=t("Import"),e[68]=t,e[69]=F):F=e[69],e[70]!==le||e[71]!==R||e[72]!==U||e[73]!==F?(u=(0,r.jsx)("div",{className:"flex flex-wrap items-center gap-2",children:(0,r.jsx)(we,{confirmLabel:R,disabled:U,onConfirm:le,testId:"ei-import",children:F})}),e[70]=le,e[71]=R,e[72]=U,e[73]=F,e[74]=u):u=e[74],j=i!==null&&(0,r.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"ei-import-result",children:[(0,r.jsx)("p",{className:"text-sm text-muted-foreground",children:t("Inserted {inserted}, {conflicts} conflicts, {errors} errors.",{conflicts:i.conflicts,errors:i.errors.length,inserted:c})}),i.errors.length>0&&(0,r.jsx)("ul",{className:"flex flex-col gap-1","data-testid":"ei-import-errors",children:i.errors.map(g=>(0,r.jsx)("li",{className:"text-xs text-destructive",children:t("line {line} ({table}): {message}",{line:g.line,message:g.message,table:g.table})},`${g.table}-${g.line.toString()}`))})]}),e[9]=d,e[10]=w,e[11]=z,e[12]=i,e[13]=G,e[14]=l,e[15]=o,e[16]=t,e[17]=y,e[18]=S,e[19]=I,e[20]=m,e[21]=v,e[22]=p,e[23]=u,e[24]=j,e[25]=E,e[26]=f,e[27]=C}else y=e[17],S=e[18],I=e[19],m=e[20],v=e[21],p=e[22],u=e[23],j=e[24],E=e[25],f=e[26],C=e[27];let O;e[75]!==y||e[76]!==v||e[77]!==p||e[78]!==u||e[79]!==j?(O=(0,r.jsxs)(y,{className:v,children:[p,u,j]}),e[75]=y,e[76]=v,e[77]=p,e[78]=u,e[79]=j,e[80]=O):O=e[80];let T;e[81]!==S||e[82]!==O||e[83]!==E||e[84]!==f?(T=(0,r.jsxs)(S,{className:E,children:[f,O]}),e[81]=S,e[82]=O,e[83]=E,e[84]=f,e[85]=T):T=e[85];let A;e[86]!==Q?(A=Q!==null&&(0,r.jsx)("p",{className:"text-sm text-destructive","data-testid":"ei-error",role:"alert",children:Q}),e[86]=Q,e[87]=A):A=e[87];let X;return e[88]!==I||e[89]!==m||e[90]!==T||e[91]!==A||e[92]!==C?(X=(0,r.jsxs)("div",{className:C,"data-testid":I,children:[m,T,A]}),e[88]=I,e[89]=m,e[90]=T,e[91]=A,e[92]=C,e[93]=X):X=e[93],X},"Be");function Le(x,e){return x+e}a(Le,"Ee");export{Me as ExportImportPanel};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as f}from"./chunk-5Y3QLNWX.js";import{a as U}from"./chunk-54MMVNPT.js";import{a as C}from"./chunk-AREBQI6D.js";import{R as v}from"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import{c as O}from"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import{b as L}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as w}from"./chunk-VDW32UET.js";import{f as P}from"./chunk-
|
|
1
|
+
import{a as f}from"./chunk-5Y3QLNWX.js";import{a as U}from"./chunk-54MMVNPT.js";import{a as C}from"./chunk-AREBQI6D.js";import{R as v}from"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import{c as O}from"./chunk-FXCBF4XT.js";import"./chunk-2OUPA2WJ.js";import{b as L}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as w}from"./chunk-VDW32UET.js";import{f as P}from"./chunk-5KCULF7S.js";import"./chunk-XBDKZZ67.js";import{d as q,f as y,g as c,h,o as p}from"./chunk-IUYFXK4X.js";import"./chunk-XNGYYOLS.js";import{a as o,e as T,f as W,h as $}from"./chunk-3XIESWL4.js";var a=T(W(),1);var e=T($(),1);var R=y(w.getPitrBookmark),V=y(w.pitrRestore),ne=o(({initialShardKey:j})=>{let m=P(),r=q(),i=j??"",[z,x]=(0,a.useState)(null),[l,A]=(0,a.useState)(""),[B,I]=(0,a.useState)(null),[u,D]=(0,a.useState)(""),[k,E]=(0,a.useState)(!1),[s,K]=(0,a.useState)(null),[F,n]=(0,a.useState)(null),[b,d]=(0,a.useState)(!1),g=(0,a.useCallback)(async()=>{d(!0),n(null);try{let t=await m.query(R,{},c(i));x(t.current)}catch(t){n(h(t))}d(!1)},[m,i]);(0,a.useEffect)(()=>{p(g())},[g]),U(()=>{p((async()=>{try{let t=await m.query(R,{},c(i));x(t.current)}catch{}})())},!0);let M=o(t=>{A(t.target.value)},"U"),Z=o(t=>{D(t.target.value)},"j"),_=o(t=>{E(t.target.checked)},"M"),G=o(()=>{l.trim()!==""&&p((async()=>{d(!0),n(null);try{let t=await m.query(R,{time:l.trim()},c(i));I(t.forTime??null),x(t.current)}catch(t){I(null),n(h(t))}d(!1)})())},"z"),S=o(t=>{p((async()=>{d(!0),n(null);try{let N=await m.mutation(V,t,c(i));K(N),await g()}catch(N){n(h(N))}d(!1)})())},"R"),H=u.trim()!==""||l.trim()!=="",J=o(()=>{let t=k?{restart:!0}:{};u.trim()===""?t.time=l.trim():t.bookmark=u.trim(),S(t)},"$"),Q=o(()=>{s!==null&&S(k?{bookmark:s.undoBookmark,restart:!0}:{bookmark:s.undoBookmark})},"D");return(0,e.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-pitr",children:[(0,e.jsx)("div",{className:"flex flex-wrap items-center gap-3",children:(0,e.jsxs)("span",{className:"text-xs text-muted-foreground",children:[r("Shard"),": ",(0,e.jsx)("span",{className:"font-mono",children:i===""?r("root"):i})]})}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"pitr-note",children:r("In-place recovery to any moment in the last 30 days. For older or portable recovery, use the snapshot backup tier.")}),F!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"pitr-error",role:"alert",children:F}),(0,e.jsxs)("section",{className:"rounded-xl border border-border bg-card p-3 shadow-xs",children:[(0,e.jsx)("h3",{className:"mb-2 text-sm font-semibold",children:r("Current bookmark")}),(0,e.jsx)("p",{className:"font-mono text-xs break-all text-muted-foreground","data-testid":"pitr-current",children:z??(0,e.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})})]}),(0,e.jsxs)("section",{className:"flex flex-col gap-3 rounded-xl border border-border bg-card p-3 shadow-xs",children:[(0,e.jsx)("h3",{className:"text-sm font-semibold",children:r("Restore")}),(0,e.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,e.jsx)(f,{htmlFor:"pitr-time",children:r("Time (ISO or epoch-ms, last 30 days)")}),(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)(v,{"data-testid":"pitr-time",id:"pitr-time",onChange:M,placeholder:"2026-06-01T00:00:00.000Z",value:l}),(0,e.jsx)(O,{"data-testid":"pitr-preview",disabled:b||l.trim()==="",onClick:G,size:"sm",type:"button",variant:"outline",children:r("Preview")})]}),B!==null&&(0,e.jsxs)("p",{className:"font-mono text-xs break-all text-muted-foreground","data-testid":"pitr-preview-bookmark",children:[r("Bookmark for that time"),": ",B]})]}),(0,e.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,e.jsx)(f,{htmlFor:"pitr-bookmark",children:r("Or an explicit bookmark (wins over time)")}),(0,e.jsx)(v,{"data-testid":"pitr-bookmark",id:"pitr-bookmark",onChange:Z,placeholder:r("bookmark string"),value:u})]}),(0,e.jsxs)(f,{className:"flex items-center gap-2 text-xs font-normal text-muted-foreground",htmlFor:"pitr-restart",children:[(0,e.jsx)("input",{checked:k,className:"size-4 accent-primary","data-testid":"pitr-restart",id:"pitr-restart",onChange:_,type:"checkbox"}),r("Restart the shard now so recovery applies immediately")]}),(0,e.jsx)("div",{children:(0,e.jsx)(C,{confirmLabel:r("Confirm restore"),disabled:b||!H,onConfirm:J,testId:"pitr-restore",children:r("Restore")})})]}),s!==null&&(0,e.jsxs)("section",{className:"flex flex-col gap-2 rounded-xl border border-border bg-card p-3 shadow-xs","data-testid":"pitr-result",children:[(0,e.jsxs)("div",{className:"flex items-center gap-2",children:[(0,e.jsx)("h3",{className:"text-sm font-semibold",children:r("Restore armed")}),(0,e.jsx)(L,{variant:s.restarted?"destructive":"secondary",children:s.restarted?r("restarted now"):r("on next restart")})]}),(0,e.jsxs)("p",{className:"font-mono text-xs break-all text-muted-foreground",children:[r("Restored to"),": ",s.restoredTo]}),(0,e.jsxs)("p",{className:"font-mono text-xs break-all text-muted-foreground","data-testid":"pitr-undo-bookmark",children:[r("Undo bookmark"),": ",s.undoBookmark]}),(0,e.jsx)("div",{children:(0,e.jsx)(C,{confirmLabel:r("Confirm undo"),disabled:b,onConfirm:Q,testId:"pitr-undo",children:r("Undo restore")})})]})]})},"de");export{ne as PitrPanel};
|