@lunora/studio 1.0.0-alpha.224 → 1.0.0-alpha.226
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +7 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.mjs +1 -1
- package/dist/packem_chunks/FileBrowser.mjs +4 -4
- package/dist/packem_chunks/SchemaViewer.mjs +1 -1
- package/dist/packem_chunks/TableEditor.mjs +1 -1
- package/dist/packem_chunks/permissions-panel.mjs +1 -1
- package/dist/packem_chunks/vector-browser.mjs +1 -1
- package/dist/packem_chunks/workflows-panel.mjs +1 -1
- package/dist/packem_shared/DataBrowser-B5Sl4vMa.mjs +4 -0
- package/dist/packem_shared/DataFilters-CYZFt2EK.mjs +1 -0
- package/dist/packem_shared/{GlobalDataBrowser-CR138dEZ.mjs → GlobalDataBrowser-BzhSVDvF.mjs} +1 -1
- package/dist/packem_shared/table-list-sidebar-CYRSPLIv.mjs +1 -0
- package/dist/standalone/{chunk-GFB3DJBT.js → chunk-224DF7HD.js} +1 -1
- package/dist/standalone/{chunk-WM5HSIP3.js → chunk-2AGQJ3RT.js} +1 -1
- package/dist/standalone/{chunk-QOQ56UE7.js → chunk-2ZMIQJFC.js} +1 -1
- package/dist/standalone/{chunk-NHLLFFXW.js → chunk-37TUKSUI.js} +1 -1
- package/dist/standalone/{chunk-FZAGSACU.js → chunk-3KA25M2D.js} +1 -1
- package/dist/standalone/{chunk-I7GBAQ72.js → chunk-3WDNFRIY.js} +1 -1
- package/dist/standalone/{chunk-VVQBWSND.js → chunk-56GQC4TY.js} +1 -1
- package/dist/standalone/{chunk-KJOMRSX7.js → chunk-5DXMAKEG.js} +1 -1
- package/dist/standalone/{chunk-G6JWVIBX.js → chunk-5TBTVXMF.js} +1 -1
- package/dist/standalone/{chunk-IL34SD2J.js → chunk-6CP4FGVV.js} +1 -1
- package/dist/standalone/{chunk-FMEXQNO7.js → chunk-6I6SDCXD.js} +1 -1
- package/dist/standalone/{chunk-Q5H5UZCT.js → chunk-6OQCFS5H.js} +1 -1
- package/dist/standalone/{chunk-E6YTK54J.js → chunk-6QBEY5L3.js} +1 -1
- package/dist/standalone/{chunk-27ILKCWI.js → chunk-6R3CL5GW.js} +1 -1
- package/dist/standalone/{chunk-SB535MB2.js → chunk-AM3Q2SY4.js} +1 -1
- package/dist/standalone/{chunk-CFYXGSV3.js → chunk-AOSUYLNV.js} +1 -1
- package/dist/standalone/{chunk-JL7WQ35Y.js → chunk-BDNFSPL2.js} +1 -1
- package/dist/standalone/{chunk-UWHH6R7J.js → chunk-IKFXSK5G.js} +1 -1
- package/dist/standalone/{chunk-OMTRTMGC.js → chunk-INWZFRAK.js} +1 -1
- package/dist/standalone/{chunk-PCYB6Q5V.js → chunk-IU6UCL3Z.js} +1 -1
- package/dist/standalone/{chunk-EVGASJNW.js → chunk-JH4ISCW2.js} +1 -1
- package/dist/standalone/chunk-JJGVOQY3.js +5 -0
- package/dist/standalone/{chunk-WQ6OGGRQ.js → chunk-JPQR4RYQ.js} +1 -1
- package/dist/standalone/{chunk-WXDKJUXF.js → chunk-JSVP2IDG.js} +1 -1
- package/dist/standalone/{chunk-QWBMBXUI.js → chunk-JYEDDOSG.js} +1 -1
- package/dist/standalone/{chunk-RFNTIPZM.js → chunk-JYP5EIUU.js} +1 -1
- package/dist/standalone/{chunk-FQEKYLWQ.js → chunk-KCQSTV6F.js} +1 -1
- package/dist/standalone/{chunk-WRSH2CJD.js → chunk-KDBCB6FG.js} +1 -1
- package/dist/standalone/chunk-KZW3DDZ5.js +1 -0
- package/dist/standalone/{chunk-3UW7JOCC.js → chunk-LZZWCAZX.js} +1 -1
- package/dist/standalone/chunk-MZP4J6RB.js +1 -0
- package/dist/standalone/{chunk-4YXKODH3.js → chunk-NXN6ZECT.js} +1 -1
- package/dist/standalone/{chunk-WLLOZ3HS.js → chunk-OQWQT3II.js} +1 -1
- package/dist/standalone/{chunk-KTBJ5SQO.js → chunk-OT2A56S3.js} +1 -1
- package/dist/standalone/chunk-P5RFX2G3.js +1 -0
- package/dist/standalone/{chunk-74CQY3AB.js → chunk-P6ONKKHY.js} +1 -1
- package/dist/standalone/{chunk-OBUY7UZO.js → chunk-PITC2AP5.js} +1 -1
- package/dist/standalone/{chunk-2LJKZSU4.js → chunk-Q4WSPRIT.js} +1 -1
- package/dist/standalone/{chunk-GQWFRBCJ.js → chunk-QDAW2ZP3.js} +1 -1
- package/dist/standalone/chunk-RATPWNIM.js +9 -0
- package/dist/standalone/chunk-RT6BD4RL.js +1 -0
- package/dist/standalone/{chunk-INHSAPFB.js → chunk-RTCWTRPH.js} +1 -1
- package/dist/standalone/{chunk-S6ZFBF3S.js → chunk-S54AMHYS.js} +1 -1
- package/dist/standalone/{chunk-3G3KM5QW.js → chunk-SERBKIWI.js} +1 -1
- package/dist/standalone/{chunk-D6Z2ZUU7.js → chunk-TL5ZV6DR.js} +1 -1
- package/dist/standalone/{chunk-KME5TGGZ.js → chunk-TP7KHFWY.js} +1 -1
- package/dist/standalone/{chunk-UTIAX6IO.js → chunk-VNWWQQJR.js} +1 -1
- package/dist/standalone/{chunk-RK5UUSYK.js → chunk-W3A4SIKT.js} +1 -1
- package/dist/standalone/{chunk-SL2WTTEZ.js → chunk-WGN2KDQO.js} +1 -1
- package/dist/standalone/{chunk-SWS6R7OJ.js → chunk-WTBOHRI6.js} +1 -1
- package/dist/standalone/chunk-WWH4SBK2.js +4 -0
- package/dist/standalone/{chunk-TSNKMJKC.js → chunk-XBVXA2OK.js} +1 -1
- package/dist/standalone/{chunk-7FTSNUL7.js → chunk-XD7F5ZP5.js} +1 -1
- package/dist/standalone/{chunk-7UHE2RRI.js → chunk-XNWVQHXW.js} +1 -1
- package/dist/standalone/{chunk-2OW5U2BZ.js → chunk-YD77YQGV.js} +1 -1
- package/dist/standalone/{chunk-KDY4VSAF.js → chunk-ZA3NKULE.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/dist/styles.css +1 -1
- package/package.json +3 -3
- package/dist/packem_shared/DataBrowser-DWSaSSRj.mjs +0 -4
- package/dist/packem_shared/DataFilters-Cocu-WWE.mjs +0 -1
- package/dist/packem_shared/table-list-sidebar-DxvakjpR.mjs +0 -1
- package/dist/standalone/chunk-2ZFFWSLG.js +0 -1
- package/dist/standalone/chunk-3EDFZHY5.js +0 -5
- package/dist/standalone/chunk-DG5KSS6E.js +0 -1
- package/dist/standalone/chunk-EBNWZ33C.js +0 -1
- package/dist/standalone/chunk-FS4K5TEX.js +0 -1
- package/dist/standalone/chunk-NZKXQEZ5.js +0 -9
- package/dist/standalone/chunk-OIHA5CMU.js +0 -4
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{a as ae}from"./chunk-EA2JKR5D.js";import{W as ee}from"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import{a as O}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import"./chunk-225VJ77I.js";import{a as K}from"./chunk-4ZEL6BYL.js";import{c as te}from"./chunk-27ILKCWI.js";import{f as M}from"./chunk-NZKXQEZ5.js";import"./chunk-FSRSK4LY.js";import"./chunk-5ICUJ4IA.js";import{a as P}from"./chunk-FKVZRPV5.js";import{a as j,b as D,c as F,d as h,e as o,f as i}from"./chunk-HEAQVSNS.js";import{a as E,e as _}from"./chunk-WUWBZPUK.js";import{d as H,f as Q,g as V,h as W,m as X,p as $}from"./chunk-PTZD7RUZ.js";import{a as n,d as Z,e as le,g as oe}from"./chunk-YKXDMIHQ.js";var c=Z(le(),1);var e=Z(oe(),1);var ie=["queued","running","paused","waiting","complete","errored","terminated"],de=["pause","resume","terminate"],ce="WORKFLOWS_NOT_CONFIGURED",me=n(l=>typeof l=="object"&&l!==null&&l.code===ce,"de"),ue=n(l=>{let r=l.error??l.output;if(r===void 0)return"\u2014";try{return JSON.stringify(r,X)}catch{return"(unserializable)"}},"ce"),fe=n(({loadDetail:l,loadInstances:r,readOnly:N,runAction:L,workflowName:g})=>{let A=M(),s=H(),[p,k]=(0,c.useState)(null),[S,C]=(0,c.useState)(null),[v,z]=(0,c.useState)(""),[b,f]=(0,c.useState)(null),[J,I]=(0,c.useState)(!1),[R,U]=(0,c.useState)(null),x=l??(a=>A.getWorkflowInstance(a)),w=N?void 0:L??(r===void 0?a=>A.setWorkflowInstanceStatus(a):void 0),T=n(async()=>{f(null),I(!1);let a=v===""?void 0:v;try{if(r===void 0){let d=await A.listWorkflowInstances({name:g,status:a});if(d.configured===!1){k(null),I(!0);return}k(d.instances);return}k(await r({name:g,status:a}))}catch(d){k(null),me(d)?I(!0):f(W(d))}},"L");(0,c.useEffect)(()=>{C(null),$(T())},[g,v]);let q=n(async a=>{f(null);try{C(await x({id:a,name:g}))}catch(d){f(W(d))}},"K"),B=n(async(a,d)=>{if(w!==void 0){U(a),f(null);try{await w({action:d,id:a,name:g}),await T()}catch(G){f(W(G))}U(null)}},"q");return(0,e.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-workflow-instances",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,e.jsx)("h3",{className:"text-sm font-medium",children:s("Instance history")}),(0,e.jsxs)("select",{"aria-label":s("Filter by status"),className:"h-8 rounded-md border border-input bg-transparent px-2.5 py-1 text-xs outline-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50","data-testid":"workflow-instances-filter",onChange:n(a=>{z(a.target.value)},"onChange"),value:v,children:[(0,e.jsx)("option",{value:"",children:s("All statuses")}),ie.map(a=>(0,e.jsx)("option",{value:a,children:a},a))]})]}),b!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"workflow-instances-error",role:"alert",children:b}),J&&(0,e.jsx)(P,{description:s("Set CLOUDFLARE_ACCOUNT_ID and CLOUDFLARE_API_TOKEN in your .dev.vars to enable workflow instance history."),testId:"workflow-instances-unconfigured",title:s("Workflow inspection not configured")}),!J&&p!==null&&p.length===0&&(0,e.jsx)(P,{description:s("No instances match this filter for the selected workflow."),testId:"workflow-instances-empty",title:s("No instances")}),p!==null&&p.length>0&&(0,e.jsx)(E,{className:"overflow-hidden py-0",children:(0,e.jsx)(_,{className:"px-0",children:(0,e.jsxs)(j,{"data-testid":"workflow-instances-table",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(h,{children:[(0,e.jsx)(o,{children:s("Instance id")}),(0,e.jsx)(o,{children:s("Status")}),(0,e.jsx)(o,{children:s("Created")}),(0,e.jsx)(o,{children:s("Ended")}),(0,e.jsx)(o,{"aria-label":s("Actions")})]})}),(0,e.jsx)(F,{children:p.map(a=>(0,e.jsxs)(h,{"data-testid":`workflow-instance-${a.id}`,children:[(0,e.jsx)(i,{className:"font-mono text-xs",children:a.id}),(0,e.jsx)(i,{className:"font-mono text-xs",children:a.status}),(0,e.jsx)(i,{className:"text-muted-foreground tabular-nums",children:a.createdOn??"\u2014"}),(0,e.jsx)(i,{className:"text-muted-foreground tabular-nums",children:a.endedOn??"\u2014"}),(0,e.jsx)(i,{className:"text-right",children:(0,e.jsxs)("div",{className:"flex justify-end gap-1.5",children:[(0,e.jsx)(O,{"data-testid":`workflow-instance-steps-${a.id}`,onClick:n(()=>{$(q(a.id))},"onClick"),size:"sm",type:"button",variant:"outline",children:s("Steps")}),w!==void 0&&de.map(d=>(0,e.jsx)(O,{"data-testid":`workflow-instance-${d}-${a.id}`,disabled:R===a.id,onClick:n(()=>{$(B(a.id,d))},"onClick"),size:"sm",type:"button",variant:"ghost",children:s(d)},d))]})})]},a.id))})]})})}),S!==null&&(0,e.jsx)(E,{className:"overflow-hidden py-0","data-testid":"workflow-instance-detail",children:(0,e.jsxs)(_,{className:"flex flex-col gap-2 px-4 py-3",children:[(0,e.jsxs)("div",{className:"flex items-center justify-between",children:[(0,e.jsxs)("span",{className:"font-mono text-xs",children:[s("Steps")," \xB7 ",S.id]}),(0,e.jsx)(O,{"data-testid":"workflow-instance-detail-close",onClick:n(()=>{C(null)},"onClick"),size:"xs",type:"button",variant:"ghost",children:s("Close")})]}),S.steps.length===0?(0,e.jsx)("p",{className:"text-xs text-muted-foreground",children:s("This instance has no recorded steps yet.")}):(0,e.jsxs)(j,{"data-testid":"workflow-instance-steps",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(h,{children:[(0,e.jsx)(o,{children:s("Step")}),(0,e.jsx)(o,{children:s("Type")}),(0,e.jsx)(o,{children:s("Attempts")}),(0,e.jsx)(o,{children:s("Started")}),(0,e.jsx)(o,{children:s("Output")})]})}),(0,e.jsx)(F,{children:S.steps.map((a,d)=>(0,e.jsxs)(h,{"data-testid":`workflow-step-${String(d)}`,children:[(0,e.jsx)(i,{className:"font-mono text-xs",children:a.name}),(0,e.jsx)(i,{className:"text-xs text-muted-foreground",children:a.type??"\u2014"}),(0,e.jsx)(i,{className:"tabular-nums",children:a.attempts??"\u2014"}),(0,e.jsx)(i,{className:"text-muted-foreground tabular-nums",children:a.start??"\u2014"}),(0,e.jsx)(i,{className:"font-mono text-xs text-muted-foreground",children:ue(a)})]},`${a.name}:${String(d)}`))})]})]})})]})},"me"),he=Q(K.createWorkflowInstance),pe=Q(K.getWorkflowInstanceStatus),xe=n(l=>{if(l.error)return`${l.error.name}: ${l.error.message}`;if(l.output===void 0)return"\u2014";try{return JSON.stringify(l.output,X)}catch{return"(unserializable)"}},"he"),we=n((l,r)=>l.some(N=>N.exportName===r)?r:l[0]?.exportName??"","pe"),$e=n(()=>{let l=M(),r=H(),{data:N,error:L}=te(K.listWorkflows,{}),[g,A]=(0,c.useState)(""),[s,p]=(0,c.useState)(""),[k,S]=(0,c.useState)(""),[C,v]=(0,c.useState)(!1),[z,b]=(0,c.useState)(null),[f,J]=(0,c.useState)([]),[I,R]=(0,c.useState)(null),U=N!==void 0,x=Array.isArray(N?.workflows)?[...N.workflows].toSorted((t,u)=>t.exportName.localeCompare(u.exportName)):[],w=we(x,g),T=x.find(t=>t.exportName===w),q=n(t=>{J(u=>{let m=u.filter(y=>!(y.exportName===t.exportName&&y.id===t.id));return[t,...m]})},"C"),B=n(async()=>{let t=w;if(t==="")return;let u,m=k.trim();if(m!=="")try{u=JSON.parse(m)}catch{b(r("Params must be valid JSON"));return}v(!0),b(null);try{let y=s.trim(),Y=await l.query(he,{exportName:t,id:y===""?void 0:y,params:u},V(""));q({exportName:t,id:Y.id,status:Y.status}),p("")}catch(y){b(W(y))}v(!1)},"L"),a=n(()=>{$(B())},"K"),d=n(async(t,u)=>{R(u);try{let m=await l.query(pe,{exportName:t,id:u},V(""));q({error:m.error,exportName:t,id:m.id,output:m.output,status:m.status})}catch(m){b(W(m))}R(null)},"q"),G=n(t=>{A(t.target.value)},"r"),re=n(t=>{p(t.target.value)},"l"),se=n(t=>{S(t.target.value)},"G"),ne=n(t=>{let{export:u,id:m}=t.currentTarget.dataset;u!==void 0&&m!==void 0&&$(d(u,m))},"te");return(0,e.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-workflows-panel",children:[L!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"workflows-error",role:"alert",children:L}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:r("Workflows are declared in code with defineWorkflow and run as durable Cloudflare Workflows. Start an instance and observe its status below.")}),U&&x.length===0?(0,e.jsx)(P,{description:r("No defineWorkflow is declared in lunora/workflows.ts in this deployment. Add one to run a durable, multi-step workflow."),testId:"workflows-empty",title:r("No workflows defined")}):(0,e.jsx)(E,{className:"overflow-hidden py-0",children:(0,e.jsx)(_,{className:"px-0",children:(0,e.jsxs)(j,{"data-testid":"workflows-table",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(h,{children:[(0,e.jsx)(o,{children:r("Export")}),(0,e.jsx)(o,{children:r("Name")}),(0,e.jsx)(o,{children:r("Class")}),(0,e.jsx)(o,{children:r("Binding")})]})}),(0,e.jsx)(F,{children:x.map(t=>(0,e.jsxs)(h,{"data-testid":`workflows-row-${t.exportName}`,children:[(0,e.jsx)(i,{className:"font-mono text-xs",children:t.exportName}),(0,e.jsx)(i,{className:"font-mono text-xs text-muted-foreground",children:t.name}),(0,e.jsx)(i,{className:"font-mono text-xs text-muted-foreground",children:t.className}),(0,e.jsx)(i,{className:"font-mono text-xs text-muted-foreground",children:t.binding})]},t.exportName))})]})})}),x.length>0&&(0,e.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"workflows-start",children:[(0,e.jsx)("h3",{className:"text-sm font-medium",children:r("Start instance")}),z!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"workflows-start-error",role:"alert",children:z}),(0,e.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,e.jsx)("select",{"aria-label":r("Workflow"),className:"h-8 rounded-md border border-input bg-transparent px-2.5 py-1 text-xs outline-none focus-visible:border-ring focus-visible:ring-1 focus-visible:ring-ring/50","data-testid":"workflows-start-select",onChange:G,value:w,children:x.map(t=>(0,e.jsx)("option",{value:t.exportName,children:t.exportName},t.exportName))}),(0,e.jsx)(ee,{"aria-label":r("Instance id (optional)"),className:"max-w-48","data-testid":"workflows-start-id",onChange:re,placeholder:r("Instance id (optional)"),value:s}),(0,e.jsx)(O,{"data-testid":"workflows-start-button",disabled:C||w==="",onClick:a,children:r(C?"Starting\u2026":"Start instance")})]}),(0,e.jsx)(ae,{"aria-label":r("Params (JSON)"),className:"font-mono","data-testid":"workflows-start-params",onChange:se,placeholder:r("Params (JSON, optional)"),value:k})]}),f.length>0&&(0,e.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"workflows-instances",children:[(0,e.jsx)("h3",{className:"text-sm font-medium",children:r("Instances")}),(0,e.jsx)(E,{className:"overflow-hidden py-0",children:(0,e.jsx)(_,{className:"px-0",children:(0,e.jsxs)(j,{"data-testid":"workflows-instances-table",children:[(0,e.jsx)(D,{children:(0,e.jsxs)(h,{children:[(0,e.jsx)(o,{children:r("Workflow")}),(0,e.jsx)(o,{children:r("Instance id")}),(0,e.jsx)(o,{children:r("Status")}),(0,e.jsx)(o,{children:r("Output")}),(0,e.jsx)(o,{})]})}),(0,e.jsx)(F,{children:f.map(t=>(0,e.jsxs)(h,{"data-testid":`workflows-instance-${t.id}`,children:[(0,e.jsx)(i,{className:"font-mono text-xs",children:t.exportName}),(0,e.jsx)(i,{className:"font-mono text-xs text-muted-foreground",children:t.id}),(0,e.jsx)(i,{className:"font-mono text-xs",children:t.status}),(0,e.jsx)(i,{className:"font-mono text-xs text-muted-foreground",children:xe(t)}),(0,e.jsx)(i,{children:(0,e.jsx)(O,{"data-export":t.exportName,"data-id":t.id,"data-testid":`workflows-instance-refresh-${t.id}`,disabled:I===t.id,onClick:ne,size:"xs",variant:"outline",children:I===t.id?r("Refreshing\u2026"):r("Refresh")})})]},`${t.exportName}:${t.id}`))})]})})})]}),T!==void 0&&(0,e.jsx)(fe,{workflowName:T.name})]})},"Ee");export{$e as default};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{W as K}from"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import{a as Q}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import"./chunk-225VJ77I.js";import{f as z}from"./chunk-NZKXQEZ5.js";import"./chunk-FSRSK4LY.js";import"./chunk-5ICUJ4IA.js";import{a as W}from"./chunk-FKVZRPV5.js";import{a as q,b as B,c as L,d as f,e as c,f as d}from"./chunk-HEAQVSNS.js";import{a as I,e as j}from"./chunk-WUWBZPUK.js";import{d as F,h as S,o as Z,p as V}from"./chunk-PTZD7RUZ.js";import{a as h,d as C,e as U,f as G,g as J}from"./chunk-YKXDMIHQ.js";var A=C(G(),1);var n=C(U(),1);var e=C(J(),1);var X=10,g=h(v=>{let l=(0,A.c)(7),{label:m,value:a}=v,r;l[0]!==m?(r=(0,e.jsx)("span",{className:"font-mono text-[11px] uppercase tracking-wide text-muted-foreground",children:m}),l[0]=m,l[1]=r):r=l[1];let p=a??"\u2014",s;l[2]!==p?(s=(0,e.jsx)("span",{className:"font-mono text-sm",children:p}),l[2]=p,l[3]=s):s=l[3];let u;return l[4]!==r||l[5]!==s?(u=(0,e.jsxs)("div",{className:"flex flex-col gap-0.5",children:[r,s]}),l[4]=r,l[5]=s,l[6]=u):u=l[6],u},"g"),se=h(({loadIndexes:v,runQuery:l}={})=>{let m=z(),a=F(),[r,p]=(0,n.useState)(null),[s,u]=(0,n.useState)(null),[N,E]=(0,n.useState)(null),[b,D]=(0,n.useState)(""),[x,y]=(0,n.useState)(null),[M,w]=(0,n.useState)(null),[T,$]=(0,n.useState)(!1);(0,n.useEffect)(()=>{let t={cancelled:!1};return V((async()=>{try{let i=await(v??(()=>m.listVectorIndexes()))();t.cancelled||(p(i),u(null),E(k=>k??i[0]?.name??null))}catch(i){t.cancelled||(p(null),u(S(i)))}})()),()=>{t.cancelled=!0}},[m,v]);let o=r?.find(t=>t.name===N)??null,H=h(t=>{E(t.currentTarget.dataset.index??null),y(null),w(null)},"Q"),O=h(t=>{D(t.target.value)},"$"),P=h(async()=>{let t=b.trim();if(!(N===null||t==="")){$(!0),w(null);try{let i=await(l??(k=>m.queryVectorIndex(k)))({name:N,text:t,topK:X});y(i)}catch(i){y(null),w(S(i))}$(!1)}},"A"),R=h(()=>{V(P())},"D");return(0,e.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-vector-browser",children:[s!==null&&(0,e.jsx)("p",{className:"text-sm text-destructive","data-testid":"vector-error",role:"alert",children:s}),r!==null&&r.length===0&&(0,e.jsx)(W,{description:a("Indexes declared with .vectorize() or defineVectorIndex() appear here."),icon:(0,e.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,e.jsx)("path",{d:"M4 7l8-4 8 4-8 4-8-4Zm0 5 8 4 8-4M4 17l8 4 8-4"})}),testId:"vector-empty",title:a("No vector indexes.")}),r!==null&&r.length>0&&(0,e.jsx)(I,{className:"overflow-hidden py-0",children:(0,e.jsx)(j,{className:"px-0",children:(0,e.jsxs)(q,{"data-testid":"vector-table",children:[(0,e.jsx)(B,{children:(0,e.jsxs)(f,{children:[(0,e.jsx)(c,{children:a("name")}),(0,e.jsx)(c,{children:a("table")}),(0,e.jsx)(c,{children:a("dimensions")}),(0,e.jsx)(c,{children:a("metric")}),(0,e.jsx)(c,{children:a("vectors")})]})}),(0,e.jsx)(L,{children:r.map(t=>(0,e.jsxs)(f,{className:t.name===N?"border-l-2 border-l-royal-amethyst bg-muted/50":"cursor-pointer","data-index":t.name,"data-testid":`vector-row-${t.name}`,onClick:H,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:t.name}),(0,e.jsx)(d,{className:"font-mono text-xs",children:t.table}),(0,e.jsx)(d,{className:"tabular-nums",children:t.dimensions??"\u2014"}),(0,e.jsx)(d,{children:t.metric??"\u2014"}),(0,e.jsx)(d,{className:"tabular-nums",children:t.vectorsCount??"\u2014"})]},t.name))})]})})}),o!==null&&(0,e.jsxs)("section",{className:"border border-border bg-card p-3","data-testid":"vector-detail",children:[(0,e.jsxs)("div",{className:"grid grid-cols-2 gap-3 sm:grid-cols-4",children:[(0,e.jsx)(g,{label:a("field"),value:o.field}),(0,e.jsx)(g,{label:a("dimensions"),value:o.dimensions}),(0,e.jsx)(g,{label:a("metric"),value:o.metric}),(0,e.jsx)(g,{label:a("vectors"),value:o.vectorsCount})]}),o.metadata!==void 0&&o.metadata.length>0&&(0,e.jsxs)("p",{className:"mt-3 text-xs text-muted-foreground","data-testid":"vector-metadata",children:[a("metadata"),": ",(0,e.jsx)("span",{className:"font-mono",children:o.metadata.join(", ")})]}),(0,e.jsxs)("div",{className:"mt-3 flex flex-wrap items-center gap-2",children:[(0,e.jsx)(K,{className:"min-w-[18rem] flex-1","data-testid":"vector-query-input",onChange:O,placeholder:a("Search by similarity\u2026"),value:b}),(0,e.jsx)(Q,{"data-testid":"vector-search",disabled:T||b.trim()==="",onClick:R,children:a(T?"Searching\u2026":"Search")})]}),M!==null&&(0,e.jsx)("p",{className:"mt-2 text-sm text-destructive","data-testid":"vector-query-error",role:"alert",children:M}),x!==null&&x.length===0&&(0,e.jsx)("p",{className:"mt-2 text-sm text-muted-foreground","data-testid":"vector-no-matches",children:a("No matches.")}),x!==null&&x.length>0&&(0,e.jsx)(I,{className:"mt-3 overflow-hidden py-0",children:(0,e.jsx)(j,{className:"px-0",children:(0,e.jsxs)(q,{"data-testid":"vector-matches",children:[(0,e.jsx)(B,{children:(0,e.jsxs)(f,{children:[(0,e.jsx)(c,{children:a("id")}),(0,e.jsx)(c,{children:a("score")}),(0,e.jsx)(c,{children:a("metadata")})]})}),(0,e.jsx)(L,{children:x.map(t=>(0,e.jsxs)(f,{"data-testid":`vector-match-${t.id}`,children:[(0,e.jsx)(d,{className:"font-mono text-xs",children:t.id}),(0,e.jsx)(d,{className:"tabular-nums",children:t.score.toFixed(4)}),(0,e.jsx)(d,{className:"max-w-md truncate font-mono text-xs",children:t.metadata===void 0?"\u2014":Z(t.metadata)})]},t.id))})]})})})]})]})},"se");export{se as VectorBrowser};
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import{a as _t,d as y}from"./chunk-5ICUJ4IA.js";import{a as o,d as L,e as ie,f as Dt,g as ze}from"./chunk-YKXDMIHQ.js";var q=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 q{static{o(this,"FocusManager")}#e;#t;#s;constructor(){super(),this.#s=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.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#e!==t&&(this.#e=t,this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},oe=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)}},j=new mr;function Ut(t){setTimeout(t,0)}o(Ut,"systemSetTimeoutZero");var Ge=typeof window>"u"||"Deno"in globalThis;function C(){}o(C,"noop");function jt(t,e){return typeof t=="function"?t(e):t}o(jt,"functionalUpdate");function pe(t){return typeof t=="number"&&t>=0&&t!==1/0}o(pe,"isValidTimeout");function Ie(t,e){return Math.max(t+(e||0)-Date.now(),0)}o(Ie,"timeUntilStale");function U(t,e){return typeof t=="function"?t(e):t}o(U,"resolveStaleTime");function I(t,e){return typeof t=="function"?t(e):t}o(I,"resolveQueryBoolean");function Oe(t,e){let{type:s="all",exact:r,fetchStatus:i,predicate:n,queryKey:a,stale:c}=t;if(a){if(r){if(e.queryHash!==me(a,e.options))return!1}else if(!G(e.queryKey,a))return!1}if(s!=="all"){let u=e.isActive();if(s==="active"&&!u||s==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||n&&!n(e))}o(Oe,"matchQuery");function Re(t,e){let{exact:s,status:r,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(s){if(ne(e.options.mutationKey)!==ne(n))return!1}else if(!G(e.options.mutationKey,n))return!1}return!(r&&e.state.status!==r||i&&!i(e))}o(Re,"matchMutation");function me(t,e){return(e?.queryKeyHashFn||ne)(t)}o(me,"hashQueryKeyByOptions");function ne(t){return JSON.stringify(t,(e,s)=>Ve(s)?Object.keys(s).sort().reduce((r,i)=>(r[i]=s[i],r),{}):s)}o(ne,"hashKey");function G(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){for(let r=0;r<e.length;r++)if(!G(t[r],e[r]))return!1;return!0}let s=Object.keys(e);for(let r of s)if(!G(t[r],e[r]))return!1;return!0}return!1}o(G,"partialMatchKey");var yr=Object.prototype.hasOwnProperty;function Je(t,e,s=0){if(t===e)return t;if(s>500)return e;let r=Nt(t)&&Nt(e);if(!r&&!(Ve(t)&&Ve(e)))return e;let n=(r?t:Object.keys(t)).length,a=r?e:Object.keys(e),c=a.length,u=r?new Array(c):{},h=0;for(let d=0;d<c;d++){let l=r?d:a[d],f=t[l],p=e[l];if(f===p){u[l]=f,(r?d<n:yr.call(t,l))&&h++;continue}if(f===null||p===null||typeof f!="object"||typeof p!="object"){u[l]=p;continue}let m=Je(f,p,s+1);u[l]=m,m===f&&h++}return n===c&&h===n?t:u}o(Je,"replaceEqualDeep");function Ae(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let s in t)if(t[s]!==e[s])return!1;return!0}o(Ae,"shallowEqualObjects");function Nt(t){return Array.isArray(t)&&t.length===Object.keys(t).length}o(Nt,"isPlainArray");function Ve(t){if(!qt(t))return!1;let e=t.constructor;if(e===void 0)return!0;let s=e.prototype;return!(!qt(s)||!s.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}o(Ve,"isPlainObject");function qt(t){return Object.prototype.toString.call(t)==="[object Object]"}o(qt,"hasObjectPrototype");function Kt(t){return new Promise(e=>{j.setTimeout(e,t)})}o(Kt,"sleep");function ye(t,e,s){return typeof s.structuralSharing=="function"?s.structuralSharing(t,e):s.structuralSharing!==!1?Je(t,e):e}o(ye,"replaceData");function br(t){return t}o(br,"keepPreviousData");function Bt(t,e,s=0){let r=[...t,e];return s&&r.length>s?r.slice(1):r}o(Bt,"addToEnd");function $t(t,e,s=0){let r=[e,...t];return s&&r.length>s?r.slice(0,-1):r}o($t,"addToStart");var ce=Symbol();function Pe(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===ce?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}o(Pe,"ensureQueryFn");function Fe(t,e){return typeof t=="function"?t(...e):!!t}o(Fe,"shouldThrowError");function Wt(t,e,s){let r=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:o(()=>(i??=e(),r||(r=!0,i.aborted?s():i.addEventListener("abort",s,{once:!0})),i),"get")}),t}o(Wt,"addConsumeAwareSignal");var K=(()=>{let t=o(()=>Ge,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function be(){let t,e,s=new Promise((i,n)=>{t=i,e=n});s.status="pending",s.catch(()=>{});function r(i){Object.assign(s,i),delete s.resolve,delete s.reject}return o(r,"finalize"),s.resolve=i=>{r({status:"fulfilled",value:i}),t(i)},s.reject=i=>{r({status:"rejected",reason:i}),e(i)},s}o(be,"pendingThenable");var Ht=Ut;function gr(){let t=[],e=0,s=o(c=>{c()},"notifyFn"),r=o(c=>{c()},"batchNotifyFn"),i=Ht,n=o(c=>{e?t.push(c):i(()=>{s(c)})},"schedule"),a=o(()=>{let c=t;t=[],c.length&&i(()=>{r(()=>{c.forEach(u=>{s(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=>{s=c},"setNotifyFunction"),setBatchNotifyFunction:o(c=>{r=c},"setBatchNotifyFunction"),setScheduler:o(c=>{i=c},"setScheduler")}}o(gr,"createNotifyManager");var v=gr();var vr=class extends q{static{o(this,"OnlineManager")}#e=!0;#t;#s;constructor(){super(),this.#s=t=>{if(typeof window<"u"&&window.addEventListener){let e=o(()=>t(!0),"onlineListener"),s=o(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",s,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",s)}}}}onSubscribe(){this.#t||this.setEventListener(this.#s)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#s=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(s=>{s(t)}))}isOnline(){return this.#e}},ue=new vr;function Sr(t){return Math.min(1e3*2**t,3e4)}o(Sr,"defaultRetryDelay");function Ye(t){return(t??"online")==="online"?ue.isOnline():!0}o(Ye,"canFetch");var Me=class extends Error{static{o(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function xe(t){let e=!1,s=0,r,i=be(),n=o(()=>i.status!=="pending","isResolved"),a=o(b=>{if(!n()){let w=new Me(b);f(w),t.onCancel?.(w)}},"cancel"),c=o(()=>{e=!0},"cancelRetry"),u=o(()=>{e=!1},"continueRetry"),h=o(()=>oe.isFocused()&&(t.networkMode==="always"||ue.isOnline())&&t.canRun(),"canContinue"),d=o(()=>Ye(t.networkMode)&&t.canRun(),"canStart"),l=o(b=>{n()||(r?.(),i.resolve(b))},"resolve"),f=o(b=>{n()||(r?.(),i.reject(b))},"reject"),p=o(()=>new Promise(b=>{r=o(w=>{(n()||h())&&b(w)},"continueFn"),t.onPause?.()}).then(()=>{r=void 0,n()||t.onContinue?.()}),"pause"),m=o(()=>{if(n())return;let b,w=s===0?t.initialPromise:void 0;try{b=w??t.fn()}catch(k){b=Promise.reject(k)}Promise.resolve(b).then(l).catch(k=>{if(n())return;let F=t.retry??(K.isServer()?0:3),_=t.retryDelay??Sr,N=typeof _=="function"?_(s,k):_,D=F===!0||typeof F=="number"&&s<F||typeof F=="function"&&F(s,k);if(e||!D){f(k);return}s++,t.onFail?.(s,k),Kt(N).then(()=>h()?void 0:p()).then(()=>{e?f(k):m()})})},"run");return{promise:i,status:o(()=>i.status,"status"),cancel:a,continue:o(()=>(r?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:d,start:o(()=>(d()?m():p().then(m),i),"start")}}o(xe,"createRetryer");var Le=class{static{o(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),pe(this.gcTime)&&(this.#e=j.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(K.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(j.clearTimeout(this.#e),this.#e=void 0)}};function Vt(t){return{onFetch:o((e,s)=>{let r=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,n=e.state.data?.pages||[],a=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,h=o(async()=>{let d=!1,l=o(m=>{Wt(m,()=>e.signal,()=>d=!0)},"addSignalProperty"),f=Pe(e.options,e.fetchOptions),p=o(async(m,b,w)=>{if(d)return Promise.reject(e.signal.reason);if(b==null&&m.pages.length)return Promise.resolve(m);let F=o(()=>{let $={client:e.client,queryKey:e.queryKey,pageParam:b,direction:w?"backward":"forward",meta:e.options.meta};return l($),$},"createQueryFnContext")(),_=await f(F),{maxPages:N}=e.options,D=w?$t:Bt;return{pages:D(m.pages,_,N),pageParams:D(m.pageParams,b,N)}},"fetchPage");if(i&&n.length){let m=i==="backward",b=m?wr:zt,w={pages:n,pageParams:a},k=b(r,w);c=await p(w,k,m)}else{let m=t??n.length;do{let b=u===0?a[0]??r.initialPageParam:zt(r,c);if(u>0&&b==null)break;c=await p(c,b),u++}while(u<m)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(h,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},s):e.fetchFn=h},"onFetch")}}o(Vt,"infiniteQueryBehavior");function zt(t,{pages:e,pageParams:s}){let r=e.length-1;return e.length>0?t.getNextPageParam(e[r],e,s[r],s):void 0}o(zt,"getNextPageParam");function wr(t,{pages:e,pageParams:s}){return e.length>0?t.getPreviousPageParam?.(e[0],e,s[0],s):void 0}o(wr,"getPreviousPageParam");var Yt=class extends Le{static{o(this,"Query")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t){super(),this.#a=!1,this.#o=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#n=t.client,this.#r=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=Jt(this.options),this.state=t.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#i?.promise}setOptions(t){if(this.options={...this.#o,...t},t?._type&&(this.#e=t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Jt(this.options);e.data!==void 0&&(this.setState(Gt(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#r.remove(this)}setData(t,e){let s=ye(this.state.data,t,this.options);return this.#c({data:s,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),s}setState(t){this.#c({type:"setState",state:t})}cancel(t){let e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(C).catch(C):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===ce||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>U(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:!Ie(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#i&&(this.#a||this.#h()?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#r.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}#h(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#c({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#i?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(h=>h.options.queryFn);u&&this.setOptions(u.options)}let s=new AbortController,r=o(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:o(()=>(this.#a=!0,s.signal),"get")})},"addSignalProperty"),i=o(()=>{let u=Pe(this.options,e),d=o(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return r(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,d,this):u(d)},"fetchFn"),a=o(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return r(u),u},"createFetchContext")();(this.#e==="infinite"?Vt(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#s=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:"fetch",meta:a.fetchOptions?.meta}),this.#i=xe({initialPromise:e?.initialPromise,fn:a.fetchFn,onCancel:o(u=>{u instanceof Me&&u.revert&&this.setState({...this.#s,fetchStatus:"idle"}),s.abort()},"onCancel"),onFail:o((u,h)=>{this.#c({type:"failed",failureCount:u,error:h})},"onFail"),onPause:o(()=>{this.#c({type:"pause"})},"onPause"),onContinue:o(()=>{this.#c({type:"continue"})},"onContinue"),retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:o(()=>!0,"canRun")});try{let u=await this.#i.start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),this.#r.config.onSuccess?.(u,this),this.#r.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof Me){if(u.silent)return this.#i.promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw this.#c({type:"error",error:u}),this.#r.config.onError?.(u,this),this.#r.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=o(s=>{switch(t.type){case"failed":return{...s,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...s,fetchStatus:"paused"};case"continue":return{...s,fetchStatus:"fetching"};case"fetch":return{...s,...Xe(s.data,this.options),fetchMeta:t.meta??null};case"success":let r={...s,...Gt(t.data,t.dataUpdatedAt),dataUpdateCount:s.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#s=t.manual?r:void 0,r;case"error":let i=t.error;return{...s,error:i,errorUpdateCount:s.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:s.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...s,isInvalidated:!0};case"setState":return{...s,...t.state}}},"reducer");this.state=e(this.state),v.batch(()=>{this.observers.forEach(s=>{s.onQueryUpdate()}),this.#r.notify({query:this,type:"updated",action:t})})}};function Xe(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Ye(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}o(Xe,"fetchState");function Gt(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}o(Gt,"successState");function Jt(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,s=e!==void 0,r=s?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:s?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:s?"success":"pending",fetchStatus:"idle"}}o(Jt,"getDefaultState");var et=class extends q{static{o(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=be(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#s=void 0;#r=void 0;#n;#i;#o;#a;#h;#c;#p;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Xt(this.#t,this.options)?this.#f():this.updateResult(),this.#v())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return Ze(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return Ze(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#w(),this.#t.removeObserver(this)}setOptions(t){let e=this.options,s=this.#t;if(this.options=this.#e.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof 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&&!Ae(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let r=this.hasListeners();r&&Zt(this.#t,s,this.options,e)&&this.#f(),this.updateResult(),r&&(this.#t!==s||I(this.options.enabled,this.#t)!==I(e.enabled,this.#t)||U(this.options.staleTime,this.#t)!==U(e.staleTime,this.#t))&&this.#y();let i=this.#b();r&&(this.#t!==s||I(this.options.enabled,this.#t)!==I(e.enabled,this.#t)||i!==this.#u)&&this.#g(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),s=this.createResult(e,t);return kr(this,s)&&(this.#r=s,this.#i=this.options,this.#n=this.#t.state),s}getCurrentResult(){return this.#r}trackResult(t,e){return new Proxy(t,{get:o((s,r)=>(this.trackProp(r),e?.(r),r==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(s,r)),"get")})}trackProp(t){this.#m.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let e=this.#e.defaultQueryOptions(t),s=this.#e.getQueryCache().build(this.#e,e);return s.fetch().then(()=>this.createResult(s,e))}fetch(t){return this.#f({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#f(t){this.#C();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(C)),e}#y(){this.#S();let t=U(this.options.staleTime,this.#t);if(K.isServer()||this.#r.isStale||!pe(t))return;let s=Ie(this.#r.dataUpdatedAt,t)+1;this.#d=j.setTimeout(()=>{this.#r.isStale||this.updateResult()},s)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#g(t){this.#w(),this.#u=t,!(K.isServer()||I(this.options.enabled,this.#t)===!1||!pe(this.#u)||this.#u===0)&&(this.#l=j.setInterval(()=>{(this.options.refetchIntervalInBackground||oe.isFocused())&&this.#f()},this.#u))}#v(){this.#y(),this.#g(this.#b())}#S(){this.#d!==void 0&&(j.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&(j.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let s=this.#t,r=this.options,i=this.#r,n=this.#n,a=this.#i,u=t!==s?t.state:this.#s,{state:h}=t,d={...h},l=!1,f;if(e._optimisticResults){let x=this.hasListeners(),fe=!x&&Xt(t,e),ke=x&&Zt(t,s,e,r);(fe||ke)&&(d={...d,...Xe(h.data,t.options)}),e._optimisticResults==="isRestoring"&&(d.fetchStatus="idle")}let{error:p,errorUpdatedAt:m,status:b}=d;f=d.data;let w=!1;if(e.placeholderData!==void 0&&f===void 0&&b==="pending"){let x;i?.isPlaceholderData&&e.placeholderData===a?.placeholderData?(x=i.data,w=!0):x=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,x!==void 0&&(b="success",f=ye(i?.data,x,e),l=!0)}if(e.select&&f!==void 0&&!w)if(i&&f===n?.data&&e.select===this.#h)f=this.#c;else try{this.#h=e.select,f=e.select(f),f=ye(i?.data,f,e),this.#c=f,this.#a=null}catch(x){this.#a=x}this.#a&&(p=this.#a,f=this.#c,m=Date.now(),b="error");let k=d.fetchStatus==="fetching",F=b==="pending",_=b==="error",N=F&&k,D=f!==void 0,M={status:b,fetchStatus:d.fetchStatus,isPending:F,isSuccess:b==="success",isError:_,isInitialLoading:N,isLoading:N,data:f,dataUpdatedAt:d.dataUpdatedAt,error:p,errorUpdatedAt:m,failureCount:d.fetchFailureCount,failureReason:d.fetchFailureReason,errorUpdateCount:d.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:d.dataUpdateCount>u.dataUpdateCount||d.errorUpdateCount>u.errorUpdateCount,isFetching:k,isRefetching:k&&!F,isLoadingError:_&&!D,isPaused:d.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:_&&D,isStale:tt(t,e),refetch:this.refetch,promise:this.#o,isEnabled:I(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let x=M.data!==void 0,fe=M.status==="error"&&!x,ke=o(Ee=>{fe?Ee.reject(M.error):x&&Ee.resolve(M.data)},"finalizeThenableIfPossible"),Qt=o(()=>{let Ee=this.#o=M.promise=be();ke(Ee)},"recreateThenable"),Te=this.#o;switch(Te.status){case"pending":t.queryHash===s.queryHash&&ke(Te);break;case"fulfilled":(fe||M.data!==Te.value)&&Qt();break;case"rejected":(!fe||M.error!==Te.reason)&&Qt();break}}return M}updateResult(){let t=this.#r,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#i=this.options,this.#n.data!==void 0&&(this.#p=this.#t),Ae(e,t))return;this.#r=e;let s=o(()=>{if(!t)return!0;let{notifyOnChangeProps:r}=this.options,i=typeof r=="function"?r():r;if(i==="all"||!i&&!this.#m.size)return!0;let n=new Set(i??this.#m);return this.options.throwOnError&&n.add("error"),Object.keys(this.#r).some(a=>{let c=a;return this.#r[c]!==t[c]&&n.has(c)})},"shouldNotifyListeners");this.#k({listeners:s()})}#C(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#s=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#v()}#k(t){v.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#r)}),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 Xt(t,e){return Cr(t,e)||t.state.data!==void 0&&Ze(t,e,e.refetchOnMount)}o(Xt,"shouldFetchOnMount");function Ze(t,e,s){if(I(e.enabled,t)!==!1&&U(e.staleTime,t)!=="static"){let r=typeof s=="function"?s(t):s;return r==="always"||r!==!1&&tt(t,e)}return!1}o(Ze,"shouldFetchOn");function Zt(t,e,s,r){return(t!==e||I(r.enabled,t)===!1)&&(!s.suspense||t.state.status!=="error")&&tt(t,s)}o(Zt,"shouldFetchOptionally");function tt(t,e){return I(e.enabled,t)!==!1&&t.isStaleByTime(U(e.staleTime,t))}o(tt,"isStale");function kr(t,e){return!Ae(t.getCurrentResult(),e)}o(kr,"shouldAssignObserverCurrentProperties");var es=class extends Le{static{o(this,"Mutation")}#e;#t;#s;#r;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#s=t.mutationCache,this.#t=[],this.state=t.state||Tr(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#s.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#s.remove(this))}continue(){return this.#r?.continue()??this.execute(this.state.variables)}async execute(t){let e=o(()=>{this.#n({type:"continue"})},"onContinue"),s={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#r=xe({fn:o(()=>this.options.mutationFn?this.options.mutationFn(t,s):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.#s.canRun(this),"canRun")});let r=this.state.status==="pending",i=!this.#r.canStart();try{if(r)e();else{this.#n({type:"pending",variables:t,isPaused:i}),this.#s.config.onMutate&&await this.#s.config.onMutate(t,this,s);let a=await this.options.onMutate?.(t,s);a!==this.state.context&&this.#n({type:"pending",context:a,variables:t,isPaused:i})}let n=await this.#r.start();return await this.#s.config.onSuccess?.(n,t,this.state.context,this,s),await this.options.onSuccess?.(n,t,this.state.context,s),await this.#s.config.onSettled?.(n,null,this.state.variables,this.state.context,this,s),await this.options.onSettled?.(n,null,t,this.state.context,s),this.#n({type:"success",data:n}),n}catch(n){try{await this.#s.config.onError?.(n,t,this.state.context,this,s)}catch(a){Promise.reject(a)}try{await this.options.onError?.(n,t,this.state.context,s)}catch(a){Promise.reject(a)}try{await this.#s.config.onSettled?.(void 0,n,this.state.variables,this.state.context,this,s)}catch(a){Promise.reject(a)}try{await this.options.onSettled?.(void 0,n,t,this.state.context,s)}catch(a){Promise.reject(a)}throw this.#n({type:"error",error:n}),n}finally{this.#s.runNext(this)}}#n(t){let e=o(s=>{switch(t.type){case"failed":return{...s,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...s,isPaused:!0};case"continue":return{...s,isPaused:!1};case"pending":return{...s,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...s,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...s,data:void 0,error:t.error,failureCount:s.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),v.batch(()=>{this.#t.forEach(s=>{s.onMutationUpdate(t)}),this.#s.notify({mutation:this,type:"updated",action:t})})}};function Tr(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}o(Tr,"getDefaultState");var ts=class extends q{static{o(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#s=0}#e;#t;#s;build(t,e,s){let r=new es({client:t,mutationCache:this,mutationId:++this.#s,options:t.defaultMutationOptions(e),state:s});return this.add(r),r}add(t){this.#e.add(t);let e=Qe(t);if(typeof e=="string"){let s=this.#t.get(e);s?s.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=Qe(t);if(typeof e=="string"){let s=this.#t.get(e);if(s)if(s.length>1){let r=s.indexOf(t);r!==-1&&s.splice(r,1)}else s[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=Qe(t);if(typeof e=="string"){let r=this.#t.get(e)?.find(i=>i.state.status==="pending");return!r||r===t}else return!0}runNext(t){let e=Qe(t);return typeof e=="string"?this.#t.get(e)?.find(r=>r!==t&&r.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(s=>Re(e,s))}findAll(t={}){return this.getAll().filter(e=>Re(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(C))))}};function Qe(t){return t.options.scope?.id}o(Qe,"scopeFor");var ss=class extends q{static{o(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,s){let r=e.queryKey,i=e.queryHash??me(r,e),n=this.get(i);return n||(n=new Yt({client:t,queryKey:r,queryHash:i,options:t.defaultQueryOptions(e),state:s,defaultOptions:t.getQueryDefaults(r)}),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(s=>Oe(e,s))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(s=>Oe(t,s)):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 st=class{static{o(this,"QueryClient")}#e;#t;#s;#r;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new ss,this.#t=t.mutationCache||new ts,this.#s=t.defaultOptions||{},this.#r=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=oe.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=ue.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),s=this.#e.build(this,e),r=s.state.data;return r===void 0?this.fetchQuery(t):(t.revalidateIfStale&&s.isStaleByTime(U(e.staleTime,s))&&this.prefetchQuery(e),Promise.resolve(r))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:s})=>{let r=s.data;return[e,r]})}setQueryData(t,e,s){let r=this.defaultQueryOptions({queryKey:t}),n=this.#e.get(r.queryHash)?.state.data,a=jt(e,n);if(a!==void 0)return this.#e.build(this,r).setData(a,{...s,manual:!0})}setQueriesData(t,e,s){return v.batch(()=>this.#e.findAll(t).map(({queryKey:r})=>[r,this.setQueryData(r,e,s)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;v.batch(()=>{e.findAll(t).forEach(s=>{e.remove(s)})})}resetQueries(t,e){let s=this.#e;return v.batch(()=>(s.findAll(t).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let s={revert:!0,...e},r=v.batch(()=>this.#e.findAll(t).map(i=>i.cancel(s)));return Promise.all(r).then(C).catch(C)}invalidateQueries(t,e={}){return v.batch(()=>(this.#e.findAll(t).forEach(s=>{s.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let s={...e,cancelRefetch:e.cancelRefetch??!0},r=v.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,s);return s.throwOnError||(n=n.catch(C)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(r).then(C)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let s=this.#e.build(this,e);return s.isStaleByTime(U(e.staleTime,s))?s.fetch(e):Promise.resolve(s.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(C).catch(C)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(C).catch(C)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return ue.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#s}setDefaultOptions(t){this.#s=t}setQueryDefaults(t,e){this.#r.set(ne(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#r.values()],s={};return e.forEach(r=>{G(t,r.queryKey)&&Object.assign(s,r.defaultOptions)}),s}setMutationDefaults(t,e){this.#n.set(ne(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],s={};return e.forEach(r=>{G(t,r.mutationKey)&&Object.assign(s,r.defaultOptions)}),s}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#s.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=me(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===ce&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#s.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var J=L(ie(),1);var he=L(ie(),1),rs=L(ze(),1);var ge=he.createContext(void 0),rt=o(t=>{let e=he.useContext(ge);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),it=o(({client:t,children:e})=>(he.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,rs.jsx)(ge.Provider,{value:t,children:e})),"QueryClientProvider");var ve=L(ie(),1),Er=L(ze(),1);function Ir(){let t=!1;return{clearReset:o(()=>{t=!1},"clearReset"),reset:o(()=>{t=!0},"reset"),isReset:o(()=>t,"isReset")}}o(Ir,"createValue");var Or=ve.createContext(Ir()),is=o(()=>ve.useContext(Or),"useQueryErrorResetBoundary");var ns=L(ie(),1);var as=o((t,e,s)=>{let r=s?.state.error&&typeof t.throwOnError=="function"?Fe(t.throwOnError,[s.state.error,s]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||r)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),os=o(t=>{ns.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),cs=o(({result:t,errorResetBoundary:e,throwOnError:s,query:r,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&r&&(i&&t.data===void 0||Fe(s,[t.error,r])),"getHasError");var _e=L(ie(),1);var us=_e.createContext(!1),hs=o(()=>_e.useContext(us),"useIsRestoring"),oc=us.Provider;var ds=o(t=>{if(t.suspense){let s=o(i=>i==="static"?i:Math.max(i??1e3,1e3),"clamp"),r=t.staleTime;t.staleTime=typeof r=="function"?(...i)=>s(r(...i)):s(r),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},"ensureSuspenseTimers"),ls=o((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),fs=o((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),nt=o((t,e,s)=>e.fetchOptimistic(t).catch(()=>{s.clearReset()}),"fetchOptimistic");function ps(t,e,s){let r=hs(),i=is(),n=rt(s),a=n.defaultQueryOptions(t);n.getDefaultOptions().queries?._experimental_beforeQuery?.(a);let c=n.getQueryCache().get(a.queryHash),u=t.subscribed!==!1;a._optimisticResults=r?"isRestoring":u?"optimistic":void 0,ds(a),as(a,i,c),os(i);let h=!n.getQueryCache().get(a.queryHash),[d]=J.useState(()=>new e(n,a)),l=d.getOptimisticResult(a),f=!r&&u;if(J.useSyncExternalStore(J.useCallback(p=>{let m=f?d.subscribe(v.batchCalls(p)):C;return d.updateResult(),m},[d,f]),()=>d.getCurrentResult(),()=>d.getCurrentResult()),J.useEffect(()=>{d.setOptions(a)},[a,d]),fs(a,l))throw nt(a,d,i);if(cs({result:l,errorResetBoundary:i,throwOnError:a.throwOnError,query:c,suspense:a.suspense}))throw l.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(a,l),a.experimental_prefetchInRender&&!K.isServer()&&ls(l,r)&&(h?nt(a,d,i):c?.promise)?.catch(C).finally(()=>{d.updateResult()}),a.notifyOnChangeProps?l:d.trackResult(l)}o(ps,"useBaseQuery");function Rr(t,e){return ps(t,et,e)}o(Rr,"useQuery");var vs=L(Dt(),1);var H=L(ie(),1);var Ar=/["\\\u0000-\u001F\uD800-\uDFFF]/,ms=o(t=>Ar.test(t)?JSON.stringify(t):`"${t}"`,"d"),ot=o(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return ms(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let a="[";for(let c=0;c<t.length;c++)c>0&&(a+=","),a+=ot(t[c]);return a+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let a=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${a} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let s=t,r=Object.keys(s).sort(),i="{",n=!0;for(let a of r){let c=s[a];c!==void 0&&(n?n=!1:i+=",",i+=ms(a),i+=":",i+=ot(c))}return i+"}"},"b"),at=o(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"u"),O="$lunora.wire$",ys="__proto__",Pr=o(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"m"),W=o((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[O,"undefined"];if(t===null)return null;let s=typeof t;if(s==="bigint")return[O,"bigint",t.toString()];if(s==="number"){let n=t;return Number.isNaN(n)?[O,"nan"]:n===1/0?[O,"inf"]:n===-1/0?[O,"-inf"]:n}if(s!=="object")return t;if(t instanceof Date)return[O,"date",W(t.getTime(),e+1)];if(t instanceof Error){let n=t,a={};for(let u of Object.keys(n)){if(n[u]===void 0)continue;let h=W(n[u],e+1);u===ys?Object.defineProperty(a,u,{configurable:!0,enumerable:!0,value:h,writable:!0}):a[u]=h}let c=[O,"error",String(n.name),String(n.message),a];return n.cause!==void 0&&c.push(W(n.cause,e+1)),c}if(t instanceof URL)return[O,"url",t.href];if(t instanceof Map)return[O,"map",[...t.entries()].map(([n,a])=>[W(n,e+1),W(a,e+1)])];if(t instanceof Set)return[O,"set",[...t].map(n=>W(n,e+1))];if(t instanceof ArrayBuffer)return[O,"bytes",at(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"?[O,"bytes",at(c)]:[O,"bytes",at(c),a]}if(Array.isArray(t)){let n=t.map(a=>W(a,e+1));return n.length>0&&n[0]===O?[O,"arr",n]:n}if(!Pr(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 r=t,i={};for(let n of Object.keys(r)){let a=r[n];if(a===void 0)continue;let c=W(a,e+1);n===ys?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"a"),Fr=o(t=>ot(W(t)),"w"),Se=o(t=>Fr(t),"O");var ct=L(ze(),1);var bs=o(t=>{t!==void 0&&(t.cancel({silent:!0}),t.setState({...t.state,data:void 0,dataUpdatedAt:0,error:null,fetchStatus:"idle",status:"pending"}))},"C"),ut=class{static{o(this,"x")}constructor(e){this.client=e}client;entries=new Map;pushes=new Map;samples=new Map;epoch=0;identityWatched=new Set;listening=!1;keyOf(e){return Se(e)}hasConsumers(e){return this.entries.has(Se(e))}openSnapshotSample(e){let s=Se(e);return this.samples.set(s,(this.samples.get(s)??0)+1),{key:s,pushes:this.pushes.get(s)??0}}closeSnapshotSample(e){let s=(this.samples.get(e.key)??1)-1,r=(this.pushes.get(e.key)??0)===e.pushes;return s>0?(this.samples.set(e.key,s),r):(this.samples.delete(e.key),this.entries.has(e.key)||this.pushes.delete(e.key),r)}clearOnIdentityChange(e){this.listenForIdentityChange(),this.identityWatched.add(e)}identityEpoch=o(()=>this.epoch,"identityEpoch");subscribeIdentityEpoch=o(e=>(this.listenForIdentityChange(),this.client.onIdentityChange(e)),"subscribeIdentityEpoch");listenForIdentityChange(){this.listening||(this.listening=!0,this.client.onIdentityChange(()=>{this.epoch+=1;for(let e of this.identityWatched){let s=e.getQueryCache();for(let r of s.findAll({queryKey:["lunora"]}))bs(r),r.getObserversCount()===0&&!this.hasConsumers(r.queryKey)&&s.remove(r)}}))}attach(e,s,r,i,n,a={}){let c=Se(s),u=this.entries.get(c);if(!u){u={errorCallbacks:new Set,refCount:0,unsubscribe:void 0},this.entries.set(c,u);let l=u;try{u.unsubscribe=this.client.subscribe(r,i,f=>{if(this.pushes.set(c,(this.pushes.get(c)??0)+1),f===void 0){bs(e.getQueryCache().find({exact:!0,queryKey:s}));return}e.setQueryData(s,f)},{onError:o(f=>{for(let p of l.errorCallbacks)p(f)},"onError"),shardKey:n})}catch(f){throw this.entries.delete(c),f}}u.refCount+=1;let{onError:h}=a;h&&u.errorCallbacks.add(h);let d=!1;return()=>{if(d)return;d=!0;let l=this.entries.get(c);l&&(l.refCount-=1,h&&l.errorCallbacks.delete(h),l.refCount<=0&&(l.unsubscribe?.(),this.entries.delete(c)))}}},gs=new WeakMap,Mr=o(t=>{let e=gs.get(t);return e||(e=new ut(t),gs.set(t,e)),e},"O"),Ss=(0,H.createContext)(null),xr=o(()=>new st({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"N"),Lr=o(t=>{let e=(0,vs.c)(13),{children:s,client:r,queryClient:i}=t,n=(0,H.use)(ge),a;e[0]!==n||e[1]!==i?(a=o(()=>i??n??xr(),"d"),e[0]=n,e[1]=i,e[2]=a):a=e[2];let[c]=(0,H.useState)(a),u=i??n??c,h,d;e[3]!==r||e[4]!==u?(h=o(()=>{Mr(r).clearOnIdentityChange(u)},"u"),d=[r,u],e[3]=r,e[4]=u,e[5]=h,e[6]=d):(h=e[5],d=e[6]),(0,H.useEffect)(h,d);let l;e[7]!==s||e[8]!==r?(l=(0,ct.jsx)(Ss,{value:r,children:s}),e[7]=s,e[8]=r,e[9]=l):l=e[9];let f=l;if(n===u)return f;let p;return e[10]!==f||e[11]!==u?(p=(0,ct.jsx)(it,{client:u,children:f}),e[10]=f,e[11]=u,e[12]=p):p=e[12],p},"R"),ht=o(()=>{let t=(0,H.use)(Ss);if(!t)throw new y("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"D");var De=o(t=>{let e="";for(let s=0;s<t.length;s+=32768)e+=String.fromCharCode(...t.subarray(s,s+32768));return btoa(e)},"w"),Qr=o(t=>{let e=atob(t),s=new Uint8Array(e.length);for(let r=0;r<e.length;r+=1)s[r]=e.codePointAt(r)??0;return s},"p"),z="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",ks=o(t=>{let e="",s=0,r=t.length-2;for(;s<r;s+=3){let n=t[s]<<16|t[s+1]<<8|t[s+2];e+=z.charAt(n>>18&63)+z.charAt(n>>12&63)+z.charAt(n>>6&63)+z.charAt(n&63)}let i=t.length-s;if(i===1){let n=t[s]<<16;e+=z.charAt(n>>18&63)+z.charAt(n>>12&63)}else if(i===2){let n=t[s]<<16|t[s+1]<<8;e+=z.charAt(n>>18&63)+z.charAt(n>>12&63)+z.charAt(n>>6&63)}return e},"h"),T="$lunora.wire$",Ue="__proto__",ws={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Cs={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},dt=o(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"E"),E=o((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[T,"undefined"];if(t===null)return null;let s=typeof t;if(s==="bigint")return[T,"bigint",t.toString()];if(s==="number"){let n=t;return Number.isNaN(n)?[T,"nan"]:n===1/0?[T,"inf"]:n===-1/0?[T,"-inf"]:n}if(s!=="object")return t;if(t instanceof Date)return[T,"date",E(t.getTime(),e+1)];if(t instanceof Error){let n=t,a={};for(let u of Object.keys(n)){if(n[u]===void 0)continue;let h=E(n[u],e+1);u===Ue?Object.defineProperty(a,u,{configurable:!0,enumerable:!0,value:h,writable:!0}):a[u]=h}let c=[T,"error",String(n.name),String(n.message),a];return n.cause!==void 0&&c.push(E(n.cause,e+1)),c}if(t instanceof URL)return[T,"url",t.href];if(t instanceof Map)return[T,"map",[...t.entries()].map(([n,a])=>[E(n,e+1),E(a,e+1)])];if(t instanceof Set)return[T,"set",[...t].map(n=>E(n,e+1))];if(t instanceof ArrayBuffer)return[T,"bytes",De(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){let n=t,a=n.constructor.name,c=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return a==="Uint8Array"?[T,"bytes",De(c)]:[T,"bytes",De(c),a]}if(Array.isArray(t)){let n=t.map(a=>E(a,e+1));return n.length>0&&n[0]===T?[T,"arr",n]:n}if(!dt(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 r=t,i={};for(let n of Object.keys(r)){let a=r[n];if(a===void 0)continue;let c=E(a,e+1);n===Ue?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"d"),S=o((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===null||typeof t!="object")return t;if(Array.isArray(t)){if(t[0]===T)switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(i=>S(i,e+1));case"bigint":{let i=t[2];if(typeof i!="string"||i.length>1024||!/^-?\d+$/.test(i))throw new RangeError("wire-codec: invalid or over-long bigint (max 1024 digits)");return BigInt(i)}case"date":{let i=S(t[2],e+1);if(typeof i!="number")throw new TypeError("wire-codec: malformed date \u2014 epoch must be a number");return new Date(i)}case"map":{let i=t[2];return new Map(i.map(n=>{if(!Array.isArray(n)||n.length!==2)throw new TypeError("wire-codec: malformed map entry \u2014 expected a [key, value] pair");return[S(n[0],e+1),S(n[1],e+1)]}))}case"set":return new Set(t[2].map(i=>S(i,e+1)));case"url":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed url \u2014 href must be a string");return new URL(i)}case"error":{let i=t[2],n=t[3];if(typeof i!="string"||typeof n!="string")throw new TypeError("wire-codec: malformed error \u2014 name and message must be strings");let a=(Object.hasOwn(Cs,i)?Cs[i]:void 0)??Error,c=new a(n);c.name!==i&&Object.defineProperty(c,"name",{configurable:!0,value:i,writable:!0});let u=S(t[4],e+1);if(u===null||typeof u!="object"||Array.isArray(u))throw new TypeError("wire-codec: malformed error \u2014 props must be an object");for(let h of Object.keys(u))h===Ue?Object.defineProperty(c,h,{configurable:!0,enumerable:!0,value:u[h],writable:!0}):c[h]=u[h];return t.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:S(t[5],e+1),writable:!0}),c}case"bytes":{let i=t[2];if(typeof i!="string")throw new TypeError("wire-codec: malformed bytes \u2014 payload must be a base64 string");let n=Qr(i);if(De(n)!==i)throw new TypeError("wire-codec: malformed bytes \u2014 payload must be canonical padded base64");let a=t[3]??"Uint8Array";if(a==="ArrayBuffer")return n.buffer.byteLength===n.byteLength?n.buffer:n.slice().buffer;let c=Object.hasOwn(ws,a)?ws[a]:void 0;return c?new c(n.slice().buffer):n}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return t.map(i=>S(i,e+1))}return t.map(i=>S(i,e+1))}let s=t,r={};for(let i of Object.keys(s)){let n=S(s[i],e+1);i===Ue?Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:n,writable:!0}):r[i]=n}return r},"u");var A=o(t=>new Promise((e,s)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{s(t.error??new Error("IndexedDB request failed"))})}),"c"),Ne=o((t,e,s,r)=>{let i;return()=>i||(i=new Promise((n,a)=>{let c=t.open(e,s);c.addEventListener("upgradeneeded",()=>{r(c.result)}),c.addEventListener("success",()=>{n(c.result)}),c.addEventListener("error",()=>{a(c.error??new Error("IndexedDB open failed"))})}),i)},"E"),qe=o((t,e)=>async(s,r)=>{let i=(await t()).transaction(e,s),n=await r(i.objectStore(e));return await new Promise((a,c)=>{i.addEventListener("complete",()=>{a()}),i.addEventListener("error",()=>{c(i.error??new Error("IndexedDB transaction failed"))}),i.addEventListener("abort",()=>{c(i.error??new Error("IndexedDB transaction aborted"))})}),n},"u");var ae=o((t,e,s)=>`${t}::${e}::${s??""}`,"T"),_r=500,Dr=o((t,e)=>{if(!Number.isInteger(t)||t<1)throw new y("INTERNAL",`${e}: maxEntries must be a positive integer, got ${String(t)}`);return t},"E");var Ur="lunora-query-cache",Nr="query-cache",Ts="by_ts",qr=1,jr=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new y("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let s=t.databaseName??Ur,r=t.storeName??Nr,i=Dr(t.maxEntries??_r,"createIndexedDbQueryCache"),n=Ne(e,s,qr,u=>{u.objectStoreNames.contains(r)||u.createObjectStore(r,{keyPath:"key"}).createIndex(Ts,"ts",{unique:!1})}),a=qe(n,r),c=o(async u=>{let h=await A(u.count())-i;h<=0||await new Promise((d,l)=>{let f=u.index(Ts).openCursor();f.addEventListener("success",()=>{let p=f.result;if(!p||h<=0){d();return}p.delete(),h-=1,p.continue()}),f.addEventListener("error",()=>{l(f.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:o(async()=>{await a("readwrite",u=>A(u.clear()))},"clear"),load:o(async()=>a("readonly",u=>A(u.getAll())),"load"),put:o(async(u,h)=>{await a("readwrite",async d=>{await A(d.put({...h,key:u})),await c(d)})},"put"),remove:o(async u=>{await a("readwrite",h=>A(h.delete(u)))},"remove")}},"N"),Es=o(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return jr()}},"L");var Is=o(()=>{let t=null;return{get:o(()=>t,"get"),set:o(e=>{t=e},"set")}},"r");var je=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,s){if(s===void 0){this.reset(e);return}this.values.set(e.key,s),this.notify(e.key,s)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}clear(){this.values.clear(),this.subscribers.clear()}subscribe(e,s){let r=this.subscribers.get(e.key);return r||(r=new Set,this.subscribers.set(e.key,r)),r.add(s),()=>{r.delete(s),r.size===0&&this.subscribers.delete(e.key)}}notify(e,s){let r=this.subscribers.get(e);if(r)for(let i of r)try{i(s)}catch{}}};var Os=0,Kr="lunora-bridge",Br=1e3,$r=3e3,Ke=class{static{o(this,"l")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onLeaderClaimAnswered;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(Os+=1,this.tabId=`tab_${String(Os)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??Br,this.leaderTimeout=e.leaderTimeout??$r,this.onBecomeLeader=e.onBecomeLeader,this.onStopBeingLeader=e.onStopBeingLeader,this.onConnectionStatus=e.onConnectionStatus,this.onSubscriptionData=e.onSubscriptionData,this.onLeaderClaimAnswered=e.onLeaderClaimAnswered,this.onSubscriptionError=e.onSubscriptionError,this.onSubscriptionSettled=e.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(e.channelName??Kr),this.bc.addEventListener("message",s=>{this.handleMessage(s.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(e,s,r,i,n){this.leader&&this.broadcast({type:"subscription-data",tabId:this.tabId,key:e,data:s,...r===void 0?{}:{cursor:r},...i===void 0?{}:{epoch:i},...n===void 0?{}:{identity:n}})}broadcastSubscriptionError(e,s,r){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:s,...r===void 0?{}:{identity:r}})}broadcastSubscriptionSettled(e,s,r,i,n,a){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...s===void 0?{}:{cursor:s},...r===void 0?{}:{epoch:r},...i===void 0?{}:{lastMutationId:i},...n===void 0?{}:{clientId:n},...a===void 0?{}:{identity:a}})}broadcastConnectionStatus(e,s){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...s===void 0?{}:{identity:s}})}broadcast(e){this.bc?.postMessage(e)}handleMessage(e){switch(e.type){case"claim-leadership":{this.handleClaimLeadership(e);break}case"connection-status":{if(this.leader||e.tabId===this.tabId)break;this.onConnectionStatus?.(e.status,e.identity);break}case"heartbeat":{this.handleHeartbeat(e);break}case"subscription-data":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionData?.(e.key,e.data,e.cursor,e.epoch,e.identity);break}case"subscription-error":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionError?.(e.key,e.error,e.identity);break}case"subscription-settled":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionSettled?.(e.key,e.cursor,e.epoch,e.lastMutationId,e.clientId,e.identity);break}case"yield-leadership":{this.knownLeader===e.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(e){if(e.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}),this.onLeaderClaimAnswered?.();return}this.knownLeader===void 0&&e.tabId<this.tabId&&(this.knownLeader=e.tabId,this.lastHeartbeat=e.ts)}}handleHeartbeat(e){if(e.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(e);return}this.lastHeartbeat=e.ts,this.knownLeader=e.tabId}}resolveLeaderVsLeaderTieBreak(e){e.tabId<this.tabId?(this.leader=!1,this.knownLeader=e.tabId,this.lastHeartbeat=e.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!(!this.running||this.leader)){if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}};var lt="_id",ft="_creationTime",pt="page",Rs="pageDelta",Wr=o(t=>{if(Array.isArray(t))return t;if(dt(t)&&Array.isArray(t[pt]))return t[pt]},"y"),Hr=o(t=>{let e;for(let s of t){let r=s[ft];if(typeof r=="number"){if(e!==void 0){if(r<e)return!0;if(r>e)return!1}e=r}}return!1},"l"),zr=o((t,e)=>{let s=e[ft];if(typeof s!="number")return t.length;let r=Hr(t);for(let[i,n]of t.entries()){let a=n[ft];if(typeof a=="number"&&(r?a<s:a>s))return i}return t.length},"x"),Vr=o(t=>{if(typeof t!="object"||t===null)return;let e=t[lt];return typeof e=="string"?e:void 0},"A"),As=o(t=>{if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.key=="string"&&typeof e.table=="string"&&(e.op==="insert"||e.op==="update"||e.op==="delete")},"b"),Gr=o((t,e)=>{let s=[];for(let u of t){if(Vr(u)===void 0)return;s.push(u)}let{key:r,op:i,row:n}=e;if(i==="delete"){let u=s.filter(h=>h[lt]!==r);return u.length===s.length?[...s]:u}if(n===void 0)return;let a=[...s],c=s.findIndex(u=>u[lt]===r);return c===-1?a.splice(zr(s,n),0,n):a[c]=n,a},"I"),Ps=o((t,e)=>{let s=Wr(t);if(s===void 0)return;let r=Gr(s,e);return r===void 0||Array.isArray(t)?r:{...t,[pt]:r}},"E");var eu=new Set(Object.keys(_t)),B=class extends y{static{o(this,"E")}constructor(e,s){super("INTERNAL",e,{data:s})}};var mt=o(t=>{let e=t?.data?.retryAfterMs;return typeof e=="number"&&Number.isFinite(e)?e:void 0},"u");var Jr=1024,Be=o(t=>{let e=t.maxBuffer??Jr,s=[],r=[],i=!1,n,a=!1,c=o(()=>{let d=r.shift();if(!d)return!1;if(n)return d.reject(n),!0;if(s.length>0){let l=s.shift();return d.resolve({done:!1,value:l}),!0}return i?(d.resolve({done:!0,value:void 0}),!0):(r.unshift(d),!1)},"u"),u={complete(){if(!(i||n))for(i=!0;c(););},fail(d){if(!(i||n))for(n=d,s.length=0;c(););},push(d){if(!(i||n||a)){if(s.length>=e){u.fail(new y("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}s.push(d),c()}}},h=o(()=>{if(!a){a=!0,i=!0,s.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:h,[Symbol.asyncIterator](){return{next(){if(n)return Promise.reject(n);if(s.length>0){let d=s.shift();return Promise.resolve({done:!1,value:d})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((d,l)=>{r.push({reject:l,resolve:d})})},return(){return h(),Promise.resolve({done:!0,value:void 0})}}}}}},"p");var Fs=/^ /u,Ms=o(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"h"),Yr=o(t=>{let e="",s=[];for(let r of t.split(`
|
|
2
|
-
`))r.startsWith("event:")?e=r.slice(6).replace(Fs,""):r.startsWith("data:")&&s.push(r.slice(5).replace(Fs,""));return{data:s.join(`
|
|
3
|
-
`),event:e}},"S"),Xr=o((t,e,s)=>{let r=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),h=r[u];if(h===void 0)throw new y("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(Ms(h))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,Ms(u));let a=n.toString();return`${s.endsWith("/")?s.slice(0,-1):s}${i}${a===""?"":`?${a}`}`},"T"),Zr=o((t,e)=>{if(t.event==="complete")return e.complete(),!0;if(t.event==="error"){let s={};try{s=JSON.parse(t.data)}catch{}let r=typeof s.message=="string"?s.message:"stream error",i=typeof s.code=="string"?s.code:"HTTP_STREAM_ERROR";return e.fail(new y(i,r)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(S(JSON.parse(t.data)))}catch{return e.fail(new y("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"E"),ei=o(async(t,e)=>{let s=t.getReader(),r=new TextDecoder,i="",n=!1,a=o(u=>{let h=n?`\r${u}`:u;n=h.endsWith("\r"),n&&(h=h.slice(0,-1)),i+=h.replaceAll(`\r
|
|
4
|
-
`,`
|
|
5
|
-
`)},"l"),c=o(()=>{let u=i.indexOf(`
|
|
6
|
-
|
|
7
|
-
`);for(;u!==-1;){let h=Yr(i.slice(0,u));if(i=i.slice(u+2),Zr(h,e))return!0;u=i.indexOf(`
|
|
8
|
-
|
|
9
|
-
`)}return!1},"d");for(;;){let{done:u,value:h}=await s.read();if(u)break;if(a(r.decode(h,{stream:!0})),c()){await s.cancel().catch(()=>{});return}}a(r.decode()),c()||e.fail(new y("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"b"),xs=o((t,e,s={})=>{let r=s.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!r)throw new y("INTERNAL","httpStream: no `fetch` implementation available");let i=Xr(t,e??{},s.baseUrl??""),n=new AbortController,a;s.signal&&(s.signal.aborted?n.abort():(a=o(()=>{n.abort()},"l"),s.signal.addEventListener("abort",a,{once:!0})));let c=o(()=>{a&&s.signal?.removeEventListener("abort",a)},"d"),{handle:u,iterable:h}=Be({maxBuffer:s.maxBuffer,onCancel:o(()=>{n.abort()},"onCancel")});return(async()=>{try{let d=await r(i,{headers:{accept:"text/event-stream",...s.headers},method:t.method,signal:n.signal});if(!d.ok){await d.body?.cancel().catch(()=>{}),u.fail(new y("HTTP_STREAM_STATUS",`httpStream: request failed (status ${d.status.toString()})`,{status:d.status}));return}if(!d.body){u.fail(new y("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await ei(d.body,u)}finally{c()}})().catch(d=>{if(n.signal.aborted){u.complete();return}if(d instanceof Error&&"code"in d){u.fail(d);return}u.fail(new y("HTTP_STREAM_TRANSPORT",d instanceof Error?d.message:String(d),{cause:d}))}),h},"_");var ti=/["\\\u0000-\u001F\uD800-\uDFFF]/,Ls=o(t=>ti.test(t)?JSON.stringify(t):`"${t}"`,"y"),yt=o(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(typeof t=="number"){if(Number.isNaN(t))return"nan";if(t===1/0)return"inf";if(t===-1/0)return"-inf";if(Object.is(t,-0))return"-0"}if(typeof t=="string")return Ls(t);if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t)){let a="[";for(let c=0;c<t.length;c++)c>0&&(a+=","),a+=yt(t[c]);return a+"]"}let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let a=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${a} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let s=t,r=Object.keys(s).sort(),i="{",n=!0;for(let a of r){let c=s[a];c!==void 0&&(n?n=!1:i+=",",i+=Ls(a),i+=":",i+=yt(c))}return i+"}"},"i"),Y=o(t=>yt(E(t)),"u");var P=class t{static{o(this,"r")}static key(e,s,r){return`${e}::${Y(s)}::${r??""}`}static keyOf(e){return`${e.fn.__lunoraRef}::${e.argsKey}::${e.shardKey??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.keyOf(e),e),this.byId.set(e.id,e)}remove(e){let s=t.keyOf(e);this.byKey.get(s)===e&&this.byKey.delete(s),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}clear(){this.byKey.clear(),this.byId.clear()}};var bt=0,Qs=o(()=>bt,"L"),X=o((t,e)=>{let s=t;for(let r of e)try{s=r.transform(s)}catch{}return s},"p"),V=o((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let s of t.callbacks)try{s(e)}catch{}}},"d"),gt=o((t,e)=>{let s;try{s=e(t.lastValue)}catch{return}let r={id:Symbol("optimistic"),transform:e},i=!1;t.optimisticLayers.push(r),V(t,s);let n=o(()=>{let c=t.optimisticLayers.findIndex(u=>u.id===r.id);return c===-1?!1:(t.optimisticLayers.splice(c,1),!0)},"a"),a=o(()=>{V(t,X(t.serverBase,t.optimisticLayers))},"s");return{confirm:o(c=>{if(c===void 0){n();return}r.commitCursor=c,bt+=1,r.acknowledgedAt=bt,t.serverCursor!==void 0&&t.serverCursor>=c&&n()&&a()},"confirm"),rollback:o(()=>{i||(i=!0,n(),a())},"rollback")}},"y"),$e=o((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let s=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(r=>r.commitCursor===void 0||r.commitCursor>e),t.optimisticLayers.length!==s},"k"),_s=o((t,e)=>{t.optimisticLayers.length!==0&&(t.optimisticLayers=t.optimisticLayers.filter(s=>s.acknowledgedAt===void 0||s.acknowledgedAt>e))},"h"),Ds=o((t,e)=>{let s=[],r=[],i=o((n,a)=>t.get(P.key(n,a,e)),"c");return{confirms:s,rollbacks:r,store:{getAllQueries:o(n=>{let a=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&a.push({args:c.args,value:c.lastValue});return a},"getAllQueries"),getQuery:o((n,a)=>i(n.__lunoraRef,a??{})?.lastValue,"getQuery"),setQuery:o((n,a,c)=>{let u=i(n.__lunoraRef,a??{});if(!u)return;let h=gt(u,()=>c);h&&(s.push(h.confirm),r.push(h.rollback))},"setQuery")}}},"v");var Us=0,si=o(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();Us+=1;let t=typeof crypto<"u"&&typeof crypto.getRandomValues=="function"?Array.from(crypto.getRandomValues(new Uint8Array(8)),e=>e.toString(16).padStart(2,"0")).join(""):Math.random().toString(16).slice(2,12);return`id_${Date.now().toString(36)}_${Us.toString(36)}_${t}`},"d"),vt=o((t,e)=>t!==void 0&&e!==t,"f"),He=si,Z=o((t,e,s,r)=>{if(t)try{t({error:s,mutationId:r,operation:e});return}catch{}console.warn(`[lunora] offline-queue persistence ${e} failed`,s)},"o"),We=class{static{o(this,"l")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},s={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=s.persistence,this.onEvict=s.onEvict,this.onSizeChange=s.onSizeChange,this.version=s.version}get size(){return this.items.length}enqueue(e){let s=e;s.id??=He(),this.items.push(s),this.persistence?.append({args:s.args,...s.baselineSeq===void 0?{}:{baselineSeq:s.baselineSeq},clientId:s.clientId,functionPath:s.functionPath,id:s.id,identity:s.identity,shardKey:s.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(r=>{Z(this.onPersistenceError,"append",r,s.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(a){throw Z(this.onPersistenceError,"load",a),a}let s=[],r=new Set(this.items.map(a=>a.id));for(let a of e)if(!r.has(a.id)){if(vt(this.version,a.version)){this.persistence.remove(a.id).catch(c=>{Z(this.onPersistenceError,"remove",c,a.id)});continue}r.add(a.id),s.push({args:a.args,baselineSeq:a.baselineSeq,clientId:a.clientId,functionPath:a.functionPath,id:a.id,identity:a.identity,reject:o(()=>{},"reject"),resolve:o(()=>{},"resolve"),shardKey:a.shardKey})}this.items.unshift(...s),this.evictOverflow(),this.notifySize();let i=new Set(this.items),n=new Set;for(let a of s)i.has(a)&&n.add(a.shardKey);return[...n]}restampIdentity(e,s){for(let r of this.items){if(r.identity!==e)continue;r.identity=s;let{id:i}=r;if(!this.persistence||i===void 0)continue;let n={args:r.args,...r.baselineSeq===void 0?{}:{baselineSeq:r.baselineSeq},clientId:r.clientId,functionPath:r.functionPath,id:i,identity:s,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}};this.rewriteStamp(i,n).catch(a=>{Z(this.onPersistenceError,"replace",a,i)})}}hasPending(e){return this.items.some(s=>e(s))}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.notifySize(),i}let s=[],r=[];for(let i of this.items)(e(i)?s:r).push(i);return this.items.length=0,this.items.push(...r),this.notifySize(),s}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],s=[];for(let r of this.items)if(r.precondition!==void 0&&!r.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",r.reject(i),e.push(r)}else s.push(r);return e.length>0&&(this.items.length=0,this.items.push(...s),this.notifySize()),e}clear(){for(let e of this.items){let s=new Error("CLIENT_CLOSED");s.code="CLIENT_CLOSED",e.reject(s)}this.items.length=0,this.notifySize()}async rewriteStamp(e,s){let r=this.persistence;if(r)try{await r.replace(s)}catch(i){Z(this.onPersistenceError,"replace",i,e)}}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(r=>{Z(this.onPersistenceError,"remove",r,e.id)});let s=new Error("offline queue overflow");s.code="OFFLINE_QUEUE_OVERFLOW",e.reject(s),this.onEvict?.(e,s)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var ri="lunora-outbox",ii="offline-mutations",St="by_id",ni=o((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new y("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let s=t.databaseName??ri,r=t.storeName??ii,i=Ne(e,s,1,a=>{a.objectStoreNames.contains(r)||a.createObjectStore(r,{autoIncrement:!0}).createIndex(St,"id",{unique:!0})}),n=qe(i,r);return{append:o(async a=>{await n("readwrite",c=>A(c.add(a)))},"append"),clear:o(async()=>{await n("readwrite",a=>A(a.clear()))},"clear"),load:o(async()=>n("readonly",a=>A(a.getAll())),"load"),remove:o(async a=>{await n("readwrite",async c=>{let u=await A(c.index(St).getKey(a));u!==void 0&&await A(c.delete(u))})},"remove"),replace:o(async a=>{await n("readwrite",async c=>{let u=await A(c.index(St).getKey(a.id));u!==void 0&&await A(c.put(a,u))})},"replace")}},"w"),Ns=o((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return ni()}},"b");var wt=o((t={},e=Math.random)=>{let s=t.initialDelayMs??250,r=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let a=Math.min(r,s*2**n);if(n+=1,!i)return a;let c=a/2;return Math.floor(c+e()*(a-c))},reset(){n=0}}},"s");var qs=new Set(["RATE_LIMITED","SHARD_ERROR","SHARD_UNAVAILABLE","TOO_MANY_REQUESTS"]),js=new Set(["TOKEN_EXPIRED","UNAUTHENTICATED","UNAUTHORIZED"]),Ks=o(t=>js.has(t?.code??""),"y"),Bs=o(t=>{if(t instanceof B)return!0;let e=t?.code;return e===void 0||qs.has(e)||js.has(e)},"O"),$s=6e4,ai=1e3,Ws=o(t=>{if(t===null)return;let e=Number(t);if(Number.isFinite(e))return e>0?e*1e3:void 0;let s=Date.parse(t);if(Number.isNaN(s))return;let r=s-Date.now();return r>0?r:void 0},"A"),oi={401:"UNAUTHORIZED",403:"FORBIDDEN",404:"NOT_FOUND",413:"PAYLOAD_TOO_LARGE",429:"TOO_MANY_REQUESTS"},de=o((t,e,s)=>{let r=Ws(s),i=r===void 0?void 0:{retryAfterMs:r},n=`LunoraClient: response carried no error envelope (status ${t.toString()}${e?` ${e}`:""})`;return t<400||t>=500||t===408?new B(n,i):new y(oi[t]??"BAD_REQUEST",n,{data:i})},"M"),le=o(t=>{let e=t?.error;return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0},"h"),Hs=o(()=>new B("LunoraClient: batch slot carried no error envelope"),"p"),zs=o((t,e)=>{let s=Ws(e);if(!(s===void 0||mt(t)!==void 0))return t.data===void 0?{retryAfterMs:s}:typeof t.data=="object"&&t.data!==null&&!Array.isArray(t.data)?{...t.data,retryAfterMs:s}:void 0},"N"),Ct=o((t,e=Math.random)=>{let s=Math.min(ai*2**Math.max(t-1,0),$s);return Math.round(s*(.5+e()*.5))},"f"),ci=o(t=>t instanceof B||qs.has(t?.code??""),"T"),Vs=o((t,e,s)=>{let r=mt(t);return r!==void 0&&r>0?Math.min(r,$s):ci(t)?Ct(e,s):void 0},"v"),Gs=983040,Js=o(t=>typeof TextEncoder>"u"?t.length:new TextEncoder().encode(t).length,"m"),Ys=new WeakSet,kt=o(t=>{let e=new y("WIRE_DECODE_FAILED",`LunoraClient: the call succeeded but its result could not be decoded (a mutation has still committed) \u2014 ${t instanceof Error?t.message:String(t)}`,{cause:t});return Ys.add(e),e},"U"),we=o(t=>t instanceof Error&&Ys.has(t),"b");var Xs=o((t,e,s,r)=>{let i=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r),n=i.present?Y(i.value):void 0;return()=>{let a=t.peekActiveQuerySnapshot(e.__lunoraRef,s,r);return!i.present||!a.present?!0:Y(a.value)===n}},"c");var Tt=500,ui=o(async t=>{let e=[],s;for(;;){let r=await t(s);if(e.push(...Array.isArray(r.records)?r.records:[]),r.truncated!==!0||typeof r.cursor!="string"||r.cursor.length===0)return e;if(r.cursor===s)throw new Error("collectPages: the list did not advance its cursor \u2014 refusing to page forever");s=r.cursor}},"We"),Zs=o((t,e)=>{if(t.size<e)return;let s=t.keys().next().value;s!==void 0&&t.delete(s)},"te");new TextDecoder;var hi=new TextEncoder,di=o(t=>ks(hi.encode(JSON.stringify(t))),"je"),li="x-lunora-expect-subject",fi=o(t=>di({subject:t}),"ze"),er=Symbol.for("lunora:session-change"),pi="lunora:session-change",mi="better-auth.message",yi="signout",cr=o(()=>{let t=globalThis,e=t[er];return e===void 0&&(e={detach:void 0,listeners:new Set,tab:`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`},t[er]=e),e},"de"),bi=o(()=>"document"in globalThis,"Xe"),gi=o(async()=>{let t=[];for(let e of cr().listeners)try{t.push(e())}catch{}await Promise.allSettled(t)},"Ze"),vi=o((t,e)=>{if(t!==mi||e===null)return!1;try{let s=JSON.parse(e);return s?.event==="session"&&s.data?.trigger===yi}catch{return!1}},"et"),Si=o(t=>{let e=[],s=o(()=>{gi().catch(()=>{})},"t"),r;try{r=typeof BroadcastChannel=="function"?new BroadcastChannel(pi):void 0}catch{r=void 0}if(r!==void 0){let n=r;n.addEventListener("message",a=>{a.data?.type==="lunora:session-change"&&a.data.tab!==t&&s()}),e.push(()=>{n.close()})}let i=globalThis;if(typeof i.addEventListener=="function"){let n=o(a=>{vi(a.key,a.newValue)&&s()},"i");i.addEventListener("storage",n),e.push(()=>{i.removeEventListener?.("storage",n)})}return()=>{for(let n of e)n()}},"tt"),wi=o(t=>{let e=cr();return e.listeners.add(t),e.detach===void 0&&bi()&&(e.detach=Si(e.tab)),()=>{e.listeners.delete(t),e.listeners.size===0&&(e.detach?.(),e.detach=void 0)}},"st"),re=class{static{o(this,"O")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[s]=e;for(let r of this.listeners)try{r(s)}catch{}}clear(){this.listeners.clear()}},Ci=o(t=>{let{afterFailedAttempts:e,intervalMs:s,onReachable:r,onStateChange:i,poll:n}=t,a=s>0&&e>0,c=0,u,h=!1,d=!1,l=o(()=>{u!==void 0&&(clearInterval(u),u=void 0,h=!1,i())},"u"),f=o(m=>{if(u!==void 0){if(!m){l();return}h||(h=!0,i()),r()}},"f"),p=o(()=>{d||(d=!0,n().then(f).finally(()=>{d=!1}).catch(()=>{}))},"p");return{isPolling:o(()=>u!==void 0&&h,"isPolling"),noteFailedOpen:o(()=>{c+=1,!(!a||u!==void 0||c<e)&&(u=setInterval(p,s),i(),p())},"noteFailedOpen"),noteOpen:o(()=>{c=0,l()},"noteOpen"),stop:l}},"rt"),ki="/_lunora/rpc",Et="/_lunora/rpc-batch",Ti="/_lunora/ws",It=o(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"D"),Ce=o(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"F"),tr=Symbol("lunora.unmergeableDelta"),Ei=o((t,e)=>{for(let s of e)s.op==="delete"?t.delete(s.key):s.value!==void 0&&t.set(s.key,s.value)},"at"),Ii="lunora-ping",Oi=3e4,Ri=1e4,Ai=5e3,Pi=3,Fi=250,Mi=5e3,xi=64,Li=3,Qi=1e4,_i=8,Di="/_lunora/admin/shard-traffic",Ui="/_lunora/admin/scheduled",Ni="/_lunora/admin/scheduled/status",qi="/_lunora/admin/scheduled/ws",ji="/_lunora/admin/scheduled/cancel",sr="/_lunora/admin/scheduled/dead",Ki="/_lunora/admin/scheduled/dead/retry",Bi="/_lunora/admin/scheduled/dead/cancel",$i="/_lunora/admin/workflows/instances",Wi="/_lunora/admin/workflows/instance",Hi="/_lunora/admin/workflows/status",Ot="/_lunora/admin/storage",zi="/_lunora/admin/storage/url",Vi="/_lunora/admin/storage/buckets",Gi="/_lunora/admin/functions",Ji="/_lunora/admin/cron-jobs",Yi="/_lunora/admin/cron-jobs/run",Xi="/_lunora/admin/openapi",Zi="/_lunora/admin/openrpc",en="/_lunora/admin/global/tables",tn="/_lunora/admin/global/table",sn="/_lunora/admin/global/facet",rn="/_lunora/admin/vector/indexes",nn="/_lunora/admin/vector/query",an="/_lunora/admin/logs/archive",on="/_lunora/admin/kv/namespaces",cn="/_lunora/admin/kv/keys",Rt="/_lunora/admin/kv/value",un="/_lunora/admin/auth/users",hn="/_lunora/admin/auth/sessions",dn="/_lunora/admin/auth/users/create",ln="/_lunora/admin/auth/users/role",fn="/_lunora/admin/auth/users/ban",pn="/_lunora/admin/auth/users/unban",mn="/_lunora/admin/auth/users/password",yn="/_lunora/admin/auth/users/remove",bn="/_lunora/admin/auth/users/impersonate",gn="/_lunora/admin/auth/sessions/revoke",vn="/_lunora/admin/auth/sessions/revoke-all",Sn="/_lunora/admin/auth/capabilities",wn="/_lunora/admin/auth/users/update",Cn="/_lunora/admin/auth/accounts",kn="/_lunora/admin/auth/accounts/unlink",Tn="/_lunora/admin/auth/passkeys",En="/_lunora/admin/auth/passkeys/delete",In="/_lunora/admin/auth/two-factor/disable",On="/_lunora/admin/auth/organizations",Rn="/_lunora/admin/auth/organizations/members",An="/_lunora/admin/auth/organizations/invitations",Pn="/_lunora/admin/auth/organizations/members/remove",Fn="/_lunora/admin/auth/organizations/invitations/cancel",Mn="/_lunora/admin/auth/config",xn="/_lunora/admin/auth/sign-up-invitations",Ln="/_lunora/admin/auth/sign-up-invitations/create",Qn="/_lunora/admin/auth/sign-up-invitations/revoke",_n="/_lunora/admin/auth/organizations/create",Dn="/_lunora/admin/auth/organizations/update",Un="/_lunora/admin/auth/organizations/remove",Nn="/_lunora/admin/auth/organizations/members/add",qn="/_lunora/admin/auth/organizations/members/invite",jn="/_lunora/admin/auth/organizations/members/role",Kn="/_lunora/admin/auth/organizations/teams",Bn="/_lunora/admin/auth/organizations/teams/create",$n="/_lunora/admin/auth/organizations/teams/update",Wn="/_lunora/admin/auth/organizations/teams/remove",Hn="/_lunora/admin/auth/organizations/teams/members",zn="/_lunora/admin/auth/organizations/teams/members/add",Vn="/_lunora/admin/auth/organizations/teams/members/remove",Gn="/_lunora/admin/auth/organizations/roles",Jn="/_lunora/admin/auth/organizations/roles/create",Yn="/_lunora/admin/auth/organizations/roles/update",Xn="/_lunora/admin/auth/organizations/roles/remove",Zn="/api/auth",ea="/get-session",At=o(t=>t==="connected"||t==="polling","W"),ta=o((t,e,s)=>t!==null||e&&s===null,"Hs"),rr=o(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"ne"),ee=o((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"C"),R=o((t,e)=>{let s=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&s.set(i,String(n));let r=s.toString();return r===""?t:`${t}?${r}`},"S"),sa=[Rs],g=o(t=>t??"","l"),ur=o((t,e)=>{let s=t.error,r=typeof s?.code=="string"?s.code:void 0,i=typeof s?.message=="string"?s.message:void 0;return{code:r,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"ue"),ra=o(t=>{let{code:e,messageText:s}=ur(t,"stream error");return e===void 0?new Error(s):new y(e,s)},"xs"),ir=o(t=>{let{code:e,messageText:s}=ur(t,"subscription error");return{message:s,...e===void 0?{}:{code:e}}},"ae");function Pt(t){if(t!==void 0)return e=>{t(e)}}o(Pt,"$");var te=o((t,e)=>{for(let s of t)try{s(e)}catch{}},"k"),ia=new TextDecoder,na=o(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return ia.decode(t)},"Bs"),Q=o((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"g"),Lt=o(t=>{let e=new Error(t.message??"request failed");if(e.code=t.code,t.data!==void 0)try{e.data=S(t.data)}catch{}return t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"z"),nr=o((t,e)=>{let s=Lt(t),r=zs(s,e);return r!==void 0&&(s.data=r),s},"oe"),se=o((t,e)=>{try{return E(t)}catch(s){let r=s instanceof Error?s.message:String(s);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${r}`,s instanceof Error?{cause:s}:void 0)}},"w"),aa=1e4,ar=o(async t=>{let e=new AbortController,s,r=new Promise((i,n)=>{s=setTimeout(()=>{e.abort(),n(new TypeError("LunoraClient: poll timed out"))},aa)});try{return await Promise.race([t(e.signal),r])}catch(i){throw e.signal.aborted?new TypeError("LunoraClient: poll timed out"):i}finally{clearTimeout(s)}},"ce"),or=o(t=>{try{return E(t),!0}catch{return!1}},"he"),Ft=o(t=>"args"in t?{...t,args:S(t.args)}:t,"j"),hr=o(t=>{let e=le(t);return e===void 0?Hs():Lt(e)},"le"),oa=o((t,e)=>{let s=Array.from({length:e});for(let r of t){if(typeof r.id!="number"||r.id<0||r.id>=e)continue;let i=r.body;s[r.id]=i!==void 0&&"error"in i?{error:hr(i),ok:!1}:{ok:!0,value:S(i?.result)}}return s.map(r=>r??{error:new Error("batch call returned no result"),ok:!1})},"Ds"),Mt=o((t,e)=>e!==null?{}:t===null?{expectSubject:null}:t?.startsWith("subj:")===!0?{expectSubject:t.slice(5)}:{},"G"),ca=Promise.resolve(),xt=class t{static{o(this,"fe")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,s){return{defaultValue:s,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;pollingFallbackAfterFailedAttempts;pollingFallbackIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;cacheSeededQueries=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new P;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;subjectToken=null;sessionProbesInFlight=0;sessionProbeGeneration=0;identityQuestions=0;identityAnsweredAt=0;releaseSessionChangeListener;warnedIdentityDisagreement=!1;identityResolutionExpected=!1;identitySettled=!1;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new re;statusListeners=new re;tokenExpiredListeners=new re;identityChangeListeners=new re;authRefusalNotifiedFor;mutationSettledListeners=new re;pendingChangeListeners=new re;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;adminSocketTeardowns=new Set;offlineFlushes=new Map;replayRetryState=new Map;replayRetryTimers=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??ee(rr(e.url),Ti),this.wsToken=e.wsToken;let s=e.authBasePath??Zn;this.authBasePath=s.endsWith("/")?s.slice(0,-1):s,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??Is(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??Oi,this.connectTimeoutMs=e.connectTimeoutMs??Ri,this.pollingFallbackIntervalMs=e.pollingFallback?.intervalMs??Ai,this.pollingFallbackAfterFailedAttempts=e.pollingFallback?.afterFailedAttempts??Pi,this.defaultConnectionContext=e.connectionContext,this.persistence=Ns(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=Es(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new je,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(r=>{this.readyResolve=r}):(this.readyResolved=!0,this.readyPromise=ca),this.offlineQueue=new We(e.offlineQueue,{onEvict:o((r,i)=>{this.emitItemSettled(r,"rejected",i)},"onEvict"),onSizeChange:o(r=>{this.pendingChangeListeners.emit(r)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${He()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})}),"document"in globalThis&&(this.releaseSessionChangeListener=wi(async()=>{!this.closed&&this.authToken===null&&await this.getCurrentUser().catch(()=>{})}))}setAuthToken(e,s){let r=this.authToken!==e,i=this.identityFingerprint(),n=this.authSubject===void 0||this.subjectToken===this.authToken,a=this.subjectAwaitingReconfirm(),c=this.isKnownNobody();this.authToken=e,this.applySubject(e,s);let u=this.identityFingerprint();u!==i&&(!r&&e!==null&&n?(this.restampQueuedIdentity(i,u),this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):!r&&e===null&&i===null&&n&&!c?(this.restampWatermarks(i,u),this.restampConnectionIdentity(i,u),this.reseedFromHydratedCache()):(this.rejectQueuedForIdentityChange(i),ta(i,c,e)&&this.evictPreviousIdentitySession()),this.restartTabCoordinatorForIdentity()),this.syncReadCacheToCredential(a),r&&this.authTokenListeners.emit(e),(u!==i||r||a)&&this.offlineQueue.size>0&&At(this.computeStatus())&&this.flushAllOfflineQueues()}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}expectIdentityResolution(){this.identityResolutionExpected=!0}currentBaseline(e){return this.baselineCursorFor(e)}replayIdentityVerdict(e){if(this.subjectAwaitingReconfirm())return"unknown";let s=this.identityFingerprint();return s===null&&this.identityUnresolved()?"unknown":e===s||e!==void 0&&this.isSameCredentialUnderTokenHash(e)?"match":s===null?"unknown":"mismatch"}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(this.identityFingerprint()??"")?.get(e??"")??0}async callMutator(e,s,r){let i=r?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new y("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=r?.shardKey??"",a=this.identityFingerprint(),c,u,h;try{u=await this.rpc(e,s,r?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:o(d=>{c=d},"onMutationAck")})}catch(d){if(!we(d))throw d;h=d}if(c!==void 0&&c>(this.clientWatermarks.get(a??"")?.get(n)??0)){let d=this.clientWatermarks.get(a??"");d===void 0&&(Zs(this.clientWatermarks,_i),d=new Map,this.clientWatermarks.set(a??"",d)),d.set(n,c)}if(h!==void 0)throw h;return{applied:c===void 0||c===i,result:u}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}onIdentityChange(e){return this.identityChangeListeners.add(e)}async getCurrentUser(){if(this.identityResolutionExpected=!0,this.closed||!this.fetchImpl)return this.identitySettled=!0,null;let e={},s=this.authToken;this.authToken&&(e.authorization=`Bearer ${this.authToken}`),this.sessionProbesInFlight+=1,this.identityQuestions+=1,this.sessionProbeGeneration=this.identityQuestions;let r=this.sessionProbeGeneration;try{let i=await this.fetchImpl(ee(this.url,`${this.authBasePath}${ea}`),{credentials:"include",headers:e,method:"GET"});if(!i.ok)return this.identitySettled=!0,i.status===401&&this.adoptResolvedSubject(s,null,r),null;let n=(await i.json())?.user??null;return this.identitySettled=!0,this.adoptResolvedSubject(s,n,r),n}finally{this.releaseSessionProbe()}}setWsToken(e){this.wsToken!==e&&(this.wsToken=e,this.bounceShardSockets())}setConnectionContext(e,s={}){this.assertLeaderOwnedSurface("setConnectionContext");let r=g(s.shardKey);e===void 0?this.connectionContexts.delete(r):this.connectionContexts.set(r,e),this.refreshConnectionContext(r)}acquireConnectionContext(e,s={}){if(this.followsAnotherTab())return()=>{};let r=g(s.shardKey),i={context:e},n=this.connectionContextHolders.get(r);n?n.push(i):this.connectionContextHolders.set(r,[i]),this.refreshConnectionContext(r);let a=!1;return()=>{if(a)return;a=!0;let c=this.connectionContextHolders.get(r);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(r),this.refreshConnectionContext(r)}}whisperSubscribe(e,s,r={}){this.assertLeaderOwnedSurface("whisperSubscribe");let i=g(r.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let a=n.get(e),c=a===void 0;if(a||(a=new Set,n.set(e,a)),a.add(s),this.ensureSocket(r.shardKey),c){let u=this.getConnection(r.shardKey);u&&Q(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),h=u?.get(e);if(!h?.delete(s)||h.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let d=this.getConnection(r.shardKey);d&&Q(d,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,s,r={}){this.assertLeaderOwnedSurface("whisper"),this.ensureSocket(r.shardKey);let i=this.getConnection(r.shardKey);i&&Q(i,{data:se(s??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let s=this.statusListeners.add(e);return e(this.computeStatus()),s}pendingCount(){return this.offlineQueue.size}debug(){let e=[],s=this.clientWatermarks.get(this.identityFingerprint()??""),r=new Set([...this.connections.keys(),...s?.keys()??[]]);for(let n of r){let a=this.connections.get(n);e.push({confirmedMutationWatermark:s?.get(n)??0,hasSocket:a?.socket!==void 0,shardKey:n===""?void 0:n,wasEverConnected:a?.wasEverConnected??!1,wsState:a?.wsState??"idle"})}let i=this.subscriptions.all().map(n=>({acked:n.acked,functionPath:n.fn.__lunoraRef,id:n.id,kind:"query",lastMutationId:n.lastMutationId,pendingOptimisticLayers:n.optimisticLayers.length,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size}));for(let n of this.shapeSubscriptions.values())i.push({acked:n.serverCursor!==void 0,functionPath:`shape:${n.name}`,id:n.id,kind:"shape",lastMutationId:n.lastMutationId,pendingOptimisticLayers:0,rowCount:n.rows.size,serverCursor:n.serverCursor,shardKey:n.shardKey,subscriberCount:n.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((n,a)=>(n.shardKey??"").localeCompare(a.shardKey??"")),subscriptions:i.toSorted((n,a)=>n.functionPath.localeCompare(a.functionPath))}}onPendingChange(e){let s=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),s}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,s){this.clientQueryStore.set(e,s)}subscribeClientQuery(e,s){return this.clientQueryStore.subscribe(e,s)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,s,r){return Xs(this,e,s,r)}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,s,r){if(!this.readyResolved)return;let i=Y(s),n=ae(e,i,r),a=this.hydratedQueryCache.get(n);if(a!==void 0)return this.cachedQueryMatchesIdentity(a)?a.value:void 0}peekActiveQuerySnapshot(e,s,r){let i=P.key(e,s,r),n=this.subscriptions.get(i);return{present:n!==void 0,value:n?.lastValue}}async query(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0})}async batch(e){return this.sendBatch(e)}async mutation(e,s,r={}){let{value:i}=await this.runMutation(e,s,r);return i}canQueueOffline(e){let{wasEverConnected:s}=this.connectionGateState(e);return this.WebSocketImpl!==void 0&&(s||this.offlineQueue.queueBeforeFirstConnect)}async action(e,s,r={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,s,r.shardKey,{attachBookmark:!0,captureBookmark:!0})}async importRows(e,s,r={}){this.assertOpen();let i=Math.max(1,Math.trunc(r.chunkSize??500)),n=r.toArgs??(d=>({rows:d})),a=s.length,c=0,u=0,h=0;for(let d=0;d<a;d+=i){let l=s.slice(d,d+i),f=h,{committed:p}=await this.runMutation(e,n(l),{...r.importId===void 0?{}:{mutationId:`${r.importId}:${String(f)}`},shardKey:r.shardKey});h+=1,c+=l.length,p&&(u+=l.length),r.onProgress?.({done:c,total:a})}return{chunks:h,imported:u,queued:c-u}}async shardTraffic(e){this.assertOpen();let s=await this.adminFetch(Di,"POST",{table:e});return{failed:s.failed??0,ok:s.ok??0,shards:s.shards??[]}}async listScheduledJobs(){return this.assertOpen(),((await this.adminFetch(Ui,"GET")).records??[]).map(e=>Ft(e))}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(Ni,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(ji,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await ui(async e=>await this.adminFetch(e===void 0?sr:`${sr}?cursor=${encodeURIComponent(e)}`,"GET"))).map(e=>Ft(e))}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Ki,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(Bi,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();let s=new URLSearchParams({name:e.name});e.status!==void 0&&s.set("status",e.status),e.page!==void 0&&s.set("page",String(e.page)),e.perPage!==void 0&&s.set("perPage",String(e.perPage));let r=await this.adminFetch(`${$i}?${s.toString()}`,"GET");return{configured:r.configured,instances:r.instances??[],page:r.page??1,perPage:r.perPage??e.perPage??0,totalCount:r.totalCount}}async getWorkflowInstance(e){this.assertOpen();let s=new URLSearchParams({id:e.id,name:e.name}),r=await this.adminFetch(`${Wi}?${s.toString()}`,"GET");return{createdOn:r.createdOn,endedOn:r.endedOn,error:r.error,id:r.id??e.id,output:r.output,params:r.params,startedOn:r.startedOn,status:r.status??"unknown",steps:r.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Hi,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let s=ee(rr(this.url),qi),r=wt(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,a=!1,c=o(()=>{a||this.closed||(n=setTimeout(d,r.next()))},"a"),u=o(f=>{if(a||this.WebSocketImpl===void 0)return;let p=f===void 0?s:`${s}?token=${encodeURIComponent(f)}`;this.openManagedSocket(i,p,this.connectTimeoutMs,{onClose:o(()=>{c()},"onClose"),onMessage:o(m=>{let b;try{b=JSON.parse(typeof m.data=="string"?m.data:"")}catch{return}b.type==="jobs"&&Array.isArray(b.records)&&(r.reset(),e(b.records.map(w=>Ft(w))))},"onMessage")})},"o"),h=o(async f=>{let p;try{p=await f()}catch{c();return}u(p)},"h"),d=o(()=>{if(a||this.WebSocketImpl===void 0)return;let{wsToken:f}=this;if(typeof f=="function"){h(f).catch(()=>{});return}u(f)},"d");d();let l=o(()=>{a=!0,n!==void 0&&(clearTimeout(n),n=void 0),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close(),i.socket=void 0},"u");return this.adminSocketTeardowns.add(l),()=>{this.adminSocketTeardowns.delete(l),l()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Gi,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Ji,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let s=await this.adminFetch(Yi,"POST",{name:e});return{name:s.name??e,ran:s.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(Xi,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Zi,"GET")}async listStorageObjects(e={}){this.assertOpen();let s=R(Ot,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),r=await this.adminFetch(s,"GET");return{cursor:r.cursor,objects:r.objects??[]}}async deleteStorageObject(e,s){this.assertOpen();let r=`${Ot}?key=${encodeURIComponent(e)}${It(s?.bucket)}`,i=await this.adminFetch(r,"DELETE");return{deleted:i.deleted===!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Vi,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let s=`${Ot}?key=${encodeURIComponent(e.key)}${It(e.bucket)}`,r=await this.adminFetch(s,"PUT",e.body,e.contentType);return{etag:r.etag,key:r.key??e.key}}async signedStorageUrl(e,s){this.assertOpen();let r=s?.expiresInSeconds,i=r===void 0?"":`&expiresIn=${encodeURIComponent(r.toString())}`,n=`${zi}?key=${encodeURIComponent(e)}${i}${It(s?.bucket)}`,a=await this.adminFetch(n,"GET");if(typeof a.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return a.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(en,"GET")}async readGlobalTablePage(e){this.assertOpen();let s=new URLSearchParams({table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(E(e.filters))),S(await this.adminFetch(`${tn}?${s.toString()}`,"GET"))}async facetGlobalColumn(e){this.assertOpen();let s=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&s.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&s.set("filters",JSON.stringify(E(e.filters))),S(await this.adminFetch(`${sn}?${s.toString()}`,"GET"))}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(rn,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(nn,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let s=await this.adminFetch(an,"POST",e);return{nextCursor:s.nextCursor,rows:s.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(on,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let s=R(cn,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(s,"GET")}async getKvValue(e){this.assertOpen();let s=R(Rt,{key:e.key,namespace:e.namespace});return await this.adminFetch(s,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(Rt,"PUT",e)}async deleteKvKey(e){this.assertOpen();let s=R(Rt,{key:e.key,namespace:e.namespace});await this.adminFetch(s,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let s=R(un,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(s,"GET")}async createAuthUser(e){return await this.adminFetch(dn,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(ln,"POST",e)}async banAuthUser(e){return await this.adminFetch(fn,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(pn,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(mn,"POST",e)}async removeAuthUser(e){await this.adminFetch(yn,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(bn,"POST",e)}async revokeAuthSession(e){await this.adminFetch(gn,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(vn,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(Sn,"GET")}async updateAuthUser(e){return await this.adminFetch(wn,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(R(Cn,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(kn,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(R(Tn,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(En,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(In,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(R(On,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let s=R(Rn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthOrgInvitations(e){let s=R(An,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async listAuthSignUpInvitations(e={}){let s=R(xn,{limit:e.limit,offset:e.offset});return await this.adminFetch(s,"GET")}async createAuthSignUpInvitation(e){return await this.adminFetch(Ln,"POST",e)}async revokeAuthSignUpInvitation(e){await this.adminFetch(Qn,"POST",e)}async removeAuthOrgMember(e){await this.adminFetch(Pn,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(Fn,"POST",e)}async getAuthConfig(){return await this.adminFetch(Mn,"GET")}async createAuthOrganization(e){return await this.adminFetch(_n,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(Dn,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(Un,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(Nn,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(qn,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(jn,"POST",e)}async listAuthOrgTeams(e){let s=R(Kn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(Bn,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch($n,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(Wn,"POST",e)}async listAuthOrgTeamMembers(e){let s=R(Hn,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(s,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(zn,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Vn,"POST",e)}async listAuthOrgRoles(e){let s=R(Gn,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(s,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Jn,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Yn,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Xn,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let s=R(hn,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(s,"GET")}subscribe(e,s,r,i={}){this.assertOpen();let n=s??{},a=P.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(a),u=Pt(r),h=Pt(i.onError),d=Pt(i.onCheckpoint);if(!c){this.nextSubId+=1;let f=`sub_${this.nextSubId.toString()}`,p=Y(n),m=this.takeHydratedCache(e.__lunoraRef,p,i.shardKey);c={acked:!1,args:n,argsKey:p,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:f,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,wireArgs:se(n,`args for '${e.__lunoraRef}'`),...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c),m!==void 0&&this.cacheSeededQueries.set(a,m)}if(c.callbacks.add(u),h&&c.errorCallbacks.add(h),d&&c.checkpointCallbacks.add(d),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let l=c;return()=>{l.callbacks.delete(u),h&&l.errorCallbacks.delete(h),d&&l.checkpointCallbacks.delete(d),l.callbacks.size===0&&(this.sendOrQueueUnsubscribe(l.shardKey,l.id,"unsubscribe"),this.returnCacheSeed(P.keyOf(l)),this.subscriptions.remove(l))}}subscribeShape(e,s,r={}){if(this.assertOpen(),this.followsAnotherTab()){let{onError:a}=r;return a!==void 0&&queueMicrotask(()=>{a({code:"NOT_IMPLEMENTED",message:"LunoraClient: `subscribeShape` is unavailable on a cross-tab follower tab. The `crossTabSync` channel only carries data from the leader tab outward and shape pokes are not part of that broadcast set, so this subscription could never resolve. Turn off `crossTabSync`, or use a `list`-backed collection, which IS relayed."})}),()=>{}}this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([s]),errorCallbacks:r.onError?new Set([r.onError]):new Set,id:i,name:e.name,onCheckpoint:r.onCheckpoint,rows:new Map,shardKey:r.shardKey,wireArgs:e.args===void 0?void 0:se(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(r.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(e,s,r={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new y("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=r,a=s??{},{handle:c,iterable:u}=Be({maxBuffer:r.maxBuffer,onCancel:o(()=>{this.cancelStream(i,n)},"onCancel")});this.ensureSocket(n);let h=this.getConnection(n),d={id:i,query:{args:se(a,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"},l={durable:r.durable===!0,generation:void 0,handle:c,lastSeq:0,message:d,shardKey:n,started:!1};this.streams.set(i,l);let f=h?.wsState==="open"&&Q(h,d);if(l.started=f,!f&&h===void 0)return this.streams.delete(i),c.fail(new y("STREAM_DISCONNECTED","stream unavailable: this tab is not the cross-tab WebSocket leader, so it holds no socket to stream over")),u;if(!f){for(h.pendingStreams=h.pendingStreams??[];h.pendingStreams.length>=xi;){let p=h.pendingStreams.shift()?.id,m=p?this.streams.get(p):void 0;m&&(m.handle.fail(new y("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(p))}h.pendingStreams.push(d)}return u}httpStream(e,s,r={}){if(this.closed)throw new y("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...r.headers};return xs(e,s,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:r.maxBuffer,signal:r.signal})}close(){this.closed=!0,this.releaseSessionChangeListener?.(),this.releaseSessionChangeListener=void 0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new y("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);for(let e of this.adminSocketTeardowns)e();this.adminSocketTeardowns.clear();for(let e of this.replayRetryTimers.values())clearTimeout(e);this.replayRetryTimers.clear(),this.replayRetryState.clear(),this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.identityChangeListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.subscriptions.clear(),this.clientQueryStore.clear(),this.hydratedQueryCache.clear(),this.cacheSeededQueries.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new y("INTERNAL","LunoraClient is closed")}followsAnotherTab(){let e=this.tabCoordinator;if(e===void 0||e.isLeader())return!1;let s=e.leaderTabId;return s!==void 0&&s!==e.id}assertLeaderOwnedSurface(e){if(this.followsAnotherTab())throw new y("NOT_IMPLEMENTED",`LunoraClient: \`${e}\` is unavailable on a cross-tab follower tab. The \`crossTabSync\` channel only carries data from the leader tab outward, so this call could never reach the server. Turn off \`crossTabSync\`, or keep \`${e}\` on the leader tab.`)}clearConnectionTimers(e){clearTimeout(e.reconnectTimer),clearTimeout(e.connectTimer),clearTimeout(e.stableTimer),e.reconnectTimer=void 0,e.connectTimer=void 0,e.stableTimer=void 0}teardownConnection(e){e.polling.stop();let s=g(e.shardKey);for(let[r,i]of this.streams)g(i.shardKey)===s&&(i.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: the connection carrying it was torn down")),this.streams.delete(r));if(e.pendingStreams=void 0,e.pendingUnsubscribes=[],this.clearResubscribeQueue(e),this.clearConnectionTimers(e),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new Ke({channelName:e,onBecomeLeader:o(()=>{for(let s of this.subscriptions.all())this.ensureSocket(s.shardKey),this.queueResubscribe(s);for(let s of this.queuedOfflineShardKeys)this.ensureSocket(s);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:o(()=>{for(let[s,r]of this.connections)this.teardownConnection(r),this.connections.delete(s);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:o((s,r)=>{if(r!==void 0&&r!==this.identityFingerprint())return;let i=s==="connected"&&this.leaderStatus!=="connected"||s==="polling"&&this.leaderStatus!=="connected"&&this.leaderStatus!=="polling";this.leaderStatus=s,s==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},"onConnectionStatus"),onSubscriptionData:o((s,r,i,n,a)=>{if(a!==void 0&&a!==this.identityFingerprint())return;let c=this.subscriptions.get(s);c&&(c.serverBase=r,this.dropCacheSeed(s),i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),$e(c,i)),V(c,X(r,c.optimisticLayers)))},"onSubscriptionData"),onLeaderClaimAnswered:o(()=>{this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onLeaderClaimAnswered"),onSubscriptionError:o((s,r,i)=>{if(i!==void 0&&i!==this.identityFingerprint())return;let n=this.subscriptions.get(s);n&&te(n.errorCallbacks,r)},"onSubscriptionError"),onSubscriptionSettled:o((s,r,i,n,a,c)=>{if(c!==void 0&&c!==this.identityFingerprint())return;let u=this.subscriptions.get(s);if(u){this.ackAndAdvanceCursor(u,r,i),n!==void 0&&a===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let h of u.checkpointCallbacks)h({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async sendBatch(e,s){if(this.assertOpen(),!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(ee(this.url,Et),{body:JSON.stringify({calls:e.map((c,u)=>({args:se(c.args??{},`args for batch call '${c.fn.__lunoraRef}'`),functionPath:c.fn.__lunoraRef,id:u,shardKey:c.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST",signal:s}),i=r.headers.get("x-d1-bookmark");i&&this.bookmark.set(i);let n;try{n=await r.json()}catch{throw new y("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}let a=le(n);if(!r.ok||a!==void 0&&!n.results)throw a!==void 0?Lt(a):new y("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let c of n.results??[]){let u=c.body?.commitCursor;typeof c.id=="number"&&typeof u=="number"&&this.recordShardCursor(e[c.id]?.shardKey,u)}return oa(n.results??[],e.length)}async runMutation(e,s,r){this.assertOpen();let i=s,n=r.mutationId??He(),a=r.replayBaseline===void 0?this.baselineCursorFor(r.shardKey):r.replayBaseline??void 0,{confirms:c,rollbacks:u}=this.applyOptimisticUpdates(e.__lunoraRef,i,r.shardKey,r.optimistic);r.optimisticUpdate&&this.applyOptimisticUpdate(r.optimisticUpdate,s,r.shardKey,u,c);let h=this.offlineFlushes.get(g(r.shardKey));h!==void 0&&await h;let{hasSocket:d,polling:l,wasEverConnected:f,wsState:p}=this.connectionGateState(r.shardKey),{queueBeforeFirstConnect:m}=this.offlineQueue,b=f||m,w=this.WebSocketImpl!==void 0&&b,k=p==="connecting"&&b&&!l,F=p!=="open"&&!d&&w&&!l,_=w&&r.replayBaseline===void 0&&this.hasPendingWriteAhead(r.shardKey),N=o(async()=>this.enqueueOfflineMutation(e,i,r.shardKey,a,n,u,c,r.precondition,r.mutationId),"V");if(F||k||_)return N();let D;try{let $=await this.rpc(e.__lunoraRef,i,r.shardKey,{baselineSeq:a,captureBookmark:!0,...Mt(r.replayIdentity,this.authToken),mutationId:n,onCommitCursor:o(M=>{D=M},"onCommitCursor")});for(let M of c)M(D);return{committed:!0,value:$}}catch($){if(l&&w&&$ instanceof TypeError&&or(i))return N();throw this.settleFailedDirectWrite($,D,c,u),$}}settleFailedDirectWrite(e,s,r,i){if(this.noteIdentityMismatch(e),we(e)){for(let n of r)n(s);return}Ce(i)}async enqueueOfflineMutation(e,s,r,i,n,a,c,u,h){let d=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let l=this.outboxMutationCounter;try{await this.outbox.enqueue({args:s,baselineSeq:i,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:h??`${this.clientId}:${String(l)}`,identity:d,mutationId:l,...a.length>0&&{onRejected:o(()=>{Ce(a)},"onRejected")},shardKey:r})}catch(f){throw Ce(a),f instanceof Error?f:new Error(String(f))}for(let f of c)f(void 0);return{committed:!1,value:void 0}}return{committed:!0,value:await new Promise((l,f)=>{let p={args:s,functionPath:e.__lunoraRef,liveAwaiter:!0,baselineSeq:i,id:n,clientId:this.clientId,identity:d,precondition:u,onCommit:o(m=>{for(let b of c)b(m)},"onCommit"),reject:o(m=>{this.queuedIdentities.delete(n),we(m)||Ce(a),f(m instanceof Error?m:new Error(String(m)))},"reject"),resolve:l,shardKey:r};this.offlineQueue.enqueue(p),this.queuedOfflineShardKeys.add(r),p.id!==void 0&&this.queuedIdentities.set(p.id,d)})}}hasPendingWriteAhead(e){if(this.outbox)return this.outbox.pending?.()??!1;let s=g(e);return this.offlineQueue.hasPending(r=>g(r.shardKey)===s)}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let s of e)this.queuedOfflineShardKeys.add(s),this.ensureSocket(s)}catch{}}hydrateAsOutboxLeader(){let e=o(()=>{this.hydratePersistedQueue().catch(()=>{})},"e"),s=globalThis.navigator?.locks;if(!s){e();return}s.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(r=>{if(this.closed){r();return}this.outboxLeaderRelease=r}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load(),s=new Map;for(let r of this.subscriptions.all())s.set(ae(r.fn.__lunoraRef,r.argsKey,r.shardKey),r);for(let{key:r,...i}of e){if(vt(this.persistenceVersion,i.version)){this.queryCache.remove(r).catch(()=>{});continue}let n=s.get(r);if(n&&this.cachedQueryMatchesIdentity(i)){this.seedSubscriptionFromCache(n,i);continue}this.hydratedQueryCache.set(r,i)}}catch{}}seedSubscriptionFromCache(e,s){e.serverBase!==void 0||e.lastValue!==void 0||!this.cachedQueryMatchesIdentity(s)||(e.serverBase=s.value,e.serverCursor=s.serverCursor,s.serverEpoch!==void 0&&(e.serverEpoch=s.serverEpoch),this.cacheSeededQueries.set(ae(e.fn.__lunoraRef,e.argsKey,e.shardKey),s),V(e,X(s.value,e.optimisticLayers)))}syncReadCacheToCredential(e){this.subjectAwaitingReconfirm()?this.revokeCacheSeededValues():e&&this.reseedFromHydratedCache()}dropCacheSeed(e){this.cacheSeededQueries.delete(e),this.hydratedQueryCache.delete(e)}returnCacheSeed(e){let s=this.cacheSeededQueries.get(e);s!==void 0&&(this.cacheSeededQueries.delete(e),this.hydratedQueryCache.set(e,s))}revokeCacheSeededValues(){if(this.cacheSeededQueries.size!==0){for(let[e,s]of this.cacheSeededQueries){let r=this.subscriptions.get(e);r!==void 0&&(r.serverBase=void 0,r.serverCursor=void 0,r.serverEpoch=void 0,V(r,X(void 0,r.optimisticLayers))),this.hydratedQueryCache.set(e,s)}this.cacheSeededQueries.clear()}}takeHydratedCache(e,s,r){let i=ae(e,s,r),n=this.hydratedQueryCache.get(i);if(!(n===void 0||!this.cachedQueryMatchesIdentity(n)))return this.hydratedQueryCache.delete(i),n}reseedFromHydratedCache(){if(this.hydratedQueryCache.size!==0)for(let e of this.subscriptions.all()){let s=ae(e.fn.__lunoraRef,e.argsKey,e.shardKey),r=this.hydratedQueryCache.get(s);r!==void 0&&this.cachedQueryMatchesIdentity(r)&&(this.hydratedQueryCache.delete(s),this.seedSubscriptionFromCache(e,r))}}persistQueryValue(e){let s=e.serverBase;if(!this.queryCache||s===void 0)return;let r=ae(e.fn.__lunoraRef,e.argsKey,e.shardKey),i=this.getConnection(e.shardKey)?.identity,n=i===void 0?this.identityFingerprint():i;n===null&&this.identityUnresolved()||(this.pendingCacheWrites.set(r,{identity:n,serverCursor:e.serverCursor,ts:Date.now(),value:s,...n===this.identityFingerprint()&&!this.subjectAwaitingReconfirm()?this.credentialStamp():{},...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},Fi))}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let s=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(s.map(async([r,i])=>e.put(r,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(s=>s.wsState==="open")?"connected":e.some(s=>s.polling.isPolling())?"polling":e.some(s=>s.wsState==="connecting")?"connecting":"offline"}baselineCursorFor(e){let s=g(e),r;for(let i of this.subscriptions.all())g(i.shardKey)!==s||i.serverCursor===void 0||(r=r===void 0?i.serverCursor:Math.max(r,i.serverCursor));return r}async pollSubscriptions(e){let s=g(e),r=[];for(let c of this.subscriptions.all())g(c.shardKey)===s&&(or(c.args)?r.push(c):te(c.errorCallbacks,{code:"WIRE_ENCODE_FAILED",message:"could not encode this subscription's args for a poll"}));if(r.length===0)return this.probeOrigin();let i=Qs(),n=this.identityFingerprint(),a;try{a=await ar(async c=>this.sendBatch(r.map(u=>({args:u.args,fn:u.fn,shardKey:u.shardKey})),c))}catch(c){return!(c instanceof TypeError)}if(this.identityFingerprint()!==n)return!0;for(let[c,u]of r.entries()){let h=a[c];if(h!==void 0){if(!h.ok){te(u.errorCallbacks,{code:h.error.code,message:h.error.message});continue}this.handleDataMessage({data:E(h.value),id:u.id,type:"data"},i)}}return!0}async probeOrigin(){let{fetchImpl:e}=this;if(!e)return!1;try{return await ar(async s=>e(ee(this.url,Et),{body:JSON.stringify({calls:[]}),headers:this.rpcRequestHeaders({}),method:"POST",signal:s})),!0}catch{return!1}}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,s,r){this.mutationSettledListeners.emit({args:e.args,code:r===void 0?void 0:r.code,error:r,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:s})}applyOptimisticUpdates(e,s,r,i){let n=[],a=[];if(!i)return{confirms:n,rollbacks:a};let c=P.key(e,s,r),u=this.subscriptions.get(c);if(u){let h=gt(u,i);h&&(n.push(h.confirm),a.push(h.rollback))}return{confirms:n,rollbacks:a}}applyOptimisticUpdate(e,s,r,i,n){let{confirms:a,rollbacks:c,store:u}=Ds(this.subscriptions,r);try{e(u,s)}catch{Ce(c);return}i.push(...c),n.push(...a)}getConnection(e){return this.connections.get(g(e))}sendOrQueueUnsubscribe(e,s,r){let i=this.getConnection(e);i&&!Q(i,{id:s,type:r})&&i.pendingUnsubscribes.push({id:s,type:r})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let r="idle";return this.leaderStatus==="connected"?r="open":this.leaderStatus==="connecting"&&(r="connecting"),{hasSocket:!1,polling:this.leaderStatus==="polling",wasEverConnected:this.leaderWasEverConnected,wsState:r}}let s=this.getConnection(e);return{hasSocket:s?.socket!==void 0,polling:s?.polling.isPolling()??!1,wasEverConnected:s?.wasEverConnected??!1,wsState:s?.wsState??"idle"}}getOrCreateConnection(e){let s=g(e),r=this.connections.get(s);return r||(r={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],polling:Ci({afterFailedAttempts:this.pollingFallbackAfterFailedAttempts,intervalMs:this.pollingFallbackIntervalMs,onReachable:o(()=>{this.flushOfflineQueue(e).catch(()=>{})},"onReachable"),onStateChange:o(()=>{this.emitConnectionStatus()},"onStateChange"),poll:o(async()=>this.pollSubscriptions(e),"poll")}),reconnect:wt(this.reconnectOptions),reconnectTimer:void 0,resubscribePending:new Map,resubscribeQueue:[],shardKey:e,socket:void 0,stableTimer:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(s,r)),r}wsUrlFor(e,s){let r=[];if(e!==void 0&&r.push(`shard=${encodeURIComponent(e)}`),s!==void 0&&r.push(`token=${encodeURIComponent(s)}`),r.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${r.join("&")}`}rpcRequestHeaders(e,s){let r={"content-type":"application/json"};e.expectSubject!==void 0&&(r[li]=fi(e.expectSubject));let i=this.shardCursors.get(this.cursorKeyFor(s));i!==void 0&&(r["x-lunora-min-seq"]=i.toString());let n=e.authToken===void 0?this.authToken:e.authToken;if(n&&(r.authorization=`Bearer ${n}`),e.mutationId&&(r["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(r["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(r["x-lunora-client-seq"]=e.clientSeq.toString()),e.baselineSeq!==void 0&&(r["x-lunora-base-seq"]=e.baselineSeq.toString()),e.attachBookmark){let a=this.bookmark.get();a&&(r["x-d1-bookmark"]=a)}return r}async rpc(e,s,r,i={}){if(!this.fetchImpl)throw new B("LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,r),a=await this.fetchImpl(ee(this.url,ki),{body:JSON.stringify({args:se(s,`args for '${e}'`),functionPath:e,shardKey:r}),headers:n,method:"POST"});if(i.captureBookmark){let d=a.headers.get("x-d1-bookmark");d&&this.bookmark.set(d)}let c;try{c=await a.json()}catch{throw de(a.status,a.statusText,a.headers.get("retry-after"))}let u=c;if(typeof u!="object"||u===null||Array.isArray(u))throw de(a.status,a.statusText,a.headers.get("retry-after"));let h=le(c);if(h!==void 0)throw nr(h,a.headers.get("retry-after"));if(!a.ok)throw de(a.status,a.statusText,a.headers.get("retry-after"));i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.learnDefaultShardKey(a,r),this.recordShardCursor(r,c.commitCursor);try{return S(c.result)}catch(d){throw kt(d)}}async adminFetch(e,s,r,i){if(!this.fetchImpl)throw new y("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let a=r instanceof ArrayBuffer||r instanceof Blob,c;r===void 0?c=void 0:a?(c=r,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(r),n["content-type"]="application/json");let u=await this.fetchImpl(ee(this.url,e),{body:c,headers:n,method:s}),h;try{h=await u.json()}catch{let l=u.statusText?` ${u.statusText}`:"";throw new y("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${l})`)}let d=le(h);if(d!==void 0){let l=new Error(d.message??"admin request failed");throw l.code=d.code,l}if(!u.ok){let l=u.statusText?` ${u.statusText}`:"";throw new y("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${l})`)}return h}effectiveConnectionContext(e){let s=this.connectionContextHolders.get(e);return s&&s.length>0?s[s.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let s=this.connections.get(e);s?.wsState==="open"&&this.sendConnectEnvelope(s)}sendConnectEnvelope(e){let s=this.effectiveConnectionContext(g(e.shardKey));Q(e,{caps:sa,clientId:this.clientId,id:"connect",type:"connect",...s===void 0?{}:{context:s}})}resendShapeSubscriptions(e){for(let s of this.shapeSubscriptions.values())g(s.shardKey)===g(e)&&this.sendShapeSubscribeIfOpen(s)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let s=this.getOrCreateConnection(e);if(!(s.wsState==="open"||s.wsState==="connecting")){if(s.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(s,e,this.wsToken).catch(()=>{});return}this.openSocket(s,e,this.wsToken)}}async openSocketWithProvidedToken(e,s,r){let i;try{i=await r()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,s,i)}openManagedSocket(e,s,r,i){let{WebSocketImpl:n}=this;if(n===void 0)throw new y("INTERNAL","no WebSocket implementation available");let a=new n(s);e.socket=a;let c=o(()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===a&&(e.socket=void 0)},"a"),u=o(h=>{c(),i.onClose(h)},"o");r>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===a){try{a.close()}catch{}u()}},r)),a.addEventListener("open",()=>{if(e.socket===a){e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now();try{i.onOpen?.()}catch(h){console.error("[lunora] connection open handler threw",h)}this.startHeartbeat(e,u)}}),a.addEventListener("message",h=>{if(e.socket===a){e.lastFrameAt=Date.now();try{i.onMessage(h)}catch(d){console.error("[lunora] server frame handler threw",d)}}}),a.addEventListener("close",h=>{e.socket===a&&u(h)}),a.addEventListener("error",()=>{e.socket===a&&u()})}openSocket(e,s,r){this.WebSocketImpl!==void 0&&(e.identity=this.identityFingerprint(),r===void 0&&this.authToken===null?(this.identityQuestions+=1,e.identityQuestion=this.identityQuestions):e.identityQuestion=void 0,e.retired=!1,this.openManagedSocket(e,this.wsUrlFor(s,r),this.connectTimeoutMs,{onClose:o(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:o(i=>{e.retired!==!0&&this.handleServerMessage(i.data,s)},"onMessage"),onOpen:o(()=>{e.wsState="open",e.wasEverConnected=!0,e.polling.noteOpen(),clearTimeout(e.stableTimer),e.stableTimer=setTimeout(()=>{e.wsState==="open"&&e.reconnect.reset()},Mi),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(s),this.clearResubscribeQueue(e);for(let n of this.subscriptions.all())g(n.shardKey)===g(s)&&this.queueResubscribe(n);if(this.resendShapeSubscriptions(s),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:a,type:c}of n)Q(e,{id:a,type:c})}this.flushPendingStreams(e);let i=this.whisperHandlers.get(g(s));if(i)for(let n of i.keys())Q(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(s).catch(()=>{})},"onOpen")}))}flushPendingStreams(e){if(!e.pendingStreams||e.pendingStreams.length===0)return;let s=e.pendingStreams;e.pendingStreams=[];for(let r of s){let i=Q(e,r)?this.streams.get(String(r.id)):void 0;i&&(i.started=!0)}}cancelStream(e,s){let r=this.getConnection(s),i=this.streams.get(e);r&&(r.pendingStreams=r.pendingStreams?.filter(n=>n.id!==e),!Q(r,{id:e,type:"unsubscribe"})&&i?.durable===!0&&i.started&&r.pendingUnsubscribes.push({id:e,type:"unsubscribe"})),this.streams.delete(e)}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;e.wsState==="connecting"&&e.polling.noteFailedOpen(),this.stopHeartbeat(e),this.clearConnectionTimers(e),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey),this.clearResubscribeQueue(e);let s=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(g(n.shardKey)!==g(e.shardKey)||s.has(i))){if(n.durable){let a={...n.message,...n.generation===void 0?{}:{generation:n.generation},sinceChunk:n.lastSeq};n.message=a,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),a];continue}n.handle.fail(new y("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(i)}if(this.WebSocketImpl===void 0)return;let r=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},r)}startHeartbeat(e,s){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;let{socket:r}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{r.close()}catch{}s();return}try{r.send(Ii)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){let s=g(e);for(let r of this.subscriptions.all())g(r.shardKey)===s&&(r.acked=!1)}queueResubscribe(e){let s=this.getConnection(e.shardKey);s&&(s.resubscribeQueue.push(e),this.drainResubscribeQueue(s))}drainResubscribeQueue(e){for(;e.resubscribePending.size<Li;){let s=e.resubscribeQueue.shift();if(!s)return;this.subscriptions.getById(s.id)&&this.sendSubscribeIfOpen(s)&&e.resubscribePending.set(s.id,setTimeout(()=>{this.releaseResubscribeSlot(e,s.id)},Qi))}}releaseResubscribeSlot(e,s){let r=e.resubscribePending.get(s);r!==void 0&&(clearTimeout(r),e.resubscribePending.delete(s),this.drainResubscribeQueue(e))}clearResubscribeQueue(e){for(let s of e.resubscribePending.values())clearTimeout(s);e.resubscribePending.clear(),e.resubscribeQueue=[]}sendSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);if(s?.wsState!=="open"||e.acked)return!1;let r=e.serverCursor!==void 0&&e.serverBase!==void 0;return Q(s,{id:e.id,query:{args:e.wireArgs,functionPath:e.fn.__lunoraRef,table:e.fn.__lunoraRef,...r?{sinceSeq:e.serverCursor}:{},...r&&e.serverEpoch!==void 0?{sinceEpoch:e.serverEpoch}:{}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let s=this.getConnection(e.shardKey);s?.wsState==="open"&&Q(s,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,s){let r=na(e);if(r===void 0)return;let i;try{i=JSON.parse(r)}catch{return}if(i.type!=="error"&&this.getConnection(s)?.reconnect.reset(),typeof i.id=="string"){let n=this.getConnection(s);n&&this.releaseResubscribeSlot(n,i.id)}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,generation:a,id:c,seq:u}=i,h=this.streams.get(c);h&&typeof u=="number"&&(h.lastSeq=u,typeof a=="number"&&(h.generation=a),h.durable=!0),h?.handle.push(S(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"identity":{this.handleIdentityFrame(i,s);break}case"pokeEnd":{this.handlePokeEnd(i,s);break}case"pokePart":{this.handlePokePart(i,s);break}case"pokeStart":{this.handlePokeStart(i,s);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,s);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:s}=e,r=s===void 0?void 0:this.streams.get(s);if(r&&s!==void 0){r.handle.fail(ra(e)),this.streams.delete(s);return}let i=s===void 0?void 0:this.subscriptions.getById(s);if(i){let a=ir(e),c=this.identityFingerprint(),u=P.keyOf(i);te(i.errorCallbacks,a),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastSubscriptionError(u,a,c);return}let n=s===void 0?void 0:this.shapeSubscriptions.get(s);n&&te(n.errorCallbacks,ir(e))}pokeBufferKey(e,s){return`${g(e)}\0${s}`}handlePokeStart(e,s){Zs(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(this.pokeBufferKey(s,e.pokeId),{baseCheckpoint:e.baseCheckpoint,bases:new Map,epoch:e.epoch,lastMutationId:new Map,parts:new Map,resets:new Set,undecodable:new Map})}handlePokePart(e,s){let r=this.pokeBuffers.get(this.pokeBufferKey(s,e.pokeId));if(!r)return;let i=[];try{for(let c of e.rowsPatch)i.push(c.value===void 0?c:{...c,value:S(c.value)})}catch(c){r.undecodable.set(e.shapeId,c);return}let n=r.parts.get(e.shapeId)??[];for(let c of i)n.push(c);r.parts.set(e.shapeId,n),e.lastMutationId!==void 0&&r.lastMutationId.set(e.shapeId,e.lastMutationId);let a=e.baseCheckpoint??r.baseCheckpoint;a!==void 0&&r.bases.set(e.shapeId,a),e.reset===!0&&r.resets.add(e.shapeId)}handlePokeEnd(e,s){let r=this.pokeBufferKey(s,e.pokeId),i=this.pokeBuffers.get(r);if(i){this.pokeBuffers.delete(r);for(let[n,a]of i.undecodable){let c=this.shapeSubscriptions.get(n);c&&te(c.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a poke for this shape \u2014 ${a instanceof Error?a.message:String(a)}`})}for(let n of i.parts.keys()){let a=this.shapeSubscriptions.get(n);a&&!i.undecodable.has(n)&&this.applyPokePart(a,i,e)}}}applyPokePart(e,s,r){let i=s.parts.get(e.id)??[],n=s.resets.has(e.id),a=s.bases.get(e.id),c=s.epoch!==void 0&&e.serverEpoch!==void 0&&s.epoch!==e.serverEpoch,u=a!==void 0&&e.serverCursor!==void 0&&e.serverCursor!==a;if(!n&&(c||u)){e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e),this.sendShapeSubscribeIfOpen(e);return}n&&e.rows.clear(),Ei(e.rows,i),r.checkpoint!==void 0&&(e.serverCursor=r.checkpoint),r.epoch!==void 0&&(e.serverEpoch=r.epoch);let h=s.lastMutationId.get(e.id);h!==void 0&&(e.lastMutationId=h),this.emitShapeRows(e),e.onCheckpoint?.({checkpoint:e.serverCursor,mutationId:e.lastMutationId})}resnapshotSubscription(e){e.acked=!1,e.serverCursor=void 0,e.serverEpoch=void 0,console.warn("[lunora] could not merge a row delta into the cached result; re-subscribing for a full snapshot"),this.sendSubscribeIfOpen(e)}emitShapeRows(e){let s=[...e.rows.values()];for(let r of e.callbacks)try{r(s)}catch{}}handleDataMessage(e,s){let{id:r}=e,i=r?this.subscriptions.getById(r):void 0;if(!i)return;let n;try{n=this.resolveDataPayload(e,i)}catch(a){te(i.errorCallbacks,{code:"WIRE_DECODE_FAILED",message:`could not decode a server frame for this subscription \u2014 ${a instanceof Error?a.message:String(a)}`});return}if(n===tr){this.resnapshotSubscription(i);return}if(i.serverBase=n,this.dropCacheSeed(P.keyOf(i)),e.cursor!==void 0&&(i.serverCursor=e.cursor),e.epoch!==void 0&&(i.serverEpoch=e.epoch),e.lastMutationId!==void 0){i.lastMutationId=Math.max(i.lastMutationId??0,e.lastMutationId);for(let a of i.checkpointCallbacks)a({checkpoint:i.serverCursor,mutationId:i.lastMutationId,rowsFollow:!0})}if(this.persistQueryValue(i),$e(i,i.serverCursor),s!==void 0&&_s(i,s),V(i,X(n,i.optimisticLayers)),this.tabCoordinator?.isLeader()){let a=P.keyOf(i);this.tabCoordinator.broadcastSubscriptionData(a,n,i.serverCursor,i.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let s=this.subscriptions.getById(e.id);s&&this.ackAndAdvanceCursor(s,e.cursor,e.epoch)}handleSettledMessage(e){let s=this.subscriptions.getById(e.id);if(s){this.ackAndAdvanceCursor(s,e.cursor,e.epoch),e.lastMutationId!==void 0&&(s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId));for(let r of s.checkpointCallbacks)r({checkpoint:s.serverCursor,mutationId:s.lastMutationId});if(this.tabCoordinator?.isLeader()){let r=P.keyOf(s);this.tabCoordinator.broadcastSubscriptionSettled(r,s.serverCursor,s.serverEpoch,s.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,s,r){e.acked=!0,(s!==void 0&&s!==e.serverCursor||r!==void 0&&r!==e.serverEpoch)&&(s!==void 0&&(e.serverCursor=s),r!==void 0&&(e.serverEpoch=r),this.persistQueryValue(e),$e(e,e.serverCursor)&&V(e,X(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,s){if("data"in e&&e.data!==void 0)return S(e.data);let r=S(e.delta);return As(r)?s.serverBase===void 0?r:Ps(s.serverBase,r)??tr:r}dispatchWhisper(e,s){let r=this.whisperHandlers.get(g(s))?.get(e.topic);if(!r)return;let i=S(e.data);for(let n of r)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let s=this.streams.get(e);if(s){s.handle.complete(),this.streams.delete(e);return}let r=this.subscriptions.getById(e);r&&(r.acked=!1,te(r.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(s=>{Z(this.onPersistenceError,"remove",s,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let s=2166136261,r=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);s^=n,s=Math.imul(s,16777619),r=Math.imul(r,33)+n}return`${e.length.toString(36)}:${(s>>>0).toString(36)}:${(r>>>0).toString(36)}`}credentialStamp(){let e=this.authToken;return e===null?{}:{credential:this.hashToken(e)}}cachedQueryMatchesIdentity(e){return this.identityFingerprint()===null&&this.identityUnresolved()?!1:!this.subjectAwaitingReconfirm()&&e.identity===this.identityFingerprint()||this.isSameCredentialUnderTokenHash(e.identity)?!0:e.credential!==void 0&&e.credential===this.credentialStamp().credential}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let s=this.authToken;return s===null?!1:this.hashToken(s)===e}releaseSessionProbe(){this.sessionProbesInFlight-=1,!(this.identityUnresolved()||this.identityFingerprint()!==null)&&!this.closed&&this.offlineQueue.size>0&&At(this.computeStatus())&&this.flushAllOfflineQueues()}identityUnresolved(){return this.sessionProbesInFlight>0?!0:this.identityResolutionExpected&&!this.identitySettled}adoptResolvedSubject(e,s,r){if(!(this.closed||this.authToken!==e||r!==this.sessionProbeGeneration)){if(e===null){this.adoptCookieSubject(s?.id??null,r);return}s!==null&&this.setAuthToken(e,s.id)}}adoptCookieSubject(e,s){return this.closed||this.authToken!==null||s<this.identityAnsweredAt?!1:(this.identityAnsweredAt=s,this.identitySettled=!0,this.setAuthToken(null,e),!0)}handleIdentityFrame(e,s){let r=this.getConnection(s)?.identityQuestion,{subject:i}=e;r===void 0||i!==null&&typeof i!="string"||this.adoptCookieSubject(i,r)||!this.closed&&this.authToken===null&&(i===null?null:`subj:${i}`)!==this.identityFingerprint()&&this.evictPreviousIdentitySession()}applySubject(e,s){if(s!==void 0){this.authSubject=s,this.subjectToken=e;return}(e===null&&this.authSubject!==null||e!==null&&this.authSubject===null)&&(this.authSubject=void 0,this.subjectToken=null)}isKnownNobody(){return this.authSubject===null&&this.authToken===null}subjectAwaitingReconfirm(){return this.authSubject!==void 0&&this.authSubject!==null&&this.subjectToken!==this.authToken}stampOf(e){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id);return s===void 0?e.identity:s}rejectQueuedForIdentityChange(e){let s=this.offlineQueue.drain(),r=[];for(let i of s){if(this.replayIdentityVerdict(this.stampOf(i))!=="mismatch"){r.push(i);continue}this.queuedIdentities.delete(i.id??""),this.unpersist(i.id);let n=new Error("offline mutation discarded: auth identity changed before replay");n.code="OFFLINE_IDENTITY_CHANGED",i.reject(n),this.emitItemSettled(i,"rejected",n)}this.offlineQueue.requeue(r),e!==null&&this.clearQueryCacheForIdentityChange()}restampConnectionIdentity(e,s){for(let r of this.connections.values())r.identity===e&&(r.identity=s)}restampQueuedIdentity(e,s){for(let[r,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(r,s);this.offlineQueue.restampIdentity(e,s)}restampWatermarks(e,s){let r=e??"",i=this.clientWatermarks.get(r);if(i===void 0)return;this.clientWatermarks.delete(r);let n=s??"",a=this.clientWatermarks.get(n);if(a===void 0)this.clientWatermarks.set(n,i);else for(let[c,u]of i)a.set(c,u)}clearQueryCacheForIdentityChange(){this.revokeCacheSeededValues(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}evictPreviousIdentitySession(){this.revokeCacheSeededValues();for(let e of this.subscriptions.all())e.serverBase=void 0,e.serverCursor=void 0,e.serverEpoch=void 0,e.acked=!1,V(e,X(void 0,e.optimisticLayers));for(let e of this.shapeSubscriptions.values())e.rows.clear(),e.serverCursor=void 0,e.serverEpoch=void 0,this.emitShapeRows(e);this.bounceShardSockets(),this.identityChangeListeners.emit()}restartTabCoordinatorForIdentity(){if(!this.tabCoordinator)return;let e=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),e&&this.tabCoordinator.promoteImmediately()}bounceShardSockets(){for(let e of this.connections.values())if(e.socket){e.retired=!0;try{e.socket.close()}catch{}}}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let s=g(e),r=this.offlineFlushes.get(s);if(r===void 0&&this.offlineQueue.size===0)return;let i=(async()=>{await(r??Promise.resolve());let{authToken:n}=this;try{await this.drainOfflineQueue(e,n)}catch{}!this.closed&&this.authToken!==n&&this.offlineQueue.size>0&&At(this.computeStatus())&&this.flushOfflineQueue(e).catch(()=>{})})();this.offlineFlushes.set(s,i),await i,this.offlineFlushes.get(s)===i&&this.offlineFlushes.delete(s)}async drainOfflineQueue(e,s){let r=this.offlineQueue.drainConflict();for(let d of r){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");let l=new Error("offline mutation skipped: precondition failed before replay");l.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",l)}let i=g(e),n=this.offlineQueue.drain(d=>g(d.shardKey)===i);if(n.length===0)return;let a=[],c=[];for(let d of n){let l=this.replayGateVerdict(d);l==="send"?a.push(d):l==="hold"&&c.push(d)}if(this.offlineQueue.requeue(c),c.length>0&&this.subjectAwaitingReconfirm()&&(this.getCurrentUser().catch(()=>{}),this.noteHeldRetryDelay(e)),a.length===0){this.scheduleRateLimitedRetry(e);return}let u=this.encodableOrSettleTerminal(a);if(u.length===0){this.scheduleRateLimitedRetry(e);return}if(u.length===1){await this.replaySequential(u,e,s),this.scheduleRateLimitedRetry(e);return}let h=[];for(let d=0;d<u.length;d+=Tt){let l=u.slice(d,d+Tt),f=await this.replayBatched(l,e,s);if(h.push(...f.requeue),f.stop){h.push(...u.slice(d+Tt));break}}h.length>0&&this.offlineQueue.requeue(h),this.scheduleRateLimitedRetry(e)}noteHeldRetryDelay(e){let s=g(e),r=this.replayRetryState.get(s),i=(r?.attempts??0)+1;this.replayRetryState.set(s,{attempts:i,delayMs:Math.max(r?.delayMs??0,Ct(i))})}noteReplayRetryDelay(e,s){let r=g(e),i=this.replayRetryState.get(r),n=(i?.attempts??0)+1,a=Vs(s,n);this.replayRetryState.set(r,{attempts:n,delayMs:a===void 0?i?.delayMs:Math.max(i?.delayMs??0,a)})}scheduleRateLimitedRetry(e){let s=g(e),r=this.replayRetryState.get(s),i=r?.delayMs;if(r===void 0||i===void 0||this.closed||this.offlineQueue.size===0){this.replayRetryState.delete(s);return}r.delayMs=void 0;let n=this.replayRetryTimers.get(s);n!==void 0&&clearTimeout(n),this.replayRetryTimers.set(s,setTimeout(()=>{this.replayRetryTimers.delete(s),this.flushOfflineQueue(e).catch(()=>{})},i))}encodableOrSettleTerminal(e){let s=[];for(let r of e)try{se(r.args,`args for '${r.functionPath}'`),s.push(r)}catch(i){this.settleReplayTerminal(r,i instanceof Error?i:new Error(String(i)))}return s}replayGateVerdict(e){let s=this.stampOf(e);if(s===void 0)return this.queuedIdentities.delete(e.id??""),"send";let r=this.replayIdentityVerdict(s);if(r==="unknown")return"hold";if(this.queuedIdentities.delete(e.id??""),r==="match")return"send";this.unpersist(e.id);let i=new Error("offline mutation skipped: auth identity changed before replay");return i.code="OFFLINE_IDENTITY_CHANGED",e.reject(i),this.emitItemSettled(e,"rejected",i),"reject"}settleReplaySuccess(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.resolve(s),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,s){let r=e.headers.get("x-lunora-shard-key");if(r===null||s!==void 0||this.defaultShardKey===r)return;this.defaultShardKey=r;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,s){if(typeof s!="number")return;let r=this.cursorKeyFor(e);this.shardCursors.set(r,Math.max(this.shardCursors.get(r)??0,s))}shouldRequeueReplayFailure(e,s){if(this.noteIdentityMismatch(e))return!0;if(Ks(e)){let r=this.hashToken(s??"");return s===this.authToken&&this.authRefusalNotifiedFor!==r&&(this.authRefusalNotifiedFor=r,this.notifyTokenExpired()),!0}return Bs(e)}noteIdentityMismatch(e){if(e?.code!=="IDENTITY_MISMATCH")return!1;let s=this.identityFingerprint();return this.getCurrentUser().then(()=>{!this.warnedIdentityDisagreement&&this.identityFingerprint()===s&&(this.warnedIdentityDisagreement=!0,console.warn('[lunora] a replayed write was refused with IDENTITY_MISMATCH, but `/get-session` still names the same user. The worker\'s `resolveIdentity` must return the same `userId` as the better-auth `user.id`, and RPC requests must carry the session cookie (`credentials: "include"` on a cross-origin fetch).'))}).catch(()=>{}),!0}settleReplayUndecodable(e,s,r){this.unpersist(e.id),this.recordShardCursor(e.shardKey,r),e.onCommit?.(r),e.reject(s),this.emitItemSettled(e,"committed",s)}settleReplayTerminal(e,s){this.unpersist(e.id),e.reject(s),this.emitItemSettled(e,"rejected",s)}async replaySequential(e,s,r){for(let i=0;i<e.length;i+=1){let n=e[i];if(!n)continue;let a;try{let c=await this.rpc(n.functionPath,n.args,n.shardKey,{authToken:r,baselineSeq:n.baselineSeq,captureBookmark:!0,clientId:n.clientId??this.clientId,...Mt(n.identity,r),mutationId:n.id,onCommitCursor:o(u=>{a=u},"onCommitCursor")});this.settleReplaySuccess(n,c,a)}catch(c){if(we(c)){this.settleReplayUndecodable(n,c,a);continue}if(!this.shouldRequeueReplayFailure(c,r)){this.settleReplayTerminal(n,c);continue}this.noteReplayRetryDelay(s,c),this.offlineQueue.requeue(e.slice(i));return}}}async replayBatched(e,s,r){if(!this.fetchImpl)return{requeue:e,stop:!0};let i=JSON.stringify({calls:e.map((h,d)=>({args:se(h.args,`args for '${h.functionPath}'`),baselineSeq:h.baselineSeq,functionPath:h.functionPath,id:d,clientId:h.clientId??this.clientId,mutationId:h.id,shardKey:h.shardKey}))});if(e.length>1&&Js(i)>Gs)return await this.replayBatchedHalves(e,s,r);let n;try{n=await this.fetchImpl(ee(this.url,Et),{body:i,headers:this.rpcRequestHeaders({attachBookmark:!0,authToken:r,...Mt(e.find(h=>h.identity!==void 0)?.identity,r)}),method:"POST"})}catch{return{requeue:e,stop:!0}}let a=n.headers.get("x-d1-bookmark");if(a&&this.bookmark.set(a),n.status===413&&e.length>1)return await this.replayBatchedHalves(e,s,r);let c,u=n.headers.get("retry-after");try{c=await n.json()}catch{return this.settleWholeBatchError(e,de(n.status,n.statusText,u),s,r)}if(!c.results){let h=le(c),d=h===void 0?de(n.status,n.statusText,u):nr(h,u);return this.settleWholeBatchError(e,d,s,r)}return{requeue:this.settleReplayBatchSlots(e,c.results,s,r),stop:!1}}settleWholeBatchError(e,s,r,i){if(s instanceof B||s.code!==void 0&&this.shouldRequeueReplayFailure(s,i))return this.noteReplayRetryDelay(r,s),{requeue:e,stop:!0};for(let n of e)this.settleReplayTerminal(n,s);return{requeue:[],stop:!1}}async replayBatchedHalves(e,s,r){let i=Math.ceil(e.length/2),n=await this.replayBatched(e.slice(0,i),s,r);if(n.stop)return{requeue:[...n.requeue,...e.slice(i)],stop:!0};let a=await this.replayBatched(e.slice(i),s,r);return{requeue:[...n.requeue,...a.requeue],stop:a.stop}}settleReplayBatchSlots(e,s,r,i){let n=new Map;for(let c of s)typeof c.id=="number"&&c.body!==void 0&&n.set(c.id,c.body);let a=[];for(let[c,u]of e.entries()){let h=n.get(c);if(h===void 0)a.push(u);else if("error"in h){let d=hr(h);this.shouldRequeueReplayFailure(d,i)?(this.noteReplayRetryDelay(r,d),a.push(u)):this.settleReplayTerminal(u,d)}else this.settleReplayBatchResult(u,h)}return a}settleReplayBatchResult(e,s){let r;try{r=S(s.result)}catch(i){this.settleReplayUndecodable(e,kt(i),s.commitCursor);return}this.settleReplaySuccess(e,r,s.commitCursor)}};var dr=L(Dt(),1),lr=L(ie(),1);var ua=o(()=>{let t=(0,dr.c)(4),e=ht(),s,r,i;return t[0]!==e?(s=o(n=>e.onConnectionStatus(()=>{n()}),"o"),r=o(()=>e.connectionStatus(),"e"),i=o(()=>e.connectionStatus(),"s"),t[0]=e,t[1]=s,t[2]=r,t[3]=i):(s=t[1],r=t[2],i=t[3]),(0,lr.useSyncExternalStore)(s,r,i)},"S");export{xt as a,br as b,rt as c,Rr as d,Lr as e,ht as f,ua as g};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{d as Le}from"./chunk-AANB526D.js";import{c as _e}from"./chunk-UYEZR3BI.js";import"./chunk-RFNGDE33.js";import"./chunk-V3CZW3JB.js";import"./chunk-MU3P2FI7.js";import{a as ye}from"./chunk-3FBLWUXD.js";import"./chunk-XZMOZFE6.js";import{a as Ee}from"./chunk-66UGPQVC.js";import"./chunk-YPRQLCKF.js";import"./chunk-GMS77BZD.js";import"./chunk-3Q2P62UR.js";import"./chunk-AWHXPIXU.js";import"./chunk-V3VJAA4D.js";import{a as Oe}from"./chunk-NFS7FTAR.js";import{a as Te}from"./chunk-EJSI4PMU.js";import"./chunk-OGUKYRFM.js";import"./chunk-OKG3HWSJ.js";import{W as Ce}from"./chunk-PLHA3OWK.js";import"./chunk-Y6CXU7T4.js";import"./chunk-4L4WTGN5.js";import{a as te}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as ae}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as be}from"./chunk-4ZEL6BYL.js";import{f as Se}from"./chunk-NZKXQEZ5.js";import"./chunk-FSRSK4LY.js";import"./chunk-5ICUJ4IA.js";import{a as he}from"./chunk-FKVZRPV5.js";import{a as $e,b as Ke,c as Fe,d as ie,e as re,f as ee}from"./chunk-HEAQVSNS.js";import{a as je,e as ze}from"./chunk-WUWBZPUK.js";import{d as Ne,f as me,g as pe,h as Q,l as ge,p as W,s as De}from"./chunk-PTZD7RUZ.js";import{a as m,d as fe,e as mt,f as pt,g as gt}from"./chunk-YKXDMIHQ.js";var M=fe(pt(),1),z=fe(mt(),1);var o=fe(gt(),1);var Ue=m((d,e,t)=>{let{onCopy:r,onDelete:l,onDownload:n,onToggleSelect:c}=t,i=m(()=>{r(d.key)},"c"),s=m(()=>{n(d.key)},"o"),u=m(()=>{l(d.key)},"f"),h=m(()=>{c(d.key)},"h");return{copy:i,download:s,name:d.key.slice(e.length),remove:u,toggle:h}},"Ee"),Me=m(d=>{let e=(0,M.c)(31),{busy:t,buttonClassName:r,copied:l,objectKey:n,onCopy:c,onDelete:i,onDownload:s,t:u}=d,h=`storage-copy-${n}`,f;e[0]!==l||e[1]!==u?(f=u(l?"Copied":"Copy URL"),e[0]=l,e[1]=u,e[2]=f):f=e[2];let p;e[3]!==t||e[4]!==r||e[5]!==c||e[6]!==h||e[7]!==f?(p=(0,o.jsx)(te,{className:r,"data-testid":h,disabled:t,onClick:c,size:"sm",type:"button",variant:"ghost",children:f}),e[3]=t,e[4]=r,e[5]=c,e[6]=h,e[7]=f,e[8]=p):p=e[8];let w=`storage-download-${n}`,a;e[9]!==u?(a=u("Download"),e[9]=u,e[10]=a):a=e[10];let k;e[11]!==t||e[12]!==r||e[13]!==s||e[14]!==w||e[15]!==a?(k=(0,o.jsx)(te,{className:r,"data-testid":w,disabled:t,onClick:s,size:"sm",type:"button",variant:"ghost",children:a}),e[11]=t,e[12]=r,e[13]=s,e[14]=w,e[15]=a,e[16]=k):k=e[16];let N;e[17]!==u?(N=u("Delete object?"),e[17]=u,e[18]=N):N=e[18];let v=`storage-delete-${n}`,b;e[19]!==u?(b=u("Delete"),e[19]=u,e[20]=b):b=e[20];let y;e[21]!==t||e[22]!==i||e[23]!==N||e[24]!==v||e[25]!==b?(y=(0,o.jsx)(Oe,{confirmLabel:N,disabled:t,onConfirm:i,testId:v,children:b}),e[21]=t,e[22]=i,e[23]=N,e[24]=v,e[25]=b,e[26]=y):y=e[26];let x;return e[27]!==y||e[28]!==p||e[29]!==k?(x=(0,o.jsxs)(o.Fragment,{children:[p,k,y]}),e[27]=y,e[28]=p,e[29]=k,e[30]=x):x=e[30],x},"$e"),Ae=m(d=>{let e=(0,M.c)(14),{objectKey:t,references:r,t:l}=d;if(r===void 0)return null;if(r.length===0){let h=`storage-orphan-${t}`,f;e[0]!==l?(f=l("Orphan"),e[0]=l,e[1]=f):f=e[1];let p;return e[2]!==h||e[3]!==f?(p=(0,o.jsx)(ae,{"data-testid":h,variant:"warning",children:f}),e[2]=h,e[3]=f,e[4]=p):p=e[4],p}let n;e[5]!==r?(n=r.map(bt).join(`
|
|
2
|
-
`),e[5]=r,e[6]=n):n=e[6];let c=n,i=`storage-refs-${t}`,s;e[7]!==r.length||e[8]!==l?(s=r.length===1?l("1 record"):l("{count} records",{count:r.length}),e[7]=r.length,e[8]=l,e[9]=s):s=e[9];let u;return e[10]!==c||e[11]!==i||e[12]!==s?(u=(0,o.jsx)(ae,{"data-testid":i,title:c,variant:"secondary",children:s}),e[10]=c,e[11]=i,e[12]=s,e[13]=u):u=e[13],u},"Fe"),Pe=m(d=>{let e=(0,M.c)(7),{objectKey:t,onToggle:r,selected:l,t:n}=d,c;e[0]!==n?(c=n("Select row"),e[0]=n,e[1]=c):c=e[1];let i=`storage-select-${t}`,s;return e[2]!==r||e[3]!==l||e[4]!==c||e[5]!==i?(s=(0,o.jsx)(ye,{"aria-label":c,checked:l,"data-testid":i,onCheckedChange:r}),e[2]=r,e[3]=l,e[4]=c,e[5]=i,e[6]=s):s=e[6],s},"Re");function bt(d){return`${d.table}\xB7${d.id}`}m(bt,"yt");var yt=m(d=>{let e=(0,M.c)(10),{colSpan:t,name:r,onEnter:l}=d,n;e[0]!==r||e[1]!==l?(n=m(()=>{l(r)},"l"),e[0]=r,e[1]=l,e[2]=n):n=e[2];let c=n,i;e[3]===Symbol.for("react.memo_cache_sentinel")?(i=(0,o.jsx)("svg",{"aria-hidden":"true",className:"size-4 text-muted-foreground",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,o.jsx)("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z"})}),e[3]=i):i=e[3];let s;e[4]!==c||e[5]!==r?(s=(0,o.jsxs)("button",{className:"inline-flex items-center gap-2 font-mono text-xs outline-none hover:text-foreground focus-visible:text-foreground","data-testid":"fb-folder",onClick:c,type:"button",children:[i,r]}),e[4]=c,e[5]=r,e[6]=s):s=e[6];let u;return e[7]!==t||e[8]!==s?(u=(0,o.jsx)(ie,{children:(0,o.jsx)(ee,{colSpan:t,children:s})}),e[7]=t,e[8]=s,e[9]=u):u=e[9],u},"xt"),xt=m(d=>{let e=(0,M.c)(37),{busy:t,copiedKey:r,handlers:l,object:n,prefix:c,references:i,selected:s,showReferences:u,t:h}=d,f;e[0]!==l||e[1]!==n||e[2]!==c?(f=Ue(n,c,l),e[0]=l,e[1]=n,e[2]=c,e[3]=f):f=e[3];let{copy:p,download:w,name:a,remove:k,toggle:N}=f,v;e[4]!==n.key||e[5]!==s||e[6]!==h||e[7]!==N?(v=(0,o.jsx)(ee,{className:"w-8",children:(0,o.jsx)(Pe,{objectKey:n.key,onToggle:N,selected:s,t:h})}),e[4]=n.key,e[5]=s,e[6]=h,e[7]=N,e[8]=v):v=e[8];let b;e[9]!==a?(b=(0,o.jsx)(ee,{className:"font-mono text-xs",children:a}),e[9]=a,e[10]=b):b=e[10];let y;e[11]!==n.size?(y=ge(n.size),e[11]=n.size,e[12]=y):y=e[12];let x;e[13]!==y?(x=(0,o.jsx)(ee,{className:"tabular-nums text-muted-foreground",children:y}),e[13]=y,e[14]=x):x=e[14];let j=n.httpMetadata?.contentType??"",S;e[15]!==j?(S=(0,o.jsx)(ee,{children:j}),e[15]=j,e[16]=S):S=e[16];let C;e[17]!==n.key||e[18]!==i||e[19]!==u||e[20]!==h?(C=u&&(0,o.jsx)(ee,{children:(0,o.jsx)(Ae,{objectKey:n.key,references:i,t:h})}),e[17]=n.key,e[18]=i,e[19]=u,e[20]=h,e[21]=C):C=e[21];let T=r===n.key,D;e[22]!==t||e[23]!==p||e[24]!==w||e[25]!==n.key||e[26]!==k||e[27]!==h||e[28]!==T?(D=(0,o.jsx)(ee,{className:"text-right",children:(0,o.jsx)("span",{className:"inline-flex items-center gap-1",children:(0,o.jsx)(Me,{busy:t,copied:T,objectKey:n.key,onCopy:p,onDelete:k,onDownload:w,t:h})})}),e[22]=t,e[23]=p,e[24]=w,e[25]=n.key,e[26]=k,e[27]=h,e[28]=T,e[29]=D):D=e[29];let F;return e[30]!==D||e[31]!==v||e[32]!==b||e[33]!==x||e[34]!==S||e[35]!==C?(F=(0,o.jsxs)(ie,{"data-testid":"fb-row",children:[v,b,x,S,C,D]}),e[30]=D,e[31]=v,e[32]=b,e[33]=x,e[34]=S,e[35]=C,e[36]=F):F=e[36],F},"vt"),vt=m(d=>{let e=(0,M.c)(65),{allSelected:t,busy:r,copiedKey:l,files:n,folders:c,handlers:i,onEnterFolder:s,prefix:u,references:h,selected:f,showReferences:p,someSelected:w,t:a,toggleSelectAll:k}=d,N;e[0]!==a?(N=a("Select all rows"),e[0]=a,e[1]=N):N=e[1];let v;e[2]!==t||e[3]!==w||e[4]!==N||e[5]!==k?(v=(0,o.jsx)(re,{className:"w-8",children:(0,o.jsx)(ye,{"aria-label":N,checked:t,"data-testid":"storage-select-all",indeterminate:w,onCheckedChange:k})}),e[2]=t,e[3]=w,e[4]=N,e[5]=k,e[6]=v):v=e[6];let b;e[7]!==a?(b=a("key"),e[7]=a,e[8]=b):b=e[8];let y;e[9]!==b?(y=(0,o.jsx)(re,{children:b}),e[9]=b,e[10]=y):y=e[10];let x;e[11]!==a?(x=a("size"),e[11]=a,e[12]=x):x=e[12];let j;e[13]!==x?(j=(0,o.jsx)(re,{children:x}),e[13]=x,e[14]=j):j=e[14];let S;e[15]!==a?(S=a("content-type"),e[15]=a,e[16]=S):S=e[16];let C;e[17]!==S?(C=(0,o.jsx)(re,{children:S}),e[17]=S,e[18]=C):C=e[18];let T;e[19]!==p||e[20]!==a?(T=p&&(0,o.jsx)(re,{children:a("used by")}),e[19]=p,e[20]=a,e[21]=T):T=e[21];let D;e[22]!==a?(D=a("Actions"),e[22]=a,e[23]=D):D=e[23];let F;e[24]!==D?(F=(0,o.jsx)(re,{"aria-label":D}),e[24]=D,e[25]=F):F=e[25];let $;e[26]!==F||e[27]!==v||e[28]!==y||e[29]!==j||e[30]!==C||e[31]!==T?($=(0,o.jsx)(Ke,{children:(0,o.jsxs)(ie,{children:[v,y,j,C,T,F]})}),e[26]=F,e[27]=v,e[28]=y,e[29]=j,e[30]=C,e[31]=T,e[32]=$):$=e[32];let O;if(e[33]!==c||e[34]!==s||e[35]!==p){let E;e[37]!==s||e[38]!==p?(E=m(_=>(0,o.jsx)(yt,{colSpan:p?6:5,name:_,onEnter:s},_),"D"),e[37]=s,e[38]=p,e[39]=E):E=e[39],O=c.map(E),e[33]=c,e[34]=s,e[35]=p,e[36]=O}else O=e[36];let B;if(e[40]!==r||e[41]!==l||e[42]!==n||e[43]!==i||e[44]!==u||e[45]!==h||e[46]!==f||e[47]!==p||e[48]!==a){let E;e[50]!==r||e[51]!==l||e[52]!==i||e[53]!==u||e[54]!==h||e[55]!==f||e[56]!==p||e[57]!==a?(E=m(_=>(0,o.jsx)(xt,{busy:r,copiedKey:l,handlers:i,object:_,prefix:u,references:h[_.key],selected:f.has(_.key),showReferences:p,t:a},_.key),"D"),e[50]=r,e[51]=l,e[52]=i,e[53]=u,e[54]=h,e[55]=f,e[56]=p,e[57]=a,e[58]=E):E=e[58],B=n.map(E),e[40]=r,e[41]=l,e[42]=n,e[43]=i,e[44]=u,e[45]=h,e[46]=f,e[47]=p,e[48]=a,e[49]=B}else B=e[49];let L;e[59]!==O||e[60]!==B?(L=(0,o.jsxs)(Fe,{children:[O,B]}),e[59]=O,e[60]=B,e[61]=L):L=e[61];let I;return e[62]!==$||e[63]!==L?(I=(0,o.jsx)(je,{className:"overflow-hidden py-0",children:(0,o.jsx)(ze,{className:"px-0",children:(0,o.jsxs)($e,{"data-testid":"fb-table",children:[$,L]})})}),e[62]=$,e[63]=L,e[64]=I):I=e[64],I},"kt"),kt=[{label:"15m",seconds:900},{label:"1h",seconds:3600},{label:"24h",seconds:86400},{label:"7d",seconds:604800}],wt=3600,Be=m((d,e)=>{if(e==="size")return d.size;if(e==="type")return d.httpMetadata?.contentType??"";if(e==="date"){if(d.uploaded===void 0)return 0;let t=new Date(d.uploaded).getTime();return Number.isNaN(t)?0:t}return e.startsWith("tag:")?d.customMetadata?.[e.slice(4)]??"":d.key},"ve"),St=m((d,e,t)=>{let r=t==="desc"?-1:1;return d.toSorted((l,n)=>{let c=Be(l,e),i=Be(n,e);return(typeof c=="number"&&typeof i=="number"?c-i:String(c).localeCompare(String(i)))*r})},"Ct"),Nt=m((d,e)=>{let t=new Set,r=[];for(let l of d){let n=l.key.slice(e.length),c=n.indexOf("/");c===-1?r.push(l):t.add(n.slice(0,c+1))}return{files:r,folders:[...t].toSorted((l,n)=>l.localeCompare(n))}},"Nt"),Ct=m(d=>{let e=(0,M.c)(59),{bucket:t,buckets:r,busy:l,draftPrefix:n,expiry:c,fileInputRef:i,onBucketChange:s,onExpiryChange:u,onFileChange:h,onList:f,onPrefixChange:p,onUploadClick:w,t:a}=d,k;e[0]!==p?(k=m(P=>{p(P.target.value)},"v"),e[0]=p,e[1]=k):k=e[1];let N=k,v;e[2]!==s?(v=m(P=>{s(P.target.value)},"x"),e[2]=s,e[3]=v):v=e[3];let b=v,y;e[4]!==u?(y=m(P=>{u(Number.parseInt(P.target.value,10))},"b"),e[4]=u,e[5]=y):y=e[5];let x=y,j;e[6]!==t||e[7]!==r||e[8]!==b||e[9]!==a?(j=r.length>0&&(0,o.jsx)("select",{"aria-label":a("Bucket"),className:"h-8 rounded-md border border-border bg-background px-1 outline-none focus-visible:border-ring","data-testid":"fb-bucket",onChange:b,value:t,children:r.map(zt)}),e[6]=t,e[7]=r,e[8]=b,e[9]=a,e[10]=j):j=e[10];let S;e[11]!==a?(S=a("Key prefix"),e[11]=a,e[12]=S):S=e[12];let C;e[13]!==a?(C=a("key prefix (optional)"),e[13]=a,e[14]=C):C=e[14];let T;e[15]!==n||e[16]!==N||e[17]!==S||e[18]!==C?(T=(0,o.jsx)(Ce,{"aria-label":S,className:"h-8 w-64 max-w-full","data-testid":"fb-prefix-input",onChange:N,placeholder:C,value:n}),e[15]=n,e[16]=N,e[17]=S,e[18]=C,e[19]=T):T=e[19];let D;e[20]!==a?(D=a("List"),e[20]=a,e[21]=D):D=e[21];let F;e[22]!==l||e[23]!==f||e[24]!==D?(F=(0,o.jsx)(te,{"data-testid":"fb-list",disabled:l,onClick:f,size:"sm",type:"button",children:D}),e[22]=l,e[23]=f,e[24]=D,e[25]=F):F=e[25];let $;e[26]!==l||e[27]!==a?($=a(l?"Uploading\u2026":"Upload"),e[26]=l,e[27]=a,e[28]=$):$=e[28];let O;e[29]!==l||e[30]!==w||e[31]!==$?(O=(0,o.jsx)(te,{"data-testid":"storage-upload",disabled:l,onClick:w,size:"sm",type:"button",variant:"outline",children:$}),e[29]=l,e[30]=w,e[31]=$,e[32]=O):O=e[32];let B;e[33]!==i||e[34]!==h?(B=(0,o.jsx)("input",{className:"hidden","data-testid":"storage-file-input",onChange:h,ref:i,type:"file"}),e[33]=i,e[34]=h,e[35]=B):B=e[35];let L;e[36]!==a?(L=a("Link expiry"),e[36]=a,e[37]=L):L=e[37];let I;e[38]!==a?(I=kt.map(P=>(0,o.jsx)("option",{value:P.seconds,children:a(P.label)},P.seconds)),e[38]=a,e[39]=I):I=e[39];let E;e[40]!==c||e[41]!==x||e[42]!==I?(E=(0,o.jsx)("select",{className:"h-8 rounded-md border border-border bg-background px-1 tabular-nums outline-none focus-visible:border-ring","data-testid":"storage-expiry",id:"storage-expiry",onChange:x,value:c,children:I}),e[40]=c,e[41]=x,e[42]=I,e[43]=E):E=e[43];let _;e[44]!==L||e[45]!==E?(_=(0,o.jsxs)("label",{className:"ml-auto flex items-center gap-1.5 text-xs text-muted-foreground",htmlFor:"storage-expiry",children:[L,E]}),e[44]=L,e[45]=E,e[46]=_):_=e[46];let U;e[47]!==a?(U=a("Open in Cloudflare"),e[47]=a,e[48]=U):U=e[48];let A;e[49]!==U?(A=(0,o.jsx)("a",{className:"text-sm text-primary underline-offset-4 hover:underline","data-testid":"fb-cf-link",href:_e,rel:"noreferrer",target:"_blank",children:U}),e[49]=U,e[50]=A):A=e[50];let H;return e[51]!==O||e[52]!==B||e[53]!==_||e[54]!==A||e[55]!==j||e[56]!==T||e[57]!==F?(H=(0,o.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[j,T,F,O,B,_,A]}),e[51]=O,e[52]=B,e[53]=_,e[54]=A,e[55]=j,e[56]=T,e[57]=F,e[58]=H):H=e[58],H},"Tt"),jt=m(d=>{let e=(0,M.c)(66),{onSortKeyChange:t,onThumbSizeChange:r,showGrid:l,showList:n,sortDirection:c,sortKey:i,t:s,tagKeys:u,thumbSize:h,toggleSortDirection:f,view:p}=d,w;e[0]!==t?(w=m(G=>{t(G.target.value)},"k"),e[0]=t,e[1]=w):w=e[1];let a=w,k;e[2]!==r?(k=m(G=>{r(Number.parseInt(G.target.value,10))},"v"),e[2]=r,e[3]=k):k=e[3];let N=k,v=p==="list",b;e[4]!==s?(b=s("List"),e[4]=s,e[5]=b):b=e[5];let y;e[6]!==n||e[7]!==v||e[8]!==b?(y=(0,o.jsx)("button",{"aria-pressed":v,className:"px-2 py-1 outline-none transition-colors hover:bg-accent aria-pressed:bg-accent aria-pressed:text-accent-foreground","data-testid":"fb-view-list",onClick:n,type:"button",children:b}),e[6]=n,e[7]=v,e[8]=b,e[9]=y):y=e[9];let x=p==="grid",j;e[10]!==s?(j=s("Grid"),e[10]=s,e[11]=j):j=e[11];let S;e[12]!==l||e[13]!==x||e[14]!==j?(S=(0,o.jsx)("button",{"aria-pressed":x,className:"border-s border-border px-2 py-1 outline-none transition-colors hover:bg-accent aria-pressed:bg-accent aria-pressed:text-accent-foreground","data-testid":"fb-view-grid",onClick:l,type:"button",children:j}),e[12]=l,e[13]=x,e[14]=j,e[15]=S):S=e[15];let C;e[16]!==y||e[17]!==S?(C=(0,o.jsxs)("div",{className:"inline-flex overflow-hidden rounded-md border border-border",children:[y,S]}),e[16]=y,e[17]=S,e[18]=C):C=e[18];let T;e[19]!==s?(T=s("Sort"),e[19]=s,e[20]=T):T=e[20];let D;e[21]!==s?(D=s("Name"),e[21]=s,e[22]=D):D=e[22];let F;e[23]!==D?(F=(0,o.jsx)("option",{value:"name",children:D}),e[23]=D,e[24]=F):F=e[24];let $;e[25]!==s?($=s("size"),e[25]=s,e[26]=$):$=e[26];let O;e[27]!==$?(O=(0,o.jsx)("option",{value:"size",children:$}),e[27]=$,e[28]=O):O=e[28];let B;e[29]!==s?(B=s("Type"),e[29]=s,e[30]=B):B=e[30];let L;e[31]!==B?(L=(0,o.jsx)("option",{value:"type",children:B}),e[31]=B,e[32]=L):L=e[32];let I;e[33]!==s?(I=s("Modified"),e[33]=s,e[34]=I):I=e[34];let E;e[35]!==I?(E=(0,o.jsx)("option",{value:"date",children:I}),e[35]=I,e[36]=E):E=e[36];let _;e[37]!==u?(_=u.map(Dt),e[37]=u,e[38]=_):_=e[38];let U;e[39]!==a||e[40]!==i||e[41]!==F||e[42]!==O||e[43]!==L||e[44]!==E||e[45]!==_?(U=(0,o.jsxs)("select",{className:"h-8 rounded-md border border-border bg-background px-1 outline-none focus-visible:border-ring","data-testid":"fb-sort",id:"fb-sort",onChange:a,value:i,children:[F,O,L,E,_]}),e[39]=a,e[40]=i,e[41]=F,e[42]=O,e[43]=L,e[44]=E,e[45]=_,e[46]=U):U=e[46];let A;e[47]!==T||e[48]!==U?(A=(0,o.jsxs)("label",{className:"flex items-center gap-1.5 text-muted-foreground",htmlFor:"fb-sort",children:[T,U]}),e[47]=T,e[48]=U,e[49]=A):A=e[49];let H;e[50]!==s?(H=s("Toggle sort direction"),e[50]=s,e[51]=H):H=e[51];let P=c==="asc"?"\u2191":"\u2193",q;e[52]!==H||e[53]!==P||e[54]!==f?(q=(0,o.jsx)("button",{"aria-label":H,className:"flex size-8 items-center justify-center rounded-md border border-border tabular-nums outline-none transition-colors hover:bg-accent focus-visible:bg-accent","data-testid":"fb-sort-dir",onClick:f,type:"button",children:P}),e[52]=H,e[53]=P,e[54]=f,e[55]=q):q=e[55];let Y;e[56]!==N||e[57]!==s||e[58]!==h||e[59]!==p?(Y=p==="grid"&&(0,o.jsxs)("label",{className:"ml-auto flex items-center gap-1.5 text-muted-foreground",htmlFor:"fb-thumb-size",children:[s("Thumbnail size"),(0,o.jsx)("input",{className:"accent-primary","data-testid":"fb-thumb-size",id:"fb-thumb-size",max:240,min:80,onChange:N,step:8,type:"range",value:h})]}),e[56]=N,e[57]=s,e[58]=h,e[59]=p,e[60]=Y):Y=e[60];let ne;return e[61]!==A||e[62]!==q||e[63]!==Y||e[64]!==C?(ne=(0,o.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs","data-testid":"fb-controls",children:[C,A,q,Y]}),e[61]=A,e[62]=q,e[63]=Y,e[64]=C,e[65]=ne):ne=e[65],ne},"_t");function zt(d){return(0,o.jsx)("option",{value:d,children:d},d)}m(zt,"Et");function Dt(d){return(0,o.jsx)("option",{value:`tag:${d}`,children:d},d)}m(Dt,"$t");var Tt=/\.(?:avif|bmp|gif|ico|jpe?g|png|svg|webp)$/iu,$t=m(d=>(d.httpMetadata?.contentType??"").startsWith("image/")||Tt.test(d.key),"Rt"),Kt=m(()=>{let d=(0,M.c)(1),e;return d[0]===Symbol.for("react.memo_cache_sentinel")?(e=(0,o.jsx)("svg",{"aria-hidden":"true",className:"size-8 text-muted-foreground/60",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.4,viewBox:"0 0 24 24",children:(0,o.jsx)("path",{d:"M7 3h7l5 5v13a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1Zm7 0v5h5"})}),d[0]=e):e=d[0],e},"zt"),Ft=m(d=>{let e=(0,M.c)(13),{object:t,resolveUrl:r}=d,[l,n]=(0,z.useState)(null),[c,i]=(0,z.useState)(!1),s;e[0]!==t?(s=$t(t),e[0]=t,e[1]=s):s=e[1];let u=s,h,f;e[2]!==u||e[3]!==t.key||e[4]!==r?(h=m(()=>{if(!u)return;let k={cancelled:!1};return W((async()=>{try{let N=await r(t.key);k.cancelled||n(N)}catch{k.cancelled||i(!0)}})()),()=>{k.cancelled=!0}},"h"),f=[u,t.key,r],e[2]=u,e[3]=t.key,e[4]=r,e[5]=h,e[6]=f):(h=e[5],f=e[6]),(0,z.useEffect)(h,f);let p;e[7]===Symbol.for("react.memo_cache_sentinel")?(p=m(()=>{i(!0)},"m"),e[7]=p):p=e[7];let w=p,a;return e[8]!==c||e[9]!==u||e[10]!==t.key||e[11]!==l?(a=(0,o.jsx)("div",{className:"flex aspect-square w-full items-center justify-center overflow-hidden rounded-md border border-border bg-muted/30",children:u&&l!==null&&!c?(0,o.jsx)("img",{alt:t.key,className:"size-full object-cover",loading:"lazy",onError:w,src:l}):(0,o.jsx)(Kt,{})}),e[8]=c,e[9]=u,e[10]=t.key,e[11]=l,e[12]=a):a=e[12],a},"Dt"),Ot=m(d=>{let e=(0,M.c)(42),{busy:t,copiedKey:r,handlers:l,object:n,prefix:c,references:i,resolveUrl:s,selected:u,showReferences:h,t:f}=d,p;e[0]!==l||e[1]!==n||e[2]!==c?(p=Ue(n,c,l),e[0]=l,e[1]=n,e[2]=c,e[3]=p):p=e[3];let{copy:w,download:a,name:k,remove:N,toggle:v}=p,b;e[4]!==n||e[5]!==s?(b=(0,o.jsx)(Ft,{object:n,resolveUrl:s}),e[4]=n,e[5]=s,e[6]=b):b=e[6];let y;e[7]!==n.key||e[8]!==u||e[9]!==f||e[10]!==v?(y=(0,o.jsx)("span",{className:"absolute left-1.5 top-1.5 rounded bg-background/80 p-0.5",children:(0,o.jsx)(Pe,{objectKey:n.key,onToggle:v,selected:u,t:f})}),e[7]=n.key,e[8]=u,e[9]=f,e[10]=v,e[11]=y):y=e[11];let x;e[12]!==b||e[13]!==y?(x=(0,o.jsxs)("div",{className:"relative",children:[b,y]}),e[12]=b,e[13]=y,e[14]=x):x=e[14];let j;e[15]!==k?(j=(0,o.jsx)("p",{className:"truncate font-mono text-xs",title:k,children:k}),e[15]=k,e[16]=j):j=e[16];let S;e[17]!==n.size?(S=ge(n.size),e[17]=n.size,e[18]=S):S=e[18];let C;e[19]!==S?(C=(0,o.jsx)("p",{className:"text-[11px] tabular-nums text-muted-foreground",children:S}),e[19]=S,e[20]=C):C=e[20];let T;e[21]!==n.key||e[22]!==i||e[23]!==h||e[24]!==f?(T=h&&(0,o.jsx)("div",{className:"mt-1",children:(0,o.jsx)(Ae,{objectKey:n.key,references:i,t:f})}),e[21]=n.key,e[22]=i,e[23]=h,e[24]=f,e[25]=T):T=e[25];let D;e[26]!==j||e[27]!==C||e[28]!==T?(D=(0,o.jsxs)("div",{className:"min-w-0",children:[j,C,T]}),e[26]=j,e[27]=C,e[28]=T,e[29]=D):D=e[29];let F=r===n.key,$;e[30]!==t||e[31]!==w||e[32]!==a||e[33]!==n.key||e[34]!==N||e[35]!==f||e[36]!==F?($=(0,o.jsx)("div",{className:"flex items-center gap-1",children:(0,o.jsx)(Me,{busy:t,buttonClassName:"h-7 px-2 text-xs",copied:F,objectKey:n.key,onCopy:w,onDelete:N,onDownload:a,t:f})}),e[30]=t,e[31]=w,e[32]=a,e[33]=n.key,e[34]=N,e[35]=f,e[36]=F,e[37]=$):$=e[37];let O;return e[38]!==$||e[39]!==x||e[40]!==D?(O=(0,o.jsxs)("div",{className:"flex flex-col gap-1.5","data-testid":"fb-tile",children:[x,D,$]}),e[38]=$,e[39]=x,e[40]=D,e[41]=O):O=e[41],O},"jt"),Et=m(d=>{let e=(0,M.c)(9),{name:t,onEnter:r}=d,l;e[0]!==t||e[1]!==r?(l=m(()=>{r(t)},"n"),e[0]=t,e[1]=r,e[2]=l):l=e[2];let n=l,c;e[3]===Symbol.for("react.memo_cache_sentinel")?(c=(0,o.jsx)("span",{className:"flex aspect-square w-full items-center justify-center rounded-md border border-border bg-muted/30 transition-colors hover:bg-accent",children:(0,o.jsx)("svg",{"aria-hidden":"true",className:"size-10 text-muted-foreground",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.4,viewBox:"0 0 24 24",children:(0,o.jsx)("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z"})})}),e[3]=c):c=e[3];let i;e[4]!==t?(i=(0,o.jsx)("span",{className:"truncate font-mono text-xs",title:t,children:t}),e[4]=t,e[5]=i):i=e[5];let s;return e[6]!==n||e[7]!==i?(s=(0,o.jsxs)("button",{className:"flex flex-col gap-1.5 text-left outline-none","data-testid":"fb-folder",onClick:n,type:"button",children:[c,i]}),e[6]=n,e[7]=i,e[8]=s):s=e[8],s},"Kt"),Lt=m(d=>{let e=(0,M.c)(34),{busy:t,copiedKey:r,files:l,folders:n,handlers:c,onEnterFolder:i,prefix:s,references:u,resolveUrl:h,selected:f,showReferences:p,size:w,t:a}=d,k;e[0]!==w?(k=w.toString(),e[0]=w,e[1]=k):k=e[1];let N=`repeat(auto-fill, minmax(${k}px, 1fr))`,v;e[2]!==N?(v={gridTemplateColumns:N},e[2]=N,e[3]=v):v=e[3];let b=v,y;if(e[4]!==n||e[5]!==i){let S;e[7]!==i?(S=m(C=>(0,o.jsx)(Et,{name:C,onEnter:i},C),"S"),e[7]=i,e[8]=S):S=e[8],y=n.map(S),e[4]=n,e[5]=i,e[6]=y}else y=e[6];let x;if(e[9]!==t||e[10]!==r||e[11]!==l||e[12]!==c||e[13]!==s||e[14]!==u||e[15]!==h||e[16]!==f||e[17]!==p||e[18]!==a){let S;e[20]!==t||e[21]!==r||e[22]!==c||e[23]!==s||e[24]!==u||e[25]!==h||e[26]!==f||e[27]!==p||e[28]!==a?(S=m(C=>(0,o.jsx)(Ot,{busy:t,copiedKey:r,handlers:c,object:C,prefix:s,references:u[C.key],resolveUrl:h,selected:f.has(C.key),showReferences:p,t:a},C.key),"S"),e[20]=t,e[21]=r,e[22]=c,e[23]=s,e[24]=u,e[25]=h,e[26]=f,e[27]=p,e[28]=a,e[29]=S):S=e[29],x=l.map(S),e[9]=t,e[10]=r,e[11]=l,e[12]=c,e[13]=s,e[14]=u,e[15]=h,e[16]=f,e[17]=p,e[18]=a,e[19]=x}else x=e[19];let j;return e[30]!==b||e[31]!==y||e[32]!==x?(j=(0,o.jsxs)("div",{className:"grid gap-4","data-testid":"fb-gallery",style:b,children:[y,x]}),e[30]=b,e[31]=y,e[32]=x,e[33]=j):j=e[33],j},"Lt"),_t=m(d=>{let e=(0,M.c)(23),{reference:t,t:r}=d,l=`fb-dangling-${t.table}-${t.id}-${t.column}`,n=`${t.table}\xB7${t.id}`,c;e[0]!==n?(c=(0,o.jsx)(ae,{variant:"secondary",children:n}),e[0]=n,e[1]=c):c=e[1];let i;e[2]!==t.column?(i=(0,o.jsx)("span",{className:"text-muted-foreground",children:t.column}),e[2]=t.column,e[3]=i):i=e[3];let s;e[4]!==r?(s=r("\u2192"),e[4]=r,e[5]=s):s=e[5];let u;e[6]!==s?(u=(0,o.jsx)("span",{className:"text-muted-foreground/60",children:s}),e[6]=s,e[7]=u):u=e[7];let h;e[8]!==t.key?(h=(0,o.jsx)("code",{className:"rounded bg-muted px-1 py-0.5 font-mono text-foreground",children:t.key}),e[8]=t.key,e[9]=h):h=e[9];let f;e[10]!==c||e[11]!==i||e[12]!==u||e[13]!==h?(f=(0,o.jsxs)("span",{className:"flex flex-wrap items-center gap-1.5",children:[c,i,u,h]}),e[10]=c,e[11]=i,e[12]=u,e[13]=h,e[14]=f):f=e[14];let p;e[15]!==r?(p=r("Missing object"),e[15]=r,e[16]=p):p=e[16];let w;e[17]!==p?(w=(0,o.jsx)(ae,{className:"border-destructive/40 text-destructive",variant:"outline",children:p}),e[17]=p,e[18]=w):w=e[18];let a;return e[19]!==l||e[20]!==w||e[21]!==f?(a=(0,o.jsxs)("li",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border border-border/60 px-3 py-2 text-xs","data-testid":l,children:[f,w]}),e[19]=l,e[20]=w,e[21]=f,e[22]=a):a=e[22],a},"Bt"),Bt=m(d=>{let e=(0,M.c)(42),{busy:t,onCheck:r,references:l,t:n,truncated:c}=d,i;e[0]!==n?(i=n("Integrity"),e[0]=n,e[1]=i):i=e[1];let s;e[2]!==i?(s=(0,o.jsx)("span",{className:"font-mono text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),e[2]=i,e[3]=s):s=e[3];let u;e[4]!==n?(u=n("Orphaned objects"),e[4]=n,e[5]=u):u=e[5];let h;e[6]!==u?(h=(0,o.jsx)("span",{className:"text-sm font-medium text-foreground",children:u}),e[6]=u,e[7]=h):h=e[7];let f;e[8]!==n?(f=n("Find records whose file reference points at an object the bucket no longer has."),e[8]=n,e[9]=f):f=e[9];let p;e[10]!==f?(p=(0,o.jsx)("span",{className:"text-xs text-muted-foreground",children:f}),e[10]=f,e[11]=p):p=e[11];let w;e[12]!==s||e[13]!==h||e[14]!==p?(w=(0,o.jsxs)("div",{className:"flex flex-col gap-1",children:[s,h,p]}),e[12]=s,e[13]=h,e[14]=p,e[15]=w):w=e[15];let a;e[16]!==t||e[17]!==n?(a=n(t?"Checking\u2026":"Check for orphans"),e[16]=t,e[17]=n,e[18]=a):a=e[18];let k;e[19]!==t||e[20]!==r||e[21]!==a?(k=(0,o.jsx)(te,{"data-testid":"fb-orphans-check",disabled:t,onClick:r,size:"sm",type:"button",variant:"outline",children:a}),e[19]=t,e[20]=r,e[21]=a,e[22]=k):k=e[22];let N;e[23]!==w||e[24]!==k?(N=(0,o.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2",children:[w,k]}),e[23]=w,e[24]=k,e[25]=N):N=e[25];let v;e[26]!==l||e[27]!==n||e[28]!==c?(v=c&&(0,o.jsx)("p",{className:"text-xs text-warning","data-testid":"fb-orphans-truncated",children:l===void 0||l.length===0?n("The bucket is larger than the scan's key limit, so dangling references could not be checked."):n("Showing the first {count} dangling references \u2014 the scan was truncated.",{count:l.length})}),e[26]=l,e[27]=n,e[28]=c,e[29]=v):v=e[29];let b;e[30]!==l?.length||e[31]!==n||e[32]!==c?(b=l?.length===0&&!c&&(0,o.jsx)(he,{description:n("Every record's file reference points at an object that exists in the bucket."),testId:"fb-orphans-empty",title:n("No dangling references.")}),e[30]=l?.length,e[31]=n,e[32]=c,e[33]=b):b=e[33];let y;e[34]!==l||e[35]!==n?(y=l!==void 0&&l.length>0&&(0,o.jsx)("ul",{className:"flex flex-col gap-1.5","data-testid":"fb-orphans-list",children:l.map(j=>(0,o.jsx)(_t,{reference:j,t:n},`${j.table}\xB7${j.id}\xB7${j.column}`))}),e[34]=l,e[35]=n,e[36]=y):y=e[36];let x;return e[37]!==N||e[38]!==v||e[39]!==b||e[40]!==y?(x=(0,o.jsxs)("section",{className:"flex flex-col gap-2 rounded-lg border border-border/60 p-3","data-testid":"fb-orphans",children:[N,v,b,y]}),e[37]=N,e[38]=v,e[39]=b,e[40]=y,e[41]=x):x=e[41],x},"It"),It=m(function(d,e){let t=(0,M.c)(18),r;t[0]===Symbol.for("react.memo_cache_sentinel")?(r=new Set,t[0]=r):r=t[0];let[l,n]=(0,z.useState)(r),c;t[1]===Symbol.for("react.memo_cache_sentinel")?(c=m(v=>{n(b=>{let y=new Set(b);return y.has(v)?y.delete(v):y.add(v),y})},"a"),t[1]=c):c=t[1];let i=c,s;t[2]===Symbol.for("react.memo_cache_sentinel")?(s=m(()=>{n(new Set)},"o"),t[2]=s):s=t[2];let u=s,h,f,p;if(t[3]!==d||t[4]!==e||t[5]!==l){let v;t[9]!==e?(v=m(b=>e(b),"x"),t[9]=e,t[10]=v):v=t[10],f=d.map(v),h=f.length>0&&f.every(b=>l.has(b)),p=!h&&f.some(b=>l.has(b)),t[3]=d,t[4]=e,t[5]=l,t[6]=h,t[7]=f,t[8]=p}else h=t[6],f=t[7],p=t[8];let w=p,a;t[11]!==f?(a=m(()=>{n(v=>f.every(b=>v.has(b))?new Set:new Set(f))},"i"),t[11]=f,t[12]=a):a=t[12];let k=a,N;return t[13]!==h||t[14]!==l||t[15]!==w||t[16]!==k?(N={allSelected:h,clear:u,selected:l,someSelected:w,toggle:i,toggleAll:k},t[13]=h,t[14]=l,t[15]=w,t[16]=k,t[17]=N):N=t[17],N},"Ot"),Rt=me(be.storageReferences),Ut=me(be.storageOrphans),Ie=1e4,Mt=1e3,At=m(async d=>{let e=[],t,r=!0,l=!1;for(;r&&e.length<Ie;){let n=await d.list({cursor:t,limit:Mt}),c=Ie-e.length;for(let i of n.objects.slice(0,c))e.push(i.key);l||=n.objects.length>c,t=n.cursor,r=t!==void 0}return{liveKeys:e,truncated:l||r}},"Gt"),Pt=3600,Wt=m((d,e)=>{if(!("document"in globalThis))return;let t=globalThis.document.createElement("a");t.href=d,t.download=e,t.rel="noopener",globalThis.document.body.append(t),t.click(),t.remove()},"Pt"),Ht=m(d=>d.key,"qt"),qt=m(({initialPrefix:d,pageSize:e})=>{let t=Se(),[r,l]=(0,z.useState)(d??""),[n,c]=(0,z.useState)(d??""),[i,s]=(0,z.useState)(wt),[u,h]=(0,z.useState)("list"),[f,p]=(0,z.useState)(128),[w,a]=(0,z.useState)("name"),[k,N]=(0,z.useState)("asc"),[v,b]=(0,z.useState)(void 0),[y,x]=(0,z.useState)(void 0),[j,S]=(0,z.useState)(!1),[C,T]=(0,z.useState)(void 0),[D,F]=(0,z.useState)(void 0),[$,O]=(0,z.useState)(""),[B,L]=(0,z.useState)({}),[I,E]=(0,z.useState)(!1),[_,U]=(0,z.useState)(void 0),[A,H]=(0,z.useState)(!1),[P,q]=(0,z.useState)(!1),[Y,ne]=(0,z.useState)([]),[G,xe]=(0,z.useState)(""),oe=(0,z.useRef)(0),J=(0,z.useRef)(0);(0,z.useEffect)(()=>{let g={cancelled:!1};return W((async()=>{try{let K=await t.listStorageBuckets();if(!g.cancelled){ne(K);let[R]=K;R!==void 0&&xe(X=>X===""?R:X)}}catch{}})()),()=>{g.cancelled=!0}},[t]);let V=(0,z.useMemo)(()=>({list:m(g=>t.listStorageObjects({...g,bucket:G}),"list"),remove:m(g=>t.deleteStorageObject(g,{bucket:G}),"remove"),signedUrl:m((g,K)=>t.signedStorageUrl(g,{...K,bucket:G}),"signedUrl"),upload:m(g=>t.uploadStorageObject({...g,bucket:G}),"upload")}),[G,t]),Z=(0,z.useCallback)(async(g,K,R)=>{oe.current+=1;let X=oe.current;x(void 0),S(!0);try{let se=await V.list({cursor:K,limit:e,prefix:g});if(X!==oe.current)return;b(we=>R&&we!==void 0?[...we,...se.objects]:se.objects),F(se.cursor)}catch(se){if(X!==oe.current)return;R||b(void 0),x(Q(se))}finally{X===oe.current&&S(!1)}},[e,V]);(0,z.useEffect)(()=>{W(Z(d??"",void 0,!1))},[Z,d]);let We=(v?.length??0)<=e;Ee(()=>{W(Z(r,void 0,!1))},We);let{files:de,folders:He}=Nt(v??[],r),qe=(0,z.useMemo)(()=>{let g=new Set;for(let K of de)for(let R of Object.keys(K.customMetadata??{}))g.add(R);return[...g].toSorted((K,R)=>K.localeCompare(R))},[de]),ce=St(de,w,k),ue=(0,z.useMemo)(()=>[...new Set(ce.map(g=>g.key))].toSorted((g,K)=>g.localeCompare(K)).join(`
|
|
3
|
-
`),[ce]);(0,z.useEffect)(()=>{let g=ue===""?[]:ue.split(`
|
|
4
|
-
`);if(g.length===0){L({});return}let K={current:!0};return W((async()=>{try{let R=await t.query(Rt,{keys:g},pe($));K.current&&(L(R.references??{}),E(Object.keys(R.storageColumns??{}).length>0))}catch{K.current&&(L({}),E(!1))}})()),()=>{K.current=!1}},[t,ue,$]);let{allSelected:Ge,clear:le,selected:ve,someSelected:Ve,toggle:Ze,toggleAll:Xe}=It(ce,Ht),Ye=m(()=>{l(n),le(),W(Z(n,void 0,!1))},"Oe"),Je=m(()=>{W(Z(r,D,!0))},"Ae"),ke=m(g=>{l(g),c(g),le(),W(Z(g,void 0,!1))},"be"),Qe=m(g=>{ke(`${r}${g}`)},"Ue"),et=m(g=>V.signedUrl(g,{expiresInSeconds:Pt}),"Me"),tt=m(()=>{h("list")},"Ge"),rt=m(()=>{h("grid")},"He"),nt=m(g=>{a(g)},"Pe"),ot=m(()=>{N(g=>g==="asc"?"desc":"asc")},"qe"),lt=m(g=>{p(g)},"Ve"),st=m(g=>{s(g)},"We"),at=m(()=>{x(void 0),S(!0),W((async()=>{try{for(let g of ve)await V.remove(g);await Z(r,void 0,!1),le()}catch(g){x(Q(g))}S(!1)})())},"Ze"),ct=m(g=>{x(void 0),W((async()=>{try{let K=await V.signedUrl(g,{expiresInSeconds:i});De(K)&&T(g)}catch(K){x(Q(K))}})())},"Xe"),it=m(g=>{x(void 0),W((async()=>{try{let K=await V.signedUrl(g,{expiresInSeconds:i}),R=g.slice(g.lastIndexOf("/")+1)||g;Wt(K,R)}catch(K){x(Q(K))}})())},"Ye");(0,z.useEffect)(()=>{if(C===void 0)return;let g=globalThis.setTimeout(()=>{T(void 0)},2e3);return()=>{globalThis.clearTimeout(g)}},[C]);let dt=m(g=>{x(void 0),S(!0),W((async()=>{try{await V.remove(g),await Z(r,void 0,!1)}catch(K){x(Q(K))}S(!1)})())},"Je"),ut=m(g=>{let K=`${r}${g.name}`;x(void 0),S(!0),W((async()=>{try{let R=await g.arrayBuffer();await V.upload({body:R,contentType:g.type===""?void 0:g.type,key:K}),await Z(r,void 0,!1)}catch(R){x(Q(R))}S(!1)})())},"Qe");(0,z.useEffect)(()=>{J.current+=1,U(void 0),q(!1)},[$]);let ft=m(()=>{J.current+=1;let g=J.current;x(void 0),H(!0),W((async()=>{try{let{liveKeys:K,truncated:R}=await At(V);if(R)g===J.current&&(U(void 0),q(!0));else{let X=await t.query(Ut,{liveKeys:K},pe($));g===J.current&&(U(X.references??[]),q(X.truncated===!0))}}catch(K){g===J.current&&(U(void 0),q(!1),x(Q(K)))}g===J.current&&H(!1)})())},"et"),ht=m(g=>{oe.current+=1,J.current+=1,xe(g),l(d??""),c(d??""),b(void 0),U(void 0),q(!1),le()},"tt");return{allSelected:Ge,bucket:G,buckets:Y,bulkDelete:at,busy:j,checkOrphans:ft,clearSelection:le,copiedKey:C,danglingBusy:A,danglingReferences:_,danglingTruncated:P,draftPrefix:n,enterFolder:Qe,error:y,expiry:i,files:ce,folders:He,hasObjects:v!==void 0&&v.length>0,hasStorageColumns:I,listFirst:Ye,loaded:v!==void 0,loadMore:Je,navigate:ke,nextCursor:D,onCopy:ct,onDelete:dt,onDownload:it,onExpiryChange:st,onFile:ut,onSortKeyChange:nt,onThumbSizeChange:lt,prefix:r,referenceShard:$,references:B,resolveUrl:et,selectBucket:ht,selected:ve,setDraftPrefix:c,setReferenceShard:O,showGrid:rt,showList:tt,someSelected:Ve,sortDirection:k,sortKey:w,tagKeys:qe,thumbSize:f,toggleSelect:Ze,toggleSelectAll:Xe,toggleSortDirection:ot,view:u}},"Vt"),Gt=100,Re=m(d=>{let e=(0,M.c)(6),{label:t,onNavigate:r,target:l}=d,n;e[0]!==r||e[1]!==l?(n=m(()=>{r(l)},"l"),e[0]=r,e[1]=l,e[2]=n):n=e[2];let c=n,i;return e[3]!==c||e[4]!==t?(i=(0,o.jsx)("button",{className:"rounded px-1 text-muted-foreground outline-none hover:text-foreground focus-visible:text-foreground",onClick:c,type:"button",children:t}),e[3]=c,e[4]=t,e[5]=i):i=e[5],i},"Se"),Vt=m(d=>{let e=(0,M.c)(11),{onNavigate:t,prefix:r,t:l}=d,n;if(e[0]!==t||e[1]!==r||e[2]!==l){let c=r.split("/").filter(Zt),i;e[4]!==l?(i=l("Folder path"),e[4]=l,e[5]=i):i=e[5];let s;e[6]!==l?(s=l("root"),e[6]=l,e[7]=s):s=e[7];let u;e[8]!==t||e[9]!==s?(u=(0,o.jsx)(Re,{label:s,onNavigate:t,target:""}),e[8]=t,e[9]=s,e[10]=u):u=e[10],n=(0,o.jsxs)("nav",{"aria-label":i,className:"flex flex-wrap items-center gap-0.5 text-xs","data-testid":"fb-breadcrumbs",children:[u,c.map((h,f)=>(0,o.jsxs)("span",{className:"flex items-center gap-0.5",children:[(0,o.jsx)("span",{className:"text-muted-foreground/50",children:"/"}),(0,o.jsx)(Re,{label:h,onNavigate:t,target:`${c.slice(0,f+1).join("/")}/`})]},`${h}-${f.toString()}`))]}),e[0]=t,e[1]=r,e[2]=l,e[3]=n}else n=e[3];return n},"Zt"),fr=m(({initialPrefix:d,pageSize:e=Gt})=>{let t=Ne(),r=qt({initialPrefix:d,pageSize:e}),l=(0,z.useRef)(null),{onCopy:n,onDelete:c,onDownload:i,onFile:s,toggleSelect:u}=r,h={onCopy:n,onDelete:c,onDownload:i,onToggleSelect:u},f=m(()=>{l.current?.click()},"u"),p=m(a=>{let k=a.target,N=k.files?.[0];k.value="",N&&s(N)},"m"),w=r.loaded&&!r.hasObjects;return(0,o.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-file-browser",children:[(0,o.jsx)(Ct,{bucket:r.bucket,buckets:r.buckets,busy:r.busy,draftPrefix:r.draftPrefix,expiry:r.expiry,fileInputRef:l,onBucketChange:r.selectBucket,onExpiryChange:r.onExpiryChange,onFileChange:p,onList:r.listFirst,onPrefixChange:r.setDraftPrefix,onUploadClick:f,t}),r.loaded&&(0,o.jsx)(Vt,{onNavigate:r.navigate,prefix:r.prefix,t}),r.hasObjects&&(0,o.jsx)(jt,{onSortKeyChange:r.onSortKeyChange,onThumbSizeChange:r.onThumbSizeChange,showGrid:r.showGrid,showList:r.showList,sortDirection:r.sortDirection,sortKey:r.sortKey,t,tagKeys:r.tagKeys,thumbSize:r.thumbSize,toggleSortDirection:r.toggleSortDirection,view:r.view}),r.hasStorageColumns&&(0,o.jsxs)("div",{className:"flex flex-wrap items-center gap-2","data-testid":"fb-references-shard",children:[(0,o.jsx)("label",{className:"text-xs text-muted-foreground",htmlFor:"fb-reference-shard-input",children:t("References shard")}),(0,o.jsx)(Te,{id:"fb-reference-shard-input",onChange:r.setReferenceShard,testId:"fb-reference-shard-input",value:r.referenceShard}),(0,o.jsx)("span",{className:"text-xs text-muted-foreground",children:t("Which shard's records are checked for references to these files. Empty = root shard.")})]}),r.hasStorageColumns&&(0,o.jsx)(Bt,{busy:r.danglingBusy,onCheck:r.checkOrphans,references:r.danglingReferences,t,truncated:r.danglingTruncated}),r.selected.size>0&&(0,o.jsx)(Le,{count:r.selected.size,editable:!0,onClear:r.clearSelection,onDelete:r.bulkDelete}),r.error!==void 0&&(0,o.jsx)("p",{className:"text-sm text-destructive","data-testid":"storage-error",role:"alert",children:r.error}),w&&(0,o.jsx)(he,{description:t("Objects you upload to your R2 buckets will appear here."),icon:(0,o.jsxs)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:[(0,o.jsx)("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7Z"}),(0,o.jsx)("path",{d:"M12 11v5m-2.5-2.5h5"})]}),testId:"fb-empty",title:t("No objects.")}),r.hasObjects&&r.view==="list"&&(0,o.jsx)(vt,{allSelected:r.allSelected,busy:r.busy,copiedKey:r.copiedKey,files:r.files,folders:r.folders,handlers:h,onEnterFolder:r.enterFolder,prefix:r.prefix,references:r.references,selected:r.selected,showReferences:r.hasStorageColumns,someSelected:r.someSelected,t,toggleSelectAll:r.toggleSelectAll}),r.hasObjects&&r.view==="grid"&&(0,o.jsx)(Lt,{busy:r.busy,copiedKey:r.copiedKey,files:r.files,folders:r.folders,handlers:h,onEnterFolder:r.enterFolder,prefix:r.prefix,references:r.references,resolveUrl:r.resolveUrl,selected:r.selected,showReferences:r.hasStorageColumns,size:r.thumbSize,t}),r.nextCursor!==void 0&&(0,o.jsx)("div",{children:(0,o.jsx)(te,{"data-testid":"fb-next",disabled:r.busy,onClick:r.loadMore,size:"sm",type:"button",variant:"outline",children:t("Load more")})})]})},"ps");function Zt(d){return d!==""}m(Zt,"Xt");export{fr as FileBrowser};
|