@lunora/studio 1.0.0-alpha.223 → 1.0.0-alpha.224
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/standalone/{chunk-4ZHQUGP5.js → chunk-27ILKCWI.js} +1 -1
- package/dist/standalone/{chunk-PQPPJGH4.js → chunk-2LJKZSU4.js} +1 -1
- package/dist/standalone/{chunk-LD7EXQJA.js → chunk-2OW5U2BZ.js} +1 -1
- package/dist/standalone/{chunk-EUBMVV62.js → chunk-2ZFFWSLG.js} +1 -1
- package/dist/standalone/{chunk-6ZPT7CTC.js → chunk-3EDFZHY5.js} +1 -1
- package/dist/standalone/{chunk-EBNLDFWL.js → chunk-3G3KM5QW.js} +1 -1
- package/dist/standalone/{chunk-5JAOC6KI.js → chunk-3UW7JOCC.js} +1 -1
- package/dist/standalone/{chunk-6LYYH4KG.js → chunk-4YXKODH3.js} +1 -1
- package/dist/standalone/{chunk-BWLFO2IE.js → chunk-74CQY3AB.js} +1 -1
- package/dist/standalone/{chunk-QYCKDIIK.js → chunk-7FTSNUL7.js} +1 -1
- package/dist/standalone/{chunk-QZRXRMVF.js → chunk-7UHE2RRI.js} +1 -1
- package/dist/standalone/{chunk-NX7UAIZ2.js → chunk-CFYXGSV3.js} +1 -1
- package/dist/standalone/{chunk-KRYLPBID.js → chunk-D6Z2ZUU7.js} +1 -1
- package/dist/standalone/{chunk-2H7LJELF.js → chunk-DG5KSS6E.js} +1 -1
- package/dist/standalone/{chunk-BNFLBJXF.js → chunk-E6YTK54J.js} +1 -1
- package/dist/standalone/{chunk-5CEDU7OP.js → chunk-EBNWZ33C.js} +1 -1
- package/dist/standalone/{chunk-VWJ4BY6M.js → chunk-EVGASJNW.js} +1 -1
- package/dist/standalone/{chunk-FRX3HV4O.js → chunk-FMEXQNO7.js} +1 -1
- package/dist/standalone/{chunk-C7JZ7GM3.js → chunk-FQEKYLWQ.js} +1 -1
- package/dist/standalone/{chunk-4RLMVWJL.js → chunk-FS4K5TEX.js} +1 -1
- package/dist/standalone/{chunk-IVSO7SEU.js → chunk-FZAGSACU.js} +1 -1
- package/dist/standalone/{chunk-ZY35EIK4.js → chunk-G6JWVIBX.js} +1 -1
- package/dist/standalone/{chunk-PJZYLISI.js → chunk-GFB3DJBT.js} +1 -1
- package/dist/standalone/{chunk-U775EN4P.js → chunk-GQWFRBCJ.js} +1 -1
- package/dist/standalone/{chunk-2PLDVCEP.js → chunk-I7GBAQ72.js} +1 -1
- package/dist/standalone/{chunk-4IX7Z3XP.js → chunk-IL34SD2J.js} +1 -1
- package/dist/standalone/{chunk-OCZPVECA.js → chunk-INHSAPFB.js} +1 -1
- package/dist/standalone/{chunk-NSTYZZ5L.js → chunk-JL7WQ35Y.js} +1 -1
- package/dist/standalone/{chunk-YTMEMOHR.js → chunk-KDY4VSAF.js} +1 -1
- package/dist/standalone/{chunk-ZXEE2Z4S.js → chunk-KJOMRSX7.js} +1 -1
- package/dist/standalone/{chunk-BOASUV37.js → chunk-KME5TGGZ.js} +1 -1
- package/dist/standalone/{chunk-TS5SE5EM.js → chunk-KTBJ5SQO.js} +1 -1
- package/dist/standalone/{chunk-6UFH4FWY.js → chunk-NHLLFFXW.js} +1 -1
- package/dist/standalone/chunk-NZKXQEZ5.js +9 -0
- package/dist/standalone/{chunk-NGBD2OUY.js → chunk-OBUY7UZO.js} +1 -1
- package/dist/standalone/{chunk-WLA5B3GY.js → chunk-OIHA5CMU.js} +1 -1
- package/dist/standalone/{chunk-YGZGLWD5.js → chunk-OMTRTMGC.js} +1 -1
- package/dist/standalone/{chunk-2UECQGYG.js → chunk-PCYB6Q5V.js} +1 -1
- package/dist/standalone/{chunk-SRVHSFKC.js → chunk-Q5H5UZCT.js} +1 -1
- package/dist/standalone/{chunk-4DLM7KCA.js → chunk-QOQ56UE7.js} +1 -1
- package/dist/standalone/{chunk-SQKUZR6R.js → chunk-QWBMBXUI.js} +1 -1
- package/dist/standalone/{chunk-CFIBDQF7.js → chunk-RFNTIPZM.js} +1 -1
- package/dist/standalone/{chunk-MK64Z2KK.js → chunk-RK5UUSYK.js} +1 -1
- package/dist/standalone/{chunk-FZXPE3EA.js → chunk-S6ZFBF3S.js} +1 -1
- package/dist/standalone/{chunk-MU57Q7EJ.js → chunk-SB535MB2.js} +1 -1
- package/dist/standalone/{chunk-NNOKBVJ7.js → chunk-SL2WTTEZ.js} +1 -1
- package/dist/standalone/{chunk-D73MZIDA.js → chunk-SWS6R7OJ.js} +1 -1
- package/dist/standalone/{chunk-EIREQDTV.js → chunk-TSNKMJKC.js} +1 -1
- package/dist/standalone/{chunk-ANAVNSAK.js → chunk-UTIAX6IO.js} +1 -1
- package/dist/standalone/{chunk-DPJRFJGG.js → chunk-UWHH6R7J.js} +1 -1
- package/dist/standalone/{chunk-YHYYGVE2.js → chunk-VVQBWSND.js} +1 -1
- package/dist/standalone/{chunk-BF5GZZ2N.js → chunk-WLLOZ3HS.js} +1 -1
- package/dist/standalone/{chunk-HZ23X7G4.js → chunk-WM5HSIP3.js} +1 -1
- package/dist/standalone/{chunk-NO3SWCXH.js → chunk-WQ6OGGRQ.js} +1 -1
- package/dist/standalone/{chunk-DHJHD5RD.js → chunk-WRSH2CJD.js} +1 -1
- package/dist/standalone/{chunk-C5JRZI3P.js → chunk-WXDKJUXF.js} +1 -1
- package/dist/standalone/studio.js +1 -1
- package/package.json +3 -3
- package/dist/standalone/chunk-BJEJVHCO.js +0 -9
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a as Pe,b as Re}from"./chunk-EIISOYGA.js";import{a as ce}from"./chunk-RPQL45FL.js";import{a as Te}from"./chunk-B2HYHTIX.js";import"./chunk-4GTO7FL5.js";import{a as Se}from"./chunk-MXLAOCAN.js";import{b as ke}from"./chunk-CMA4PTV7.js";import{a as de}from"./chunk-UYEZR3BI.js";import{a as Le}from"./chunk-Z5O2NQAV.js";import{a as ie}from"./chunk-QKEJLVC5.js";import{a as xe}from"./chunk-S3CRZLGS.js";import{a as be}from"./chunk-EJSI4PMU.js";import{b as ve}from"./chunk-OGUKYRFM.js";import"./chunk-6D6Z2KXU.js";import"./chunk-OKG3HWSJ.js";import{W as D}from"./chunk-PLHA3OWK.js";import"./chunk-Y6CXU7T4.js";import"./chunk-4L4WTGN5.js";import{a as pe}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as re}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as ye}from"./chunk-EIREQDTV.js";import"./chunk-ULIQFBZU.js";import"./chunk-FZXPE3EA.js";import"./chunk-35DM4JJG.js";import{a as ne}from"./chunk-4ZEL6BYL.js";import{c as oe}from"./chunk-4ZHQUGP5.js";import{f as ge}from"./chunk-BJEJVHCO.js";import"./chunk-FSRSK4LY.js";import"./chunk-5ICUJ4IA.js";import{a as J}from"./chunk-FKVZRPV5.js";import{a as we,b as Ne,c as Ce,d as se,e as B,f as W}from"./chunk-HEAQVSNS.js";import{d as z,h as ae,i as fe,p as le}from"./chunk-PTZD7RUZ.js";import{a as v,d as te,e as _e,f as Ae,g as Ue,i as j}from"./chunk-YKXDMIHQ.js";var K=te(Ae(),1);var I=te(_e(),1);var r=te(Ue(),1);var me=["trace","debug","log","info","warn","error","fatal"],$e="LOG_ARCHIVE_NOT_CONFIGURED",ze={cursor:void 0,error:null,loading:!1,notConfigured:!1,rows:null},De=v((i,e)=>{switch(e.type){case"append":return{...i,cursor:e.cursor,error:null,loading:!1,rows:[...i.rows??[],...e.rows]};case"failed":return{cursor:void 0,error:e.message,loading:!1,notConfigured:!1,rows:null};case"loaded":return{cursor:e.cursor,error:null,loading:!1,notConfigured:!1,rows:e.rows};case"loading":return{...i,error:null,loading:!0,notConfigured:!1};case"notConfigured":return{cursor:void 0,error:null,loading:!1,notConfigured:!0,rows:null};case"pageFailed":return{...i,error:e.message,loading:!1};default:return i}},"De"),Be=v(i=>{let e=(0,K.c)(33),{row:t}=i,n;e[0]!==t.fields?(n=ce(t.fields),e[0]=t.fields,e[1]=n):n=e[1];let s=n,o=`lg-archive-row-${String(t.ts)}`,c;e[2]!==t.ts?(c=new Date(t.ts).toLocaleString(),e[2]=t.ts,e[3]=c):c=e[3];let f;e[4]!==c?(f=(0,r.jsx)(W,{className:"tabular-nums whitespace-nowrap text-xs text-muted-foreground",children:c}),e[4]=c,e[5]=f):f=e[5];let m=Pe[t.level],d;e[6]!==t.level||e[7]!==m?(d=(0,r.jsx)(W,{children:(0,r.jsx)(re,{variant:m,children:t.level})}),e[6]=t.level,e[7]=m,e[8]=d):d=e[8];let a;e[9]!==t.functionPath?(a=(0,r.jsx)(W,{className:"font-mono text-xs",children:t.functionPath}),e[9]=t.functionPath,e[10]=a):a=e[10];let h;e[11]!==t.message?(h=(0,r.jsx)("div",{className:"truncate",title:t.message,children:t.message}),e[11]=t.message,e[12]=h):h=e[12];let l;e[13]!==s?(l=s!==""&&(0,r.jsx)("div",{className:"truncate font-mono text-[11px] text-muted-foreground",title:s,children:s}),e[13]=s,e[14]=l):l=e[14];let u;e[15]!==h||e[16]!==l?(u=(0,r.jsxs)(W,{className:"max-w-md",children:[h,l]}),e[15]=h,e[16]=l,e[17]=u):u=e[17];let g=t.traceId??"\u2014",b;e[18]!==g?(b=(0,r.jsx)(W,{className:"font-mono text-[11px] text-muted-foreground",children:g}),e[18]=g,e[19]=b):b=e[19];let x=t.shardKey??"\u2014",w;e[20]!==x?(w=(0,r.jsx)(W,{className:"font-mono text-[11px] text-muted-foreground",children:x}),e[20]=x,e[21]=w):w=e[21];let N=t.userId??"\u2014",y;e[22]!==N?(y=(0,r.jsx)(W,{className:"font-mono text-[11px] text-muted-foreground",children:N}),e[22]=N,e[23]=y):y=e[23];let T;return e[24]!==u||e[25]!==b||e[26]!==w||e[27]!==y||e[28]!==o||e[29]!==f||e[30]!==d||e[31]!==a?(T=(0,r.jsxs)(se,{"data-testid":o,children:[f,d,a,u,b,w,y]}),e[24]=u,e[25]=b,e[26]=w,e[27]=y,e[28]=o,e[29]=f,e[30]=d,e[31]=a,e[32]=T):T=e[32],T},"Qe"),We=v(({shardKey:i})=>{let e=ge(),t=z(),[n,s]=(0,I.useState)(""),[o,c]=(0,I.useState)(""),[f,m]=(0,I.useState)(""),[{cursor:d,error:a,loading:h,notConfigured:l,rows:u},g]=(0,I.useReducer)(De,ze),b=ie(n.trim(),400),x=ie(o.trim(),400),w={...b===""?{}:{functionPathPrefix:b},...f===""?{}:{minLevel:f},...i===""?{}:{shardKey:i},...x===""?{}:{userId:x}},N=JSON.stringify(w),y=(0,I.useRef)(N);(0,I.useEffect)(()=>{let p={cancelled:!1};return y.current=N,le((async()=>{g({type:"loading"});try{let C=await e.queryLogArchive(w);p.cancelled||g({cursor:C.nextCursor,rows:C.rows,type:"loaded"})}catch(C){p.cancelled||g(fe(C)===$e?{type:"notConfigured"}:{message:ae(C),type:"failed"})}})()),()=>{p.cancelled=!0}},[e,N]);let T=v(async()=>{if(d===void 0)return;let p=N;g({type:"loading"});try{let C=await e.queryLogArchive({...w,cursor:d});y.current===p&&g({cursor:C.nextCursor,rows:C.rows,type:"append"})}catch(C){y.current===p&&g({message:ae(C),type:"pageFailed"})}},"T"),R=v(p=>{s(p.target.value)},"R"),k=v(p=>{c(p.target.value)},"N"),L=v(p=>{m(p.target.value)},"L"),S=v(()=>{le(T())},"S");return l?(0,r.jsx)(J,{action:(0,r.jsx)("a",{className:"text-sm text-primary underline-offset-4 hover:underline",href:de,rel:"noreferrer",target:"_blank",children:t("Open in Cloudflare")}),description:t("Wire pipelineLogSink to a Cloudflare Pipeline \u2192 R2 Data Catalog table and set R2_SQL_ACCOUNT_ID, R2_SQL_TOKEN, R2_SQL_BUCKET to browse the durable log archive here."),testId:"lg-archive-not-configured",title:t("Log archive not configured")}):(0,r.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lg-archive",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,r.jsx)(D,{"aria-label":t("Function path prefix"),className:"h-8 w-48","data-testid":"lg-archive-path",onChange:R,placeholder:t("function path\u2026"),value:n}),(0,r.jsx)(D,{"aria-label":t("User id"),className:"h-8 w-40","data-testid":"lg-archive-user",onChange:k,placeholder:t("user id\u2026"),value:o}),(0,r.jsxs)("select",{"aria-label":t("Minimum level"),className:"h-8 rounded-md border border-border bg-background px-2 text-sm","data-testid":"lg-archive-min-level",onChange:L,value:f,children:[(0,r.jsx)("option",{value:"",children:t("min level")}),me.map(p=>(0,r.jsx)("option",{value:p,children:p},p))]})]}),a!==null&&(0,r.jsx)("p",{className:"text-sm text-destructive","data-testid":"lg-archive-error",role:"alert",children:a}),h&&u===null&&a===null&&(0,r.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"lg-archive-loading",children:t("Loading\u2026")}),u!==null&&u.length===0&&(0,r.jsx)(J,{description:t("No archived logs match these filters. The durable archive fills as pipelineLogSink flushes records to R2."),testId:"lg-archive-empty",title:t("No archived logs.")}),u!==null&&u.length>0&&(0,r.jsx)("div",{className:"overflow-hidden rounded-xl border border-border shadow-xs",children:(0,r.jsxs)(we,{"data-testid":"lg-archive-table",children:[(0,r.jsx)(Ne,{children:(0,r.jsxs)(se,{children:[(0,r.jsx)(B,{children:t("Time")}),(0,r.jsx)(B,{children:t("Level")}),(0,r.jsx)(B,{children:t("Function")}),(0,r.jsx)(B,{children:t("Message")}),(0,r.jsx)(B,{children:t("Trace")}),(0,r.jsx)(B,{children:t("Shard")}),(0,r.jsx)(B,{children:t("User")})]})}),(0,r.jsx)(Ce,{children:u.map((p,C)=>(0,r.jsx)(Be,{row:p},`${String(p.ts)}-${String(C)}`))})]})}),d!==void 0&&(0,r.jsx)("div",{children:(0,r.jsx)(pe,{"data-testid":"lg-archive-more",disabled:h,onClick:S,size:"sm",variant:"outline",children:t(h?"Loading\u2026":"Load more")})})]})},"ze"),je=v(i=>{let e=(0,K.c)(11),{level:t,onToggle:n,selected:s}=i,o;e[0]!==t||e[1]!==n?(o=v(()=>{n(t)},"o"),e[0]=t,e[1]=n,e[2]=o):o=e[2];let c=o,f=s?"border-border bg-muted font-medium":"border-input text-muted-foreground",m;e[3]!==f?(m=j("rounded-md border px-2 py-1 text-xs",f),e[3]=f,e[4]=m):m=e[4];let d=`logs-level-${t}`,a;return e[5]!==t||e[6]!==c||e[7]!==s||e[8]!==m||e[9]!==d?(a=(0,r.jsx)("button",{"aria-pressed":s,className:m,"data-testid":d,onClick:c,type:"button",children:t}),e[5]=t,e[6]=c,e[7]=s,e[8]=m,e[9]=d,e[10]=a):a=e[10],a},"Ge"),Ve=v(i=>{let e=(0,K.c)(68),{levelFilter:t,onLogPathChange:n,onSearchChange:s,onTimeRangeChange:o,onToggleLevel:c,onToggleSummary:f,pathFilter:m,search:d,showSummary:a,timeRange:h}=i,l=z(),u;e[0]!==l?(u=l("Search messages"),e[0]=l,e[1]=u):u=e[1];let g;e[2]!==l?(g=l("search message"),e[2]=l,e[3]=g):g=e[3];let b;e[4]!==s||e[5]!==d||e[6]!==u||e[7]!==g?(b=(0,r.jsx)(D,{"aria-label":u,className:"h-8 w-48","data-testid":"lg-search",onChange:s,placeholder:g,value:d}),e[4]=s,e[5]=d,e[6]=u,e[7]=g,e[8]=b):b=e[8];let x;e[9]!==l?(x=l("Function path"),e[9]=l,e[10]=x):x=e[10];let w;e[11]!==l?(w=l("filter path"),e[11]=l,e[12]=w):w=e[12];let N;e[13]!==n||e[14]!==m||e[15]!==x||e[16]!==w?(N=(0,r.jsx)(D,{"aria-label":x,className:"h-8 w-40","data-testid":"logs-path-filter",onChange:n,placeholder:w,value:m}),e[13]=n,e[14]=m,e[15]=x,e[16]=w,e[17]=N):N=e[17];let y;e[18]!==l?(y=l("Level filter"),e[18]=l,e[19]=y):y=e[19];let T;e[20]!==t||e[21]!==c?(T=me.map(Q=>(0,r.jsx)(je,{level:Q,onToggle:c,selected:t.has(Q)},Q)),e[20]=t,e[21]=c,e[22]=T):T=e[22];let R;e[23]!==y||e[24]!==T?(R=(0,r.jsx)("div",{"aria-label":y,className:"inline-flex items-center gap-1","data-testid":"logs-level-filter",role:"group",children:T}),e[23]=y,e[24]=T,e[25]=R):R=e[25];let k;e[26]!==l?(k=l("Time range"),e[26]=l,e[27]=k):k=e[27];let L;e[28]!==l?(L=l("All time"),e[28]=l,e[29]=L):L=e[29];let S;e[30]!==L?(S=(0,r.jsx)("option",{value:"all",children:L}),e[30]=L,e[31]=S):S=e[31];let p;e[32]!==l?(p=l("Last 5m"),e[32]=l,e[33]=p):p=e[33];let C;e[34]!==p?(C=(0,r.jsx)("option",{value:"5m",children:p}),e[34]=p,e[35]=C):C=e[35];let q;e[36]!==l?(q=l("Last 15m"),e[36]=l,e[37]=q):q=e[37];let F;e[38]!==q?(F=(0,r.jsx)("option",{value:"15m",children:q}),e[38]=q,e[39]=F):F=e[39];let O;e[40]!==l?(O=l("Last hour"),e[40]=l,e[41]=O):O=e[41];let E;e[42]!==O?(E=(0,r.jsx)("option",{value:"1h",children:O}),e[42]=O,e[43]=E):E=e[43];let M;e[44]!==o||e[45]!==k||e[46]!==S||e[47]!==C||e[48]!==F||e[49]!==E||e[50]!==h?(M=(0,r.jsxs)("select",{"aria-label":k,className:"h-8 rounded-md border border-input bg-transparent px-2 text-sm shadow-xs focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none","data-testid":"logs-time-range",onChange:o,value:h,children:[S,C,F,E]}),e[44]=o,e[45]=k,e[46]=S,e[47]=C,e[48]=F,e[49]=E,e[50]=h,e[51]=M):M=e[51];let V=a?"border-border bg-muted font-medium":"border-input text-muted-foreground",_;e[52]!==V?(_=j("h-8 rounded-md border px-3 text-sm",V),e[52]=V,e[53]=_):_=e[53];let U;e[54]!==a||e[55]!==l?(U=l(a?"List":"Summary"),e[54]=a,e[55]=l,e[56]=U):U=e[56];let A;e[57]!==f||e[58]!==a||e[59]!==_||e[60]!==U?(A=(0,r.jsx)("button",{"aria-pressed":a,className:_,"data-testid":"logs-summary-toggle",onClick:f,type:"button",children:U}),e[57]=f,e[58]=a,e[59]=_,e[60]=U,e[61]=A):A=e[61];let $;return e[62]!==M||e[63]!==A||e[64]!==b||e[65]!==N||e[66]!==R?($=(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[b,N,R,M,A]}),e[62]=M,e[63]=A,e[64]=b,e[65]=N,e[66]=R,e[67]=$):$=e[67],$},"He"),Qe=v(i=>{let e=(0,K.c)(53),{onOutcomeChange:t,onPathChange:n,onTableChange:s,onUserChange:o,outcomeFilter:c,pathPrefix:f,tableFilter:m,userIdFilter:d}=i,a=z(),h;e[0]!==a?(h=a("Function path"),e[0]=a,e[1]=h):h=e[1];let l;e[2]!==a?(l=a("file:function"),e[2]=a,e[3]=l):l=e[3];let u;e[4]!==n||e[5]!==f||e[6]!==h||e[7]!==l?(u=(0,r.jsx)(D,{"aria-label":h,className:"h-8 w-44","data-testid":"lg-req-path",onChange:n,placeholder:l,value:f}),e[4]=n,e[5]=f,e[6]=h,e[7]=l,e[8]=u):u=e[8];let g;e[9]!==a?(g=a("User id"),e[9]=a,e[10]=g):g=e[10];let b;e[11]!==a?(b=a("userId"),e[11]=a,e[12]=b):b=e[12];let x;e[13]!==o||e[14]!==g||e[15]!==b||e[16]!==d?(x=(0,r.jsx)(D,{"aria-label":g,className:"h-8 w-32","data-testid":"lg-req-user",onChange:o,placeholder:b,value:d}),e[13]=o,e[14]=g,e[15]=b,e[16]=d,e[17]=x):x=e[17];let w;e[18]!==a?(w=a("Table touched"),e[18]=a,e[19]=w):w=e[19];let N;e[20]!==a?(N=a("table"),e[20]=a,e[21]=N):N=e[21];let y;e[22]!==s||e[23]!==w||e[24]!==N||e[25]!==m?(y=(0,r.jsx)(D,{"aria-label":w,className:"h-8 w-32","data-testid":"lg-req-table",onChange:s,placeholder:N,value:m}),e[22]=s,e[23]=w,e[24]=N,e[25]=m,e[26]=y):y=e[26];let T;e[27]!==a?(T=a("Outcome filter"),e[27]=a,e[28]=T):T=e[28];let R;e[29]!==a?(R=a("all"),e[29]=a,e[30]=R):R=e[30];let k;e[31]!==R?(k=(0,r.jsx)("option",{value:"all",children:R}),e[31]=R,e[32]=k):k=e[32];let L;e[33]!==a?(L=a("ok"),e[33]=a,e[34]=L):L=e[34];let S;e[35]!==L?(S=(0,r.jsx)("option",{value:"ok",children:L}),e[35]=L,e[36]=S):S=e[36];let p;e[37]!==a?(p=a("error"),e[37]=a,e[38]=p):p=e[38];let C;e[39]!==p?(C=(0,r.jsx)("option",{value:"error",children:p}),e[39]=p,e[40]=C):C=e[40];let q;e[41]!==t||e[42]!==c||e[43]!==T||e[44]!==k||e[45]!==S||e[46]!==C?(q=(0,r.jsxs)("select",{"aria-label":T,className:"h-8 rounded-md border border-input bg-transparent px-2 text-sm shadow-xs focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none","data-testid":"lg-req-outcome",onChange:t,value:c,children:[k,S,C]}),e[41]=t,e[42]=c,e[43]=T,e[44]=k,e[45]=S,e[46]=C,e[47]=q):q=e[47];let F;return e[48]!==q||e[49]!==u||e[50]!==x||e[51]!==y?(F=(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[u,x,y,q]}),e[48]=q,e[49]=u,e[50]=x,e[51]=y,e[52]=F):F=e[52],F},"We"),Fe=v(i=>{let e=(0,K.c)(7),{bucket:t}=i,n;e[0]!==t.key?(n=(0,r.jsx)("span",{className:"truncate text-muted-foreground",role:"gridcell",children:t.key}),e[0]=t.key,e[1]=n):n=e[1];let s;e[2]!==t.count?(s=(0,r.jsx)("span",{className:"shrink-0 tabular-nums",role:"gridcell",children:t.count}),e[2]=t.count,e[3]=s):s=e[3];let o;return e[4]!==n||e[5]!==s?(o=(0,r.jsxs)("div",{className:"flex items-center justify-between gap-4 px-3 py-1 font-mono text-xs","data-testid":"logs-summary-row",role:"row",children:[n,s]}),e[4]=n,e[5]=s,e[6]=o):o=e[6],o},"ve"),Ye=v(i=>{let e=(0,K.c)(31),{summary:t}=i,n=z(),s;e[0]!==t.total||e[1]!==n?(s=n("{count} entries",{count:t.total}),e[0]=t.total,e[1]=n,e[2]=s):s=e[2];let o;e[3]!==s?(o=(0,r.jsx)("p",{className:"text-xs text-muted-foreground","data-testid":"logs-summary-total",children:s}),e[3]=s,e[4]=o):o=e[4];let c;e[5]!==n?(c=n("By level"),e[5]=n,e[6]=c):c=e[6];let f;e[7]!==c?(f=(0,r.jsx)("h4",{className:"mb-1 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:c}),e[7]=c,e[8]=f):f=e[8];let m;e[9]!==t.byLevel?(m=t.byLevel.map(Ge),e[9]=t.byLevel,e[10]=m):m=e[10];let d;e[11]!==m?(d=(0,r.jsx)("div",{className:"overflow-hidden rounded-lg border border-border","data-testid":"logs-summary-levels",role:"grid",children:m}),e[11]=m,e[12]=d):d=e[12];let a;e[13]!==f||e[14]!==d?(a=(0,r.jsxs)("div",{children:[f,d]}),e[13]=f,e[14]=d,e[15]=a):a=e[15];let h;e[16]!==n?(h=n("By function"),e[16]=n,e[17]=h):h=e[17];let l;e[18]!==h?(l=(0,r.jsx)("h4",{className:"mb-1 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:h}),e[18]=h,e[19]=l):l=e[19];let u;e[20]!==t.byPath?(u=t.byPath.map(He),e[20]=t.byPath,e[21]=u):u=e[21];let g;e[22]!==u?(g=(0,r.jsx)("div",{className:"overflow-hidden rounded-lg border border-border","data-testid":"logs-summary-paths",role:"grid",children:u}),e[22]=u,e[23]=g):g=e[23];let b;e[24]!==g||e[25]!==l?(b=(0,r.jsxs)("div",{children:[l,g]}),e[24]=g,e[25]=l,e[26]=b):b=e[26];let x;return e[27]!==b||e[28]!==o||e[29]!==a?(x=(0,r.jsxs)("div",{className:"flex flex-col gap-4 rounded-xl border border-border bg-card p-4 shadow-xs","data-testid":"logs-summary",children:[o,a,b]}),e[27]=b,e[28]=o,e[29]=a,e[30]=x):x=e[30],x},"Ye");function Ge(i){return(0,r.jsx)(Fe,{bucket:i},i.key)}v(Ge,"je");function He(i){return(0,r.jsx)(Fe,{bucket:i},i.key)}v(He,"Je");var Je=v(i=>{let e=(0,K.c)(46),{liveError:t,onShardKeyChange:n,onShowArchive:s,onShowErrors:o,onShowRequests:c,shardKey:f,view:m}=i,d=z(),a=m==="requests",h=m==="requests"?"bg-muted font-medium":"text-muted-foreground",l;e[0]!==h?(l=j("px-3 py-1 text-sm",h),e[0]=h,e[1]=l):l=e[1];let u;e[2]!==d?(u=d("Requests"),e[2]=d,e[3]=u):u=e[3];let g;e[4]!==c||e[5]!==a||e[6]!==l||e[7]!==u?(g=(0,r.jsx)("button",{"aria-selected":a,className:l,"data-testid":"lg-view-requests",onClick:c,role:"tab",type:"button",children:u}),e[4]=c,e[5]=a,e[6]=l,e[7]=u,e[8]=g):g=e[8];let b=m==="errors",x=m==="errors"?"bg-muted font-medium":"text-muted-foreground",w;e[9]!==x?(w=j("px-3 py-1 text-sm",x),e[9]=x,e[10]=w):w=e[10];let N;e[11]!==d?(N=d("Errors"),e[11]=d,e[12]=N):N=e[12];let y;e[13]!==o||e[14]!==b||e[15]!==w||e[16]!==N?(y=(0,r.jsx)("button",{"aria-selected":b,className:w,"data-testid":"lg-view-errors",onClick:o,role:"tab",type:"button",children:N}),e[13]=o,e[14]=b,e[15]=w,e[16]=N,e[17]=y):y=e[17];let T=m==="archive",R=m==="archive"?"bg-muted font-medium":"text-muted-foreground",k;e[18]!==R?(k=j("px-3 py-1 text-sm",R),e[18]=R,e[19]=k):k=e[19];let L;e[20]!==d?(L=d("Archive"),e[20]=d,e[21]=L):L=e[21];let S;e[22]!==s||e[23]!==T||e[24]!==k||e[25]!==L?(S=(0,r.jsx)("button",{"aria-selected":T,className:k,"data-testid":"lg-view-archive",onClick:s,role:"tab",type:"button",children:L}),e[22]=s,e[23]=T,e[24]=k,e[25]=L,e[26]=S):S=e[26];let p;e[27]!==y||e[28]!==S||e[29]!==g?(p=(0,r.jsxs)("div",{className:"inline-flex overflow-hidden rounded-lg border border-border",role:"tablist",children:[g,y,S]}),e[27]=y,e[28]=S,e[29]=g,e[30]=p):p=e[30];let C;e[31]!==n||e[32]!==f?(C=(0,r.jsx)(be,{onChange:n,testId:"lg-shard-input",value:f}),e[31]=n,e[32]=f,e[33]=C):C=e[33];let q;e[34]!==t||e[35]!==m?(q=m!=="archive"&&(0,r.jsx)(Le,{message:t,prefix:"lg"}),e[34]=t,e[35]=m,e[36]=q):q=e[36];let F;e[37]!==d?(F=d("Open in Cloudflare"),e[37]=d,e[38]=F):F=e[38];let O;e[39]!==F?(O=(0,r.jsx)("a",{className:"text-sm text-primary underline-offset-4 hover:underline","data-testid":"lg-cf-link",href:de,rel:"noreferrer",target:"_blank",children:F}),e[39]=F,e[40]=O):O=e[40];let E;return e[41]!==p||e[42]!==C||e[43]!==q||e[44]!==O?(E=(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[p,C,q,O]}),e[41]=p,e[42]=C,e[43]=q,e[44]=O,e[45]=E):E=e[45],E},"Xe"),ue=400,Xe=36,Ze={height:ue,overflow:"auto"},Oe={left:0,position:"absolute",top:0,width:"100%"},et={error:"destructive",ok:"secondary"},Ee=v(i=>{let e=(0,K.c)(6),{onOpenTrace:t,traceId:n}=i,s=z(),o;e[0]!==t||e[1]!==s||e[2]!==n?(o=n===void 0?null:(0,r.jsx)("button",{className:"text-primary underline-offset-2 hover:underline","data-testid":"lg-trace-link",onClick:v(()=>{t(n)},"onClick"),type:"button",children:s("Trace")}),e[0]=t,e[1]=s,e[2]=n,e[3]=o):o=e[3];let c;return e[4]!==o?(c=(0,r.jsx)("span",{className:"w-16 shrink-0 text-right",role:"gridcell",children:o}),e[4]=o,e[5]=c):c=e[5],c},"xe"),tt=v(i=>{let e=(0,K.c)(13),{entry:t,index:n,measureRef:s,onOpenTrace:o,start:c}=i,f=`translateY(${String(c)}px)`,m;e[0]!==f?(m={...Oe,transform:f},e[0]=f,e[1]=m):m=e[1];let d=m,a;e[2]!==t?(a=(0,r.jsx)(Re,{entry:t}),e[2]=t,e[3]=a):a=e[3];let h;e[4]!==t.traceId||e[5]!==o?(h=(0,r.jsx)(Ee,{onOpenTrace:o,traceId:t.traceId}),e[4]=t.traceId,e[5]=o,e[6]=h):h=e[6];let l;return e[7]!==n||e[8]!==s||e[9]!==d||e[10]!==a||e[11]!==h?(l=(0,r.jsxs)("div",{className:"flex items-center border-b border-border px-3 py-1.5 font-mono text-xs hover:bg-muted/50","data-index":n,"data-testid":"lg-row",ref:s,role:"row",style:d,children:[a,h]}),e[7]=n,e[8]=s,e[9]=d,e[10]=a,e[11]=h,e[12]=l):l=e[12],l},"rt"),Ie=v(i=>i.length===0?"\u2014":i.join(", "),"ce"),rt=v(i=>{let e=(0,K.c)(41),{entry:t,index:n,measureRef:s,onOpenTrace:o,start:c}=i,f=`translateY(${String(c)}px)`,m;e[0]!==f?(m={...Oe,transform:f},e[0]=f,e[1]=m):m=e[1];let d=m,a;e[2]!==t.ts?(a=new Date(t.ts).toLocaleString(),e[2]=t.ts,e[3]=a):a=e[3];let h;e[4]!==a?(h=(0,r.jsx)("span",{className:"w-40 shrink-0 tabular-nums text-muted-foreground",role:"gridcell",children:a}),e[4]=a,e[5]=h):h=e[5];let l=et[t.outcome],u;e[6]!==t.outcome||e[7]!==l?(u=(0,r.jsx)("span",{className:"w-16 shrink-0",role:"gridcell",children:(0,r.jsx)(re,{variant:l,children:t.outcome})}),e[6]=t.outcome,e[7]=l,e[8]=u):u=e[8];let g;e[9]!==t.functionPath?(g=(0,r.jsx)("span",{className:"w-44 shrink-0 truncate",role:"gridcell",title:t.functionPath,children:t.functionPath}),e[9]=t.functionPath,e[10]=g):g=e[10];let b=t.shardKey??"\u2014",x;e[11]!==b?(x=(0,r.jsx)("span",{className:"w-24 shrink-0 truncate text-muted-foreground",role:"gridcell",children:b}),e[11]=b,e[12]=x):x=e[12];let w=t.userId??"\u2014",N;e[13]!==w?(N=(0,r.jsx)("span",{className:"w-24 shrink-0 truncate text-muted-foreground",role:"gridcell",children:w}),e[13]=w,e[14]=N):N=e[14];let y;e[15]!==t.durationMs?(y=Math.round(t.durationMs),e[15]=t.durationMs,e[16]=y):y=e[16];let T=`${String(y)}ms`,R;e[17]!==T?(R=(0,r.jsx)("span",{className:"w-16 shrink-0 tabular-nums text-muted-foreground",role:"gridcell",children:T}),e[17]=T,e[18]=R):R=e[18];let k;e[19]!==t.errorMessage||e[20]!==t.outcome||e[21]!==t.tablesRead||e[22]!==t.tablesWritten?(k=t.outcome==="error"&&t.errorMessage!==void 0?t.errorMessage:`r:${Ie(t.tablesRead)} \xB7 w:${Ie(t.tablesWritten)}`,e[19]=t.errorMessage,e[20]=t.outcome,e[21]=t.tablesRead,e[22]=t.tablesWritten,e[23]=k):k=e[23];let L;e[24]!==k?(L=(0,r.jsx)("span",{className:"flex-1 truncate text-muted-foreground",role:"gridcell",children:k}),e[24]=k,e[25]=L):L=e[25];let S;e[26]!==t.traceId||e[27]!==o?(S=(0,r.jsx)(Ee,{onOpenTrace:o,traceId:t.traceId}),e[26]=t.traceId,e[27]=o,e[28]=S):S=e[28];let p;return e[29]!==n||e[30]!==s||e[31]!==d||e[32]!==N||e[33]!==R||e[34]!==L||e[35]!==S||e[36]!==h||e[37]!==u||e[38]!==g||e[39]!==x?(p=(0,r.jsxs)("div",{className:"flex items-center border-b border-border px-3 py-1.5 font-mono text-xs hover:bg-muted/50","data-index":n,"data-testid":"lg-req-row",ref:s,role:"row",style:d,children:[h,u,g,x,N,R,L,S]}),e[29]=n,e[30]=s,e[31]=d,e[32]=N,e[33]=R,e[34]=L,e[35]=S,e[36]=h,e[37]=u,e[38]=g,e[39]=x,e[40]=p):p=e[40],p},"st"),qe=v(i=>{let{entries:e}=i??{};return Array.isArray(e)?e:[]},"de"),at=v(i=>{let e={};return i.functionPathPrefix.trim()!==""&&(e.functionPathPrefix=i.functionPathPrefix.trim()),i.userId.trim()!==""&&(e.userId=i.userId.trim()),i.tableTouched.trim()!==""&&(e.tableTouched=i.tableTouched.trim()),(i.outcome==="ok"||i.outcome==="error")&&(e.outcome=i.outcome),e},"lt"),lt={"5m":300*1e3,"15m":900*1e3,"1h":3600*1e3},ot=v((i,e)=>{let t=e.search.trim().toLowerCase(),n=e.path.trim().toLowerCase(),s=e.range==="all"?Number.NEGATIVE_INFINITY:e.now-lt[e.range];return i.filter(o=>e.levels.size>0&&!e.levels.has(o.level)||o.timestamp<s||n!==""&&!(o.functionPath??"").toLowerCase().includes(n)?!1:t===""||o.message.toLowerCase().includes(t)||ce(o.fields).toLowerCase().includes(t))},"at"),nt="\u2014",st=v(i=>{let e=new Map,t=new Map;for(let o of i){e.set(o.level,(e.get(o.level)??0)+1);let c=o.functionPath??nt;t.set(c,(t.get(c)??0)+1)}let n=me.filter(o=>e.has(o)).map(o=>({count:e.get(o)??0,key:o})),s=[...t.entries()].map(([o,c])=>({count:c,key:o})).toSorted((o,c)=>c.count===o.count?o.key.localeCompare(c.key):c.count-o.count);return{byLevel:n,byPath:s,total:i.length}},"it"),qt=v(({initialShardKey:i})=>{let e=z(),[t,n]=(0,I.useState)("requests"),{queryShardKey:s,setShardKey:o,shardKey:c}=xe(i),[f,m]=(0,I.useState)(""),[d,a]=(0,I.useState)(()=>new Set),[h,l]=(0,I.useState)(""),[u,g]=(0,I.useState)("all"),[b,x]=(0,I.useState)(!1),[w,N]=(0,I.useState)(""),[y,T]=(0,I.useState)(""),[R,k]=(0,I.useState)(""),[L,S]=(0,I.useState)("all"),p=at({functionPathPrefix:w,outcome:L,tableTouched:R,userId:y}),C=oe(ne.getRequestLog,p,{enabled:t==="requests",live:!0,shardKey:s}),q=oe(ne.getLogs,{},{enabled:t==="errors",live:!0,shardKey:s}),F=t==="requests"?C:q,{error:O,errorSource:E,isLoading:M,liveError:V}=F,_=Te(s),U=qe(q.data),A=qe(C.data);(0,I.useEffect)(()=>{F.data!==void 0&&ve(s)},[F.data,s]);let $=ot(U,{levels:d,now:Date.now(),path:h,range:u,search:f}),Q=st($),X=t==="requests"?A.length:$.length,Z=t==="errors"&&b,Y=(0,I.useMemo)(()=>O!==null?"error":X===0?M?Z?"summary":"list":"empty":Z?"summary":"list",[X,M,O,Z]),he=(0,I.useRef)(null),G=ke({count:X,estimateSize:v(()=>Xe,"estimateSize"),getScrollElement:v(()=>he.current,"getScrollElement"),initialRect:{height:ue,width:800},observeElementRect:v((P,ee)=>Se(P,ee,ue),"observeElementRect"),overscan:8}),Ke=G.getVirtualItems(),Me={height:G.getTotalSize(),position:"relative",width:"100%"};return(0,r.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-logs",children:[(0,r.jsx)(Je,{liveError:V,onShardKeyChange:o,onShowArchive:v(()=>{n("archive"),x(!1)},"onShowArchive"),onShowErrors:v(()=>{n("errors"),x(!1)},"onShowErrors"),onShowRequests:v(()=>{n("requests"),x(!1)},"onShowRequests"),shardKey:c,view:t}),t==="errors"&&(0,r.jsx)(Ve,{levelFilter:d,onLogPathChange:v(P=>{l(P.target.value)},"onLogPathChange"),onSearchChange:v(P=>{m(P.target.value)},"onSearchChange"),onTimeRangeChange:v(P=>{g(P.target.value)},"onTimeRangeChange"),onToggleLevel:v(P=>{a(ee=>{let H=new Set(ee);return H.has(P)?H.delete(P):H.add(P),H})},"onToggleLevel"),onToggleSummary:v(()=>{x(P=>!P)},"onToggleSummary"),pathFilter:h,search:f,showSummary:b,timeRange:u}),t==="requests"&&(0,r.jsx)(Qe,{onOutcomeChange:v(P=>{S(P.target.value)},"onOutcomeChange"),onPathChange:v(P=>{N(P.target.value)},"onPathChange"),onTableChange:v(P=>{k(P.target.value)},"onTableChange"),onUserChange:v(P=>{T(P.target.value)},"onUserChange"),outcomeFilter:L,pathPrefix:w,tableFilter:R,userIdFilter:y}),t==="archive"?(0,r.jsx)(We,{shardKey:s}):(0,r.jsxs)(r.Fragment,{children:[Y==="error"&&(0,r.jsx)(ye,{error:E,testId:"lg-error"}),Y==="empty"&&(0,r.jsx)(J,{description:e("Function and request logs for this shard show up here as your app handles traffic."),icon:(0,r.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,r.jsx)("path",{d:"M4 5h16M4 12h16M4 19h10"})}),testId:"lg-empty",title:e("No logs.")}),Y==="summary"&&(0,r.jsx)(Ye,{summary:Q}),Y==="list"&&(0,r.jsx)("div",{className:"rounded-xl border border-border shadow-xs","data-testid":"lg-scroll",ref:he,style:Ze,children:(0,r.jsx)("div",{"aria-label":e("Recent logs"),"data-testid":"lg-table",role:"grid",style:Me,children:Ke.map(P=>t==="requests"?(0,r.jsx)(rt,{entry:A[P.index],index:P.index,measureRef:G.measureElement,onOpenTrace:_,start:P.start},P.key):(0,r.jsx)(tt,{entry:$[P.index],index:P.index,measureRef:G.measureElement,onOpenTrace:_,start:P.start},P.key))})})]})]})},"Wt");export{qt as LogsPanel,ot as filterLogs,st as summarizeLogs};
|
|
1
|
+
import{a as Pe,b as Re}from"./chunk-EIISOYGA.js";import{a as ce}from"./chunk-RPQL45FL.js";import{a as Te}from"./chunk-B2HYHTIX.js";import"./chunk-4GTO7FL5.js";import{a as Se}from"./chunk-MXLAOCAN.js";import{b as ke}from"./chunk-CMA4PTV7.js";import{a as de}from"./chunk-UYEZR3BI.js";import{a as Le}from"./chunk-Z5O2NQAV.js";import{a as ie}from"./chunk-QKEJLVC5.js";import{a as xe}from"./chunk-S3CRZLGS.js";import{a as be}from"./chunk-EJSI4PMU.js";import{b as ve}from"./chunk-OGUKYRFM.js";import"./chunk-6D6Z2KXU.js";import"./chunk-OKG3HWSJ.js";import{W as D}from"./chunk-PLHA3OWK.js";import"./chunk-Y6CXU7T4.js";import"./chunk-4L4WTGN5.js";import{a as pe}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as re}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as ye}from"./chunk-TSNKMJKC.js";import"./chunk-ULIQFBZU.js";import"./chunk-S6ZFBF3S.js";import"./chunk-35DM4JJG.js";import{a as ne}from"./chunk-4ZEL6BYL.js";import{c as oe}from"./chunk-27ILKCWI.js";import{f as ge}from"./chunk-NZKXQEZ5.js";import"./chunk-FSRSK4LY.js";import"./chunk-5ICUJ4IA.js";import{a as J}from"./chunk-FKVZRPV5.js";import{a as we,b as Ne,c as Ce,d as se,e as B,f as W}from"./chunk-HEAQVSNS.js";import{d as z,h as ae,i as fe,p as le}from"./chunk-PTZD7RUZ.js";import{a as v,d as te,e as _e,f as Ae,g as Ue,i as j}from"./chunk-YKXDMIHQ.js";var K=te(Ae(),1);var I=te(_e(),1);var r=te(Ue(),1);var me=["trace","debug","log","info","warn","error","fatal"],$e="LOG_ARCHIVE_NOT_CONFIGURED",ze={cursor:void 0,error:null,loading:!1,notConfigured:!1,rows:null},De=v((i,e)=>{switch(e.type){case"append":return{...i,cursor:e.cursor,error:null,loading:!1,rows:[...i.rows??[],...e.rows]};case"failed":return{cursor:void 0,error:e.message,loading:!1,notConfigured:!1,rows:null};case"loaded":return{cursor:e.cursor,error:null,loading:!1,notConfigured:!1,rows:e.rows};case"loading":return{...i,error:null,loading:!0,notConfigured:!1};case"notConfigured":return{cursor:void 0,error:null,loading:!1,notConfigured:!0,rows:null};case"pageFailed":return{...i,error:e.message,loading:!1};default:return i}},"De"),Be=v(i=>{let e=(0,K.c)(33),{row:t}=i,n;e[0]!==t.fields?(n=ce(t.fields),e[0]=t.fields,e[1]=n):n=e[1];let s=n,o=`lg-archive-row-${String(t.ts)}`,c;e[2]!==t.ts?(c=new Date(t.ts).toLocaleString(),e[2]=t.ts,e[3]=c):c=e[3];let f;e[4]!==c?(f=(0,r.jsx)(W,{className:"tabular-nums whitespace-nowrap text-xs text-muted-foreground",children:c}),e[4]=c,e[5]=f):f=e[5];let m=Pe[t.level],d;e[6]!==t.level||e[7]!==m?(d=(0,r.jsx)(W,{children:(0,r.jsx)(re,{variant:m,children:t.level})}),e[6]=t.level,e[7]=m,e[8]=d):d=e[8];let a;e[9]!==t.functionPath?(a=(0,r.jsx)(W,{className:"font-mono text-xs",children:t.functionPath}),e[9]=t.functionPath,e[10]=a):a=e[10];let h;e[11]!==t.message?(h=(0,r.jsx)("div",{className:"truncate",title:t.message,children:t.message}),e[11]=t.message,e[12]=h):h=e[12];let l;e[13]!==s?(l=s!==""&&(0,r.jsx)("div",{className:"truncate font-mono text-[11px] text-muted-foreground",title:s,children:s}),e[13]=s,e[14]=l):l=e[14];let u;e[15]!==h||e[16]!==l?(u=(0,r.jsxs)(W,{className:"max-w-md",children:[h,l]}),e[15]=h,e[16]=l,e[17]=u):u=e[17];let g=t.traceId??"\u2014",b;e[18]!==g?(b=(0,r.jsx)(W,{className:"font-mono text-[11px] text-muted-foreground",children:g}),e[18]=g,e[19]=b):b=e[19];let x=t.shardKey??"\u2014",w;e[20]!==x?(w=(0,r.jsx)(W,{className:"font-mono text-[11px] text-muted-foreground",children:x}),e[20]=x,e[21]=w):w=e[21];let N=t.userId??"\u2014",y;e[22]!==N?(y=(0,r.jsx)(W,{className:"font-mono text-[11px] text-muted-foreground",children:N}),e[22]=N,e[23]=y):y=e[23];let T;return e[24]!==u||e[25]!==b||e[26]!==w||e[27]!==y||e[28]!==o||e[29]!==f||e[30]!==d||e[31]!==a?(T=(0,r.jsxs)(se,{"data-testid":o,children:[f,d,a,u,b,w,y]}),e[24]=u,e[25]=b,e[26]=w,e[27]=y,e[28]=o,e[29]=f,e[30]=d,e[31]=a,e[32]=T):T=e[32],T},"Qe"),We=v(({shardKey:i})=>{let e=ge(),t=z(),[n,s]=(0,I.useState)(""),[o,c]=(0,I.useState)(""),[f,m]=(0,I.useState)(""),[{cursor:d,error:a,loading:h,notConfigured:l,rows:u},g]=(0,I.useReducer)(De,ze),b=ie(n.trim(),400),x=ie(o.trim(),400),w={...b===""?{}:{functionPathPrefix:b},...f===""?{}:{minLevel:f},...i===""?{}:{shardKey:i},...x===""?{}:{userId:x}},N=JSON.stringify(w),y=(0,I.useRef)(N);(0,I.useEffect)(()=>{let p={cancelled:!1};return y.current=N,le((async()=>{g({type:"loading"});try{let C=await e.queryLogArchive(w);p.cancelled||g({cursor:C.nextCursor,rows:C.rows,type:"loaded"})}catch(C){p.cancelled||g(fe(C)===$e?{type:"notConfigured"}:{message:ae(C),type:"failed"})}})()),()=>{p.cancelled=!0}},[e,N]);let T=v(async()=>{if(d===void 0)return;let p=N;g({type:"loading"});try{let C=await e.queryLogArchive({...w,cursor:d});y.current===p&&g({cursor:C.nextCursor,rows:C.rows,type:"append"})}catch(C){y.current===p&&g({message:ae(C),type:"pageFailed"})}},"T"),R=v(p=>{s(p.target.value)},"R"),k=v(p=>{c(p.target.value)},"N"),L=v(p=>{m(p.target.value)},"L"),S=v(()=>{le(T())},"S");return l?(0,r.jsx)(J,{action:(0,r.jsx)("a",{className:"text-sm text-primary underline-offset-4 hover:underline",href:de,rel:"noreferrer",target:"_blank",children:t("Open in Cloudflare")}),description:t("Wire pipelineLogSink to a Cloudflare Pipeline \u2192 R2 Data Catalog table and set R2_SQL_ACCOUNT_ID, R2_SQL_TOKEN, R2_SQL_BUCKET to browse the durable log archive here."),testId:"lg-archive-not-configured",title:t("Log archive not configured")}):(0,r.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lg-archive",children:[(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[(0,r.jsx)(D,{"aria-label":t("Function path prefix"),className:"h-8 w-48","data-testid":"lg-archive-path",onChange:R,placeholder:t("function path\u2026"),value:n}),(0,r.jsx)(D,{"aria-label":t("User id"),className:"h-8 w-40","data-testid":"lg-archive-user",onChange:k,placeholder:t("user id\u2026"),value:o}),(0,r.jsxs)("select",{"aria-label":t("Minimum level"),className:"h-8 rounded-md border border-border bg-background px-2 text-sm","data-testid":"lg-archive-min-level",onChange:L,value:f,children:[(0,r.jsx)("option",{value:"",children:t("min level")}),me.map(p=>(0,r.jsx)("option",{value:p,children:p},p))]})]}),a!==null&&(0,r.jsx)("p",{className:"text-sm text-destructive","data-testid":"lg-archive-error",role:"alert",children:a}),h&&u===null&&a===null&&(0,r.jsx)("p",{className:"text-sm text-muted-foreground","data-testid":"lg-archive-loading",children:t("Loading\u2026")}),u!==null&&u.length===0&&(0,r.jsx)(J,{description:t("No archived logs match these filters. The durable archive fills as pipelineLogSink flushes records to R2."),testId:"lg-archive-empty",title:t("No archived logs.")}),u!==null&&u.length>0&&(0,r.jsx)("div",{className:"overflow-hidden rounded-xl border border-border shadow-xs",children:(0,r.jsxs)(we,{"data-testid":"lg-archive-table",children:[(0,r.jsx)(Ne,{children:(0,r.jsxs)(se,{children:[(0,r.jsx)(B,{children:t("Time")}),(0,r.jsx)(B,{children:t("Level")}),(0,r.jsx)(B,{children:t("Function")}),(0,r.jsx)(B,{children:t("Message")}),(0,r.jsx)(B,{children:t("Trace")}),(0,r.jsx)(B,{children:t("Shard")}),(0,r.jsx)(B,{children:t("User")})]})}),(0,r.jsx)(Ce,{children:u.map((p,C)=>(0,r.jsx)(Be,{row:p},`${String(p.ts)}-${String(C)}`))})]})}),d!==void 0&&(0,r.jsx)("div",{children:(0,r.jsx)(pe,{"data-testid":"lg-archive-more",disabled:h,onClick:S,size:"sm",variant:"outline",children:t(h?"Loading\u2026":"Load more")})})]})},"ze"),je=v(i=>{let e=(0,K.c)(11),{level:t,onToggle:n,selected:s}=i,o;e[0]!==t||e[1]!==n?(o=v(()=>{n(t)},"o"),e[0]=t,e[1]=n,e[2]=o):o=e[2];let c=o,f=s?"border-border bg-muted font-medium":"border-input text-muted-foreground",m;e[3]!==f?(m=j("rounded-md border px-2 py-1 text-xs",f),e[3]=f,e[4]=m):m=e[4];let d=`logs-level-${t}`,a;return e[5]!==t||e[6]!==c||e[7]!==s||e[8]!==m||e[9]!==d?(a=(0,r.jsx)("button",{"aria-pressed":s,className:m,"data-testid":d,onClick:c,type:"button",children:t}),e[5]=t,e[6]=c,e[7]=s,e[8]=m,e[9]=d,e[10]=a):a=e[10],a},"Ge"),Ve=v(i=>{let e=(0,K.c)(68),{levelFilter:t,onLogPathChange:n,onSearchChange:s,onTimeRangeChange:o,onToggleLevel:c,onToggleSummary:f,pathFilter:m,search:d,showSummary:a,timeRange:h}=i,l=z(),u;e[0]!==l?(u=l("Search messages"),e[0]=l,e[1]=u):u=e[1];let g;e[2]!==l?(g=l("search message"),e[2]=l,e[3]=g):g=e[3];let b;e[4]!==s||e[5]!==d||e[6]!==u||e[7]!==g?(b=(0,r.jsx)(D,{"aria-label":u,className:"h-8 w-48","data-testid":"lg-search",onChange:s,placeholder:g,value:d}),e[4]=s,e[5]=d,e[6]=u,e[7]=g,e[8]=b):b=e[8];let x;e[9]!==l?(x=l("Function path"),e[9]=l,e[10]=x):x=e[10];let w;e[11]!==l?(w=l("filter path"),e[11]=l,e[12]=w):w=e[12];let N;e[13]!==n||e[14]!==m||e[15]!==x||e[16]!==w?(N=(0,r.jsx)(D,{"aria-label":x,className:"h-8 w-40","data-testid":"logs-path-filter",onChange:n,placeholder:w,value:m}),e[13]=n,e[14]=m,e[15]=x,e[16]=w,e[17]=N):N=e[17];let y;e[18]!==l?(y=l("Level filter"),e[18]=l,e[19]=y):y=e[19];let T;e[20]!==t||e[21]!==c?(T=me.map(Q=>(0,r.jsx)(je,{level:Q,onToggle:c,selected:t.has(Q)},Q)),e[20]=t,e[21]=c,e[22]=T):T=e[22];let R;e[23]!==y||e[24]!==T?(R=(0,r.jsx)("div",{"aria-label":y,className:"inline-flex items-center gap-1","data-testid":"logs-level-filter",role:"group",children:T}),e[23]=y,e[24]=T,e[25]=R):R=e[25];let k;e[26]!==l?(k=l("Time range"),e[26]=l,e[27]=k):k=e[27];let L;e[28]!==l?(L=l("All time"),e[28]=l,e[29]=L):L=e[29];let S;e[30]!==L?(S=(0,r.jsx)("option",{value:"all",children:L}),e[30]=L,e[31]=S):S=e[31];let p;e[32]!==l?(p=l("Last 5m"),e[32]=l,e[33]=p):p=e[33];let C;e[34]!==p?(C=(0,r.jsx)("option",{value:"5m",children:p}),e[34]=p,e[35]=C):C=e[35];let q;e[36]!==l?(q=l("Last 15m"),e[36]=l,e[37]=q):q=e[37];let F;e[38]!==q?(F=(0,r.jsx)("option",{value:"15m",children:q}),e[38]=q,e[39]=F):F=e[39];let O;e[40]!==l?(O=l("Last hour"),e[40]=l,e[41]=O):O=e[41];let E;e[42]!==O?(E=(0,r.jsx)("option",{value:"1h",children:O}),e[42]=O,e[43]=E):E=e[43];let M;e[44]!==o||e[45]!==k||e[46]!==S||e[47]!==C||e[48]!==F||e[49]!==E||e[50]!==h?(M=(0,r.jsxs)("select",{"aria-label":k,className:"h-8 rounded-md border border-input bg-transparent px-2 text-sm shadow-xs focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none","data-testid":"logs-time-range",onChange:o,value:h,children:[S,C,F,E]}),e[44]=o,e[45]=k,e[46]=S,e[47]=C,e[48]=F,e[49]=E,e[50]=h,e[51]=M):M=e[51];let V=a?"border-border bg-muted font-medium":"border-input text-muted-foreground",_;e[52]!==V?(_=j("h-8 rounded-md border px-3 text-sm",V),e[52]=V,e[53]=_):_=e[53];let U;e[54]!==a||e[55]!==l?(U=l(a?"List":"Summary"),e[54]=a,e[55]=l,e[56]=U):U=e[56];let A;e[57]!==f||e[58]!==a||e[59]!==_||e[60]!==U?(A=(0,r.jsx)("button",{"aria-pressed":a,className:_,"data-testid":"logs-summary-toggle",onClick:f,type:"button",children:U}),e[57]=f,e[58]=a,e[59]=_,e[60]=U,e[61]=A):A=e[61];let $;return e[62]!==M||e[63]!==A||e[64]!==b||e[65]!==N||e[66]!==R?($=(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[b,N,R,M,A]}),e[62]=M,e[63]=A,e[64]=b,e[65]=N,e[66]=R,e[67]=$):$=e[67],$},"He"),Qe=v(i=>{let e=(0,K.c)(53),{onOutcomeChange:t,onPathChange:n,onTableChange:s,onUserChange:o,outcomeFilter:c,pathPrefix:f,tableFilter:m,userIdFilter:d}=i,a=z(),h;e[0]!==a?(h=a("Function path"),e[0]=a,e[1]=h):h=e[1];let l;e[2]!==a?(l=a("file:function"),e[2]=a,e[3]=l):l=e[3];let u;e[4]!==n||e[5]!==f||e[6]!==h||e[7]!==l?(u=(0,r.jsx)(D,{"aria-label":h,className:"h-8 w-44","data-testid":"lg-req-path",onChange:n,placeholder:l,value:f}),e[4]=n,e[5]=f,e[6]=h,e[7]=l,e[8]=u):u=e[8];let g;e[9]!==a?(g=a("User id"),e[9]=a,e[10]=g):g=e[10];let b;e[11]!==a?(b=a("userId"),e[11]=a,e[12]=b):b=e[12];let x;e[13]!==o||e[14]!==g||e[15]!==b||e[16]!==d?(x=(0,r.jsx)(D,{"aria-label":g,className:"h-8 w-32","data-testid":"lg-req-user",onChange:o,placeholder:b,value:d}),e[13]=o,e[14]=g,e[15]=b,e[16]=d,e[17]=x):x=e[17];let w;e[18]!==a?(w=a("Table touched"),e[18]=a,e[19]=w):w=e[19];let N;e[20]!==a?(N=a("table"),e[20]=a,e[21]=N):N=e[21];let y;e[22]!==s||e[23]!==w||e[24]!==N||e[25]!==m?(y=(0,r.jsx)(D,{"aria-label":w,className:"h-8 w-32","data-testid":"lg-req-table",onChange:s,placeholder:N,value:m}),e[22]=s,e[23]=w,e[24]=N,e[25]=m,e[26]=y):y=e[26];let T;e[27]!==a?(T=a("Outcome filter"),e[27]=a,e[28]=T):T=e[28];let R;e[29]!==a?(R=a("all"),e[29]=a,e[30]=R):R=e[30];let k;e[31]!==R?(k=(0,r.jsx)("option",{value:"all",children:R}),e[31]=R,e[32]=k):k=e[32];let L;e[33]!==a?(L=a("ok"),e[33]=a,e[34]=L):L=e[34];let S;e[35]!==L?(S=(0,r.jsx)("option",{value:"ok",children:L}),e[35]=L,e[36]=S):S=e[36];let p;e[37]!==a?(p=a("error"),e[37]=a,e[38]=p):p=e[38];let C;e[39]!==p?(C=(0,r.jsx)("option",{value:"error",children:p}),e[39]=p,e[40]=C):C=e[40];let q;e[41]!==t||e[42]!==c||e[43]!==T||e[44]!==k||e[45]!==S||e[46]!==C?(q=(0,r.jsxs)("select",{"aria-label":T,className:"h-8 rounded-md border border-input bg-transparent px-2 text-sm shadow-xs focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 focus-visible:outline-none","data-testid":"lg-req-outcome",onChange:t,value:c,children:[k,S,C]}),e[41]=t,e[42]=c,e[43]=T,e[44]=k,e[45]=S,e[46]=C,e[47]=q):q=e[47];let F;return e[48]!==q||e[49]!==u||e[50]!==x||e[51]!==y?(F=(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[u,x,y,q]}),e[48]=q,e[49]=u,e[50]=x,e[51]=y,e[52]=F):F=e[52],F},"We"),Fe=v(i=>{let e=(0,K.c)(7),{bucket:t}=i,n;e[0]!==t.key?(n=(0,r.jsx)("span",{className:"truncate text-muted-foreground",role:"gridcell",children:t.key}),e[0]=t.key,e[1]=n):n=e[1];let s;e[2]!==t.count?(s=(0,r.jsx)("span",{className:"shrink-0 tabular-nums",role:"gridcell",children:t.count}),e[2]=t.count,e[3]=s):s=e[3];let o;return e[4]!==n||e[5]!==s?(o=(0,r.jsxs)("div",{className:"flex items-center justify-between gap-4 px-3 py-1 font-mono text-xs","data-testid":"logs-summary-row",role:"row",children:[n,s]}),e[4]=n,e[5]=s,e[6]=o):o=e[6],o},"ve"),Ye=v(i=>{let e=(0,K.c)(31),{summary:t}=i,n=z(),s;e[0]!==t.total||e[1]!==n?(s=n("{count} entries",{count:t.total}),e[0]=t.total,e[1]=n,e[2]=s):s=e[2];let o;e[3]!==s?(o=(0,r.jsx)("p",{className:"text-xs text-muted-foreground","data-testid":"logs-summary-total",children:s}),e[3]=s,e[4]=o):o=e[4];let c;e[5]!==n?(c=n("By level"),e[5]=n,e[6]=c):c=e[6];let f;e[7]!==c?(f=(0,r.jsx)("h4",{className:"mb-1 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:c}),e[7]=c,e[8]=f):f=e[8];let m;e[9]!==t.byLevel?(m=t.byLevel.map(Ge),e[9]=t.byLevel,e[10]=m):m=e[10];let d;e[11]!==m?(d=(0,r.jsx)("div",{className:"overflow-hidden rounded-lg border border-border","data-testid":"logs-summary-levels",role:"grid",children:m}),e[11]=m,e[12]=d):d=e[12];let a;e[13]!==f||e[14]!==d?(a=(0,r.jsxs)("div",{children:[f,d]}),e[13]=f,e[14]=d,e[15]=a):a=e[15];let h;e[16]!==n?(h=n("By function"),e[16]=n,e[17]=h):h=e[17];let l;e[18]!==h?(l=(0,r.jsx)("h4",{className:"mb-1 font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:h}),e[18]=h,e[19]=l):l=e[19];let u;e[20]!==t.byPath?(u=t.byPath.map(He),e[20]=t.byPath,e[21]=u):u=e[21];let g;e[22]!==u?(g=(0,r.jsx)("div",{className:"overflow-hidden rounded-lg border border-border","data-testid":"logs-summary-paths",role:"grid",children:u}),e[22]=u,e[23]=g):g=e[23];let b;e[24]!==g||e[25]!==l?(b=(0,r.jsxs)("div",{children:[l,g]}),e[24]=g,e[25]=l,e[26]=b):b=e[26];let x;return e[27]!==b||e[28]!==o||e[29]!==a?(x=(0,r.jsxs)("div",{className:"flex flex-col gap-4 rounded-xl border border-border bg-card p-4 shadow-xs","data-testid":"logs-summary",children:[o,a,b]}),e[27]=b,e[28]=o,e[29]=a,e[30]=x):x=e[30],x},"Ye");function Ge(i){return(0,r.jsx)(Fe,{bucket:i},i.key)}v(Ge,"je");function He(i){return(0,r.jsx)(Fe,{bucket:i},i.key)}v(He,"Je");var Je=v(i=>{let e=(0,K.c)(46),{liveError:t,onShardKeyChange:n,onShowArchive:s,onShowErrors:o,onShowRequests:c,shardKey:f,view:m}=i,d=z(),a=m==="requests",h=m==="requests"?"bg-muted font-medium":"text-muted-foreground",l;e[0]!==h?(l=j("px-3 py-1 text-sm",h),e[0]=h,e[1]=l):l=e[1];let u;e[2]!==d?(u=d("Requests"),e[2]=d,e[3]=u):u=e[3];let g;e[4]!==c||e[5]!==a||e[6]!==l||e[7]!==u?(g=(0,r.jsx)("button",{"aria-selected":a,className:l,"data-testid":"lg-view-requests",onClick:c,role:"tab",type:"button",children:u}),e[4]=c,e[5]=a,e[6]=l,e[7]=u,e[8]=g):g=e[8];let b=m==="errors",x=m==="errors"?"bg-muted font-medium":"text-muted-foreground",w;e[9]!==x?(w=j("px-3 py-1 text-sm",x),e[9]=x,e[10]=w):w=e[10];let N;e[11]!==d?(N=d("Errors"),e[11]=d,e[12]=N):N=e[12];let y;e[13]!==o||e[14]!==b||e[15]!==w||e[16]!==N?(y=(0,r.jsx)("button",{"aria-selected":b,className:w,"data-testid":"lg-view-errors",onClick:o,role:"tab",type:"button",children:N}),e[13]=o,e[14]=b,e[15]=w,e[16]=N,e[17]=y):y=e[17];let T=m==="archive",R=m==="archive"?"bg-muted font-medium":"text-muted-foreground",k;e[18]!==R?(k=j("px-3 py-1 text-sm",R),e[18]=R,e[19]=k):k=e[19];let L;e[20]!==d?(L=d("Archive"),e[20]=d,e[21]=L):L=e[21];let S;e[22]!==s||e[23]!==T||e[24]!==k||e[25]!==L?(S=(0,r.jsx)("button",{"aria-selected":T,className:k,"data-testid":"lg-view-archive",onClick:s,role:"tab",type:"button",children:L}),e[22]=s,e[23]=T,e[24]=k,e[25]=L,e[26]=S):S=e[26];let p;e[27]!==y||e[28]!==S||e[29]!==g?(p=(0,r.jsxs)("div",{className:"inline-flex overflow-hidden rounded-lg border border-border",role:"tablist",children:[g,y,S]}),e[27]=y,e[28]=S,e[29]=g,e[30]=p):p=e[30];let C;e[31]!==n||e[32]!==f?(C=(0,r.jsx)(be,{onChange:n,testId:"lg-shard-input",value:f}),e[31]=n,e[32]=f,e[33]=C):C=e[33];let q;e[34]!==t||e[35]!==m?(q=m!=="archive"&&(0,r.jsx)(Le,{message:t,prefix:"lg"}),e[34]=t,e[35]=m,e[36]=q):q=e[36];let F;e[37]!==d?(F=d("Open in Cloudflare"),e[37]=d,e[38]=F):F=e[38];let O;e[39]!==F?(O=(0,r.jsx)("a",{className:"text-sm text-primary underline-offset-4 hover:underline","data-testid":"lg-cf-link",href:de,rel:"noreferrer",target:"_blank",children:F}),e[39]=F,e[40]=O):O=e[40];let E;return e[41]!==p||e[42]!==C||e[43]!==q||e[44]!==O?(E=(0,r.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[p,C,q,O]}),e[41]=p,e[42]=C,e[43]=q,e[44]=O,e[45]=E):E=e[45],E},"Xe"),ue=400,Xe=36,Ze={height:ue,overflow:"auto"},Oe={left:0,position:"absolute",top:0,width:"100%"},et={error:"destructive",ok:"secondary"},Ee=v(i=>{let e=(0,K.c)(6),{onOpenTrace:t,traceId:n}=i,s=z(),o;e[0]!==t||e[1]!==s||e[2]!==n?(o=n===void 0?null:(0,r.jsx)("button",{className:"text-primary underline-offset-2 hover:underline","data-testid":"lg-trace-link",onClick:v(()=>{t(n)},"onClick"),type:"button",children:s("Trace")}),e[0]=t,e[1]=s,e[2]=n,e[3]=o):o=e[3];let c;return e[4]!==o?(c=(0,r.jsx)("span",{className:"w-16 shrink-0 text-right",role:"gridcell",children:o}),e[4]=o,e[5]=c):c=e[5],c},"xe"),tt=v(i=>{let e=(0,K.c)(13),{entry:t,index:n,measureRef:s,onOpenTrace:o,start:c}=i,f=`translateY(${String(c)}px)`,m;e[0]!==f?(m={...Oe,transform:f},e[0]=f,e[1]=m):m=e[1];let d=m,a;e[2]!==t?(a=(0,r.jsx)(Re,{entry:t}),e[2]=t,e[3]=a):a=e[3];let h;e[4]!==t.traceId||e[5]!==o?(h=(0,r.jsx)(Ee,{onOpenTrace:o,traceId:t.traceId}),e[4]=t.traceId,e[5]=o,e[6]=h):h=e[6];let l;return e[7]!==n||e[8]!==s||e[9]!==d||e[10]!==a||e[11]!==h?(l=(0,r.jsxs)("div",{className:"flex items-center border-b border-border px-3 py-1.5 font-mono text-xs hover:bg-muted/50","data-index":n,"data-testid":"lg-row",ref:s,role:"row",style:d,children:[a,h]}),e[7]=n,e[8]=s,e[9]=d,e[10]=a,e[11]=h,e[12]=l):l=e[12],l},"rt"),Ie=v(i=>i.length===0?"\u2014":i.join(", "),"ce"),rt=v(i=>{let e=(0,K.c)(41),{entry:t,index:n,measureRef:s,onOpenTrace:o,start:c}=i,f=`translateY(${String(c)}px)`,m;e[0]!==f?(m={...Oe,transform:f},e[0]=f,e[1]=m):m=e[1];let d=m,a;e[2]!==t.ts?(a=new Date(t.ts).toLocaleString(),e[2]=t.ts,e[3]=a):a=e[3];let h;e[4]!==a?(h=(0,r.jsx)("span",{className:"w-40 shrink-0 tabular-nums text-muted-foreground",role:"gridcell",children:a}),e[4]=a,e[5]=h):h=e[5];let l=et[t.outcome],u;e[6]!==t.outcome||e[7]!==l?(u=(0,r.jsx)("span",{className:"w-16 shrink-0",role:"gridcell",children:(0,r.jsx)(re,{variant:l,children:t.outcome})}),e[6]=t.outcome,e[7]=l,e[8]=u):u=e[8];let g;e[9]!==t.functionPath?(g=(0,r.jsx)("span",{className:"w-44 shrink-0 truncate",role:"gridcell",title:t.functionPath,children:t.functionPath}),e[9]=t.functionPath,e[10]=g):g=e[10];let b=t.shardKey??"\u2014",x;e[11]!==b?(x=(0,r.jsx)("span",{className:"w-24 shrink-0 truncate text-muted-foreground",role:"gridcell",children:b}),e[11]=b,e[12]=x):x=e[12];let w=t.userId??"\u2014",N;e[13]!==w?(N=(0,r.jsx)("span",{className:"w-24 shrink-0 truncate text-muted-foreground",role:"gridcell",children:w}),e[13]=w,e[14]=N):N=e[14];let y;e[15]!==t.durationMs?(y=Math.round(t.durationMs),e[15]=t.durationMs,e[16]=y):y=e[16];let T=`${String(y)}ms`,R;e[17]!==T?(R=(0,r.jsx)("span",{className:"w-16 shrink-0 tabular-nums text-muted-foreground",role:"gridcell",children:T}),e[17]=T,e[18]=R):R=e[18];let k;e[19]!==t.errorMessage||e[20]!==t.outcome||e[21]!==t.tablesRead||e[22]!==t.tablesWritten?(k=t.outcome==="error"&&t.errorMessage!==void 0?t.errorMessage:`r:${Ie(t.tablesRead)} \xB7 w:${Ie(t.tablesWritten)}`,e[19]=t.errorMessage,e[20]=t.outcome,e[21]=t.tablesRead,e[22]=t.tablesWritten,e[23]=k):k=e[23];let L;e[24]!==k?(L=(0,r.jsx)("span",{className:"flex-1 truncate text-muted-foreground",role:"gridcell",children:k}),e[24]=k,e[25]=L):L=e[25];let S;e[26]!==t.traceId||e[27]!==o?(S=(0,r.jsx)(Ee,{onOpenTrace:o,traceId:t.traceId}),e[26]=t.traceId,e[27]=o,e[28]=S):S=e[28];let p;return e[29]!==n||e[30]!==s||e[31]!==d||e[32]!==N||e[33]!==R||e[34]!==L||e[35]!==S||e[36]!==h||e[37]!==u||e[38]!==g||e[39]!==x?(p=(0,r.jsxs)("div",{className:"flex items-center border-b border-border px-3 py-1.5 font-mono text-xs hover:bg-muted/50","data-index":n,"data-testid":"lg-req-row",ref:s,role:"row",style:d,children:[h,u,g,x,N,R,L,S]}),e[29]=n,e[30]=s,e[31]=d,e[32]=N,e[33]=R,e[34]=L,e[35]=S,e[36]=h,e[37]=u,e[38]=g,e[39]=x,e[40]=p):p=e[40],p},"st"),qe=v(i=>{let{entries:e}=i??{};return Array.isArray(e)?e:[]},"de"),at=v(i=>{let e={};return i.functionPathPrefix.trim()!==""&&(e.functionPathPrefix=i.functionPathPrefix.trim()),i.userId.trim()!==""&&(e.userId=i.userId.trim()),i.tableTouched.trim()!==""&&(e.tableTouched=i.tableTouched.trim()),(i.outcome==="ok"||i.outcome==="error")&&(e.outcome=i.outcome),e},"lt"),lt={"5m":300*1e3,"15m":900*1e3,"1h":3600*1e3},ot=v((i,e)=>{let t=e.search.trim().toLowerCase(),n=e.path.trim().toLowerCase(),s=e.range==="all"?Number.NEGATIVE_INFINITY:e.now-lt[e.range];return i.filter(o=>e.levels.size>0&&!e.levels.has(o.level)||o.timestamp<s||n!==""&&!(o.functionPath??"").toLowerCase().includes(n)?!1:t===""||o.message.toLowerCase().includes(t)||ce(o.fields).toLowerCase().includes(t))},"at"),nt="\u2014",st=v(i=>{let e=new Map,t=new Map;for(let o of i){e.set(o.level,(e.get(o.level)??0)+1);let c=o.functionPath??nt;t.set(c,(t.get(c)??0)+1)}let n=me.filter(o=>e.has(o)).map(o=>({count:e.get(o)??0,key:o})),s=[...t.entries()].map(([o,c])=>({count:c,key:o})).toSorted((o,c)=>c.count===o.count?o.key.localeCompare(c.key):c.count-o.count);return{byLevel:n,byPath:s,total:i.length}},"it"),qt=v(({initialShardKey:i})=>{let e=z(),[t,n]=(0,I.useState)("requests"),{queryShardKey:s,setShardKey:o,shardKey:c}=xe(i),[f,m]=(0,I.useState)(""),[d,a]=(0,I.useState)(()=>new Set),[h,l]=(0,I.useState)(""),[u,g]=(0,I.useState)("all"),[b,x]=(0,I.useState)(!1),[w,N]=(0,I.useState)(""),[y,T]=(0,I.useState)(""),[R,k]=(0,I.useState)(""),[L,S]=(0,I.useState)("all"),p=at({functionPathPrefix:w,outcome:L,tableTouched:R,userId:y}),C=oe(ne.getRequestLog,p,{enabled:t==="requests",live:!0,shardKey:s}),q=oe(ne.getLogs,{},{enabled:t==="errors",live:!0,shardKey:s}),F=t==="requests"?C:q,{error:O,errorSource:E,isLoading:M,liveError:V}=F,_=Te(s),U=qe(q.data),A=qe(C.data);(0,I.useEffect)(()=>{F.data!==void 0&&ve(s)},[F.data,s]);let $=ot(U,{levels:d,now:Date.now(),path:h,range:u,search:f}),Q=st($),X=t==="requests"?A.length:$.length,Z=t==="errors"&&b,Y=(0,I.useMemo)(()=>O!==null?"error":X===0?M?Z?"summary":"list":"empty":Z?"summary":"list",[X,M,O,Z]),he=(0,I.useRef)(null),G=ke({count:X,estimateSize:v(()=>Xe,"estimateSize"),getScrollElement:v(()=>he.current,"getScrollElement"),initialRect:{height:ue,width:800},observeElementRect:v((P,ee)=>Se(P,ee,ue),"observeElementRect"),overscan:8}),Ke=G.getVirtualItems(),Me={height:G.getTotalSize(),position:"relative",width:"100%"};return(0,r.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-logs",children:[(0,r.jsx)(Je,{liveError:V,onShardKeyChange:o,onShowArchive:v(()=>{n("archive"),x(!1)},"onShowArchive"),onShowErrors:v(()=>{n("errors"),x(!1)},"onShowErrors"),onShowRequests:v(()=>{n("requests"),x(!1)},"onShowRequests"),shardKey:c,view:t}),t==="errors"&&(0,r.jsx)(Ve,{levelFilter:d,onLogPathChange:v(P=>{l(P.target.value)},"onLogPathChange"),onSearchChange:v(P=>{m(P.target.value)},"onSearchChange"),onTimeRangeChange:v(P=>{g(P.target.value)},"onTimeRangeChange"),onToggleLevel:v(P=>{a(ee=>{let H=new Set(ee);return H.has(P)?H.delete(P):H.add(P),H})},"onToggleLevel"),onToggleSummary:v(()=>{x(P=>!P)},"onToggleSummary"),pathFilter:h,search:f,showSummary:b,timeRange:u}),t==="requests"&&(0,r.jsx)(Qe,{onOutcomeChange:v(P=>{S(P.target.value)},"onOutcomeChange"),onPathChange:v(P=>{N(P.target.value)},"onPathChange"),onTableChange:v(P=>{k(P.target.value)},"onTableChange"),onUserChange:v(P=>{T(P.target.value)},"onUserChange"),outcomeFilter:L,pathPrefix:w,tableFilter:R,userIdFilter:y}),t==="archive"?(0,r.jsx)(We,{shardKey:s}):(0,r.jsxs)(r.Fragment,{children:[Y==="error"&&(0,r.jsx)(ye,{error:E,testId:"lg-error"}),Y==="empty"&&(0,r.jsx)(J,{description:e("Function and request logs for this shard show up here as your app handles traffic."),icon:(0,r.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,r.jsx)("path",{d:"M4 5h16M4 12h16M4 19h10"})}),testId:"lg-empty",title:e("No logs.")}),Y==="summary"&&(0,r.jsx)(Ye,{summary:Q}),Y==="list"&&(0,r.jsx)("div",{className:"rounded-xl border border-border shadow-xs","data-testid":"lg-scroll",ref:he,style:Ze,children:(0,r.jsx)("div",{"aria-label":e("Recent logs"),"data-testid":"lg-table",role:"grid",style:Me,children:Ke.map(P=>t==="requests"?(0,r.jsx)(rt,{entry:A[P.index],index:P.index,measureRef:G.measureElement,onOpenTrace:_,start:P.start},P.key):(0,r.jsx)(tt,{entry:$[P.index],index:P.index,measureRef:G.measureElement,onOpenTrace:_,start:P.start},P.key))})})]})]})},"Wt");export{qt as LogsPanel,ot as filterLogs,st as summarizeLogs};
|
|
@@ -0,0 +1,9 @@
|
|
|
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 +1 @@
|
|
|
1
|
-
import{W as R}from"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import{a as B}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as S}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as q}from"./chunk-
|
|
1
|
+
import{W as R}from"./chunk-PLHA3OWK.js";import"./chunk-4L4WTGN5.js";import{a as B}from"./chunk-55754F6H.js";import"./chunk-IS6LVJ6L.js";import"./chunk-AAVLPU5Q.js";import{b as S}from"./chunk-FEWMAPNI.js";import"./chunk-225VJ77I.js";import{a as q}from"./chunk-TSNKMJKC.js";import"./chunk-ULIQFBZU.js";import"./chunk-S6ZFBF3S.js";import"./chunk-35DM4JJG.js";import{a as U}from"./chunk-4ZEL6BYL.js";import{c as O}from"./chunk-27ILKCWI.js";import"./chunk-NZKXQEZ5.js";import"./chunk-FSRSK4LY.js";import"./chunk-5ICUJ4IA.js";import{a as D}from"./chunk-FKVZRPV5.js";import{a as G,b as J,c as K,d as F,e as s,f as o}from"./chunk-HEAQVSNS.js";import{a as V,e as W}from"./chunk-WUWBZPUK.js";import{d as P,t as H}from"./chunk-PTZD7RUZ.js";import{a as n,d as j,e as re,f as ae,g as ie}from"./chunk-YKXDMIHQ.js";var X=j(ae(),1),M=j(re(),1);var t=j(ie(),1);var ne=n(e=>e==="ok"?"success":e==="failed"?"destructive":e==="expired"?"warning":"secondary","te"),Q=n(e=>e.endpoint??e.id,"M"),ve=n(()=>{let e=(0,X.c)(38),r=P(),[i,Y]=(0,M.useState)("all"),[l,Z]=(0,M.useState)(""),g;e[0]===Symbol.for("react.memo_cache_sentinel")?(g={},e[0]=g):g=e[0];let{data:I,error:d,errorSource:x,isLoading:_,refetch:v}=O(U.listPushSubscriptions,g),N;if(e[1]!==I?.subscriptions||e[2]!==d||e[3]!==x||e[4]!==_||e[5]!==i||e[6]!==v||e[7]!==l||e[8]!==r){let L=I?.subscriptions??[],T=l.trim().toLowerCase(),A=L.filter(a=>i!=="all"&&a.kind!==i?!1:T===""?!0:`${Q(a)} ${a.userId??""}`.toLowerCase().includes(T)),b;e[10]===Symbol.for("react.memo_cache_sentinel")?(b=n(a=>{Z(a.target.value)},"w"),e[10]=b):b=e[10];let ee=b,w;e[11]!==v?(w=n(()=>{v()},"y"),e[11]=v,e[12]=w):w=e[12];let E=w,k;e[13]===Symbol.for("react.memo_cache_sentinel")?(k=["all","web-push","fcm"],e[13]=k):k=e[13];let te=k,c;e[14]!==i||e[15]!==r?(c=(0,t.jsx)("div",{className:"flex items-center gap-1","data-testid":"nt-kind-filter",role:"tablist",children:te.map(a=>(0,t.jsx)(B,{"aria-selected":i===a,"data-testid":`nt-kind-${a}`,onClick:n(()=>{Y(a)},"onClick"),role:"tab",size:"sm",type:"button",variant:i===a?"secondary":"ghost",children:a==="all"?r("All"):a},a))}),e[14]=i,e[15]=r,e[16]=c):c=e[16];let m;e[17]!==r?(m=r("Filter devices"),e[17]=r,e[18]=m):m=e[18];let h;e[19]!==r?(h=r("filter endpoint, user"),e[19]=r,e[20]=h):h=e[20];let u;e[21]!==l||e[22]!==m||e[23]!==h?(u=(0,t.jsx)(R,{"aria-label":m,className:"h-8 w-56","data-testid":"nt-search",onChange:ee,placeholder:h,value:l}),e[21]=l,e[22]=m,e[23]=h,e[24]=u):u=e[24];let f;e[25]!==r?(f=r("Refresh"),e[25]=r,e[26]=f):f=e[26];let p;e[27]!==E||e[28]!==f?(p=(0,t.jsx)(B,{className:"ml-auto","data-testid":"nt-refresh",onClick:E,size:"sm",type:"button",variant:"outline",children:f}),e[27]=E,e[28]=f,e[29]=p):p=e[29];let $=L.length>0&&(0,t.jsx)(S,{"data-testid":"nt-count",variant:"secondary",children:r("{count} devices",{count:L.length})}),y;e[30]!==p||e[31]!==$||e[32]!==c||e[33]!==u?(y=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[c,u,p,$]}),e[30]=p,e[31]=$,e[32]=c,e[33]=u,e[34]=y):y=e[34];let C;e[35]!==d||e[36]!==x?(C=d!==null&&(0,t.jsx)(q,{error:x,testId:"nt-error"}),e[35]=d,e[36]=x,e[37]=C):C=e[37],N=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"lunora-notifications",children:[y,C,d===null&&!_&&A.length===0&&(0,t.jsx)(D,{description:r("Registered Web Push / FCM devices appear here. Configure lunora/notify.ts with defineNotify({ store }) and register a device with ctx.push.register(...)."),icon:(0,t.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,t.jsx)("path",{d:"M15 17h5l-1.4-1.4A2 2 0 0 1 18 14.2V11a6 6 0 0 0-4-5.7V5a2 2 0 1 0-4 0v.3A6 6 0 0 0 6 11v3.2a2 2 0 0 1-.6 1.4L4 17h5m6 0v1a3 3 0 1 1-6 0v-1m6 0H9"})}),testId:"nt-empty",title:r("No registered devices.")}),A.length>0&&(0,t.jsx)(V,{className:"overflow-hidden py-0",children:(0,t.jsx)(W,{className:"max-h-[30rem] overflow-auto px-0",children:(0,t.jsxs)(G,{"data-testid":"nt-table",children:[(0,t.jsx)(J,{children:(0,t.jsxs)(F,{children:[(0,t.jsx)(s,{children:r("kind")}),(0,t.jsx)(s,{children:r("endpoint")}),(0,t.jsx)(s,{children:r("user")}),(0,t.jsx)(s,{children:r("last seen")}),(0,t.jsx)(s,{children:r("status")}),(0,t.jsx)(s,{children:r("error")})]})}),(0,t.jsx)(K,{children:A.map(a=>{let z=Q(a);return(0,t.jsxs)(F,{"data-testid":"nt-row",children:[(0,t.jsx)(o,{children:(0,t.jsx)(S,{variant:"outline",children:a.kind})}),(0,t.jsx)(o,{className:"max-w-[28ch] truncate font-mono text-xs",title:z,children:z}),(0,t.jsx)(o,{className:"max-w-[16ch] truncate font-mono text-xs",children:a.userId??(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})}),(0,t.jsx)(o,{className:"text-muted-foreground tabular-nums",children:H(a.lastSeenAt,"\u2014")}),(0,t.jsx)(o,{children:(0,t.jsx)(S,{"data-testid":`nt-status-${a.id}`,variant:ne(a.lastStatus),children:a.lastStatus??r("n/a")})}),(0,t.jsx)(o,{className:"max-w-[28ch] truncate font-mono text-xs text-muted-foreground",title:a.lastError??void 0,children:a.lastError??(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"})})]},a.id)})})]})})})]}),e[1]=I?.subscriptions,e[2]=d,e[3]=x,e[4]=_,e[5]=i,e[6]=v,e[7]=l,e[8]=r,e[9]=N}else N=e[9];return N},"ge");export{ve as default};
|