@lunora/studio 1.0.0-alpha.104 → 1.0.0-alpha.106

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/dist/index.d.ts +2 -2
  2. package/dist/index.js +1 -1
  3. package/dist/mount.js +1 -1
  4. package/dist/packem_chunks/LogsPanel.js +1 -1
  5. package/dist/packem_chunks/MetricsPanel.js +1 -1
  6. package/dist/packem_chunks/agents-panel.js +1 -1
  7. package/dist/packem_chunks/evals-panel.js +1 -0
  8. package/dist/packem_chunks/kv-browser.js +1 -1
  9. package/dist/packem_chunks/traces-panel.js +1 -1
  10. package/dist/packem_shared/{Studio-DG_n-8Pc.js → Studio-CD66AkL1.js} +1 -1
  11. package/dist/packem_shared/{StudioApp-bavavhpe.js → StudioApp-0Vaayv2I.js} +1 -1
  12. package/dist/packem_shared/log-fields-CoL3hsIQ.js +1 -0
  13. package/dist/packem_shared/log-line-BDI826X-.js +1 -0
  14. package/dist/packem_shared/studio-CUXq5VSB.js +2 -0
  15. package/dist/packem_shared/trace-handoff-Dw7mwjxu.js +1 -0
  16. package/dist/packem_shared/{use-open-trace-D9XDDHHS.js → use-open-trace-CniEgUdp.js} +1 -1
  17. package/dist/standalone/{chunk-VA5RUELS.js → chunk-25IDU7IW.js} +1 -1
  18. package/dist/standalone/{chunk-WVXS24SB.js → chunk-2ZG23BA5.js} +1 -1
  19. package/dist/standalone/{chunk-BR5GIQWK.js → chunk-5DVJR52Z.js} +1 -1
  20. package/dist/standalone/{chunk-P6U7JNSA.js → chunk-5MJ3G4DY.js} +1 -1
  21. package/dist/standalone/{chunk-C2W6YSI7.js → chunk-5RIKPDDA.js} +1 -1
  22. package/dist/standalone/chunk-5UY7MLRC.js +1 -0
  23. package/dist/standalone/{chunk-5BKFMQKO.js → chunk-63D4ABMW.js} +1 -1
  24. package/dist/standalone/chunk-6KWKX3RH.js +1 -0
  25. package/dist/standalone/{chunk-5VYZCZNH.js → chunk-6QBOXH2I.js} +1 -1
  26. package/dist/standalone/{chunk-WE4LGWB4.js → chunk-6WB63KTN.js} +1 -1
  27. package/dist/standalone/chunk-7CZI2HNL.js +1 -0
  28. package/dist/standalone/{chunk-YPQISHBM.js → chunk-7P7NURTD.js} +1 -1
  29. package/dist/standalone/{chunk-KMGVTPH2.js → chunk-7QOXFLZB.js} +1 -1
  30. package/dist/standalone/{chunk-WWOB5XZT.js → chunk-7UP7OQJG.js} +1 -1
  31. package/dist/standalone/chunk-AXQU7ULF.js +1 -0
  32. package/dist/standalone/chunk-BCOT3QRZ.js +1 -0
  33. package/dist/standalone/chunk-BDHAGUAY.js +11 -0
  34. package/dist/standalone/{chunk-AI5UNHBF.js → chunk-BG5ELOW6.js} +1 -1
  35. package/dist/standalone/{chunk-FCSU7IHH.js → chunk-BXJPPINU.js} +1 -1
  36. package/dist/standalone/{chunk-3JJIZ5GZ.js → chunk-BZDIRP7L.js} +1 -1
  37. package/dist/standalone/{chunk-LMZCWLYL.js → chunk-C3YACIEE.js} +1 -1
  38. package/dist/standalone/{chunk-ZBVGZ4YA.js → chunk-CAOA5AM4.js} +1 -1
  39. package/dist/standalone/{chunk-XOIXFWZS.js → chunk-CKG2DTZ2.js} +1 -1
  40. package/dist/standalone/{chunk-WEOEKMJN.js → chunk-DNEIBTLL.js} +1 -1
  41. package/dist/standalone/{chunk-ZKDSO2VL.js → chunk-DRR3KV5L.js} +1 -1
  42. package/dist/standalone/{chunk-K5463KGW.js → chunk-EF5J67J3.js} +1 -1
  43. package/dist/standalone/chunk-EJWTF334.js +1 -0
  44. package/dist/standalone/{chunk-NLANS7IB.js → chunk-EP4JQH5X.js} +1 -1
  45. package/dist/standalone/{chunk-OXGSORBK.js → chunk-EXL35M7T.js} +1 -1
  46. package/dist/standalone/{chunk-LFOT3KUL.js → chunk-F2I4JLFR.js} +1 -1
  47. package/dist/standalone/{chunk-OJDJMESX.js → chunk-F3J6ER2V.js} +1 -1
  48. package/dist/standalone/{chunk-KMT6UDR7.js → chunk-FZ2N52BV.js} +1 -1
  49. package/dist/standalone/{chunk-GCIAXZBG.js → chunk-HBSEWNIR.js} +1 -1
  50. package/dist/standalone/{chunk-EVPGUJH7.js → chunk-HFRJMPXJ.js} +1 -1
  51. package/dist/standalone/{chunk-ILQLRPP6.js → chunk-HLENOQDN.js} +1 -1
  52. package/dist/standalone/{chunk-GPXYZOOF.js → chunk-HUF7RMS3.js} +1 -1
  53. package/dist/standalone/{chunk-KHZFULUH.js → chunk-HX7IXD7I.js} +1 -1
  54. package/dist/standalone/{chunk-44W6IDID.js → chunk-IBPWTHHW.js} +1 -1
  55. package/dist/standalone/chunk-KUVMORDQ.js +1 -0
  56. package/dist/standalone/{chunk-REJA4WG5.js → chunk-KZRWBSYQ.js} +1 -1
  57. package/dist/standalone/{chunk-6VTX32BC.js → chunk-LWE6NWQX.js} +1 -1
  58. package/dist/standalone/{chunk-LZFOZFYW.js → chunk-OBMNLQWG.js} +1 -1
  59. package/dist/standalone/{chunk-2POO335F.js → chunk-OENUM3OW.js} +1 -1
  60. package/dist/standalone/{chunk-QM4IZJHK.js → chunk-OKQ3NJOW.js} +1 -1
  61. package/dist/standalone/chunk-QWGT25SE.js +1 -0
  62. package/dist/standalone/{chunk-TWF72RNA.js → chunk-RFSPHFKM.js} +1 -1
  63. package/dist/standalone/chunk-RJS7UD5U.js +1 -0
  64. package/dist/standalone/{chunk-RPGUPO5I.js → chunk-S23KCFVU.js} +1 -1
  65. package/dist/standalone/{chunk-EAGPIRHK.js → chunk-S4665UG5.js} +1 -1
  66. package/dist/standalone/chunk-SY6ANTKE.js +1 -0
  67. package/dist/standalone/{chunk-76XT6OKR.js → chunk-TCV7MMYR.js} +1 -1
  68. package/dist/standalone/{chunk-GY66QQZJ.js → chunk-UFESYXCE.js} +1 -1
  69. package/dist/standalone/{chunk-EP5VOTNC.js → chunk-UKI2ZYB2.js} +1 -1
  70. package/dist/standalone/{chunk-42JIUZ5A.js → chunk-UTK6JUTY.js} +1 -1
  71. package/dist/standalone/{chunk-AAU2LQP2.js → chunk-VIJLMIC3.js} +1 -1
  72. package/dist/standalone/chunk-VOY5EALQ.js +1 -0
  73. package/dist/standalone/{chunk-56Q3NCCQ.js → chunk-VR3OBMGZ.js} +1 -1
  74. package/dist/standalone/{chunk-LFYM72CD.js → chunk-WJCKVELA.js} +1 -1
  75. package/dist/standalone/{chunk-Q5LK5ZBG.js → chunk-WZ65AZKA.js} +1 -1
  76. package/dist/standalone/{chunk-L6ZL7C6I.js → chunk-XEGWCG5S.js} +1 -1
  77. package/dist/standalone/{chunk-VITTPKH5.js → chunk-XFGE43TZ.js} +1 -1
  78. package/dist/standalone/{chunk-DUFBHFX6.js → chunk-XNSCEAHM.js} +1 -1
  79. package/dist/standalone/{chunk-WXALMQCU.js → chunk-XVD7HWY7.js} +1 -1
  80. package/dist/standalone/chunk-XYV7TMYI.js +1 -0
  81. package/dist/standalone/{chunk-FSPXSK4F.js → chunk-YJ25NVR2.js} +1 -1
  82. package/dist/standalone/{chunk-ZU6JSCBE.js → chunk-Z2IF3TEX.js} +1 -1
  83. package/dist/standalone/{chunk-6ZVSFYWY.js → chunk-ZCNMXKF2.js} +2 -2
  84. package/dist/standalone/studio.js +1 -1
  85. package/package.json +6 -6
  86. package/dist/packem_shared/log-line-CmtmbZNE.js +0 -1
  87. package/dist/packem_shared/studio-C9Qvg13j.js +0 -2
  88. package/dist/packem_shared/trace-handoff-D7j9TjUT.js +0 -1
  89. package/dist/standalone/chunk-CJQ2534J.js +0 -1
  90. package/dist/standalone/chunk-IN6NPKXV.js +0 -1
  91. package/dist/standalone/chunk-J6IUJLIJ.js +0 -1
  92. package/dist/standalone/chunk-K2E4OECF.js +0 -1
  93. package/dist/standalone/chunk-MX46UN6V.js +0 -1
  94. package/dist/standalone/chunk-WNCBCYI4.js +0 -1
  95. package/dist/standalone/chunk-WVU7GHTG.js +0 -11
  96. package/dist/standalone/chunk-X3W5GATZ.js +0 -1
  97. package/dist/standalone/chunk-ZD3CL42S.js +0 -1
  98. package/dist/standalone/chunk-ZMNCF2DE.js +0 -1
@@ -0,0 +1 @@
1
+ import{a as o}from"./chunk-3XIESWL4.js";var h=o(e=>{let t=0,n=0,r=0,a=0,l=0,i=0,c=0;for(let{metrics:s}of e){if(s===null){l+=1;continue}a+=1,t+=s.requests,n+=s.errors,r+=s.databaseSize??0,s.cache!==null&&(i+=s.cache.hits,c+=s.cache.hits+s.cache.misses)}return{failed:l,hitRate:c===0?null:i/c,reachable:a,totalDatabaseSize:r,totalErrors:n,totalRequests:t}},"u"),f=o((e,t)=>{let n=new Set,r=[];for(let a of["",e.trim(),...t])n.has(a)||(n.add(a),r.push(a));return r},"h"),u=o((e,t)=>{if(e.length===0)return 0;if(e.sort((r,a)=>r-a),t<=0)return e[0]??0;if(t>=100)return e.at(-1)??0;let n=Math.ceil(t/100*e.length)-1;return e[n]??0},"i"),p=o(e=>{let t=e.functions;if(!t||t.length===0)return{p90:0,p95:0};let n=1e3,r=[];for(let a of t){if(a.calls<=0)continue;let l=a.totalDurationMs/a.calls,i=Math.min(a.calls,n);for(let c=0;c<i;c+=1)r.push(l)}return r.length===0?{p90:0,p95:0}:{p90:u([...r],90),p95:u([...r],95)}},"f");var g=o(e=>e.map(t=>({...t,avgDurationMs:t.execCount>0?t.totalDurationMs/t.execCount:0})),"g");export{h as a,f as b,p as c,g as d};
@@ -1 +1 @@
1
- import{b as h}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{b as A}from"./chunk-KMT6UDR7.js";import{f as k}from"./chunk-WVU7GHTG.js";import"./chunk-XBDKZZ67.js";import{a as y,e as S}from"./chunk-WQH3LT2P.js";import{d as I}from"./chunk-IUYFXK4X.js";import"./chunk-BR5GIQWK.js";import{a as u,e as w,g as j,h as z}from"./chunk-3XIESWL4.js";var N=w(j(),1);var a=w(z(),1);var P=[{key:"accounts",label:"Accounts"},{key:"admin",label:"Admin"},{key:"organization",label:"Organizations"},{key:"passkey",label:"Passkeys"},{key:"twoFactor",label:"Two-factor"}],v=u(e=>{if(e===void 0)return"\u2014";let i=[[86400,"d"],[3600,"h"],[60,"m"]];for(let[t,d]of i)if(e>=t&&e%t===0)return`${String(e/t)}${d}`;return`${String(e)}s`},"v"),g=u(e=>{let i=(0,N.c)(8),{children:t,heading:d,testId:r}=e,l;i[0]!==d?(l=(0,a.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,a.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:d})}),i[0]=d,i[1]=l):l=i[1];let s;i[2]!==t?(s=(0,a.jsx)(S,{className:"p-3",children:t}),i[2]=t,i[3]=s):s=i[3];let c;return i[4]!==l||i[5]!==s||i[6]!==r?(c=(0,a.jsxs)(y,{className:"gap-0 py-0","data-testid":r,children:[l,s]}),i[4]=l,i[5]=s,i[6]=r,i[7]=c):c=i[7],c},"h"),o=u(e=>{let i=(0,N.c)(7),{label:t,value:d}=e,r;i[0]!==t?(r=(0,a.jsx)("span",{className:"text-sm",children:t}),i[0]=t,i[1]=r):r=i[1];let l;i[2]!==d?(l=(0,a.jsx)("span",{className:"text-sm text-muted-foreground tabular-nums",children:d}),i[2]=d,i[3]=l):l=i[3];let s;return i[4]!==r||i[5]!==l?(s=(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-xl border border-border bg-card p-2 shadow-xs",children:[r,l]}),i[4]=r,i[5]=l,i[6]=s):s=i[6],s},"c"),T=u(()=>{let e=(0,N.c)(20),i=k(),t=I(),d;e[0]===Symbol.for("react.memo_cache_sentinel")?(d=["lunora-auth-config"],e[0]=d):d=e[0];let r;e[1]!==i?(r=u(()=>i.getAuthConfig(),"s"),e[1]=i,e[2]=r):r=e[2];let{data:l,error:s}=A(d,r),c;e[3]!==t?(c=u(n=>(0,a.jsx)(h,{variant:n?"success":"outline",children:t(n?"Enabled":"Disabled")}),"u"),e[3]=t,e[4]=c):c=e[4];let m=c,p;e[5]!==s?(p=s!==null&&(0,a.jsx)("p",{className:"px-4 py-8 text-center text-sm text-destructive","data-testid":"auth-config-error",role:"alert",children:s}),e[5]=s,e[6]=p):p=e[6];let f;e[7]!==l||e[8]!==s||e[9]!==t?(f=s===null&&l===void 0&&(0,a.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"auth-config-loading",children:t("Loading auth configuration\u2026")}),e[7]=l,e[8]=s,e[9]=t,e[10]=f):f=e[10];let x;e[11]!==l||e[12]!==s||e[13]!==m||e[14]!==t?(x=s===null&&l!==void 0&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(g,{heading:t("Enabled capabilities"),testId:"auth-config-capabilities",children:(0,a.jsx)("ul",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:P.map(n=>{let $=l.capabilities[n.key];return(0,a.jsxs)("li",{className:"flex items-center justify-between gap-2 rounded-xl border border-border bg-card p-2 shadow-xs","data-testid":`auth-config-cap-${n.key}`,children:[(0,a.jsx)("span",{className:"text-sm",children:t(n.label)}),m($)]},n.key)})})}),(0,a.jsx)(g,{heading:t("Plugins"),testId:"auth-config-plugins",children:l.plugins.length===0?(0,a.jsx)("p",{className:"text-sm text-muted-foreground",children:t("No plugins enabled.")}):(0,a.jsx)("div",{className:"flex flex-wrap gap-2",children:l.plugins.map(L)})}),(0,a.jsx)(g,{heading:t("Sign-in methods"),testId:"auth-config-signin",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Email & password"),value:m(l.emailAndPassword)}),(0,a.jsx)(o,{label:t("Social providers"),value:l.socialProviders.length===0?t("None"):(0,a.jsx)("span",{className:"flex flex-wrap justify-end gap-1",children:l.socialProviders.map(q)})})]})}),l.organization.enabled&&(0,a.jsx)(g,{heading:t("Organizations"),testId:"auth-config-org",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Teams"),value:m(l.organization.teams)}),(0,a.jsx)(o,{label:t("Custom roles"),value:m(l.organization.roles)})]})}),(0,a.jsx)(g,{heading:t("Session policy"),testId:"auth-config-session",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Expires in"),value:v(l.session.expiresIn)}),(0,a.jsx)(o,{label:t("Refresh after"),value:v(l.session.updateAge)}),(0,a.jsx)(o,{label:t("Fresh window"),value:v(l.session.freshAge)}),(0,a.jsx)(o,{label:t("Cookie cache"),value:m(l.session.cookieCache===!0)})]})}),(0,a.jsx)(g,{heading:t("Rate limit"),testId:"auth-config-ratelimit",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Status"),value:m(l.rateLimit.enabled)}),l.rateLimit.enabled&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(o,{label:t("Max requests"),value:l.rateLimit.max??"\u2014"}),(0,a.jsx)(o,{label:t("Window"),value:v(l.rateLimit.window)})]})]})}),l.userFields.length>0&&(0,a.jsx)(g,{heading:t("Plugin user fields"),testId:"auth-config-user-fields",children:(0,a.jsx)("ul",{className:"flex flex-col gap-2",children:l.userFields.map(n=>(0,a.jsxs)("li",{className:"flex items-center justify-between gap-2 rounded-xl border border-border bg-card p-2 shadow-xs","data-testid":`auth-config-user-field-${n.name}`,children:[(0,a.jsxs)("span",{className:"flex flex-col",children:[(0,a.jsx)("span",{className:"font-mono text-xs",children:n.name}),n.plugin!==void 0&&(0,a.jsx)("span",{className:"text-[11px] text-muted-foreground",children:n.plugin})]}),(0,a.jsxs)("span",{className:"flex items-center gap-1",children:[(0,a.jsx)(h,{variant:"outline",children:n.type}),n.required&&(0,a.jsx)(h,{variant:"secondary",children:t("required")}),n.unique&&(0,a.jsx)(h,{variant:"secondary",children:t("unique")})]})]},n.name))})}),(0,a.jsx)(y,{className:"gap-0 py-0",children:(0,a.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground","data-testid":"auth-config-note",children:t("OAuth providers, email templates, and rate limits are configured at deploy time in the better-auth setup and aren't editable here. See the Mail tab for email output.")})})]}),e[11]=l,e[12]=s,e[13]=m,e[14]=t,e[15]=x):x=e[15];let b;return e[16]!==p||e[17]!==f||e[18]!==x?(b=(0,a.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"auth-config",children:[p,f,x]}),e[16]=p,e[17]=f,e[18]=x,e[19]=b):b=e[19],b},"M");function L(e){return(0,a.jsx)(h,{"data-testid":`auth-config-plugin-${e}`,variant:"outline",children:e},e)}u(L,"P");function q(e){return(0,a.jsx)(h,{"data-testid":`auth-config-provider-${e}`,variant:"outline",children:e},e)}u(q,"z");export{T as default};
1
+ import{b as h}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{b as A}from"./chunk-FZ2N52BV.js";import{f as k}from"./chunk-BDHAGUAY.js";import"./chunk-XBDKZZ67.js";import{a as y,e as S}from"./chunk-WQH3LT2P.js";import{d as I}from"./chunk-IUYFXK4X.js";import"./chunk-5DVJR52Z.js";import{a as u,e as w,g as j,h as z}from"./chunk-3XIESWL4.js";var N=w(j(),1);var a=w(z(),1);var P=[{key:"accounts",label:"Accounts"},{key:"admin",label:"Admin"},{key:"organization",label:"Organizations"},{key:"passkey",label:"Passkeys"},{key:"twoFactor",label:"Two-factor"}],v=u(e=>{if(e===void 0)return"\u2014";let i=[[86400,"d"],[3600,"h"],[60,"m"]];for(let[t,d]of i)if(e>=t&&e%t===0)return`${String(e/t)}${d}`;return`${String(e)}s`},"v"),g=u(e=>{let i=(0,N.c)(8),{children:t,heading:d,testId:r}=e,l;i[0]!==d?(l=(0,a.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,a.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:d})}),i[0]=d,i[1]=l):l=i[1];let s;i[2]!==t?(s=(0,a.jsx)(S,{className:"p-3",children:t}),i[2]=t,i[3]=s):s=i[3];let c;return i[4]!==l||i[5]!==s||i[6]!==r?(c=(0,a.jsxs)(y,{className:"gap-0 py-0","data-testid":r,children:[l,s]}),i[4]=l,i[5]=s,i[6]=r,i[7]=c):c=i[7],c},"h"),o=u(e=>{let i=(0,N.c)(7),{label:t,value:d}=e,r;i[0]!==t?(r=(0,a.jsx)("span",{className:"text-sm",children:t}),i[0]=t,i[1]=r):r=i[1];let l;i[2]!==d?(l=(0,a.jsx)("span",{className:"text-sm text-muted-foreground tabular-nums",children:d}),i[2]=d,i[3]=l):l=i[3];let s;return i[4]!==r||i[5]!==l?(s=(0,a.jsxs)("div",{className:"flex items-center justify-between gap-2 rounded-xl border border-border bg-card p-2 shadow-xs",children:[r,l]}),i[4]=r,i[5]=l,i[6]=s):s=i[6],s},"c"),T=u(()=>{let e=(0,N.c)(20),i=k(),t=I(),d;e[0]===Symbol.for("react.memo_cache_sentinel")?(d=["lunora-auth-config"],e[0]=d):d=e[0];let r;e[1]!==i?(r=u(()=>i.getAuthConfig(),"s"),e[1]=i,e[2]=r):r=e[2];let{data:l,error:s}=A(d,r),c;e[3]!==t?(c=u(n=>(0,a.jsx)(h,{variant:n?"success":"outline",children:t(n?"Enabled":"Disabled")}),"u"),e[3]=t,e[4]=c):c=e[4];let m=c,p;e[5]!==s?(p=s!==null&&(0,a.jsx)("p",{className:"px-4 py-8 text-center text-sm text-destructive","data-testid":"auth-config-error",role:"alert",children:s}),e[5]=s,e[6]=p):p=e[6];let f;e[7]!==l||e[8]!==s||e[9]!==t?(f=s===null&&l===void 0&&(0,a.jsx)("p",{className:"px-4 py-8 text-center text-sm text-muted-foreground","data-testid":"auth-config-loading",children:t("Loading auth configuration\u2026")}),e[7]=l,e[8]=s,e[9]=t,e[10]=f):f=e[10];let x;e[11]!==l||e[12]!==s||e[13]!==m||e[14]!==t?(x=s===null&&l!==void 0&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(g,{heading:t("Enabled capabilities"),testId:"auth-config-capabilities",children:(0,a.jsx)("ul",{className:"grid grid-cols-1 gap-2 sm:grid-cols-2",children:P.map(n=>{let $=l.capabilities[n.key];return(0,a.jsxs)("li",{className:"flex items-center justify-between gap-2 rounded-xl border border-border bg-card p-2 shadow-xs","data-testid":`auth-config-cap-${n.key}`,children:[(0,a.jsx)("span",{className:"text-sm",children:t(n.label)}),m($)]},n.key)})})}),(0,a.jsx)(g,{heading:t("Plugins"),testId:"auth-config-plugins",children:l.plugins.length===0?(0,a.jsx)("p",{className:"text-sm text-muted-foreground",children:t("No plugins enabled.")}):(0,a.jsx)("div",{className:"flex flex-wrap gap-2",children:l.plugins.map(L)})}),(0,a.jsx)(g,{heading:t("Sign-in methods"),testId:"auth-config-signin",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Email & password"),value:m(l.emailAndPassword)}),(0,a.jsx)(o,{label:t("Social providers"),value:l.socialProviders.length===0?t("None"):(0,a.jsx)("span",{className:"flex flex-wrap justify-end gap-1",children:l.socialProviders.map(q)})})]})}),l.organization.enabled&&(0,a.jsx)(g,{heading:t("Organizations"),testId:"auth-config-org",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Teams"),value:m(l.organization.teams)}),(0,a.jsx)(o,{label:t("Custom roles"),value:m(l.organization.roles)})]})}),(0,a.jsx)(g,{heading:t("Session policy"),testId:"auth-config-session",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Expires in"),value:v(l.session.expiresIn)}),(0,a.jsx)(o,{label:t("Refresh after"),value:v(l.session.updateAge)}),(0,a.jsx)(o,{label:t("Fresh window"),value:v(l.session.freshAge)}),(0,a.jsx)(o,{label:t("Cookie cache"),value:m(l.session.cookieCache===!0)})]})}),(0,a.jsx)(g,{heading:t("Rate limit"),testId:"auth-config-ratelimit",children:(0,a.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,a.jsx)(o,{label:t("Status"),value:m(l.rateLimit.enabled)}),l.rateLimit.enabled&&(0,a.jsxs)(a.Fragment,{children:[(0,a.jsx)(o,{label:t("Max requests"),value:l.rateLimit.max??"\u2014"}),(0,a.jsx)(o,{label:t("Window"),value:v(l.rateLimit.window)})]})]})}),l.userFields.length>0&&(0,a.jsx)(g,{heading:t("Plugin user fields"),testId:"auth-config-user-fields",children:(0,a.jsx)("ul",{className:"flex flex-col gap-2",children:l.userFields.map(n=>(0,a.jsxs)("li",{className:"flex items-center justify-between gap-2 rounded-xl border border-border bg-card p-2 shadow-xs","data-testid":`auth-config-user-field-${n.name}`,children:[(0,a.jsxs)("span",{className:"flex flex-col",children:[(0,a.jsx)("span",{className:"font-mono text-xs",children:n.name}),n.plugin!==void 0&&(0,a.jsx)("span",{className:"text-[11px] text-muted-foreground",children:n.plugin})]}),(0,a.jsxs)("span",{className:"flex items-center gap-1",children:[(0,a.jsx)(h,{variant:"outline",children:n.type}),n.required&&(0,a.jsx)(h,{variant:"secondary",children:t("required")}),n.unique&&(0,a.jsx)(h,{variant:"secondary",children:t("unique")})]})]},n.name))})}),(0,a.jsx)(y,{className:"gap-0 py-0",children:(0,a.jsx)("p",{className:"px-4 py-3 text-xs text-muted-foreground","data-testid":"auth-config-note",children:t("OAuth providers, email templates, and rate limits are configured at deploy time in the better-auth setup and aren't editable here. See the Mail tab for email output.")})})]}),e[11]=l,e[12]=s,e[13]=m,e[14]=t,e[15]=x):x=e[15];let b;return e[16]!==p||e[17]!==f||e[18]!==x?(b=(0,a.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"auth-config",children:[p,f,x]}),e[16]=p,e[17]=f,e[18]=x,e[19]=b):b=e[19],b},"M");function L(e){return(0,a.jsx)(h,{"data-testid":`auth-config-plugin-${e}`,variant:"outline",children:e},e)}u(L,"P");function q(e){return(0,a.jsx)(h,{"data-testid":`auth-config-provider-${e}`,variant:"outline",children:e},e)}u(q,"z");export{T as default};
@@ -1 +1 @@
1
- import{a as ke}from"./chunk-V53KNYRN.js";import{a as T}from"./chunk-5Y3QLNWX.js";import{a as Pe}from"./chunk-IGCNMZSB.js";import{a as be}from"./chunk-RMN2JN4S.js";import"./chunk-GRL5MG3Z.js";import"./chunk-7T7UOTYK.js";import{R as $}from"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import{a as F}from"./chunk-MWIKAR7F.js";import"./chunk-DJZYD5I5.js";import"./chunk-2OUPA2WJ.js";import{b as M}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as ge}from"./chunk-ZBVGZ4YA.js";import"./chunk-XXQUMVWH.js";import"./chunk-56Q3NCCQ.js";import"./chunk-QLQADHFE.js";import{a as Z}from"./chunk-VDW32UET.js";import{c as ae}from"./chunk-KMT6UDR7.js";import{f as oe}from"./chunk-WVU7GHTG.js";import"./chunk-XBDKZZ67.js";import{a as de}from"./chunk-XQCVZAGU.js";import{a as Ne,b as ve,c as we,d as ce,e as le,f as re}from"./chunk-WJQLNYGX.js";import{a as se,b as pe,c as fe,d as ue,e as ne}from"./chunk-WQH3LT2P.js";import{d as Y,f as he,g as xe,h as ye,o as te}from"./chunk-IUYFXK4X.js";import"./chunk-BR5GIQWK.js";import{a as d,e as ie,f as _e,g as Ae,h as Fe}from"./chunk-3XIESWL4.js";var p=ie(_e(),1);var me=ie(Ae(),1);var t=ie(Fe(),1);var Ce=["read","insert","update","delete"],Te=d((e,a)=>({delete:e("Delete"),insert:e("Insert"),read:e("Read"),update:e("Update")})[a],"_e"),ze=d(e=>{let a=new Set;for(let i of e?.advisories??[])if(i.name==="rls_uncovered_table"){let{table:s}=i.metadata;typeof s=="string"&&s!==""&&a.add(s)}return a},"Ae"),Ee=d((e,a,i)=>{let s=new Map,l=d(n=>{let o=s.get(n);if(o!==void 0)return o;let f={cells:{delete:{},insert:{},read:{},update:{}},maskedColumns:new Set,table:n,uncovered:i.has(n)};return s.set(n,f),f},"r");for(let n of e)l(n.table).cells[n.on]={procedure:n.procedure};for(let n of a)l(n.table).maskedColumns.add(n.column);for(let n of i)l(n);return[...s.values()].toSorted((n,o)=>n.table.localeCompare(o.table))},"Fe"),Le=d(e=>{let a=(0,me.c)(17),i;a[0]!==e?(i=e===void 0?{}:e,a[0]=e,a[1]=i):i=a[1];let{onProbe:s}=i,l=Y(),n,o;a[2]===Symbol.for("react.memo_cache_sentinel")?(n={},o={live:!0},a[2]=n,a[3]=o):(n=a[2],o=a[3]);let f=ae(Z.rlsPolicies,n,o),r;a[4]===Symbol.for("react.memo_cache_sentinel")?(r={},a[4]=r):r=a[4];let b=ae(Z.maskPolicies,r),h;a[5]===Symbol.for("react.memo_cache_sentinel")?(h={},a[5]=h):h=a[5];let g=ae(Z.getAdvisories,h),N;if(a[6]!==g.data||a[7]!==b.data||a[8]!==s||a[9]!==f||a[10]!==l){let v=null;f.data!==void 0&&(v=Array.isArray(f.data.policies)?f.data.policies:[]);let z=Array.isArray(b.data?.columns)?b.data.columns:[],j=g.data??null,{error:C,errorSource:w,liveError:S}=f,_=v===null?[]:Ee(v,z,ze(j)),k;a[12]!==S?(k=(0,t.jsx)("div",{className:"flex items-center justify-end",children:(0,t.jsx)(Pe,{message:S,prefix:"pm"})}),a[12]=S,a[13]=k):k=a[13];let x;a[14]!==C||a[15]!==w?(x=C!==null&&(0,t.jsx)(ge,{error:w,testId:"pm-error"}),a[14]=C,a[15]=w,a[16]=x):x=a[16],N=(0,t.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-permissions-matrix",children:[k,x,v!==null&&_.length===0?(0,t.jsx)(de,{description:l("Add a `definePolicy` and wire it through `.use(rls(...))` to populate this matrix."),testId:"pm-empty",title:l("No policy")}):(0,t.jsxs)(Ne,{"data-testid":"pm-table",children:[(0,t.jsx)(ve,{children:(0,t.jsxs)(ce,{children:[(0,t.jsx)(le,{children:l("Table")}),Ce.map(c=>(0,t.jsx)(le,{children:Te(l,c)},c)),(0,t.jsx)(le,{children:l("Masked columns")})]})}),(0,t.jsx)(we,{children:_.map(c=>(0,t.jsxs)(ce,{"data-testid":`pm-row-${c.table}`,children:[(0,t.jsx)(re,{className:"font-mono text-xs",children:(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[c.table,c.uncovered&&(0,t.jsx)(M,{"data-testid":`pm-uncovered-${c.table}`,title:l("Uncovered \u2014 reachable without a policy"),variant:"destructive",children:l("Uncovered \u2014 reachable without a policy")})]})}),Ce.map(I=>{let y=c.cells[I];return(0,t.jsx)(re,{"data-testid":`pm-cell-${c.table}-${I}`,children:y.procedure===void 0?(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:l("No policy")}):(0,t.jsxs)("span",{className:"flex flex-col gap-1",children:[(0,t.jsx)(M,{variant:"secondary",children:l("Covered by {procedure}",{procedure:y.procedure})}),s!==void 0&&(0,t.jsx)(F,{className:"h-auto justify-start p-0 text-[11px]","data-testid":`pm-probe-${c.table}-${I}`,onClick:d(()=>{s(c.table,I,y.procedure??"")},"onClick"),size:"xs",type:"button",variant:"ghost",children:l("Probe this")})]})},I)}),(0,t.jsx)(re,{children:c.maskedColumns.size===0?(0,t.jsx)("span",{"aria-hidden":"true",className:"text-muted-foreground",children:"\u2014"}):(0,t.jsx)("span",{className:"flex flex-wrap gap-1",children:[...c.maskedColumns].map(Oe)})})]},c.table))})]})]}),a[6]=g.data,a[7]=b.data,a[8]=s,a[9]=f,a[10]=l,a[11]=N}else N=a[11];return N},"Te");function Oe(e){return(0,t.jsx)(M,{variant:"outline",children:e},e)}d(Oe,"Ee");var Re=he(Z.runAs),je=d(()=>{let e=oe();return async({args:a,functionPath:i,shardKey:s="",userId:l})=>{let n=Re;try{return{kind:"allowed",value:await e.query(n,{args:a,functionPath:i,userId:l},xe(s))}}catch(o){return{kind:"denied",message:o instanceof Error?o.message:String(o)}}}},"Re"),Me=d(e=>e===void 0?"undefined":JSON.stringify(e,null,2),"Me"),$e=d(({functions:e,prefill:a,runAsIdentity:i=!1}={})=>{let s=oe(),l=Y(),n=je(),[o,f]=(0,p.useState)(null),[r,b]=(0,p.useState)(null),h=e??o??[],[g,N]=(0,p.useState)(""),[v,z]=(0,p.useState)("{}"),[j,C]=(0,p.useState)(""),[w,S]=(0,p.useState)(""),[_,k]=(0,p.useState)(!1),[x,c]=(0,p.useState)(null),[I,y]=(0,p.useState)(null),A=(0,p.useRef)(-1);(0,p.useEffect)(()=>{if(e!==void 0)return;let m=!1;return s.listFunctions().then(u=>(m||f(u),u)).catch(u=>{m||b(ye(u))}),()=>{m=!0}},[s,e]),(0,p.useEffect)(()=>{if(a===void 0||A.current===a.nonce)return;A.current=a.nonce;let m=a.functionPath;queueMicrotask(()=>{N(m),c(null)})},[a]);let P=g===""?h[0]?.path??"":g,E=d(async()=>{if(P==="")return;let m;try{m=v.trim()===""?{}:JSON.parse(v)}catch(u){y(l("Invalid JSON args: {message}",{message:u.message})),c(null);return}y(null),k(!0);try{let u=await n({args:m,functionPath:P,shardKey:j.trim(),userId:w.trim()});c(u)}finally{k(!1)}},"F"),L=d(()=>{te(E())},"T"),H=d(m=>{N(m.target.value)},"B"),O=d(m=>{z(m.target.value)},"E"),R=d(m=>{S(m.target.value)},"L");return(0,t.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-permissions-playground",children:[r!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"pp-discover-error",role:"alert",children:r}),!i&&(0,t.jsx)(de,{description:l("Dev only: runs the selected function as this user over the admin gate so you can test auth and RLS."),testId:"pp-gate",title:l("Set `runAsIdentity` to forge an identity and probe access.")}),(0,t.jsxs)("div",{className:"flex flex-col gap-3 rounded-md border border-border p-3",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(T,{htmlFor:"pp-function",children:l("Function")}),(0,t.jsx)("select",{"aria-label":l("Function"),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","data-testid":"pp-function",id:"pp-function",onChange:H,value:P,children:h.map(m=>(0,t.jsxs)("option",{value:m.path,children:[m.path," (",m.kind,")"]},m.path))})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(T,{htmlFor:"pp-args",children:l("Arguments")}),(0,t.jsx)(ke,{"aria-label":l("Arguments"),className:"font-mono text-xs","data-testid":"pp-args",id:"pp-args",onChange:O,value:v})]}),(0,t.jsx)(be,{onChange:C,testId:"pp-shard",value:j}),(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(T,{htmlFor:"pp-user",children:l("Run as (userId)")}),(0,t.jsx)($,{"aria-label":l("Identity (userId) to run as"),className:"font-mono text-xs","data-testid":"pp-user",id:"pp-user",onChange:R,placeholder:l("Leave empty to run as admin"),value:w})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(F,{"data-testid":"pp-run",disabled:!i||_||P==="",onClick:L,type:"button",children:l(_?"Probing\u2026":"Run probe")}),w.trim()!==""&&(0,t.jsx)(M,{"data-testid":"pp-as-badge",variant:"secondary",children:l("as {userId}",{userId:w.trim()})})]})]}),I!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"pp-args-error",role:"alert",children:I}),x!==null&&x.kind==="allowed"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"pp-outcome-allowed",children:[(0,t.jsx)(M,{variant:"secondary",children:l("Allowed")}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs","data-testid":"pp-result",children:Me(x.value)})]}),x!==null&&x.kind==="denied"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"pp-outcome-denied",children:[(0,t.jsx)(M,{variant:"destructive",children:l("Denied")}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs text-destructive","data-testid":"pp-denied",role:"alert",children:x.message})]})]})},"Oe"),qe="/__lunora/policy-scaffold",De={"already-wired":"That procedure already has an rls(...) policy wired in.","file-exists":"A policy file with that name already exists \u2014 pick another name or edit it by hand.","invalid-identifier":"Name, table, and policy-set must be plain identifiers (letters, digits, _ or $).","unknown-procedure":"No exported procedure was found at that file path.","unsupported-procedure-shape":"That procedure uses the bare query({\u2026}) form \u2014 convert it to the builder form (c.use(\u2026).query(\u2026)) before wiring RLS."},Je=d(async e=>{let a=await fetch(qe,{body:JSON.stringify(e),headers:{"Content-Type":"application/json"},method:"POST"}),i=await a.json();if(i.needsManualEdit===!0)return{kind:"needs-manual-edit",message:i.message??"This change must be made by hand."};if(a.ok)return{diagnostics:i.diagnostics??[],kind:"ok",label:i.fileName??i.exportName??""};let s=i.error;return{kind:"error",message:s===void 0?`policy scaffold failed (${String(a.status)})`:De[s]??s}},"qe"),Se={exportName:"",filePath:"",policyName:"",policies:"",tableName:""},Ue=d(()=>{let e=(0,me.c)(69),a=Y(),[i,s]=(0,p.useState)(null),[l,n]=(0,p.useState)(!1),[o,f]=(0,p.useState)(null),[r,b]=(0,p.useState)(Se),h;e[0]===Symbol.for("react.memo_cache_sentinel")?(h=d(ee=>{let G=ee.target.name,{value:V}=ee.target;b(Ie=>({...Ie,[G]:V}))},"u"),e[0]=h):h=e[0];let g=h,N;e[1]===Symbol.for("react.memo_cache_sentinel")?(N=d(()=>{s(null),b(Se)},"N"),e[1]=N):N=e[1];let v=N,z;e[2]===Symbol.for("react.memo_cache_sentinel")?(z=d(async ee=>{n(!0),f(null);try{let G=await Je(ee);f(G),G.kind==="ok"&&v()}catch(G){let V=G;f({kind:"error",message:V instanceof Error?V.message:String(V)})}n(!1)},"A"),e[2]=z):z=e[2];let j=z,C;e[3]!==r.policyName||e[4]!==r.tableName?(C=d(()=>{te(j({kind:"scaffoldPolicy",name:r.policyName.trim(),table:r.tableName.trim()}))},"S"),e[3]=r.policyName,e[4]=r.tableName,e[5]=C):C=e[5];let w=C,S;e[6]!==r.exportName||e[7]!==r.filePath||e[8]!==r.policies?(S=d(()=>{te(j({exportName:r.exportName.trim(),filePath:r.filePath.trim(),kind:"wireRls",policies:r.policies.trim()}))},"C"),e[6]=r.exportName,e[7]=r.filePath,e[8]=r.policies,e[9]=S):S=e[9];let _=S,k;e[10]===Symbol.for("react.memo_cache_sentinel")?(k=d(()=>{f(null),s("scaffold")},"k"),e[10]=k):k=e[10];let x=k,c;e[11]===Symbol.for("react.memo_cache_sentinel")?(c=d(()=>{f(null),s("wire")},"c"),e[11]=c):c=e[11];let I=c,y;e[12]!==a?(y=a("Scaffold access rules"),e[12]=a,e[13]=y):y=e[13];let A;e[14]!==y?(A=(0,t.jsx)(fe,{children:y}),e[14]=y,e[15]=A):A=e[15];let P;e[16]!==a?(P=a("Writes a new deny-by-default policy file under lunora/, or wires one into a procedure, then reruns codegen. Local dev only."),e[16]=a,e[17]=P):P=e[17];let E;e[18]!==P?(E=(0,t.jsx)(ue,{children:P}),e[18]=P,e[19]=E):E=e[19];let L;e[20]!==E||e[21]!==A?(L=(0,t.jsxs)(pe,{children:[A,E]}),e[20]=E,e[21]=A,e[22]=L):L=e[22];let H=i==="scaffold"?"default":"outline",O;e[23]!==a?(O=a("New policy file"),e[23]=a,e[24]=O):O=e[24];let R;e[25]!==H||e[26]!==O?(R=(0,t.jsx)(F,{"data-testid":"policy-scaffolder-new",onClick:x,size:"xs",type:"button",variant:H,children:O}),e[25]=H,e[26]=O,e[27]=R):R=e[27];let m=i==="wire"?"default":"outline",u;e[28]!==a?(u=a("Wire into a procedure"),e[28]=a,e[29]=u):u=e[29];let q;e[30]!==m||e[31]!==u?(q=(0,t.jsx)(F,{"data-testid":"policy-scaffolder-wire",onClick:I,size:"xs",type:"button",variant:m,children:u}),e[30]=m,e[31]=u,e[32]=q):q=e[32];let D;e[33]!==R||e[34]!==q?(D=(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[R,q]}),e[33]=R,e[34]=q,e[35]=D):D=e[35];let J;e[36]!==l||e[37]!==r.policyName||e[38]!==r.tableName||e[39]!==i||e[40]!==w||e[41]!==a?(J=i==="scaffold"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"policy-scaffolder-new-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(T,{htmlFor:"policy-scaffolder-name",children:a("Policy name")}),(0,t.jsx)($,{"data-testid":"policy-scaffolder-name",id:"policy-scaffolder-name",name:"policyName",onChange:g,value:r.policyName})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(T,{htmlFor:"policy-scaffolder-table",children:a("Table name")}),(0,t.jsx)($,{"data-testid":"policy-scaffolder-table",id:"policy-scaffolder-table",name:"tableName",onChange:g,value:r.tableName})]}),(0,t.jsx)(F,{"data-testid":"policy-scaffolder-create",disabled:l||r.policyName.trim()===""||r.tableName.trim()==="",onClick:w,size:"xs",type:"button",children:a(l?"Creating\u2026":"Create policy file")}),(0,t.jsx)(F,{onClick:v,size:"xs",type:"button",variant:"ghost",children:a("Cancel")})]}),e[36]=l,e[37]=r.policyName,e[38]=r.tableName,e[39]=i,e[40]=w,e[41]=a,e[42]=J):J=e[42];let U;e[43]!==l||e[44]!==r.exportName||e[45]!==r.filePath||e[46]!==r.policies||e[47]!==i||e[48]!==_||e[49]!==a?(U=i==="wire"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"policy-scaffolder-wire-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(T,{htmlFor:"policy-scaffolder-file",children:a("Procedure file path")}),(0,t.jsx)($,{"data-testid":"policy-scaffolder-file",id:"policy-scaffolder-file",name:"filePath",onChange:g,value:r.filePath})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(T,{htmlFor:"policy-scaffolder-export",children:a("Exported procedure")}),(0,t.jsx)($,{"data-testid":"policy-scaffolder-export",id:"policy-scaffolder-export",name:"exportName",onChange:g,value:r.exportName})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(T,{htmlFor:"policy-scaffolder-policies",children:a("Policy set identifier")}),(0,t.jsx)($,{"data-testid":"policy-scaffolder-policies",id:"policy-scaffolder-policies",name:"policies",onChange:g,value:r.policies})]}),(0,t.jsx)(F,{"data-testid":"policy-scaffolder-apply",disabled:l||r.filePath.trim()===""||r.exportName.trim()===""||r.policies.trim()==="",onClick:_,size:"xs",type:"button",children:a(l?"Wiring\u2026":"Wire RLS")}),(0,t.jsx)(F,{onClick:v,size:"xs",type:"button",variant:"ghost",children:a("Cancel")})]}),e[43]=l,e[44]=r.exportName,e[45]=r.filePath,e[46]=r.policies,e[47]=i,e[48]=_,e[49]=a,e[50]=U):U=e[50];let K;e[51]!==o?(K=o?.kind==="error"&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive","data-testid":"policy-scaffolder-error",role:"alert",children:o.message}),e[51]=o,e[52]=K):K=e[52];let W;e[53]!==o?.kind||e[54]!==a?(W=o?.kind==="needs-manual-edit"&&(0,t.jsx)("p",{className:"mt-3 text-sm text-amber-600 dark:text-amber-500","data-testid":"policy-scaffolder-manual",role:"alert",children:a("This change must be made by hand \u2014 the scaffolder only adds new, deny-by-default rules.")}),e[53]=o?.kind,e[54]=a,e[55]=W):W=e[55];let B;e[56]!==o||e[57]!==a?(B=o?.kind==="ok"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-col gap-1","data-testid":"policy-scaffolder-ok",children:[(0,t.jsx)("p",{className:"text-sm text-emerald-600 dark:text-emerald-500",children:a("Scaffolded {label} and reran codegen. Fill in the `when` predicates before relying on it.",{label:o.label})}),o.diagnostics.length>0&&(0,t.jsx)("ul",{className:"flex flex-col gap-0.5","data-testid":"policy-scaffolder-diagnostics",children:o.diagnostics.map(Ke)})]}),e[56]=o,e[57]=a,e[58]=B):B=e[58];let Q;e[59]!==D||e[60]!==J||e[61]!==U||e[62]!==K||e[63]!==W||e[64]!==B?(Q=(0,t.jsxs)(ne,{children:[D,J,U,K,W,B]}),e[59]=D,e[60]=J,e[61]=U,e[62]=K,e[63]=W,e[64]=B,e[65]=Q):Q=e[65];let X;return e[66]!==L||e[67]!==Q?(X=(0,t.jsxs)(se,{"data-testid":"policy-scaffolder",size:"sm",children:[L,Q]}),e[66]=L,e[67]=Q,e[68]=X):X=e[68],X},"Je");function Ke(e){return(0,t.jsx)("li",{className:"font-mono text-[11px] text-destructive",children:e},e)}d(Ke,"De");var st=d(({functions:e,runAsIdentity:a=!1,schemaEditable:i=!1}={})=>{let s=Y(),[l,n]=(0,p.useState)(void 0),o=d((f,r,b)=>{b!==""&&n(h=>({functionPath:b,nonce:(h?.nonce??0)+1}))},"o");return(0,t.jsxs)("div",{className:"flex flex-col gap-8","data-testid":"lunora-permissions",children:[(0,t.jsxs)("section",{className:"flex flex-col gap-3",children:[(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:s("Permissions")})}),(0,t.jsx)(Le,{onProbe:o})]}),(0,t.jsx)("section",{className:"flex flex-col gap-3",children:(0,t.jsxs)(se,{className:"gap-0 py-0",children:[(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:s("Probe")})}),(0,t.jsxs)(ne,{className:"px-4 py-4",children:[(0,t.jsx)("p",{className:"mb-3 text-sm text-muted-foreground",children:s("Pick a function and an identity, then run it to see the access outcome.")}),(0,t.jsx)($e,{functions:e,prefill:l,runAsIdentity:a})]})]})}),i&&(0,t.jsx)("section",{className:"flex flex-col gap-2",children:(0,t.jsx)(Ue,{})})]})},"nt");export{st as PermissionsPanel};
1
+ import{a as ke}from"./chunk-V53KNYRN.js";import{a as T}from"./chunk-5Y3QLNWX.js";import{a as Pe}from"./chunk-IGCNMZSB.js";import{a as be}from"./chunk-RMN2JN4S.js";import"./chunk-GRL5MG3Z.js";import"./chunk-7T7UOTYK.js";import{R as $}from"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import{a as F}from"./chunk-MWIKAR7F.js";import"./chunk-DJZYD5I5.js";import"./chunk-2OUPA2WJ.js";import{b as M}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as ge}from"./chunk-CAOA5AM4.js";import"./chunk-XXQUMVWH.js";import"./chunk-VR3OBMGZ.js";import"./chunk-QLQADHFE.js";import{a as Z}from"./chunk-VDW32UET.js";import{c as ae}from"./chunk-FZ2N52BV.js";import{f as oe}from"./chunk-BDHAGUAY.js";import"./chunk-XBDKZZ67.js";import{a as de}from"./chunk-XQCVZAGU.js";import{a as Ne,b as ve,c as we,d as ce,e as le,f as re}from"./chunk-WJQLNYGX.js";import{a as se,b as pe,c as fe,d as ue,e as ne}from"./chunk-WQH3LT2P.js";import{d as Y,f as he,g as xe,h as ye,o as te}from"./chunk-IUYFXK4X.js";import"./chunk-5DVJR52Z.js";import{a as d,e as ie,f as _e,g as Ae,h as Fe}from"./chunk-3XIESWL4.js";var p=ie(_e(),1);var me=ie(Ae(),1);var t=ie(Fe(),1);var Ce=["read","insert","update","delete"],Te=d((e,a)=>({delete:e("Delete"),insert:e("Insert"),read:e("Read"),update:e("Update")})[a],"_e"),ze=d(e=>{let a=new Set;for(let i of e?.advisories??[])if(i.name==="rls_uncovered_table"){let{table:s}=i.metadata;typeof s=="string"&&s!==""&&a.add(s)}return a},"Ae"),Ee=d((e,a,i)=>{let s=new Map,l=d(n=>{let o=s.get(n);if(o!==void 0)return o;let f={cells:{delete:{},insert:{},read:{},update:{}},maskedColumns:new Set,table:n,uncovered:i.has(n)};return s.set(n,f),f},"r");for(let n of e)l(n.table).cells[n.on]={procedure:n.procedure};for(let n of a)l(n.table).maskedColumns.add(n.column);for(let n of i)l(n);return[...s.values()].toSorted((n,o)=>n.table.localeCompare(o.table))},"Fe"),Le=d(e=>{let a=(0,me.c)(17),i;a[0]!==e?(i=e===void 0?{}:e,a[0]=e,a[1]=i):i=a[1];let{onProbe:s}=i,l=Y(),n,o;a[2]===Symbol.for("react.memo_cache_sentinel")?(n={},o={live:!0},a[2]=n,a[3]=o):(n=a[2],o=a[3]);let f=ae(Z.rlsPolicies,n,o),r;a[4]===Symbol.for("react.memo_cache_sentinel")?(r={},a[4]=r):r=a[4];let b=ae(Z.maskPolicies,r),h;a[5]===Symbol.for("react.memo_cache_sentinel")?(h={},a[5]=h):h=a[5];let g=ae(Z.getAdvisories,h),N;if(a[6]!==g.data||a[7]!==b.data||a[8]!==s||a[9]!==f||a[10]!==l){let v=null;f.data!==void 0&&(v=Array.isArray(f.data.policies)?f.data.policies:[]);let z=Array.isArray(b.data?.columns)?b.data.columns:[],j=g.data??null,{error:C,errorSource:w,liveError:S}=f,_=v===null?[]:Ee(v,z,ze(j)),k;a[12]!==S?(k=(0,t.jsx)("div",{className:"flex items-center justify-end",children:(0,t.jsx)(Pe,{message:S,prefix:"pm"})}),a[12]=S,a[13]=k):k=a[13];let x;a[14]!==C||a[15]!==w?(x=C!==null&&(0,t.jsx)(ge,{error:w,testId:"pm-error"}),a[14]=C,a[15]=w,a[16]=x):x=a[16],N=(0,t.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-permissions-matrix",children:[k,x,v!==null&&_.length===0?(0,t.jsx)(de,{description:l("Add a `definePolicy` and wire it through `.use(rls(...))` to populate this matrix."),testId:"pm-empty",title:l("No policy")}):(0,t.jsxs)(Ne,{"data-testid":"pm-table",children:[(0,t.jsx)(ve,{children:(0,t.jsxs)(ce,{children:[(0,t.jsx)(le,{children:l("Table")}),Ce.map(c=>(0,t.jsx)(le,{children:Te(l,c)},c)),(0,t.jsx)(le,{children:l("Masked columns")})]})}),(0,t.jsx)(we,{children:_.map(c=>(0,t.jsxs)(ce,{"data-testid":`pm-row-${c.table}`,children:[(0,t.jsx)(re,{className:"font-mono text-xs",children:(0,t.jsxs)("span",{className:"flex items-center gap-1.5",children:[c.table,c.uncovered&&(0,t.jsx)(M,{"data-testid":`pm-uncovered-${c.table}`,title:l("Uncovered \u2014 reachable without a policy"),variant:"destructive",children:l("Uncovered \u2014 reachable without a policy")})]})}),Ce.map(I=>{let y=c.cells[I];return(0,t.jsx)(re,{"data-testid":`pm-cell-${c.table}-${I}`,children:y.procedure===void 0?(0,t.jsx)("span",{className:"text-xs text-muted-foreground",children:l("No policy")}):(0,t.jsxs)("span",{className:"flex flex-col gap-1",children:[(0,t.jsx)(M,{variant:"secondary",children:l("Covered by {procedure}",{procedure:y.procedure})}),s!==void 0&&(0,t.jsx)(F,{className:"h-auto justify-start p-0 text-[11px]","data-testid":`pm-probe-${c.table}-${I}`,onClick:d(()=>{s(c.table,I,y.procedure??"")},"onClick"),size:"xs",type:"button",variant:"ghost",children:l("Probe this")})]})},I)}),(0,t.jsx)(re,{children:c.maskedColumns.size===0?(0,t.jsx)("span",{"aria-hidden":"true",className:"text-muted-foreground",children:"\u2014"}):(0,t.jsx)("span",{className:"flex flex-wrap gap-1",children:[...c.maskedColumns].map(Oe)})})]},c.table))})]})]}),a[6]=g.data,a[7]=b.data,a[8]=s,a[9]=f,a[10]=l,a[11]=N}else N=a[11];return N},"Te");function Oe(e){return(0,t.jsx)(M,{variant:"outline",children:e},e)}d(Oe,"Ee");var Re=he(Z.runAs),je=d(()=>{let e=oe();return async({args:a,functionPath:i,shardKey:s="",userId:l})=>{let n=Re;try{return{kind:"allowed",value:await e.query(n,{args:a,functionPath:i,userId:l},xe(s))}}catch(o){return{kind:"denied",message:o instanceof Error?o.message:String(o)}}}},"Re"),Me=d(e=>e===void 0?"undefined":JSON.stringify(e,null,2),"Me"),$e=d(({functions:e,prefill:a,runAsIdentity:i=!1}={})=>{let s=oe(),l=Y(),n=je(),[o,f]=(0,p.useState)(null),[r,b]=(0,p.useState)(null),h=e??o??[],[g,N]=(0,p.useState)(""),[v,z]=(0,p.useState)("{}"),[j,C]=(0,p.useState)(""),[w,S]=(0,p.useState)(""),[_,k]=(0,p.useState)(!1),[x,c]=(0,p.useState)(null),[I,y]=(0,p.useState)(null),A=(0,p.useRef)(-1);(0,p.useEffect)(()=>{if(e!==void 0)return;let m=!1;return s.listFunctions().then(u=>(m||f(u),u)).catch(u=>{m||b(ye(u))}),()=>{m=!0}},[s,e]),(0,p.useEffect)(()=>{if(a===void 0||A.current===a.nonce)return;A.current=a.nonce;let m=a.functionPath;queueMicrotask(()=>{N(m),c(null)})},[a]);let P=g===""?h[0]?.path??"":g,E=d(async()=>{if(P==="")return;let m;try{m=v.trim()===""?{}:JSON.parse(v)}catch(u){y(l("Invalid JSON args: {message}",{message:u.message})),c(null);return}y(null),k(!0);try{let u=await n({args:m,functionPath:P,shardKey:j.trim(),userId:w.trim()});c(u)}finally{k(!1)}},"F"),L=d(()=>{te(E())},"T"),H=d(m=>{N(m.target.value)},"B"),O=d(m=>{z(m.target.value)},"E"),R=d(m=>{S(m.target.value)},"L");return(0,t.jsxs)("div",{className:"flex flex-col gap-3","data-testid":"lunora-permissions-playground",children:[r!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"pp-discover-error",role:"alert",children:r}),!i&&(0,t.jsx)(de,{description:l("Dev only: runs the selected function as this user over the admin gate so you can test auth and RLS."),testId:"pp-gate",title:l("Set `runAsIdentity` to forge an identity and probe access.")}),(0,t.jsxs)("div",{className:"flex flex-col gap-3 rounded-md border border-border p-3",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(T,{htmlFor:"pp-function",children:l("Function")}),(0,t.jsx)("select",{"aria-label":l("Function"),className:"flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-xs outline-none focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50","data-testid":"pp-function",id:"pp-function",onChange:H,value:P,children:h.map(m=>(0,t.jsxs)("option",{value:m.path,children:[m.path," (",m.kind,")"]},m.path))})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(T,{htmlFor:"pp-args",children:l("Arguments")}),(0,t.jsx)(ke,{"aria-label":l("Arguments"),className:"font-mono text-xs","data-testid":"pp-args",id:"pp-args",onChange:O,value:v})]}),(0,t.jsx)(be,{onChange:C,testId:"pp-shard",value:j}),(0,t.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,t.jsx)(T,{htmlFor:"pp-user",children:l("Run as (userId)")}),(0,t.jsx)($,{"aria-label":l("Identity (userId) to run as"),className:"font-mono text-xs","data-testid":"pp-user",id:"pp-user",onChange:R,placeholder:l("Leave empty to run as admin"),value:w})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(F,{"data-testid":"pp-run",disabled:!i||_||P==="",onClick:L,type:"button",children:l(_?"Probing\u2026":"Run probe")}),w.trim()!==""&&(0,t.jsx)(M,{"data-testid":"pp-as-badge",variant:"secondary",children:l("as {userId}",{userId:w.trim()})})]})]}),I!==null&&(0,t.jsx)("p",{className:"text-sm text-destructive","data-testid":"pp-args-error",role:"alert",children:I}),x!==null&&x.kind==="allowed"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"pp-outcome-allowed",children:[(0,t.jsx)(M,{variant:"secondary",children:l("Allowed")}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs","data-testid":"pp-result",children:Me(x.value)})]}),x!==null&&x.kind==="denied"&&(0,t.jsxs)("div",{className:"flex flex-col gap-2","data-testid":"pp-outcome-denied",children:[(0,t.jsx)(M,{variant:"destructive",children:l("Denied")}),(0,t.jsx)("pre",{className:"overflow-auto rounded-md border border-border bg-muted/50 p-3 font-mono text-xs text-destructive","data-testid":"pp-denied",role:"alert",children:x.message})]})]})},"Oe"),qe="/__lunora/policy-scaffold",De={"already-wired":"That procedure already has an rls(...) policy wired in.","file-exists":"A policy file with that name already exists \u2014 pick another name or edit it by hand.","invalid-identifier":"Name, table, and policy-set must be plain identifiers (letters, digits, _ or $).","unknown-procedure":"No exported procedure was found at that file path.","unsupported-procedure-shape":"That procedure uses the bare query({\u2026}) form \u2014 convert it to the builder form (c.use(\u2026).query(\u2026)) before wiring RLS."},Je=d(async e=>{let a=await fetch(qe,{body:JSON.stringify(e),headers:{"Content-Type":"application/json"},method:"POST"}),i=await a.json();if(i.needsManualEdit===!0)return{kind:"needs-manual-edit",message:i.message??"This change must be made by hand."};if(a.ok)return{diagnostics:i.diagnostics??[],kind:"ok",label:i.fileName??i.exportName??""};let s=i.error;return{kind:"error",message:s===void 0?`policy scaffold failed (${String(a.status)})`:De[s]??s}},"qe"),Se={exportName:"",filePath:"",policyName:"",policies:"",tableName:""},Ue=d(()=>{let e=(0,me.c)(69),a=Y(),[i,s]=(0,p.useState)(null),[l,n]=(0,p.useState)(!1),[o,f]=(0,p.useState)(null),[r,b]=(0,p.useState)(Se),h;e[0]===Symbol.for("react.memo_cache_sentinel")?(h=d(ee=>{let G=ee.target.name,{value:V}=ee.target;b(Ie=>({...Ie,[G]:V}))},"u"),e[0]=h):h=e[0];let g=h,N;e[1]===Symbol.for("react.memo_cache_sentinel")?(N=d(()=>{s(null),b(Se)},"N"),e[1]=N):N=e[1];let v=N,z;e[2]===Symbol.for("react.memo_cache_sentinel")?(z=d(async ee=>{n(!0),f(null);try{let G=await Je(ee);f(G),G.kind==="ok"&&v()}catch(G){let V=G;f({kind:"error",message:V instanceof Error?V.message:String(V)})}n(!1)},"A"),e[2]=z):z=e[2];let j=z,C;e[3]!==r.policyName||e[4]!==r.tableName?(C=d(()=>{te(j({kind:"scaffoldPolicy",name:r.policyName.trim(),table:r.tableName.trim()}))},"S"),e[3]=r.policyName,e[4]=r.tableName,e[5]=C):C=e[5];let w=C,S;e[6]!==r.exportName||e[7]!==r.filePath||e[8]!==r.policies?(S=d(()=>{te(j({exportName:r.exportName.trim(),filePath:r.filePath.trim(),kind:"wireRls",policies:r.policies.trim()}))},"C"),e[6]=r.exportName,e[7]=r.filePath,e[8]=r.policies,e[9]=S):S=e[9];let _=S,k;e[10]===Symbol.for("react.memo_cache_sentinel")?(k=d(()=>{f(null),s("scaffold")},"k"),e[10]=k):k=e[10];let x=k,c;e[11]===Symbol.for("react.memo_cache_sentinel")?(c=d(()=>{f(null),s("wire")},"c"),e[11]=c):c=e[11];let I=c,y;e[12]!==a?(y=a("Scaffold access rules"),e[12]=a,e[13]=y):y=e[13];let A;e[14]!==y?(A=(0,t.jsx)(fe,{children:y}),e[14]=y,e[15]=A):A=e[15];let P;e[16]!==a?(P=a("Writes a new deny-by-default policy file under lunora/, or wires one into a procedure, then reruns codegen. Local dev only."),e[16]=a,e[17]=P):P=e[17];let E;e[18]!==P?(E=(0,t.jsx)(ue,{children:P}),e[18]=P,e[19]=E):E=e[19];let L;e[20]!==E||e[21]!==A?(L=(0,t.jsxs)(pe,{children:[A,E]}),e[20]=E,e[21]=A,e[22]=L):L=e[22];let H=i==="scaffold"?"default":"outline",O;e[23]!==a?(O=a("New policy file"),e[23]=a,e[24]=O):O=e[24];let R;e[25]!==H||e[26]!==O?(R=(0,t.jsx)(F,{"data-testid":"policy-scaffolder-new",onClick:x,size:"xs",type:"button",variant:H,children:O}),e[25]=H,e[26]=O,e[27]=R):R=e[27];let m=i==="wire"?"default":"outline",u;e[28]!==a?(u=a("Wire into a procedure"),e[28]=a,e[29]=u):u=e[29];let q;e[30]!==m||e[31]!==u?(q=(0,t.jsx)(F,{"data-testid":"policy-scaffolder-wire",onClick:I,size:"xs",type:"button",variant:m,children:u}),e[30]=m,e[31]=u,e[32]=q):q=e[32];let D;e[33]!==R||e[34]!==q?(D=(0,t.jsxs)("div",{className:"flex flex-wrap gap-2",children:[R,q]}),e[33]=R,e[34]=q,e[35]=D):D=e[35];let J;e[36]!==l||e[37]!==r.policyName||e[38]!==r.tableName||e[39]!==i||e[40]!==w||e[41]!==a?(J=i==="scaffold"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"policy-scaffolder-new-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(T,{htmlFor:"policy-scaffolder-name",children:a("Policy name")}),(0,t.jsx)($,{"data-testid":"policy-scaffolder-name",id:"policy-scaffolder-name",name:"policyName",onChange:g,value:r.policyName})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(T,{htmlFor:"policy-scaffolder-table",children:a("Table name")}),(0,t.jsx)($,{"data-testid":"policy-scaffolder-table",id:"policy-scaffolder-table",name:"tableName",onChange:g,value:r.tableName})]}),(0,t.jsx)(F,{"data-testid":"policy-scaffolder-create",disabled:l||r.policyName.trim()===""||r.tableName.trim()==="",onClick:w,size:"xs",type:"button",children:a(l?"Creating\u2026":"Create policy file")}),(0,t.jsx)(F,{onClick:v,size:"xs",type:"button",variant:"ghost",children:a("Cancel")})]}),e[36]=l,e[37]=r.policyName,e[38]=r.tableName,e[39]=i,e[40]=w,e[41]=a,e[42]=J):J=e[42];let U;e[43]!==l||e[44]!==r.exportName||e[45]!==r.filePath||e[46]!==r.policies||e[47]!==i||e[48]!==_||e[49]!==a?(U=i==="wire"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-wrap items-end gap-2","data-testid":"policy-scaffolder-wire-form",children:[(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(T,{htmlFor:"policy-scaffolder-file",children:a("Procedure file path")}),(0,t.jsx)($,{"data-testid":"policy-scaffolder-file",id:"policy-scaffolder-file",name:"filePath",onChange:g,value:r.filePath})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(T,{htmlFor:"policy-scaffolder-export",children:a("Exported procedure")}),(0,t.jsx)($,{"data-testid":"policy-scaffolder-export",id:"policy-scaffolder-export",name:"exportName",onChange:g,value:r.exportName})]}),(0,t.jsxs)("div",{className:"flex flex-col gap-1 text-xs",children:[(0,t.jsx)(T,{htmlFor:"policy-scaffolder-policies",children:a("Policy set identifier")}),(0,t.jsx)($,{"data-testid":"policy-scaffolder-policies",id:"policy-scaffolder-policies",name:"policies",onChange:g,value:r.policies})]}),(0,t.jsx)(F,{"data-testid":"policy-scaffolder-apply",disabled:l||r.filePath.trim()===""||r.exportName.trim()===""||r.policies.trim()==="",onClick:_,size:"xs",type:"button",children:a(l?"Wiring\u2026":"Wire RLS")}),(0,t.jsx)(F,{onClick:v,size:"xs",type:"button",variant:"ghost",children:a("Cancel")})]}),e[43]=l,e[44]=r.exportName,e[45]=r.filePath,e[46]=r.policies,e[47]=i,e[48]=_,e[49]=a,e[50]=U):U=e[50];let K;e[51]!==o?(K=o?.kind==="error"&&(0,t.jsx)("p",{className:"mt-3 text-sm text-destructive","data-testid":"policy-scaffolder-error",role:"alert",children:o.message}),e[51]=o,e[52]=K):K=e[52];let W;e[53]!==o?.kind||e[54]!==a?(W=o?.kind==="needs-manual-edit"&&(0,t.jsx)("p",{className:"mt-3 text-sm text-amber-600 dark:text-amber-500","data-testid":"policy-scaffolder-manual",role:"alert",children:a("This change must be made by hand \u2014 the scaffolder only adds new, deny-by-default rules.")}),e[53]=o?.kind,e[54]=a,e[55]=W):W=e[55];let B;e[56]!==o||e[57]!==a?(B=o?.kind==="ok"&&(0,t.jsxs)("div",{className:"mt-3 flex flex-col gap-1","data-testid":"policy-scaffolder-ok",children:[(0,t.jsx)("p",{className:"text-sm text-emerald-600 dark:text-emerald-500",children:a("Scaffolded {label} and reran codegen. Fill in the `when` predicates before relying on it.",{label:o.label})}),o.diagnostics.length>0&&(0,t.jsx)("ul",{className:"flex flex-col gap-0.5","data-testid":"policy-scaffolder-diagnostics",children:o.diagnostics.map(Ke)})]}),e[56]=o,e[57]=a,e[58]=B):B=e[58];let Q;e[59]!==D||e[60]!==J||e[61]!==U||e[62]!==K||e[63]!==W||e[64]!==B?(Q=(0,t.jsxs)(ne,{children:[D,J,U,K,W,B]}),e[59]=D,e[60]=J,e[61]=U,e[62]=K,e[63]=W,e[64]=B,e[65]=Q):Q=e[65];let X;return e[66]!==L||e[67]!==Q?(X=(0,t.jsxs)(se,{"data-testid":"policy-scaffolder",size:"sm",children:[L,Q]}),e[66]=L,e[67]=Q,e[68]=X):X=e[68],X},"Je");function Ke(e){return(0,t.jsx)("li",{className:"font-mono text-[11px] text-destructive",children:e},e)}d(Ke,"De");var st=d(({functions:e,runAsIdentity:a=!1,schemaEditable:i=!1}={})=>{let s=Y(),[l,n]=(0,p.useState)(void 0),o=d((f,r,b)=>{b!==""&&n(h=>({functionPath:b,nonce:(h?.nonce??0)+1}))},"o");return(0,t.jsxs)("div",{className:"flex flex-col gap-8","data-testid":"lunora-permissions",children:[(0,t.jsxs)("section",{className:"flex flex-col gap-3",children:[(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:s("Permissions")})}),(0,t.jsx)(Le,{onProbe:o})]}),(0,t.jsx)("section",{className:"flex flex-col gap-3",children:(0,t.jsxs)(se,{className:"gap-0 py-0",children:[(0,t.jsx)("header",{className:"border-b border-border px-4 py-3",children:(0,t.jsx)("span",{className:"font-mono text-[11px] tracking-wide text-muted-foreground uppercase",children:s("Probe")})}),(0,t.jsxs)(ne,{className:"px-4 py-4",children:[(0,t.jsx)("p",{className:"mb-3 text-sm text-muted-foreground",children:s("Pick a function and an identity, then run it to see the access outcome.")}),(0,t.jsx)($e,{functions:e,prefill:l,runAsIdentity:a})]})]})}),i&&(0,t.jsx)("section",{className:"flex flex-col gap-2",children:(0,t.jsx)(Ue,{})})]})},"nt");export{st as PermissionsPanel};
@@ -1 +1 @@
1
- import{a as C}from"./chunk-V53KNYRN.js";import{a as T}from"./chunk-5Y3QLNWX.js";import{b as v}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as k}from"./chunk-ZBVGZ4YA.js";import"./chunk-XXQUMVWH.js";import"./chunk-56Q3NCCQ.js";import"./chunk-QLQADHFE.js";import{a as S}from"./chunk-VDW32UET.js";import{c as b}from"./chunk-KMT6UDR7.js";import"./chunk-WVU7GHTG.js";import"./chunk-XBDKZZ67.js";import{a as c}from"./chunk-XQCVZAGU.js";import{a as w,b as A,c as O,d as f,e as l,f as s}from"./chunk-WJQLNYGX.js";import{a as y,e as N}from"./chunk-WQH3LT2P.js";import{d as x}from"./chunk-IUYFXK4X.js";import"./chunk-BR5GIQWK.js";import{a as n,e as p,f as $,h as L}from"./chunk-3XIESWL4.js";var F=p($(),1);var e=p(L(),1);var q=n(a=>{let t=a.trim();if(t.length===0)return{context:void 0,error:null};try{let o=JSON.parse(t);return o===null||typeof o!="object"||Array.isArray(o)?{context:void 0,error:"Targeting context must be a JSON object."}:{context:o,error:null}}catch{return{context:void 0,error:"Targeting context is not valid JSON."}}},"L"),D='{ "targetingKey": "user-123", "plan": "premium" }',M=n(a=>a.type==="object"?JSON.stringify(a.value):String(a.value),"V"),Y=n(({initialShardKey:a=""})=>{let t=x(),[o,j]=(0,F.useState)(""),{context:g,error:m}=q(o),I=g===void 0?{}:{context:g},{data:i,error:J,errorSource:K,liveError:E}=b(S.listFlags,I,{live:!0,shardKey:a}),u=i!==void 0,U=i?.configured??!1,h=Array.isArray(i?.flags)?[...i.flags].toSorted((r,V)=>r.key.localeCompare(V.key)):[],d;return u&&!U?d=(0,e.jsx)(c,{description:t("No @lunora/flags provider is wired in this deployment. Add lunora/flags.ts with defineFlags({ provider }) to gate code paths on feature flags."),testId:"flags-unconfigured",title:t("No flags provider configured")}):u&&h.length===0?d=(0,e.jsx)(c,{description:t('A flags provider is configured, but no handler reads a flag yet. Call ctx.flags.boolean("key", false) in a query, mutation, or action.'),testId:"flags-empty",title:t("No flags read")}):d=(0,e.jsx)(y,{className:"overflow-hidden py-0",children:(0,e.jsx)(N,{className:"px-0",children:(0,e.jsxs)(w,{"data-testid":"flags-table",children:[(0,e.jsx)(A,{children:(0,e.jsxs)(f,{children:[(0,e.jsx)(l,{children:t("Key")}),(0,e.jsx)(l,{children:t("Type")}),(0,e.jsx)(l,{children:t("Value")}),(0,e.jsx)(l,{children:t("Reason")}),(0,e.jsx)(l,{children:t("Variant")})]})}),(0,e.jsx)(O,{children:h.map(r=>(0,e.jsxs)(f,{"data-testid":`flags-row-${r.key}`,children:[(0,e.jsx)(s,{className:"font-mono text-xs",children:r.key}),(0,e.jsx)(s,{className:"font-mono text-xs text-muted-foreground",children:r.type}),(0,e.jsx)(s,{className:"font-mono text-xs",children:M(r)}),(0,e.jsx)(s,{children:r.errorCode===void 0?(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:r.reason??"\u2014"}):(0,e.jsx)(v,{"data-testid":`flags-error-${r.key}`,variant:"destructive",children:r.errorCode})}),(0,e.jsx)(s,{className:"font-mono text-xs text-muted-foreground",children:r.variant??"\u2014"})]},r.key))})]})})}),(0,e.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-flags-panel",children:[J!==null&&(0,e.jsx)(k,{error:K,testId:"flags-error"}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:t('Feature flags are read in code with ctx.flags.<type>("key", default). They evaluate through the OpenFeature provider configured in lunora/flags.ts; edit the targeting context below to see how each flag resolves for a given audience.')}),(0,e.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,e.jsx)(T,{htmlFor:"flags-targeting-context",children:t("Targeting context (JSON)")}),(0,e.jsx)(C,{className:"font-mono text-xs","data-testid":"flags-context-input",id:"flags-targeting-context",onChange:n(r=>{j(r.target.value)},"onChange"),placeholder:D,rows:3,value:o}),m!==null&&(0,e.jsx)("p",{className:"text-xs text-destructive","data-testid":"flags-context-error",role:"alert",children:t(m)}),E!==void 0&&(0,e.jsx)("p",{className:"text-xs text-amber-600 dark:text-amber-500","data-testid":"flags-live-error",role:"alert",children:t("Live updates unavailable; showing the last evaluation.")})]}),d]})},"X");export{Y as default};
1
+ import{a as C}from"./chunk-V53KNYRN.js";import{a as T}from"./chunk-5Y3QLNWX.js";import{b as v}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as k}from"./chunk-CAOA5AM4.js";import"./chunk-XXQUMVWH.js";import"./chunk-VR3OBMGZ.js";import"./chunk-QLQADHFE.js";import{a as S}from"./chunk-VDW32UET.js";import{c as b}from"./chunk-FZ2N52BV.js";import"./chunk-BDHAGUAY.js";import"./chunk-XBDKZZ67.js";import{a as c}from"./chunk-XQCVZAGU.js";import{a as w,b as A,c as O,d as f,e as l,f as s}from"./chunk-WJQLNYGX.js";import{a as y,e as N}from"./chunk-WQH3LT2P.js";import{d as x}from"./chunk-IUYFXK4X.js";import"./chunk-5DVJR52Z.js";import{a as n,e as p,f as $,h as L}from"./chunk-3XIESWL4.js";var F=p($(),1);var e=p(L(),1);var q=n(a=>{let t=a.trim();if(t.length===0)return{context:void 0,error:null};try{let o=JSON.parse(t);return o===null||typeof o!="object"||Array.isArray(o)?{context:void 0,error:"Targeting context must be a JSON object."}:{context:o,error:null}}catch{return{context:void 0,error:"Targeting context is not valid JSON."}}},"L"),D='{ "targetingKey": "user-123", "plan": "premium" }',M=n(a=>a.type==="object"?JSON.stringify(a.value):String(a.value),"V"),Y=n(({initialShardKey:a=""})=>{let t=x(),[o,j]=(0,F.useState)(""),{context:g,error:m}=q(o),I=g===void 0?{}:{context:g},{data:i,error:J,errorSource:K,liveError:E}=b(S.listFlags,I,{live:!0,shardKey:a}),u=i!==void 0,U=i?.configured??!1,h=Array.isArray(i?.flags)?[...i.flags].toSorted((r,V)=>r.key.localeCompare(V.key)):[],d;return u&&!U?d=(0,e.jsx)(c,{description:t("No @lunora/flags provider is wired in this deployment. Add lunora/flags.ts with defineFlags({ provider }) to gate code paths on feature flags."),testId:"flags-unconfigured",title:t("No flags provider configured")}):u&&h.length===0?d=(0,e.jsx)(c,{description:t('A flags provider is configured, but no handler reads a flag yet. Call ctx.flags.boolean("key", false) in a query, mutation, or action.'),testId:"flags-empty",title:t("No flags read")}):d=(0,e.jsx)(y,{className:"overflow-hidden py-0",children:(0,e.jsx)(N,{className:"px-0",children:(0,e.jsxs)(w,{"data-testid":"flags-table",children:[(0,e.jsx)(A,{children:(0,e.jsxs)(f,{children:[(0,e.jsx)(l,{children:t("Key")}),(0,e.jsx)(l,{children:t("Type")}),(0,e.jsx)(l,{children:t("Value")}),(0,e.jsx)(l,{children:t("Reason")}),(0,e.jsx)(l,{children:t("Variant")})]})}),(0,e.jsx)(O,{children:h.map(r=>(0,e.jsxs)(f,{"data-testid":`flags-row-${r.key}`,children:[(0,e.jsx)(s,{className:"font-mono text-xs",children:r.key}),(0,e.jsx)(s,{className:"font-mono text-xs text-muted-foreground",children:r.type}),(0,e.jsx)(s,{className:"font-mono text-xs",children:M(r)}),(0,e.jsx)(s,{children:r.errorCode===void 0?(0,e.jsx)("span",{className:"font-mono text-xs text-muted-foreground",children:r.reason??"\u2014"}):(0,e.jsx)(v,{"data-testid":`flags-error-${r.key}`,variant:"destructive",children:r.errorCode})}),(0,e.jsx)(s,{className:"font-mono text-xs text-muted-foreground",children:r.variant??"\u2014"})]},r.key))})]})})}),(0,e.jsxs)("div",{className:"flex flex-col gap-6","data-testid":"lunora-flags-panel",children:[J!==null&&(0,e.jsx)(k,{error:K,testId:"flags-error"}),(0,e.jsx)("p",{className:"text-sm text-muted-foreground",children:t('Feature flags are read in code with ctx.flags.<type>("key", default). They evaluate through the OpenFeature provider configured in lunora/flags.ts; edit the targeting context below to see how each flag resolves for a given audience.')}),(0,e.jsxs)("div",{className:"flex flex-col gap-2",children:[(0,e.jsx)(T,{htmlFor:"flags-targeting-context",children:t("Targeting context (JSON)")}),(0,e.jsx)(C,{className:"font-mono text-xs","data-testid":"flags-context-input",id:"flags-targeting-context",onChange:n(r=>{j(r.target.value)},"onChange"),placeholder:D,rows:3,value:o}),m!==null&&(0,e.jsx)("p",{className:"text-xs text-destructive","data-testid":"flags-context-error",role:"alert",children:t(m)}),E!==void 0&&(0,e.jsx)("p",{className:"text-xs text-amber-600 dark:text-amber-500","data-testid":"flags-live-error",role:"alert",children:t("Live updates unavailable; showing the last evaluation.")})]}),d]})},"X");export{Y as default};
@@ -0,0 +1 @@
1
+ import{m as h,n as v}from"./chunk-HFRJMPXJ.js";import{a as u,e as p,g as x,h as y,j as g}from"./chunk-3XIESWL4.js";var b=p(x(),1);var s=p(y(),1);var N={value:{colors:{dark:["var(--foreground)"],light:["var(--foreground)"]},label:""}},j=u(i=>{let e=(0,b.c)(12),{ariaLabel:c,className:m,series:l,testId:d}=i;if(l.length<2)return null;let t;e[0]!==l?(t=l.slice(-40).map(w),e[0]=l,e[1]=t):t=e[1];let f=t,a;e[2]!==m?(a=g("h-6 w-[120px]",m),e[2]=m,e[3]=a):a=e[3];let o;e[4]===Symbol.for("react.memo_cache_sentinel")?(o=(0,s.jsx)(v,{dataKey:"value"}),e[4]=o):o=e[4];let r;e[5]!==f?(r=(0,s.jsx)(h,{animationType:"none",barCategoryGap:1,className:"h-full w-full",config:N,data:f,children:o}),e[5]=f,e[6]=r):r=e[6];let n;return e[7]!==c||e[8]!==a||e[9]!==r||e[10]!==d?(n=(0,s.jsx)("div",{"aria-label":c,className:a,"data-testid":d,role:"img",children:r}),e[7]=c,e[8]=a,e[9]=r,e[10]=d,e[11]=n):n=e[11],n},"S");function w(i,e){return{index:e,value:i}}u(w,"b");export{j as a};
@@ -0,0 +1 @@
1
+ import{a as k}from"./chunk-AXQU7ULF.js";import{a as U}from"./chunk-XFGE43TZ.js";import"./chunk-KUVMORDQ.js";import"./chunk-HFRJMPXJ.js";import"./chunk-4UOFSGUS.js";import"./chunk-CZZWYUTR.js";import{a as E}from"./chunk-3CWGJYBB.js";import{a as A}from"./chunk-RMN2JN4S.js";import"./chunk-GRL5MG3Z.js";import"./chunk-SMIESS7P.js";import"./chunk-7T7UOTYK.js";import"./chunk-CFPZYHPY.js";import"./chunk-T6VMSOBB.js";import"./chunk-7QIFDWQV.js";import"./chunk-2OUPA2WJ.js";import{b as j}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as F}from"./chunk-CAOA5AM4.js";import"./chunk-XXQUMVWH.js";import"./chunk-VR3OBMGZ.js";import"./chunk-QLQADHFE.js";import{a as T}from"./chunk-VDW32UET.js";import{c as S}from"./chunk-FZ2N52BV.js";import"./chunk-BDHAGUAY.js";import"./chunk-XBDKZZ67.js";import{a as O}from"./chunk-XQCVZAGU.js";import{a as w,e as C}from"./chunk-WQH3LT2P.js";import{d as I,r as $}from"./chunk-IUYFXK4X.js";import"./chunk-5DVJR52Z.js";import{a as p,e as K,g as D,h as H}from"./chunk-3XIESWL4.js";var M=K(D(),1);var m=K(H(),1);var L=p(r=>r.length===0?void 0:{max:Math.max(...r),mean:r.reduce((e,t)=>e+t,0)/r.length,min:Math.min(...r)},"F"),q=/^gen_ai\.evaluation\.(.+)\.score$/u,B=p(r=>{let e=[];for(let t of r)for(let s of t.spans)for(let[a,l]of Object.entries(s.attributes??{})){let o=q.exec(a);if(!o||typeof l!="number")continue;let i=o[1],c=s.attributes?.[`gen_ai.evaluation.${i}.label`];e.push({...typeof c=="string"?{label:c}:{},name:i,score:l,spanName:s.name,startTs:t.startTs+s.offsetMs,traceId:t.traceId})}return e.toSorted((t,s)=>s.startTs-t.startTs)},"U"),R=p(r=>{let e=[];for(let t of r?.series??[]){let s=q.exec(t.name);s&&e.push({name:s[1],points:t.points})}return e},"B"),V=p((r,e)=>{let t=new Set([...r.map(a=>a.name),...e.map(a=>a.name)]),s=[];for(let a of t){let l=r.filter(n=>n.name===a),o=e.find(n=>n.name===a)?.points??[],i=o.at(-1)?.last??l[0]?.score,c=o.length>0?{max:Math.max(...o.map(n=>n.max)),mean:o.reduce((n,d)=>n+d.sum,0)/o.reduce((n,d)=>n+d.count,0),min:Math.min(...o.map(n=>n.min))}:L(l.map(n=>n.score));s.push({...i===void 0?{}:{latest:i},...c,name:a,points:o,runs:l})}return s.toSorted((a,l)=>a.name.localeCompare(l.name))},"H"),z=p(r=>Array.isArray(r?.traces)?r.traces:[],"L"),N=p(r=>r===void 0?"\u2014":r.toFixed(2),"N"),G=p(r=>{let e=(0,M.c)(34),{card:t,onOpenTrace:s}=r,a=I(),l;e[0]!==t.name?(l=(0,m.jsx)("h3",{className:"font-mono text-sm font-semibold text-foreground","data-testid":"ev-name",children:t.name}),e[0]=t.name,e[1]=l):l=e[1];let o;e[2]!==t.latest?(o=N(t.latest),e[2]=t.latest,e[3]=o):o=e[3];let i;e[4]!==o?(i=(0,m.jsx)("span",{className:"font-mono text-lg text-foreground","data-testid":"ev-latest",children:o}),e[4]=o,e[5]=i):i=e[5];let c;e[6]!==l||e[7]!==i?(c=(0,m.jsxs)("div",{className:"flex items-baseline justify-between gap-3",children:[l,i]}),e[6]=l,e[7]=i,e[8]=c):c=e[8];let n;e[9]!==t.max||e[10]!==t.mean||e[11]!==t.min||e[12]!==a?(n=a("min {min} \xB7 mean {mean} \xB7 max {max}",{max:N(t.max),mean:N(t.mean),min:N(t.min)}),e[9]=t.max,e[10]=t.mean,e[11]=t.min,e[12]=a,e[13]=n):n=e[13];let d;e[14]!==n?(d=(0,m.jsx)("p",{className:"font-mono text-xs text-muted-foreground","data-testid":"ev-summary",children:n}),e[14]=n,e[15]=d):d=e[15];let f;e[16]!==t.name||e[17]!==t.points||e[18]!==a?(f=t.points.length>1?(0,m.jsx)(k,{ariaLabel:a("Score trend for {name}",{name:t.name}),className:"h-10 w-full",series:t.points.map(J),testId:"ev-trend"}):(0,m.jsx)("p",{className:"text-xs text-muted-foreground","data-testid":"ev-no-trend",children:a("No durable history yet \u2014 pass ctx.metrics to recordEvaluation to chart a trend.")}),e[16]=t.name,e[17]=t.points,e[18]=a,e[19]=f):f=e[19];let h;if(e[20]!==t.runs||e[21]!==s||e[22]!==a){let v;e[24]!==s||e[25]!==a?(v=p(u=>(0,m.jsxs)("div",{className:"flex items-center justify-between gap-2 font-mono text-xs","data-testid":"ev-run",children:[(0,m.jsxs)("span",{className:"truncate text-muted-foreground",children:[$(u.startTs)," \xB7 ",u.spanName]}),(0,m.jsxs)("span",{className:"flex items-center gap-2",children:[u.label===void 0?null:(0,m.jsx)(j,{variant:"outline",children:u.label}),(0,m.jsx)("span",{className:"text-foreground",children:N(u.score)}),s===void 0?null:(0,m.jsx)("button",{className:"text-muted-foreground underline-offset-2 hover:underline",onClick:p(()=>{s(u.traceId)},"onClick"),title:a("Open the trace {trace}",{trace:u.traceId}),type:"button",children:u.traceId.slice(0,8)})]})]},`${u.traceId}:${u.spanName}`),"x"),e[24]=s,e[25]=a,e[26]=v):v=e[26],h=t.runs.slice(0,5).map(v),e[20]=t.runs,e[21]=s,e[22]=a,e[23]=h}else h=e[23];let x;e[27]!==h?(x=(0,m.jsx)("div",{className:"flex flex-col gap-1",children:h}),e[27]=h,e[28]=x):x=e[28];let g;return e[29]!==c||e[30]!==d||e[31]!==f||e[32]!==x?(g=(0,m.jsx)(w,{"data-testid":"ev-card",children:(0,m.jsxs)(C,{className:"flex flex-col gap-3 p-4",children:[c,d,f,x]})}),e[29]=c,e[30]=d,e[31]=f,e[32]=x,e[33]=g):g=e[33],g},"R"),oe=p(r=>{let e=(0,M.c)(19),{initialShardKey:t}=r,s=I(),{queryShardKey:a,setShardKey:l,shardKey:o}=E(t),i=U(a),c;e[0]===Symbol.for("react.memo_cache_sentinel")?(c={},e[0]=c):c=e[0];let n;e[1]!==a?(n={live:!0,shardKey:a},e[1]=a,e[2]=n):n=e[2];let{data:d,error:f}=S(T.getTraces,c,n),h;e[3]===Symbol.for("react.memo_cache_sentinel")?(h={},e[3]=h):h=e[3];let x;e[4]!==a?(x={live:!0,shardKey:a},e[4]=a,e[5]=x):x=e[5];let{data:g}=S(T.getMetricHistory,h,x),v;if(e[6]!==d||e[7]!==f||e[8]!==g||e[9]!==i||e[10]!==l||e[11]!==o||e[12]!==s){let u=V(B(z(d)),R(g)),y;e[14]!==l||e[15]!==o?(y=(0,m.jsx)(A,{onChange:l,testId:"ev-shard-input",value:o}),e[14]=l,e[15]=o,e[16]=y):y=e[16];let b;e[17]!==f?(b=f===null?null:(0,m.jsx)(F,{error:f,testId:"ev-error"}),e[17]=f,e[18]=b):b=e[18],v=(0,m.jsxs)("section",{className:"flex flex-col gap-4","data-testid":"ev-panel",children:[y,b,u.length===0?(0,m.jsx)(O,{description:s("Call recordEvaluation from a graded run and its score shows up here."),testId:"ev-empty",title:s("No evals recorded")}):(0,m.jsx)("div",{className:"grid gap-3 md:grid-cols-2",children:u.map(_=>(0,m.jsx)(G,{card:_,onOpenTrace:i},_.name))})]}),e[6]=d,e[7]=f,e[8]=g,e[9]=i,e[10]=l,e[11]=o,e[12]=s,e[13]=v}else v=e[13];return v},"ne");function J(r){return r.last}p(J,"V");export{oe as default};
@@ -0,0 +1,11 @@
1
+ import{c as p}from"./chunk-5DVJR52Z.js";import{a,e as P,f as $,g as mt,h as Ue}from"./chunk-3XIESWL4.js";var L=class{static{a(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 br=class extends L{static{a(this,"FocusManager")}#e;#t;#r;constructor(){super(),this.#r=t=>{if(typeof window<"u"&&window.addEventListener){let e=a(()=>t(),"listener");return window.addEventListener("visibilitychange",e,!1),()=>{window.removeEventListener("visibilitychange",e)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#r=t,this.#t?.(),this.#t=t(e=>{typeof e=="boolean"?this.setFocused(e):this.onFocus()})}setFocused(t){this.#e!==t&&(this.#e=t,this.onFocus())}onFocus(){let t=this.isFocused();this.listeners.forEach(e=>{e(t)})}isFocused(){return typeof this.#e=="boolean"?this.#e:globalThis.document?.visibilityState!=="hidden"}},X=new br;var vr={setTimeout:a((t,e)=>setTimeout(t,e),"setTimeout"),clearTimeout:a(t=>clearTimeout(t),"clearTimeout"),setInterval:a((t,e)=>setInterval(t,e),"setInterval"),clearInterval:a(t=>clearInterval(t),"clearInterval")},gr=class{static{a(this,"TimeoutManager")}#e=vr;#t=!1;setTimeoutProvider(t){this.#e=t}setTimeout(t,e){return this.#e.setTimeout(t,e)}clearTimeout(t){this.#e.clearTimeout(t)}setInterval(t,e){return this.#e.setInterval(t,e)}clearInterval(t){this.#e.clearInterval(t)}},Q=new gr;function yt(t){setTimeout(t,0)}a(yt,"systemSetTimeoutZero");var Ke=typeof window>"u"||"Deno"in globalThis;function g(){}a(g,"noop");function gt(t,e){return typeof t=="function"?t(e):t}a(gt,"functionalUpdate");function ie(t){return typeof t=="number"&&t>=0&&t!==1/0}a(ie,"isValidTimeout");function me(t,e){return Math.max(t+(e||0)-Date.now(),0)}a(me,"timeUntilStale");function x(t,e){return typeof t=="function"?t(e):t}a(x,"resolveStaleTime");function I(t,e){return typeof t=="function"?t(e):t}a(I,"resolveQueryBoolean");function ye(t,e){let{type:r="all",exact:s,fetchStatus:i,predicate:n,queryKey:o,stale:c}=t;if(o){if(s){if(e.queryHash!==ne(o,e.options))return!1}else if(!K(e.queryKey,o))return!1}if(r!=="all"){let u=e.isActive();if(r==="active"&&!u||r==="inactive"&&u)return!1}return!(typeof c=="boolean"&&e.isStale()!==c||i&&i!==e.state.fetchStatus||n&&!n(e))}a(ye,"matchQuery");function be(t,e){let{exact:r,status:s,predicate:i,mutationKey:n}=t;if(n){if(!e.options.mutationKey)return!1;if(r){if(H(e.options.mutationKey)!==H(n))return!1}else if(!K(e.options.mutationKey,n))return!1}return!(s&&e.state.status!==s||i&&!i(e))}a(be,"matchMutation");function ne(t,e){return(e?.queryKeyHashFn||H)(t)}a(ne,"hashQueryKeyByOptions");function H(t){return JSON.stringify(t,(e,r)=>qe(r)?Object.keys(r).sort().reduce((s,i)=>(s[i]=r[i],s),{}):r)}a(H,"hashKey");function K(t,e){if(t===e)return!0;if(typeof t!=typeof e)return!1;if(t&&e&&typeof t=="object"&&typeof e=="object"){if(Array.isArray(t)&&Array.isArray(e)){for(let s=0;s<e.length;s++)if(!K(t[s],e[s]))return!1;return!0}let r=Object.keys(e);for(let s of r)if(!K(t[s],e[s]))return!1;return!0}return!1}a(K,"partialMatchKey");var Sr=Object.prototype.hasOwnProperty;function Ne(t,e,r=0){if(t===e)return t;if(r>500)return e;let s=bt(t)&&bt(e);if(!s&&!(qe(t)&&qe(e)))return e;let n=(s?t:Object.keys(t)).length,o=s?e:Object.keys(e),c=o.length,u=s?new Array(c):{},d=0;for(let h=0;h<c;h++){let l=s?h:o[h],f=t[l],m=e[l];if(f===m){u[l]=f,(s?h<n:Sr.call(t,l))&&d++;continue}if(f===null||m===null||typeof f!="object"||typeof m!="object"){u[l]=m;continue}let y=Ne(f,m,r+1);u[l]=y,y===f&&d++}return n===c&&d===n?t:u}a(Ne,"replaceEqualDeep");function ve(t,e){if(!e||Object.keys(t).length!==Object.keys(e).length)return!1;for(let r in t)if(t[r]!==e[r])return!1;return!0}a(ve,"shallowEqualObjects");function bt(t){return Array.isArray(t)&&t.length===Object.keys(t).length}a(bt,"isPlainArray");function qe(t){if(!vt(t))return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(!vt(r)||!r.hasOwnProperty("isPrototypeOf")||Object.getPrototypeOf(t)!==Object.prototype)}a(qe,"isPlainObject");function vt(t){return Object.prototype.toString.call(t)==="[object Object]"}a(vt,"hasObjectPrototype");function St(t){return new Promise(e=>{Q.setTimeout(e,t)})}a(St,"sleep");function ae(t,e,r){return typeof r.structuralSharing=="function"?r.structuralSharing(t,e):r.structuralSharing!==!1?Ne(t,e):e}a(ae,"replaceData");function wr(t){return t}a(wr,"keepPreviousData");function wt(t,e,r=0){let s=[...t,e];return r&&s.length>r?s.slice(1):s}a(wt,"addToEnd");function Ct(t,e,r=0){let s=[e,...t];return r&&s.length>r?s.slice(0,-1):s}a(Ct,"addToStart");var Y=Symbol();function ge(t,e){return!t.queryFn&&e?.initialPromise?()=>e.initialPromise:!t.queryFn||t.queryFn===Y?()=>Promise.reject(new Error(`Missing queryFn: '${t.queryHash}'`)):t.queryFn}a(ge,"ensureQueryFn");function Se(t,e){return typeof t=="function"?t(...e):!!t}a(Se,"shouldThrowError");function kt(t,e,r){let s=!1,i;return Object.defineProperty(t,"signal",{enumerable:!0,get:a(()=>(i??=e(),s||(s=!0,i.aborted?r():i.addEventListener("abort",r,{once:!0})),i),"get")}),t}a(kt,"addConsumeAwareSignal");var D=(()=>{let t=a(()=>Ke,"isServerFn");return{isServer(){return t()},setIsServer(e){t=e}}})();function oe(){let t,e,r=new Promise((i,n)=>{t=i,e=n});r.status="pending",r.catch(()=>{});function s(i){Object.assign(r,i),delete r.resolve,delete r.reject}return a(s,"finalize"),r.resolve=i=>{s({status:"fulfilled",value:i}),t(i)},r.reject=i=>{s({status:"rejected",reason:i}),e(i)},r}a(oe,"pendingThenable");var It=yt;function Cr(){let t=[],e=0,r=a(c=>{c()},"notifyFn"),s=a(c=>{c()},"batchNotifyFn"),i=It,n=a(c=>{e?t.push(c):i(()=>{r(c)})},"schedule"),o=a(()=>{let c=t;t=[],c.length&&i(()=>{s(()=>{c.forEach(u=>{r(u)})})})},"flush");return{batch:a(c=>{let u;e++;try{u=c()}finally{e--,e||o()}return u},"batch"),batchCalls:a(c=>(...u)=>{n(()=>{c(...u)})},"batchCalls"),schedule:n,setNotifyFunction:a(c=>{r=c},"setNotifyFunction"),setBatchNotifyFunction:a(c=>{s=c},"setBatchNotifyFunction"),setScheduler:a(c=>{i=c},"setScheduler")}}a(Cr,"createNotifyManager");var v=Cr();var kr=class extends L{static{a(this,"OnlineManager")}#e=!0;#t;#r;constructor(){super(),this.#r=t=>{if(typeof window<"u"&&window.addEventListener){let e=a(()=>t(!0),"onlineListener"),r=a(()=>t(!1),"offlineListener");return window.addEventListener("online",e,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",e),window.removeEventListener("offline",r)}}}}onSubscribe(){this.#t||this.setEventListener(this.#r)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(t){this.#r=t,this.#t?.(),this.#t=t(this.setOnline.bind(this))}setOnline(t){this.#e!==t&&(this.#e=t,this.listeners.forEach(r=>{r(t)}))}isOnline(){return this.#e}},Z=new kr;function Ir(t){return Math.min(1e3*2**t,3e4)}a(Ir,"defaultRetryDelay");function Be(t){return(t??"online")==="online"?Z.isOnline():!0}a(Be,"canFetch");var we=class extends Error{static{a(this,"CancelledError")}constructor(t){super("CancelledError"),this.revert=t?.revert,this.silent=t?.silent}};function Ce(t){let e=!1,r=0,s,i=oe(),n=a(()=>i.status!=="pending","isResolved"),o=a(b=>{if(!n()){let w=new we(b);f(w),t.onCancel?.(w)}},"cancel"),c=a(()=>{e=!0},"cancelRetry"),u=a(()=>{e=!1},"continueRetry"),d=a(()=>X.isFocused()&&(t.networkMode==="always"||Z.isOnline())&&t.canRun(),"canContinue"),h=a(()=>Be(t.networkMode)&&t.canRun(),"canStart"),l=a(b=>{n()||(s?.(),i.resolve(b))},"resolve"),f=a(b=>{n()||(s?.(),i.reject(b))},"reject"),m=a(()=>new Promise(b=>{s=a(w=>{(n()||d())&&b(w)},"continueFn"),t.onPause?.()}).then(()=>{s=void 0,n()||t.onContinue?.()}),"pause"),y=a(()=>{if(n())return;let b,w=r===0?t.initialPromise:void 0;try{b=w??t.fn()}catch(E){b=Promise.reject(E)}Promise.resolve(b).then(l).catch(E=>{if(n())return;let M=t.retry??(D.isServer()?0:3),U=t.retryDelay??Ir,B=typeof U=="function"?U(r,E):U,j=M===!0||typeof M=="number"&&r<M||typeof M=="function"&&M(r,E);if(e||!j){f(E);return}r++,t.onFail?.(r,E),St(B).then(()=>d()?void 0:m()).then(()=>{e?f(E):y()})})},"run");return{promise:i,status:a(()=>i.status,"status"),cancel:o,continue:a(()=>(s?.(),i),"continue"),cancelRetry:c,continueRetry:u,canStart:h,start:a(()=>(h()?y():m().then(y),i),"start")}}a(Ce,"createRetryer");var ke=class{static{a(this,"Removable")}#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),ie(this.gcTime)&&(this.#e=Q.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(t){this.gcTime=Math.max(this.gcTime||0,t??(D.isServer()?1/0:300*1e3))}clearGcTimeout(){this.#e!==void 0&&(Q.clearTimeout(this.#e),this.#e=void 0)}};function Tt(t){return{onFetch:a((e,r)=>{let s=e.options,i=e.fetchOptions?.meta?.fetchMore?.direction,n=e.state.data?.pages||[],o=e.state.data?.pageParams||[],c={pages:[],pageParams:[]},u=0,d=a(async()=>{let h=!1,l=a(y=>{kt(y,()=>e.signal,()=>h=!0)},"addSignalProperty"),f=ge(e.options,e.fetchOptions),m=a(async(y,b,w)=>{if(h)return Promise.reject(e.signal.reason);if(b==null&&y.pages.length)return Promise.resolve(y);let M=a(()=>{let De={client:e.client,queryKey:e.queryKey,pageParam:b,direction:w?"backward":"forward",meta:e.options.meta};return l(De),De},"createQueryFnContext")(),U=await f(M),{maxPages:B}=e.options,j=w?Ct:wt;return{pages:j(y.pages,U,B),pageParams:j(y.pageParams,b,B)}},"fetchPage");if(i&&n.length){let y=i==="backward",b=y?Er:Et,w={pages:n,pageParams:o},E=b(s,w);c=await m(w,E,y)}else{let y=t??n.length;do{let b=u===0?o[0]??s.initialPageParam:Et(s,c);if(u>0&&b==null)break;c=await m(c,b),u++}while(u<y)}return c},"fetchFn");e.options.persister?e.fetchFn=()=>e.options.persister?.(d,{client:e.client,queryKey:e.queryKey,meta:e.options.meta,signal:e.signal},r):e.fetchFn=d},"onFetch")}}a(Tt,"infiniteQueryBehavior");function Et(t,{pages:e,pageParams:r}){let s=e.length-1;return e.length>0?t.getNextPageParam(e[s],e,r[s],r):void 0}a(Et,"getNextPageParam");function Er(t,{pages:e,pageParams:r}){return e.length>0?t.getPreviousPageParam?.(e[0],e,r[0],r):void 0}a(Er,"getPreviousPageParam");var Pt=class extends ke{static{a(this,"Query")}#e;#t;#r;#s;#n;#i;#o;#a;constructor(t){super(),this.#a=!1,this.#o=t.defaultOptions,this.setOptions(t.options),this.observers=[],this.#n=t.client,this.#s=this.#n.getQueryCache(),this.queryKey=t.queryKey,this.queryHash=t.queryHash,this.#t=Rt(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=Rt(this.options);e.data!==void 0&&(this.setState(Ot(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&this.#s.remove(this)}setData(t,e){let r=ae(this.state.data,t,this.options);return this.#c({data:r,type:"success",dataUpdatedAt:e?.updatedAt,manual:e?.manual}),r}setState(t){this.#c({type:"setState",state:t})}cancel(t){let e=this.#i?.promise;return this.#i?.cancel(t),e?e.then(g).catch(g):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return this.#t}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>I(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===Y||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>x(t.options.staleTime,this)==="static"):!1}isStale(){return this.getObserversCount()>0?this.observers.some(t=>t.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(t=0){return this.state.data===void 0?!0:t==="static"?!1:this.state.isInvalidated?!0:!me(this.state.dataUpdatedAt,t)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#i?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#i?.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),this.#s.notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(e=>e!==t),this.observers.length||(this.#i&&(this.#a||this.#h()?this.#i.cancel({revert:!0}):this.#i.cancelRetry()),this.scheduleGc()),this.#s.notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}#h(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"}invalidate(){this.state.isInvalidated||this.#c({type:"invalidate"})}async fetch(t,e){if(this.state.fetchStatus!=="idle"&&this.#i?.status()!=="rejected"){if(this.state.data!==void 0&&e?.cancelRefetch)this.cancel({silent:!0});else if(this.#i)return this.#i.continueRetry(),this.#i.promise}if(t&&this.setOptions(t),!this.options.queryFn){let u=this.observers.find(d=>d.options.queryFn);u&&this.setOptions(u.options)}let r=new AbortController,s=a(u=>{Object.defineProperty(u,"signal",{enumerable:!0,get:a(()=>(this.#a=!0,r.signal),"get")})},"addSignalProperty"),i=a(()=>{let u=ge(this.options,e),h=a(()=>{let l={client:this.#n,queryKey:this.queryKey,meta:this.meta};return s(l),l},"createQueryFnContext")();return this.#a=!1,this.options.persister?this.options.persister(u,h,this):u(h)},"fetchFn"),o=a(()=>{let u={fetchOptions:e,options:this.options,queryKey:this.queryKey,client:this.#n,state:this.state,fetchFn:i};return s(u),u},"createFetchContext")();(this.#e==="infinite"?Tt(this.options.pages):this.options.behavior)?.onFetch(o,this),this.#r=this.state,(this.state.fetchStatus==="idle"||this.state.fetchMeta!==o.fetchOptions?.meta)&&this.#c({type:"fetch",meta:o.fetchOptions?.meta}),this.#i=Ce({initialPromise:e?.initialPromise,fn:o.fetchFn,onCancel:a(u=>{u instanceof we&&u.revert&&this.setState({...this.#r,fetchStatus:"idle"}),r.abort()},"onCancel"),onFail:a((u,d)=>{this.#c({type:"failed",failureCount:u,error:d})},"onFail"),onPause:a(()=>{this.#c({type:"pause"})},"onPause"),onContinue:a(()=>{this.#c({type:"continue"})},"onContinue"),retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:a(()=>!0,"canRun")});try{let u=await this.#i.start();if(u===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(u),this.#s.config.onSuccess?.(u,this),this.#s.config.onSettled?.(u,this.state.error,this),u}catch(u){if(u instanceof we){if(u.silent)return this.#i.promise;if(u.revert){if(this.state.data===void 0)throw u;return this.state.data}}throw this.#c({type:"error",error:u}),this.#s.config.onError?.(u,this),this.#s.config.onSettled?.(this.state.data,u,this),u}finally{this.scheduleGc()}}#c(t){let e=a(r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...je(r.data,this.options),fetchMeta:t.meta??null};case"success":let s={...r,...Ot(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#r=t.manual?s:void 0,s;case"error":let i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}},"reducer");this.state=e(this.state),v.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),this.#s.notify({query:this,type:"updated",action:t})})}};function je(t,e){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:Be(e.networkMode)?"fetching":"paused",...t===void 0&&{error:null,status:"pending"}}}a(je,"fetchState");function Ot(t,e){return{data:t,dataUpdatedAt:e??Date.now(),error:null,isInvalidated:!1,status:"success"}}a(Ot,"successState");function Rt(t){let e=typeof t.initialData=="function"?t.initialData():t.initialData,r=e!==void 0,s=r?typeof t.initialDataUpdatedAt=="function"?t.initialDataUpdatedAt():t.initialDataUpdatedAt:0;return{data:e,dataUpdateCount:0,dataUpdatedAt:r?s??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:r?"success":"pending",fetchStatus:"idle"}}a(Rt,"getDefaultState");var He=class extends L{static{a(this,"QueryObserver")}constructor(t,e){super(),this.options=e,this.#e=t,this.#a=null,this.#o=oe(),this.bindMethods(),this.setOptions(e)}#e;#t=void 0;#r=void 0;#s=void 0;#n;#i;#o;#a;#h;#c;#p;#d;#l;#u;#m=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),At(this.#t,this.options)?this.#f():this.updateResult(),this.#g())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return $e(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return $e(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#S(),this.#w(),this.#t.removeObserver(this)}setOptions(t){let e=this.options,r=this.#t;if(this.options=this.#e.defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof I(this.options.enabled,this.#t)!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");this.#C(),this.#t.setOptions(this.options),e._defaulted&&!ve(this.options,e)&&this.#e.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#t,observer:this});let s=this.hasListeners();s&&Ft(this.#t,r,this.options,e)&&this.#f(),this.updateResult(),s&&(this.#t!==r||I(this.options.enabled,this.#t)!==I(e.enabled,this.#t)||x(this.options.staleTime,this.#t)!==x(e.staleTime,this.#t))&&this.#y();let i=this.#b();s&&(this.#t!==r||I(this.options.enabled,this.#t)!==I(e.enabled,this.#t)||i!==this.#u)&&this.#v(i)}getOptimisticResult(t){let e=this.#e.getQueryCache().build(this.#e,t),r=this.createResult(e,t);return Or(this,r)&&(this.#s=r,this.#i=this.options,this.#n=this.#t.state),r}getCurrentResult(){return this.#s}trackResult(t,e){return new Proxy(t,{get:a((r,s)=>(this.trackProp(s),e?.(s),s==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#o.status==="pending"&&this.#o.reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,s)),"get")})}trackProp(t){this.#m.add(t)}getCurrentQuery(){return this.#t}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){let e=this.#e.defaultQueryOptions(t),r=this.#e.getQueryCache().build(this.#e,e);return r.fetch().then(()=>this.createResult(r,e))}fetch(t){return this.#f({...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#s))}#f(t){this.#C();let e=this.#t.fetch(this.options,t);return t?.throwOnError||(e=e.catch(g)),e}#y(){this.#S();let t=x(this.options.staleTime,this.#t);if(D.isServer()||this.#s.isStale||!ie(t))return;let r=me(this.#s.dataUpdatedAt,t)+1;this.#d=Q.setTimeout(()=>{this.#s.isStale||this.updateResult()},r)}#b(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(this.#t):this.options.refetchInterval)??!1}#v(t){this.#w(),this.#u=t,!(D.isServer()||I(this.options.enabled,this.#t)===!1||!ie(this.#u)||this.#u===0)&&(this.#l=Q.setInterval(()=>{(this.options.refetchIntervalInBackground||X.isFocused())&&this.#f()},this.#u))}#g(){this.#y(),this.#v(this.#b())}#S(){this.#d!==void 0&&(Q.clearTimeout(this.#d),this.#d=void 0)}#w(){this.#l!==void 0&&(Q.clearInterval(this.#l),this.#l=void 0)}createResult(t,e){let r=this.#t,s=this.options,i=this.#s,n=this.#n,o=this.#i,u=t!==r?t.state:this.#r,{state:d}=t,h={...d},l=!1,f;if(e._optimisticResults){let R=this.hasListeners(),se=!R&&At(t,e),le=R&&Ft(t,r,e,s);(se||le)&&(h={...h,...je(d.data,t.options)}),e._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:m,errorUpdatedAt:y,status:b}=h;f=h.data;let w=!1;if(e.placeholderData!==void 0&&f===void 0&&b==="pending"){let R;i?.isPlaceholderData&&e.placeholderData===o?.placeholderData?(R=i.data,w=!0):R=typeof e.placeholderData=="function"?e.placeholderData(this.#p?.state.data,this.#p):e.placeholderData,R!==void 0&&(b="success",f=ae(i?.data,R,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=ae(i?.data,f,e),this.#c=f,this.#a=null}catch(R){this.#a=R}this.#a&&(m=this.#a,f=this.#c,y=Date.now(),b="error");let E=h.fetchStatus==="fetching",M=b==="pending",U=b==="error",B=M&&E,j=f!==void 0,q={status:b,fetchStatus:h.fetchStatus,isPending:M,isSuccess:b==="success",isError:U,isInitialLoading:B,isLoading:B,data:f,dataUpdatedAt:h.dataUpdatedAt,error:m,errorUpdatedAt:y,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>u.dataUpdateCount||h.errorUpdateCount>u.errorUpdateCount,isFetching:E,isRefetching:E&&!M,isLoadingError:U&&!j,isPaused:h.fetchStatus==="paused",isPlaceholderData:l,isRefetchError:U&&j,isStale:ze(t,e),refetch:this.refetch,promise:this.#o,isEnabled:I(e.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){let R=q.data!==void 0,se=q.status==="error"&&!R,le=a(pe=>{se?pe.reject(q.error):R&&pe.resolve(q.data)},"finalizeThenableIfPossible"),pt=a(()=>{let pe=this.#o=q.promise=oe();le(pe)},"recreateThenable"),fe=this.#o;switch(fe.status){case"pending":t.queryHash===r.queryHash&&le(fe);break;case"fulfilled":(se||q.data!==fe.value)&&pt();break;case"rejected":(!se||q.error!==fe.reason)&&pt();break}}return q}updateResult(){let t=this.#s,e=this.createResult(this.#t,this.options);if(this.#n=this.#t.state,this.#i=this.options,this.#n.data!==void 0&&(this.#p=this.#t),ve(e,t))return;this.#s=e;let r=a(()=>{if(!t)return!0;let{notifyOnChangeProps:s}=this.options,i=typeof s=="function"?s():s;if(i==="all"||!i&&!this.#m.size)return!0;let n=new Set(i??this.#m);return this.options.throwOnError&&n.add("error"),Object.keys(this.#s).some(o=>{let c=o;return this.#s[c]!==t[c]&&n.has(c)})},"shouldNotifyListeners");this.#k({listeners:r()})}#C(){let t=this.#e.getQueryCache().build(this.#e,this.options);if(t===this.#t)return;let e=this.#t;this.#t=t,this.#r=t.state,this.hasListeners()&&(e?.removeObserver(this),t.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#g()}#k(t){v.batch(()=>{t.listeners&&this.listeners.forEach(e=>{e(this.#s)}),this.#e.getQueryCache().notify({query:this.#t,type:"observerResultsUpdated"})})}};function Tr(t,e){return I(e.enabled,t)!==!1&&t.state.data===void 0&&!(t.state.status==="error"&&I(e.retryOnMount,t)===!1)}a(Tr,"shouldLoadOnMount");function At(t,e){return Tr(t,e)||t.state.data!==void 0&&$e(t,e,e.refetchOnMount)}a(At,"shouldFetchOnMount");function $e(t,e,r){if(I(e.enabled,t)!==!1&&x(e.staleTime,t)!=="static"){let s=typeof r=="function"?r(t):r;return s==="always"||s!==!1&&ze(t,e)}return!1}a($e,"shouldFetchOn");function Ft(t,e,r,s){return(t!==e||I(s.enabled,t)===!1)&&(!r.suspense||t.state.status!=="error")&&ze(t,r)}a(Ft,"shouldFetchOptionally");function ze(t,e){return I(e.enabled,t)!==!1&&t.isStaleByTime(x(e.staleTime,t))}a(ze,"isStale");function Or(t,e){return!ve(t.getCurrentResult(),e)}a(Or,"shouldAssignObserverCurrentProperties");var Mt=class extends ke{static{a(this,"Mutation")}#e;#t;#r;#s;constructor(t){super(),this.#e=t.client,this.mutationId=t.mutationId,this.#r=t.mutationCache,this.#t=[],this.state=t.state||Rr(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){this.#t.includes(t)||(this.#t.push(t),this.clearGcTimeout(),this.#r.notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){this.#t=this.#t.filter(e=>e!==t),this.scheduleGc(),this.#r.notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){this.#t.length||(this.state.status==="pending"?this.scheduleGc():this.#r.remove(this))}continue(){return this.#s?.continue()??this.execute(this.state.variables)}async execute(t){let e=a(()=>{this.#n({type:"continue"})},"onContinue"),r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#s=Ce({fn:a(()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),"fn"),onFail:a((n,o)=>{this.#n({type:"failed",failureCount:n,error:o})},"onFail"),onPause:a(()=>{this.#n({type:"pause"})},"onPause"),onContinue:e,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:a(()=>this.#r.canRun(this),"canRun")});let s=this.state.status==="pending",i=!this.#s.canStart();try{if(s)e();else{this.#n({type:"pending",variables:t,isPaused:i}),this.#r.config.onMutate&&await this.#r.config.onMutate(t,this,r);let o=await this.options.onMutate?.(t,r);o!==this.state.context&&this.#n({type:"pending",context:o,variables:t,isPaused:i})}let n=await this.#s.start();return await this.#r.config.onSuccess?.(n,t,this.state.context,this,r),await this.options.onSuccess?.(n,t,this.state.context,r),await this.#r.config.onSettled?.(n,null,this.state.variables,this.state.context,this,r),await this.options.onSettled?.(n,null,t,this.state.context,r),this.#n({type:"success",data:n}),n}catch(n){try{await this.#r.config.onError?.(n,t,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onError?.(n,t,this.state.context,r)}catch(o){Promise.reject(o)}try{await this.#r.config.onSettled?.(void 0,n,this.state.variables,this.state.context,this,r)}catch(o){Promise.reject(o)}try{await this.options.onSettled?.(void 0,n,t,this.state.context,r)}catch(o){Promise.reject(o)}throw this.#n({type:"error",error:n}),n}finally{this.#r.runNext(this)}}#n(t){let e=a(r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}},"reducer");this.state=e(this.state),v.batch(()=>{this.#t.forEach(r=>{r.onMutationUpdate(t)}),this.#r.notify({mutation:this,type:"updated",action:t})})}};function Rr(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}a(Rr,"getDefaultState");var xt=class extends L{static{a(this,"MutationCache")}constructor(t={}){super(),this.config=t,this.#e=new Set,this.#t=new Map,this.#r=0}#e;#t;#r;build(t,e,r){let s=new Mt({client:t,mutationCache:this,mutationId:++this.#r,options:t.defaultMutationOptions(e),state:r});return this.add(s),s}add(t){this.#e.add(t);let e=Ie(t);if(typeof e=="string"){let r=this.#t.get(e);r?r.push(t):this.#t.set(e,[t])}this.notify({type:"added",mutation:t})}remove(t){if(this.#e.delete(t)){let e=Ie(t);if(typeof e=="string"){let r=this.#t.get(e);if(r)if(r.length>1){let s=r.indexOf(t);s!==-1&&r.splice(s,1)}else r[0]===t&&this.#t.delete(e)}}this.notify({type:"removed",mutation:t})}canRun(t){let e=Ie(t);if(typeof e=="string"){let s=this.#t.get(e)?.find(i=>i.state.status==="pending");return!s||s===t}else return!0}runNext(t){let e=Ie(t);return typeof e=="string"?this.#t.get(e)?.find(s=>s!==t&&s.state.isPaused)?.continue()??Promise.resolve():Promise.resolve()}clear(){v.batch(()=>{this.#e.forEach(t=>{this.notify({type:"removed",mutation:t})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(t){let e={exact:!0,...t};return this.getAll().find(r=>be(e,r))}findAll(t={}){return this.getAll().filter(e=>be(t,e))}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}resumePausedMutations(){let t=this.getAll().filter(e=>e.state.isPaused);return v.batch(()=>Promise.all(t.map(e=>e.continue().catch(g))))}};function Ie(t){return t.options.scope?.id}a(Ie,"scopeFor");var _t=class extends L{static{a(this,"QueryCache")}constructor(t={}){super(),this.config=t,this.#e=new Map}#e;build(t,e,r){let s=e.queryKey,i=e.queryHash??ne(s,e),n=this.get(i);return n||(n=new Pt({client:t,queryKey:s,queryHash:i,options:t.defaultQueryOptions(e),state:r,defaultOptions:t.getQueryDefaults(s)}),this.add(n)),n}add(t){this.#e.has(t.queryHash)||(this.#e.set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){let e=this.#e.get(t.queryHash);e&&(t.destroy(),e===t&&this.#e.delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){v.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return this.#e.get(t)}getAll(){return[...this.#e.values()]}find(t){let e={exact:!0,...t};return this.getAll().find(r=>ye(e,r))}findAll(t={}){let e=this.getAll();return Object.keys(t).length>0?e.filter(r=>ye(t,r)):e}notify(t){v.batch(()=>{this.listeners.forEach(e=>{e(t)})})}onFocus(){v.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){v.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}};var We=class{static{a(this,"QueryClient")}#e;#t;#r;#s;#n;#i;#o;#a;constructor(t={}){this.#e=t.queryCache||new _t,this.#t=t.mutationCache||new xt,this.#r=t.defaultOptions||{},this.#s=new Map,this.#n=new Map,this.#i=0}mount(){this.#i++,this.#i===1&&(this.#o=X.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#a=Z.subscribe(async t=>{t&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#i--,this.#i===0&&(this.#o?.(),this.#o=void 0,this.#a?.(),this.#a=void 0)}isFetching(t){return this.#e.findAll({...t,fetchStatus:"fetching"}).length}isMutating(t){return this.#t.findAll({...t,status:"pending"}).length}getQueryData(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state.data}ensureQueryData(t){let e=this.defaultQueryOptions(t),r=this.#e.build(this,e),s=r.state.data;return s===void 0?this.fetchQuery(t):(t.revalidateIfStale&&r.isStaleByTime(x(e.staleTime,r))&&this.prefetchQuery(e),Promise.resolve(s))}getQueriesData(t){return this.#e.findAll(t).map(({queryKey:e,state:r})=>{let s=r.data;return[e,s]})}setQueryData(t,e,r){let s=this.defaultQueryOptions({queryKey:t}),n=this.#e.get(s.queryHash)?.state.data,o=gt(e,n);if(o!==void 0)return this.#e.build(this,s).setData(o,{...r,manual:!0})}setQueriesData(t,e,r){return v.batch(()=>this.#e.findAll(t).map(({queryKey:s})=>[s,this.setQueryData(s,e,r)]))}getQueryState(t){let e=this.defaultQueryOptions({queryKey:t});return this.#e.get(e.queryHash)?.state}removeQueries(t){let e=this.#e;v.batch(()=>{e.findAll(t).forEach(r=>{e.remove(r)})})}resetQueries(t,e){let r=this.#e;return v.batch(()=>(r.findAll(t).forEach(s=>{s.reset()}),this.refetchQueries({type:"active",...t},e)))}cancelQueries(t,e={}){let r={revert:!0,...e},s=v.batch(()=>this.#e.findAll(t).map(i=>i.cancel(r)));return Promise.all(s).then(g).catch(g)}invalidateQueries(t,e={}){return v.batch(()=>(this.#e.findAll(t).forEach(r=>{r.invalidate()}),t?.refetchType==="none"?Promise.resolve():this.refetchQueries({...t,type:t?.refetchType??t?.type??"active"},e)))}refetchQueries(t,e={}){let r={...e,cancelRefetch:e.cancelRefetch??!0},s=v.batch(()=>this.#e.findAll(t).filter(i=>!i.isDisabled()&&!i.isStatic()).map(i=>{let n=i.fetch(void 0,r);return r.throwOnError||(n=n.catch(g)),i.state.fetchStatus==="paused"?Promise.resolve():n}));return Promise.all(s).then(g)}fetchQuery(t){let e=this.defaultQueryOptions(t);e.retry===void 0&&(e.retry=!1);let r=this.#e.build(this,e);return r.isStaleByTime(x(e.staleTime,r))?r.fetch(e):Promise.resolve(r.state.data)}prefetchQuery(t){return this.fetchQuery(t).then(g).catch(g)}fetchInfiniteQuery(t){return t._type="infinite",this.fetchQuery(t)}prefetchInfiniteQuery(t){return this.fetchInfiniteQuery(t).then(g).catch(g)}ensureInfiniteQueryData(t){return t._type="infinite",this.ensureQueryData(t)}resumePausedMutations(){return Z.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#r}setDefaultOptions(t){this.#r=t}setQueryDefaults(t,e){this.#s.set(H(t),{queryKey:t,defaultOptions:e})}getQueryDefaults(t){let e=[...this.#s.values()],r={};return e.forEach(s=>{K(t,s.queryKey)&&Object.assign(r,s.defaultOptions)}),r}setMutationDefaults(t,e){this.#n.set(H(t),{mutationKey:t,defaultOptions:e})}getMutationDefaults(t){let e=[...this.#n.values()],r={};return e.forEach(s=>{K(t,s.mutationKey)&&Object.assign(r,s.defaultOptions)}),r}defaultQueryOptions(t){if(t._defaulted)return t;let e={...this.#r.queries,...this.getQueryDefaults(t.queryKey),...t,_defaulted:!0};return e.queryHash||(e.queryHash=ne(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===Y&&(e.enabled=!1),e}defaultMutationOptions(t){return t?._defaulted?t:{...this.#r.mutations,...t?.mutationKey&&this.getMutationDefaults(t.mutationKey),...t,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}};var N=P($(),1);var ee=P($(),1),Lt=P(Ue(),1);var ce=ee.createContext(void 0),Ve=a(t=>{let e=ee.useContext(ce);if(t)return t;if(!e)throw new Error("No QueryClient set, use QueryClientProvider to set one");return e},"useQueryClient"),Ge=a(({client:t,children:e})=>(ee.useEffect(()=>(t.mount(),()=>{t.unmount()}),[t]),(0,Lt.jsx)(ce.Provider,{value:t,children:e})),"QueryClientProvider");var ue=P($(),1),Pr=P(Ue(),1);function Ar(){let t=!1;return{clearReset:a(()=>{t=!1},"clearReset"),reset:a(()=>{t=!0},"reset"),isReset:a(()=>t,"isReset")}}a(Ar,"createValue");var Fr=ue.createContext(Ar()),Qt=a(()=>ue.useContext(Fr),"useQueryErrorResetBoundary");var Dt=P($(),1);var Ut=a((t,e,r)=>{let s=r?.state.error&&typeof t.throwOnError=="function"?Se(t.throwOnError,[r.state.error,r]):t.throwOnError;(t.suspense||t.experimental_prefetchInRender||s)&&(e.isReset()||(t.retryOnMount=!1))},"ensurePreventErrorBoundaryRetry"),qt=a(t=>{Dt.useEffect(()=>{t.clearReset()},[t])},"useClearResetErrorBoundary"),Kt=a(({result:t,errorResetBoundary:e,throwOnError:r,query:s,suspense:i})=>t.isError&&!e.isReset()&&!t.isFetching&&s&&(i&&t.data===void 0||Se(r,[t.error,s])),"getHasError");var Ee=P($(),1);var Nt=Ee.createContext(!1),Bt=a(()=>Ee.useContext(Nt),"useIsRestoring"),_a=Nt.Provider;var jt=a(t=>{if(t.suspense){let r=a(i=>i==="static"?i:Math.max(i??1e3,1e3),"clamp"),s=t.staleTime;t.staleTime=typeof s=="function"?(...i)=>r(s(...i)):r(s),typeof t.gcTime=="number"&&(t.gcTime=Math.max(t.gcTime,1e3))}},"ensureSuspenseTimers"),$t=a((t,e)=>t.isLoading&&t.isFetching&&!e,"willFetch"),Ht=a((t,e)=>t?.suspense&&e.isPending,"shouldSuspend"),Je=a((t,e,r)=>e.fetchOptimistic(t).catch(()=>{r.clearReset()}),"fetchOptimistic");function zt(t,e,r){let s=Bt(),i=Qt(),n=Ve(r),o=n.defaultQueryOptions(t);n.getDefaultOptions().queries?._experimental_beforeQuery?.(o);let c=n.getQueryCache().get(o.queryHash),u=t.subscribed!==!1;o._optimisticResults=s?"isRestoring":u?"optimistic":void 0,jt(o),Ut(o,i,c),qt(i);let d=!n.getQueryCache().get(o.queryHash),[h]=N.useState(()=>new e(n,o)),l=h.getOptimisticResult(o),f=!s&&u;if(N.useSyncExternalStore(N.useCallback(m=>{let y=f?h.subscribe(v.batchCalls(m)):g;return h.updateResult(),y},[h,f]),()=>h.getCurrentResult(),()=>h.getCurrentResult()),N.useEffect(()=>{h.setOptions(o)},[o,h]),Ht(o,l))throw Je(o,h,i);if(Kt({result:l,errorResetBoundary:i,throwOnError:o.throwOnError,query:c,suspense:o.suspense}))throw l.error;return n.getDefaultOptions().queries?._experimental_afterQuery?.(o,l),o.experimental_prefetchInRender&&!D.isServer()&&$t(l,s)&&(d?Je(o,h,i):c?.promise)?.catch(g).finally(()=>{h.updateResult()}),o.notifyOnChangeProps?l:h.trackResult(l)}a(zt,"useBaseQuery");function Mr(t,e){return zt(t,He,e)}a(Mr,"useQuery");var Wt=P(mt(),1);var z=P($(),1),Xe=P(Ue(),1);var Vt=(0,z.createContext)(null),xr=a(()=>new We({defaultOptions:{mutations:{retry:0},queries:{gcTime:5*6e4,retry:0,staleTime:Number.POSITIVE_INFINITY}}}),"v"),_r=a(t=>{let e=(0,Wt.c)(9),{children:r,client:s,queryClient:i}=t,n=(0,z.use)(ce),o;e[0]!==n||e[1]!==i?(o=a(()=>i??n??xr(),"o"),e[0]=n,e[1]=i,e[2]=o):o=e[2];let[c]=(0,z.useState)(o),u=i??n??c,d;e[3]!==r||e[4]!==s?(d=(0,Xe.jsx)(Vt,{value:s,children:r}),e[3]=r,e[4]=s,e[5]=d):d=e[5];let h=d;if(n===u)return h;let l;return e[6]!==h||e[7]!==u?(l=(0,Xe.jsx)(Ge,{client:u,children:h}),e[6]=h,e[7]=u,e[8]=l):l=e[8],l},"b"),Ye=a(()=>{let t=(0,z.use)(Vt);if(!t)throw new p("INTERNAL","useLunora must be used inside <LunoraProvider />");return t},"q");var Gt=a(()=>{let t=null;return{get:a(()=>t,"get"),set:a(e=>{t=e},"set")}},"l");var Te=class{static{a(this,"u")}values=new Map;subscribers=new Map;get(e){return this.values.has(e.key)?this.values.get(e.key):e.defaultValue}set(e,r){if(r===void 0){this.reset(e);return}this.values.set(e.key,r),this.notify(e.key,r)}reset(e){this.values.delete(e.key),this.notify(e.key,e.defaultValue)}subscribe(e,r){let s=this.subscribers.get(e.key);return s||(s=new Set,this.subscribers.set(e.key,s)),s.add(r),()=>{s.delete(r),s.size===0&&this.subscribers.delete(e.key)}}notify(e,r){let s=this.subscribers.get(e);if(s)for(let i of s)try{i(r)}catch{}}};var Jt=0,Lr="lunora-bridge",Qr=1e3,Dr=3e3,Oe=class{static{a(this,"c")}bc;tabId;heartbeatInterval;leaderTimeout;knownLeader=void 0;leader=!1;running=!1;promotionPending=!1;lastHeartbeat=0;heartbeatTimer=void 0;leaderCheckTimer=void 0;onBecomeLeader;onStopBeingLeader;onConnectionStatus;onSubscriptionData;onSubscriptionError;onSubscriptionSettled;constructor(e={}){if(Jt+=1,this.tabId=`tab_${String(Jt)}_${crypto.randomUUID()}`,this.heartbeatInterval=e.heartbeatInterval??Qr,this.leaderTimeout=e.leaderTimeout??Dr,this.onBecomeLeader=e.onBecomeLeader,this.onStopBeingLeader=e.onStopBeingLeader,this.onConnectionStatus=e.onConnectionStatus,this.onSubscriptionData=e.onSubscriptionData,this.onSubscriptionError=e.onSubscriptionError,this.onSubscriptionSettled=e.onSubscriptionSettled,typeof BroadcastChannel>"u"){this.bc=void 0;return}this.bc=new BroadcastChannel(e.channelName??Lr),this.bc.addEventListener("message",r=>{this.handleMessage(r.data)})}start(){if(!this.running){if(this.running=!0,this.bc===void 0){this.becomeLeader();return}this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout),this.leaderCheckTimer=setInterval(()=>{this.checkLeaderHealth()},this.leaderTimeout),this.heartbeatTimer=setInterval(()=>{this.sendHeartbeat()},this.heartbeatInterval)}}stop(){this.running=!1,this.leader&&(this.broadcast({type:"yield-leadership",tabId:this.tabId}),this.leader=!1,this.knownLeader=void 0,this.onStopBeingLeader?.()),this.heartbeatTimer!==void 0&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=void 0),this.leaderCheckTimer!==void 0&&(clearInterval(this.leaderCheckTimer),this.leaderCheckTimer=void 0),this.bc?.close()}isLeader(){return this.leader}promoteImmediately(){this.running&&this.becomeLeader()}get leaderTabId(){return this.knownLeader}get id(){return this.tabId}get isRunning(){return this.running}broadcastSubscriptionData(e,r,s,i,n){this.leader&&this.broadcast({type:"subscription-data",tabId:this.tabId,key:e,data:r,...s===void 0?{}:{cursor:s},...i===void 0?{}:{epoch:i},...n===void 0?{}:{identity:n}})}broadcastSubscriptionError(e,r){this.leader&&this.broadcast({type:"subscription-error",tabId:this.tabId,key:e,error:r})}broadcastSubscriptionSettled(e,r,s,i,n,o){this.leader&&this.broadcast({type:"subscription-settled",tabId:this.tabId,key:e,...r===void 0?{}:{cursor:r},...s===void 0?{}:{epoch:s},...i===void 0?{}:{lastMutationId:i},...n===void 0?{}:{clientId:n},...o===void 0?{}:{identity:o}})}broadcastConnectionStatus(e,r){this.leader&&this.broadcast({type:"connection-status",tabId:this.tabId,status:e,...r===void 0?{}:{identity:r}})}broadcast(e){this.bc?.postMessage(e)}handleMessage(e){switch(e.type){case"claim-leadership":{this.handleClaimLeadership(e);break}case"connection-status":{if(this.leader||e.tabId===this.tabId)break;this.onConnectionStatus?.(e.status,e.identity);break}case"heartbeat":{this.handleHeartbeat(e);break}case"subscription-data":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionData?.(e.key,e.data,e.cursor,e.epoch,e.identity);break}case"subscription-error":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionError?.(e.key,e.error);break}case"subscription-settled":{if(this.leader||e.tabId===this.tabId)break;this.onSubscriptionSettled?.(e.key,e.cursor,e.epoch,e.lastMutationId,e.clientId,e.identity);break}case"yield-leadership":{this.knownLeader===e.tabId&&(this.knownLeader=void 0,this.running&&!this.leader&&this.claimAndPromote());break}}}handleClaimLeadership(e){if(e.tabId!==this.tabId){if(this.leader){this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()});return}this.knownLeader===void 0&&e.tabId<this.tabId&&(this.knownLeader=e.tabId,this.lastHeartbeat=e.ts)}}handleHeartbeat(e){if(e.tabId!==this.tabId){if(this.leader){this.resolveLeaderVsLeaderTieBreak(e);return}this.lastHeartbeat=e.ts,this.knownLeader=e.tabId}}resolveLeaderVsLeaderTieBreak(e){e.tabId<this.tabId?(this.leader=!1,this.knownLeader=e.tabId,this.lastHeartbeat=e.ts,this.onStopBeingLeader?.()):this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}becomeLeader(){this.leader||(this.leader=!0,this.knownLeader=this.tabId,this.lastHeartbeat=Date.now(),this.onBecomeLeader?.(),this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()}))}sendHeartbeat(){this.leader&&this.broadcast({type:"heartbeat",tabId:this.tabId,ts:Date.now()})}checkLeaderHealth(){if(!(!this.running||this.leader)){if(this.knownLeader===void 0){this.claimAndPromote();return}Date.now()-this.lastHeartbeat>this.leaderTimeout&&(this.knownLeader=void 0,this.claimAndPromote())}}claimAndPromote(){this.promotionPending||(this.promotionPending=!0,this.broadcast({type:"claim-leadership",tabId:this.tabId,ts:Date.now()}),setTimeout(()=>{this.promotionPending=!1,this.running&&this.knownLeader===void 0&&this.becomeLeader()},this.leaderTimeout))}};var Ze=a(t=>{let e="";for(let r=0;r<t.length;r+=32768)e+=String.fromCharCode(...t.subarray(r,r+32768));return btoa(e)},"b"),Ur=a(t=>{let e=atob(t),r=new Uint8Array(e.length);for(let s=0;s<e.length;s+=1)r[s]=e.codePointAt(s)??0;return r},"g"),k="$lunora.wire$",et="__proto__",Xt={BigInt64Array,BigUint64Array,Float32Array,Float64Array,Int8Array,Int16Array,Int32Array,Uint8Array,Uint8ClampedArray,Uint16Array,Uint32Array},Yt={Error,EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError},tt=a(t=>{if(t===null||typeof t!="object")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.prototype},"m"),O=a((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===void 0)return[k,"undefined"];if(t===null)return null;let r=typeof t;if(r==="bigint")return[k,"bigint",t.toString()];if(r==="number"){let n=t;return Number.isNaN(n)?[k,"nan"]:n===1/0?[k,"inf"]:n===-1/0?[k,"-inf"]:n}if(r!=="object")return t;if(t instanceof Date)return[k,"date",O(t.getTime(),e+1)];if(t instanceof Error){let n=t,o={};for(let u of Object.keys(n))n[u]!==void 0&&(o[u]=O(n[u],e+1));let c=[k,"error",n.name,n.message,o];return n.cause!==void 0&&c.push(O(n.cause,e+1)),c}if(t instanceof URL)return[k,"url",t.href];if(t instanceof Map)return[k,"map",[...t.entries()].map(([n,o])=>[O(n,e+1),O(o,e+1)])];if(t instanceof Set)return[k,"set",[...t].map(n=>O(n,e+1))];if(t instanceof ArrayBuffer)return[k,"bytes",Ze(new Uint8Array(t)),"ArrayBuffer"];if(ArrayBuffer.isView(t)){let n=t,o=n.constructor.name,c=new Uint8Array(n.buffer,n.byteOffset,n.byteLength);return o==="Uint8Array"?[k,"bytes",Ze(c)]:[k,"bytes",Ze(c),o]}if(Array.isArray(t)){let n=t.map(o=>O(o,e+1));return n.length>0&&n[0]===k?[k,"arr",n]:n}if(!tt(t)){let n=t.constructor?.name??"value";throw new TypeError(`wire-codec: cannot encode a ${n} over the Lunora wire \u2014 only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`)}let s=t,i={};for(let n of Object.keys(s)){let o=s[n];if(o===void 0)continue;let c=O(o,e+1);n===et?Object.defineProperty(i,n,{configurable:!0,enumerable:!0,value:c,writable:!0}):i[n]=c}return i},"s"),S=a((t,e=0)=>{if(e>64)throw new RangeError("wire-codec: value nesting exceeds the 64-level limit");if(t===null||typeof t!="object")return t;if(Array.isArray(t)){if(t[0]===k)switch(t[1]){case"-inf":return-1/0;case"arr":return t[2].map(i=>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":return new Date(S(t[2],e+1));case"map":return new Map(t[2].map(([i,n])=>[S(i,e+1),S(n,e+1)]));case"set":return new Set(t[2].map(i=>S(i,e+1)));case"url":return new URL(t[2]);case"error":{let i=t[2],n=t[3],o=(Object.hasOwn(Yt,i)?Yt[i]:void 0)??Error,c=new o(n);c.name!==i&&Object.defineProperty(c,"name",{configurable:!0,value:i,writable:!0});let u=S(t[4],e+1);for(let d of Object.keys(u))d===et?Object.defineProperty(c,d,{configurable:!0,enumerable:!0,value:u[d],writable:!0}):c[d]=u[d];return t.length>5&&Object.defineProperty(c,"cause",{configurable:!0,value:S(t[5],e+1),writable:!0}),c}case"bytes":{let i=Ur(t[2]),n=t[3]??"Uint8Array";if(n==="ArrayBuffer")return i.buffer.byteLength===i.byteLength?i.buffer:i.slice().buffer;let o=Object.hasOwn(Xt,n)?Xt[n]:void 0;return o?new o(i.slice().buffer):i}case"inf":return 1/0;case"nan":return Number.NaN;case"undefined":return;default:return t.map(i=>S(i,e+1))}return t.map(i=>S(i,e+1))}let r=t,s={};for(let i of Object.keys(r)){let n=S(r[i],e+1);i===et?Object.defineProperty(s,i,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[i]=n}return s},"f");var rt="_id",st="_creationTime",it="page",Zt="pageDelta",qr=a(t=>{if(Array.isArray(t))return t;if(tt(t)&&Array.isArray(t[it]))return t[it]},"d"),Kr=a(t=>{let e;for(let r of t){let s=r[st];if(typeof s=="number"){if(e!==void 0){if(s<e)return!0;if(s>e)return!1}e=s}}return!1},"g"),Nr=a((t,e)=>{let r=e[st];if(typeof r!="number")return t.length;let s=Kr(t);for(let[i,n]of t.entries()){let o=n[st];if(typeof o=="number"&&(s?o<r:o>r))return i}return t.length},"A"),Br=a(t=>{if(typeof t!="object"||t===null)return;let e=t[rt];return typeof e=="string"?e:void 0},"b"),er=a(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")},"k"),jr=a((t,e)=>{let r=[];for(let u of t){if(Br(u)===void 0)return;r.push(u)}let{key:s,op:i,row:n}=e;if(i==="delete"){let u=r.filter(d=>d[rt]!==s);return u.length===r.length?[...r]:u}if(n===void 0)return;let o=[...r],c=r.findIndex(u=>u[rt]===s);return c===-1?o.splice(Nr(r,n),0,n):o[c]=n,o},"m"),tr=a((t,e)=>{let r=qr(t);if(r===void 0)return;let s=jr(r,e);return s===void 0||Array.isArray(t)?s:{...t,[it]:s}},"$");var $r=1024,Re=a(t=>{let e=t.maxBuffer??$r,r=[],s=[],i=!1,n,o=!1,c=a(()=>{let h=s.shift();if(!h)return!1;if(n)return h.reject(n),!0;if(r.length>0){let l=r.shift();return h.resolve({done:!1,value:l}),!0}return i?(h.resolve({done:!0,value:void 0}),!0):(s.unshift(h),!1)},"n"),u={complete(){if(!(i||n))for(i=!0;c(););},fail(h){if(!(i||n))for(n=h,r.length=0;c(););},push(h){if(!(i||n||o)){if(r.length>=e){u.fail(new p("STREAM_BACKPRESSURE",`stream buffer overflow (max=${e.toString()}); the consumer cannot keep up with the producer`));return}r.push(h),c()}}},d=a(()=>{if(!o){o=!0,i=!0,r.length=0;try{t.onCancel()}catch{}for(;c(););}},"c");return{handle:u,iterable:{cancel:d,[Symbol.asyncIterator](){return{next(){if(n)return Promise.reject(n);if(r.length>0){let h=r.shift();return Promise.resolve({done:!1,value:h})}return i?Promise.resolve({done:!0,value:void 0}):new Promise((h,l)=>{s.push({reject:l,resolve:h})})},return(){return d(),Promise.resolve({done:!0,value:void 0})}}}}}},"d");var rr=/^ /u,sr=a(t=>typeof t=="object"&&t!==null?JSON.stringify(t):String(t),"u"),Hr=a(t=>{let e="",r=[];for(let s of t.split(`
2
+ `))s.startsWith("event:")?e=s.slice(6).replace(rr,""):s.startsWith("data:")&&r.push(s.slice(5).replace(rr,""));return{data:r.join(`
3
+ `),event:e}},"p"),zr=a((t,e,r)=>{let s=e.params??{},i=t.path.split("/").map(c=>{if(!c.startsWith(":"))return c;let u=c.slice(1),d=s[u];if(d===void 0)throw new p("HTTP_STREAM_MISSING_PARAM",`httpStream: missing path param ":${u}" for route ${t.path}`);return encodeURIComponent(sr(d))}).join("/"),n=new URLSearchParams;for(let[c,u]of Object.entries(e.searchParams??{}))u!==void 0&&n.set(c,sr(u));let o=n.toString();return`${r.endsWith("/")?r.slice(0,-1):r}${i}${o===""?"":`?${o}`}`},"S"),Wr=a((t,e)=>{if(t.event==="complete")return e.complete(),!0;if(t.event==="error"){let r={};try{r=JSON.parse(t.data)}catch{}let s=typeof r.message=="string"?r.message:"stream error",i=typeof r.code=="string"?r.code:"HTTP_STREAM_ERROR";return e.fail(new p(i,s)),!0}if((t.event===""||t.event==="message")&&t.data!=="")try{e.push(JSON.parse(t.data))}catch{return e.fail(new p("HTTP_STREAM_BAD_CHUNK","httpStream: malformed SSE chunk (invalid JSON)")),!0}return!1},"T"),Vr=a(async(t,e)=>{let r=t.getReader(),s=new TextDecoder,i="",n=a(()=>{let o=i.indexOf(`
4
+
5
+ `);for(;o!==-1;){let c=Hr(i.slice(0,o));if(i=i.slice(o+2),Wr(c,e))return!0;o=i.indexOf(`
6
+
7
+ `)}return!1},"c");for(;;){let{done:o,value:c}=await r.read();if(o)break;if(i+=s.decode(c,{stream:!0}).replaceAll(`\r
8
+ `,`
9
+ `),n()){await r.cancel().catch(()=>{});return}}i+=s.decode().replaceAll(`\r
10
+ `,`
11
+ `),n()||e.fail(new p("HTTP_STREAM_INTERRUPTED","httpStream: stream ended without a complete frame"))},"g"),ir=a((t,e,r={})=>{let s=r.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0);if(!s)throw new p("INTERNAL","httpStream: no `fetch` implementation available");let i=zr(t,e??{},r.baseUrl??""),n=new AbortController,o;r.signal&&(r.signal.aborted?n.abort():(o=a(()=>{n.abort()},"n"),r.signal.addEventListener("abort",o,{once:!0})));let c=a(()=>{o&&r.signal?.removeEventListener("abort",o)},"l"),{handle:u,iterable:d}=Re({maxBuffer:r.maxBuffer,onCancel:a(()=>{n.abort()},"onCancel")});return(async()=>{try{let h=await s(i,{headers:{accept:"text/event-stream",...r.headers},method:t.method,signal:n.signal});if(!h.ok){await h.body?.cancel().catch(()=>{}),u.fail(new p("HTTP_STREAM_STATUS",`httpStream: request failed (status ${h.status.toString()})`,{status:h.status}));return}if(!h.body){u.fail(new p("HTTP_STREAM_NO_BODY","httpStream: response has no body"));return}await Vr(h.body,u)}finally{c()}})().catch(h=>{if(n.signal.aborted){u.complete();return}if(h instanceof Error&&"code"in h){u.fail(h);return}u.fail(new p("HTTP_STREAM_TRANSPORT",h instanceof Error?h.message:String(h),{cause:h}))}),d},"w");var Gr=a((t,e)=>t<e?-1:t>e?1:0,"y"),nt=a(t=>{if(t===void 0)return"null";if(typeof t=="bigint")throw new TypeError("stableStringify: cannot use a bigint in a stable JSON cache key \u2014 pass it as a string, or use stableWireKey");if(t===null||typeof t!="object")return JSON.stringify(t);if(Array.isArray(t))return`[${t.map(n=>nt(n)).join(",")}]`;let e=Object.getPrototypeOf(t);if(e!==null&&e!==Object.prototype){let n=t.constructor?.name??"value";throw new TypeError(`stableStringify: cannot use a ${n} in a stable JSON cache key \u2014 only plain objects, arrays, and JSON primitives are supported (wire-typed values key via stableWireKey)`)}let r=t,s=Object.keys(r).toSorted(Gr),i=[];for(let n of s){let o=r[n];o!==void 0&&i.push(`${JSON.stringify(n)}:${nt(o)}`)}return`{${i.join(",")}}`},"n"),W=a(t=>nt(O(t)),"l");var _=class t{static{a(this,"y")}static key(e,r,s){return`${e}::${W(r)}::${s??""}`}byKey=new Map;byId=new Map;get(e){return this.byKey.get(e)}getById(e){return this.byId.get(e)}add(e){this.byKey.set(t.key(e.fn.__lunoraRef,e.args,e.shardKey),e),this.byId.set(e.id,e)}remove(e){let r=t.key(e.fn.__lunoraRef,e.args,e.shardKey);this.byKey.get(r)===e&&this.byKey.delete(r),this.byId.delete(e.id)}all(){return[...this.byKey.values()]}};var he=a((t,e)=>{let r=t;for(let s of e)try{r=s.transform(r)}catch{}return r},"m"),te=a((t,e)=>{if(e!==t.lastValue){t.lastValue=e;for(let r of t.callbacks)try{r(e)}catch{}}},"u"),at=a((t,e)=>{let r;try{r=e(t.lastValue)}catch{return}let s={id:Symbol("optimistic"),transform:e};t.optimisticLayers.push(s),te(t,r);let i=a(()=>{let o=t.optimisticLayers.findIndex(c=>c.id===s.id);return o===-1?!1:(t.optimisticLayers.splice(o,1),!0)},"i"),n=a(()=>{te(t,he(t.serverBase,t.optimisticLayers))},"a");return{confirm:a(o=>{if(o===void 0){i();return}s.commitCursor=o,t.serverCursor!==void 0&&t.serverCursor>=o&&i()&&n()},"confirm"),rollback:a(()=>{i()&&n()},"rollback")}},"p"),Pe=a((t,e)=>{if(e===void 0||t.optimisticLayers.length===0)return!1;let r=t.optimisticLayers.length;return t.optimisticLayers=t.optimisticLayers.filter(s=>s.commitCursor===void 0||s.commitCursor>e),t.optimisticLayers.length!==r},"d"),nr=a((t,e)=>{let r=[],s=[],i=a((n,o)=>t.get(_.key(n,o,e)),"i");return{confirms:r,rollbacks:s,store:{getAllQueries:a(n=>{let o=[];for(let c of t.all())c.fn.__lunoraRef===n.__lunoraRef&&(c.shardKey??"")===(e??"")&&o.push({args:c.args,value:c.lastValue});return o},"getAllQueries"),getQuery:a((n,o)=>i(n.__lunoraRef,o??{})?.lastValue,"getQuery"),setQuery:a((n,o,c)=>{let u=i(n.__lunoraRef,o??{});if(!u)return;let d=at(u,()=>c);d&&(r.push(d.confirm),s.push(d.rollback))},"setQuery")}}},"L");var ar=0,Jr=a(()=>{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID();ar+=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)}_${ar.toString(36)}_${t}`},"a"),ot=a((t,e)=>t!==void 0&&e!==t,"f"),Fe=Jr,re=a((t,e,r,s)=>{if(t){t({error:r,mutationId:s,operation:e});return}console.warn(`[lunora] offline-queue persistence ${e} failed`,r)},"h"),Ae=class{static{a(this,"u")}queueBeforeFirstConnect;maxItems;onPersistenceError;persistence;onEvict;onSizeChange;version;items=[];constructor(e={},r={}){this.maxItems=e.maxItems??1e3,this.queueBeforeFirstConnect=e.queueBeforeFirstConnect??!1,this.onPersistenceError=e.onPersistenceError,this.persistence=r.persistence,this.onEvict=r.onEvict,this.onSizeChange=r.onSizeChange,this.version=r.version}get size(){return this.items.length}enqueue(e){let r=e;r.id??=Fe(),this.items.push(r),this.persistence?.append({args:r.args,clientId:r.clientId,functionPath:r.functionPath,id:r.id,identity:r.identity,shardKey:r.shardKey,...this.version===void 0?{}:{version:this.version}}).catch(s=>{re(this.onPersistenceError,"append",s,r.id)}),this.evictOverflow(),this.notifySize()}async hydrate(){if(!this.persistence)return[];let e;try{e=await this.persistence.load()}catch(n){throw re(this.onPersistenceError,"load",n),n}let r=[];for(let n of e)if(!(this.items.some(o=>o.id===n.id)||r.some(o=>o.id===n.id))){if(ot(this.version,n.version)){this.persistence.remove(n.id).catch(o=>{re(this.onPersistenceError,"remove",o,n.id)});continue}r.push({args:n.args,clientId:n.clientId,functionPath:n.functionPath,id:n.id,identity:n.identity,reject:a(()=>{},"reject"),resolve:a(()=>{},"resolve"),shardKey:n.shardKey})}this.items.unshift(...r),this.evictOverflow(),this.notifySize();let s=new Set(this.items),i=new Set;for(let n of r)s.has(n)&&i.add(n.shardKey);return[...i]}drain(e){if(!e){let i=[...this.items];return this.items.length=0,this.notifySize(),i}let r=[],s=[];for(let i of this.items)(e(i)?r:s).push(i);return this.items.length=0,this.items.push(...s),this.notifySize(),r}requeue(e){e.length!==0&&(this.items.unshift(...e),this.notifySize())}drainConflict(){let e=[],r=[];for(let s of this.items)if(s.precondition!==void 0&&!s.precondition()){let i=new Error("offline mutation skipped: precondition failed before replay");i.code="OFFLINE_PRECONDITION_FAILED",s.reject(i),e.push(s)}else r.push(s);return e.length>0&&(this.items.length=0,this.items.push(...r),this.notifySize()),e}clear(){for(let e of this.items){let r=new Error("CLIENT_CLOSED");r.code="CLIENT_CLOSED",e.reject(r)}this.items.length=0,this.notifySize()}evictOverflow(){for(;this.items.length>this.maxItems;){let e=this.items.shift();if(e){e.id&&this.persistence?.remove(e.id).catch(s=>{re(this.onPersistenceError,"remove",s,e.id)});let r=new Error("offline queue overflow");r.code="OFFLINE_QUEUE_OVERFLOW",e.reject(r),this.onEvict?.(e,r)}}}notifySize(){this.onSizeChange?.(this.items.length)}};var A=a(t=>new Promise((e,r)=>{t.addEventListener("success",()=>{e(t.result)}),t.addEventListener("error",()=>{r(t.error??new Error("IndexedDB request failed"))})}),"i"),Me=a((t,e,r,s)=>{let i;return()=>i||(i=new Promise((n,o)=>{let c=t.open(e,r);c.addEventListener("upgradeneeded",()=>{s(c.result)}),c.addEventListener("success",()=>{n(c.result)}),c.addEventListener("error",()=>{o(c.error??new Error("IndexedDB open failed"))})}),i)},"c"),xe=a((t,e)=>async(r,s)=>{let i=(await t()).transaction(e,r),n=await s(i.objectStore(e));return await new Promise((o,c)=>{i.addEventListener("complete",()=>{o()}),i.addEventListener("error",()=>{c(i.error??new Error("IndexedDB transaction failed"))}),i.addEventListener("abort",()=>{c(i.error??new Error("IndexedDB transaction aborted"))})}),n},"E");var Xr="lunora-outbox",Yr="offline-mutations",or="by_id",Zr=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new p("INTERNAL","createIndexedDbPersistence: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryPersistence()");let r=t.databaseName??Xr,s=t.storeName??Yr,i=Me(e,r,1,o=>{o.objectStoreNames.contains(s)||o.createObjectStore(s,{autoIncrement:!0}).createIndex(or,"id",{unique:!0})}),n=xe(i,s);return{append:a(async o=>{await n("readwrite",c=>A(c.add(o)))},"append"),clear:a(async()=>{await n("readwrite",o=>A(o.clear()))},"clear"),load:a(async()=>n("readonly",o=>A(o.getAll())),"load"),remove:a(async o=>{await n("readwrite",async c=>{let u=await A(c.index(or).getKey(o));u!==void 0&&await A(c.delete(u))})},"remove")}},"x"),cr=a((t,e=!0)=>{if(t!==!1){if(t)return t;if(!(!e||typeof indexedDB>"u"))return Zr()}},"P");var _e=a((t,e,r)=>`${t}::${e}::${r??""}`,"k"),es=500;var ts="lunora-query-cache",rs="query-cache",ur="by_ts",ss=1,is=a((t={})=>{let e=t.indexedDB??(typeof indexedDB>"u"?void 0:indexedDB);if(!e)throw new p("INTERNAL","createIndexedDbQueryCache: no IndexedDB available \u2014 pass `indexedDB` or use createInMemoryQueryCache()");let r=t.databaseName??ts,s=t.storeName??rs,i=t.maxEntries??es,n=Me(e,r,ss,u=>{u.objectStoreNames.contains(s)||u.createObjectStore(s,{keyPath:"key"}).createIndex(ur,"ts",{unique:!1})}),o=xe(n,s),c=a(async u=>{let d=await A(u.count())-i;d<=0||await new Promise((h,l)=>{let f=u.index(ur).openCursor();f.addEventListener("success",()=>{let m=f.result;if(!m||d<=0){h();return}m.delete(),d-=1,m.continue()}),f.addEventListener("error",()=>{l(f.error??new Error("IndexedDB eviction failed"))})})},"y");return{clear:a(async()=>{await o("readwrite",u=>A(u.clear()))},"clear"),load:a(async()=>o("readonly",u=>A(u.getAll())),"load"),put:a(async(u,d)=>{await o("readwrite",async h=>{await A(h.put({...d,key:u})),await c(h)})},"put"),remove:a(async u=>{await o("readwrite",d=>A(d.delete(u)))},"remove")}},"I"),hr=a(t=>{if(t!==!1){if(t)return t;if(!(typeof indexedDB>"u"))return is()}},"N");var ct=a((t={},e=Math.random)=>{let r=t.initialDelayMs??250,s=t.maxDelayMs??3e4,i=t.jitter??!0,n=0;return{next(){let o=Math.min(s,r*2**n);if(n+=1,!i)return o;let c=o/2;return Math.floor(c+e()*(o-c))},reset(){n=0}}},"s");var ut=500,ns=a((t,e)=>{if(t.size<e)return;let r=t.keys().next().value;r!==void 0&&t.delete(r)},"ot"),J=class{static{a(this,"C")}listeners=new Set;add(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}emit(...e){let[r]=e;for(let s of this.listeners)try{s(r)}catch{}}clear(){this.listeners.clear()}},as="/_lunora/rpc",dr="/_lunora/rpc-batch",os="/_lunora/ws",ht=a(t=>t===void 0||t===""?"":`&bucket=${encodeURIComponent(t)}`,"M"),Le=a(t=>{for(let e=t.length-1;e>=0;e-=1)t[e]?.()},"O"),cs=a((t,e)=>{for(let r of e)r.op==="delete"?t.delete(r.key):r.value!==void 0&&t.set(r.key,r.value)},"ut"),us="lunora-ping",hs=3e4,ds=1e4,ls=250,fs=64,ps="/_lunora/admin/shard-traffic",ms="/_lunora/admin/scheduled",ys="/_lunora/admin/scheduled/status",bs="/_lunora/admin/scheduled/ws",vs="/_lunora/admin/scheduled/cancel",gs="/_lunora/admin/scheduled/dead",Ss="/_lunora/admin/scheduled/dead/retry",ws="/_lunora/admin/scheduled/dead/cancel",Cs="/_lunora/admin/workflows/instances",ks="/_lunora/admin/workflows/instance",Is="/_lunora/admin/workflows/status",dt="/_lunora/admin/storage",Es="/_lunora/admin/storage/url",Ts="/_lunora/admin/storage/buckets",Os="/_lunora/admin/functions",Rs="/_lunora/admin/cron-jobs",Ps="/_lunora/admin/cron-jobs/run",As="/_lunora/admin/openapi",Fs="/_lunora/admin/openrpc",Ms="/_lunora/admin/global/tables",xs="/_lunora/admin/global/table",_s="/_lunora/admin/global/facet",Ls="/_lunora/admin/vector/indexes",Qs="/_lunora/admin/vector/query",Ds="/_lunora/admin/logs/archive",Us="/_lunora/admin/kv/namespaces",qs="/_lunora/admin/kv/keys",lt="/_lunora/admin/kv/value",Ks="/_lunora/admin/auth/users",Ns="/_lunora/admin/auth/sessions",Bs="/_lunora/admin/auth/users/create",js="/_lunora/admin/auth/users/role",$s="/_lunora/admin/auth/users/ban",Hs="/_lunora/admin/auth/users/unban",zs="/_lunora/admin/auth/users/password",Ws="/_lunora/admin/auth/users/remove",Vs="/_lunora/admin/auth/users/impersonate",Gs="/_lunora/admin/auth/sessions/revoke",Js="/_lunora/admin/auth/sessions/revoke-all",Xs="/_lunora/admin/auth/capabilities",Ys="/_lunora/admin/auth/users/update",Zs="/_lunora/admin/auth/accounts",ei="/_lunora/admin/auth/accounts/unlink",ti="/_lunora/admin/auth/passkeys",ri="/_lunora/admin/auth/passkeys/delete",si="/_lunora/admin/auth/two-factor/disable",ii="/_lunora/admin/auth/organizations",ni="/_lunora/admin/auth/organizations/members",ai="/_lunora/admin/auth/organizations/invitations",oi="/_lunora/admin/auth/organizations/members/remove",ci="/_lunora/admin/auth/organizations/invitations/cancel",ui="/_lunora/admin/auth/config",hi="/_lunora/admin/auth/organizations/create",di="/_lunora/admin/auth/organizations/update",li="/_lunora/admin/auth/organizations/remove",fi="/_lunora/admin/auth/organizations/members/add",pi="/_lunora/admin/auth/organizations/members/invite",mi="/_lunora/admin/auth/organizations/members/role",yi="/_lunora/admin/auth/organizations/teams",bi="/_lunora/admin/auth/organizations/teams/create",vi="/_lunora/admin/auth/organizations/teams/update",gi="/_lunora/admin/auth/organizations/teams/remove",Si="/_lunora/admin/auth/organizations/teams/members",wi="/_lunora/admin/auth/organizations/teams/members/add",Ci="/_lunora/admin/auth/organizations/teams/members/remove",ki="/_lunora/admin/auth/organizations/roles",Ii="/_lunora/admin/auth/organizations/roles/create",Ei="/_lunora/admin/auth/organizations/roles/update",Ti="/_lunora/admin/auth/organizations/roles/remove",Oi="/api/auth",Ri="/get-session",lr=a(t=>t.startsWith("https://")?`wss://${t.slice(8)}`:t.startsWith("http://")?`ws://${t.slice(7)}`:t,"U"),V=a((t,e)=>`${t.endsWith("/")?t.slice(0,-1):t}${e}`,"v"),T=a((t,e)=>{let r=new URLSearchParams;for(let[i,n]of Object.entries(e))n!==void 0&&n!==""&&r.set(i,String(n));let s=r.toString();return s===""?t:`${t}?${s}`},"f"),Pi=[Zt],C=a(t=>t??"","m"),pr=a((t,e)=>{let r=t.error,s=typeof r?.code=="string"?r.code:void 0,i=typeof r?.message=="string"?r.message:void 0;return{code:s,messageText:(typeof t.message=="string"?t.message:void 0)??i??e}},"W"),Ai=a(t=>{let{code:e,messageText:r}=pr(t,"stream error");return e===void 0?new Error(r):new p(e,r)},"xe"),fr=a(t=>{let{code:e,messageText:r}=pr(t,"subscription error");return{message:r,...e===void 0?{}:{code:e}}},"N"),Qe=a((t,e)=>{for(let r of t)try{r(e)}catch{}},"E"),Fi=new TextDecoder,Mi=a(t=>{if(typeof t=="string")return t;if(t instanceof ArrayBuffer)return Fi.decode(t)},"Me"),F=a((t,e)=>{if(!t.socket||t.wsState!=="open")return!1;try{return t.socket.send(JSON.stringify(e)),!0}catch{return!1}},"g"),de=a(t=>{let e=new Error(t.message??"request failed");return e.code=t.code,t.data!==void 0&&(e.data=S(t.data)),t.hint!==void 0&&(e.hint=t.hint),t.docsUrl!==void 0&&(e.docsUrl=t.docsUrl),e},"T"),G=a((t,e)=>{try{return O(t)}catch(r){let s=r instanceof Error?r.message:String(r);throw new TypeError(`LunoraClient: cannot encode ${e} \u2014 ${s}`,r instanceof Error?{cause:r}:void 0)}},"k"),xi=a((t,e)=>{let r=Array.from({length:e});for(let s of t){if(typeof s.id!="number"||s.id<0||s.id>=e)continue;let i=s.body;r[s.id]=i&&"error"in i&&i.error?{error:de(i.error),ok:!1}:{ok:!0,value:S(i?.result)}}return r.map(s=>s??{error:new Error("batch call returned no result"),ok:!1})},"Le"),_i=new Set(["SHARD_ERROR","SHARD_UNAVAILABLE"]),Li=Promise.resolve(),ft=class t{static{a(this,"z")}static MAX_POKE_BUFFERS=256;static createClientQuery(e,r){return{defaultValue:r,key:e}}url;wsUrl;clientQueryStore;wsToken;authBasePath;fetchImpl;WebSocketImpl;bookmark;reconnectOptions;connectTimeoutMs;heartbeatIntervalMs;offlineQueue;outbox;clientId;shardCursors=new Map;defaultShardKey;readyResolved=!1;readyResolve;readyPromise;clientWatermarks=new Map;outboxMutationCounter=0;onPersistenceError;persistence;persistenceVersion;outboxLeaderRelease;queryCache;hydratedQueryCache=new Map;pendingCacheWrites=new Map;cacheFlushTimer;subscriptions=new _;tabCoordinator;leaderStatus;leaderWasEverConnected=!1;connections=new Map;defaultConnectionContext;connectionContexts=new Map;connectionContextHolders=new Map;authToken=null;authSubject=void 0;queuedIdentities=new Map;queuedOfflineShardKeys=new Set;closed=!1;authTokenListeners=new J;statusListeners=new J;tokenExpiredListeners=new J;mutationSettledListeners=new J;pendingChangeListeners=new J;whisperHandlers=new Map;lastStatus="idle";nextSubId=0;nextStreamId=0;streams=new Map;shapeSubscriptions=new Map;pokeBuffers=new Map;nextShapeId=0;constructor(e){this.url=e.url,this.wsUrl=e.wsUrl??V(lr(e.url),os),this.wsToken=e.wsToken;let r=e.authBasePath??Oi;this.authBasePath=r.endsWith("/")?r.slice(0,-1):r,this.fetchImpl=e.fetch??(typeof fetch=="function"?fetch.bind(globalThis):void 0),this.WebSocketImpl=e.WebSocket??(typeof WebSocket=="function"?WebSocket:void 0),this.bookmark=e.bookmarkStorage??Gt(),this.reconnectOptions=e.reconnect,this.heartbeatIntervalMs=e.heartbeatIntervalMs??hs,this.connectTimeoutMs=e.connectTimeoutMs??ds,this.defaultConnectionContext=e.connectionContext,this.persistence=cr(e.persistence,e.outbox===void 0),this.persistenceVersion=e.persistenceVersion,this.queryCache=hr(e.queryCache),this.onPersistenceError=e.offlineQueue?.onPersistenceError,this.clientQueryStore=new Te,e.crossTabSync?(this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start()):this.tabCoordinator=void 0,e.hydrateOnStart&&this.queryCache?this.readyPromise=new Promise(s=>{this.readyResolve=s}):(this.readyResolved=!0,this.readyPromise=Li),this.offlineQueue=new Ae(e.offlineQueue,{onEvict:a((s,i)=>{this.emitItemSettled(s,"rejected",i)},"onEvict"),onSizeChange:a(s=>{this.pendingChangeListeners.emit(s)},"onSizeChange"),persistence:this.persistence,version:e.persistenceVersion}),this.outbox=e.outbox,this.clientId=e.clientId??`client-${Fe()}`,this.persistence&&queueMicrotask(()=>{this.hydrateAsOutboxLeader()}),this.queryCache&&queueMicrotask(()=>{(async()=>{try{await this.hydrateQueryCache()}catch{}finally{this.readyResolved=!0,this.readyResolve?.()}})().catch(()=>{})})}setAuthToken(e,r){let s=this.authToken!==e,i=this.identityFingerprint();this.authToken=e,r!==void 0&&(this.authSubject=r);let n=this.identityFingerprint();if(n!==i&&(s?this.rejectQueuedForIdentityChange():this.restampQueuedIdentity(i,n),this.tabCoordinator)){let o=this.tabCoordinator.isLeader();this.tabCoordinator.stop(),this.tabCoordinator=this.createTabCoordinator(),this.tabCoordinator.start(),o&&this.tabCoordinator.promoteImmediately()}s&&this.authTokenListeners.emit(e)}getAuthToken(){return this.authToken}currentIdentity(){return this.identityFingerprint()}clientIdentifier(){return this.clientId}confirmedMutationWatermark(e){return this.clientWatermarks.get(e??"")??0}async callMutator(e,r,s){let i=s?.clientSeq;if(i!==void 0&&(!Number.isInteger(i)||i<=0))throw new p("INTERNAL",`callMutator: clientSeq must be a positive integer, got ${String(i)}`);let n=s?.shardKey??"",o,c=await this.rpc(e,r,s?.shardKey,{captureBookmark:!0,clientId:this.clientId,clientSeq:i,onMutationAck:a(u=>{o=u},"onMutationAck")});return o!==void 0&&o>(this.clientWatermarks.get(n)??0)&&this.clientWatermarks.set(n,o),{applied:o===void 0||o===i,result:c}}onAuthTokenChange(e){return this.authTokenListeners.add(e)}async getCurrentUser(){if(this.closed||!this.fetchImpl)return null;let e={};this.authToken&&(e.authorization=`Bearer ${this.authToken}`);try{let r=await this.fetchImpl(V(this.url,`${this.authBasePath}${Ri}`),{credentials:"include",headers:e,method:"GET"});return r.ok?(await r.json())?.user??null:null}catch{return null}}setWsToken(e){if(this.wsToken!==e){this.wsToken=e;for(let r of this.connections.values())if(r.socket)try{r.socket.close()}catch{}}}setConnectionContext(e,r={}){let s=C(r.shardKey);e===void 0?this.connectionContexts.delete(s):this.connectionContexts.set(s,e),this.refreshConnectionContext(s)}acquireConnectionContext(e,r={}){let s=C(r.shardKey),i={context:e},n=this.connectionContextHolders.get(s);n?n.push(i):this.connectionContextHolders.set(s,[i]),this.refreshConnectionContext(s);let o=!1;return()=>{if(o)return;o=!0;let c=this.connectionContextHolders.get(s);if(!c)return;let u=c.indexOf(i);u!==-1&&c.splice(u,1),c.length===0&&this.connectionContextHolders.delete(s),this.refreshConnectionContext(s)}}whisperSubscribe(e,r,s={}){let i=C(s.shardKey),n=this.whisperHandlers.get(i);n||(n=new Map,this.whisperHandlers.set(i,n));let o=n.get(e),c=o===void 0;if(o||(o=new Set,n.set(e,o)),o.add(r),this.ensureSocket(s.shardKey),c){let u=this.getConnection(s.shardKey);u&&F(u,{topic:e,type:"whisper_subscribe"})}return()=>{let u=this.whisperHandlers.get(i),d=u?.get(e);if(!d?.delete(r)||d.size>0)return;u?.delete(e),u?.size===0&&this.whisperHandlers.delete(i);let h=this.getConnection(s.shardKey);h&&F(h,{topic:e,type:"whisper_unsubscribe"})}}whisper(e,r,s={}){this.ensureSocket(s.shardKey);let i=this.getConnection(s.shardKey);i&&F(i,{data:G(r??null,`whisper data for topic '${e}'`),topic:e,type:"whisper"})}onTokenExpired(e){return this.tokenExpiredListeners.add(e)}connectionStatus(){return this.computeStatus()}onConnectionStatus(e){let r=this.statusListeners.add(e);return e(this.computeStatus()),r}pendingCount(){return this.offlineQueue.size}debug(){let e=[],r=new Set([...this.connections.keys(),...this.clientWatermarks.keys()]);for(let i of r){let n=this.connections.get(i);e.push({confirmedMutationWatermark:this.clientWatermarks.get(i)??0,hasSocket:n?.socket!==void 0,shardKey:i===""?void 0:i,wasEverConnected:n?.wasEverConnected??!1,wsState:n?.wsState??"idle"})}let s=this.subscriptions.all().map(i=>({acked:i.acked,functionPath:i.fn.__lunoraRef,id:i.id,kind:"query",lastMutationId:i.lastMutationId,pendingOptimisticLayers:i.optimisticLayers.length,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size}));for(let i of this.shapeSubscriptions.values())s.push({acked:i.serverCursor!==void 0,functionPath:`shape:${i.name}`,id:i.id,kind:"shape",lastMutationId:i.lastMutationId,pendingOptimisticLayers:0,rowCount:i.rows.size,serverCursor:i.serverCursor,shardKey:i.shardKey,subscriberCount:i.callbacks.size});return{clientId:this.clientId,closed:this.closed,connectionStatus:this.computeStatus(),pendingWrites:this.offlineQueue.size,shards:e.toSorted((i,n)=>(i.shardKey??"").localeCompare(n.shardKey??"")),subscriptions:s.toSorted((i,n)=>i.functionPath.localeCompare(n.functionPath))}}onPendingChange(e){let r=this.pendingChangeListeners.add(e);return e(this.offlineQueue.size),r}onMutationSettled(e){return this.mutationSettledListeners.add(e)}getWebSocketImpl(){return this.WebSocketImpl}getClientQuery(e){return this.clientQueryStore.get(e)}setClientQuery(e,r){this.clientQueryStore.set(e,r)}subscribeClientQuery(e,r){return this.clientQueryStore.subscribe(e,r)}resetClientQuery(e){this.clientQueryStore.reset(e)}snapshotPrecondition(e,r,s){let i=this.peekActiveQueryValue(e.__lunoraRef,r,s),n=i===void 0?void 0:W(i);return()=>{let o=this.peekActiveQueryValue(e.__lunoraRef,r,s);return n===void 0&&o===void 0?!0:n===void 0||o===void 0?!1:W(o)===n}}whenReady(){return this.readyPromise}get isReady(){return this.readyResolved}peekHydratedQuery(e,r,s){if(!this.readyResolved)return;let i=W(r),n=_e(e,i,s),o=this.hydratedQueryCache.get(n);if(o!==void 0)return o.identity===this.identityFingerprint()?o.value:void 0}peekActiveQueryValue(e,r,s){let i=_.key(e,r,s);return this.subscriptions.get(i)?.lastValue}async query(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey,{attachBookmark:!0})}async batch(e){if(this.assertOpen(),!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");if(e.length===0)return[];let r=await this.fetchImpl(V(this.url,dr),{body:JSON.stringify({calls:e.map((n,o)=>({args:G(n.args??{},`args for batch call '${n.fn.__lunoraRef}'`),functionPath:n.fn.__lunoraRef,id:o,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"}),s=r.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await r.json()}catch{throw new p("INTERNAL",`LunoraClient: batch response was not JSON (status ${r.status.toString()})`)}if(!r.ok||i.error&&!i.results)throw i.error?de(i.error):new p("INTERNAL",`LunoraClient: batch request failed (status ${r.status.toString()})`);for(let n of i.results??[]){let o=n.body?.commitCursor;typeof n.id=="number"&&typeof o=="number"&&this.recordShardCursor(e[n.id]?.shardKey,o)}return xi(i.results??[],e.length)}async mutation(e,r,s={}){this.assertOpen();let i=r,n=s.mutationId??Fe(),{confirms:o,rollbacks:c}=this.applyOptimisticUpdates(e.__lunoraRef,i,s.shardKey,s.optimistic);s.optimisticUpdate&&this.applyOptimisticUpdate(s.optimisticUpdate,r,s.shardKey,c,o);let{hasSocket:u,wasEverConnected:d,wsState:h}=this.connectionGateState(s.shardKey),{queueBeforeFirstConnect:l}=this.offlineQueue,f=d||l,m=this.WebSocketImpl!==void 0&&f;if(h!=="open"&&!u&&m||h==="connecting"&&f)return this.enqueueOfflineMutation(e,i,s.shardKey,n,c,o,s.precondition);try{let y,b=await this.rpc(e.__lunoraRef,i,s.shardKey,{captureBookmark:!0,mutationId:n,onCommitCursor:a(w=>{y=w},"onCommitCursor")});for(let w of o)w(y);return b}catch(y){throw Le(c),y}}async action(e,r,s={}){return this.assertOpen(),await this.rpc(e.__lunoraRef,r,s.shardKey)}async importRows(e,r,s={}){this.assertOpen();let i=Math.max(1,Math.trunc(s.chunkSize??500)),n=s.toArgs??(d=>({rows:d})),o=r.length,c=0,u=0;for(let d=0;d<o;d+=i){let h=r.slice(d,d+i),l=u;await this.mutation(e,n(h),{...s.importId===void 0?{}:{mutationId:`${s.importId}:${String(l)}`},shardKey:s.shardKey}),u+=1,c+=h.length,s.onProgress?.({done:c,total:o})}return{chunks:u,imported:c}}async shardTraffic(e){this.assertOpen();let r=await this.adminFetch(ps,"POST",{table:e});return{failed:r.failed??0,ok:r.ok??0,shards:r.shards??[]}}async listScheduledJobs(){return this.assertOpen(),(await this.adminFetch(ms,"GET")).records??[]}async schedulerStatus(){this.assertOpen();let e=await this.adminFetch(ys,"GET");return{backlog:e.backlog??0,inFlight:e.inFlight??0,pools:e.pools??[]}}async cancelScheduledJob(e){return this.assertOpen(),{cancelled:(await this.adminFetch(vs,"POST",{id:e})).cancelled===!0}}async listDeadJobs(){return this.assertOpen(),(await this.adminFetch(gs,"GET")).records??[]}async retryDeadJob(e){return this.assertOpen(),{retried:(await this.adminFetch(Ss,"POST",{id:e})).retried===!0}}async removeDeadJob(e){return this.assertOpen(),{removed:(await this.adminFetch(ws,"POST",{id:e})).removed===!0}}async listWorkflowInstances(e){this.assertOpen();let r=new URLSearchParams({name:e.name});e.status!==void 0&&r.set("status",e.status),e.page!==void 0&&r.set("page",String(e.page)),e.perPage!==void 0&&r.set("perPage",String(e.perPage));let s=await this.adminFetch(`${Cs}?${r.toString()}`,"GET");return{configured:s.configured,instances:s.instances??[],page:s.page??1,perPage:s.perPage??e.perPage??0,totalCount:s.totalCount}}async getWorkflowInstance(e){this.assertOpen();let r=new URLSearchParams({id:e.id,name:e.name}),s=await this.adminFetch(`${ks}?${r.toString()}`,"GET");return{createdOn:s.createdOn,endedOn:s.endedOn,error:s.error,id:s.id??e.id,output:s.output,params:s.params,startedOn:s.startedOn,status:s.status??"unknown",steps:s.steps??[]}}async setWorkflowInstanceStatus(e){return this.assertOpen(),{status:(await this.adminFetch(Is,"POST",{action:e.action,id:e.id,name:e.name})).status??"unknown"}}subscribeScheduledJobs(e){if(this.assertOpen(),this.WebSocketImpl===void 0)return()=>{};let r=V(lr(this.url),bs),s=ct(this.reconnectOptions),i={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,socket:void 0},n,o=!1,c=a(()=>{o||(n=setTimeout(h,s.next()))},"a"),u=a(l=>{if(o||this.WebSocketImpl===void 0)return;let f=l===void 0?r:`${r}?token=${encodeURIComponent(l)}`;this.openManagedSocket(i,f,this.connectTimeoutMs,{onClose:a(()=>{c()},"onClose"),onMessage:a(m=>{try{let y=JSON.parse(typeof m.data=="string"?m.data:"");y.type==="jobs"&&Array.isArray(y.records)&&e(y.records)}catch{}},"onMessage"),onOpen:a(()=>{s.reset()},"onOpen")})},"o"),d=a(async l=>{let f;try{f=await l()}catch{c();return}u(f)},"c"),h=a(()=>{if(o||this.WebSocketImpl===void 0)return;let{wsToken:l}=this;if(typeof l=="function"){d(l).catch(()=>{});return}u(l)},"u");return h(),()=>{o=!0,n!==void 0&&clearTimeout(n),i.connectTimer!==void 0&&(clearTimeout(i.connectTimer),i.connectTimer=void 0),this.stopHeartbeat(i),i.socket?.close()}}async listFunctions(){return this.assertOpen(),(await this.adminFetch(Os,"GET")).functions??[]}async getCronJobs(){return this.assertOpen(),(await this.adminFetch(Rs,"GET")).jobs??[]}async runCronJob(e){this.assertOpen();let r=await this.adminFetch(Ps,"POST",{name:e});return{name:r.name??e,ran:r.ran===!0}}async fetchOpenApi(){return this.assertOpen(),await this.adminFetch(As,"GET")}async fetchOpenRpc(){return this.assertOpen(),await this.adminFetch(Fs,"GET")}async listStorageObjects(e={}){this.assertOpen();let r=T(dt,{bucket:e.bucket,cursor:e.cursor,limit:e.limit,prefix:e.prefix}),s=await this.adminFetch(r,"GET");return{cursor:s.cursor,objects:s.objects??[]}}async deleteStorageObject(e,r){this.assertOpen();let s=`${dt}?key=${encodeURIComponent(e)}${ht(r?.bucket)}`,i=await this.adminFetch(s,"DELETE");return{deleted:i.deleted??!0,key:i.key??e}}async listStorageBuckets(){return this.assertOpen(),(await this.adminFetch(Ts,"GET")).buckets??[]}async uploadStorageObject(e){this.assertOpen();let r=`${dt}?key=${encodeURIComponent(e.key)}${ht(e.bucket)}`,s=await this.adminFetch(r,"PUT",e.body,e.contentType);return{etag:s.etag,key:s.key??e.key}}async signedStorageUrl(e,r){this.assertOpen();let s=r?.expiresInSeconds,i=s===void 0?"":`&expiresIn=${encodeURIComponent(s.toString())}`,n=`${Es}?key=${encodeURIComponent(e)}${i}${ht(r?.bucket)}`,o=await this.adminFetch(n,"GET");if(typeof o.url!="string")throw new TypeError("LunoraClient: storage URL endpoint returned no `url`");return o.url}async listGlobalTables(){return this.assertOpen(),await this.adminFetch(Ms,"GET")}async readGlobalTablePage(e){this.assertOpen();let r=new URLSearchParams({table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.offset!==void 0&&r.set("offset",String(e.offset)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${xs}?${r.toString()}`,"GET")}async facetGlobalColumn(e){this.assertOpen();let r=new URLSearchParams({column:e.column,table:e.table});return e.limit!==void 0&&r.set("limit",String(e.limit)),e.filters!==void 0&&e.filters.length>0&&r.set("filters",JSON.stringify(e.filters)),await this.adminFetch(`${_s}?${r.toString()}`,"GET")}async listVectorIndexes(){return this.assertOpen(),(await this.adminFetch(Ls,"GET")).indexes??[]}async queryVectorIndex(e){return this.assertOpen(),(await this.adminFetch(Qs,"POST",e)).matches??[]}async queryLogArchive(e={}){this.assertOpen();let r=await this.adminFetch(Ds,"POST",e);return{nextCursor:r.nextCursor,rows:r.rows??[]}}async listKvNamespaces(){return this.assertOpen(),(await this.adminFetch(Us,"GET")).namespaces??[]}async listKvKeys(e){this.assertOpen();let r=T(qs,{cursor:e.cursor,limit:e.limit,namespace:e.namespace,prefix:e.prefix});return await this.adminFetch(r,"GET")}async getKvValue(e){this.assertOpen();let r=T(lt,{key:e.key,namespace:e.namespace});return await this.adminFetch(r,"GET")}async putKvValue(e){this.assertOpen(),await this.adminFetch(lt,"PUT",e)}async deleteKvKey(e){this.assertOpen();let r=T(lt,{key:e.key,namespace:e.namespace});await this.adminFetch(r,"DELETE")}async listAuthUsers(e={}){this.assertOpen();let r=T(Ks,{filterField:e.filterField,filterValue:e.filterValue,limit:e.limit,offset:e.offset,search:e.search,searchField:e.searchField,sortBy:e.sortBy,sortDirection:e.sortDirection});return await this.adminFetch(r,"GET")}async createAuthUser(e){return await this.adminFetch(Bs,"POST",e)}async setAuthUserRole(e){return await this.adminFetch(js,"POST",e)}async banAuthUser(e){return await this.adminFetch($s,"POST",e)}async unbanAuthUser(e){return await this.adminFetch(Hs,"POST",e)}async setAuthUserPassword(e){await this.adminFetch(zs,"POST",e)}async removeAuthUser(e){await this.adminFetch(Ws,"POST",e)}async impersonateAuthUser(e){return await this.adminFetch(Vs,"POST",e)}async revokeAuthSession(e){await this.adminFetch(Gs,"POST",e)}async revokeAuthUserSessions(e){await this.adminFetch(Js,"POST",e)}async getAuthCapabilities(){return await this.adminFetch(Xs,"GET")}async updateAuthUser(e){return await this.adminFetch(Ys,"POST",e)}async listAuthAccounts(e){return await this.adminFetch(T(Zs,{userId:e.userId}),"GET")}async unlinkAuthAccount(e){await this.adminFetch(ei,"POST",e)}async listAuthPasskeys(e){return await this.adminFetch(T(ti,{userId:e.userId}),"GET")}async deleteAuthPasskey(e){await this.adminFetch(ri,"POST",e)}async disableAuthTwoFactor(e){await this.adminFetch(si,"POST",e)}async listAuthOrganizations(e={}){return await this.adminFetch(T(ii,{limit:e.limit,offset:e.offset}),"GET")}async listAuthOrgMembers(e){let r=T(ni,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async listAuthOrgInvitations(e){let r=T(ai,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async removeAuthOrgMember(e){await this.adminFetch(oi,"POST",e)}async cancelAuthOrgInvitation(e){await this.adminFetch(ci,"POST",e)}async getAuthConfig(){return await this.adminFetch(ui,"GET")}async createAuthOrganization(e){return await this.adminFetch(hi,"POST",e)}async updateAuthOrganization(e){return await this.adminFetch(di,"POST",e)}async deleteAuthOrganization(e){await this.adminFetch(li,"POST",e)}async addAuthOrgMember(e){return await this.adminFetch(fi,"POST",e)}async inviteAuthOrgMember(e){return await this.adminFetch(pi,"POST",e)}async setAuthOrgMemberRole(e){return await this.adminFetch(mi,"POST",e)}async listAuthOrgTeams(e){let r=T(yi,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgTeam(e){return await this.adminFetch(bi,"POST",e)}async updateAuthOrgTeam(e){return await this.adminFetch(vi,"POST",e)}async removeAuthOrgTeam(e){await this.adminFetch(gi,"POST",e)}async listAuthOrgTeamMembers(e){let r=T(Si,{limit:e.limit,offset:e.offset,teamId:e.teamId});return await this.adminFetch(r,"GET")}async addAuthOrgTeamMember(e){return await this.adminFetch(wi,"POST",e)}async removeAuthOrgTeamMember(e){await this.adminFetch(Ci,"POST",e)}async listAuthOrgRoles(e){let r=T(ki,{limit:e.limit,offset:e.offset,organizationId:e.organizationId});return await this.adminFetch(r,"GET")}async createAuthOrgRole(e){return await this.adminFetch(Ii,"POST",e)}async updateAuthOrgRole(e){return await this.adminFetch(Ei,"POST",e)}async deleteAuthOrgRole(e){await this.adminFetch(Ti,"POST",e)}async listAuthSessions(e={}){this.assertOpen();let r=T(Ns,{limit:e.limit,offset:e.offset,userId:e.userId});return await this.adminFetch(r,"GET")}subscribe(e,r,s,i={}){this.assertOpen();let n=r??{},o=_.key(e.__lunoraRef,n,i.shardKey),c=this.subscriptions.get(o),u=s,d=i.onError;if(!c){this.nextSubId+=1;let l=`sub_${this.nextSubId.toString()}`,f=W(n),m=this.takeHydratedCache(e.__lunoraRef,f,i.shardKey);c={acked:!1,args:n,argsKey:f,callbacks:new Set,checkpointCallbacks:new Set,errorCallbacks:new Set,fn:e,id:l,lastValue:m?.value,optimisticLayers:[],serverBase:m?.value,serverCursor:m?.serverCursor,shardKey:i.shardKey,...m?.serverEpoch===void 0?{}:{serverEpoch:m.serverEpoch}},this.subscriptions.add(c)}if(c.callbacks.add(u),d&&c.errorCallbacks.add(d),i.onCheckpoint&&c.checkpointCallbacks.add(i.onCheckpoint),c.lastValue!==void 0)try{u(c.lastValue)}catch{}this.ensureSocket(i.shardKey),this.sendSubscribeIfOpen(c);let h=c;return()=>{h.callbacks.delete(u),d&&h.errorCallbacks.delete(d),i.onCheckpoint&&h.checkpointCallbacks.delete(i.onCheckpoint),h.callbacks.size===0&&(this.sendOrQueueUnsubscribe(h.shardKey,h.id,"unsubscribe"),this.subscriptions.remove(h))}}subscribeShape(e,r,s={}){this.assertOpen(),this.nextShapeId+=1;let i=`shape_${this.nextShapeId.toString()}`,n={args:e.args,callbacks:new Set([r]),errorCallbacks:s.onError?new Set([s.onError]):new Set,id:i,name:e.name,onCheckpoint:s.onCheckpoint,rows:new Map,shardKey:s.shardKey,wireArgs:e.args===void 0?void 0:G(e.args,`shape args for '${e.name}'`)};return this.shapeSubscriptions.set(i,n),this.ensureSocket(s.shardKey),this.sendShapeSubscribeIfOpen(n),()=>{this.shapeSubscriptions.delete(i),this.sendOrQueueUnsubscribe(n.shardKey,i,"shape_unsubscribe")}}stream(e,r,s={}){if(this.assertOpen(),this.WebSocketImpl===void 0)throw new p("INTERNAL","LunoraClient: streams require a WebSocket implementation");this.nextStreamId+=1;let i=`stream_${this.nextStreamId.toString()}`,{shardKey:n}=s,o=r??{},{handle:c,iterable:u}=Re({maxBuffer:s.maxBuffer,onCancel:a(()=>{let l=this.getConnection(n);l&&F(l,{id:i,type:"unsubscribe"}),this.streams.delete(i)},"onCancel")});this.ensureSocket(n);let d=this.getConnection(n),h={id:i,query:{args:G(o,`stream args for '${e.__lunoraRef}'`),functionPath:e.__lunoraRef,shardKey:n},type:"stream"};if(this.streams.set(i,{durable:s.durable===!0,handle:c,lastSeq:0,message:h,shardKey:n}),!(d?.wsState==="open"&&F(d,h))&&d){for(d.pendingStreams=d.pendingStreams??[];d.pendingStreams.length>=fs;){let l=d.pendingStreams.shift()?.id,f=l?this.streams.get(l):void 0;f&&(f.handle.fail(new p("STREAM_QUEUE_OVERFLOW","stream-start frame evicted while socket was unreachable")),this.streams.delete(l))}d.pendingStreams.push(h)}return u}httpStream(e,r,s={}){if(this.closed)throw new p("CLIENT_CLOSED","LunoraClient is closed");if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let i={...this.authToken?{authorization:`Bearer ${this.authToken}`}:{},...s.headers};return ir(e,r,{baseUrl:this.url,fetch:this.fetchImpl,headers:i,maxBuffer:s.maxBuffer,signal:s.signal})}close(){this.closed=!0,this.outboxLeaderRelease?.(),this.outboxLeaderRelease=void 0;for(let e of this.streams.values())e.handle.fail(new p("CLIENT_CLOSED","LunoraClient closed"));this.streams.clear();for(let e of this.connections.values())this.teardownConnection(e);this.offlineQueue.clear(),this.queuedIdentities.clear(),this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.size>0&&this.flushQueryCacheWrites().catch(()=>{}),this.authTokenListeners.clear(),this.statusListeners.clear(),this.tokenExpiredListeners.clear(),this.mutationSettledListeners.clear(),this.pendingChangeListeners.clear(),this.whisperHandlers.clear(),this.shapeSubscriptions.clear(),this.pokeBuffers.clear(),this.tabCoordinator?.stop(),this.tabCoordinator=void 0}assertOpen(){if(this.closed)throw new p("INTERNAL","LunoraClient is closed")}teardownConnection(e){if(e.reconnectTimer!==void 0&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=void 0),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),this.stopHeartbeat(e),e.socket){try{e.socket.close()}catch{}e.socket=void 0}e.wsState="closed"}createTabCoordinator(){let e=`lunora-bridge::${this.url}::${this.identityFingerprint()??"anon"}`;return new Oe({channelName:e,onBecomeLeader:a(()=>{for(let r of this.subscriptions.all())this.ensureSocket(r.shardKey),this.sendSubscribeIfOpen(r);this.tabCoordinator?.broadcastConnectionStatus(this.computeStatus(),this.identityFingerprint())},"onBecomeLeader"),onStopBeingLeader:a(()=>{for(let[r,s]of this.connections)this.teardownConnection(s),this.connections.delete(r);this.leaderStatus=void 0,this.leaderWasEverConnected=!1},"onStopBeingLeader"),onConnectionStatus:a((r,s)=>{if(s!==void 0&&s!==this.identityFingerprint())return;let i=r==="connected"&&this.leaderStatus!=="connected";this.leaderStatus=r,r==="connected"&&(this.leaderWasEverConnected=!0),this.emitConnectionStatus(),i&&this.flushAllOfflineQueues()},"onConnectionStatus"),onSubscriptionData:a((r,s,i,n,o)=>{if(o!==void 0&&o!==this.identityFingerprint())return;let c=this.subscriptions.get(r);c&&(c.serverBase=s,i!==void 0&&(c.serverCursor=i,n!==void 0&&(c.serverEpoch=n),Pe(c,i)),te(c,he(s,c.optimisticLayers)))},"onSubscriptionData"),onSubscriptionError:a((r,s)=>{let i=this.subscriptions.get(r);i&&Qe(i.errorCallbacks,s)},"onSubscriptionError"),onSubscriptionSettled:a((r,s,i,n,o,c)=>{if(c!==void 0&&c!==this.identityFingerprint())return;let u=this.subscriptions.get(r);if(u){this.ackAndAdvanceCursor(u,s,i),n!==void 0&&o===this.clientId&&(u.lastMutationId=Math.max(u.lastMutationId??0,n));for(let d of u.checkpointCallbacks)d({checkpoint:u.serverCursor,mutationId:u.lastMutationId})}},"onSubscriptionSettled")})}async enqueueOfflineMutation(e,r,s,i,n,o,c){let u=this.identityFingerprint();if(this.outbox){this.outboxMutationCounter+=1;let d=this.outboxMutationCounter;try{await this.outbox.enqueue({args:r,clientId:this.clientId,functionPath:e.__lunoraRef,idempotencyKey:`${this.clientId}:${String(d)}`,identity:u,mutationId:d,shardKey:s})}catch(h){throw Le(n),h instanceof Error?h:new Error(String(h))}for(let h of o)h(void 0);return}return new Promise((d,h)=>{let l={args:r,functionPath:e.__lunoraRef,liveAwaiter:!0,id:i,clientId:this.clientId,identity:u,precondition:c,onCommit:a(f=>{for(let m of o)m(f)},"onCommit"),reject:a(f=>{this.queuedIdentities.delete(i),Le(n),h(f instanceof Error?f:new Error(String(f)))},"reject"),resolve:d,shardKey:s};this.offlineQueue.enqueue(l),this.queuedOfflineShardKeys.add(s),l.id!==void 0&&this.queuedIdentities.set(l.id,u)})}async hydratePersistedQueue(){try{let e=await this.offlineQueue.hydrate();for(let r of e)this.queuedOfflineShardKeys.add(r),this.ensureSocket(r)}catch{}}hydrateAsOutboxLeader(){let e=a(()=>{this.hydratePersistedQueue().catch(()=>{})},"t"),r=globalThis.navigator?.locks;if(!r){e();return}r.request(`lunora:outbox-leader:${this.url}`,()=>(this.closed||e(),new Promise(s=>{if(this.closed){s();return}this.outboxLeaderRelease=s}))).catch(e)}async hydrateQueryCache(){if(this.queryCache)try{let e=await this.queryCache.load();for(let{key:r,...s}of e){if(ot(this.persistenceVersion,s.version)){this.queryCache.remove(r).catch(()=>{});continue}this.hydratedQueryCache.set(r,s)}}catch{}}takeHydratedCache(e,r,s){let i=_e(e,r,s),n=this.hydratedQueryCache.get(i);if(n!==void 0)return this.hydratedQueryCache.delete(i),n.identity===this.identityFingerprint()?n:void 0}persistQueryValue(e){let r=e.serverBase;if(!this.queryCache||r===void 0)return;let s=_e(e.fn.__lunoraRef,e.argsKey,e.shardKey);this.pendingCacheWrites.set(s,{identity:this.identityFingerprint(),serverCursor:e.serverCursor,ts:Date.now(),value:r,...e.serverEpoch===void 0?{}:{serverEpoch:e.serverEpoch},...this.persistenceVersion===void 0?{}:{version:this.persistenceVersion}}),this.cacheFlushTimer??=setTimeout(()=>{this.flushQueryCacheWrites().catch(()=>{})},ls)}async flushQueryCacheWrites(){this.cacheFlushTimer=void 0;let{queryCache:e}=this;if(!e){this.pendingCacheWrites.clear();return}let r=[...this.pendingCacheWrites.entries()];this.pendingCacheWrites.clear(),await Promise.allSettled(r.map(([s,i])=>e.put(s,i)))}computeStatus(){if(this.tabCoordinator&&!this.tabCoordinator.isLeader())return this.leaderStatus??"idle";let e=[...this.connections.values()];return e.length===0?"idle":e.some(r=>r.wsState==="open")?"connected":e.some(r=>r.wsState==="connecting")?"connecting":"offline"}emitConnectionStatus(){let e=this.computeStatus();e!==this.lastStatus&&(this.lastStatus=e,this.statusListeners.emit(e),this.tabCoordinator?.isLeader()&&this.tabCoordinator.broadcastConnectionStatus(e,this.identityFingerprint()))}emitItemSettled(e,r,s){this.mutationSettledListeners.emit({args:e.args,code:s===void 0?void 0:s.code,error:s,functionPath:e.functionPath,hadAwaiter:e.liveAwaiter??!1,id:e.id??"",shardKey:e.shardKey,status:r})}applyOptimisticUpdates(e,r,s,i){let n=[],o=[];if(!i)return{confirms:n,rollbacks:o};let c=_.key(e,r,s),u=this.subscriptions.get(c);if(u){let d=at(u,i);d&&(n.push(d.confirm),o.push(d.rollback))}return{confirms:n,rollbacks:o}}applyOptimisticUpdate(e,r,s,i,n){let{confirms:o,rollbacks:c,store:u}=nr(this.subscriptions,s);try{e(u,r)}catch{Le(c);return}i.push(...c),n.push(...o)}getConnection(e){return this.connections.get(C(e))}sendOrQueueUnsubscribe(e,r,s){let i=this.getConnection(e);i&&!F(i,{id:r,type:s})&&i.pendingUnsubscribes.push({id:r,type:s})}connectionGateState(e){if(this.tabCoordinator&&!this.tabCoordinator.isLeader()){let s="idle";return this.leaderStatus==="connected"?s="open":this.leaderStatus==="connecting"&&(s="connecting"),{hasSocket:!1,wasEverConnected:this.leaderWasEverConnected,wsState:s}}let r=this.getConnection(e);return{hasSocket:r?.socket!==void 0,wasEverConnected:r?.wasEverConnected??!1,wsState:r?.wsState??"idle"}}getOrCreateConnection(e){let r=C(e),s=this.connections.get(r);return s||(s={connectTimer:void 0,heartbeatTimer:void 0,lastFrameAt:0,pendingUnsubscribes:[],reconnect:ct(this.reconnectOptions),reconnectTimer:void 0,shardKey:e,socket:void 0,wasEverConnected:!1,wsState:"idle"},this.connections.set(r,s)),s}wsUrlFor(e,r){let s=[];if(e!==void 0&&s.push(`shard=${encodeURIComponent(e)}`),r!==void 0&&s.push(`token=${encodeURIComponent(r)}`),s.length===0)return this.wsUrl;let i=this.wsUrl.includes("?")?"&":"?";return`${this.wsUrl}${i}${s.join("&")}`}rpcRequestHeaders(e,r){let s={"content-type":"application/json"},i=this.shardCursors.get(this.cursorKeyFor(r));if(i!==void 0&&(s["x-lunora-min-seq"]=i.toString()),this.authToken&&(s.authorization=`Bearer ${this.authToken}`),e.mutationId&&(s["x-lunora-mutation-id"]=e.mutationId),(e.clientId!==void 0||e.mutationId!==void 0)&&(s["x-lunora-client-id"]=e.clientId??this.clientId),e.clientSeq!==void 0&&(s["x-lunora-client-seq"]=e.clientSeq.toString()),e.attachBookmark){let n=this.bookmark.get();n&&(s["x-d1-bookmark"]=n)}return s}async rpc(e,r,s,i={}){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let n=this.rpcRequestHeaders(i,s),o=await this.fetchImpl(V(this.url,as),{body:JSON.stringify({args:G(r,`args for '${e}'`),functionPath:e,shardKey:s}),headers:n,method:"POST"});if(i.captureBookmark){let u=o.headers.get("x-d1-bookmark");u&&this.bookmark.set(u)}let c;try{c=await o.json()}catch{let u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${o.status.toString()}${u})`)}if("error"in c)throw de(c.error);if(!o.ok){let u=o.statusText?` ${o.statusText}`:"";throw new p("INTERNAL",`LunoraClient: request failed (status ${o.status.toString()}${u})`)}return i.onMutationAck?.(c.lastMutationId),i.onCommitCursor?.(c.commitCursor),this.learnDefaultShardKey(o,s),this.recordShardCursor(s,c.commitCursor),S(c.result)}async adminFetch(e,r,s,i){if(!this.fetchImpl)throw new p("INTERNAL","LunoraClient: no `fetch` implementation available");let n={};this.authToken&&(n.authorization=`Bearer ${this.authToken}`);let o=s instanceof ArrayBuffer||s instanceof Blob,c;s===void 0?c=void 0:o?(c=s,i!==void 0&&(n["content-type"]=i)):(c=JSON.stringify(s),n["content-type"]="application/json");let u=await this.fetchImpl(V(this.url,e),{body:c,headers:n,method:r}),d;try{d=await u.json()}catch{let h=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: response was not JSON (status ${u.status.toString()}${h})`)}if(typeof d=="object"&&d!==null&&"error"in d){let h=d.error,l=new Error(h.message??"admin request failed");throw l.code=h.code,l}if(!u.ok){let h=u.statusText?` ${u.statusText}`:"";throw new p("INTERNAL",`LunoraClient: admin request failed (status ${u.status.toString()}${h})`)}return d}effectiveConnectionContext(e){let r=this.connectionContextHolders.get(e);return r&&r.length>0?r[r.length-1]?.context:this.connectionContexts.get(e)??this.defaultConnectionContext}refreshConnectionContext(e){let r=this.connections.get(e);r?.wsState==="open"&&this.sendConnectEnvelope(r)}sendConnectEnvelope(e){let r=this.effectiveConnectionContext(C(e.shardKey));F(e,{caps:Pi,clientId:this.clientId,id:"connect",type:"connect",...r===void 0?{}:{context:r}})}resendShapeSubscriptions(e){for(let r of this.shapeSubscriptions.values())C(r.shardKey)===C(e)&&this.sendShapeSubscribeIfOpen(r)}ensureSocket(e){if(this.closed||this.WebSocketImpl===void 0||this.tabCoordinator&&!this.tabCoordinator.isLeader())return;let r=this.getOrCreateConnection(e);if(!(r.wsState==="open"||r.wsState==="connecting")){if(r.wsState="connecting",this.emitConnectionStatus(),typeof this.wsToken=="function"){this.openSocketWithProvidedToken(r,e,this.wsToken).catch(()=>{});return}this.openSocket(r,e,this.wsToken)}}async openSocketWithProvidedToken(e,r,s){let i;try{i=await s()}catch{this.handleDisconnect(e);return}this.closed||this.WebSocketImpl===void 0||e.wsState!=="connecting"||e.socket!==void 0||this.openSocket(e,r,i)}openManagedSocket(e,r,s,i){let{WebSocketImpl:n}=this;if(n===void 0)throw new p("INTERNAL","no WebSocket implementation available");let o=new n(r);e.socket=o;let c=a(()=>{this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket===o&&(e.socket=void 0)},"a"),u=a(d=>{c(),i.onClose(d)},"o");s>0&&(e.connectTimer=setTimeout(()=>{if(e.connectTimer=void 0,e.socket===o){try{o.close()}catch{}u()}},s)),o.addEventListener("open",()=>{e.socket===o&&(e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.lastFrameAt=Date.now(),i.onOpen(),this.startHeartbeat(e,u))}),o.addEventListener("message",d=>{e.socket===o&&(e.lastFrameAt=Date.now(),i.onMessage(d))}),o.addEventListener("close",d=>{e.socket===o&&u(d)}),o.addEventListener("error",()=>{e.socket===o&&u()})}openSocket(e,r,s){this.WebSocketImpl!==void 0&&this.openManagedSocket(e,this.wsUrlFor(r,s),this.connectTimeoutMs,{onClose:a(i=>{i?.code===4001&&this.notifyTokenExpired(),this.handleDisconnect(e)},"onClose"),onMessage:a(i=>{this.handleServerMessage(i.data,r)},"onMessage"),onOpen:a(()=>{e.wsState="open",e.wasEverConnected=!0,e.reconnect.reset(),this.emitConnectionStatus(),this.sendConnectEnvelope(e),this.markShardPendingAck(r);for(let n of this.subscriptions.all())C(n.shardKey)===C(r)&&this.sendSubscribeIfOpen(n);if(this.resendShapeSubscriptions(r),e.pendingUnsubscribes.length>0){let n=e.pendingUnsubscribes;e.pendingUnsubscribes=[];for(let{id:o,type:c}of n)F(e,{id:o,type:c})}if(e.pendingStreams&&e.pendingStreams.length>0){let n=e.pendingStreams;e.pendingStreams=[];for(let o of n)F(e,o)}let i=this.whisperHandlers.get(C(r));if(i)for(let n of i.keys())F(e,{topic:n,type:"whisper_subscribe"});this.flushOfflineQueue(r).catch(()=>{})},"onOpen")})}handleDisconnect(e){if(this.closed||e.wsState==="idle"||e.wsState==="closed")return;this.stopHeartbeat(e),e.connectTimer!==void 0&&(clearTimeout(e.connectTimer),e.connectTimer=void 0),e.socket=void 0,e.wsState="idle",this.emitConnectionStatus(),this.markShardPendingAck(e.shardKey);let r=new Set((e.pendingStreams??[]).map(i=>i.id));for(let[i,n]of this.streams)if(!(C(n.shardKey)!==C(e.shardKey)||r.has(i))){if(n.durable){let o={...n.message,sinceChunk:n.lastSeq};n.message=o,e.pendingStreams=[...(e.pendingStreams??[]).filter(c=>c.id!==i),o];continue}n.handle.fail(new p("STREAM_DISCONNECTED","stream terminated: WebSocket disconnected")),this.streams.delete(i)}if(this.WebSocketImpl===void 0)return;let s=e.reconnect.next();e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=void 0,this.ensureSocket(e.shardKey)},s)}startHeartbeat(e,r){this.stopHeartbeat(e),!(this.heartbeatIntervalMs<=0)&&(e.heartbeatTimer=setInterval(()=>{if(!e.socket)return;let{socket:s}=e;if(Date.now()-e.lastFrameAt>this.heartbeatIntervalMs*2.5){try{s.close()}catch{}r();return}try{s.send(us)}catch{}},this.heartbeatIntervalMs))}stopHeartbeat(e){e.heartbeatTimer!==void 0&&(clearInterval(e.heartbeatTimer),e.heartbeatTimer=void 0)}markShardPendingAck(e){let r=C(e);for(let s of this.subscriptions.all())C(s.shardKey)===r&&(s.acked=!1)}sendSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);if(r?.wsState!=="open"||e.acked)return;let s=e.fn.__lunoraTable??e.fn.__lunoraRef;F(r,{id:e.id,query:{args:O(e.args),functionPath:e.fn.__lunoraRef,table:s,...e.serverCursor===void 0?{}:{sinceSeq:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}},type:"subscribe"})}sendShapeSubscribeIfOpen(e){let r=this.getConnection(e.shardKey);r?.wsState==="open"&&F(r,{id:e.id,shape:{name:e.name,...e.wireArgs===void 0?{}:{args:e.wireArgs}},type:"shape_subscribe",...e.serverCursor===void 0?{}:{sinceCheckpoint:e.serverCursor},...e.serverEpoch===void 0?{}:{sinceEpoch:e.serverEpoch}})}handleServerMessage(e,r){let s=Mi(e);if(s===void 0)return;let i;try{i=JSON.parse(s)}catch{return}switch(i.type){case"ack":{let n=this.subscriptions.getById(i.id);n&&(n.acked=!0);return}case"chunk":{let{data:n,id:o,seq:c}=i,u=this.streams.get(o);u&&typeof c=="number"&&(u.lastSeq=c,u.durable=!0),u?.handle.push(S(n));return}case"complete":{this.handleCompleteMessage(i.id);return}case"data":case"delta":{this.handleDataMessage(i);return}case"error":{this.handleErrorMessage(i);break}case"pokeEnd":{this.handlePokeEnd(i);break}case"pokePart":{this.handlePokePart(i);break}case"pokeStart":{this.handlePokeStart(i);break}case"resume":{this.handleResumeMessage(i);break}case"settled":{this.handleSettledMessage(i);break}case"whisper":{this.dispatchWhisper(i,r);break}}}handleErrorMessage(e){if(e.error?.code==="TOKEN_EXPIRED"){this.notifyTokenExpired();return}let{id:r}=e,s=r===void 0?void 0:this.streams.get(r);if(s&&r!==void 0){s.handle.fail(Ai(e)),this.streams.delete(r);return}let i=r===void 0?void 0:this.subscriptions.getById(r);if(i){Qe(i.errorCallbacks,fr(e));return}let n=r===void 0?void 0:this.shapeSubscriptions.get(r);n&&Qe(n.errorCallbacks,fr(e))}handlePokeStart(e){ns(this.pokeBuffers,t.MAX_POKE_BUFFERS),this.pokeBuffers.set(e.pokeId,{baseCheckpoint:e.baseCheckpoint,epoch:e.epoch,lastMutationId:new Map,parts:new Map})}handlePokePart(e){let r=this.pokeBuffers.get(e.pokeId);if(!r)return;let s=r.parts.get(e.shapeId)??[];for(let i of e.rowsPatch)s.push(i.value===void 0?i:{...i,value:S(i.value)});r.parts.set(e.shapeId,s),e.lastMutationId!==void 0&&r.lastMutationId.set(e.shapeId,e.lastMutationId)}handlePokeEnd(e){let r=this.pokeBuffers.get(e.pokeId);if(r){this.pokeBuffers.delete(e.pokeId);for(let[s,i]of r.parts){let n=this.shapeSubscriptions.get(s);if(!n)continue;let o=r.epoch!==void 0&&n.serverEpoch!==void 0&&r.epoch!==n.serverEpoch,c=r.baseCheckpoint!==void 0&&n.serverCursor!==void 0&&n.serverCursor!==r.baseCheckpoint;if(o||c){n.rows.clear(),n.serverCursor=void 0,n.serverEpoch=void 0,this.emitShapeRows(n),this.sendShapeSubscribeIfOpen(n);continue}cs(n.rows,i),e.checkpoint!==void 0&&(n.serverCursor=e.checkpoint),e.epoch!==void 0&&(n.serverEpoch=e.epoch);let u=r.lastMutationId.get(s);u!==void 0&&(n.lastMutationId=u),this.emitShapeRows(n),n.onCheckpoint?.({checkpoint:n.serverCursor,mutationId:n.lastMutationId})}}}emitShapeRows(e){let r=[...e.rows.values()];for(let s of e.callbacks)try{s(r)}catch{}}handleDataMessage(e){let{id:r}=e,s=r?this.subscriptions.getById(r):void 0;if(!s)return;let i=this.resolveDataPayload(e,s);if(s.serverBase=i,e.cursor!==void 0&&(s.serverCursor=e.cursor),e.epoch!==void 0&&(s.serverEpoch=e.epoch),e.lastMutationId!==void 0){s.lastMutationId=Math.max(s.lastMutationId??0,e.lastMutationId);for(let n of s.checkpointCallbacks)n({checkpoint:s.serverCursor,mutationId:s.lastMutationId})}if(this.persistQueryValue(s),Pe(s,s.serverCursor),te(s,he(i,s.optimisticLayers)),this.tabCoordinator?.isLeader()){let n=_.key(s.fn.__lunoraRef,s.args,s.shardKey);this.tabCoordinator.broadcastSubscriptionData(n,i,s.serverCursor,s.serverEpoch,this.identityFingerprint())}}handleResumeMessage(e){let r=this.subscriptions.getById(e.id);r&&this.ackAndAdvanceCursor(r,e.cursor,e.epoch)}handleSettledMessage(e){let r=this.subscriptions.getById(e.id);if(r){this.ackAndAdvanceCursor(r,e.cursor,e.epoch),e.lastMutationId!==void 0&&(r.lastMutationId=e.lastMutationId);for(let s of r.checkpointCallbacks)s({checkpoint:r.serverCursor,mutationId:r.lastMutationId});if(this.tabCoordinator?.isLeader()){let s=_.key(r.fn.__lunoraRef,r.args,r.shardKey);this.tabCoordinator.broadcastSubscriptionSettled(s,r.serverCursor,r.serverEpoch,r.lastMutationId,this.clientId,this.identityFingerprint())}}}ackAndAdvanceCursor(e,r,s){e.acked=!0,(r!==void 0&&r!==e.serverCursor||s!==void 0&&s!==e.serverEpoch)&&(r!==void 0&&(e.serverCursor=r),s!==void 0&&(e.serverEpoch=s),this.persistQueryValue(e),Pe(e,e.serverCursor)&&te(e,he(e.serverBase,e.optimisticLayers)))}resolveDataPayload(e,r){if("data"in e&&e.data!==void 0)return S(e.data);let s=S(e.delta);if(er(s)&&r.serverBase!==void 0){let i=tr(r.serverBase,s);if(i!==void 0)return i}return s}dispatchWhisper(e,r){let s=this.whisperHandlers.get(C(r))?.get(e.topic);if(!s)return;let i=S(e.data);for(let n of s)try{n(i,e.from)}catch{}}notifyTokenExpired(){this.tokenExpiredListeners.emit()}handleCompleteMessage(e){let r=this.streams.get(e);if(r){r.handle.complete(),this.streams.delete(e);return}let s=this.subscriptions.getById(e);s&&(s.acked=!1,Qe(s.errorCallbacks,{code:"SUBSCRIPTION_CANCELLED",message:"subscription was cancelled by the server"}))}unpersist(e){e&&this.persistence?.remove(e).catch(r=>{re(this.onPersistenceError,"remove",r,e)})}identityFingerprint(){if(this.authSubject!==void 0)return this.authSubject===null?null:`subj:${this.authSubject}`;let e=this.authToken;return e===null?null:this.hashToken(e)}hashToken(e){let r=2166136261,s=5381;for(let i=0;i<e.length;i+=1){let n=e.charCodeAt(i);r^=n,r=Math.imul(r,16777619),s=Math.imul(s,33)+n}return`${e.length.toString(36)}:${(r>>>0).toString(36)}:${(s>>>0).toString(36)}`}isSameCredentialUnderTokenHash(e){if(e===null||e.startsWith("subj:"))return!1;let r=this.authToken;return r===null?!1:this.hashToken(r)===e}rejectQueuedForIdentityChange(){let e=this.offlineQueue.drain();for(let r of e){this.queuedIdentities.delete(r.id??""),this.unpersist(r.id);let s=new Error("offline mutation discarded: auth identity changed before replay");s.code="OFFLINE_IDENTITY_CHANGED",r.reject(s),this.emitItemSettled(r,"rejected",s)}this.clearQueryCacheForIdentityChange()}restampQueuedIdentity(e,r){for(let[s,i]of this.queuedIdentities)i===e&&this.queuedIdentities.set(s,r)}clearQueryCacheForIdentityChange(){this.cacheFlushTimer!==void 0&&(clearTimeout(this.cacheFlushTimer),this.cacheFlushTimer=void 0),this.pendingCacheWrites.clear(),this.hydratedQueryCache.clear(),this.queryCache?.clear().catch(()=>{})}flushAllOfflineQueues(){for(let e of this.queuedOfflineShardKeys)this.flushOfflineQueue(e).catch(()=>{})}async flushOfflineQueue(e){let r=this.offlineQueue.drainConflict();for(let d of r){this.unpersist(d.id),this.queuedIdentities.delete(d.id??"");let h=new Error("offline mutation skipped: precondition failed before replay");h.code="OFFLINE_PRECONDITION_FAILED",this.emitItemSettled(d,"rejected",h)}let s=C(e),i=this.offlineQueue.drain(d=>C(d.shardKey)===s);if(i.length===0)return;let n=this.identityFingerprint(),o=[];for(let d of i)this.passesReplayIdentityGate(d,n)&&o.push(d);if(o.length===0)return;let c=this.encodableOrSettleTerminal(o);if(c.length===0)return;if(c.length===1){await this.replaySequential(c);return}let u=[];for(let d=0;d<c.length;d+=ut){let h=c.slice(d,d+ut),l=await this.replayBatched(h);if(u.push(...l.requeue),l.stop){u.push(...c.slice(d+ut));break}}u.length>0&&this.offlineQueue.requeue(u)}encodableOrSettleTerminal(e){let r=[];for(let s of e)try{G(s.args,`args for '${s.functionPath}'`),r.push(s)}catch(i){this.settleReplayTerminal(s,i instanceof Error?i:new Error(String(i)))}return r}passesReplayIdentityGate(e,r){let s=e.id===void 0?void 0:this.queuedIdentities.get(e.id),i=s===void 0?e.identity:s;if(i!==void 0&&i!==r&&!this.isSameCredentialUnderTokenHash(i)){this.queuedIdentities.delete(e.id??""),this.unpersist(e.id);let n=new Error("offline mutation skipped: auth identity changed before replay");return n.code="OFFLINE_IDENTITY_CHANGED",e.reject(n),this.emitItemSettled(e,"rejected",n),!1}return this.queuedIdentities.delete(e.id??""),!0}settleReplaySuccess(e,r,s){this.unpersist(e.id),this.recordShardCursor(e.shardKey,s),e.onCommit?.(s),e.resolve(r),this.emitItemSettled(e,"committed")}cursorKeyFor(e){return e??this.defaultShardKey??""}learnDefaultShardKey(e,r){let s=e.headers.get("x-lunora-shard-key");if(s===null||r!==void 0||this.defaultShardKey===s)return;this.defaultShardKey=s;let i=this.shardCursors.get("");i!==void 0&&(this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,i)),this.shardCursors.delete(""))}recordShardCursor(e,r){if(typeof r!="number")return;let s=this.cursorKeyFor(e);this.shardCursors.set(s,Math.max(this.shardCursors.get(s)??0,r))}settleReplayTerminal(e,r){this.unpersist(e.id),e.reject(r),this.emitItemSettled(e,"rejected",r)}async replaySequential(e){for(let r=0;r<e.length;r+=1){let s=e[r];if(s)try{let i,n=await this.rpc(s.functionPath,s.args,s.shardKey,{captureBookmark:!0,clientId:s.clientId??this.clientId,mutationId:s.id,onCommitCursor:a(o=>{i=o},"onCommitCursor")});this.settleReplaySuccess(s,n,i)}catch(i){if(i.code!==void 0){this.settleReplayTerminal(s,i);continue}this.offlineQueue.requeue(e.slice(r));return}}}async replayBatched(e){if(!this.fetchImpl)return{requeue:e,stop:!0};let r;try{r=await this.fetchImpl(V(this.url,dr),{body:JSON.stringify({calls:e.map((n,o)=>({args:G(n.args,`args for '${n.functionPath}'`),functionPath:n.functionPath,id:o,clientId:n.clientId??this.clientId,mutationId:n.id,shardKey:n.shardKey}))}),headers:this.rpcRequestHeaders({attachBookmark:!0}),method:"POST"})}catch{return{requeue:e,stop:!0}}let s=r.headers.get("x-d1-bookmark");s&&this.bookmark.set(s);let i;try{i=await r.json()}catch{return{requeue:e,stop:!0}}if(!i.results){if(i.error){let n=de(i.error);for(let o of e)this.settleReplayTerminal(o,n);return{requeue:[],stop:!1}}return{requeue:e,stop:!0}}return{requeue:this.settleReplayBatchSlots(e,i.results),stop:!1}}settleReplayBatchSlots(e,r){let s=new Map;for(let n of r)typeof n.id=="number"&&n.body!==void 0&&s.set(n.id,n.body);let i=[];for(let[n,o]of e.entries()){let c=s.get(n);c===void 0?i.push(o):"error"in c?_i.has(c.error.code)?i.push(o):this.settleReplayTerminal(o,de(c.error)):this.settleReplaySuccess(o,S(c.result),c.commitCursor)}return i}};var mr=P(mt(),1),yr=P($(),1);var Qi=a(()=>{let t=(0,mr.c)(4),e=Ye(),r,s,i;return t[0]!==e?(r=a(n=>e.onConnectionStatus(()=>{n()}),"n"),s=a(()=>e.connectionStatus(),"e"),i=a(()=>e.connectionStatus(),"r"),t[0]=e,t[1]=r,t[2]=s,t[3]=i):(r=t[1],s=t[2],i=t[3]),(0,yr.useSyncExternalStore)(r,s,i)},"f");export{ft as a,wr as b,Ve as c,Mr as d,_r as e,Ye as f,Qi as g};
@@ -1 +1 @@
1
- import{a as W}from"./chunk-54MMVNPT.js";import{a as F}from"./chunk-3CWGJYBB.js";import{a as E}from"./chunk-RMN2JN4S.js";import"./chunk-GRL5MG3Z.js";import"./chunk-7T7UOTYK.js";import"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import"./chunk-2OUPA2WJ.js";import{b as y}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as L}from"./chunk-ZBVGZ4YA.js";import"./chunk-XXQUMVWH.js";import"./chunk-56Q3NCCQ.js";import"./chunk-QLQADHFE.js";import{a as D}from"./chunk-VDW32UET.js";import{c as _}from"./chunk-KMT6UDR7.js";import"./chunk-WVU7GHTG.js";import"./chunk-XBDKZZ67.js";import{a as T}from"./chunk-XQCVZAGU.js";import{a as O,b as P,c as U,d as w,e as h,f as p}from"./chunk-WJQLNYGX.js";import{a as $,e as j}from"./chunk-WQH3LT2P.js";import{d as M}from"./chunk-IUYFXK4X.js";import"./chunk-BR5GIQWK.js";import{a as S,e as A,g as R,h as Z}from"./chunk-3XIESWL4.js";var B=A(R(),1);var t=A(Z(),1);var q=80,z=S(a=>{if(a===void 0)return"";let e=JSON.stringify(a);return e.length>q?`${e.slice(0,q)}\u2026`:e},"W"),G=S(a=>{let e=[];for(let r of a){let n=r.id.toString();if(r.subscriptions.length===0){e.push({admin:r.admin,connectionId:r.id,key:`c${n}`,subscription:null});continue}r.subscriptions.forEach((l,i)=>{e.push({admin:r.admin,connectionId:r.id,key:`c${n}-s${i.toString()}`,subscription:l})})}return e},"B"),C=(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"}),oe=S(a=>{let e=(0,B.c)(22),{initialShardKey:r}=a,n=M(),{queryShardKey:l,setShardKey:i,shardKey:m}=F(r),f;e[0]===Symbol.for("react.memo_cache_sentinel")?(f={},e[0]=f):f=e[0];let b;e[1]!==l?(b={keepPreviousData:!0,shardKey:l},e[1]=l,e[2]=b):b=e[2];let{data:s,error:o,errorSource:u,refetch:J}=_(D.listSubscriptions,f,b);W(J,!0);let x;if(e[3]!==o||e[4]!==u||e[5]!==s||e[6]!==i||e[7]!==m||e[8]!==n){let k=s===void 0?[]:G(s.connections),c;e[10]!==i||e[11]!==m?(c=(0,t.jsx)(E,{onChange:i,testId:"subs-shard-input",value:m}),e[10]=i,e[11]=m,e[12]=c):c=e[12];let d;e[13]!==s||e[14]!==n?(d=s!==void 0&&(0,t.jsxs)("div",{className:"ml-auto flex items-center gap-2 text-sm text-muted-foreground","data-testid":"subs-count",children:[(0,t.jsx)(y,{variant:"secondary",children:n("{count} connections",{count:s.totalConnections})}),(0,t.jsx)(y,{variant:"secondary",children:n("{count} subscriptions",{count:s.totalSubscriptions})})]}),e[13]=s,e[14]=n,e[15]=d):d=e[15];let g;e[16]!==c||e[17]!==d?(g=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[c,d]}),e[16]=c,e[17]=d,e[18]=g):g=e[18];let v;e[19]!==o||e[20]!==u?(v=o!==null&&(0,t.jsx)(L,{error:u,testId:"subs-error"}),e[19]=o,e[20]=u,e[21]=v):v=e[21],x=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"subs-panel",children:[g,v,o===null&&s!==void 0&&k.length===0&&(0,t.jsx)(T,{description:n("Active WebSocket subscriptions on this shard."),icon:(0,t.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,t.jsx)("path",{d:"M5 12a7 7 0 0 1 14 0M8 12a4 4 0 0 1 8 0M12 12v8m0-8a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"})}),testId:"subs-empty",title:n("No active subscriptions.")}),o===null&&k.length>0&&(0,t.jsx)($,{className:"overflow-hidden py-0",children:(0,t.jsx)(j,{className:"px-0",children:(0,t.jsxs)(O,{"data-testid":"subs-table",children:[(0,t.jsx)(P,{children:(0,t.jsxs)(w,{children:[(0,t.jsx)(h,{children:n("Connection")}),(0,t.jsx)(h,{children:n("Function path")}),(0,t.jsx)(h,{children:n("Table")}),(0,t.jsx)(h,{children:n("Arguments")})]})}),(0,t.jsx)(U,{children:k.map(N=>{let{subscription:I}=N,K=z(I?.args);return(0,t.jsxs)(w,{"data-testid":"subs-row",children:[(0,t.jsx)(p,{className:"font-medium tabular-nums",children:(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:["#",N.connectionId,N.admin&&(0,t.jsx)(y,{variant:"outline",children:n("admin")})]})}),(0,t.jsx)(p,{className:"font-mono text-xs",children:I?.functionPath??C}),(0,t.jsx)(p,{children:I?.table??C}),(0,t.jsx)(p,{className:"max-w-[32ch] truncate font-mono text-xs text-muted-foreground",title:K||void 0,children:K||C})]},N.key)})})]})})})]}),e[3]=o,e[4]=u,e[5]=s,e[6]=i,e[7]=m,e[8]=n,e[9]=x}else x=e[9];return x},"oe");export{oe as default};
1
+ import{a as W}from"./chunk-54MMVNPT.js";import{a as F}from"./chunk-3CWGJYBB.js";import{a as E}from"./chunk-RMN2JN4S.js";import"./chunk-GRL5MG3Z.js";import"./chunk-7T7UOTYK.js";import"./chunk-CFPZYHPY.js";import"./chunk-7QIFDWQV.js";import"./chunk-2OUPA2WJ.js";import{b as y}from"./chunk-THIXMMZD.js";import"./chunk-6ST5ECQA.js";import{a as L}from"./chunk-CAOA5AM4.js";import"./chunk-XXQUMVWH.js";import"./chunk-VR3OBMGZ.js";import"./chunk-QLQADHFE.js";import{a as D}from"./chunk-VDW32UET.js";import{c as _}from"./chunk-FZ2N52BV.js";import"./chunk-BDHAGUAY.js";import"./chunk-XBDKZZ67.js";import{a as T}from"./chunk-XQCVZAGU.js";import{a as O,b as P,c as U,d as w,e as h,f as p}from"./chunk-WJQLNYGX.js";import{a as $,e as j}from"./chunk-WQH3LT2P.js";import{d as M}from"./chunk-IUYFXK4X.js";import"./chunk-5DVJR52Z.js";import{a as S,e as A,g as R,h as Z}from"./chunk-3XIESWL4.js";var B=A(R(),1);var t=A(Z(),1);var q=80,z=S(a=>{if(a===void 0)return"";let e=JSON.stringify(a);return e.length>q?`${e.slice(0,q)}\u2026`:e},"W"),G=S(a=>{let e=[];for(let r of a){let n=r.id.toString();if(r.subscriptions.length===0){e.push({admin:r.admin,connectionId:r.id,key:`c${n}`,subscription:null});continue}r.subscriptions.forEach((l,i)=>{e.push({admin:r.admin,connectionId:r.id,key:`c${n}-s${i.toString()}`,subscription:l})})}return e},"B"),C=(0,t.jsx)("span",{className:"text-muted-foreground",children:"\u2014"}),oe=S(a=>{let e=(0,B.c)(22),{initialShardKey:r}=a,n=M(),{queryShardKey:l,setShardKey:i,shardKey:m}=F(r),f;e[0]===Symbol.for("react.memo_cache_sentinel")?(f={},e[0]=f):f=e[0];let b;e[1]!==l?(b={keepPreviousData:!0,shardKey:l},e[1]=l,e[2]=b):b=e[2];let{data:s,error:o,errorSource:u,refetch:J}=_(D.listSubscriptions,f,b);W(J,!0);let x;if(e[3]!==o||e[4]!==u||e[5]!==s||e[6]!==i||e[7]!==m||e[8]!==n){let k=s===void 0?[]:G(s.connections),c;e[10]!==i||e[11]!==m?(c=(0,t.jsx)(E,{onChange:i,testId:"subs-shard-input",value:m}),e[10]=i,e[11]=m,e[12]=c):c=e[12];let d;e[13]!==s||e[14]!==n?(d=s!==void 0&&(0,t.jsxs)("div",{className:"ml-auto flex items-center gap-2 text-sm text-muted-foreground","data-testid":"subs-count",children:[(0,t.jsx)(y,{variant:"secondary",children:n("{count} connections",{count:s.totalConnections})}),(0,t.jsx)(y,{variant:"secondary",children:n("{count} subscriptions",{count:s.totalSubscriptions})})]}),e[13]=s,e[14]=n,e[15]=d):d=e[15];let g;e[16]!==c||e[17]!==d?(g=(0,t.jsxs)("div",{className:"flex flex-wrap items-center gap-2",children:[c,d]}),e[16]=c,e[17]=d,e[18]=g):g=e[18];let v;e[19]!==o||e[20]!==u?(v=o!==null&&(0,t.jsx)(L,{error:u,testId:"subs-error"}),e[19]=o,e[20]=u,e[21]=v):v=e[21],x=(0,t.jsxs)("div",{className:"flex flex-col gap-4","data-testid":"subs-panel",children:[g,v,o===null&&s!==void 0&&k.length===0&&(0,t.jsx)(T,{description:n("Active WebSocket subscriptions on this shard."),icon:(0,t.jsx)("svg",{"aria-hidden":"true",fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.6,viewBox:"0 0 24 24",children:(0,t.jsx)("path",{d:"M5 12a7 7 0 0 1 14 0M8 12a4 4 0 0 1 8 0M12 12v8m0-8a1 1 0 1 0 0-2 1 1 0 0 0 0 2Z"})}),testId:"subs-empty",title:n("No active subscriptions.")}),o===null&&k.length>0&&(0,t.jsx)($,{className:"overflow-hidden py-0",children:(0,t.jsx)(j,{className:"px-0",children:(0,t.jsxs)(O,{"data-testid":"subs-table",children:[(0,t.jsx)(P,{children:(0,t.jsxs)(w,{children:[(0,t.jsx)(h,{children:n("Connection")}),(0,t.jsx)(h,{children:n("Function path")}),(0,t.jsx)(h,{children:n("Table")}),(0,t.jsx)(h,{children:n("Arguments")})]})}),(0,t.jsx)(U,{children:k.map(N=>{let{subscription:I}=N,K=z(I?.args);return(0,t.jsxs)(w,{"data-testid":"subs-row",children:[(0,t.jsx)(p,{className:"font-medium tabular-nums",children:(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:["#",N.connectionId,N.admin&&(0,t.jsx)(y,{variant:"outline",children:n("admin")})]})}),(0,t.jsx)(p,{className:"font-mono text-xs",children:I?.functionPath??C}),(0,t.jsx)(p,{children:I?.table??C}),(0,t.jsx)(p,{className:"max-w-[32ch] truncate font-mono text-xs text-muted-foreground",title:K||void 0,children:K||C})]},N.key)})})]})})})]}),e[3]=o,e[4]=u,e[5]=s,e[6]=i,e[7]=m,e[8]=n,e[9]=x}else x=e[9];return x},"oe");export{oe as default};
@@ -1 +1 @@
1
- import{a as $}from"./chunk-CJQ2534J.js";import{a as b}from"./chunk-ZBVGZ4YA.js";import"./chunk-XXQUMVWH.js";import"./chunk-56Q3NCCQ.js";import"./chunk-QLQADHFE.js";import{a as u}from"./chunk-VDW32UET.js";import{c as p}from"./chunk-KMT6UDR7.js";import"./chunk-WVU7GHTG.js";import"./chunk-XBDKZZ67.js";import{a as y,b as w,c as j,d as h,e as i,f as n}from"./chunk-WJQLNYGX.js";import{a as l,e as c}from"./chunk-WQH3LT2P.js";import{d as k}from"./chunk-IUYFXK4X.js";import"./chunk-BR5GIQWK.js";import{a as o,e as S,h as T,j as x}from"./chunk-3XIESWL4.js";var e=S(T(),1);var m={clean:"text-emerald-600 dark:text-emerald-400",exempt:"text-muted-foreground",failing:"text-red-600 dark:text-red-400",warned:"text-amber-600 dark:text-amber-400"},A={"at-risk":"text-red-600 dark:text-red-400",excellent:"text-emerald-600 dark:text-emerald-400",good:"text-emerald-600 dark:text-emerald-400","needs-work":"text-amber-600 dark:text-amber-400"},O=o((r,a)=>`exempt: ${r.exemptReason===void 0||r.exemptReason===""?a:r.exemptReason}`,"S"),P=o(r=>r.toSorted((a,d)=>a.coverage==="clean"&&d.coverage!=="clean"?1:d.coverage==="clean"&&a.coverage!=="clean"?-1:a.score-d.score),"T"),q=o(({testId:r="advisor-health"})=>{let a=k(),d=p(u.getAdvisories,{},{live:!0}),g=p(u.getAdvisorProcedures,{},{live:!0}),f=d.data?.advisories??null,N=g.data?.procedures??null,t=f===null||N===null?null:$(N,f),v=g.error??d.error;if(v!==null)return(0,e.jsx)(b,{error:v,testId:`${r}-error`});if(t===null)return(0,e.jsx)(l,{children:(0,e.jsx)(c,{className:"py-8 text-center text-muted-foreground","data-testid":`${r}-loading`,children:a("Loading\u2026")})});let I=P(t.procedures);return(0,e.jsxs)("div",{className:"space-y-4","data-testid":r,children:[(0,e.jsx)(l,{children:(0,e.jsxs)(c,{className:"flex flex-wrap items-baseline gap-x-6 gap-y-2 py-6",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("span",{className:x("text-4xl font-semibold tabular-nums",A[t.grade]),"data-testid":`${r}-score`,children:t.score}),(0,e.jsx)("span",{className:"text-muted-foreground text-lg",children:"/100"})]}),(0,e.jsx)("span",{className:x("text-sm font-medium uppercase tracking-wide",A[t.grade]),"data-testid":`${r}-grade`,children:t.grade}),(0,e.jsxs)("div",{className:"text-muted-foreground flex gap-4 text-sm tabular-nums","data-testid":`${r}-summary`,children:[(0,e.jsxs)("span",{className:m.clean,children:[t.summary.clean," ",a("clean")]}),(0,e.jsxs)("span",{className:m.warned,children:[t.summary.warned," ",a("warned")]}),(0,e.jsxs)("span",{className:m.failing,children:[t.summary.failing," ",a("failing")]}),(0,e.jsxs)("span",{className:m.exempt,children:[t.summary.exempt," ",a("exempt")]})]})]})}),t.project.checks.length>0&&(0,e.jsx)(l,{children:(0,e.jsxs)(c,{className:"py-4 text-sm","data-testid":`${r}-project`,children:[(0,e.jsxs)("span",{className:"font-medium",children:[a("Schema & config")," ",t.project.score,"/100"]}),(0,e.jsxs)("span",{className:"text-muted-foreground",children:[" \u2014 ",t.project.checks.map(s=>s.name).join(", ")]})]})}),(0,e.jsx)(l,{children:(0,e.jsx)(c,{className:"p-0",children:(0,e.jsxs)(y,{children:[(0,e.jsx)(w,{children:(0,e.jsxs)(h,{children:[(0,e.jsx)(i,{className:"w-20",children:a("Score")}),(0,e.jsx)(i,{children:a("Procedure")}),(0,e.jsx)(i,{className:"w-32",children:a("Kind")}),(0,e.jsx)(i,{children:a("Rules fired")})]})}),(0,e.jsx)(j,{children:I.map(s=>(0,e.jsxs)(h,{"data-testid":`${r}-row`,children:[(0,e.jsx)(n,{className:x("tabular-nums font-medium",m[s.coverage]),children:s.coverage==="exempt"?"\u2014":s.score}),(0,e.jsx)(n,{className:"font-mono text-xs",children:s.id}),(0,e.jsxs)(n,{className:"text-muted-foreground text-xs",children:[s.visibility," ",s.kind,s.sensitivity.level==="high"&&(0,e.jsx)("span",{className:"ml-1 text-amber-600 dark:text-amber-400",children:a("sensitive")})]}),(0,e.jsx)(n,{className:"text-muted-foreground text-xs",children:s.coverage==="exempt"?O(s,a("no reason given")):s.checks.map(R=>R.name).join(", ")})]},s.id))})]})})})]})},"O");export{q as default};
1
+ import{a as $}from"./chunk-5UY7MLRC.js";import{a as b}from"./chunk-CAOA5AM4.js";import"./chunk-XXQUMVWH.js";import"./chunk-VR3OBMGZ.js";import"./chunk-QLQADHFE.js";import{a as u}from"./chunk-VDW32UET.js";import{c as p}from"./chunk-FZ2N52BV.js";import"./chunk-BDHAGUAY.js";import"./chunk-XBDKZZ67.js";import{a as y,b as w,c as j,d as h,e as i,f as n}from"./chunk-WJQLNYGX.js";import{a as l,e as c}from"./chunk-WQH3LT2P.js";import{d as k}from"./chunk-IUYFXK4X.js";import"./chunk-5DVJR52Z.js";import{a as o,e as S,h as T,j as x}from"./chunk-3XIESWL4.js";var e=S(T(),1);var m={clean:"text-emerald-600 dark:text-emerald-400",exempt:"text-muted-foreground",failing:"text-red-600 dark:text-red-400",warned:"text-amber-600 dark:text-amber-400"},A={"at-risk":"text-red-600 dark:text-red-400",excellent:"text-emerald-600 dark:text-emerald-400",good:"text-emerald-600 dark:text-emerald-400","needs-work":"text-amber-600 dark:text-amber-400"},O=o((r,a)=>`exempt: ${r.exemptReason===void 0||r.exemptReason===""?a:r.exemptReason}`,"S"),P=o(r=>r.toSorted((a,d)=>a.coverage==="clean"&&d.coverage!=="clean"?1:d.coverage==="clean"&&a.coverage!=="clean"?-1:a.score-d.score),"T"),q=o(({testId:r="advisor-health"})=>{let a=k(),d=p(u.getAdvisories,{},{live:!0}),g=p(u.getAdvisorProcedures,{},{live:!0}),f=d.data?.advisories??null,N=g.data?.procedures??null,t=f===null||N===null?null:$(N,f),v=g.error??d.error;if(v!==null)return(0,e.jsx)(b,{error:v,testId:`${r}-error`});if(t===null)return(0,e.jsx)(l,{children:(0,e.jsx)(c,{className:"py-8 text-center text-muted-foreground","data-testid":`${r}-loading`,children:a("Loading\u2026")})});let I=P(t.procedures);return(0,e.jsxs)("div",{className:"space-y-4","data-testid":r,children:[(0,e.jsx)(l,{children:(0,e.jsxs)(c,{className:"flex flex-wrap items-baseline gap-x-6 gap-y-2 py-6",children:[(0,e.jsxs)("div",{children:[(0,e.jsx)("span",{className:x("text-4xl font-semibold tabular-nums",A[t.grade]),"data-testid":`${r}-score`,children:t.score}),(0,e.jsx)("span",{className:"text-muted-foreground text-lg",children:"/100"})]}),(0,e.jsx)("span",{className:x("text-sm font-medium uppercase tracking-wide",A[t.grade]),"data-testid":`${r}-grade`,children:t.grade}),(0,e.jsxs)("div",{className:"text-muted-foreground flex gap-4 text-sm tabular-nums","data-testid":`${r}-summary`,children:[(0,e.jsxs)("span",{className:m.clean,children:[t.summary.clean," ",a("clean")]}),(0,e.jsxs)("span",{className:m.warned,children:[t.summary.warned," ",a("warned")]}),(0,e.jsxs)("span",{className:m.failing,children:[t.summary.failing," ",a("failing")]}),(0,e.jsxs)("span",{className:m.exempt,children:[t.summary.exempt," ",a("exempt")]})]})]})}),t.project.checks.length>0&&(0,e.jsx)(l,{children:(0,e.jsxs)(c,{className:"py-4 text-sm","data-testid":`${r}-project`,children:[(0,e.jsxs)("span",{className:"font-medium",children:[a("Schema & config")," ",t.project.score,"/100"]}),(0,e.jsxs)("span",{className:"text-muted-foreground",children:[" \u2014 ",t.project.checks.map(s=>s.name).join(", ")]})]})}),(0,e.jsx)(l,{children:(0,e.jsx)(c,{className:"p-0",children:(0,e.jsxs)(y,{children:[(0,e.jsx)(w,{children:(0,e.jsxs)(h,{children:[(0,e.jsx)(i,{className:"w-20",children:a("Score")}),(0,e.jsx)(i,{children:a("Procedure")}),(0,e.jsx)(i,{className:"w-32",children:a("Kind")}),(0,e.jsx)(i,{children:a("Rules fired")})]})}),(0,e.jsx)(j,{children:I.map(s=>(0,e.jsxs)(h,{"data-testid":`${r}-row`,children:[(0,e.jsx)(n,{className:x("tabular-nums font-medium",m[s.coverage]),children:s.coverage==="exempt"?"\u2014":s.score}),(0,e.jsx)(n,{className:"font-mono text-xs",children:s.id}),(0,e.jsxs)(n,{className:"text-muted-foreground text-xs",children:[s.visibility," ",s.kind,s.sensitivity.level==="high"&&(0,e.jsx)("span",{className:"ml-1 text-amber-600 dark:text-amber-400",children:a("sensitive")})]}),(0,e.jsx)(n,{className:"text-muted-foreground text-xs",children:s.coverage==="exempt"?O(s,a("no reason given")):s.checks.map(R=>R.name).join(", ")})]},s.id))})]})})})]})},"O");export{q as default};