@protobase/ui 0.21.9 → 0.21.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/account/account-security-page.js +5 -4
- package/dist/auth/auth-messages.js +2 -1
- package/dist/auth/auth-provider.js +8 -3
- package/dist/package.js +1 -1
- package/dist/shell/assets/{app-B_L-OYQJ.js → app-9imuOKuW.js} +6 -6
- package/dist/shell/assets/{index-CRNWPM01.js → index-C_o0i6I2.js} +1 -1
- package/dist/shell/assets/{maplibre-DZlOrjmh.js → maplibre-DLYsHwYU.js} +1 -1
- package/dist/shell/assets/{markdown-content-DT_18T89.js → markdown-content-B410ow-t.js} +1 -1
- package/dist/shell/assets/{record-map-Bmns3gJf.js → record-map-DvgWFyLn.js} +1 -1
- package/dist/shell/assets/{records-map-Ci3qFCDs.js → records-map-CLj0uHGq.js} +1 -1
- package/dist/shell/assets/{shared-protobase-ui-DPgVYrS4.js → shared-protobase-ui-Bf1h2ktk.js} +1 -1
- package/dist/shell/index.html +3 -3
- package/dist/shell/protobase.shell.json +1 -1
- package/package.json +4 -4
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/markdown-content-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/markdown-content-B410ow-t.js","assets/rolldown-runtime-hePW80VL.js","assets/react-Cvdyeg_0.js","assets/jsx-runtime-NZYk81nU.js","assets/records-map-CLj0uHGq.js","assets/maplibre-DLYsHwYU.js","assets/react-dom-B-VxWsjA.js","assets/maplibre-DBE96hFo.css","assets/record-map-DvgWFyLn.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{n as e,r as t,t as n}from"./rolldown-runtime-hePW80VL.js";import{t as r}from"./react-Cvdyeg_0.js";import{t as i}from"./react-dom-B-VxWsjA.js";import{t as a}from"./jsx-runtime-NZYk81nU.js";var o=t(r(),1),s=e=>e?.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase();function c(e,t,n=[]){if(t==null)throw Error(`[lucide]: iconNode is required when icon name is used`);return{name:s(e),size:24,node:t,...n.length>0?{aliases:n}:{}}}var l=e=>{let t=``,n=!1;for(let r of e){if(r===`-`||r===`_`||r<=` `){n=t.length>0;continue}t.length===0?t+=r.toLowerCase():t+=n?r.toUpperCase():r,n=!1}return t},u=e=>{let t=l(e);return t.charAt(0).toUpperCase()+t.slice(1)},d=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),f={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,"stroke-width":2,"stroke-linecap":`round`,"stroke-linejoin":`round`};function p(e){return e!=null}function m(e,t={}){let n=t.attributeNames??{},r=e=>n[e]??e,i=e.size??e.width??f.width,a=e.size??e.height??f.height,o=e.aliases?.filter(e=>typeof e==`string`&&e.trim()!==``).map(e=>`lucide-${e}`)??[],s=[...e.name?[`lucide-${e.name}`]:[],...o],c=t.className?.split(` `).filter(Boolean)??[],l=t.includeDefaultClasses===!1?d(...c):d(`lucide`,...s,...c),u=t.absoluteStrokeWidth?Number(t.strokeWidth??f[`stroke-width`])*Number(e.size??e.width??f.width)/Number(t.size??t.width??f.width):t.strokeWidth??f[`stroke-width`];return[`svg`,{...Object.entries(f).reduce((e,[t,n])=>(e[r(t)]=n,e),{}),...`color`in t&&t.color&&{[r(`stroke`)]:t.color},...`size`in t&&p(t.size)&&{[r(`width`)]:t.size,[r(`height`)]:t.size},...`width`in t&&p(t.width)&&{[r(`width`)]:t.width},...`height`in t&&p(t.height)&&{[r(`height`)]:t.height},[r(`stroke-width`)]:u,...l&&{[r(`class`)]:l},[r(`viewBox`)]:`0 0 ${i} ${a}`,...t.hasA11yProp===!1?{[r(`aria-hidden`)]:`true`}:{},...`attributes`in t&&t.attributes},e.node.map(e=>{let[n,i,a]=e,o=t.nonScalingStroke?{[r(`vector-effect`)]:`non-scaling-stroke`,...i}:i;return a?[n,o,a]:[n,o]})]}function h(e,t={}){return m(e,{...t,attributeNames:{...t.attributeNames,class:`className`,"stroke-width":`strokeWidth`,"stroke-linecap":`strokeLinecap`,"stroke-linejoin":`strokeLinejoin`,"vector-effect":`vectorEffect`}})}var g=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},_=(0,o.createContext)({}),v=()=>(0,o.useContext)(_),y=(0,o.forwardRef)(({color:e,size:t,width:n,height:r,strokeWidth:i,absoluteStrokeWidth:a,nonScalingStroke:s,className:c=``,children:l,iconNode:u=[],icon:f={node:u,aliases:[],size:24},...p},m)=>{let{size:_=24,strokeWidth:y=2,absoluteStrokeWidth:b=!1,nonScalingStroke:x=!1,color:S=`currentColor`,className:C=``}=v()??{},w=!!l||g(p),[T,E,D=[]]=h(f,{color:e??S,width:n??t??_,height:r??t??_,strokeWidth:i??y,absoluteStrokeWidth:a??b,nonScalingStroke:s??x,className:d(C,c),hasA11yProp:w,attributes:p});return(0,o.createElement)(T,{ref:m,...E},[...D.map(([e,t])=>(0,o.createElement)(e,t)),...Array.isArray(l)?l:[l]])});function b(e,t=[],n=[]){let r=typeof e==`string`?c(e,t,n):e,i=(0,o.forwardRef)(({className:e,...t},n)=>(0,o.createElement)(y,{ref:n,icon:r,className:e,...t}));return r.name&&(i.displayName=u(r.name)),i}var x={name:`arrow-down`,size:24,node:[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]};x.node;var S=b(x),C={name:`arrow-right`,size:24,node:[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]};C.node;var w=b(C),T={name:`arrow-up-down`,size:24,node:[[`path`,{d:`m21 16-4 4-4-4`,key:`f6ql7i`}],[`path`,{d:`M17 20V4`,key:`1ejh1v`}],[`path`,{d:`m3 8 4-4 4 4`,key:`11wl7u`}],[`path`,{d:`M7 4v16`,key:`1glfcx`}]]};T.node;var E=b(T),D={name:`arrow-up-right`,size:24,node:[[`path`,{d:`M7 7h10v10`,key:`1tivn9`}],[`path`,{d:`M7 17 17 7`,key:`1vkiza`}]]};D.node;var O=b(D),k={name:`arrow-up`,size:24,node:[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]};k.node;var A=b(k),j={name:`bath`,size:24,node:[[`path`,{d:`M10 4 8 6`,key:`1rru8s`}],[`path`,{d:`M17 19v2`,key:`ts1sot`}],[`path`,{d:`M2 12h20`,key:`9i4pu4`}],[`path`,{d:`M7 19v2`,key:`12npes`}],[`path`,{d:`M9 5 7.621 3.621A2.121 2.121 0 0 0 4 5v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5`,key:`14ym8i`}]]};j.node;var M=b(j),N={name:`bed`,size:24,node:[[`path`,{d:`M2 4v16`,key:`vw9hq8`}],[`path`,{d:`M2 8h18a2 2 0 0 1 2 2v10`,key:`1dgv2r`}],[`path`,{d:`M2 17h20`,key:`18nfp3`}],[`path`,{d:`M6 8v9`,key:`1yriud`}]]};N.node;var ee=b(N),P={name:`bell`,size:24,node:[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]};P.node;var te=b(P),F={name:`book-open`,size:24,node:[[`path`,{d:`M12 5v16`,key:`1f6ucr`}],[`path`,{d:`M20.001 19A2 2 0 0022 17V5a2 2 0 00-1.999-2L16 3.002A5 5 0 0012 5a5 5 0 00-4-2H4a2 2 0 00-2 2v12a2 2 0 001.999 2H8a5 5 0 014 2 5 5 0 014-2z`,key:`1fyvmf`}]]};F.node;var ne=b(F),re={name:`bookmark-check`,size:24,node:[[`path`,{d:`M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z`,key:`oz39mx`}],[`path`,{d:`m9 10 2 2 4-4`,key:`1gnqz4`}]]};re.node;var ie=b(re),I={name:`bookmark-plus`,size:24,node:[[`path`,{d:`M12 7v6`,key:`lw1j43`}],[`path`,{d:`M15 10H9`,key:`o6yqo3`}],[`path`,{d:`M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z`,key:`oz39mx`}]]};I.node;var ae=b(I),oe={name:`bookmark`,size:24,node:[[`path`,{d:`M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z`,key:`oz39mx`}]]};oe.node;var se=b(oe),L={name:`boxes`,size:24,node:[[`path`,{d:`M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z`,key:`lc1i9w`}],[`path`,{d:`m7 16.5-4.74-2.85`,key:`1o9zyk`}],[`path`,{d:`m7 16.5 5-3`,key:`va8pkn`}],[`path`,{d:`M7 16.5v5.17`,key:`jnp8gn`}],[`path`,{d:`M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z`,key:`8zsnat`}],[`path`,{d:`m17 16.5-5-3`,key:`8arw3v`}],[`path`,{d:`m17 16.5 4.74-2.85`,key:`8rfmw`}],[`path`,{d:`M17 16.5v5.17`,key:`k6z78m`}],[`path`,{d:`M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z`,key:`1xygjf`}],[`path`,{d:`M12 8 7.26 5.15`,key:`1vbdud`}],[`path`,{d:`m12 8 4.74-2.85`,key:`3rx089`}],[`path`,{d:`M12 13.5V8`,key:`1io7kd`}]]};L.node;var ce=b(L),le={name:`building-complex`,size:24,node:[[`path`,{d:`M10 12h4`,key:`a56b0p`}],[`path`,{d:`M10 8h4`,key:`1sr2af`}],[`path`,{d:`M14 21v-3a2 2 0 0 0-4 0v3`,key:`1rgiei`}],[`path`,{d:`M6 10H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-2`,key:`secmi2`}],[`path`,{d:`M6 21V5a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v16`,key:`16ra0t`}]],aliases:[`building-2`]};le.node;var ue=b(le),de={name:`calendar`,size:24,node:[[`path`,{d:`M8 2v3`,key:`1ioesn`}],[`path`,{d:`M16 2v3`,key:`otl347`}],[`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`,key:`h1oib`}],[`path`,{d:`M3 9h18`,key:`1pudct`}]]};de.node;var fe=b(de),pe={name:`chart-column`,size:24,node:[[`path`,{d:`M3 3v16a2 2 0 0 0 2 2h16`,key:`c24i48`}],[`path`,{d:`M18 17V9`,key:`2bz60n`}],[`path`,{d:`M13 17V5`,key:`1frdt8`}],[`path`,{d:`M8 17v-3`,key:`17ska0`}]],aliases:[`bar-chart-3`]};pe.node;var me=b(pe),he={name:`check`,size:24,node:[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]};he.node;var ge=b(he),_e={name:`chevron-down`,size:24,node:[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]};_e.node;var ve=b(_e),ye={name:`chevron-left`,size:24,node:[[`path`,{d:`m15 18-6-6 6-6`,key:`1wnfg3`}]]};ye.node;var be=b(ye),xe={name:`chevron-right`,size:24,node:[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]};xe.node;var Se=b(xe),Ce={name:`chevrons-up-down`,size:24,node:[[`path`,{d:`m7 15 5 5 5-5`,key:`1hf1tw`}],[`path`,{d:`m7 9 5-5 5 5`,key:`sgt6xg`}]]};Ce.node;var we=b(Ce),Te={name:`circle-arrow-up`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m16 12-4-4-4 4`,key:`177agl`}],[`path`,{d:`M12 16V8`,key:`1sbj14`}]],aliases:[`arrow-up-circle`]};Te.node;var Ee=b(Te),De={name:`circle-check`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m16 9-5.5 5.5L8 12`,key:`xofnsj`}]],aliases:[`check-circle-2`]};De.node;var Oe=b(De),ke={name:`circle-dashed`,size:24,node:[[`path`,{d:`M10.1 2.182a10 10 0 0 1 3.8 0`,key:`5ilxe3`}],[`path`,{d:`M13.9 21.818a10 10 0 0 1-3.8 0`,key:`11zvb9`}],[`path`,{d:`M17.609 3.721a10 10 0 0 1 2.69 2.7`,key:`1iw5b2`}],[`path`,{d:`M2.182 13.9a10 10 0 0 1 0-3.8`,key:`c0bmvh`}],[`path`,{d:`M20.279 17.609a10 10 0 0 1-2.7 2.69`,key:`1ruxm7`}],[`path`,{d:`M21.818 10.1a10 10 0 0 1 0 3.8`,key:`qkgqxc`}],[`path`,{d:`M3.721 6.391a10 10 0 0 1 2.7-2.69`,key:`1mcia2`}],[`path`,{d:`M6.391 20.279a10 10 0 0 1-2.69-2.7`,key:`1fvljs`}]]};ke.node;var Ae=b(ke),je={name:`circle-x`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]],aliases:[`x-circle`]};je.node;var Me=b(je),Ne={name:`circle`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]]};Ne.node;var Pe=b(Ne),Fe={name:`columns-3`,size:24,node:[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`path`,{d:`M15 3v18`,key:`14nvp0`}]],aliases:[`panels-left-right`]};Fe.node;var Ie=b(Fe),Le={name:`copy`,size:24,node:[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]};Le.node;var Re=b(Le),ze={name:`credit-card`,size:24,node:[[`rect`,{width:`20`,height:`14`,x:`2`,y:`5`,rx:`2`,key:`ynyp8z`}],[`line`,{x1:`2`,x2:`22`,y1:`10`,y2:`10`,key:`1b3vmo`}],[`path`,{d:`M6 14h2`,key:`mk7k0u`}]]};ze.node;var Be=b(ze),Ve={name:`door-open`,size:24,node:[[`path`,{d:`M10 21H2`,key:`1sthdo`}],[`path`,{d:`M10 3H7a2 2 0 00-2 2v16`,key:`15gt7x`}],[`path`,{d:`M14 12h.01`,key:`1jfl7z`}],[`path`,{d:`M19 21V5a2 2 0 00-1.675-1.974l-6.163-1.013A1 1 0 0010 3v18a1 1 0 001.124.992z`,key:`tyvg9a`}],[`path`,{d:`M22 21h-3`,key:`1ec3tr`}]]};Ve.node;var He=b(Ve),Ue={name:`download`,size:24,node:[[`path`,{d:`M12 15V3`,key:`m9g1x1`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`path`,{d:`m7 10 5 5 5-5`,key:`brsn70`}]]};Ue.node;var We=b(Ue),Ge={name:`earth`,size:24,node:[[`path`,{d:`M21.54 15H17a2 2 0 0 0-2 2v4.54`,key:`1djwo0`}],[`path`,{d:`M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17`,key:`1tzkfa`}],[`path`,{d:`M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05`,key:`14pb5j`}],[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}]],aliases:[`globe-2`]};Ge.node;var Ke=b(Ge),qe={name:`ellipsis-vertical`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`12`,cy:`5`,r:`1`,key:`gxeob9`}],[`circle`,{cx:`12`,cy:`19`,r:`1`,key:`lyex9k`}]],aliases:[`more-vertical`]};qe.node;var Je=b(qe),Ye={name:`ellipsis`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`19`,cy:`12`,r:`1`,key:`1wjl8i`}],[`circle`,{cx:`5`,cy:`12`,r:`1`,key:`1pcz8c`}]],aliases:[`more-horizontal`]};Ye.node;var Xe=b(Ye),Ze={name:`external-link`,size:24,node:[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]};Ze.node;var Qe=b(Ze),$e={name:`eye-off`,size:24,node:[[`path`,{d:`M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49`,key:`ct8e1f`}],[`path`,{d:`M14.084 14.158a3 3 0 0 1-4.242-4.242`,key:`151rxh`}],[`path`,{d:`M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143`,key:`13bj9a`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]};$e.node;var eee=b($e),et={name:`eye`,size:24,node:[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]};et.node;var tt=b(et),nt={name:`file-code-corner`,size:24,node:[[`path`,{d:`M4 12.15V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2h-3.35`,key:`1wthlu`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m5 16-3 3 3 3`,key:`331omg`}],[`path`,{d:`m9 22 3-3-3-3`,key:`lsp7cz`}]],aliases:[`file-code-2`]};nt.node;var rt=b(nt),it={name:`file-spreadsheet`,size:24,node:[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M8 13h2`,key:`yr2amv`}],[`path`,{d:`M14 13h2`,key:`un5t4a`}],[`path`,{d:`M8 17h2`,key:`2yhykz`}],[`path`,{d:`M14 17h2`,key:`10kma7`}]]};it.node;var tee=b(it),at={name:`file-text`,size:24,node:[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10 9H8`,key:`b1mrlr`}],[`path`,{d:`M16 13H8`,key:`t4e002`}],[`path`,{d:`M16 17H8`,key:`z1uh3a`}]]};at.node;var ot=b(at),st={name:`grip-vertical`,size:24,node:[[`circle`,{cx:`9`,cy:`12`,r:`1`,key:`1vctgf`}],[`circle`,{cx:`9`,cy:`5`,r:`1`,key:`hp0tcf`}],[`circle`,{cx:`9`,cy:`19`,r:`1`,key:`fkjjf6`}],[`circle`,{cx:`15`,cy:`12`,r:`1`,key:`1tmaij`}],[`circle`,{cx:`15`,cy:`5`,r:`1`,key:`19l28e`}],[`circle`,{cx:`15`,cy:`19`,r:`1`,key:`f4zoj3`}]]};st.node;var ct=b(st),lt={name:`heart`,size:24,node:[[`path`,{d:`M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5`,key:`mvr1a0`}]]};lt.node;var ut=b(lt),dt={name:`house`,size:24,node:[[`path`,{d:`M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8`,key:`5wwlr5`}],[`path`,{d:`M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`,key:`r6nss1`}]],aliases:[`home`]};dt.node;var nee=b(dt),ft={name:`images`,size:24,node:[[`path`,{d:`m22 11-1.296-1.296a2.4 2.4 0 0 0-3.408 0L11 16`,key:`9kzy35`}],[`path`,{d:`M4 8a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2`,key:`1t0f0t`}],[`circle`,{cx:`13`,cy:`7`,r:`1`,fill:`currentColor`,key:`1obus6`}],[`rect`,{x:`8`,y:`2`,width:`14`,height:`14`,rx:`2`,key:`1gvhby`}]]};ft.node;var pt=b(ft),mt={name:`info`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]};mt.node;var ht=b(mt),gt={name:`key-round`,size:24,node:[[`path`,{d:`M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z`,key:`1s6t7t`}],[`circle`,{cx:`16.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`w0ekpg`}]]};gt.node;var _t=b(gt),vt={name:`land-plot`,size:24,node:[[`path`,{d:`m12 8 6-3-6-3v10`,key:`mvpnpy`}],[`path`,{d:`m8 11.99-5.5 3.14a1 1 0 0 0 0 1.74l8.5 4.86a2 2 0 0 0 2 0l8.5-4.86a1 1 0 0 0 0-1.74L16 12`,key:`ek95tt`}],[`path`,{d:`m6.49 12.85 11.02 6.3`,key:`1kt42w`}],[`path`,{d:`M17.51 12.85 6.5 19.15`,key:`v55bdg`}]]};vt.node;var yt=b(vt),bt={name:`layout-dashboard`,size:24,node:[[`rect`,{width:`7`,height:`9`,x:`3`,y:`3`,rx:`1`,key:`10lvy0`}],[`rect`,{width:`7`,height:`5`,x:`14`,y:`3`,rx:`1`,key:`16une8`}],[`rect`,{width:`7`,height:`9`,x:`14`,y:`12`,rx:`1`,key:`1hutg5`}],[`rect`,{width:`7`,height:`5`,x:`3`,y:`16`,rx:`1`,key:`ldoo1y`}]]};bt.node;var xt=b(bt),St={name:`layout-grid`,size:24,node:[[`rect`,{width:`7`,height:`7`,x:`3`,y:`3`,rx:`1`,key:`1g98yp`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`3`,rx:`1`,key:`6d4xhi`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`14`,rx:`1`,key:`nxv5o0`}],[`rect`,{width:`7`,height:`7`,x:`3`,y:`14`,rx:`1`,key:`1bb6yr`}]]};St.node;var ree=b(St),Ct={name:`leaf`,size:24,node:[[`path`,{d:`M11 20a10 10 0 0010-10 25.9 25.9 0 00-1.04-7.281 1 1 0 00-1.755-.325C15.833 5.5 13 5.5 9.8 6.1A7 7 0 0011 20`,key:`1wjnjv`}],[`path`,{d:`M2 21a5 5 0 012.911-4.544C7.613 15.212 8.351 15.24 11 13`,key:`c1ejpn`}]]};Ct.node;var wt=b(Ct),Tt={name:`life-buoy`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m4.93 4.93 4.24 4.24`,key:`1ymg45`}],[`path`,{d:`m14.83 9.17 4.24-4.24`,key:`1cb5xl`}],[`path`,{d:`m14.83 14.83 4.24 4.24`,key:`q42g0n`}],[`path`,{d:`m9.17 14.83-4.24 4.24`,key:`bqpfvv`}],[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}]]};Tt.node;var Et=b(Tt),Dt={name:`link-2`,size:24,node:[[`path`,{d:`M9 17H7A5 5 0 0 1 7 7h2`,key:`8i5ue5`}],[`path`,{d:`M15 7h2a5 5 0 1 1 0 10h-2`,key:`1b9ql8`}],[`line`,{x1:`8`,x2:`16`,y1:`12`,y2:`12`,key:`1jonct`}]]};Dt.node;var Ot=b(Dt),kt={name:`list`,size:24,node:[[`path`,{d:`M3 5h.01`,key:`18ugdj`}],[`path`,{d:`M3 12h.01`,key:`nlz23k`}],[`path`,{d:`M3 19h.01`,key:`noohij`}],[`path`,{d:`M8 5h13`,key:`1pao27`}],[`path`,{d:`M8 12h13`,key:`1za7za`}],[`path`,{d:`M8 19h13`,key:`m83p4d`}]]};kt.node;var At=b(kt),jt={name:`loader-circle`,size:24,node:[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]],aliases:[`loader-2`]};jt.node;var Mt=b(jt),Nt={name:`lock`,size:24,node:[[`rect`,{width:`18`,height:`11`,x:`3`,y:`11`,rx:`2`,ry:`2`,key:`1w4ew1`}],[`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`,key:`fwvmzm`}]]};Nt.node;var Pt=b(Nt),Ft={name:`log-in`,size:24,node:[[`path`,{d:`m10 17 5-5-5-5`,key:`1bsop3`}],[`path`,{d:`M15 12H3`,key:`6jk70r`}],[`path`,{d:`M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4`,key:`u53s6r`}]]};Ft.node;var It=b(Ft),Lt={name:`log-out`,size:24,node:[[`path`,{d:`m16 17 5-5-5-5`,key:`1bji2h`}],[`path`,{d:`M21 12H9`,key:`dn1m92`}],[`path`,{d:`M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4`,key:`1uf3rs`}]]};Lt.node;var Rt=b(Lt),zt={name:`mail`,size:24,node:[[`path`,{d:`m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7`,key:`132q7q`}],[`rect`,{x:`2`,y:`4`,width:`20`,height:`16`,rx:`2`,key:`izxlao`}]]};zt.node;var Bt=b(zt),Vt={name:`map`,size:24,node:[[`path`,{d:`M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z`,key:`169xi5`}],[`path`,{d:`M15 5.764v15`,key:`1pn4in`}],[`path`,{d:`M9 3.236v15`,key:`1uimfh`}]]};Vt.node;var iee=b(Vt),Ht={name:`menu`,size:24,node:[[`path`,{d:`M4 5h16`,key:`1tepv9`}],[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 19h16`,key:`1djgab`}]]};Ht.node;var aee=b(Ht),Ut={name:`minus`,size:24,node:[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]};Ut.node;var Wt=b(Ut),Gt={name:`monitor`,size:24,node:[[`rect`,{width:`20`,height:`14`,x:`2`,y:`3`,rx:`2`,key:`48i651`}],[`line`,{x1:`8`,x2:`16`,y1:`21`,y2:`21`,key:`1svkeh`}],[`line`,{x1:`12`,x2:`12`,y1:`17`,y2:`21`,key:`vw1qmm`}]]};Gt.node;var Kt=b(Gt),qt={name:`moon`,size:24,node:[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]};qt.node;var Jt=b(qt),Yt={name:`network`,size:24,node:[[`rect`,{x:`16`,y:`16`,width:`6`,height:`6`,rx:`1`,key:`4q2zg0`}],[`rect`,{x:`2`,y:`16`,width:`6`,height:`6`,rx:`1`,key:`8cvhb9`}],[`rect`,{x:`9`,y:`2`,width:`6`,height:`6`,rx:`1`,key:`1egb70`}],[`path`,{d:`M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3`,key:`1jsf9p`}],[`path`,{d:`M12 12V8`,key:`2874zd`}]]};Yt.node;var Xt=b(Yt),Zt={name:`package`,size:24,node:[[`path`,{d:`M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z`,key:`1a0edw`}],[`path`,{d:`M12 22V12`,key:`d0xqtd`}],[`polyline`,{points:`3.29 7 12 12 20.71 7`,key:`ousv84`}],[`path`,{d:`m7.5 4.27 9 5.15`,key:`1c824w`}]]};Zt.node;var Qt=b(Zt),$t={name:`paperclip`,size:24,node:[[`path`,{d:`m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551`,key:`1miecu`}]]};$t.node;var en=b($t),tn={name:`pencil`,size:24,node:[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]};tn.node;var nn=b(tn),rn={name:`plus`,size:24,node:[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]};rn.node;var an=b(rn),on={name:`puzzle`,size:24,node:[[`path`,{d:`M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z`,key:`w46dr5`}]]};on.node;var sn=b(on),cn={name:`receipt`,size:24,node:[[`path`,{d:`M12 17V7`,key:`pyj7ub`}],[`path`,{d:`M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8`,key:`1elt7d`}],[`path`,{d:`M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z`,key:`ycz6yz`}]]};cn.node;var ln=b(cn),un={name:`refresh-cw`,size:24,node:[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]};un.node;var oee=b(un),dn={name:`ruler-dimension-line`,size:24,node:[[`path`,{d:`M10 15v-3`,key:`1pjskw`}],[`path`,{d:`M14 15v-3`,key:`1o1mqj`}],[`path`,{d:`M18 15v-3`,key:`cws6he`}],[`path`,{d:`M2 8V4`,key:`3jv1jz`}],[`path`,{d:`M22 6H2`,key:`1iqbfk`}],[`path`,{d:`M22 8V4`,key:`16f4ou`}],[`path`,{d:`M6 15v-3`,key:`1ij1qe`}],[`rect`,{x:`2`,y:`12`,width:`20`,height:`8`,rx:`2`,key:`1tqiko`}]]};dn.node;var see=b(dn),fn={name:`search`,size:24,node:[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]};fn.node;var pn=b(fn),mn={name:`send-horizontal`,size:24,node:[[`path`,{d:`M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z`,key:`117uat`}],[`path`,{d:`M6 12h16`,key:`s4cdu5`}]],aliases:[`send-horizonal`]};mn.node;var cee=b(mn),hn={name:`send`,size:24,node:[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]};hn.node;var lee=b(hn),gn={name:`settings`,size:24,node:[[`path`,{d:`M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915`,key:`1i5ecw`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]};gn.node;var _n=b(gn),vn={name:`shield-check`,size:24,node:[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]};vn.node;var yn=b(vn),bn={name:`shopping-cart`,size:24,node:[[`path`,{d:`m2.05 2.05 1.099-.028a1 1 0 0 1 1.008.815l2.69 14.347A1 1 0 0 0 7.83 18H18`,key:`uebgi3`}],[`path`,{d:`M4.563 5h16.435a1 1 0 0 1 .981 1.204l-1.026 6.226A2 2 0 0 1 18.962 14H6.25`,key:`1j7c9p`}],[`circle`,{cx:`18`,cy:`20`,r:`2`,key:`t9985n`}],[`circle`,{cx:`8`,cy:`20`,r:`2`,key:`ckkr5m`}]]};bn.node;var xn=b(bn),Sn={name:`sliders-horizontal`,size:24,node:[[`path`,{d:`M10 5H3`,key:`1qgfaw`}],[`path`,{d:`M12 19H3`,key:`yhmn1j`}],[`path`,{d:`M14 3v4`,key:`1sua03`}],[`path`,{d:`M16 17v4`,key:`1q0r14`}],[`path`,{d:`M21 12h-9`,key:`1o4lsq`}],[`path`,{d:`M21 19h-5`,key:`1rlt1p`}],[`path`,{d:`M21 5h-7`,key:`1oszz2`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M8 12H3`,key:`a7s4jb`}]]};Sn.node;var Cn=b(Sn),wn={name:`sparkles`,size:24,node:[[`path`,{d:`M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z`,key:`1s2grr`}],[`path`,{d:`M20 2v4`,key:`1rf3ol`}],[`path`,{d:`M22 4h-4`,key:`gwowj6`}],[`circle`,{cx:`4`,cy:`20`,r:`2`,key:`6kqj1y`}]],aliases:[`stars`]};wn.node;var Tn=b(wn),En={name:`square-kanban`,size:24,node:[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M8 7v7`,key:`1x2jlm`}],[`path`,{d:`M12 7v4`,key:`xawao1`}],[`path`,{d:`M16 7v9`,key:`1hp2iy`}]],aliases:[`kanban-square`]};En.node;var Dn=b(En),On={name:`sun-moon`,size:24,node:[[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M14.837 16.385a6 6 0 1 1-7.223-7.222c.624-.147.97.66.715 1.248a4 4 0 0 0 5.26 5.259c.589-.255 1.396.09 1.248.715`,key:`xlf6rm`}],[`path`,{d:`M16 12a4 4 0 0 0-4-4`,key:`6vsxu`}],[`path`,{d:`m19 5-1.256 1.256`,key:`1yg6a6`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}]]};On.node;var kn=b(On),An={name:`sun`,size:24,node:[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]};An.node;var jn=b(An),Mn={name:`table-2`,size:24,node:[[`path`,{d:`M3 9h18`,key:`1pudct`}],[`path`,{d:`M9 3v18`,key:`fh3hqa`}],[`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`,key:`h1oib`}]]};Mn.node;var Nn=b(Mn),Pn={name:`tag`,size:24,node:[[`path`,{d:`M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z`,key:`vktsd0`}],[`circle`,{cx:`7.5`,cy:`7.5`,r:`.5`,fill:`currentColor`,key:`kqv944`}]]};Pn.node;var Fn=b(Pn),In={name:`tags`,size:24,node:[[`path`,{d:`M13.172 2a2 2 0 0 1 1.414.586l6.71 6.71a2.4 2.4 0 0 1 0 3.408l-4.592 4.592a2.4 2.4 0 0 1-3.408 0l-6.71-6.71A2 2 0 0 1 6 9.172V3a1 1 0 0 1 1-1z`,key:`16rjxf`}],[`path`,{d:`M2 7v6.172a2 2 0 0 0 .586 1.414l6.71 6.71a2.4 2.4 0 0 0 3.191.193`,key:`178nd4`}],[`circle`,{cx:`10.5`,cy:`6.5`,r:`.5`,fill:`currentColor`,key:`12ikhr`}]]};In.node;var Ln=b(In),Rn={name:`trash`,size:24,node:[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]],aliases:[`trash-2`]};Rn.node;var zn=b(Rn),Bn={name:`triangle-alert`,size:24,node:[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]],aliases:[`alert-triangle`]};Bn.node;var Vn=b(Bn),Hn={name:`truck`,size:24,node:[[`path`,{d:`M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2`,key:`wrbu53`}],[`path`,{d:`M15 18H9`,key:`1lyqi6`}],[`path`,{d:`M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14`,key:`lysw3i`}],[`circle`,{cx:`17`,cy:`18`,r:`2`,key:`332jqn`}],[`circle`,{cx:`7`,cy:`18`,r:`2`,key:`19iecd`}]]};Hn.node;var Un=b(Hn),Wn={name:`upload`,size:24,node:[[`path`,{d:`M12 3v12`,key:`1x0j5s`}],[`path`,{d:`m17 8-5-5-5 5`,key:`7q97r8`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}]]};Wn.node;var Gn=b(Wn),Kn={name:`user-round-cog`,size:24,node:[[`path`,{d:`m14.305 19.53.923-.382`,key:`3m78fa`}],[`path`,{d:`m15.228 16.852-.923-.383`,key:`npixar`}],[`path`,{d:`m16.852 15.228-.383-.923`,key:`5xggr7`}],[`path`,{d:`m16.852 20.772-.383.924`,key:`dpfhf9`}],[`path`,{d:`m19.148 15.228.383-.923`,key:`1reyyz`}],[`path`,{d:`m19.53 21.696-.382-.924`,key:`1goivc`}],[`path`,{d:`M2 21a8 8 0 0 1 10.434-7.62`,key:`1yezr2`}],[`path`,{d:`m20.772 16.852.924-.383`,key:`htqkph`}],[`path`,{d:`m20.772 19.148.924.383`,key:`9w9pjp`}],[`circle`,{cx:`10`,cy:`8`,r:`5`,key:`o932ke`}],[`circle`,{cx:`18`,cy:`18`,r:`3`,key:`1xkwt0`}]],aliases:[`user-cog-2`]};Kn.node;var uee=b(Kn),qn={name:`users`,size:24,node:[[`path`,{d:`M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2`,key:`1yyitq`}],[`path`,{d:`M16 3.128a4 4 0 0 1 0 7.744`,key:`16gr8j`}],[`path`,{d:`M22 21v-2a4 4 0 0 0-3-3.87`,key:`kshegd`}],[`circle`,{cx:`9`,cy:`7`,r:`4`,key:`nufk8`}]]};qn.node;var Jn=b(qn),Yn={name:`wallet`,size:24,node:[[`path`,{d:`M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1`,key:`18etb6`}],[`path`,{d:`M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4`,key:`xoc0q4`}]]};Yn.node;var dee=b(Yn),Xn={name:`warehouse`,size:24,node:[[`path`,{d:`M18 21V10a1 1 0 0 0-1-1H7a1 1 0 0 0-1 1v11`,key:`pb2vm6`}],[`path`,{d:`M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 1.132-1.803l7.95-3.974a2 2 0 0 1 1.837 0l7.948 3.974A2 2 0 0 1 22 8z`,key:`doq5xv`}],[`path`,{d:`M6 13h12`,key:`yf64js`}],[`path`,{d:`M6 17h12`,key:`1jwigz`}]]};Xn.node;var Zn=b(Xn),Qn={name:`x`,size:24,node:[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]};Qn.node;var $n=b(Qn),er={name:`zap`,size:24,node:[[`path`,{d:`M15.914 4a1.5 1.5 0 00-2.474-1.561l-9 9A1.5 1.5 0 005.5 14h4.002a.5.5 0 01.471.666L8.086 20a1.5 1.5 0 002.475 1.56l9-9A1.5 1.5 0 0018.5 10h-3.997a.5.5 0 01-.472-.667z`,key:`1v7up4`}]]};er.node;var tr=b(er),nr=t(i()),rr=`/-/account`,ir=`/-/sign-in-policy`,ar=(e,t,n)=>[{id:`account-security`,label:`Sign-in & security`,icon:_t,href:`${e}${rr}`,active:t===rr},...n?[{id:`sign-in-policy`,label:`Sign-in policy`,icon:yn,href:`${e}${ir}`,active:t===ir}]:[]],or=(e,t,n,r)=>({code:e,message:t,hint:n,span:r}),sr=(e,t)=>{let n=Array.from({length:t.length+1},(e,t)=>t);for(let r=1;r<=e.length;r++){let i=[r];for(let a=1;a<=t.length;a++){let o=e[r-1]===t[a-1]?0:1;i[a]=Math.min(n[a]+1,i[a-1]+1,n[a-1]+o)}n=i}return n[t.length]},cr=(e,t)=>{let n=e.toLowerCase(),r=t.map(e=>({candidate:e,score:sr(n,e.toLowerCase())})).sort((e,t)=>e.score-t.score)[0];return r&&r.score<=Math.max(2,Math.floor(e.length/3))?r.candidate:void 0},lr=(e,t)=>({start:e.start,end:t.end}),ur=(e,t)=>t===2?e%4==0&&(e%100!=0||e%400==0)?29:28:[4,6,9,11].includes(t)?30:31,dr=e=>{let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return!1;let[n,r,i]=[Number(t[1]),Number(t[2]),Number(t[3])];return r>=1&&r<=12&&i>=1&&i<=ur(n,r)},fr=e=>{let t=/^(\d{4}-\d{2}-\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/.exec(e);if(!t)return!1;let[n,r,i]=[Number(t[2]),Number(t[3]),Number(t[4])],[a,o]=[Number(t[5]??0),Number(t[6]??0)];return dr(t[1])&&n<=23&&r<=59&&i<=59&&a<=23&&o<=59},pr={s:1,m:60,h:3600,d:86400,w:604800},mr=e=>fr(e)?Date.parse(e.toUpperCase()):void 0,hr=/^(\d+(?:\.\d+)?)(s|m|h|d|w)$/,gr=e=>{let t=hr.exec(e);return t?Number(t[1])*pr[t[2]]:void 0},_r=/\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:[Zz]|[+-]\d{2}:\d{2})/y,vr=/\d{4}-\d{2}-\d{2}/y,yr=/[TtZz0-9:.+-]*/y,br=/0[xX][0-9a-fA-F]+/y,xr=/\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/y,Sr=(e,t,n)=>(e.lastIndex=n,e.exec(t)?.[0]),Cr=(e,t,n,r)=>{let i=Sr(_r,e,t);if(i&&fr(i))return{kind:`timestamp`,end:t+i.length};if(i||Sr(vr,e,t)){let n=t+(Sr(yr,e,t)??``).length;return{kind:`error`,end:n,error:or(`invalid-timestamp`,`"${e.slice(t,n)}" is not a valid RFC-3339 timestamp`,`Use a full timestamp like 2012-04-21T11:30:00Z, or quote a plain date: "2012-04-21"`,{start:t,end:n})}}let a=Sr(br,e,t);if(a)return n(e[t+a.length])?{kind:`number`,end:t+a.length}:void 0;let o=t+Sr(xr,e,t).length;return(r.durationUnits?`smhdw`:`s`).includes(e[o]??` `)&&n(e[o+1])?{kind:`duration`,end:o+1}:n(e[o])?{kind:`number`,end:o}:void 0},wr={a:`\x07`,b:`\b`,f:`\f`,n:`
|
|
3
3
|
`,r:`\r`,t:` `,v:`\v`,"'":`'`,'"':`"`,"\\":`\\`,"?":`?`,"`":"`"},Tr=(e,t,n)=>{let r=e.slice(t,t+n);return r.length===n&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):void 0},Er=(e,t)=>{let n=e[t+1];if(n===void 0)return{error:`a backslash at the end`,end:t+1};if(Object.hasOwn(wr,n))return{text:wr[n],end:t+2};let r={x:2,u:4,U:8};if(Object.hasOwn(r,n)){let i=Tr(e,t+2,r[n]),a=t+2+r[n];return i!==void 0&&i<=1114111&&!(i>=55296&&i<=57343)?{text:String.fromCodePoint(i),end:a}:{error:`\\${n} needs ${r[n]} hex digits naming a Unicode scalar value`,end:t+2}}let i=/^[0-3][0-7]{2}/.exec(e.slice(t+1,t+4));return i?{text:String.fromCharCode(parseInt(i[0],8)),end:t+4}:{error:`the escape "\\${n}"`,end:t+2}},Dr=(e,t)=>{let n=e[t],r=[],i=``,a=t+1;for(;a<e.length;){let t=e[a];if(t===n)return{end:a+1,value:i,errors:r};if(t!==`\\`){i+=t,a++;continue}let o=Er(e,a);`text`in o?i+=o.text:r.push(or(`invalid-escape`,`Invalid escape: ${o.error}`,`Valid escapes: \\a \\b \\f \\n \\r \\t \\v \\' \\" \\\\ \\? \\\` \\xHH \\uXXXX \\UXXXXXXXX \\ooo`,{start:a,end:o.end})),a=o.end}return r.push(or(`unterminated-string`,`String is missing its closing quote`,`Add a closing ${n}`,{start:t,end:e.length})),{end:e.length,value:void 0,errors:r}},Or={"(":`lparen`,")":`rparen`,",":`comma`,".":`dot`,":":`has`,"=":`eq`,"<":`lt`,">":`gt`,"-":`minus`},kr={AND:`and`,OR:`or`,NOT:`not`},Ar=e=>{let[t,n,r]=[e.at(-1),e.at(-2),e.at(-3)];return t?.kind===`rparen`&&n?.kind===`lparen`&&r?.text===`now`},jr=(e,t={})=>{let n=[],r=[],i=e=>e!==void 0&&(e in Or||e===`!`||t.arithmetic===!0&&e===`+`),a=e=>e===void 0||/\s/.test(e)||i(e)||e===`"`||e===`'`,o=(t,r,i,a=e.slice(r,i))=>n.push({kind:t,text:e.slice(r,i),value:a,span:{start:r,end:i}}),s=e.isWellFormed()?-1:e.search(/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/);s>=0&&r.push(or(`invalid-unicode`,`The filter contains an unpaired surrogate`,`Use well-formed UTF-16 text`,{start:s,end:s+1}));let c=0;for(;c<e.length;){let i=e[c];if(/\s/.test(i)){c++;continue}if(i===`"`||i===`'`){let t=Dr(e,c);r.push(...t.errors),t.value!==void 0&&o(`string`,c,t.end,t.value),c=t.end;continue}if(/[0-9]/.test(i)){let n=Cr(e,c,a,t);if(n?.kind===`error`?r.push(n.error):n&&o(n.kind,c,n.end),n){c=n.end;continue}}if(i===`!`||i===`<`||i===`>`){let t=e[c+1]===`=`;if(i===`!`&&!t){r.push(or(`unexpected-character`,`Unexpected character "!"`,`Use != for "not equal" or NOT / - for negation`,{start:c,end:c+1})),c++;continue}o(i===`!`?`ne`:i===`<`?t?`le`:`lt`:t?`ge`:`gt`,c,c+(t?2:1)),c+=t?2:1;continue}if(Object.hasOwn(Or,i)){o(Or[i],c,c+1),c++;continue}let s=t.arithmetic===`now-offset`&&Ar(n);if(i===`+`&&(t.arithmetic===!0||s)){o(`plus`,c,c+1),c++;continue}let l=c+1;for(;!a(e[l]);)l++;let u=e.slice(c,l);o(Object.hasOwn(kr,u)?kr[u]:`text`,c,l),c=l}return o(`eof`,e.length,e.length),{tokens:n,errors:r}},Mr=class extends Error{error;constructor(e){super(e.message),this.error=e}},Nr=(e,t,n,r)=>{throw new Mr(or(e,t,n,r))},R=(e,t=0)=>e.tokens[Math.min(e.pos+t,e.tokens.length-1)],Pr=e=>{let t=R(e);return t.kind!==`eof`&&e.pos++,t},Fr=(e,t)=>R(e).kind===t?Pr(e):void 0,Ir=e=>e.kind===`eof`?`end of input`:`"${e.text}"`,Lr=(e,t,n,r)=>Fr(e,t)??Nr(`expected-token`,`Expected ${n} but found ${Ir(R(e))}`,r,R(e).span),Rr=(e,t,n)=>{e.depth>=e.maxDepth&&Nr(`too-deep`,`The filter is nested too deeply`,`Nest at most ${e.maxDepth} levels`,t),e.depth++;try{return n()}finally{e.depth--}},fee=[`text`,`and`,`or`,`not`],pee=e=>{let t=Lr(e,`text`,`a field name or value`,`Text may not contain spaces or the characters ( ) - . = : < > ! ,`),n=[t.text],r=t.span;for(;R(e).kind===`dot`;){let t=R(e,1),i=t.kind===`number`&&/^\d+(\.\d+)?$/.test(t.text);!fee.includes(t.kind)&&!i&&Nr(`expected-token`,`Expected a field name after "." but found ${Ir(t)}`,`Write traversals like customer.country`,t.span),Pr(e),Pr(e),n.push(...i?t.text.split(`.`):[t.text]),r=lr(r,t.span)}return{kind:`member`,path:n,span:r}},mee=e=>({kind:`duration`,amount:Number(e.text.slice(0,-1)),unit:e.text.slice(-1),span:e.span}),hee=[`member`,`string`,`number`,`boolean`,`duration`,`timestamp`,`call`,`binary`],zr=e=>hee.includes(e.kind),gee=(e,t,n)=>Rr(e,n,()=>{Pr(e);let r=[];if(R(e).kind!==`rparen`)do r.push(Hr(e));while(Fr(e,`comma`));return{kind:`call`,name:t,args:r,span:lr(n,Lr(e,`rparen`,`")"`,`Close the call to ${t}() with ")"`).span)}}),Br=e=>{let t=R(e);switch(t.kind){case`string`:return Pr(e),{kind:`string`,value:t.value,span:t.span};case`number`:return Pr(e),{kind:`number`,value:Number(t.text),raw:t.text,span:t.span};case`duration`:return Pr(e),mee(t);case`timestamp`:return Pr(e),{kind:`timestamp`,value:t.text,span:t.span};case`minus`:{let n=R(e,1);(n.kind!==`number`||n.span.start!==t.span.end)&&Nr(`unexpected-token`,`Expected a number after "-" but found ${Ir(n)}`,`Write negative numbers as -5, without a space`,n.span),Pr(e),Pr(e);let r=`-${n.text}`;return{kind:`number`,value:-Number(n.text),raw:r,span:lr(t.span,n.span)}}case`text`:{if((t.text===`true`||t.text===`false`)&&R(e,1).kind!==`dot`&&(R(e,1).kind!==`lparen`||R(e,1).span.start!==t.span.end))return Pr(e),{kind:`boolean`,value:t.text===`true`,span:t.span};let n=pee(e);return R(e).kind===`lparen`&&R(e).span.start===n.span.end?gee(e,n.path.join(`.`),n.span):n}default:return Nr(`unexpected-token`,`Expected a value but found ${Ir(t)}`,`Values are text, "strings", numbers, true/false, durations, timestamps or function calls`,t.span)}},_ee=e=>{let t=Pr(e);return Rr(e,t.span,()=>{let n=e.expression(e);return Lr(e,`rparen`,`")"`,`Close the group opened here`),n?n.kind===`global`?n.value:n:Nr(`unexpected-token`,`Empty group`,`Put an expression inside the parentheses`,t.span)})},Vr=e=>R(e).kind===`lparen`?_ee(e):Br(e),vee=e=>[`text`,`string`,`number`,`duration`,`timestamp`,`lparen`,`minus`].includes(R(e,1).kind),Hr=e=>{let t=Vr(e);if(!e.extensions.arithmetic||!zr(t))return t;let n=t,r=e.extensions.arithmetic===`now-offset`,i=()=>n.kind===`call`&&n.name===`now`&&n.args.length===0,a=()=>!r||i()&&R(e,1).kind===`duration`;if(r&&i()&&(R(e).kind===`plus`||R(e).kind===`minus`)&&R(e,1).kind!==`duration`)return Nr(`expected-token`,`Expected a duration after "${R(e).text}" but found ${Ir(R(e,1))}`,`Durations need a unit, for example now() - 30d`,R(e,1).span);for(;(R(e).kind===`plus`||R(e).kind===`minus`)&&vee(e)&&a();){let t=Pr(e).kind===`plus`?`+`:`-`,r=Vr(e);if(!zr(r))return Nr(`unexpected-token`,`Arithmetic needs values, not conditions`,`Use values on both sides of + and -`,r.span);n={kind:`binary`,op:t,left:n,right:r,span:lr(n.span,r.span)}}return n},Ur=e=>{let t=R(e),n=Hr(e);return zr(n)||Nr(`unexpected-token`,`A comparison needs a value on the right`,`Write field = value`,t.span),n},yee={eq:`=`,ne:`!=`,lt:`<`,le:`<=`,gt:`>`,ge:`>=`},Wr=[`text`,`string`,`number`,`duration`,`timestamp`,`not`,`minus`,`lparen`],Gr=(e,t)=>{let n=t.filter(e=>e!==void 0);return n.length<=1?n[0]:{kind:e,args:n,span:lr(n[0].span,n[n.length-1].span)}},bee=e=>{let t=0;for(;;){let{kind:n}=R(e);if(n===`eof`||t===0&&(n===`and`||n===`or`||n===`rparen`))return;n===`lparen`&&t++,n===`rparen`&&t--,Pr(e)}},xee=e=>{let t=Br(e),n=R(e);if(n.kind===`has`){Pr(e);let n=R(e);if(n.kind===`text`&&n.text===`*`)return Pr(e),{kind:`present`,left:t,span:lr(t.span,n.span)};let r=Ur(e);return{kind:`has`,left:t,right:r,span:lr(t.span,r.span)}}let r=yee[n.kind];if(r){Pr(e);let n=Ur(e);return{kind:`compare`,op:r,left:t,right:n,span:lr(t.span,n.span)}}return t.kind===`call`?t:{kind:`global`,value:t,span:t.span}},Kr=e=>{let t=R(e);return t.kind===`lparen`?(Pr(e),Rr(e,t.span,()=>{let n=Xr(e);return Fr(e,`rparen`)||e.errors.push(or(`expected-token`,`Expected ")" but found ${Ir(R(e))}`,`Close the group opened here`,t.span)),n})):xee(e)},See=e=>{let t=R(e);if(t.kind!==`not`&&t.kind!==`minus`)return Wr.includes(t.kind)?Rr(e,t.span,()=>Kr(e)):Nr(`unexpected-token`,`Unexpected ${Ir(t)}`,`Expected a field, a value or "("`,t.span);Pr(e);let n=R(e),r=n.kind===`minus`&&R(e,1).kind===`number`&&R(e,1).span.start===n.span.end;(n.kind===`not`||n.kind===`minus`&&!r)&&Nr(`unexpected-token`,`Negations cannot be stacked`,`Group the inner one: NOT (NOT a)`,n.span);let i=Rr(e,t.span,()=>Kr(e));if(!i)return;let a=lr(t.span,i.span);if(t.kind===`minus`&&i.kind===`global`&&i.value.kind===`number`&&!i.value.raw.startsWith(`-`)){let{raw:e,value:t}=i.value;return{kind:`global`,value:{kind:`number`,value:-t,raw:`-${e}`,span:a},span:a}}return{kind:`not`,arg:i,span:a}},qr=e=>{try{return See(e)}catch(t){if(!(t instanceof Mr))throw t;e.errors.push(t.error),bee(e);return}},Jr=e=>{let t=[qr(e)];for(;Fr(e,`or`);)t.push(qr(e));return Gr(`or`,t)},Yr=e=>{let t=[Jr(e)];for(;Wr.includes(R(e).kind);)t.push(Jr(e));return Gr(`sequence`,t)},Xr=e=>{let t=[Yr(e)];for(;Fr(e,`and`);)t.push(Yr(e));return Gr(`and`,t)},Zr=(e,t={})=>{let n=t.maxLength??1e4;if(e.length>n)return{ok:!1,ast:void 0,errors:[or(`too-long`,`The filter is longer than ${n} characters`,`Shorten the filter`,{start:n,end:e.length})]};let r=t.extensions??{},i=jr(e,r),a={tokens:i.tokens,pos:0,errors:i.errors,depth:0,maxDepth:t.maxDepth??64,extensions:r,expression:Xr},o=[];for(;R(a).kind!==`eof`;){if(R(a).kind===`rparen`){let e=Pr(a);a.errors.push(or(`unexpected-token`,`Unmatched ")"`,`Remove it or add a matching "("`,e.span));continue}o.push(Xr(a))}let s=o.filter(e=>e!==void 0),c=s.length<=1?s[0]:{kind:`and`,args:s,span:{start:s[0].span.start,end:s[s.length-1].span.end}},l=[...a.errors].sort((e,t)=>e.span.start-t.span.start);return l.length===0?{ok:!0,ast:c,errors:[]}:{ok:!1,ast:c,errors:l}},Qr=(e,t)=>{if(Object.hasOwn(e,t))return{name:t,spec:e[t]};let n=Object.entries(e).find(([,e])=>e.aliases?.includes(t));return n&&{name:n[0],spec:n[1]}},$r=(e,t)=>{let n=t.path[0],r=Qr(e.schema.fields,n);if(!r){let r=Object.entries(e.schema.fields).filter(([,e])=>e.filterable!==!1).map(([e])=>e),i=cr(n,r);e.errors.push(or(`unknown-field`,`Unknown field "${n}"`,i?`Did you mean "${i}"?`:`Available fields: ${r.join(`, `)}`,t.span));return}let i=[r.name],a=r.spec,o=a.filterable!==!1;for(let n of t.path.slice(1)){let r=a.type===`message`?a.fields?.[n]:a.type===`map`?a.value:a.type===`any`?a:void 0;if(!r||a.type===`message`&&!Object.hasOwn(a.fields??{},n)){e.errors.push(or(`invalid-traversal`,`Cannot traverse into "${n}" of "${i.join(`.`)}"`,a.type===`message`?`Available fields: ${Object.keys(a.fields??{}).join(`, `)}`:`Only message, map and any fields can be traversed`,t.span));return}i.push(n),a=r,o&&=a.filterable!==!1}if(!o){e.errors.push(or(`not-filterable`,`Field "${i.join(`.`)}" cannot be filtered on`,`Mark it filterable in the schema`,t.span));return}return{...t,path:i,field:{name:i.join(`.`),spec:a}}},ei=(e,t)=>({message:e,hint:t}),ti=(e,t)=>ei(`Expected ${e}`,t),ni=e=>e.kind===`string`?e.value:e.kind===`member`?e.path.join(`.`):void 0,ri={integer:/^-?(\d+|0[xX][0-9a-fA-F]+)$/,number:/^-?\d+(\.\d+)?([eE][+-]?\d+)?$|^-?0[xX][0-9a-fA-F]+$/},ii=(e,t)=>e===t||e===`any`||t===`any`||[`integer`,`number`].includes(e)&&[`integer`,`number`].includes(t),ai=(e,t,n)=>{let r=ni(n);switch(e){case`any`:return;case`string`:return r===void 0?ti(`a string`,`Quote text values: "..."`):void 0;case`enum`:return r!==void 0&&t?.values?.includes(r)?void 0:ei(`Invalid enum value`,`Allowed values: ${(t?.values??[]).join(`, `)}`);case`integer`:case`number`:{let t=n.kind===`number`?n.raw:r;return t!==void 0&&ri[e].test(t)?void 0:ti(e===`integer`?`an integer`:`a number`,`Write 42, -1.5 or 2.5e3, or quote a numeric string`)}case`boolean`:return n.kind===`boolean`||r===`true`||r===`false`?void 0:ti(`true or false`,`Write true or false`);case`timestamp`:return n.kind===`timestamp`||r!==void 0&&fr(r)?void 0:ti(`an RFC-3339 timestamp`,`Use "2012-04-21T11:30:00Z"`);case`duration`:return n.kind===`duration`||r!==void 0&&gr(r)!==void 0?void 0:ti(`a duration`,`Use a number with a unit, for example 20s or 1.5s`);case`map`:case`message`:return ei(`${e} fields cannot be compared`,`Compare a nested field, or use field:key`)}},oi=e=>[`member`,`string`,`number`,`boolean`,`duration`,`timestamp`,`call`,`binary`].includes(e.kind),si=(e,t,n,r)=>{if(!oi(n)){e.errors.push(or(`wrong-argument`,`Argument "${t.name}" must be a value`,`Pass a field, literal or function call`,n.span));return}if(t.type===`field`){if(n.kind!==`member`){e.errors.push(or(`wrong-argument`,`Argument "${t.name}" must be a field`,`Pass a field name without quotes`,n.span));return}let r=$r(e,n);if(r&&t.of&&!t.of.includes(r.field.spec.type)){e.errors.push(or(`wrong-argument`,`Argument "${t.name}" cannot be a ${r.field.spec.type} field`,`Accepted field types: ${t.of.join(`, `)}`,n.span));return}return r}let i=r(e,n);if(!i)return;if(t.type===`any`)return i.node;let a=i.type&&(n.kind===`call`||n.kind===`binary`)?ii(t.type,i.type)?void 0:{message:`Expected ${t.type}`,hint:`Argument "${t.name}" is ${i.type}`}:ai(t.type,void 0,i.node);return a&&e.errors.push(or(`wrong-argument`,a.message,a.hint,n.span)),a?void 0:i.node},ci=(e,t,n)=>{let r=e.schema.functions??{};if(!Object.hasOwn(r,t.name)){let n=cr(t.name,Object.keys(r));e.errors.push(or(`unknown-function`,`Unknown function "${t.name}"`,n?`Did you mean "${n}"?`:`Available functions: ${Object.keys(r).join(`, `)||`none`}`,t.span));return}let i=r[t.name],a=i.params.length;if(t.args.length<a||!i.rest&&t.args.length>a){let n=i.rest?`at least ${a}`:String(a);e.errors.push(or(`wrong-arity`,`${t.name}() takes ${n} argument(s) but got ${t.args.length}`,`Usage: ${t.name}(${[...i.params,...i.rest?[i.rest]:[]].map(e=>e.name).join(`, `)})`,t.span));return}let o=t.args.map((t,r)=>si(e,i.params[r]??i.rest,t,n));if(!o.some(e=>e===void 0))return{call:{...t,args:o},returns:i.returns??`boolean`}},li=(e,t,n)=>{if(e===`timestamp`&&t===`duration`)return`timestamp`;if(e===`timestamp`&&t===`timestamp`&&n===`-`||e===`duration`&&t===`duration`)return`duration`;if((e===`integer`||e===`number`)&&(t===`integer`||t===`number`))return e===`integer`&&t===`integer`?`integer`:`number`},ui={number:`number`,boolean:`boolean`,duration:`duration`,timestamp:`timestamp`},di=(e,t)=>{switch(t.kind){case`call`:{let n=ci(e,t,di);return n&&{node:n.call,type:n.returns}}case`binary`:{let n=di(e,t.left),r=di(e,t.right);if(!n||!r)return;let i=n.type&&r.type?li(n.type,r.type,t.op):n.type??r.type??`number`;if(!i){e.errors.push(or(`invalid-value`,`Cannot apply "${t.op}" to ${n.type} and ${r.type}`,`Add a duration to a timestamp, or combine numbers`,t.span));return}return{node:{...t,left:n.node,right:r.node},type:i}}case`number`:case`boolean`:case`duration`:case`timestamp`:return{node:t,type:ui[t.kind]};default:return{node:t,type:void 0}}},fi=[`string`,`integer`,`number`,`timestamp`,`duration`,`any`],pi=(e,t)=>{if(t.kind===`member`){let n=$r(e,t);return n&&{node:n,type:n.field.spec.type,spec:n.field.spec}}let n=di(e,t);return n&&{...n,spec:void 0}},mi=(e,t,n,r)=>{e.errors.push(or(`operator-not-allowed`,t,n,r.span))},hi=(e,t,n)=>{if(!t.type)return di(e,n)?.node;let r=di(e,n);if(!r)return;let i=r.type&&(n.kind===`call`||n.kind===`binary`)?ii(t.type,r.type)?void 0:{message:`Expected ${t.type} but got ${r.type}`,hint:`Compare values of the same type`}:ai(t.type,t.spec,r.node);return i&&e.errors.push(or(`invalid-value`,i.message,i.hint,n.span)),i?void 0:r.node},gi=(e,t)=>{let n=pi(e,t.left);if(!n)return;let r=n.type;if(n.spec?.repeated)return mi(e,`"${t.op}" is not supported on repeated fields`,`Use field:value to test membership`,t);if(r===`map`||r===`message`)return mi(e,`${r} fields cannot be compared`,`Use field:key, or compare a nested field`,t);if(r&&![`=`,`!=`].includes(t.op)&&!fi.includes(r))return mi(e,`"${t.op}" is not supported for ${r} fields`,`Supported: = !=`,t);let i=(t.op===`=`||t.op===`!=`)&&t.right.kind===`string`&&t.right.value.includes(`*`);if(i&&r&&r!==`string`&&r!==`any`){e.errors.push(or(`wildcard-not-allowed`,`Wildcards are only supported on string fields, not ${r}`,`Remove the "*"`,t.right.span));return}let a=i?t.right:hi(e,n,t.right);return a&&{...t,left:n.node,right:a}},_i=(e,t)=>{let n=pi(e,t.left);if(!n)return;let{type:r,spec:i}=n,a=hi(e,!i?.repeated&&(r===`map`||r===`message`)?{...n,type:`string`}:n,t.right);return a&&{...t,left:n.node,right:a}},vi=(e,t)=>{switch(t.kind){case`sequence`:case`and`:case`or`:{let n=t.args.map(t=>vi(e,t));return n.every(e=>e)?{...t,args:n}:void 0}case`not`:{let n=vi(e,t.arg);return n&&{...t,arg:n}}case`compare`:return gi(e,t);case`has`:return _i(e,t);case`present`:{let n=pi(e,t.left);return n&&{...t,left:n.node}}case`global`:return t;case`call`:{let n=ci(e,t,di);if(n&&n.returns!==`boolean`){e.errors.push(or(`not-boolean`,`${t.name}() returns ${n.returns}, not a condition`,`Compare its result: f(x) > 1`,t.span));return}return n?.call}}},yi=(e,t)=>{let n={schema:t,errors:[]},r=vi(n,e);return!r||n.errors.length>0?{ok:!1,errors:[...n.errors].sort((e,t)=>e.span.start-t.span.start)}:{ok:!0,ast:r}},bi={"\\":`\\\\`,'"':`\\"`,"\n":`\\n`,"\r":`\\r`," ":`\\t`,"\x07":`\\a`,"\b":`\\b`,"\f":`\\f`,"\v":`\\v`},xi=e=>{if(!e.isWellFormed())throw Error(`Strings with unpaired surrogates cannot be printed`);return`"${e.replace(/[\\"\u0000-\u001f\u007f-\u009f]/g,e=>bi[e]??`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`},Si=e=>{switch(e.kind){case`string`:return xi(e.value);case`number`:return e.raw;case`boolean`:return String(e.value);case`duration`:return`${e.amount}${e.unit}`;case`timestamp`:return e.value}},Ci=e=>e.kind===`number`&&e.raw.startsWith(`-`),wi=e=>{switch(e.kind){case`member`:return e.path.join(`.`);case`call`:return`${e.name}(${e.args.map(Ti).join(`, `)})`;case`binary`:if(e.right.kind===`binary`)throw Error(`Arithmetic is left-associative; a binary on the right cannot be printed`);return`${wi(e.left)} ${e.op} ${wi(e.right)}`;default:return Si(e)}},Ti=e=>Di(e)?`(${Ai(e)})`:wi(e),Ei=[`member`,`string`,`number`,`boolean`,`duration`,`timestamp`,`binary`],Di=e=>!Ei.includes(e.kind)&&e.kind!==`call`,Oi=e=>{if(Ci(e))throw Error(`A negative number cannot start a comparison; "-5 = x" parses as a negation`);return wi(e)},ki=(e,t)=>({and:[`and`,`or`],sequence:[`and`,`or`,`sequence`],or:[`and`,`or`,`sequence`],not:[`and`,`or`,`sequence`,`not`]})[e].includes(t.kind)?`(${Ai(t)})`:Ai(t),Ai=e=>{switch(e.kind){case`and`:return e.args.map(e=>ki(`and`,e)).join(` AND `);case`or`:return e.args.map(e=>ki(`or`,e)).join(` OR `);case`sequence`:return e.args.map(e=>ki(`sequence`,e)).join(` `);case`not`:return`NOT ${ki(`not`,e.arg)}`;case`compare`:return`${Oi(e.left)} ${e.op} ${wi(e.right)}`;case`has`:return`${Oi(e.left)}:${wi(e.right)}`;case`present`:return`${Oi(e.left)}:*`;case`global`:return wi(e.value);case`call`:return wi(e)}},ji=class{int;scale;constructor(e,t){this.int=e,this.scale=t}compare(e){let t=Math.max(this.scale,e.scale),n=this.int*10n**BigInt(t-this.scale),r=e.int*10n**BigInt(t-e.scale);return n<r?-1:+(n>r)}toNumber(){return Number(`${this.int}e-${this.scale}`)}},Mi=/^(-?)(\d+)(?:\.(\d+))?$/,Ni=e=>{let t=Mi.exec(e);if(!t)return;let n=t[3]??``;return new ji(BigInt(`${t[1]}${t[2]}${n}`),n.length)},Pi=/^-?(?:\d+(?:\.\d+)?(?:[eE][+-]?\d+)?|0[xX][0-9a-fA-F]+)$/,Fi=e=>{if(typeof e==`number`)return e;if(typeof e==`bigint`)return Number(e);if(e instanceof ji)return e.toNumber();if(typeof e==`string`&&Pi.test(e))return e.startsWith(`-`)?-Number(e.slice(1)):Number(e)},Ii=e=>typeof e==`bigint`?new ji(e,0):typeof e==`number`?Number.isFinite(e)?Ni(String(e)):void 0:typeof e==`string`?Ni(e):e instanceof ji?e:void 0,Li=(e,t)=>{let n=0,r=0,i=-1,a=0;for(;r<t.length;)if(n<e.length&&e[n]===`*`)i=n++,a=r;else if(n<e.length&&e[n]===t[r])n++,r++;else if(i>=0)n=i+1,r=++a;else return!1;for(;e[n]===`*`;)n++;return n===e.length},Ri=e=>typeof e==`object`&&!!e&&!(e instanceof Date)&&!(e instanceof ji)&&`seconds`in e&&typeof e.seconds==`number`,zi=e=>{switch(e.kind){case`string`:return e.value;case`number`:return Ni(e.raw)??e.value;case`boolean`:return e.value;case`duration`:return{seconds:e.amount*pr[e.unit]};case`timestamp`:return new Date(mr(e.value)??NaN)}},Bi=e=>Ri(e)?e.seconds:typeof e==`number`?e:typeof e==`string`?gr(e):void 0,Vi=e=>e instanceof Date?e.getTime():typeof e==`string`?mr(e):void 0,Hi=e=>{switch(e.kind){case`string`:return e.value;case`member`:return e.path.join(`.`);case`number`:return e.raw;case`boolean`:return String(e.value);case`duration`:return`${e.amount}${e.unit}`;case`timestamp`:return e.value;default:return}},Ui=(e,t)=>{switch(e){case`=`:return t===0;case`!=`:return t!==0;case`<`:return t<0;case`<=`:return t<=0;case`>`:return t>0;case`>=`:return t>=0}},Wi=(e,t)=>e<t?-1:+(e>t),Gi=(e,t)=>{let n=Ii(e),r=Ii(t);if(n&&r)return n.compare(r);let i=Fi(e),a=Fi(t);return i===void 0||a===void 0||Number.isNaN(i)||Number.isNaN(a)?void 0:Wi(i,a)},Ki=(e,t,n)=>{let r=(e===`=`||e===`!=`)&&n.includes(`*`);if(typeof t==`string`)return r?Ui(e,+!Li(n,t)):Ui(e,Wi(t,n));if(typeof t==`number`||typeof t==`bigint`){let r=Gi(t,n);return r===void 0?void 0:Ui(e,r)}if(t instanceof Date){let r=Vi(n);return r===void 0?void 0:Ui(e,Wi(t.getTime(),r))}if(typeof t==`boolean`)return n===`true`||n===`false`?Ui(e,Wi(String(t),n)):void 0;if(Ri(t)){let r=Bi(n);return r===void 0?void 0:Ui(e,Wi(t.seconds,r))}},qi=(e,t,n)=>{if(t==null)return!1;if(typeof n==`string`)return Ki(e,t,n)??!1;if(n instanceof ji||typeof n==`number`||typeof n==`bigint`){let r=Gi(t,n);return r!==void 0&&Ui(e,r)}if(typeof n==`boolean`){let r=typeof t==`string`?t===`true`||t!==`false`&&void 0:t;return typeof r==`boolean`&&Ui(e,Wi(String(r),String(n)))}if(n instanceof Date){let r=Vi(t);return r===void 0||Number.isNaN(n.getTime())?!1:Ui(e,Wi(r,n.getTime()))}if(Ri(n)){let r=Bi(t);return r!==void 0&&Ui(e,Wi(r,n.seconds))}return!1},Ji=(e,t)=>{let n=[e];for(let e of t)n=n.flatMap(t=>Array.isArray(t)?t.flatMap(t=>Yi(t,e)):Yi(t,e));return n.filter(e=>e!=null)},Yi=(e,t)=>typeof e!=`object`||!e?[]:e instanceof Map?e.has(t)?[e.get(t)]:[]:Object.hasOwn(e,t)?[e[t]]:[],Xi=e=>e.flatMap(e=>Array.isArray(e)?e:[e]),Zi=32,Qi=(e,t)=>t>Zi||e==null?[]:typeof e==`string`?[e]:typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`?[String(e)]:e instanceof Date?[e.toISOString()]:Array.isArray(e)?e.flatMap(e=>Qi(e,t+1)):e instanceof Map?[...e.values()].flatMap(e=>Qi(e,t+1)):typeof e==`object`?Object.values(e).flatMap(e=>Qi(e,t+1)):[],$i=(e,t)=>{let n=e.toLowerCase();return Qi(t,0).some(e=>e.toLowerCase().includes(n))},ea=e=>[`member`,`string`,`number`,`boolean`,`duration`,`timestamp`,`call`,`binary`].includes(e.kind),ta=(e,t,n)=>{let r=e===`+`?1:-1;if(t instanceof Date&&Ri(n))return new Date(t.getTime()+r*n.seconds*1e3);if(t instanceof Date&&n instanceof Date&&e===`-`)return{seconds:(t.getTime()-n.getTime())/1e3};if(Ri(t)&&Ri(n))return{seconds:t.seconds+r*n.seconds};let i=t instanceof ji?t.toNumber():t,a=n instanceof ji?n.toNumber():n;return typeof i==`number`&&typeof a==`number`?i+r*a:void 0},na=(e,t)=>{let n=t.options.functions?.[e.name];if(!n?.evaluate)throw Error(`Function "${e.name}" has no evaluate implementation`);let r=e.args.map((e,r)=>{let i=n.params[r]??n.rest;return e.kind===`member`&&i?.type===`field`?Xi(Ji(t.record,e.path)):ea(e)?ra(e,t):la(e,t)});return n.evaluate(...r)},ra=(e,t)=>{switch(e.kind){case`member`:return e.path.join(`.`);case`call`:return na(e,t);case`binary`:return ta(e.op,ra(e.left,t),ra(e.right,t));default:return zi(e)}},ia=(e,t)=>e.kind===`member`?Ji(t.record,e.path):[ra(e,t)],aa=(e,t,n)=>Xi(t).some(t=>qi(e,t,n)),oa=(e,t)=>{let n=e.kind===`member`?e.field?.spec.type:void 0;return typeof t!=`string`||!n?t:n===`timestamp`?Vi(t)===void 0?t:new Date(Vi(t)):n===`duration`?Bi(t)===void 0?t:{seconds:Bi(t)}:n===`integer`||n===`number`?Ii(t)??t:n===`boolean`?t===`true`||t!==`false`&&t:t},sa=(e,t)=>{let n=oa(e.left,ra(e.right,t)),r=ia(e.left,t);return e.op===`!=`?!aa(`=`,r,n):aa(e.op,r,n)},ca=(e,t)=>{let n=ra(e.right,t),r=Hi(e.right);return ia(e.left,t).some(e=>Array.isArray(e)?e.some(e=>qi(`=`,e,n)):e instanceof Map?r!==void 0&&e.has(r):typeof e==`object`&&e&&!(e instanceof Date)&&!Ri(e)&&!(e instanceof ji)?r!==void 0&&Object.hasOwn(e,r):qi(`=`,e,n))},la=(e,t)=>{switch(e.kind){case`sequence`:case`and`:return e.args.every(e=>la(e,t));case`or`:return e.args.some(e=>la(e,t));case`not`:return!la(e.arg,t);case`compare`:return sa(e,t);case`has`:return ca(e,t);case`present`:return ia(e.left,t).some(e=>e!=null);case`global`:return(t.options.search??$i)(Hi(e.value)??String(ra(e.value,t)),t.record);case`call`:return na(e,t)===!0}},ua=(e,t,n={})=>la(e,{record:t,options:n}),da=(e,t,n,r)=>({code:e,message:t,hint:n,span:r}),fa=(e,t)=>{let n=Array.from({length:t.length+1},(e,t)=>t);for(let r=1;r<=e.length;r++){let i=[r];for(let a=1;a<=t.length;a++){let o=e[r-1]===t[a-1]?0:1;i[a]=Math.min(n[a]+1,i[a-1]+1,n[a-1]+o)}n=i}return n[t.length]},pa=(e,t)=>{let n=e.toLowerCase(),r=t.map(e=>({candidate:e,score:fa(n,e.toLowerCase())})).sort((e,t)=>e.score-t.score)[0];return r&&r.score<=Math.max(2,Math.floor(e.length/3))?r.candidate:void 0},ma={in:{params:[{name:`field`,type:`field`}],rest:{name:`value`,type:`any`}},search:{params:[{name:`text`,type:`string`}]},similar:{params:[{name:`field`,type:`field`,of:[`string`]},{name:`text`,type:`string`}]},regex:{params:[{name:`field`,type:`field`,of:[`string`]},{name:`pattern`,type:`string`}]},isNull:{params:[{name:`field`,type:`field`}]},now:{params:[],returns:`timestamp`}},ha={extensions:{arithmetic:`now-offset`,durationUnits:!0}},ga=e=>{switch(e.type){case`text`:return`string`;case`integer`:case`bigint`:return`integer`;case`boolean`:case`timestamp`:case`enum`:return e.type;default:return`any`}},_a=e=>({fields:Object.fromEntries(Object.values(e.fields).map(e=>[e.name,{type:ga(e),filterable:e.filterable,sortable:e.sortable,aliases:e.aliases,...e.enumValues&&{values:e.enumValues}}])),functions:ma}),va=(e,t,n,r)=>{e.errors.push(da(`unsupported`,t,n,r))},ya=(e,t)=>t.kind===`member`?{kind:`field`,path:t.path,span:t.span}:va(e,`Only fields can be compared`,`Put a field name on the left, for example total > 100`,t.span),Cee=(e,t)=>{switch(t.kind){case`member`:return{kind:`string`,value:t.path.join(`.`),span:t.span};case`call`:return t.name===`now`&&t.args.length===0?{kind:`now`,span:t.span}:va(e,`${t.name}() cannot be used as a value`,`Only now() is a value function`,t.span);case`binary`:{let n=t.left;return n.kind===`call`&&n.name===`now`&&n.args.length===0&&t.right.kind===`duration`?{kind:`now`,offset:{sign:t.op,duration:t.right},span:t.span}:va(e,`Arithmetic is only supported as now() +/- duration`,`Write now() - 30d`,t.span)}default:return t}},ba=(e,t)=>(`kind`in t&&[`member`,`call`,`binary`].includes(t.kind)?void 0:t)||(t.kind===`member`?{kind:`string`,value:t.path.join(`.`),span:t.span}:va(e,`Expected a literal value`,`Use strings, numbers, true/false, durations or timestamps`,t.span)),wee=e=>{switch(e.kind){case`member`:return e.path.join(`.`);case`string`:case`timestamp`:return e.kind,e.value;case`number`:return e.raw;case`boolean`:return String(e.value);case`duration`:return`${e.amount}${e.unit}`;default:return``}},Tee=(e,t)=>{let[n,r,...i]=t.args,a=n?.kind===`member`?ya(e,n):void 0,o=e=>e?.kind===`string`?e.value:void 0,s=n=>{e.errors.push(da(`invalid-arguments`,`Invalid arguments to ${t.name}()`,`Usage: ${n}`,t.span))};switch(t.name){case`in`:{let n=t.args.slice(1).map(t=>ba(e,t));return!a||n.length===0?s(`in(field, value1, value2, ...)`):n.every(e=>e)?{kind:`in`,field:a,values:n,span:t.span}:void 0}case`search`:return o(n)!==void 0&&!r?{kind:`search`,text:o(n),span:t.span}:s(`search("text")`);case`similar`:return a&&o(r)!==void 0&&i.length===0?{kind:`similar`,field:a,text:o(r),span:t.span}:s(`similar(field, "text")`);case`regex`:return a&&o(r)!==void 0&&i.length===0?{kind:`regex`,field:a,pattern:o(r),span:t.span}:s(`regex(field, "pattern")`);case`isNull`:return a&&!r?{kind:`isNull`,field:a,span:t.span}:s(`isNull(field)`);default:e.errors.push(da(`unknown-function`,`Unknown function "${t.name}"`,`Available functions: ${Object.keys(ma).join(`, `)}`,t.span));return}},Eee=e=>e.every(e=>e)?e:void 0,xa=(e,t)=>{switch(t.kind){case`sequence`:case`and`:case`or`:{let n=Eee(t.args.map(t=>xa(e,t)));return n&&{kind:t.kind===`or`?`or`:`and`,args:n,span:t.span}}case`not`:{let n=xa(e,t.arg);return n&&{kind:`not`,arg:n,span:t.span}}case`compare`:{let n=ya(e,t.left),r=Cee(e,t.right);return n&&r&&{kind:`compare`,op:t.op,field:n,value:r,span:t.span}}case`has`:{let n=ya(e,t.left),r=ba(e,t.right);return n&&r&&{kind:`has`,field:n,value:r,span:t.span}}case`present`:{let n=ya(e,t.left);return n&&{kind:`present`,field:n,span:t.span}}case`global`:return{kind:`search`,text:wee(t.value),span:t.span};case`call`:return Tee(e,t)}},Sa=(e,t={})=>{let n=Zr(e,{...ha,...t}),r={errors:[]},i=n.ast&&xa(r,n.ast),a=[...n.errors,...r.errors].sort((e,t)=>e.span.start-t.span.start);return a.length===0?{ok:!0,ast:i,errors:[]}:{ok:!1,ast:i,errors:a}},Dee=(e,t)=>t===2?e%4==0&&(e%100!=0||e%400==0)?29:28:[4,6,9,11].includes(t)?30:31,Ca=e=>{let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return!1;let[n,r,i]=[Number(t[1]),Number(t[2]),Number(t[3])];return r>=1&&r<=12&&i>=1&&i<=Dee(n,r)},Oee=e=>{let t=/^(\d{4}-\d{2}-\d{2})[Tt](\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:[Zz]|[+-](\d{2}):(\d{2}))$/.exec(e);if(!t)return!1;let[n,r,i]=[Number(t[2]),Number(t[3]),Number(t[4])],[a,o]=[Number(t[5]??0),Number(t[6]??0)];return Ca(t[1])&&n<=23&&r<=59&&i<=59&&a<=23&&o<=59},wa=(e,t)=>({message:e,hint:t}),kee=-(2n**63n),Aee=2n**63n-1n,jee=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ta=e=>e.kind===`number`?e.raw:e.kind===`string`?e.value:void 0,Ea=(e,t=`Write ${e} values like the examples in the docs`)=>wa(`Expected ${e}`,t),Mee=e=>{let t=Ta(e),n=t===void 0?NaN:Number(t);if(t===void 0||t.trim()===``||!Number.isSafeInteger(n))return Ea(`a whole number`,`Use an integer such as 42, or a bigint field for larger values`)},Nee=e=>{let t=Ta(e);if(t===void 0||!/^-?\d+$/.test(t)||BigInt(t)<kee||BigInt(t)>Aee)return Ea(`a 64-bit integer`,`Use plain digits such as 9007199254740993 (no exponent or fraction)`)},Pee=e=>{let t=Ta(e);if(t===void 0||!/^-?\d+(\.\d+)?$/.test(t))return Ea(`a decimal number`,`Use plain digits such as 100.50, or quote it: "100.50" (no exponent)`)},Fee=(e,t)=>{if(t.kind===`now`)return e.type===`date`||e.type===`timestamp`?void 0:wa(`now() only works with date and timestamp fields`,`Field "${e.name}" is ${e.type}`);switch(e.type){case`text`:return t.kind===`string`?void 0:Ea(`a quoted string`,`Wrap the text in double quotes`);case`integer`:return Mee(t);case`bigint`:return Nee(t);case`decimal`:return Pee(t);case`boolean`:return t.kind===`boolean`?void 0:Ea(`true or false`);case`date`:return t.kind===`string`&&Ca(t.value)?void 0:Ea(`a date`,`Quote a calendar date: "2012-04-21"`);case`timestamp`:return t.kind===`timestamp`||t.kind===`string`&&Oee(t.value)?void 0:Ea(`an RFC-3339 timestamp`,`Use 2012-04-21T11:30:00Z, or now() - 7d`);case`uuid`:return t.kind===`string`&&jee.test(t.value)?void 0:Ea(`a uuid`,`Quote a uuid like "0b5a4f0e-6f2a-4a3c-9d4e-1f2a3b4c5d6e"`);case`enum`:return t.kind===`string`&&e.enumValues?.includes(t.value)?void 0:wa(`Invalid enum value`,`Allowed values: ${(e.enumValues??[]).join(`, `)}`);case`currency`:return t.kind===`string`&&/^[A-Z]{3}$/.test(t.value)?void 0:Ea(`an ISO 4217 currency code`,`Use three capital letters, for example "EUR"`);case`country`:return t.kind===`string`&&/^[A-Z]{2}$/.test(t.value)?void 0:Ea(`an ISO 3166-1 country code`,`Use two capital letters, for example "NL"`);case`relation`:return t.kind===`string`||t.kind===`number`&&Number.isSafeInteger(t.value)?void 0:Ea(`a record key`,`Use the related record key: 42 or "abc"`);case`json`:case`file`:return wa(`${e.type} fields cannot be compared`,`Use field:value on json fields, or isNull(field)`)}},Iee=(e,t)=>Object.hasOwn(e.fields,t)?e.fields[t]:Object.values(e.fields).find(e=>e.aliases.includes(t)),Da=(e,t,n)=>{if(t.path.length>1){e.errors.push(da(`unsupported-traversal`,`Traversal into "${t.path.join(`.`)}" is not supported yet`,`Filter on fields of this resource only`,t.span));return}let r=t.path[0],i=Iee(e.model,r);if(!i){let i=Object.values(e.model.fields).filter(e=>e[n]).map(e=>e.name),a=pa(r,i);e.errors.push(da(`unknown-field`,`Unknown field "${r}"`,a?`Did you mean "${a}"?`:`Available fields: ${i.join(`, `)}`,t.span));return}if(!i[n]){let r=n===`filterable`?`filterable`:`sortable`;e.errors.push(da(n===`filterable`?`not-filterable`:`not-sortable`,`Field "${i.name}" is not ${r}`,`Mark it with .${r}() in data.ts`,t.span));return}return i},Lee=[`=`,`!=`],Ree=[`=`,`!=`,`<`,`<=`,`>`,`>=`],zee=e=>{switch(e){case`text`:case`integer`:case`bigint`:case`decimal`:case`date`:case`timestamp`:return Ree;case`json`:case`file`:return[];default:return Lee}},Bee=e=>e===`json`||e===`file`,Oa=(e,t,n)=>{let r=Fee(t,n);return r&&e.errors.push(da(`invalid-value`,r.message,r.hint,n.span)),!r},ka=(e,t,n,r)=>{e.errors.push(da(`operator-not-allowed`,t,n,r))},Aa=(e,t)=>(e===`=`||e===`!=`)&&t.kind===`string`&&t.value.includes(`*`),Vee=(e,t)=>{let n=Da(e,t.field,`filterable`);if(!n)return;let r=zee(n.type);if(!r.includes(t.op)){ka(e,`Operator "${t.op}" is not supported for ${n.type} fields`,r.length?`Supported: ${r.join(` `)}`:`Use field:value on json fields, or isNull(field)`,t.span);return}if(Aa(t.op,t.value)&&n.type!==`text`){e.errors.push(da(`wildcard-not-allowed`,`Wildcards are only supported on text fields, not ${n.type}`,`Remove the "*" or filter a text field`,t.value.span));return}if(Aa(t.op,t.value)||Oa(e,n,t.value))return{...t,field:n}},Hee=(e,t)=>{let n=Da(e,t.field,`filterable`);if(n){if(n.type!==`json`){ka(e,`":" is only supported on json fields, not ${n.type}`,`Use = on ${n.type} fields, or field:* to test for a value`,t.span);return}return{...t,field:n}}},Uee=(e,t)=>{let n=Da(e,t.field,`filterable`);if(n){if(Bee(n.type)){ka(e,`in() is not supported for ${n.type} fields`,`Use field:value on json fields`,t.span);return}return t.values.map(t=>Oa(e,n,t)).every(Boolean)?{...t,field:n}:void 0}},Wee=(e,t,n)=>{let r=Da(e,n,`filterable`);if(r&&r.type!==`text`){ka(e,`${t}() only works on text fields, not ${r.type}`,`Field "${r.name}" is ${r.type}`,n.span);return}return r},ja=(e,t)=>{switch(t.kind){case`and`:case`or`:{let n=t.args.map(t=>ja(e,t));return n.every(e=>e)?{...t,args:n}:void 0}case`not`:{let n=ja(e,t.arg);return n&&{...t,arg:n}}case`compare`:return Vee(e,t);case`has`:return Hee(e,t);case`in`:return Uee(e,t);case`search`:if(e.model.search?.length)return t;e.errors.push(da(`no-search-fields`,`This resource has no search fields`,`Declare them with .search((r) => [r.title]) in data.ts`,t.span));return;case`present`:case`isNull`:{let n=Da(e,t.field,`filterable`);return n&&{...t,field:n}}case`similar`:case`regex`:{let n=Wee(e,t.kind,t.field);return n&&{...t,field:n}}}},Ma=(e,t)=>{let n={model:e,errors:[]},r=ja(n,t);return!r||n.errors.length>0?{ok:!1,errors:[...n.errors].sort((e,t)=>e.span.start-t.span.start)}:{ok:!0,filter:r}},Na=(e,t)=>`path`in e?{kind:`member`,path:e.path,span:e.span}:{kind:`member`,path:[e.name],field:{name:e.name,spec:{type:ga(e)}},span:t},Pa=(e,t,n)=>({kind:`call`,name:e,args:t,span:n}),Fa=(e,t)=>({kind:`string`,value:e,span:t}),Gee=e=>{if(e.kind!==`now`)return e;let t={kind:`call`,name:`now`,args:[],span:e.span};return e.offset?{kind:`binary`,op:e.offset.sign,left:t,right:e.offset.duration,span:e.span}:t},Ia=(e,t={})=>{let n=e=>Ia(e,t);switch(e.kind){case`and`:case`or`:return{kind:e.kind,args:e.args.map(n),span:e.span};case`not`:return{kind:`not`,arg:n(e.arg),span:e.span};case`compare`:return{kind:`compare`,op:e.op,left:Na(e.field,e.span),right:Gee(e.value),span:e.span};case`has`:return{kind:`has`,left:Na(e.field,e.span),right:e.value,span:e.span};case`present`:return{kind:`present`,left:Na(e.field,e.span),span:e.span};case`in`:return t.expand?{kind:`or`,args:e.values.map(t=>({kind:`compare`,op:`=`,left:Na(e.field,e.span),right:t,span:e.span})),span:e.span}:Pa(`in`,[Na(e.field,e.span),...e.values],e.span);case`search`:return Pa(`search`,[Fa(e.text,e.span)],e.span);case`similar`:return Pa(`similar`,[Na(e.field,e.span),Fa(e.text,e.span)],e.span);case`regex`:return Pa(`regex`,[Na(e.field,e.span),Fa(e.pattern,e.span)],e.span);case`isNull`:return t.expand?{kind:`not`,arg:{kind:`present`,left:Na(e.field,e.span),span:e.span},span:e.span}:Pa(`isNull`,[Na(e.field,e.span)],e.span)}},La=(e,t)=>{let n=Ma(e,t);if(!n.ok&&n.errors.some(e=>e.code===`unsupported-traversal`))return n;let r=yi(Ia(t),_a(e));return r.ok?Ma(e,t):{ok:!1,errors:r.errors}},Kee=/^[\d\s+\-().\/]+$/,Ra=e=>Kee.test(e)?e.replace(/\D/g,``):``,za=e=>{let t=e.split(/\s+/).filter(Boolean).map(e=>({text:e,digits:Ra(e),whole:!1})),n=t.length>1?Ra(e.trim()):``;return n?[{text:e.trim(),digits:n,whole:!0},...t]:t},Ba=(e,t,n)=>e==null?!1:n===`digitsEnd`?t.digits!==``&&String(e).replace(/\D/g,``).endsWith(t.digits):!t.whole&&String(e).toLowerCase().includes(t.text.toLowerCase()),Va=(e,t,n)=>(e.search??[]).filter(r=>Ba(t[r],n,e.searchMatch?.[r])),Ha=(e,t,n)=>{let r=za(n),i=r.filter(e=>!e.whole),a=r.find(e=>e.whole);return a&&Va(e,t,a).length>0?!0:i.length>0&&i.every(n=>Va(e,t,n).length>0)},Ua=(e,t,n,r)=>{for(let i of za(n)){let n=Va(e,t,i);if(n.length>0&&!n.some(e=>r.includes(e)))return n[0]}},Wa=e=>()=>{throw Error(`Not implemented: ${e}() needs the database (the resource's search fields, trigram matching), so it cannot be evaluated against a record`)},Ga=(e,t,n)=>({...ma,search:{...ma.search,evaluate:n?e=>Ha(n,t,e):Wa(`search`)},similar:{...ma.similar,evaluate:Wa(`similar`)},regex:{...ma.regex,evaluate:(e,t)=>e.some(e=>typeof e==`string`&&new RegExp(t).test(e))},now:{...ma.now,evaluate:e}}),Ka=(e,t,n={})=>ua(Ia(e,{expand:!0}),t,{functions:Ga(n.now??(()=>new Date),t,n.search)}),qa=e=>Ai(Ia(e)),Ja=e=>{let t=[];for(let n of e.matchAll(/,|\.|[^\s,.]+/g)){let e=n.index,r=n[0]===`,`?`comma`:n[0]===`.`?`dot`:`word`;t.push({kind:r,text:n[0],span:{start:e,end:e+n[0].length}})}return t},Ya=e=>{let t=Ja(e),n=[],r=[],i={start:e.length,end:e.length},a=0,o=(e,t,r,i)=>n.push(or(e,t,r,i)),s=()=>{for(;a<t.length&&t[a].kind!==`comma`;)a++;a++},c=()=>{let e=t[a];if(!e||e.kind!==`word`)return o(`expected-field`,`Expected a field name but found ${e?`"${e.text}"`:`end of input`}`,`Write order_by like: createdAt desc, total`,e?.span??i),!1;let n=[e.text],s=e;for(a++;t[a]?.kind===`dot`;){let e=t[a+1];if(e?.kind!==`word`)return o(`expected-field`,`Expected a field name after "."`,`Write subfields like address.street`,e?.span??i),!1;n.push(e.text),s=e,a+=2}let c=t[a],l=`asc`;if(c?.kind===`word`){if(c.text!==`asc`&&c.text!==`desc`)return o(`unexpected-token`,`Expected "desc" or "," but found "${c.text}"`,`Separate fields with commas; append " desc" for descending order`,c.span),!1;l=c.text,s=c,a++}let u=t[a];return u&&u.kind!==`comma`?(o(`unexpected-token`,`Expected "," but found "${u.text}"`,`Separate fields with commas`,u.span),!1):(r.push({path:n,direction:l,span:{start:e.span.start,end:s.span.end}}),!0)};for(;a<t.length;){if(!c()){s();continue}t[a]?.kind===`comma`&&(a++,a>=t.length&&o(`expected-field`,`Expected a field name after ","`,`Remove the trailing comma`,i))}return n.length===0?{ok:!0,items:r,errors:[]}:{ok:!1,items:r,errors:n}},Xa=(e,t)=>{if(Object.hasOwn(e,t))return{name:t,field:e[t]};let n=Object.entries(e).find(([,e])=>e.aliases?.includes(t));return n&&{name:n[0],field:n[1]}},Za=(e,t)=>{let n=[],r=[];for(let i of e){let e=Xa(t.fields,i.path[0]);if(!e){let e=Object.entries(t.fields).filter(([,e])=>e.sortable!==!1).map(([e])=>e),r=cr(i.path[0],e);n.push(or(`unknown-field`,`Unknown field "${i.path[0]}"`,r?`Did you mean "${r}"?`:`Available fields: ${e.join(`, `)}`,i.span));continue}let a=[e.name],o=e.field,s=o.sortable!==!1,c=!1;for(let e of i.path.slice(1)){let t=o.fields?Xa(o.fields,e)?.field:o.value;if(!t){n.push(or(`invalid-traversal`,`Cannot sort by "${e}" inside "${a.join(`.`)}"`,`Only nested message fields and map values can be traversed`,i.span)),c=!0;break}a.push(o.fields?Xa(o.fields,e).name:e),o=t,s&&=o.sortable!==!1}if(!c){if(!s){n.push(or(`not-sortable`,`Field "${a.join(`.`)}" cannot be sorted on`,`Mark it sortable in the schema`,i.span));continue}r.push({...i,path:a})}}return n.length===0?{ok:!0,items:r}:{ok:!1,errors:n}},Qa=e=>e.map(e=>({path:e.path.path,direction:e.direction,span:e.span})),$a=e=>e.replace(/([^\s,])(\s+)(asc|desc)(?=\s|,|$)/gi,(e,t,n,r)=>`${t}${n}${r.toLowerCase()}`),eo=e=>{let t=Ya($a(e)),n=t.items.map(e=>({path:{kind:`field`,path:e.path,span:e.span},direction:e.direction,span:e.span}));return t.ok?{ok:!0,items:n,errors:[]}:{ok:!1,items:n,errors:t.errors}},to=(e,t)=>{let n=t.filter(e=>e.path.path.length>1).map(e=>da(`unsupported-traversal`,`Traversal into "${e.path.path.join(`.`)}" is not supported yet`,`Sort on fields of this resource only`,e.path.span));if(n.length>0)return{ok:!1,errors:n};let r=Za(Qa(t),_a(e));return r.ok?{ok:!0,sort:r.items.map(e=>[e.path[0],e.direction])}:{ok:!1,errors:r.errors}},no=e=>{let t=/^(\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)([smhdw])$/.exec(e);if(!t)throw Error(`Invalid duration "${e}", expected for example 30d or 1.5h`);return{kind:`duration`,amount:Number(t[1]),unit:t[2],span:{start:0,end:0}}},ro={start:0,end:0},io=e=>({kind:`field`,path:e.split(`.`),span:ro}),ao=e=>{if(typeof e==`string`)return{kind:`string`,value:e,span:ro};if(typeof e==`boolean`)return{kind:`boolean`,value:e,span:ro};if(!Number.isFinite(e))throw Error(`Filter numbers must be finite`);return{kind:`number`,value:e,raw:String(e),span:ro}},oo=e=>typeof e==`object`?e:ao(e),so=(e,t)=>{if(t.length===0)throw Error(`where.${e} needs at least one filter`);return t.length===1?t[0]:{kind:e,args:t,span:ro}},co=()=>{let e=e=>(t,n)=>({kind:`compare`,op:e,field:io(t),value:oo(n),span:ro}),t=e=>t=>({kind:`now`,offset:{sign:e,duration:no(t)},span:ro});return{eq:e(`=`),ne:e(`!=`),lt:e(`<`),lte:e(`<=`),gt:e(`>`),gte:e(`>=`),between:(t,n,r)=>so(`and`,[e(`>=`)(t,n),e(`<=`)(t,r)]),has:(e,t)=>({kind:`has`,field:io(e),value:ao(t),span:ro}),present:e=>({kind:`present`,field:io(e),span:ro}),in:(e,t)=>({kind:`in`,field:io(e),values:t.map(ao),span:ro}),isNull:e=>({kind:`isNull`,field:io(e),span:ro}),search:e=>({kind:`search`,text:e,span:ro}),similar:(e,t)=>({kind:`similar`,field:io(e),text:t,span:ro}),regex:(e,t)=>({kind:`regex`,field:io(e),pattern:t,span:ro}),and:(...e)=>so(`and`,e),or:(...e)=>so(`or`,e),not:e=>({kind:`not`,arg:e,span:ro}),now:()=>({kind:`now`,span:ro}),ago:t(`-`),fromNow:t(`+`)}},lo=co(),uo=/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,fo=e=>[...e.matchAll(uo)].map(e=>e[1]),po=e=>e.kind===`record`?(Array.isArray(e.key)?e.key:[e.key]).filter(e=>typeof e==`string`):e.kind===`list`?[e.filter,e.orderBy].filter(e=>e!==void 0):e.kind===`create`?Object.values(e.values??{}):[],mo=e=>[...new Set(po(e).flatMap(fo))],ho=(e,t)=>e.replace(uo,(e,n)=>t[n]===null||t[n]===void 0?``:String(t[n])),go=(e,t={})=>{if(e.kind===`record`){let n=e=>typeof e==`string`?ho(e,t):e;return{...e,key:Array.isArray(e.key)?e.key.map(n):n(e.key)}}return e.kind===`create`?e.values?{...e,values:Object.fromEntries(Object.entries(e.values).map(([e,n])=>[e,ho(n,t)]))}:e:e.kind===`list`?{...e,...e.filter!==void 0&&{filter:ho(e.filter,t)},...e.orderBy!==void 0&&{orderBy:ho(e.orderBy,t)}}:e},_o=e=>/^\{([A-Za-z_][A-Za-z0-9_]*)\}$/.exec(e)?.[1],vo=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.keys(e).length===1&&typeof e.$field==`string`,yo=e=>typeof e==`object`&&!!e&&!Array.isArray(e),bo=e=>vo(e)?e.$field:Array.isArray(e)?e.map(bo):yo(e)?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,bo(t)])):e,xo=`table`,So={text:`text`,integer:`integer`,decimal:`decimal`,boolean:`boolean`,date:`date`,choice:`text`,custom:`json`},Co=e=>({name:e.name,column:e.name,type:e.options?`enum`:So[e.kind],nullable:!0,readOnly:!1,filterable:e.kind!==`custom`,sortable:!1,aliases:[],...e.options&&{enumValues:e.options.map(e=>e.value)}}),wo=e=>({name:`inputs`,table:{name:`inputs`},fields:Object.fromEntries(e.map(e=>[e.name,Co(e)])),primaryKey:[]}),To=(e,t)=>{let n=e[t].when;if(n===void 0)return;let r=Sa(n);if(!r.ok)return r.errors.map(e=>e.message).join(`; `);if(!r.ast)return`it is empty`;let i=La(wo(e.slice(0,t)),r.ast);return i.ok?i.filter:i.errors.map(e=>e.message).join(`; `)},Eo=(e,t)=>{let n=new Set,r={};return e.forEach((i,a)=>{let o=To(e,a);if(typeof o==`string`)throw Error(`Input "${i.name}": ${o}`);let s=o===void 0||Ka(o,r)===!0;s&&n.add(i.name),r[i.name]=s?t[i.name]??null:null}),n},Do=e=>`groupBy`in e,Oo=/^[a-z0-9][a-z0-9_-]*$/,ko=e=>{if(!e.startsWith(`/-/forms/`))return;let t=e.slice(9);return Oo.test(t)?{name:t}:void 0},Ao=e=>{if(!Array.isArray(e))return String(e);let t=e;return t.length===1?String(t[0]):t.map(e=>encodeURIComponent(String(e))).join(`,`)},jo=/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/,Mo=e=>{let t=jo.exec(e);return t?[Number(t[1]),Number(t[2]),Number(t[3])]:void 0},No=(e,t)=>e[0]-t[0]||e[1]-t[1]||e[2]-t[2],Po=/^(>=|<=|>|<|=)?(.+)$/,Fo={">=":e=>e>=0,"<=":e=>e<=0,">":e=>e>0,"<":e=>e<0,"=":e=>e===0},Io=(e,t)=>{let n=Mo(e),r=t.trim().split(/\s+/);if(!n||t.trim()===``)return;let i=!0;for(let e of r){let[,t=`=`,r=``]=Po.exec(e)??[],a=Mo(r);if(!a)return;i&&=Fo[t](No(n,a))}return i},Lo=(e,t)=>{if(e.api!==t.api)return`it is built for plugin API ${e.api}, and this app has plugin API ${t.api}`;let n=Io(t.version,e.protobase);if(n===void 0)return`its Protobase range "${e.protobase}" is not one this app reads, such as >=0.12.0`;if(!n)return`it needs Protobase ${e.protobase}, and this app runs ${t.version}`},Ro=`[Filtered]`,zo=/authorization|cookie|passw|secret|token|api[-_]?key|credential|session|csrf|signature|^sig$/i,Bo=new Set([`url`,`query_string`,`from`,`to`]),Vo=12,Ho=e=>e.replace(/(^|&)([^=&]*)=([^&]*)/g,(e,t,n)=>zo.test(n)?`${t}${n}=${Ro}`:e),Uo=e=>{let t=e.indexOf(`?`);if(t===-1)return e;let n=e.indexOf(`#`,t),r=n===-1?e.slice(t+1):e.slice(t+1,n);return`${e.slice(0,t+1)}${Ho(r)}${n===-1?``:e.slice(n)}`},Wo=(e,t,n)=>zo.test(e)?Ro:typeof t==`string`&&Bo.has(e)?e===`query_string`?Ho(t):Uo(t):Go(t,n+1),Go=(e,t)=>t>Vo||typeof e!=`object`||!e?e:Array.isArray(e)?e.map(e=>Array.isArray(e)&&e.length===2&&typeof e[0]==`string`?[e[0],Wo(e[0],e[1],t)]:Go(e,t+1)):Object.fromEntries(Object.entries(e).map(([e,n])=>[e,Wo(e,n,t)])),Ko=e=>Go(e,0),qo=[`unknown-field`,`not-filterable`,`not-sortable`,`unsupported-traversal`,`invalid-traversal`],Jo=e=>e.replace(/(["']?)\{[A-Za-z_][A-Za-z0-9_]*\}\1/g,(e,t)=>t?`${t}x${t}`:`0`),Yo=(e,t)=>{let n=Sa(Jo(t));if(!n.ok)return n.errors.map(e=>`filter: ${e.message}`);if(!n.ast)return[];let r=La(e,n.ast);return r.ok?[]:r.errors.filter(e=>qo.includes(e.code)).map(e=>`filter: ${e.message}`)},Xo=(e,t)=>{if(mo({kind:`list`,resource:e.name,orderBy:t}).length>0)return[];let n=eo(t);if(!n.ok)return n.errors.map(e=>`orderBy: ${e.message}`);let r=to(e,n.items);return r.ok?[]:r.errors.map(e=>`orderBy: ${e.message}`)},Zo=(e,{models:t,pages:n,source:r})=>{let i=mo(e).flatMap(e=>r?Object.hasOwn(r.fields,e)?[]:[`"{${e}}" is not a field of ${r.name}`]:[`"{${e}}" takes a value from the record, but the link sits on none`]);switch(e.kind){case`page`:return n&&!n.has(e.page)?[`unknown page "${e.page}"`]:[];case`list`:case`record`:case`create`:{let n=Object.hasOwn(t,e.resource)?t[e.resource]:void 0;return n?e.kind===`create`?[...i,...Object.keys(e.values??{}).filter(e=>!Object.hasOwn(n.fields,e)).map(t=>`values: unknown field "${t}" on ${e.resource}`)]:e.kind===`list`?[...i,...e.filter?Yo(n,e.filter):[],...e.orderBy?Xo(n,e.orderBy):[]]:i:[`unknown resource "${e.resource}"`]}default:return[`an address's kind is list, record, create or page, not "${String(e.kind)}"`]}},Qo={messages:[],replying:!1},$o=(e,t)=>{let n=e.findIndex(e=>e.id===t.id);return n===-1?[...e,t]:e.map((e,r)=>r===n?t:e)},es=(e,t,n)=>{let r=e.find(e=>e.id===t);return $o(e,r?{...r,parts:$o(r.parts,n)}:{id:t,from:`assistant`,parts:[n]})},ts=(e,t)=>{switch(t.type){case`state`:return t.state;case`message`:return{...e,messages:$o(e.messages,t.message)};case`part`:return{...e,messages:es(e.messages,t.messageId,t.part)};case`patch`:{let{replying:n=e.replying,status:r=e.status,placeholder:i=e.placeholder}=t;return{messages:e.messages,replying:n,...r!=null&&{status:r},...i!=null&&{placeholder:i}}}}},ns=async(e,t,n)=>{let r=new TextDecoder,i=e.getReader();n?.addEventListener(`abort`,()=>void i.cancel(),{once:!0});let a=``,o=[],s=e=>{if(e===``){o.length>0&&t(o.join(`
|
|
4
4
|
`)),o=[];return}e.startsWith(`data:`)&&o.push(e.slice(e.startsWith(`data: `)?6:5))};for(;;){let{done:e,value:t}=await i.read();a+=e?r.decode():r.decode(t,{stream:!0});let n=a.split(/\r\n|\r|\n/);if(a=e?``:n.pop()??``,n.forEach(s),e)return s(``)}},rs=(e,t)=>t?.[e]??e,is={filter:`filter`,orderBy:`order_by`,display:`display`,filterLayout:`layout`,map:`map`,calendar:`calendar`,savedSearch:`saved_search`,create:`new`,edit:`edit`},as=[`display`,`filter`,`orderBy`,`filterLayout`,`savedSearch`],os=e=>`${e.latitude.toFixed(5)},${e.longitude.toFixed(5)},${e.zoom.toFixed(2)}`,ss=(e,t,n=-t)=>Number.isFinite(e)&&e>=n&&e<=t,cs=e=>{let t=e?.split(`,`);if(t?.length!==3||t.some(e=>e.trim()===``))return;let[n,r,i]=t.map(Number);return ss(n,90)&&ss(r,180)&&ss(i,22,0)?{latitude:n,longitude:r,zoom:i}:void 0},ls=e=>`${e.scale},${e.day}`,us=e=>{let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return!1;let[n,r,i]=t.slice(1).map(Number),a=new Date(Date.UTC(n,r-1,i));return a.getUTCFullYear()===n&&a.getUTCMonth()===r-1&&a.getUTCDate()===i},ds=e=>{let t=e?.split(`,`);if(t?.length!==2)return;let[n,r]=t;return(n===`month`||n===`week`)&&us(r)?{scale:n,day:r}:void 0},fs=e=>{let t=new URLSearchParams;for(let n of as){let r=e[n];r!==void 0&&r!==``&&t.set(is[n],r)}e.map&&t.set(is.map,os(e.map)),e.calendar&&t.set(is.calendar,ls(e.calendar));let n=t.toString();return n?`?${n}`:``},ps=(e,t=``)=>{switch(e.kind){case`page`:return`${t}/${encodeURIComponent(e.page)}`;case`create`:return`${t}/${encodeURIComponent(e.resource)}/${is.create}${hs(e.values)}`;case`record`:return`${t}/${encodeURIComponent(e.resource)}/${encodeURIComponent(Ao(e.key))}${e.edit?`?${is.edit}=true`:``}`;case`list`:return`${t}/${encodeURIComponent(e.resource)}${fs(e)}`}},ms=e=>{try{return e.split(`/`).filter(Boolean).map(decodeURIComponent)}catch(e){if(e instanceof URIError)return;throw e}},hs=(e={})=>{let t=new URLSearchParams(Object.entries(e).filter(([,e])=>e!==``)).toString();return t?`?${t}`:``},gs=e=>e===`bar`||e===`panel`?e:void 0,_s=(e,t)=>{let n=new URL(e,`http://app`),r=ms(n.pathname);if(!r||r.length===0||r.length>2)return;let[i,a]=r;if(i===`-`)return;if(t.has(i))return a===void 0?{kind:`page`,page:i}:void 0;if(a===is.create){let e=Object.fromEntries([...n.searchParams].filter(([,e])=>e!==``));return{kind:`create`,resource:i,...Object.keys(e).length>0&&{values:e}}}if(a!==void 0)return{kind:`record`,resource:i,key:a,...n.searchParams.get(is.edit)===`true`&&{edit:!0}};let o=n.searchParams,s=o.get(is.display)||void 0,c=o.get(is.filter)||void 0,l=o.get(is.orderBy)||void 0,u=gs(o.get(is.filterLayout)),d=cs(o.get(is.map)),f=ds(o.get(is.calendar)),p=o.get(is.savedSearch)||void 0;return{kind:`list`,resource:i,...s&&{display:s},...c&&{filter:c},...l&&{orderBy:l},...u&&{filterLayout:u},...d&&{map:d},...f&&{calendar:f},...p&&{savedSearch:p}}},vs=`/-/sign-in`,ys={step:`step`,next:`next`},bs=[`sign-in`,`forgot-password`,`email-code`,`sign-up`,`sign-up-code`,`sign-up-details`],xs=e=>bs.includes(e),Ss=e=>{if(!e?.startsWith(`/`))return;let t=new URL(e,`http://local`);if(t.origin===`http://local`&&t.pathname!==`/-/sign-in`)return`${t.pathname}${t.search}`},Cs=({step:e=`sign-in`,next:t}={})=>{let n=new URLSearchParams;e!==`sign-in`&&n.set(ys.step,e);let r=Ss(t);r&&r!==`/`&&n.set(ys.next,r);let i=n.toString();return i?`${vs}?${i}`:vs},ws=(e,t)=>{if(e!==`/-/sign-in`)return;let n=t.get(ys.step),r=Ss(t.get(ys.next));return{step:xs(n)?n:`sign-in`,...r&&{next:r}}},Ts=e=>typeof e==`string`?e:e&&qa(e),Es=e=>{let t=Object.entries(e??{}).map(([e,t])=>`${e}.${t}`);return t.length>0?t:void 0},Ds=e=>({photos:e&&`${e.resource}.${e.field}.${e.image}`,photos_order_by:e?.sort}),Os=(e={})=>({filter:Ts(e.filter)||void 0,order_by:e.orderBy,page_size:e.pageSize,page_token:e.pageToken||void 0,fields:e.fields?.join(`,`),labels:Es(e.labels)?.join(`,`),...Ds(e.photos),count:e.count}),ks=e=>{let t=new URLSearchParams;for(let[n,r]of Object.entries(e))r!==void 0&&t.set(n,String(r));let n=t.toString();return n?`?${n}`:``},As=e=>e.startsWith(`/`)&&!e.startsWith(`//`),js=e=>{if(typeof e!=`object`||!e)return!1;let{uri:t,url:n}=e;return typeof t==`string`&&typeof n==`string`&&As(n)},Ms=e=>e!==void 0&&URL.canParse(e)?new URL(e).origin:void 0,Ns=(e,t)=>({...e,url:`${t}${e.url}`,...e.variants&&{variants:Object.fromEntries(Object.entries(e.variants).map(([e,n])=>[e,As(n.url)?{...n,url:`${t}${n.url}`}:n]))}}),Ps=(e,t)=>t===void 0||typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,js(n)?Ns(n,t):n])),Fs=(e,t)=>t===void 0?e:Object.fromEntries(Object.entries(e).map(([e,n])=>[e,n.map(e=>js(e)?Ns(e,t):e)])),Is=class extends Error{problem;constructor(e){super(e.detail??e.title),this.problem=e,this.name=`ApiError`}get status(){return this.problem.status}get slug(){return this.problem.type.split(`:`).at(-1)??``}get operation(){return this.problem.operation??this.errors.find(e=>e.operation!==void 0)?.operation}get blockedBy(){return this.problem.blockedBy}get errors(){return this.problem.errors??[]}get filterErrors(){return this.slug===`invalid-filter`?this.errors:[]}},Ls=class extends Is{constructor(e){super(e),this.name=`PreconditionFailedError`}},Rs=e=>e instanceof Is,zs=e=>typeof e==`object`&&!!e&&`type`in e&&`status`in e,Bs=async e=>{let t=e.headers.get(`content-type`)?.includes(`json`)??!1?await e.json():void 0,n=zs(t)?t:{type:`urn:protobase:problem:unknown`,title:e.statusText||`Request failed`,status:e.status};return n.status===412?new Ls(n):new Is(n)},Vs=(e={})=>{let t=e.baseUrl??`/api/v1`,n=t.replace(/\/[^/]*$/,``),r=e.fetch??((e,t)=>fetch(e,t));return async({method:i,path:a,query:o=``,body:s,headers:c,accept:l=[],system:u,raw:d,via:f,signal:p})=>{let m=async l=>{let m=await e.token?.({refresh:l});return(f??r)(`${u?n:t}${a}${o}`,{method:i,headers:{...s!==void 0&&{"content-type":`application/json`},...m&&{authorization:`Bearer ${m}`},...e.headers?.(),...c},body:d??(s===void 0?void 0:JSON.stringify(s)),...p&&{signal:p}})},h=await m(!1);h.status===401&&e.token&&(h=await m(!0),h.status===401&&e.onUnauthenticated?.());let g=h.headers.get(`x-meta-version`);if(g&&e.onMetaVersion?.(g),!h.ok&&!l.includes(h.status))throw await Bs(h);return h}},Hs=e=>new Headers(e.trim().split(/[\r\n]+/).filter(Boolean).map(e=>{let t=e.indexOf(`:`);return[e.slice(0,t).trim(),e.slice(t+1).trim()]})),Us=e=>(t,n={})=>new Promise((r,i)=>{let a=new XMLHttpRequest;a.open(n.method??`GET`,String(t)),new Headers(n.headers).forEach((e,t)=>a.setRequestHeader(t,e)),a.responseType=`blob`,a.upload.onprogress=t=>e(t.loaded,t.lengthComputable?t.total:t.loaded),a.onload=()=>{let e=a.status===204||a.status===304;r(new Response(e?null:a.response,{status:a.status,statusText:a.statusText,headers:Hs(a.getAllResponseHeaders())}))},a.onerror=()=>i(TypeError(`Network request failed`)),a.onabort=()=>i(new DOMException(`The upload was aborted`,`AbortError`)),n.signal?.addEventListener(`abort`,()=>a.abort()),a.send(n.body)}),Ws=e=>typeof e==`string`?e:e.toModel().name,Gs=(e,t)=>`/${Ws(e)}/${Ao(t)}`,Ks=(e,t,n)=>({items:e.items.map(e=>Ps(e,n)),nextPageToken:e.next_page_token,totalSizeEstimate:e.total_size_estimate,...e.prev_page_token!==void 0&&{prevPageToken:e.prev_page_token},...e.total_size!==void 0&&{totalSize:e.total_size},...e.labels!==void 0&&{labels:e.labels},...e.photos!==void 0&&{photos:Fs(e.photos,n)},...t.headers.get(`x-protobase-warning`)&&{warning:t.headers.get(`x-protobase-warning`)}}),qs=({created_at:e,...t})=>({...t,createdAt:e}),Js=e=>e.headers.get(`etag`)??``,Ys=async(e,t)=>{let{permissions:n,...r}=await e.json();return{record:Ps(r,t),etag:Js(e),...n&&{permissions:n}}},Xs=(e,t)=>({results:(e.results??[]).map(e=>e.op===`create`||e.op===`update`?{...e,record:Ps(e.record,t)}:e.op===`reorder`?{...e,records:e.records.map(e=>({...e,record:Ps(e.record,t)}))}:e)}),Zs=(e={})=>{let t=Vs(e),n=Ms(e.baseUrl),r=async(e,r)=>{let i=await t({method:`GET`,path:`/${Ws(e)}`,query:ks(Os(r))});return Ks(await i.json(),i,n)},i=async(e,r)=>{let i=Os(r),a=await t({method:`POST`,path:`/${Ws(e)}:search`,body:{...i,fields:r?.fields,labels:Es(r?.labels)}});return Ks(await a.json(),a,n)},a=async(e,r)=>Ys(await t({method:`GET`,path:Gs(e,r)}),n),o=async(e,r)=>{let i=await t({method:`POST`,path:`/${Ws(e)}`,body:r});return{record:Ps(await i.json(),n),etag:Js(i),location:i.headers.get(`location`)??``}},s=async(e,r,i,a)=>Ys(await t({method:`PATCH`,path:Gs(e,r),body:i,headers:{"if-match":a}}),n),c=async(e,n,{etag:r}={})=>{await t({method:`DELETE`,path:Gs(e,n),headers:r?{"if-match":r}:void 0})},l=async(e,r)=>{let i=await t({method:`POST`,path:`${Gs(e,r)}:undelete`});return{record:Ps(await i.json(),n),etag:Js(i)}},u=async(e,n,r)=>(await(await t({method:`POST`,path:`${Gs(e,n)}:reveal`,body:{field:r}})).json()).value,d=async(e,r,i)=>Ys(await t({method:`POST`,path:`${Gs(e,r)}:generate`,body:{action:i}}),n),f=async(e,n,{pageSize:r,pageToken:i}={})=>{let a=ks({page_size:r,page_token:i||void 0}),o=await(await t({method:`GET`,path:`${Gs(e,n)}:history`,query:a})).json();return{items:o.items.map(({database_role:e,...t})=>({...t,databaseRole:e})),nextPageToken:o.next_page_token}},p=async(e,n,{pageSize:r,pageToken:i}={})=>{let a=ks({page_size:r,page_token:i||void 0}),o=await(await t({method:`GET`,path:`${Gs(e,n)}:comments`,query:a})).json();return{items:o.items.map(qs),nextPageToken:o.next_page_token}},m=async(e,n,{body:r,mentions:i=[]})=>qs(await(await t({method:`POST`,path:`${Gs(e,n)}:comments`,body:{body:r,mentions:i}})).json()),h=async(e,n,r)=>(await(await t({method:`GET`,path:`${Gs(e,n)}:mentionable`,query:ks({q:r})})).json()).items,g=async e=>{let r=e=>typeof e==`object`&&e&&`$ref`in e?e:Ao(e),i=e.map(e=>({...e,resource:Ws(e.resource),...`key`in e&&{key:r(e.key)},...e.op===`reorder`&&{keys:e.keys.map(r)}}));return Xs(await(await t({method:`POST`,path:`:batchWrite`,body:{ops:i}})).json(),n)},_=async(e,n,r={})=>(await(await t({method:`GET`,path:`/${Ws(e)}:facets`,query:ks({field:n,filter:Ts(r.filter)||void 0,limit:r.limit,label:r.label})})).json()).facets,v=async(e,n)=>{let r=await(await t({method:`GET`,path:`/${Ws(e)}:aggregate`,query:ks({group_by:n.groupBy,filter:Ts(n.filter)||void 0,sum:n.sum,average:n.average,limit:n.limit,label:n.label,granularity:n.granularity,range:n.range,from:n.from,to:n.to,time_zone:n.timeZone})})).json();return{groupBy:r.group_by,granularity:r.granularity,timeZone:r.time_zone,groups:r.groups}},y=async(e,n)=>{let r=await(await t({method:`GET`,path:`/${Ws(e)}:series`,query:ks({field:n.field,range:n.range,from:n.from,to:n.to,granularity:n.granularity,time_zone:n.timeZone,filter:Ts(n.filter)||void 0})})).json();return{field:r.field,granularity:r.granularity,timeZone:r.time_zone,points:r.points}},b=async(e,n,r={})=>(await t({method:`GET`,path:`/${Ws(e)}:histogram`,query:ks({field:n,buckets:r.buckets,filter:Ts(r.filter)||void 0})})).json(),x=async(e,r)=>{let i=await(await t({method:`GET`,path:`/${Ws(e)}:map`,query:ks({latitude:r.latitude,longitude:r.longitude,zoom:r.zoom,filter:Ts(r.filter)||void 0,order_by:r.orderBy,fields:r.fields?.join(`,`),labels:Es(r.labels)?.join(`,`),...Ds(r.photos)})})).json();return{items:i.items.map(e=>Ps(e,n)),buckets:i.buckets,totalSize:i.total_size,...i.labels!==void 0&&{labels:i.labels},...i.photos!==void 0&&{photos:Fs(i.photos,n)}}},S=async(e,r)=>{let i=await t({method:`GET`,path:`/${Ws(e)}:seek`,query:ks({...Os(r),position:r.position})});return Ks(await i.json(),i,n)},C=async(e,{signal:n}={})=>{let r=await t({method:`GET`,path:`/meta`,system:!0,headers:e?{"if-none-match":e}:void 0,accept:[304],...n&&{signal:n}});return r.status===304?{status:`unchanged`}:{status:`modified`,meta:await r.json(),etag:Js(r)}},w=async(e,{method:n,body:r,path:i=``,query:a,headers:o}={})=>{let s=await t({method:n??(r===void 0?`GET`:`POST`),path:`/functions/${encodeURIComponent(e)}${i}`,query:a?`?${new URLSearchParams(a)}`:``,body:r,headers:o,system:!0});if(s.status!==204)return s.headers.get(`content-type`)?.includes(`json`)?s.json():s.text()},T=async(e,n,r,{onProgress:i,signal:a}={})=>{let o=`name`in r&&typeof r.name==`string`?r.name:void 0,s=i&&typeof XMLHttpRequest<`u`?Us(i):void 0,c=await(await t({method:`POST`,path:`/${Ws(e)}:upload`,query:`?${new URLSearchParams({field:n,...o!==void 0&&{name:o}})}`,raw:r,headers:{"content-type":r.type||`application/octet-stream`},...s&&{via:s},...a&&{signal:a}})).json();return i?.(r.size,r.size),c},E=e=>`/forms/${encodeURIComponent(e)}`;return{list:r,search:i,get:a,create:o,update:s,remove:c,undelete:l,generate:d,reveal:u,history:f,comments:p,comment:m,mentionable:h,batchWrite:g,facets:_,aggregate:v,series:y,histogram:b,map:x,seek:S,meta:C,invoke:w,upload:T,form:async e=>(await t({method:`GET`,path:E(e),system:!0})).json(),formChallenge:async e=>(await t({method:`GET`,path:`${E(e)}:challenge`,system:!0})).json(),submitForm:async(e,n,r)=>{await t({method:`POST`,path:E(e),body:{values:n,proof:r},system:!0})}}},Qs=e=>typeof e==`string`?e:e.toModel().name,$s=(e,t)=>{let n=n=>t(Qs(n))??e;return{list:(e,t)=>n(e).list(e,t),search:(e,t)=>n(e).search(e,t),get:(e,t)=>n(e).get(e,t),create:(e,t)=>n(e).create(e,t),update:(e,t,r,i)=>n(e).update(e,t,r,i),remove:(e,t,r)=>n(e).remove(e,t,r),undelete:(e,t)=>n(e).undelete(e,t),generate:(e,t,r)=>n(e).generate(e,t,r),reveal:(e,t,r)=>n(e).reveal(e,t,r),history:(e,t,r)=>n(e).history(e,t,r),comments:(e,t,r)=>n(e).comments(e,t,r),comment:(e,t,r)=>n(e).comment(e,t,r),mentionable:(e,t,r)=>n(e).mentionable(e,t,r),batchWrite:t=>{let r=[...new Set(t.map(e=>n(e.resource)))];return r.length>1?Promise.reject(Error(`A batch writes to one API, but these writes are for ${[...new Set(t.map(e=>Qs(e.resource)))].join(`, `)}, which different APIs serve`)):(r[0]??e).batchWrite(t)},facets:(e,t,r)=>n(e).facets(e,t,r),aggregate:(e,t)=>n(e).aggregate(e,t),series:(e,t)=>n(e).series(e,t),histogram:(e,t,r)=>n(e).histogram(e,t,r),map:(e,t)=>n(e).map(e,t),seek:(e,t)=>n(e).seek(e,t),meta:(t,n)=>e.meta(t,n),invoke:(t,n)=>e.invoke(t,n),upload:(e,t,r,i)=>n(e).upload(e,t,r,i),form:t=>e.form(t),formChallenge:t=>e.formChallenge(t),submitForm:(t,n,r)=>e.submitForm(t,n,r)}},ec=e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&typeof e.type==`string`&&Array.isArray(e.children),tc=e=>typeof e==`object`&&!!e&&e.kind===`member`,nc=e=>tc(e)?[e.path.join(`.`)]:typeof e!=`object`||!e?[]:Object.values(e).flatMap(nc),rc=e=>tc(e)?{...e,path:[e.path.join(`.`)]}:Array.isArray(e)?e.map(rc):typeof e!=`object`||!e?e:Object.fromEntries(Object.entries(e).map(([e,t])=>[e,rc(t)])),ic=e=>{let t=Zr(e);return t.ok?t.ast?{ok:!0,ast:t.ast,paths:[...new Set(nc(t.ast))]}:{ok:!1,message:`the condition is empty`}:{ok:!1,message:t.errors.map(e=>e.message).join(`; `)}},ac=(e,t)=>e.ast!==void 0&&ua(rc(e.ast),t),oc=(e,t)=>{let[n,r,...i]=e.split(`.`);return n&&r===`count`&&i.length===0&&!t(n)?n:void 0},sc=(e,t,n)=>{let r=[],i=e[t],a=n.split(`.`);for(let[o,s]of a.entries()){if(!i)return{ok:!1,message:`unknown resource "${t}"`};let c=Object.hasOwn(i.fields,s)?i.fields[s]:void 0;if(!c)return{ok:!1,message:`unknown field "${a.slice(0,o+1).join(`.`)}" on ${i.name}`};if(r.push({model:i,field:c}),o===a.length-1)break;if(c.type!==`relation`||!c.relation)return{ok:!1,message:`"${a.slice(0,o+1).join(`.`)}" is not a relation, so "${n}" cannot go through it`};t=c.relation.resource,i=e[t]}return{ok:!0,steps:r}},cc=(e,t)=>({...e,fields:Object.fromEntries(Object.entries(e.fields).map(([e,n])=>{if(!n.relation||Object.hasOwn(t,n.relation.resource))return[e,n];let{relation:r,...i}=n;return[e,i]}))}),lc=(e,t)=>{if(e.kind!==`related`)return[e];if(!Object.hasOwn(t,e.resource)||e.through&&!Object.hasOwn(t,e.through.resource))return[];let{columns:n,...r}=e,i=n?.filter(n=>sc(t,e.resource,n).ok);return[i&&i.length>0?{...r,columns:i}:r]},uc=(e,t,n)=>e.run?.kind!==`link`||!(`to`in e.run)||Zo(e.run.to,{models:n,pages:new Set,source:t}).length===0,dc=(e,t)=>({...e,layout:e.layout.flatMap(e=>lc(e,t)),actions:e.actions.filter(n=>uc(n,t[e.resource],t))}),fc=(e,t)=>{let n=e.resources.filter(e=>t.resources.includes(e.name)),r=Object.fromEntries(n.map(e=>[e.name,e])),i=n.map(e=>cc(e,r)),a=Object.fromEntries(i.map(e=>[e.name,e]));return{resources:i,views:e.views.filter(e=>Object.hasOwn(a,e.resource)).map(e=>dc(e,a)),permissions:Object.fromEntries(n.flatMap(t=>e.permissions?.[t.name]?[[t.name,e.permissions[t.name]]]:[]))}},pc=class extends Error{status;code;constructor(e,t,n){super(e),this.status=t,this.code=n,this.name=`AuthError`}},z=(e,t)=>new pc(e?.message||t,e?.status??500,e?.code),mc=e=>({signInMethods:async()=>{let{data:t,error:n}=await e.$fetch(`/account/sign-in-methods`);if(n||!t)throw z(n,`Could not read your sign-in methods`);return t},passkeys:async()=>{let{data:t,error:n}=await e.passkey.listUserPasskeys();if(n||!t)throw z(n,`Could not read your passkeys`);return t.map(e=>({id:e.id,backedUp:e.backedUp,...e.name&&{name:e.name},...e.createdAt&&{createdAt:new Date(e.createdAt).toISOString()}}))},addPasskey:async t=>{let{error:n}=await e.passkey.addPasskey(t?{name:t}:{});if(n)throw z(n,`Could not add the passkey`)},renamePasskey:async(t,n)=>{let{error:r}=await e.passkey.updatePasskey({id:t,name:n});if(r)throw z(r,`Could not rename the passkey`)},removePasskey:async t=>{let{error:n}=await e.passkey.deletePasskey({id:t});if(n)throw z(n,`Could not remove the passkey`)},startAuthenticatorApp:async t=>{let{data:n,error:r}=await e.twoFactor.enable({method:`totp`,...t&&{password:t}});if(r||n?.method!==`totp`)throw z(r,`Could not start two-factor authentication`);return{totpURI:n.totpURI,backupCodes:n.backupCodes}},confirmAuthenticatorApp:async t=>{let{error:n}=await e.twoFactor.verifyTotp({code:t});if(n)throw z(n,`The code did not work`)},turnOnEmailedCodes:async t=>{let{error:n}=await e.twoFactor.enable({method:`otp`,...t&&{password:t}});if(n)throw z(n,`Could not turn on two-factor authentication`)},turnOffTwoFactor:async t=>{let{error:n}=await e.twoFactor.disable(t?{password:t}:{});if(n)throw z(n,`Could not turn off two-factor authentication`)},linkedProviders:async()=>{let{data:t,error:n}=await e.listAccounts();if(n||!t)throw z(n,`Could not read your linked accounts`);return[...new Set(t.map(e=>e.providerId).filter(e=>e!==`credential`))]},linkProvider:async(t,n)=>{let{data:r,error:i}=await e.linkSocial({provider:t,callbackURL:n,errorCallbackURL:n,disableRedirect:!0});if(i||!r?.url)throw z(i,`Could not start linking the account`);return r.url},newBackupCodes:async t=>{let{data:n,error:r}=await e.twoFactor.generateBackupCodes(t?{password:t}:{});if(r||!n)throw z(r,`Could not make new backup codes`);return n.backupCodes}});function hc(e){return Object.fromEntries(Object.entries(e).map(([e,t])=>[e,{code:e,message:t,toString:()=>e}]))}var gc=hc({CHALLENGE_NOT_FOUND:`Challenge not found`,YOU_ARE_NOT_ALLOWED_TO_REGISTER_THIS_PASSKEY:`You are not allowed to register this passkey`,FAILED_TO_VERIFY_REGISTRATION:`Failed to verify registration`,PASSKEY_NOT_FOUND:`Passkey not found`,AUTHENTICATION_FAILED:`Authentication failed`,UNABLE_TO_CREATE_SESSION:`Unable to create session`,USER_NOT_FOUND:`User not found`,FAILED_TO_UPDATE_PASSKEY:`Failed to update passkey`,PREVIOUSLY_REGISTERED:`Previously registered`,REGISTRATION_CANCELLED:`Registration cancelled`,AUTH_CANCELLED:`Auth cancelled`,UNKNOWN_ERROR:`Unknown error`,SESSION_REQUIRED:`Passkey registration requires an authenticated session`,RESOLVE_USER_REQUIRED:`Passkey registration requires either an authenticated session or a resolveUser callback when requireSession is false`,RESOLVED_USER_INVALID:`Resolved user is invalid`}),_c=`1.7.7`;function vc(e){let t=new Uint8Array(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=/g,``)}function yc(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`),n=(4-t.length%4)%4,r=t.padEnd(t.length+n,`=`),i=atob(r),a=new ArrayBuffer(i.length),o=new Uint8Array(a);for(let e=0;e<i.length;e++)o[e]=i.charCodeAt(e);return a}function bc(){return xc.stubThis(globalThis?.PublicKeyCredential!==void 0&&typeof globalThis.PublicKeyCredential==`function`)}var xc={stubThis:e=>e};function Sc(e){let{id:t}=e;return{...e,id:yc(t),transports:e.transports}}function Cc(e){return e===`localhost`||/^((xn--[a-z0-9-]+|[a-z0-9]+(-[a-z0-9]+)*)\.)+([a-z]{2,}|xn--[a-z0-9-]+)$/i.test(e)}var wc=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=r??n.name,this.code=t}};function Tc({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new wc({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(n.authenticatorSelection?.requireResidentKey===!0)return new wc({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(t.mediation===`conditional`&&n.authenticatorSelection?.userVerification===`required`)return new wc({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(n.authenticatorSelection?.userVerification===`required`)return new wc({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new wc({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new wc({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return n.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new wc({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new wc({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!Cc(t))return new wc({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rp.id!==t)return new wc({message:`The RP ID "${n.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(n.user.id.byteLength<1||n.user.id.byteLength>64)return new wc({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new wc({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}var Ec=new class{constructor(){Object.defineProperty(this,"controller",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}createNewAbortSignal(){if(this.controller){let e=Error(`Cancelling existing WebAuthn API call for new one`);e.name=`AbortError`,this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=Error(`Manually cancelling existing WebAuthn API call`);e.name=`AbortError`,this.controller.abort(e),this.controller=void 0}}},Dc=[`cross-platform`,`platform`];function Oc(e){if(e&&!(Dc.indexOf(e)<0))return e}async function kc(e){!e.optionsJSON&&e.challenge&&(console.warn(`startRegistration() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useAutoRegister:n=!1}=e;if(!bc())throw Error(`WebAuthn is not supported in this browser`);let r={...t,challenge:yc(t.challenge),user:{...t.user,id:yc(t.user.id)},excludeCredentials:t.excludeCredentials?.map(Sc)},i={};n&&(i.mediation=`conditional`),i.publicKey=r,i.signal=Ec.createNewAbortSignal();let a;try{a=await navigator.credentials.create(i)}catch(e){throw Tc({error:e,options:i})}if(!a)throw Error(`Registration was not completed`);let{id:o,rawId:s,response:c,type:l}=a,u;typeof c.getTransports==`function`&&(u=c.getTransports());let d;if(typeof c.getPublicKeyAlgorithm==`function`)try{d=c.getPublicKeyAlgorithm()}catch(e){Ac(`getPublicKeyAlgorithm()`,e)}let f;if(typeof c.getPublicKey==`function`)try{let e=c.getPublicKey();e!==null&&(f=vc(e))}catch(e){Ac(`getPublicKey()`,e)}let p;if(typeof c.getAuthenticatorData==`function`)try{p=vc(c.getAuthenticatorData())}catch(e){Ac(`getAuthenticatorData()`,e)}return{id:o,rawId:vc(s),response:{attestationObject:vc(c.attestationObject),clientDataJSON:vc(c.clientDataJSON),transports:u,publicKeyAlgorithm:d,publicKey:f,authenticatorData:p},type:l,clientExtensionResults:a.getClientExtensionResults(),authenticatorAttachment:Oc(a.authenticatorAttachment)}}function Ac(e,t){console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${e}. You should report this error to them.\n`,t)}function jc(){if(!bc())return Mc.stubThis(new Promise(e=>e(!1)));let e=globalThis.PublicKeyCredential;return e?.isConditionalMediationAvailable===void 0?Mc.stubThis(new Promise(e=>e(!1))):Mc.stubThis(e.isConditionalMediationAvailable())}var Mc={stubThis:e=>e};function Nc({error:e,options:t}){let{publicKey:n}=t;if(!n)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(t.signal instanceof AbortSignal)return new wc({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new wc({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let t=globalThis.location.hostname;if(!Cc(t))return new wc({message:`${globalThis.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(n.rpId!==t)return new wc({message:`The RP ID "${n.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new wc({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return e}async function Pc(e){!e.optionsJSON&&e.challenge&&(console.warn(`startAuthentication() was not called correctly. It will try to continue with the provided options, but this call should be refactored to use the expected call structure instead. See https://simplewebauthn.dev/docs/packages/browser#typeerror-cannot-read-properties-of-undefined-reading-challenge for more information.`),e={optionsJSON:e});let{optionsJSON:t,useBrowserAutofill:n=!1,verifyBrowserAutofillInput:r=!0}=e;if(!bc())throw Error(`WebAuthn is not supported in this browser`);let i;t.allowCredentials?.length!==0&&(i=t.allowCredentials?.map(Sc));let a={...t,challenge:yc(t.challenge),allowCredentials:i},o={};if(n){if(!await jc())throw Error(`Browser does not support WebAuthn autofill`);if(document.querySelectorAll(`input[autocomplete$='webauthn']`).length<1&&r)throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');o.mediation=`conditional`,a.allowCredentials=[]}o.publicKey=a,o.signal=Ec.createNewAbortSignal();let s;try{s=await navigator.credentials.get(o)}catch(e){throw Nc({error:e,options:o})}if(!s)throw Error(`Authentication was not completed`);let{id:c,rawId:l,response:u,type:d}=s,f;return u.userHandle&&(f=vc(u.userHandle)),{id:c,rawId:vc(l),response:{authenticatorData:vc(u.authenticatorData),clientDataJSON:vc(u.clientDataJSON),signature:vc(u.signature),userHandle:f},type:d,clientExtensionResults:s.getClientExtensionResults(),authenticatorAttachment:Oc(s.authenticatorAttachment)}}var Fc=`1.7.7`,Ic=Symbol.for(`better-auth:broadcast-channel`),Lc=()=>Math.floor(Date.now()/1e3),qee=class{listeners=new Set;name;constructor(e=`better-auth.message`){this.name=e}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}post(e){if(typeof window<`u`)try{localStorage.setItem(this.name,JSON.stringify({...e,timestamp:Lc()}))}catch{}}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=e=>{if(e.key!==this.name)return;let t=JSON.parse(e.newValue??`{}`);t?.event===`session`&&t?.data&&this.listeners.forEach(e=>e(t))};return window.addEventListener(`storage`,e),()=>{window.removeEventListener(`storage`,e)}}};function Rc(e=`better-auth.message`){return globalThis[Ic]||(globalThis[Ic]=new qee(e)),globalThis[Ic]}var zc=[],Bc=0,Vc=null,Hc=4,Jee=globalThis.nanostoresGlobal||={epoch:0},Yee=()=>{let e,t;for(;Bc<zc.length;){t=Bc,Bc+=Hc;let n=Vc?.get(zc[t]);if(n){if(!n.has(zc[t+1]))continue;n.clear()}try{zc[t](zc[t+1].value,zc[t+2],zc[t+3])}catch(t){e=t}}if(zc.length=Bc=0,e)throw e},Uc=e=>{let t=[],n={eq:Object.is,get(){return n.lc||n.listen(()=>{})(),n.value},init:e,lc:0,listen(e){return n.lc=t.push(e),()=>{Vc?.get(e)?.delete(n);for(let t=Bc;t<zc.length;)zc[t]===e&&zc[t+1]===n?zc.splice(t,Hc):t+=Hc;let r=t.indexOf(e);~r&&(t.splice(r,1),--n.lc||n.off())}},notify(e,r){Jee.epoch++;let i=!zc.length&&!0;for(let i of t)zc.push(i,n,e,r);i&&Yee()},off(){},set(e){let t=n.value;n.eq(t,e)||(n.value=e,n.notify(t))},subscribe(e){let t=n.listen(e);return e(n.value),t},value:e};return n},Xee=2,Zee=5,Wc=6,Gc=10,Kc=(e,t,n,r)=>(e.events=e.events||{},e.events[n+Gc]||(e.events[n+Gc]=r(t=>{e.events[n].reduceRight((e,t)=>(t(e),e),{shared:{},...t})})),e.events[n]=e.events[n]||[],e.events[n].push(t),()=>{let r=e.events[n],i=r.indexOf(t);~i&&(r.splice(i,1),r.length||(e.events[n+Gc](),delete e.events[n+Gc]))}),Qee=(e,t)=>Kc(e,t,Xee,t=>{let n=e.set,r=e.setKey;return e.setKey&&=(n,i)=>{let a;if(t({abort:()=>{a=!0},changed:n,newValue:{...e.value,[n]:i}}),!a)return r(n,i)},e.set=e=>{let r;if(t({abort:()=>{r=!0},newValue:e}),!r)return n(e)},()=>{e.set=n,e.setKey=r}}),qc=1e3,Jc=(e,t)=>Kc(e,n=>{let r=t(n);r&&e.events[Wc].push(r)},Zee,t=>{let n=e.listen;e.listen=(...r)=>(!e.lc&&!e.active&&(e.active=!0,t()),n(...r));let r=e.off;return e.events[Wc]=[],e.off=()=>{r(),setTimeout(()=>{if(e.active&&!e.lc){e.active=!1;for(let t of e.events[Wc])t();e.events[Wc]=[]}},qc)},()=>{e.listen=n,e.off=r}});function Yc(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Xc(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!Xc(e[n],t[n]))return!1;return!0}if(Yc(e)&&Yc(t)){let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!(r in t)||!Xc(e[r],t[r]))return!1;return!0}return!1}function Zc(e,t){return Qee(e,({newValue:n,abort:r})=>{t(e.value,n)&&r()})}var Qc=Symbol.for(`better-auth:focus-manager`),$ee=class{listeners=new Set;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setFocused(e){this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||typeof document>`u`||window.addEventListener===void 0)return()=>{};let e=()=>{document.visibilityState===`visible`&&this.setFocused(!0)};return document.addEventListener(`visibilitychange`,e,!1),()=>{document.removeEventListener(`visibilitychange`,e,!1)}}};function $c(){return globalThis[Qc]||(globalThis[Qc]=new $ee),globalThis[Qc]}var el=Symbol.for(`better-auth:online-manager`),ete=class{listeners=new Set;isOnline=typeof navigator<`u`?navigator.onLine:!0;subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}setOnline(e){this.isOnline=e,this.listeners.forEach(t=>t(e))}setup(){if(typeof window>`u`||window.addEventListener===void 0)return()=>{};let e=()=>this.setOnline(!0),t=()=>this.setOnline(!1);return window.addEventListener(`online`,e,!1),window.addEventListener(`offline`,t,!1),()=>{window.removeEventListener(`online`,e,!1),window.removeEventListener(`offline`,t,!1)}}};function tl(){return globalThis[el]||(globalThis[el]=new ete),globalThis[el]}var tte={proto:/"(?:_|\\u0{2}5[Ff]){2}(?:p|\\u0{2}70)(?:r|\\u0{2}72)(?:o|\\u0{2}6[Ff])(?:t|\\u0{2}74)(?:o|\\u0{2}6[Ff])(?:_|\\u0{2}5[Ff]){2}"\s*:/,constructor:/"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/,protoShort:/"__proto__"\s*:/,constructorShort:/"constructor"\s*:/},nte=/^\s*["[{]|^\s*-?\d{1,16}(\.\d{1,17})?([Ee][+-]?\d+)?\s*$/,nl={true:!0,false:!1,null:null,undefined:void 0,nan:NaN,infinity:1/0,"-infinity":-1/0},rte=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,7}))?(?:Z|([+-])(\d{2}):(\d{2}))$/;function ite(e){return e instanceof Date&&!isNaN(e.getTime())}function ate(e){let t=rte.exec(e);if(!t)return null;let[,n,r,i,a,o,s,c,l,u,d]=t,f=new Date(Date.UTC(parseInt(n,10),parseInt(r,10)-1,parseInt(i,10),parseInt(a,10),parseInt(o,10),parseInt(s,10),c?parseInt(c.padEnd(3,`0`),10):0));if(l){let e=(parseInt(u,10)*60+parseInt(d,10))*(l===`+`?-1:1);f.setUTCMinutes(f.getUTCMinutes()+e)}return ite(f)?f:null}function ote(e,t={}){let{strict:n=!1,warnings:r=!1,reviver:i,parseDates:a=!0}=t;if(typeof e!=`string`)return e;let o=e.trim(),s=o.toLowerCase();if(s.length<=9&&s in nl)return nl[s];if(!nte.test(o)){if(n)throw SyntaxError(`[better-json] Invalid JSON`);return e}if(Object.entries(tte).some(([e,t])=>{let n=t.test(o);return n&&r&&console.warn(`[better-json] Detected potential prototype pollution attempt using ${e} pattern`),n})&&n)throw Error(`[better-json] Potential prototype pollution attempt detected`);try{return JSON.parse(o,(e,t)=>{if(e===`__proto__`||e===`constructor`&&t&&typeof t==`object`&&`prototype`in t){r&&console.warn(`[better-json] Dropping "${e}" key to prevent prototype pollution`);return}if(a&&typeof t==`string`){let e=ate(t);if(e)return e}return i?i(e,t):t})}catch(t){if(n)throw t;return e}}function ste(e,t={strict:!0}){return ote(e,t)}var cte=Symbol.for(`better-auth:auth-query`);function rl(e){let t=Uc(e);return Object.defineProperty(t,cte,{value:!0}),t}var lte=()=>typeof window>`u`;function ute(e,t){return Xc(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}var dte=(e,t,n,r)=>{let i=rl({data:null,error:null,isPending:!0,isRefetching:!1,refetch:e=>o(e)});Jc(i,()=>Zc(i,ute));let a=0,o=async e=>{let o=++a;return new Promise(s=>{let c=typeof r==`function`?r({data:i.get().data,error:i.get().error,isPending:i.get().isPending}):r;n(t,{...c,query:{...c?.query,...e?.query},async onSuccess(e){if(o===a){let t=i.get(),n=t.data!=null&&e.data!=null&&Xc(t.data,e.data)?t.data:e.data;i.set({data:n,error:null,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}await c?.onSuccess?.(e)},async onError(e){let{request:t}=e,n=typeof t.retry==`number`?t.retry:t.retry?.attempts,r=t.retryAttempt||0;if(!(n&&r<n)){if(o===a){let t=e.error.status===401;i.set({error:e.error,data:t?null:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}await c?.onError?.(e)}},async onRequest(e){if(o===a){let e=i.get();i.set({isPending:e.data===null,data:e.data,error:null,isRefetching:!0,refetch:i.value.refetch})}await c?.onRequest?.(e)}}).catch(e=>{o===a&&i.set({error:e,data:i.get().data,isPending:!1,isRefetching:!1,refetch:i.value.refetch})}).finally(()=>{s(void 0)})})};e=Array.isArray(e)?e:[e];let s=!1,c=!1,l=!1,u=()=>{if(s){l=!0;return}s=!0,o().finally(()=>{s=!1;let e=l&&c;l=!1,e&&u()})};return Jc(i,()=>{if(lte())return;c=!0;let t=!1,n,r=e.map(e=>e.listen(()=>{t?o():(t=!0,clearTimeout(n),u())}));return n=setTimeout(()=>{t=!0,u()},0),()=>{c=!1;for(let e of r)e();clearTimeout(n)}}),i},il=()=>Math.floor(Date.now()/1e3),fte=5;function pte(e){let{fetchSession:t,shouldPollSession:n=()=>!0,sessionSignal:r,options:i={}}=e,a=i.sessionOptions?.refetchInterval??0,o=i.sessionOptions?.refetchOnWindowFocus??!0,s=i.sessionOptions?.refetchWhenOffline??!1,c={isInitialized:!1,lastSessionRequest:0},l=()=>s||tl().isOnline,u=e=>{if(l()){if(e?.event===`storage`){t();return}if(e?.event===`poll`){c.lastSessionRequest=il(),t();return}if(e?.event===`visibilitychange`){if(il()-c.lastSessionRequest<fte)return;c.lastSessionRequest=il(),t();return}t()}},d=e=>{Rc().post({event:`session`,data:{trigger:e},clientId:Math.random().toString(36).substring(7)})},f=()=>{a&&a>0&&(c.pollInterval=setInterval(()=>{n()&&u({event:`poll`})},a*1e3))},p=()=>{c.unsubscribeBroadcast=Rc().subscribe(()=>{u({event:`storage`})})},m=()=>{o&&(c.unsubscribeFocus=$c().subscribe(()=>{u({event:`visibilitychange`})}))},h=()=>{c.unsubscribeOnline=tl().subscribe(e=>{e&&u({event:`visibilitychange`})})},g=()=>{c.unsubscribeSignal=r.listen(()=>{t()})};return{init:()=>{c.isInitialized||(c.isInitialized=!0,f(),p(),m(),h(),g(),c.cleanupBroadcastSetup=Rc().setup(),c.cleanupFocusSetup=$c().setup(),c.cleanupOnlineSetup=tl().setup())},cleanup:()=>{c.isInitialized&&(c.pollInterval&&=(clearInterval(c.pollInterval),void 0),c.unsubscribeBroadcast&&=(c.unsubscribeBroadcast(),void 0),c.unsubscribeFocus&&=(c.unsubscribeFocus(),void 0),c.unsubscribeOnline&&=(c.unsubscribeOnline(),void 0),c.unsubscribeSignal&&=(c.unsubscribeSignal(),void 0),c.cleanupBroadcastSetup&&=(c.cleanupBroadcastSetup(),void 0),c.cleanupFocusSetup&&=(c.cleanupFocusSetup(),void 0),c.cleanupOnlineSetup&&=(c.cleanupOnlineSetup(),void 0),c.isInitialized=!1,c.lastSessionRequest=0)},triggerRefetch:u,broadcastSessionUpdate:d}}var al=Object.create(null),ol=e=>({}),sl=new Proxy(al,{get(e,t){return ol()[t]??al[t]},has(e,t){return t in ol()||t in al},set(e,t,n){let r=ol(!0);return r[t]=n,!0},deleteProperty(e,t){if(!t)return!1;let n=ol(!0);return delete n[t],!0},ownKeys(){let e=ol(!0);return Object.keys(e)}});sl.NODE_ENV;function cl(e,t){return typeof process<`u`?{}[e]??t:typeof Deno<`u`?Deno.env.get(e)??t:typeof Bun<`u`?Bun.env[e]??t:t}Object.freeze({get BETTER_AUTH_SECRET(){return cl(`BETTER_AUTH_SECRET`)},get AUTH_SECRET(){return cl(`AUTH_SECRET`)},get BETTER_AUTH_TELEMETRY(){return cl(`BETTER_AUTH_TELEMETRY`)},get BETTER_AUTH_TELEMETRY_ID(){return cl(`BETTER_AUTH_TELEMETRY_ID`)},get NODE_ENV(){return cl(`NODE_ENV`,`development`)},get PACKAGE_VERSION(){return cl(`PACKAGE_VERSION`,`0.0.0`)},get BETTER_AUTH_TELEMETRY_ENDPOINT(){return cl(`BETTER_AUTH_TELEMETRY_ENDPOINT`,``)}});function mte(){let e=Object.getOwnPropertyDescriptor(Error,`stackTraceLimit`);return e===void 0?Object.isExtensible(Error):Object.prototype.hasOwnProperty.call(e,`writable`)?e.writable:e.set!==void 0}function hte(e){let t=e.split(`
|
|
5
5
|
at `);return t.length<=1?e:(t.splice(1,1),t.join(`
|
|
6
|
-
at `))}function gte(e,t){class n extends e{#e;constructor(...e){if(mte()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=hte(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(n.prototype,"constructor",{get(){return t},enumerable:!1,configurable:!0}),n}var _te={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};gte(class extends Error{status;body;headers;statusCode;constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:_te[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=n,this.statusCode=r,this.name=`APIError`,this.status=e,this.headers=n,this.statusCode=r,this.body=t}},Error);var ll=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}},vte=47;function ul(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===vte;)t--;return t===e.length?e:e.slice(0,t)}function yte(e){try{return(ul(new URL(e).pathname)||`/`)!==`/`}catch{throw new ll(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function bte(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new ll(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof ll?t:new ll(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function dl(e,t=`/api/auth`){if(bte(e),yte(e))return e;let n=ul(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function fl(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function xte(e,t,n,r,i){if(e)return dl(e,t);if(r!==!1){let e=sl.BETTER_AUTH_URL||sl.NEXT_PUBLIC_BETTER_AUTH_URL||sl.PUBLIC_BETTER_AUTH_URL||sl.NUXT_PUBLIC_BETTER_AUTH_URL||sl.NUXT_PUBLIC_AUTH_URL||(sl.BASE_URL===`/`?void 0:sl.BASE_URL);if(e)return dl(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&fl(o,`proto`)&&fl(a,`host`))try{return dl(`${o}://${a}`,t)}catch{}if(n){let e=Ste(n.url);if(!e)throw new ll(`Could not get origin from request. Please provide a valid base URL.`);return dl(e,t)}if(typeof window<`u`&&window.location)return dl(window.location.origin,t)}function Ste(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var Cte=[`javascript:`,`data:`,`vbscript:`];function pl(e){let t;try{t=new URL(e)}catch{return!0}return!Cte.includes(t.protocol)}var wte={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&pl(e.data.url)&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}},Tte=()=>typeof window>`u`,Ete=qc;function Dte(e,t){if(typeof window>`u`)return;let n=e.get();n.data===null&&t!==null&&e.set({...n,data:t,error:null,isPending:!1})}function ml(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}function Ote(e){return!e||e.session===null&&e.user===null?null:e}function kte(e,t){return Xc(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}function Ate(e,t){let n=Uc(!1),r,i=0,a=0;n.listen(()=>{a++,i=0});let o=e=>u(e),s=rl({data:null,error:null,isPending:!0,isRefetching:!1,refetch:o});Zc(s,kte);let c=async(t,n)=>{let r=s.value;if(s.set({...r,isPending:r.data===null,isRefetching:!0,error:null,refetch:o}),t.aborted)return`aborted`;try{let r=await e(`/get-session`,{method:`GET`,query:n?.query,signal:t});if(t.aborted)return`aborted`;let{data:i,error:a}=ml(r),c=`fresh`;if(i?.needsRefresh)try{let n=await e(`/get-session`,{method:`POST`,signal:t});if(t.aborted)return`aborted`;({data:i,error:a}=ml(n))}catch{if(t.aborted)return`aborted`;c=`stale`}if(a){let e=s.value,t=a?.status===401;return s.set({data:t?null:e.data,error:a,isPending:!1,isRefetching:!1,refetch:o}),`failed`}let l=Ote(i),u=s.value,d=u.data!=null&&l!=null&&Xc(u.data,l)?u.data:l;return s.set({data:d,error:null,isPending:!1,isRefetching:!1,refetch:o}),c}catch(e){if(t.aborted)return`aborted`;let n=s.value;return s.set({data:n.data,error:e,isPending:!1,isRefetching:!1,refetch:o}),`failed`}},l=()=>{let e=s.value.data?.session?.expiresAt,t=e instanceof Date?e.getTime():1/0;return Math.min(Date.now()+Ete,t)},u=e=>{i=0,r?.cancel();let t=new AbortController,n={cancel:()=>t.abort(),promise:Promise.resolve().then(()=>t.signal.aborted?`aborted`:c(t.signal,e)),revision:a};r=n;let o=e=>{r===n&&(r=void 0,e===`fresh`&&n.revision===a&&(i=l()))};return n.promise.then(o,()=>o(`failed`)),n.promise.then(()=>void 0)},d=()=>r?.revision===a?r.promise.then(()=>void 0):Date.now()<i?Promise.resolve():u(),f=()=>{};return Jc(s,()=>{let e;Tte()||(e=setTimeout(()=>{d()},0));let r=pte({fetchSession:u,shouldPollSession:()=>s.value.data!=null,sessionSignal:n,options:t});return r.init(),f=r.broadcastSessionUpdate,()=>{e&&clearTimeout(e),r.cleanup()}}),{session:s,$sessionSignal:n,broadcastSessionUpdate:e=>f(e)}}function hl(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function gl(e,t,n=`.`,r){if(!hl(t))return gl(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:hl(a)&&hl(i[t])?gl(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function jte(e){return(...t)=>t.reduce((t,n)=>gl(t,n,``,e),{})}var Mte=jte(),Nte=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},Pte=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let t=await i.init?.call(i,e.toString(),n);n=t.options||n,e=t.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},_l=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},Fte=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function Ite(e){if(typeof e==`number`)return new _l({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new _l(e);case`exponential`:return new Fte(e);default:throw Error(`Invalid retry strategy`)}}var Lte=[`get`,`post`,`put`,`patch`,`delete`];function vl(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return Lte.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}var Rte=e=>e===`.`||e===`..`,zte=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function Bte(e,t){let n=t.get(e);if(n===void 0)return zte(e);if(Rte(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function Vte(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``,{path:o}=vl(e);o!==e&&(e=`/${o}`),a.endsWith(`/`)||(a+=`/`);let[s,c]=e.replace(a,``).split(`?`),l=new URLSearchParams(c);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)l.append(e,n);continue}else n=JSON.stringify(t);l.set(e,n)}let u=new Map;if(r){if(Array.isArray(r)){let e=s.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];u.set(n,String(e))}}else for(let[e,t]of Object.entries(r))u.set(`:${e}`,String(t))}s=s.split(`/`).map(e=>Bte(e,u)).join(`/`),s=s.replace(/^\/+/,``);let d=l.toString();return d=d.length>0?`?${d}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${s}${d}`,a):`${a}${s}${d}`}var Hte=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},Ute=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Wte(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return Ute.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function Gte(e){try{return JSON.parse(e),!0}catch{return!1}}function yl(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function bl(e){try{return JSON.parse(e)}catch{return e}}function xl(e){return typeof e==`function`}function Kte(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&xl(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&xl(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function Sl(...e){let t={};for(let n of e)if(n){if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}}return t}async function qte(e){let t=new Headers(Sl(e?.headers,await Hte(e)));if(!t.has(`content-type`)){let n=Jte(e?.body);n&&t.set(`content-type`,n)}return t}function Jte(e){return yl(e)?`application/json`:null}function Yte(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function Xte(e,t){let{body:n}=e;return n?!yl(n)||typeof n==`string`?n:Yte(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function Zte(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=vl(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function Qte(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var $te=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function Cl(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new $te(n.issues);return n.value}function wl(e){"@babel/helpers - typeof";return wl=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},wl(e)}function ene(e,t){if(wl(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(wl(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function tne(e){var t=ene(e,`string`);return wl(t)==`symbol`?t:t+``}function nne(e,t,n){return(t=tne(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Tl(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function El(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Tl(Object(n),!0).forEach(function(t){nne(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Tl(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var Dl=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await Pte(e,t),o=Kte(a),s=new AbortController,c=a.signal??s.signal,l=Vte(i,a),u=await qte(a),d=Xte(a,u),f=Zte(i,a),p=El(El({},a),{},{url:l,headers:u,body:d,method:f,signal:c});for(let e of r.onRequest)if(e){let t=await e(p);typeof t==`object`&&t&&Object.assign(p,t)}(`pipeTo`in p&&typeof p.pipeTo==`function`||typeof(t==null||(n=t.body)==null?void 0:n.pipe)==`function`)&&(`duplex`in p||(p.duplex=`half`));let{clearTimeout:m}=Qte(a,s),h=await o(p.url,p);m();let g={response:h,request:p};for(let e of r.onResponse)if(e){var _;let n=await e(El(El({},g),{},{response:t!=null&&(_=t.hookOptions)!=null&&_.cloneResponse?h.clone():h}));n instanceof Response?h=n:typeof n==`object`&&n&&(h=n.response)}if(h.ok){if(p.method===`HEAD`)return{data:``,error:null};let e=Wte(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??bl)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await Cl(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(El(El({},n),{},{response:t!=null&&(v=t.hookOptions)!=null&&v.cloneResponse?h.clone():h}))}return t?.throw?n.data:{data:n.data,error:null}}let y=t?.jsonParser??bl,b=await h.text(),x=Gte(b),S=x?await y(b):null,C={response:h,responseText:b,request:p,error:El(El({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var w;await e(El(El({},C),{},{response:t!=null&&(w=t.hookOptions)!=null&&w.cloneResponse?h.clone():h}))}if(t?.retry){let n=Ite(t.retry),i=t.retryAttempt??0;if(await n.shouldAttemptRetry(i,h)){for(let e of r.onRetry)e&&await e(g);let a=n.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await Dl(e,El(El({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new Nte(h.status,h.statusText,x?S:b);return{data:null,error:El(El({},S),{},{status:h.status,statusText:h.statusText})}},rne=e=>({id:`apply-schema`,name:`Apply Schema`,version:`1.0.0`,async init(t,n){var r;let i=El(El({},n),e.query!==void 0&&{query:El(El({},e.query),n?.query)}),a=((r=e.plugins)==null||(r=r.find(e=>e.schema?.config?t.startsWith(e.schema.config.baseURL||``)||t.startsWith(e.schema.config.prefix||``):!1))==null?void 0:r.schema)||e.schema;if(a){let r=t;a.config?.prefix&&r.startsWith(a.config.prefix)&&(r=r.replace(a.config.prefix,``),a.config.baseURL&&(t=t.replace(a.config.prefix,a.config.baseURL))),a.config?.baseURL&&r.startsWith(a.config.baseURL)&&(r=r.replace(a.config.baseURL,``)),r.startsWith(`/`)&&r.charAt(1)===`@`&&(r=r.substring(1));let o=a.schema[r];if(o){let{method:a,path:s}=vl(r);a&&(t=t.slice(0,t.length-r.length)+s);let c=n?.headers;if(o.headers&&!n?.disableValidation){let e={};if(n?.headers){if(n.headers instanceof Headers)n.headers.forEach((t,n)=>{e[n.toLowerCase()]=t});else if(typeof n.headers==`object`)for(let[t,r]of Object.entries(n.headers))r!=null&&(e[t.toLowerCase()]=r)}let t=await Cl(o.headers,e),r={};for(let[e,n]of Object.entries(t))r[e.toLowerCase()]=n;c=r}let l=o.method??a;if(i=El(El(El(El({},i),l!==void 0&&{method:l}),o.output!==void 0&&{output:o.output}),c!==void 0&&{headers:c}),!n?.disableValidation){if(o.query&&(i.query=await Cl(o.query,n?.query),i.query!==null&&typeof i.query==`object`)){let t=El({},e.query);for(let e of Object.keys(t))n?.query&&Object.prototype.hasOwnProperty.call(n.query,e)&&(t[e]=n.query[e]);i.query=El(El({},t),i.query)}i=El(El({},i),{},{body:o.input?await Cl(o.input,n?.body):n?.body,params:o.params?await Cl(o.params,n?.params):n?.params})}return{url:t,options:i}}}return El({url:t},(n!==void 0||e.query!==void 0)&&{options:i})}}),ine=e=>{async function t(t,n){let r=El(El(El({},e),n),{},{headers:Sl(e?.headers,n?.headers),plugins:[...e?.plugins||[],rne(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await Dl(t,r)}catch(e){return{data:null,error:{status:500,statusText:`Fetch Error`,message:`Fetch related error. Captured by catchAllError option. See error property for more details.`,error:e}}}return await Dl(t,r)}return t},ane=e=>{if(typeof process>`u`)return;let t=e??`/api/auth`;if({}.NEXT_PUBLIC_AUTH_URL)return{}.NEXT_PUBLIC_AUTH_URL;if(typeof window>`u`){if({}.NEXTAUTH_URL)try{return{}.NEXTAUTH_URL}catch{}if({}.VERCEL_URL)try{let e={}.VERCEL_URL.startsWith(`http`)?``:`https://`;return`${new URL(`${e}${{}.VERCEL_URL}`).origin}${t}`}catch{}}},one=e=>e===`/sign-out`||e===`/update-user`||e===`/update-session`||e===`/sign-up/email`||e===`/sign-in/email`||e===`/delete-user`||e===`/verify-email`||e===`/revoke-sessions`||e===`/revoke-session`||e===`/revoke-other-sessions`||e===`/change-email`||e===`/change-password`,sne=(e,t)=>{let n=`credentials`in Request.prototype,r=xte(e?.baseURL,e?.basePath,void 0,t)??ane(e?.basePath)??`/api/auth`,i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>e!==void 0)||[],a={id:`lifecycle-hooks`,name:`lifecycle-hooks`,hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:o,onError:s,onRequest:c,onResponse:l,...u}=e?.fetchOptions||{},d=ine({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?ste(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[wte],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=Ate(d,e),h=!1,g=e=>{h||e===null||(h=!0,Dte(p,e))},_=e?.plugins||[],v={},y={$sessionSignal:f,session:p},b={"/sign-out":`POST`,"/revoke-sessions":`POST`,"/revoke-other-sessions":`POST`,"/delete-user":`POST`},x=[{signal:`$sessionSignal`,matcher:one,callback(e){e===`/sign-out`?m(`signout`):(e===`/update-user`||e===`/update-session`)&&m(`updateUser`)}}];for(let e of _)e.getAtoms&&Object.assign(y,e.getAtoms?.(d)),e.pathMethods&&Object.assign(b,e.pathMethods),e.atomListeners&&x.push(...e.atomListeners);let S={notify:e=>{y[e].set(!y[e].get())},listen:(e,t)=>{y[e].subscribe(t)},atoms:y};for(let t of _)t.getActions&&(v=Mte(t.getActions?.(d,S,e)??{},v));return{get baseURL(){return r},pluginsActions:v,pluginsAtoms:y,pluginPathMethods:b,atomListeners:x,hydrateSession:g,$sessionSignal:f,$fetch:d,$store:S}};function cne(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function lne(e){return e.charAt(0).toUpperCase()+e.slice(1)}var une=/[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu,dne=/['\u2019]/g;function fne(e){return e.replace(dne,``).match(une)??[]}function pne(e){return fne(e).map(e=>e.toLowerCase()).join(`-`)}function mne(e,t,n){let r=t[e],{fetchOptions:i,query:a,...o}=n||{};return r||(i?.method?i.method:o&&Object.keys(o).length>0?`POST`:`GET`)}function hne(e,t,n,r,i){function a(o=[]){return new Proxy(function(){},{get(t,n){if(typeof n!=`string`||n===`then`||n===`catch`||n===`finally`)return;let r=[...o,n],i=e;for(let e of r)if(i&&typeof i==`object`&&e in i)i=i[e];else{i=void 0;break}return typeof i==`function`||cne(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(pne).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=mne(c,n,l);return await t(c,{...m,body:h===`GET`?void 0:{...p,...m?.body||{}},query:d||m?.query,method:h,async onSuccess(e){if(await m?.onSuccess?.(e),!i||m.disableSignal)return;let t=i.filter(e=>e.matcher(c));if(!t.length)return;let n=new Set;for(let e of t){let t=r[e.signal];if(!t)return;if(n.has(e.signal))continue;n.add(e.signal);let i=t.get();setTimeout(()=>{t.set(!i)},10),e.callback?.(c)}}})}})}return a()}function gne(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,hydrateSession:i,$fetch:a,atomListeners:o,$store:s}=sne(e),c={};for(let[e,t]of Object.entries(r))c[`use${lne(e)}`]=t;return hne({...n,...c,hydrateSession:i,$fetch:a,$store:s},a,t,r,o)}var _ne=(e,{$listPasskeys:t,$store:n})=>({signIn:{passkey:async(r,i)=>{let a=await e(`/passkey/generate-authenticate-options`,{method:`GET`,throw:!1});if(!a.data)return a;let o=a.data.extensions||r?.extensions?{...a.data.extensions||{},...r?.extensions||{}}:void 0,s;try{s=await Pc({optionsJSON:{...a.data,extensions:o},useBrowserAutofill:r?.autoFill})}catch(e){return{data:null,error:{code:e instanceof wc?e.code:`AUTH_CANCELLED`,message:gc.AUTH_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}}try{let{clientExtensionResults:a,...o}=s,c=await e(`/passkey/verify-authentication`,{body:{response:o},...r?.fetchOptions,...i,method:`POST`,throw:!1});return t.set(Math.random()),n.notify(`$sessionSignal`),r?.returnWebAuthnResponse?{...c,webauthn:{response:s,clientExtensionResults:a}}:c}catch(e){return console.error(`[Better Auth] Error verifying passkey`,e),{data:null,error:{code:`AUTH_CANCELLED`,message:gc.AUTH_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}}}},passkey:{addPasskey:async(r,i)=>{let a=await e(`/passkey/generate-register-options`,{method:`GET`,query:{...r?.authenticatorAttachment&&{authenticatorAttachment:r.authenticatorAttachment},...r?.name&&{name:r.name},...r?.context&&{context:r.context}},throw:!1});if(!a.data)return a;try{let o=a.data.extensions||r?.extensions?{...a.data.extensions||{},...r?.extensions||{}}:void 0,s=await kc({optionsJSON:{...a.data,extensions:o},useAutoRegister:r?.useAutoRegister}),{clientExtensionResults:c,...l}=s,u=await e(`/passkey/verify-registration`,{...r?.fetchOptions,...i,body:{response:l,name:r?.name,...r?.createSession&&{createSession:!0}},method:`POST`,throw:!1});return u.data?(t.set(Math.random()),u.data.session&&n.notify(`$sessionSignal`),r?.returnWebAuthnResponse?{...u,webauthn:{response:s,clientExtensionResults:c}}:u):u}catch(e){return e instanceof wc?e.code===`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`?{data:null,error:{code:e.code,message:gc.PREVIOUSLY_REGISTERED.message,status:400,statusText:`BAD_REQUEST`}}:e.code===`ERROR_CEREMONY_ABORTED`?{data:null,error:{code:e.code,message:gc.REGISTRATION_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}:{data:null,error:{code:e.code,message:e.message,status:400,statusText:`BAD_REQUEST`}}:{data:null,error:{code:`UNKNOWN_ERROR`,message:e instanceof Error?e.message:gc.UNKNOWN_ERROR.message,status:500,statusText:`INTERNAL_SERVER_ERROR`}}}}},$Infer:{}}),vne=()=>{let e=Uc();return{id:`passkey`,version:_c,$InferServerPlugin:{},getActions:(t,n)=>_ne(t,{$listPasskeys:e,$store:n}),getAtoms(t){return{listPasskeys:dte(e,`/passkey/list-user-passkeys`,t,{method:`GET`}),$listPasskeys:e}},pathMethods:{"/passkey/register":`POST`,"/passkey/authenticate":`POST`},atomListeners:[{matcher(e){return e===`/passkey/verify-registration`||e===`/passkey/delete-passkey`||e===`/passkey/update-passkey`||e===`/sign-out`},signal:`$listPasskeys`},{matcher:e=>e===`/passkey/verify-authentication`,signal:`$sessionSignal`}],$ERROR_CODES:gc}},yne=hc({OTP_EXPIRED:`OTP expired`,INVALID_OTP:`Invalid OTP`,TOO_MANY_ATTEMPTS:`Too many attempts`}),bne=()=>({id:`email-otp`,version:Fc,$InferServerPlugin:{},atomListeners:[{matcher:e=>e===`/email-otp/verify-email`||e===`/sign-in/email-otp`||e===`/email-otp/request-email-change`,signal:`$sessionSignal`}],$ERROR_CODES:yne}),xne=e=>{let t=e?.jwks?.jwksPath??`/jwks`;return{id:`better-auth-client`,version:Fc,$InferServerPlugin:{},pathMethods:{[t]:`GET`},getActions:(e,n,r)=>({jwks:async n=>await e(t,{method:`GET`,...n})})}},Sne=hc({OTP_NOT_ENABLED:`OTP not enabled`,OTP_NOT_CONFIGURED:`OTP is not available`,OTP_HAS_EXPIRED:`OTP has expired`,TOTP_NOT_ENABLED:`TOTP not enabled`,TOTP_ALREADY_ENABLED:`TOTP is already enabled`,TOTP_NOT_CONFIGURED:`TOTP is not available`,TWO_FACTOR_NOT_ENABLED:`Two factor isn't enabled`,BACKUP_CODES_NOT_ENABLED:`Backup codes aren't enabled`,INVALID_BACKUP_CODE:`Invalid backup code`,INVALID_CODE:`Invalid code`,TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:`Too many attempts. Please request a new code.`,ACCOUNT_TEMPORARILY_LOCKED:`Too many failed verification attempts. Your account is temporarily locked. Please try again later.`,INVALID_TWO_FACTOR_COOKIE:`Invalid two factor cookie`}),Cne=e=>({id:`two-factor`,version:Fc,$InferServerPlugin:{},atomListeners:[{matcher:e=>e.startsWith(`/two-factor/`),signal:`$sessionSignal`}],pathMethods:{"/two-factor/disable":`POST`,"/two-factor/enable":`POST`,"/two-factor/send-otp":`POST`,"/two-factor/generate-backup-codes":`POST`,"/two-factor/get-totp-uri":`POST`,"/two-factor/verify-totp":`POST`,"/two-factor/verify-otp":`POST`,"/two-factor/verify-backup-code":`POST`},fetchPlugins:[{id:`two-factor`,name:`two-factor`,hooks:{async onSuccess(t){if(t.data?.twoFactorRedirect){if(e?.onTwoFactorRedirect){await e.onTwoFactorRedirect({twoFactorMethods:t.data.twoFactorMethods});return}e?.twoFactorPage&&typeof window<`u`&&pl(e.twoFactorPage)&&(window.location.href=e.twoFactorPage)}}}}],$ERROR_CODES:Sne}),wne=(e,t,n)=>gne({baseURL:e,basePath:t,plugins:[xne(),bne(),Cne(),vne()],fetchOptions:{customFetchImpl:n}}),Ol=e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?JSON.parse(e):[],kl=e=>{let t=e.split(`,`);return t.includes(`owner`)?`owner`:t.includes(`admin`)?`admin`:`member`},Tne=e=>({id:e.id,userId:e.userId,name:e.user.name||e.user.email,email:e.user.email,role:kl(e.role),appRoles:Ol(e.appRoles),createdAt:new Date(e.createdAt).toISOString()}),Al=e=>({id:e.id,email:e.email,role:kl(e.role),appRoles:Ol(e.appRoles),status:e.status,expiresAt:new Date(e.expiresAt).toISOString(),...e.organizationName&&{organizationName:e.organizationName}}),Ene=(e,t)=>{let n=async(t,n,r={})=>{let{data:i,error:a}=await e.$fetch(t,{method:r.method??(r.body?`POST`:`GET`),...r.body&&{body:r.body},...r.query&&{query:r.query}});if(a)throw z(a,n);return i},r=async e=>(await t(),e);return{list:async()=>await n(`/organization/list`,`Could not read your organizations`)??[],current:()=>n(`/organization/current`,`Could not read the current organization`),switchTo:async e=>r(await n(`/organization/switch`,`Could not switch the organization`,{body:{organizationId:e}})),search:async e=>(await n(`/organization/search`,`Could not search the organizations`,{query:{query:e}})).organizations,create:async e=>r(await n(`/organization/create`,`Could not create the organization`,{body:e})),rename:(e,t)=>n(`/organization/update`,`Could not change the organization`,{body:{organizationId:e,data:t}}),remove:async e=>r(await n(`/organization/delete`,`Could not delete the organization`,{body:{organizationId:e}})),leave:async e=>r(await n(`/organization/leave`,`Could not leave the organization`,{body:{organizationId:e}})),members:async e=>(await n(`/organization/list-members`,`Could not read the members`,{query:{organizationId:e,limit:`1000`}})).members.map(Tne),setRole:(e,t,r)=>n(`/organization/update-member-role`,`Could not change the role`,{body:{organizationId:e,memberId:t,role:r}}),setAppRoles:(e,t)=>n(`/organization/set-app-roles`,`Could not change the app roles`,{body:{memberId:e,appRoles:t}}),removeMember:(e,t)=>n(`/organization/remove-member`,`Could not remove the member`,{body:{organizationId:e,memberIdOrEmail:t}}),transferOwnership:(e,t=`admin`)=>n(`/organization/transfer-ownership`,`Could not hand the organization over`,{body:{memberId:e,keepAs:t}}),invitations:async e=>(await n(`/organization/list-invitations`,`Could not read the invitations`,{query:{organizationId:e}})??[]).map(Al),invite:async(e,t)=>{let r=await n(`/organization/invite-member`,`Could not send the invitation`,{body:{organizationId:e,...t}});return{invitation:Al(r),...r.link&&{link:r.link}}},resend:async(e,t)=>{let r=await n(`/organization/invite-member`,`Could not send the invitation again`,{body:{organizationId:e,email:t.email,role:t.role,resend:!0}});return{invitation:Al(r),...r.link&&{link:r.link}}},revoke:e=>n(`/organization/cancel-invitation`,`Could not revoke the invitation`,{body:{invitationId:e}}),myInvitations:async()=>(await n(`/organization/list-user-invitations`,`Could not read your invitations`)??[]).map(Al),invitation:e=>n(`/invitation`,`This invitation link is not valid`,{query:{token:e}}),accept:async e=>r(await n(`/invitation/accept`,`Could not accept the invitation`,{body:{token:e}})),signUpFromInvitation:async(e,t)=>r(await n(`/invitation/sign-up`,`Could not create your account`,{body:{token:e,...t}}))}},Dne=(e,t)=>({current:async()=>{let{data:t,error:n}=await e.$fetch(`/role/current`,{method:`GET`});if(n)throw z(n,`Could not read your roles`);return t},switchTo:async n=>{let{error:r}=await e.$fetch(`/role/switch`,{method:`POST`,body:{role:n}});if(r)throw z(r,`Could not switch the role`);await t()}}),One=(e,t)=>{let n=async e=>e?.twoFactorRedirect?{kind:`two-factor`,methods:e.twoFactorMethods??[]}:(await t(),{kind:`signed-in`,user:e?.user});return{signIn:async(t,r)=>{let{data:i,error:a}=await e.signIn.email({email:t,password:r});if(a||!i)throw z(a,`Sign-in failed`);return n(i)},sendSignInCode:async t=>{let{error:n}=await e.emailOtp.sendVerificationOtp({email:t,type:`sign-in`});if(n)throw z(n,`Could not send the code`)},signInWithCode:async(t,r)=>{let{data:i,error:a}=await e.signIn.emailOtp({email:t,otp:r});if(a||!i)throw z(a,`Sign-in failed`);return n(i)},sendSignUpCode:async t=>{let{error:n}=await e.$fetch(`/sign-up/send-code`,{method:`POST`,body:{email:t}});if(n)throw z(n,`Could not send the code`)},verifySignUpCode:async(t,n)=>{let{data:r,error:i}=await e.$fetch(`/sign-up/verify-code`,{method:`POST`,body:{email:t,code:n}});if(i||!r)throw z(i,`Could not check the code`);return r.ticket},signUp:async n=>{let{data:r,error:i}=await e.$fetch(`/sign-up/create`,{method:`POST`,body:n});if(i||!r)throw z(i,`Could not create your account`);return await t(),r.user},signInWithPasskey:async n=>{let r=await e.$fetch(`/passkey/generate-authenticate-options`,{method:`GET`,...n&&{query:{rpId:n}}});if(r.error||!r.data)throw z(r.error,`Sign-in failed`);let{clientExtensionResults:i,...a}=await Pc({optionsJSON:r.data}).catch(e=>{throw new pc(`Auth cancelled`,400,e instanceof wc?e.code:`AUTH_CANCELLED`)}),o=await e.$fetch(`/passkey/verify-authentication`,{method:`POST`,body:{response:a}});if(o.error||!o.data)throw z(o.error,`Sign-in failed`);return await t(),o.data.user},sendTwoFactorCode:async()=>{let{error:t}=await e.twoFactor.sendOtp();if(t)throw z(t,`Could not send the code`)},verifyTwoFactor:async({method:n,code:r,trustDevice:i=!1})=>{let{data:a,error:o}=await(n===`totp`?e.twoFactor.verifyTotp:n===`otp`?e.twoFactor.verifyOtp:e.twoFactor.verifyBackupCode)({code:r,trustDevice:i});if(o||!a)throw z(o,`The code did not work`);return await t(),a.user}}},jl=e=>({read:async()=>{let{data:t,error:n}=await e.$fetch(`/policy/sign-in`);if(n||!t)throw z(n,`Could not read the sign-in policy`);return t},save:async t=>{let{data:n,error:r}=await e.$fetch(`/policy/sign-in`,{method:`POST`,body:t});if(r||!n)throw z(r,`Could not save the sign-in policy`);return n}}),Ml=e=>new Date(e).toISOString(),Nl=({startedAt:e,expiresAt:t,endedAt:n,...r})=>({...r,startedAt:Ml(e),expiresAt:Ml(t),...n&&{endedAt:Ml(n)}}),Pl=e=>({start:async t=>{let{data:n,error:r}=await e.$fetch(`/staff/sign-in`,{method:`POST`,body:t});if(r||!n?.url)throw z(r,`Could not start the staff sign-in`);return n.url},current:async()=>{let{data:t,error:n}=await e.$fetch(`/staff/session`);if(n||!t)throw z(n,`Could not read the session`);return t.staff?Nl(t.staff):void 0},stop:async()=>{let{error:t}=await e.$fetch(`/staff/stop`,{method:`POST`,body:{}});if(t)throw z(t,`Could not end the staff session`)},log:async()=>{let{data:t,error:n}=await e.$fetch(`/staff/sign-ins`);if(n||!t)throw z(n,`Could not read the staff sign-ins`);return t.signIns.map(Nl)}}),Fl=e=>{let t=e.split(`.`)[1];if(!t)throw Error(`Not a JWT`);let n=JSON.parse(atob(t.replace(/-/g,`+`).replace(/_/g,`/`)));if(typeof n.exp!=`number`)throw Error(`The token has no expiry`);return n.exp*1e3},Il=(e={})=>{let t=e.origin??globalThis.location?.origin??`http://localhost`,n=e.basePath??`/api/auth`,r=e.refreshMarginMs??6e4,i=e.fetch??((e,t)=>fetch(e,t)),a=wne(t,n,i),o=Pl(a),s,c,l,u=()=>{s=void 0,clearTimeout(l)},d=async()=>{let{data:t}=await a.$fetch(`/token`);if(!t?.token){u();return}return s={token:t.token,expiresAt:Fl(t.token)},clearTimeout(l),l=setTimeout(()=>void f({refresh:!0}).then(t=>t||e.onSignedOut?.()),Math.max(1e3,s.expiresAt-Date.now()-r)),s.token},f=async({refresh:e=!1}={})=>!e&&s&&s.expiresAt-Date.now()>r?s.token:(c??=d().finally(()=>{c=void 0}),c);return{token:f,status:async()=>{let e=await i(`${t}${n}/status`);if(e.status===404)throw new pc(`This server has no sign-in. Is the API URL right?`,404);if(!e.ok)throw new pc(`Could not read the sign-in status`,e.status);let r=await e.json();return{needsAdmin:!!r.needsAdmin,signInMethods:r.signInMethods??[`password`],passwordReset:!!r.passwordReset,...r.signUp&&{signUp:!0},socialProviders:r.socialProviders??[],...r.platformSignIn&&{platformSignIn:r.platformSignIn},...r.staffSignIn&&{staffSignIn:r.staffSignIn},...r.passkeyDomains&&{passkeyDomains:r.passkeyDomains},...r.organizations&&{organizations:r.organizations},...r.anonymous&&{anonymous:!0},...r.plugins&&r.plugins.length>0&&{plugins:r.plugins}}},session:async()=>{let{data:e}=await a.getSession();return e?.user},...One(a,()=>f({refresh:!0})),signInSocial:async(e,t)=>{let{data:n,error:r}=await a.signIn.social({provider:e,callbackURL:t,errorCallbackURL:t,disableRedirect:!0});if(r||!n?.url)throw z(r,`Sign-in failed`);return n.url},signOut:async()=>{u(),await a.signOut()},requestPasswordReset:async(e,t)=>{let{error:n}=await a.requestPasswordReset({email:e,redirectTo:t});if(n)throw z(n,`Could not send the reset link`)},resetPassword:async(e,t)=>{let{error:n}=await a.resetPassword({token:e,newPassword:t});if(n)throw z(n,`Could not set the password`)},account:mc(a),organizations:Ene(a,()=>f({refresh:!0})),roles:Dne(a,()=>f({refresh:!0})),signInPolicy:jl(a),staff:{...o,stop:async()=>{u(),await o.stop()}}}},Ll=e=>Math.min(3e4,1e3*2**e),Rl=(e,t)=>new Promise(n=>{let r=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(r),n()},{once:!0})}),zl=`http://same-origin.invalid`,Bl=(e,t)=>{let n=new URL(e,zl),r=new URL(t,`${n.href}/`);if(r.origin!==n.origin)throw Error(`${t} is not on the assistant backend's origin`);return n.origin===zl?`${r.pathname}${r.search}`:r.href},Vl=e=>{let t=e.url.replace(/\/+$/,``),n=e.fetch??((e,t)=>fetch(e,t)),r=e.retryDelayMs??Ll,i=async(r,i)=>{let a=await e.token(),o=await n(`${t}${r}`,{method:i.method,headers:{...i.body===void 0?{accept:`text/event-stream`}:{"content-type":`application/json`},...a&&{authorization:`Bearer ${a}`}},body:i.body===void 0?void 0:JSON.stringify(i.body),signal:i.signal});if(!o.ok)throw await Bs(o);return o},a=async(e,t,n)=>{let r=await i(`/events`,{method:`GET`,signal:e});if(!r.body)throw Error(`The assistant backend answered the event stream without a body`);n(),await ns(r.body,e=>t(JSON.parse(e)),e)};return{connect:(e,t)=>{let n=new AbortController,{signal:i}=n;return(async()=>{let n=0;for(;!i.aborted;){t?.({state:`connecting`});let o=await a(i,e,()=>{n=0,t?.({state:`open`})}).then(()=>void 0,e=>e??Error(`The assistant stream failed`));if(i.aborted)return;t?.({state:`retrying`,...o!==void 0&&{error:o}}),await Rl(r(n++),i)}})(),()=>n.abort()},send:async(e,t)=>{await i(`/messages`,{method:`POST`,body:{text:e,...t&&{page:t}}})},act:async(e,t)=>{await i(`/actions`,{method:`POST`,body:{partId:e,actionId:t}})},fetch:async(r,i={})=>{let a=Bl(t,r),o=await e.token(),s=new Headers(i.headers);o&&s.set(`authorization`,`Bearer ${o}`);let c=await n(a,{...i,headers:s});if(!c.ok)throw await Bs(c);return c}}},Hl=e=>typeof e==`object`&&!!e&&`error`in e&&typeof e.error==`object`&&e.error!==null&&`code`in e.error&&`message`in e.error,Ul=async e=>{let t=e.headers.get(`content-type`)?.includes(`json`)??!1?await e.clone().json():void 0;return Hl(t)?new Is({type:`urn:protobase:problem:${t.error.code}`,title:e.statusText||`Request failed`,status:e.status,detail:t.error.message}):Bs(e)},Wl=e=>{let t=e.url.replace(/\/+$/,``),n=e.fetch??((e,t)=>fetch(e,t)),r=async(r,i)=>{let a=await e.token(),o=await n(`${t}${r}`,{method:i,headers:{accept:`application/json`,...a&&{authorization:`Bearer ${a}`}}});if(!o.ok)throw await Ul(o);return await o.json()};return{status:()=>r(``,`GET`),update:()=>r(`/update`,`POST`)}},B=(...e)=>e.filter(Boolean).join(` `),Gl=e=>(0,o.useSyncExternalStore)(t=>{let n=window.matchMedia(e);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)},()=>window.matchMedia(e).matches,()=>!1),Kl=()=>Gl(`(min-width: 768px)`),ql=()=>Gl(`not all and (min-width: 640px)`),V=t(a(),1),Jl=e=>e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey,Yl=`flex min-h-[49px] min-w-0 flex-1 flex-col items-center justify-center gap-1 pb-1 pt-1.5 text-[10px] font-medium leading-none`,Xl=({tabs:e,onNavigate:t,onMore:n,moreOpen:r,moreControls:i,sticky:a,ref:o})=>{let s=!e.some(e=>e.active);return(0,V.jsxs)(`nav`,{ref:o,"aria-label":`Tabs`,className:B(`flex shrink-0 border-t bg-background pb-[env(safe-area-inset-bottom)] md:hidden`,a&&`sticky bottom-0 z-30`),children:[e.map(e=>{let n=e.icon;return(0,V.jsxs)(`a`,{href:e.href,"aria-current":e.active?`page`:void 0,...e.external?{target:`_blank`,rel:`noreferrer`}:{},onClick:n=>{!e.external&&t&&Jl(n)&&(n.preventDefault(),t(e.href))},className:B(Yl,e.active?`text-primary-text`:`text-muted-foreground`),children:[(0,V.jsx)(n,{className:`size-6`,strokeWidth:e.active?2.2:1.9,"aria-hidden":!0}),(0,V.jsx)(`span`,{className:`max-w-full truncate px-0.5`,children:e.label})]},e.id)}),(0,V.jsxs)(`button`,{type:`button`,"aria-expanded":r,"aria-controls":i,"data-current":s||void 0,onClick:n,className:B(Yl,s?`text-primary-text`:`text-muted-foreground`),children:[(0,V.jsx)(Xe,{className:`size-6`,strokeWidth:s?2.2:1.9,"aria-hidden":!0}),`More`]})]})},Zl=`data-pb-scroll-locked`,Ql=()=>{let{body:e,documentElement:t}=document,n=e.style.overflow,r=t.hasAttribute(Zl);return window.innerWidth>t.clientWidth&&t.setAttribute(Zl,``),e.style.overflow=`hidden`,()=>{e.style.overflow=n,r||t.removeAttribute(Zl)}},$l=`a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`,eu=[],tu=(e,t,n)=>{let r=(0,o.useRef)(n);r.current=n,(0,o.useEffect)(()=>{if(!t||!e.current)return;let n=e.current,i=document.activeElement instanceof HTMLElement?document.activeElement:null,a=Ql(),o={};eu.push(o);let s=()=>[...n.querySelectorAll($l)];(s()[0]??n).focus();let c=e=>{if(eu.at(-1)!==o)return;if(e.key===`Escape`)return r.current();if(e.key!==`Tab`)return;let t=s();if(t.length===0)return e.preventDefault();let i=t[0],a=t[t.length-1];e.shiftKey&&document.activeElement===i?(e.preventDefault(),a.focus()):!e.shiftKey&&document.activeElement===a?(e.preventDefault(),i.focus()):n.contains(document.activeElement)||(e.preventDefault(),i.focus())};return document.addEventListener(`keydown`,c),()=>{document.removeEventListener(`keydown`,c),eu.splice(eu.indexOf(o),1),a(),i?.focus()}},[t,e])},nu=({id:e,open:t,onClose:n,children:r})=>{let i=(0,o.useRef)(null);return tu(i,t,n),t?(0,V.jsxs)(`div`,{className:`fixed inset-0 z-50 md:hidden`,children:[(0,V.jsx)(`div`,{className:`absolute inset-0 bg-backdrop/40`,onClick:n,"aria-hidden":!0}),(0,V.jsx)(`div`,{ref:i,id:e,role:`dialog`,"aria-modal":`true`,"aria-label":`Navigation`,tabIndex:-1,className:`absolute inset-y-0 left-0 flex w-60 max-w-[85vw] bg-sidebar shadow-pop outline-none`,onClick:e=>e.target.closest(`a`)&&n(),children:r})]}):null},ru=(0,o.createContext)(()=>{}),iu=e=>{let t=(0,o.useContext)(ru);(0,o.useLayoutEffect)(()=>(t(e),()=>t(void 0)),[t,e])},au=e=>{(0,o.useLayoutEffect)(()=>{if(!e)return;let t=document.documentElement;return t.style.setProperty(`scrollbar-gutter`,`stable`),()=>{t.style.removeProperty(`scrollbar-gutter`)}},[e])},ou=[`--pb-sticky-top`,`--pb-sticky-bottom`,`scroll-padding-top`,`scroll-padding-bottom`],su=(e,t,n,r)=>{(0,o.useLayoutEffect)(()=>{if(!e)return;let r=document.documentElement,i=()=>{let e=`${t.current?.offsetHeight??0}px`,i=`${n.current?.offsetHeight??0}px`;r.style.setProperty(`--pb-sticky-top`,e),r.style.setProperty(`--pb-sticky-bottom`,i),r.style.setProperty(`scroll-padding-top`,e),r.style.setProperty(`scroll-padding-bottom`,i)},a=new ResizeObserver(i);for(let e of[t.current,n.current])e&&a.observe(e);return i(),()=>{a.disconnect();for(let e of ou)r.style.removeProperty(e)}},[e,t,n,r])},cu=({className:e})=>(0,V.jsx)(`span`,{className:B(`block h-3 rounded bg-muted [animation:pb-shimmer_1.4s_ease-in-out_infinite]`,e)}),lu=e=>e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey,uu=({parts:e,onNavigate:t})=>(0,V.jsx)(`nav`,{"aria-label":`Breadcrumb`,className:`flex min-w-0 items-center gap-1.5`,children:e.map((n,r)=>{let i=r===e.length-1,{label:a,href:o,loading:s}=typeof n==`string`?{label:n,href:void 0,loading:!1}:n,c=s?(0,V.jsx)(cu,{className:`w-24`}):a,l=B(`truncate`,i?`font-semibold`:`text-muted-foreground`);return(0,V.jsxs)(`span`,{className:B(`min-w-0 items-center gap-1.5`,i?`flex`:`hidden md:flex`),children:[r>0&&(0,V.jsx)(Se,{className:`hidden size-3.5 shrink-0 text-faint-foreground md:block`}),o?(0,V.jsx)(`a`,{href:o,"aria-current":i?`page`:void 0,"aria-label":s?a:void 0,"aria-busy":s||void 0,onClick:e=>{t&&lu(e)&&(e.preventDefault(),t(o))},className:B(l,`rounded-sm hover:text-foreground hover:underline`),children:c}):(0,V.jsx)(`span`,{className:l,"aria-label":s?a:void 0,"aria-busy":s||void 0,children:c})]},`${r}-${a}`)})}),du=({to:e,onClick:t,...n})=>(0,V.jsx)(`a`,{href:e.href,onClick:n=>{t?.(n),!n.defaultPrevented&&lu(n)&&(n.preventDefault(),e.onFollow())},...n}),fu=`M312.3 9.9Q257 9.9 217.1 -21.1Q177.3 -52.1 168.4 -108.8L181.1 -110.3V205H54.8V-510H176.7V-404.5L168.3 -407Q179.7 -460.8 221.2 -490.4Q262.7 -520 319.8 -520Q376.2 -520 417 -488.4Q457.8 -456.8 479.8 -398.6Q501.8 -340.5 501.8 -259.9Q501.8 -177.6 478.3 -116.8Q454.9 -55.9 412.5 -23Q370.1 9.9 312.3 9.9ZM274.4 -92.6Q320.2 -92.6 345.8 -133.8Q371.4 -175.1 371.4 -256.4Q371.4 -337.7 345.7 -377.6Q320.1 -417.5 274 -417.5Q228.6 -417.5 202.7 -376.4Q176.9 -335.3 176.9 -254Q176.9 -173.3 202.7 -132.9Q228.4 -92.6 274.4 -92.6Z M549.8 0V-510H671.7V-388.3H676.1V0H549.8ZM676.1 -286.5 661.3 -386.2Q677.9 -455.2 711.8 -487.6Q745.7 -520 794.3 -520Q809 -520 818 -516.6V-394.2Q814.2 -395.6 807.1 -396.1Q800 -396.6 789.4 -396.6Q734.6 -396.6 705.3 -370.5Q676.1 -344.4 676.1 -286.5Z M1043.8 10Q974.7 10 922.6 -23.6Q870.6 -57.2 842.1 -117.5Q813.6 -177.8 813.6 -257Q813.6 -336.5 842.2 -395.5Q870.8 -454.5 922.5 -487.2Q974.2 -520 1043.8 -520Q1113.7 -520 1165.4 -487.2Q1217.1 -454.5 1245.6 -395.5Q1274 -336.5 1274 -257Q1274 -177.8 1245.5 -117.5Q1217 -57.2 1165.3 -23.6Q1113.6 10 1043.8 10ZM1043.8 -90.5Q1073.5 -90.5 1095.9 -108.9Q1118.2 -127.3 1130.9 -164.4Q1143.6 -201.5 1143.6 -257.5Q1143.6 -339.8 1116 -379.7Q1088.4 -419.5 1043.8 -419.5Q999.3 -419.5 971.6 -379.5Q944 -339.5 944 -257.5Q944 -201.5 956.7 -164.4Q969.4 -127.3 991.8 -108.9Q1014.3 -90.5 1043.8 -90.5Z M1509 10.2Q1427.2 10.2 1387.6 -29.2Q1348 -68.6 1348 -147.7V-613.8L1474.2 -666.1V-146.7Q1474.2 -118.4 1489.9 -104.3Q1505.6 -90.3 1539.2 -90.3Q1552 -90.3 1562.7 -92.5Q1573.3 -94.8 1582.5 -98.7V-1.9Q1571.6 4 1552 7.1Q1532.4 10.2 1509 10.2ZM1270.1 -411V-510H1580.6V-411H1270.1Z M1810.8 10Q1741.7 10 1689.6 -23.6Q1637.6 -57.2 1609.1 -117.5Q1580.6 -177.8 1580.6 -257Q1580.6 -336.5 1609.2 -395.5Q1637.8 -454.5 1689.5 -487.2Q1741.2 -520 1810.8 -520Q1880.7 -520 1932.4 -487.2Q1984.1 -454.5 2012.6 -395.5Q2041 -336.5 2041 -257Q2041 -177.8 2012.5 -117.5Q1984 -57.2 1932.3 -23.6Q1880.6 10 1810.8 10ZM1810.8 -90.5Q1840.5 -90.5 1862.9 -108.9Q1885.2 -127.3 1897.9 -164.4Q1910.6 -201.5 1910.6 -257.5Q1910.6 -339.8 1883 -379.7Q1855.4 -419.5 1810.8 -419.5Q1766.3 -419.5 1738.6 -379.5Q1711 -339.5 1711 -257.5Q1711 -201.5 1723.7 -164.4Q1736.4 -127.3 1758.8 -108.9Q1781.3 -90.5 1810.8 -90.5Z M2343.3 9.9Q2288 9.9 2247.7 -21.1Q2207.4 -52.1 2198.5 -108.8L2205.8 -110.3V0H2085.8V-720H2212.1V-404.5L2203.7 -407Q2215.1 -460.8 2255.6 -490.4Q2296.2 -520 2351 -520Q2407.3 -520 2448 -488.4Q2488.8 -456.8 2510.8 -398.6Q2532.8 -340.5 2532.8 -259.9Q2532.8 -177.6 2509.3 -116.8Q2485.9 -55.9 2443.5 -23Q2401.1 9.9 2343.3 9.9ZM2305.4 -92.6Q2350.7 -92.6 2376.6 -133.8Q2402.4 -175.1 2402.4 -256.4Q2402.4 -337.7 2376.5 -377.6Q2350.6 -417.5 2305 -417.5Q2260.5 -417.5 2234.2 -376.4Q2207.9 -335.3 2207.9 -254Q2207.9 -173.3 2234.1 -132.9Q2260.3 -92.6 2305.4 -92.6Z M2834 0Q2828 -19.1 2825.7 -41.7Q2823.3 -64.2 2823.3 -91.8H2818.6V-356Q2818.6 -391.9 2803.1 -409.1Q2787.5 -426.3 2756.2 -426.3Q2724.2 -426.3 2706.4 -408.7Q2688.7 -391.2 2686.3 -358.9H2571.2Q2574.6 -429.6 2625.4 -474.8Q2676.1 -520 2763.5 -520Q2850.2 -520 2896.1 -476.5Q2941.9 -432.9 2941.9 -352.2V-91.8Q2941.9 -69.5 2944.7 -46.7Q2947.5 -23.8 2954.1 0H2834ZM2690.6 10Q2631.9 10 2595.4 -26.3Q2558.9 -62.5 2558.9 -124.5Q2558.9 -185 2594.3 -224Q2629.8 -263 2704.5 -287.6L2845.4 -337.4V-248.7L2753.4 -219.3Q2716.5 -206.1 2699.3 -186.6Q2682.2 -167.2 2682.2 -139Q2682.2 -112.4 2697.5 -98.4Q2712.9 -84.3 2739.4 -84.3Q2773.2 -84.3 2795.9 -104.1Q2818.6 -123.9 2818.6 -153.1L2829.9 -85.8Q2812.6 -37.4 2776.8 -13.7Q2741 10 2690.6 10Z M3168 10Q3080.6 10 3030.1 -34.2Q2979.6 -78.4 2974.7 -158.1H3082.4Q3086.3 -120 3108.9 -100.5Q3131.5 -80.9 3169.8 -80.9Q3202 -80.9 3218.9 -93.9Q3235.8 -106.9 3235.8 -131.3Q3235.8 -151.1 3224.3 -165.6Q3212.9 -180.1 3178.9 -195.4L3111.2 -224.8Q3053 -247.7 3023.8 -284.2Q2994.5 -320.8 2994.5 -373.9Q2994.5 -440.1 3040.1 -480Q3085.7 -520 3162.8 -520Q3242.2 -520 3288.4 -480Q3334.6 -440 3339.5 -367.9H3231.8Q3228.6 -399.7 3211.3 -414.4Q3194 -429.1 3164 -429.1Q3136.1 -429.1 3120.5 -417Q3104.8 -405 3104.8 -382.7Q3104.8 -364.2 3117.7 -349.8Q3130.6 -335.5 3162.4 -321.6L3236.6 -289.6Q3288.6 -269.2 3317.4 -229.2Q3346.1 -189.1 3346.1 -136.9Q3346.1 -69 3299.2 -29.5Q3252.3 10 3168 10Z M3587.8 10Q3520 10 3469.2 -23.3Q3418.5 -56.6 3390.5 -116.5Q3362.6 -176.3 3362.6 -255.8Q3362.6 -336.4 3390.9 -395.7Q3419.3 -454.9 3470.7 -487.5Q3522 -520 3591.1 -520Q3656.6 -520 3702.7 -489.8Q3748.8 -459.7 3773.7 -403.1Q3798.6 -346.5 3798.6 -266.5Q3798.6 -253.7 3798 -242.5Q3797.5 -231.3 3795.8 -221.4H3440V-306.9H3709L3681.8 -277.9Q3681.6 -355.2 3657.7 -390.7Q3633.8 -426.3 3589.3 -426.3Q3541.7 -426.3 3515.6 -384Q3489.5 -341.7 3489.5 -255Q3489.5 -168.4 3515 -126.1Q3540.5 -83.7 3590.6 -83.7Q3623.7 -83.7 3644.6 -102Q3665.5 -120.3 3673.8 -156.3H3788.9Q3772.2 -81.6 3721.5 -35.8Q3670.8 10 3587.8 10Z`,pu=`fill-[#ff5a1f] dark:fill-[#ff6a33]`,mu=`fill-[#14161a] dark:fill-[#f1f0ea]`,hu=({className:e})=>(0,V.jsxs)(`svg`,{viewBox:`0 0 32 32`,className:B(`size-7 shrink-0`,e),"aria-hidden":!0,children:[(0,V.jsx)(`path`,{className:pu,fillRule:`evenodd`,d:`M0 5a5 5 0 0 1 5-5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2zM4 5a1 1 0 0 1 1-1h5v6H4z`}),(0,V.jsx)(`path`,{className:mu,d:`M17 0h10a5 5 0 0 1 5 5v22a5 5 0 0 1-5 5H5a5 5 0 0 1-5-5V17h17z`})]}),gu=({className:e})=>(0,V.jsx)(`svg`,{viewBox:`54.8 -720 3743.8 925`,className:B(`h-3.5 w-auto`,e),role:`img`,"aria-label":`Protobase`,children:(0,V.jsx)(`path`,{className:mu,d:fu})}),_u=`Protobase`,vu=({compact:e,workspace:t,appName:n})=>(0,V.jsxs)(`div`,{className:`flex items-center gap-2.5 overflow-hidden`,children:[(0,V.jsx)(hu,{}),!e&&(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5 leading-tight`,children:[n&&n!==_u?(0,V.jsx)(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:n}):(0,V.jsx)(gu,{className:`self-start`}),t&&(0,V.jsx)(`div`,{className:`truncate text-[11px] text-muted-foreground`,children:t})]})]}),yu=[{label:`Sales`,items:[{id:`orders`,label:`Orders`,icon:xn,count:12},{id:`customers`,label:`Customers`,icon:ue},{id:`invoices`,label:`Invoices`,icon:ot,count:3}]},{label:`Inventory`,items:[{id:`products`,label:`Products`,icon:Qt},{id:`stock-moves`,label:`Stock moves`,icon:ce},{id:`warehouses`,label:`Warehouses`,icon:Zn},{id:`shipments`,label:`Shipments`,icon:Un}]},{label:`Finance`,items:[{id:`payments`,label:`Payments`,icon:Be},{id:`credit-notes`,label:`Credit notes`,icon:ln},{id:`reports`,label:`Reports`,icon:me}]},{label:`Admin`,items:[{id:`users`,label:`Users`,icon:Jn},{id:`settings`,label:`Settings`,icon:_n}]}],bu={xs:`size-5 text-[9px]`,sm:`size-6 text-[10px]`,md:`size-8 text-xs`},xu=({initials:e,hue:t,size:n=`sm`,className:r})=>(0,V.jsx)(`span`,{className:B(`inline-flex shrink-0 select-none items-center justify-center rounded-full font-semibold text-white ring-2 ring-background`,bu[n],r),style:{background:`oklch(0.58 0.13 ${t})`},children:e}),Su=({people:e,size:t=`sm`})=>(0,V.jsx)(`span`,{className:`inline-flex -space-x-1`,children:e.map(e=>(0,V.jsx)(xu,{...e,size:t},e.initials))}),Cu=e=>{let t=e.slice(1),n=t.length===3?[...t].map(e=>e+e).join(``):t,[r,i,a]=[0,2,4].map(e=>{let t=Number.parseInt(n.slice(e,e+2),16)/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},wu=`#ffffff`,Tu=`#111827`,Eu=e=>{let t=Cu(e);return 1.05/(t+.05)>=(t+.05)/(Cu(Tu)+.05)?wu:Tu},Du={neutral:`bg-muted text-muted-foreground`,blue:`bg-primary-soft text-primary-text`,green:`bg-success-soft text-success-text`,amber:`bg-warning-soft text-warning-text`,red:`bg-danger-soft text-danger-text`,violet:`bg-violet-soft text-violet-text`},Ou={neutral:`bg-faint-foreground`,blue:`bg-primary`,green:`bg-success`,amber:`bg-warning`,red:`bg-danger`,violet:`bg-violet`},ku=`polygon(0 0, calc(100% - 0.625rem) 0, 100% 50%, calc(100% - 0.625rem) 100%, 0 100%)`,Au=({tone:e=`neutral`,dot:t=!0,color:n,shape:r,children:i,className:a})=>(0,V.jsxs)(`span`,{style:{...n!==void 0&&{backgroundColor:n,color:Eu(n)},...r===`arrow`&&{clipPath:ku}},className:B(r===`arrow`?`inline-flex h-5 items-center gap-1.5 rounded-l-sm pr-4 pl-2 text-xs font-semibold whitespace-nowrap`:`inline-flex h-5 items-center gap-1.5 rounded-full px-2 text-xs font-medium whitespace-nowrap`,n===void 0&&Du[e],a),children:[t&&n===void 0&&r===void 0&&(0,V.jsx)(`span`,{className:B(`size-1.5 rounded-full`,Ou[e])}),i]}),ju=({label:e,current:t,others:n,rowClassName:r,onSwitch:i})=>(0,V.jsxs)(`div`,{className:`border-b py-1`,role:`group`,"aria-label":e,children:[t&&(0,V.jsxs)(`div`,{className:B(r,`text-foreground hover:bg-transparent`),"aria-current":`true`,children:[(0,V.jsx)(ge,{className:`size-4`}),(0,V.jsx)(`span`,{className:`truncate`,children:t.label})]}),n.map(e=>(0,V.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>i(e.id),className:r,children:[(0,V.jsx)(`span`,{className:`size-4`}),(0,V.jsx)(`span`,{className:`truncate`,children:e.label})]},e.id))]}),Mu={sm:{group:`h-7`,option:`px-2.5 text-xs`},md:{group:`h-8`,option:`px-3 text-body`}},Nu={group:(e=`sm`)=>B(`inline-flex`,Mu[e].group,`rounded-md bg-muted p-0.5`),option:(e,t=`sm`)=>B(`inline-flex items-center gap-1.5 rounded`,Mu[t].option,`font-medium transition-colors`,e?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`)},Pu=({value:e,options:t,onChange:n,label:r,size:i=`sm`,iconOnly:a=!1})=>(0,V.jsx)(`span`,{role:`group`,"aria-label":r,className:Nu.group(i),children:t.map(t=>(0,V.jsxs)(`button`,{type:`button`,"aria-pressed":t.value===e,...a&&{"aria-label":t.label,title:t.label},onClick:()=>n(t.value),className:Nu.option(t.value===e,i),children:[t.icon&&(0,V.jsx)(t.icon,{className:`size-3.5`}),!a&&t.label]},t.value))}),Fu=[{value:`light`,label:`Light`,icon:jn},{value:`dark`,label:`Dark`,icon:Jt},{value:`system`,label:`System`,icon:Kt}],Iu=({theme:e,className:t})=>(0,V.jsxs)(`div`,{className:t,children:[(0,V.jsx)(kn,{className:`size-4`}),(0,V.jsx)(`span`,{className:`flex-1`,children:`Theme`}),(0,V.jsx)(Pu,{label:`Theme`,iconOnly:!0,value:e.preference,options:Fu,onChange:e.onChange})]}),Lu=`flex min-h-11 w-full items-center gap-2.5 px-3 py-1.5 text-left text-muted-foreground hover:bg-muted md:min-h-0`,Ru=({user:e,compact:t,open:n,items:r=[],onNavigate:i,onSignOut:a,organizations:s,roles:c,theme:l})=>{let u=c?.roles.find(e=>e.name===c.active),[d,f]=(0,o.useState)(!1),p=n??d,m=(0,o.useRef)(null),[h,g]=(0,o.useState)();return(0,o.useEffect)(()=>{if(!p||n!==void 0)return;let e=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!m.current?.contains(e.target))&&f(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,e)}},[p,n]),(0,V.jsxs)(`div`,{ref:m,className:`relative`,children:[(0,V.jsxs)(`button`,{type:`button`,className:`flex min-h-11 w-full items-center gap-2.5 rounded-md p-1 text-left hover:bg-muted md:min-h-0`,"aria-label":`Profile menu`,"aria-haspopup":`menu`,"aria-expanded":p,onClick:()=>{let e=m.current?.getBoundingClientRect();e&&g({left:e.left,bottom:window.innerHeight-e.top+8}),f(!d)},children:[(0,V.jsx)(xu,{initials:e.initials,hue:e.hue,size:`md`,className:`ring-0`}),!t&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1 leading-tight`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.name}),(0,V.jsx)(Au,{tone:e.roleTone,dot:!1,className:`mt-0.5 h-4 px-1.5 text-[10px]`,children:e.role})]}),(0,V.jsx)(we,{className:`size-3.5 shrink-0 text-faint-foreground`})]})]}),p&&(0,V.jsxs)(`div`,{role:`menu`,className:n===void 0?`fixed z-[60] w-56 overflow-hidden rounded-lg border bg-background py-1 shadow-pop`:`absolute bottom-full left-0 z-50 mb-2 w-56 overflow-hidden rounded-lg border bg-background py-1 shadow-pop`,style:n===void 0&&h?{left:h.left,bottom:h.bottom}:void 0,children:[(0,V.jsxs)(`div`,{className:`border-b px-3 pb-2 pt-1.5`,children:[(0,V.jsx)(`div`,{className:`font-medium`,children:e.name}),(0,V.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e.email})]}),s&&(s.current||s.others.length>0)&&(0,V.jsx)(ju,{label:`Organizations`,...s.current&&{current:{id:s.current.id,label:s.current.name}},others:s.others.map(({id:e,name:t})=>({id:e,label:t})),rowClassName:Lu,onSwitch:e=>{f(!1),s.onSwitch(e)}}),c&&c.roles.length>1&&(0,V.jsx)(ju,{label:`Roles`,...u&&{current:{id:u.name,label:u.label}},others:c.roles.filter(e=>e!==u).map(({name:e,label:t})=>({id:e,label:t})),rowClassName:Lu,onSwitch:e=>{f(!1),c.onSwitch(e)}}),r.length>0&&(0,V.jsx)(`div`,{className:B((l||a)&&`border-b`),children:r.map(e=>{let t=e.icon;return(0,V.jsxs)(`a`,{role:`menuitem`,href:e.href,"aria-current":e.active?`page`:void 0,...e.external?{target:`_blank`,rel:`noreferrer`}:{},onClick:t=>{f(!1),!e.external&&i&&(t.preventDefault(),i(e.href))},className:B(Lu,e.active&&`bg-muted text-foreground`),children:[(0,V.jsx)(t,{className:`size-4`}),e.label]},e.id)})}),l&&(0,V.jsx)(`div`,{className:B(a&&`border-b`),children:(0,V.jsx)(Iu,{theme:l,className:B(Lu,`hover:bg-transparent`)})}),a&&(0,V.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:a,className:Lu,children:[(0,V.jsx)(Rt,{className:`size-4`}),`Sign out`]})]})]})},zu=(e,t)=>{try{return e()}catch(e){if(!(e instanceof DOMException))throw e;return t}},Bu=`protobase:nav-open:`,Vu=e=>`${Bu}${e}`,Hu=(e,t)=>zu(()=>e.getItem(t)!==`false`,!0),Uu=(e,t,n)=>zu(()=>n?e.removeItem(t):e.setItem(t,`false`),void 0),Wu=({label:e,side:t=`right`,visible:n,children:r})=>(0,V.jsxs)(`span`,{className:`group/tooltip relative inline-flex`,children:[r,(0,V.jsx)(`span`,{role:`tooltip`,className:B(`pointer-events-none absolute z-50 whitespace-nowrap rounded-md bg-foreground px-2 py-1 text-xs font-medium text-background opacity-0 shadow-md transition-opacity group-hover/tooltip:opacity-100`,n&&`opacity-100`,t===`right`&&`left-full top-1/2 ml-2 -translate-y-1/2`,t===`top`&&`bottom-full left-1/2 mb-2 -translate-x-1/2`,t===`bottom`&&`left-1/2 top-full mt-2 -translate-x-1/2`),children:e})]}),Gu=e=>e===`text-large`||e===`text-small`||e===`icon-expand`,Ku=e=>e===`text-large`||e===`text-small`,qu={"text-large":`w-60`,"text-small":`w-52`,icon:`w-14`,"icon-label":`w-[76px]`,"icon-tooltip":`w-14`,"icon-expand":`w-14`},Ju={"text-large":`h-9 gap-3 px-3 text-sm`,"text-small":`h-7 gap-2.5 px-2.5 text-xs`,icon:`size-9 justify-center`,"icon-label":`w-full flex-col gap-0.5 py-1.5 text-[10px]`,"icon-tooltip":`size-9 justify-center`,"icon-expand":`h-8 gap-3 px-3`},Yu=({item:e,mode:t,active:n,onNavigate:r,className:i})=>{let a=e.icon,o=(0,V.jsxs)(`a`,{onClick:r&&(t=>{t.preventDefault(),r(e.href??`#${e.id}`)}),href:e.href??`#${e.id}`,"aria-label":e.problem?`${e.label}: ${e.problem}`:e.label,"aria-current":n?`page`:void 0,title:e.problem,className:B(`flex shrink-0 items-center rounded-md font-medium transition-colors`,Ju[t],n?`bg-primary-soft text-primary-text`:`text-muted-foreground hover:bg-muted hover:text-foreground`,i),children:[(0,V.jsx)(a,{className:B(`shrink-0`,t===`text-small`?`size-4`:`size-[18px]`),strokeWidth:n?2.2:1.9}),(Gu(t)||t===`icon-label`)&&(0,V.jsx)(`span`,{className:`whitespace-nowrap`,children:e.label}),Ku(t)&&e.count&&(0,V.jsx)(`span`,{className:`ml-auto rounded bg-muted px-1.5 text-[11px] tabular-nums text-muted-foreground`,children:e.count}),Ku(t)&&e.problem&&(0,V.jsx)(Vn,{"aria-hidden":!0,className:`ml-auto size-3.5 shrink-0 text-warning-text`})]});return t===`icon-tooltip`?(0,V.jsx)(Wu,{label:e.label,children:o}):o},Xu={neutral:`bg-faint-foreground`,info:`bg-primary`,success:`bg-success`,warning:`bg-warning`,danger:`bg-danger`},Zu=({tone:e,pulse:t=!1,className:n})=>(0,V.jsxs)(`span`,{"aria-hidden":!0,className:B(`relative flex size-2 shrink-0`,n),"data-tone":e,"data-pulse":t||void 0,children:[t&&(0,V.jsx)(`span`,{className:B(`absolute inset-0 animate-ping rounded-full opacity-60 motion-reduce:animate-none`,Xu[e])}),(0,V.jsx)(`span`,{className:B(`relative size-2 rounded-full`,Xu[e])})]}),Qu={"text-large":`h-8 gap-2.5 px-2.5`,"text-small":`h-7 gap-2 px-2 text-xs`},$u={"text-large":`ml-[20px]`,"text-small":`ml-[17px]`},ed=({item:e,recent:t,mode:n,active:r,onNavigate:i})=>{let a=Vu(e.id),[s,c]=(0,o.useState)(()=>Hu(localStorage,a)),l=(0,o.useId)(),u=e.href??`#${e.id}`,d=()=>{Uu(localStorage,a,!s),c(!s)},f=e=>({href:e,onClick:i&&(t=>{t.preventDefault(),i(e)})});return(0,V.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,V.jsxs)(`div`,{className:`relative`,children:[(0,V.jsx)(Yu,{item:e,mode:n,active:r,onNavigate:i,className:`pr-8`}),(0,V.jsx)(`button`,{type:`button`,"aria-expanded":s,"aria-controls":l,"aria-label":`Recent ${e.label.toLowerCase()}`,onClick:d,className:`absolute right-1 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground`,children:(0,V.jsx)(Se,{className:B(`size-3.5 transition-transform`,s&&`rotate-90`)})})]}),s&&(0,V.jsxs)(`ul`,{id:l,"aria-label":`Recent ${e.label.toLowerCase()}`,className:B(`flex flex-col gap-0.5 border-l pl-1.5`,$u[n]),children:[t.state===`loading`&&(0,V.jsx)(`li`,{className:B(`flex items-center text-faint-foreground`,Qu[n]),children:`Loading...`}),t.state===`error`&&(0,V.jsx)(`li`,{className:B(`flex items-center text-faint-foreground`,Qu[n]),children:`Could not load`}),t.state===`ready`&&t.records.map(e=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(`a`,{...f(e.href),"aria-label":`${e.label}, ${e.status}`,title:`${e.label} (${e.status})`,"aria-current":e.active?`page`:void 0,className:B(`flex min-w-0 items-center rounded-md font-medium transition-colors`,Qu[n],e.active?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:[(0,V.jsx)(Zu,{tone:e.tone,pulse:e.pulse}),(0,V.jsx)(`span`,{className:`truncate`,children:e.label})]})},e.id)),(0,V.jsx)(`li`,{children:(0,V.jsx)(`a`,{...f(u),className:B(`flex items-center rounded-md text-faint-foreground transition-colors hover:bg-muted hover:text-foreground`,Qu[n]),children:`View all`})})]})]})},td=({mode:e,activeItem:t,user:n,workspace:r,appName:i,forceExpanded:a,profileMenuOpen:o,groups:s=yu,userMenu:c,onNavigate:l,onSignOut:u,signIn:d,organizations:f,roles:p,theme:m,sticky:h,logo:g=vu})=>{let _=e===`icon-expand`,v=_&&a,y=Ku(e)||_;return(0,V.jsx)(`nav`,{"aria-label":`Resources`,className:B(h?`sticky top-0 h-dvh self-start`:`relative`,`z-30 shrink-0`,qu[e]),children:(0,V.jsxs)(`div`,{className:B(`group/side absolute inset-y-0 left-0 flex flex-col overflow-hidden border-r bg-sidebar`,_?`w-14 transition-[width,box-shadow] duration-150 hover:w-60 hover:shadow-pop focus-within:w-60 focus-within:shadow-pop`:`w-full`,v&&`w-60 shadow-pop`),children:[(0,V.jsx)(`div`,{className:B(`flex h-12 shrink-0 items-center px-3.5`,e===`icon-label`&&`justify-center px-0`),children:(0,V.jsx)(g,{compact:!y,workspace:r,appName:i})}),(0,V.jsx)(`div`,{className:B(`flex-1 overflow-y-auto overflow-x-hidden pb-2`,`px-2`),children:s.map((n,r)=>(0,V.jsxs)(`div`,{className:B(`flex flex-col gap-0.5`,r>0&&`mt-3`),children:[y?(0,V.jsx)(`div`,{className:B(`px-3 pb-1 pt-1 text-[11px] font-medium uppercase tracking-wide text-faint-foreground`,_&&`h-4 whitespace-nowrap py-0 opacity-0 transition-opacity group-hover/side:opacity-100 group-focus-within/side:opacity-100`,v&&`opacity-100`),children:n.label}):r>0&&(0,V.jsx)(`div`,{className:`mx-auto mb-1 h-px w-6 bg-border`}),n.items.map(n=>n.recent&&Ku(e)?(0,V.jsx)(ed,{item:n,recent:n.recent,mode:e,active:n.id===t,onNavigate:l},n.id):(0,V.jsx)(Yu,{item:n,mode:e,active:n.id===t,onNavigate:l},n.id))]},n.label))}),(0,V.jsx)(`div`,{className:B(`shrink-0 border-t p-2`,e!==`text-large`&&e!==`text-small`&&!_&&`flex justify-center`),children:n?(0,V.jsx)(Ru,{user:n,compact:!y,open:o,items:c,onNavigate:l,onSignOut:u,organizations:f,roles:p,theme:m}):(0,V.jsxs)(V.Fragment,{children:[m&&y&&(0,V.jsx)(Iu,{theme:m,className:`flex min-h-11 w-full items-center gap-2.5 whitespace-nowrap p-1.5 text-muted-foreground md:min-h-0`}),d&&(0,V.jsxs)(du,{to:d,"aria-label":`Sign in`,className:`flex min-h-11 w-full items-center gap-2.5 rounded-md p-1.5 text-left font-medium text-muted-foreground hover:bg-muted hover:text-foreground md:min-h-0`,children:[(0,V.jsx)(It,{className:`size-4 shrink-0`}),y&&(0,V.jsx)(`span`,{className:`whitespace-nowrap`,children:`Sign in`})]})]})})]})})},nd=(0,o.createContext)(null),rd=()=>(0,o.useContext)(nd),id=e=>{let t=e.at(-2);if(typeof t==`object`&&t.href&&!t.loading)return{label:t.label,href:t.href}},ad=(0,o.createContext)(void 0),od=()=>{let e=(0,o.useContext)(ad);return e?{id:e.id,name:e.name,"aria-describedby":e.describedBy,"aria-invalid":e.invalid||void 0,"aria-required":e.required||void 0}:{}},sd=({leading:e,trailing:t,invalid:n,className:r,wrapperClassName:i,...a})=>{let o=od();return(0,V.jsxs)(`span`,{className:B(`flex h-8 items-center gap-2 rounded-md border bg-background px-2.5 text-muted-foreground shadow-sm focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20`,n?`border-danger`:`border-border-strong`,i),children:[e,(0,V.jsx)(`input`,{className:B(`min-w-0 flex-1 bg-transparent text-body text-foreground outline-none placeholder:text-faint-foreground`,r),...o,...n&&{"aria-invalid":!0},...a}),t]})},cd=({children:e})=>(0,V.jsx)(`kbd`,{className:`inline-flex h-5 items-center rounded border border-border-strong bg-background px-1.5 font-sans text-[11px] font-medium text-muted-foreground`,children:e}),ld=({className:e})=>(0,V.jsx)(Mt,{"aria-label":`Loading`,className:B(`size-4 animate-spin`,e)}),ud=(e,t,n)=>t===0?-1:e<0?n===1?0:t-1:(e+n+t)%t,dd=e=>e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0,fd=({search:e,className:t=`w-96`,autoFocus:n,showShortcut:r=!0,ref:i})=>{let a=(0,o.useId)(),s=(0,o.useRef)(null),[c,l]=(0,o.useState)(!1),[u,d]=(0,o.useState)(-1),f=e.groups.flatMap(e=>e.hits),p=c&&(e.query!==``||e.loading),m=e=>`${a}-${e}`,h=e=>{s.current=e,typeof i==`function`?i(e):i&&(i.current=e)},g=t=>{e.onSelect(t),d(-1),s.current?.blur()},_=()=>{e.onTextChange(``),d(-1),s.current?.focus()},v=t=>{if(t.key===`ArrowDown`||t.key===`ArrowUp`)t.preventDefault(),d(e=>ud(e,f.length,t.key===`ArrowDown`?1:-1));else if(t.key===`Enter`){let e=f[u]??f[0];if(!e)return;t.preventDefault(),g(e.href)}else t.key===`Escape`&&(e.text?e.onTextChange(``):t.currentTarget.blur(),d(-1))},y=-1;return(0,V.jsxs)(`div`,{className:B(`relative`,t),children:[(0,V.jsx)(sd,{ref:h,wrapperClassName:`w-full bg-surface shadow-none`,leading:e.loading?(0,V.jsx)(ld,{className:`size-4`}):(0,V.jsx)(pn,{className:`size-4`}),trailing:e.text?(0,V.jsx)(`button`,{type:`button`,"aria-label":`Clear search`,className:`-mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground`,onMouseDown:e=>e.preventDefault(),onClick:_,children:(0,V.jsx)($n,{className:`size-3.5`})}):r?(0,V.jsx)(`span`,{className:`hidden md:inline-flex`,children:(0,V.jsx)(cd,{children:`⌘K`})}):void 0,placeholder:e.placeholder,"aria-label":`Global search`,role:`combobox`,"aria-autocomplete":`list`,"aria-expanded":p,"aria-controls":a,"aria-activedescendant":p&&f[u]?m(u):void 0,autoFocus:n,value:e.text,onChange:t=>{e.onTextChange(t.target.value),d(-1)},onFocus:()=>l(!0),onBlur:()=>l(!1),onKeyDown:v}),p&&(0,V.jsxs)(`div`,{id:a,role:`listbox`,"aria-label":`Search results`,className:`absolute right-0 top-full z-40 mt-1 max-h-96 w-full min-w-72 overflow-y-auto rounded-lg border bg-background py-1 shadow-pop`,children:[e.groups.length===0&&(0,V.jsx)(`p`,{className:`px-3 py-2 text-muted-foreground`,children:e.loading?`Searching`:`No matches for “${e.query}”`}),e.groups.map(e=>(0,V.jsxs)(`div`,{role:`group`,"aria-label":e.label,children:[(0,V.jsx)(`div`,{className:`px-3 pb-1 pt-2 text-[11px] font-medium uppercase tracking-wide text-faint-foreground`,children:e.label}),e.failed&&(0,V.jsxs)(`p`,{className:`px-3 py-1.5 text-danger-text`,children:[`Could not search `,e.label.toLowerCase()]}),e.hits.map(e=>{y+=1;let t=y;return(0,V.jsxs)(`a`,{id:m(t),href:e.href,tabIndex:-1,role:`option`,"aria-selected":t===u,className:B(`block px-3 py-1.5`,t===u?`bg-primary-soft text-primary-text`:`hover:bg-muted`),onMouseDown:e=>e.preventDefault(),onClick:t=>{dd(t)||(t.preventDefault(),g(e.href))},onMouseEnter:()=>d(t),children:[(0,V.jsx)(`span`,{className:`block truncate font-semibold`,children:e.title}),e.subtitle&&(0,V.jsx)(`span`,{className:B(`block truncate text-xs`,t===u?`text-primary-text/80`:`text-muted-foreground`),children:e.subtitle})]},e.id)})]},e.id))]})]})},pd=({breadcrumb:e,onNavigate:t,actions:n,onMenu:r,menuOpen:i,menuControls:a,search:s,sticky:c,slotRef:l,ref:u})=>{let[d,f]=(0,o.useState)(!1),p=id(e),m=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(!s)return;let e=e=>{if(e.key.toLowerCase()!==`k`||!(e.metaKey||e.ctrlKey))return;e.preventDefault();let t=m.current;t&&t.offsetParent!==null?t.focus():f(!0)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[s]),(0,V.jsxs)(`header`,{ref:u,className:B(c?`sticky top-0 z-30`:`relative`,`flex h-12 shrink-0 items-center gap-1 border-b bg-background pl-4 pr-2 md:gap-4 md:px-5`),children:[r&&(0,V.jsx)(`button`,{type:`button`,"aria-label":`Open navigation`,"aria-expanded":!!i,"aria-controls":a,onClick:r,className:B(`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`,`-ml-3`),children:(0,V.jsx)(aee,{className:`size-5`})}),p&&(0,V.jsx)(`a`,{href:p.href,"aria-label":`Back to ${p.label}`,onClick:e=>{t&&lu(e)&&(e.preventDefault(),t(p.href))},className:B(`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`,!r&&`-ml-3`),children:(0,V.jsx)(be,{className:`size-5`})}),(0,V.jsx)(uu,{parts:e,onNavigate:t}),(0,V.jsxs)(`div`,{className:`ml-auto flex items-center gap-1 md:gap-3`,children:[s&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`div`,{className:`hidden md:block`,children:(0,V.jsx)(fd,{ref:m,search:s})}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Search`,"aria-expanded":d,onClick:()=>f(!0),className:`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`,children:(0,V.jsx)(pn,{className:`size-5`})})]}),n,(0,V.jsx)(`div`,{ref:l,className:`contents md:hidden`})]}),s&&d&&(0,V.jsxs)(`div`,{className:`absolute inset-0 z-20 flex items-center gap-1 bg-background px-3 md:hidden`,children:[(0,V.jsx)(fd,{className:`min-w-0 flex-1`,autoFocus:!0,showShortcut:!1,search:{...s,onSelect:e=>{s.onSelect(e),f(!1)}}}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Close search`,onClick:()=>f(!1),className:`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`,children:(0,V.jsx)($n,{className:`size-5`})})]})]})},md=`app-drawer`,hd=({sidebarMode:e,activeItem:t,breadcrumb:n,user:r,workspace:i,appName:a,logo:s,actions:c,rightPanel:l,forceExpanded:u,profileMenuOpen:d,navGroups:f,userMenu:p,bottomBar:m,onNavigate:h,onSignOut:g,signIn:_,organizations:v,roles:y,theme:b,search:x,pageScroll:S=!1,className:C,children:w})=>{let T=Kl(),[E,D]=(0,o.useState)(!1);(0,o.useEffect)(()=>{T&&D(!1)},[T]);let O=!T&&m&&m.length>0?m:void 0,[k,A]=(0,o.useState)(),j=k??S,M=(0,o.useRef)(null),[N,ee]=(0,o.useState)(null),P=(0,o.useRef)(null);su(j,M,P,!!O),au(j);let te=(e,n=!1)=>(0,V.jsx)(td,{mode:e,sticky:n,activeItem:t,user:r,workspace:i,appName:a,forceExpanded:u,profileMenuOpen:d,groups:f,userMenu:p,onNavigate:h,onSignOut:g,signIn:_,organizations:v,roles:y,theme:b,logo:s});return(0,V.jsx)(ru.Provider,{value:A,children:(0,V.jsxs)(`div`,{className:B(j?`flex min-h-full w-full overflow-x-clip bg-background`:`relative flex h-full min-h-0 w-full overflow-hidden bg-background`,C),children:[T?te(e,j):(0,V.jsx)(nu,{id:md,open:E,onClose:()=>D(!1),children:te(`text-large`)}),(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,V.jsx)(pd,{ref:M,slotRef:ee,sticky:j,breadcrumb:n,onNavigate:h,actions:c,onMenu:T||O?void 0:()=>D(!0),menuOpen:E,menuControls:md,search:x}),(0,V.jsx)(`main`,{className:j?`flex flex-1 flex-col`:`flex min-h-0 flex-1 flex-col`,children:(0,V.jsx)(nd.Provider,{value:N,children:w})}),O&&(0,V.jsx)(Xl,{ref:P,sticky:j,tabs:O,onNavigate:h,onMore:()=>D(!0),moreOpen:E,moreControls:md})]}),l&&(0,V.jsx)(`div`,{className:j?`sticky top-0 flex h-dvh shrink-0 self-start`:`flex shrink-0`,children:l})]})})},gd=({title:e,subtitle:t,aside:n,actions:r})=>{let i=(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight`,children:e}),t&&(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:t})]});return(0,V.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-x-4 gap-y-2`,children:[n?(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center justify-between gap-3`,children:[i,n]}):i,r&&(0,V.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-2 sm:w-auto`,children:r})]})},_d=`Too many attempts. Wait a minute and try again.`,vd=`The passkey prompt closed before it finished. Try again.`,yd={INVALID_EMAIL_OR_PASSWORD:`The email or password is not right.`,INVALID_PASSWORD:`The password is not right.`,INVALID_OTP:`The code is not right.`,OTP_EXPIRED:`The code has expired. Ask for a new one.`,TOO_MANY_ATTEMPTS:`Too many wrong codes. Ask for a new one.`,INVALID_CODE:`The code is not right.`,INVALID_BACKUP_CODE:`The backup code is not right, or was used before.`,TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:`Too many wrong codes. Sign in again.`,ACCOUNT_TEMPORARILY_LOCKED:`Too many wrong codes. Wait 15 minutes and try again.`,INVALID_TWO_FACTOR_COOKIE:`This sign-in took too long. Sign in again.`,AUTH_CANCELLED:vd,ERROR_CEREMONY_ABORTED:vd,REGISTRATION_CANCELLED:vd,PASSKEY_NOT_FOUND:`This passkey is not registered for an account here.`,AUTHENTICATION_FAILED:`The passkey could not be checked. Try again.`,PREVIOUSLY_REGISTERED:`This passkey is added already.`,ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED:`This passkey is added already.`,SESSION_NOT_FRESH:`For this change, sign out and sign in again first.`},bd=e=>e.code?yd[e.code]:void 0,xd=e=>bd(e)??(e.status===429?_d:e.message),Sd=e=>bd(e)??(e.status===429?_d:e.status===401?yd.INVALID_EMAIL_OR_PASSWORD:e.message),Cd={STAFF_PERMISSION_MISSING:`Your staff account has no permission to sign in as people here.`,STAFF_SIGN_IN_NOT_STRONG:`Sign in to your staff account with a passkey or a second step, then try again.`,STAFF_SIGN_IN_STALE:`Your staff sign-in is too old. Sign in to your staff account again.`,STAFF_SIGN_IN_EXPIRED:`This staff sign-in took too long or was used already. Start again.`,STAFF_SIGN_IN_FAILED:`The staff sign-in did not go through at the provider. Try again.`,STAFF_USER_UNAVAILABLE:`There is no account with this address, or it is disabled.`,STAFF_REASON_REQUIRED:`Say why you sign in as this person, in at least 10 characters.`,SIGN_IN_METHOD_FORBIDDEN:`Staff sign-in is turned off for this app.`,INVALID_CALLBACK_URL:`This page is not on an address the server trusts.`},wd=e=>{let t=typeof e==`string`?e:e.code;return t&&Cd[t]?Cd[t]:typeof e==`string`?`The staff sign-in did not go through. Try again.`:e.status===429?_d:e.message},Td={signup_disabled:e=>`No account here belongs to this ${e} account. Ask an admin to add you, or sign in another way.`,account_not_linked:e=>`Your ${e} account is not linked to your account here. Sign in another way, then connect ${e} on the Sign-in & security page.`,account_already_linked_to_different_user:e=>`This ${e} account is linked to someone else here already.`,unable_to_link_account:e=>`Your ${e} account could not be linked. Try again.`,access_denied:e=>`${e} did not let you in, or you cancelled.`},Ed=(e,t)=>Td[e]?.(t)??`Signing in with ${t} did not go through. Try again.`,Dd=`sign-in`,Od=`error`,kd=e=>{let t=new URL(e).searchParams;if(!t.has(Od))return t.get(`sign-in`)||void 0},Ad=e=>new URL(e).searchParams.get(Od)||void 0,jd=e=>{let t=new URL(e);for(let e of[Dd,Od])t.searchParams.delete(e);return`${t.pathname}${t.search}${t.hash}`},Md={github:`GitHub`,gitlab:`GitLab`,google:`Google`,microsoft:`Microsoft`,apple:`Apple`},Nd=(e,t)=>t?.provider===e?t.name:Md[e]??e.charAt(0).toUpperCase()+e.slice(1),Pd=(0,o.createContext)(null),H=()=>{let e=(0,o.useContext)(Pd);if(!e)throw Error(`useAuth must be used inside AuthProvider`);return e},Fd=({session:e,children:t})=>{let[n,r]=(0,o.useState)({kind:`loading`}),[i,a]=(0,o.useState)([`password`]),[s,c]=(0,o.useState)(!1),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)([]),[p,m]=(0,o.useState)([]),[h,g]=(0,o.useState)(),[_,v]=(0,o.useState)(),[y,b]=(0,o.useState)(),[x,S]=(0,o.useState)(!1),[C,w]=(0,o.useState)([]),T=(0,o.useCallback)(()=>x?{kind:`visitor`}:{kind:`signed-out`},[x]),E=(0,o.useCallback)(()=>r(e=>e.kind===`signed-in`?{kind:`signed-out`}:e),[]),D=(0,o.useRef)(E);D.current=E;let O=(0,o.useMemo)(()=>e??Il({onSignedOut:()=>D.current()}),[e]),k=(0,o.useCallback)(async e=>{let[{missing:t},n]=await Promise.all([O.account.signInMethods(),O.staff.current()]);r(t.length>0?{kind:`setup-required`,user:e,missing:t}:{kind:`signed-in`,user:e,...n&&{staff:n}})},[O]),A=(0,o.useCallback)(async e=>e.kind===`two-factor`?r({kind:`two-factor`,methods:e.methods}):k(e.user),[k]),j=(0,o.useCallback)(()=>{r({kind:`loading`}),O.status().then(async e=>{if(a(e.signInMethods),c(e.passwordReset),u(!!e.signUp),f(e.passkeyDomains??[]),m(e.socialProviders),g(e.platformSignIn),v(e.staffSignIn),b(e.organizations),S(!!e.anonymous),w(e.plugins??[]),e.needsAdmin)return r({kind:`needs-admin`});let t=await O.session();return t?k(t):r({kind:e.anonymous?`visitor`:`signed-out`})}).catch(e=>r({kind:`error`,message:e instanceof Error?e.message:`The server did not answer`}))},[O,k]);(0,o.useEffect)(j,[j]);let M=(0,o.useMemo)(()=>({state:n,session:O,signInMethods:i,passwordReset:s,canSignUp:l,passkeyDomains:d,socialProviders:p,signInProviders:p.map(e=>({id:e,name:Nd(e,h)})),staffSignIn:_,...y&&{organizations:y},markSignedOut:E,recheck:j,beforeSignIn:C,adoptSession:async()=>{let e=await O.session();return e?(await k(e),!0):!1},...x&&{browse:()=>{r(e=>e.kind===`signed-out`?{kind:`visitor`}:e)}},signIn:async(e,t)=>A(await O.signIn(e,t)),sendSignInCode:e=>O.sendSignInCode(e),signInWithCode:async(e,t)=>A(await O.signInWithCode(e,t)),sendSignUpCode:e=>O.sendSignUpCode(e),verifySignUpCode:(e,t)=>O.verifySignUpCode(e,t),signUp:async e=>k(await O.signUp(e)),signInWithPasskey:async e=>k(await O.signInWithPasskey(e)),verifyTwoFactor:async e=>k(await O.verifyTwoFactor(e)),signInSocial:async e=>{window.location.assign(await O.signInSocial(e,new URL(jd(window.location.href),window.location.href).href))},linkProvider:async e=>{window.location.assign(await O.account.linkProvider(e,new URL(jd(window.location.href),window.location.href).href))},stopStaffSession:async()=>{await O.staff.stop(),r(T())},signOut:async()=>{await O.signOut(),r(T())}}),[n,O,i,s,l,d,p,h,_,y,x,C,T,E,j,A,k]);return(0,V.jsx)(Pd.Provider,{value:M,children:t})},Id=new Map,Ld=(e,t)=>{let n=`${e}:${t??``}`,r=Id.get(n);if(r)return r;let i=new Intl.NumberFormat(`en-IE`,{style:`currency`,currency:e,...t!==void 0&&{minimumFractionDigits:t,maximumFractionDigits:t}});return Id.set(n,i),i},Rd=(e,t=`EUR`,n)=>Ld(t,n).format(e/100),zd=new Intl.NumberFormat(`en-IE`),Bd=e=>zd.format(e),Vd=e=>e>0?`+${zd.format(e)}`:zd.format(e).replace(`-`,`−`),Hd=e=>`${e}%`,Ud=e=>{if(e<1e4)return`${Bd(e)} rows`;let t=10**(Math.floor(Math.log10(e))-3);return`about ${Bd(Math.round(e/t)*t)} rows`},Wd=()=>Intl.DateTimeFormat().resolvedOptions().timeZone,Gd=new Map,Kd=e=>{let t=Gd.get(e);if(t)return t;let n=new Intl.DateTimeFormat(`en-US`,{timeZone:e,hourCycle:`h23`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`});return Gd.set(e,n),n},qd=(e,t)=>{let n=Object.fromEntries(Kd(t).formatToParts(e).map(e=>[e.type,e.value]));return{year:Number(n.year),month:Number(n.month),day:Number(n.day),hour:Number(n.hour),minute:Number(n.minute),second:Number(n.second)}},Jd=(e,t)=>{let n=qd(e,t);return Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second)-Math.floor(e/1e3)*1e3},Yd=e=>String(e).padStart(2,`0`),Xd=(e,t)=>{let n=qd(e,t);return`${n.year}-${Yd(n.month)}-${Yd(n.day)}`},Zd=(e,t)=>e-Jd(e-Jd(e,t),t),Qd=(e,t)=>Zd(Date.parse(`${e}T00:00:00Z`),t),$d=new Map,ef=(e,t)=>{let n=$d.get(t)??new Intl.DateTimeFormat(`en-GB`,{timeZone:t,timeZoneName:`shortOffset`});$d.set(t,n);let r=n.formatToParts(e).find(e=>e.type===`timeZoneName`)?.value??t;return t===`UTC`||t===`Etc/UTC`?`UTC`:`${t} (${r})`},tf=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),nf=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,timeZone:`UTC`}),rf=new Intl.DateTimeFormat(`en-GB`,{month:`long`,year:`numeric`,timeZone:`UTC`}),af=new Intl.DateTimeFormat(`en-GB`,{weekday:`short`,timeZone:`UTC`}),of=new Intl.DateTimeFormat(`en-GB`,{weekday:`long`,day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),sf=e=>tf.format(e),cf=e=>nf.format(e),lf=new Map,uf=e=>{let t=lf.get(e);if(t)return t;let n={day:new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:e}),time:new Intl.DateTimeFormat(`en-GB`,{hour:`2-digit`,minute:`2-digit`,hour12:!1,timeZone:e})};return lf.set(e,n),n},df=(e,t=Wd())=>{let n=uf(t);return`${n.day.format(e)}, ${n.time.format(e)}`},ff=e=>rf.format(e),pf=e=>af.format(e),mf=e=>of.format(e),hf=(e,t)=>tf.formatRange(e,t),gf=(e,t=Wd())=>uf(t).time.format(e),_f=e=>e<60?`${e} s ago`:e<3600?`${Math.floor(e/60)} min ago`:e<86400?`${Math.floor(e/3600)} h ago`:`${Math.floor(e/86400)} d ago`,vf=new Intl.RelativeTimeFormat(`en`,{numeric:`auto`}),yf=[[`year`,31536e3],[`month`,2592e3],[`day`,86400],[`hour`,3600],[`minute`,60]],bf=e=>{let[t,n]=yf.find(([,t])=>e>=t)??[`second`,1];return t===`second`&&e<45?`just now`:vf.format(-Math.floor(e/n),t)},xf={primary:`bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm`,secondary:`bg-background text-foreground border border-border-strong hover:bg-muted shadow-sm`,ghost:`text-muted-foreground hover:bg-muted hover:text-foreground`,danger:`bg-background text-danger-text border border-border-strong hover:bg-danger-soft shadow-sm`},Sf={sm:`h-7 px-2.5 text-xs gap-1.5`,md:`h-8 px-3 text-body gap-2`},Cf=({variant:e=`secondary`,size:t=`md`}={})=>B(`inline-flex shrink-0 items-center justify-center rounded-md font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-60 disabled:cursor-default`,xf[e],Sf[t]),U=({variant:e=`secondary`,size:t=`md`,loading:n,className:r,children:i,disabled:a,...o})=>(0,V.jsxs)(`button`,{type:`button`,disabled:a||n,className:B(Cf({variant:e,size:t}),r),...o,children:[n&&(0,V.jsx)(ld,{className:`size-3.5`}),i]}),wf=({title:e,description:t,onClose:n,actions:r,children:i,wide:a=!1})=>{let s=(0,o.useRef)(null);return tu(s,!0,n),(0,V.jsx)(`div`,{className:`fixed inset-0 z-[90] flex items-center justify-center bg-backdrop/30 p-4`,onMouseDown:e=>e.target===e.currentTarget&&n(),children:(0,V.jsxs)(`div`,{ref:s,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":e,className:B(`outline-none max-h-[90vh] w-full overflow-y-auto rounded-lg border bg-background p-4 shadow-pop sm:p-5`,a?`max-w-3xl`:`max-w-md`),children:[(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:e}),t&&(0,V.jsx)(`p`,{className:`mt-1.5 text-muted-foreground`,children:t}),i&&(0,V.jsx)(`div`,{className:`mt-4`,children:i}),(0,V.jsx)(`div`,{className:`mt-5 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end [&>*]:min-h-11 sm:[&>*]:min-h-0`,children:r})]})})},Tf=({title:e,status:t,description:n,children:r})=>(0,V.jsxs)(`section`,{"aria-label":e,className:`rounded-lg border bg-background p-4 sm:p-5`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:e}),t]}),(0,V.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:n}),r&&(0,V.jsx)(`div`,{className:`mt-4`,children:r})]}),Ef=({message:e})=>e?(0,V.jsx)(`p`,{role:`alert`,className:`mb-3 text-xs font-medium text-danger-text`,children:e}):null,Df={allowed:`Sign in with Face ID, Touch ID, Windows Hello, your phone or a security key instead of a password.`,required:`This app requires a passkey for every account. Sign in with Face ID, Touch ID, Windows Hello, your phone or a security key.`,forbidden:`Your admin turned passkeys off for this app, so they cannot be used to sign in.`},Of=({rule:e,passkeys:t,onAdd:n,onRename:r,onRemove:i})=>{let[a,s]=(0,o.useState)(!1),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(``),m=e===`required`&&t.length<=1,h=async e=>{s(!0),l(void 0);try{await e(),d(void 0)}catch(e){if(!(e instanceof pc))throw e;l(xd(e))}s(!1)};return(0,V.jsxs)(Tf,{title:`Passkeys`,status:e===`required`&&(0,V.jsx)(Au,{tone:`blue`,children:`Required`}),description:Df[e],children:[(0,V.jsx)(Ef,{message:u?void 0:c}),t.length>0&&(0,V.jsx)(`ul`,{className:`mb-3 divide-y rounded-md border`,children:t.map(e=>(0,V.jsxs)(`li`,{className:`flex flex-wrap items-center gap-3 px-3 py-2.5`,children:[(0,V.jsx)(_t,{className:`size-4 shrink-0 text-muted-foreground`}),(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.name??`Passkey`}),(0,V.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[e.createdAt?`Added ${sf(Date.parse(e.createdAt))}`:`Added earlier`,` · `,e.backedUp?`Synced across your devices`:`On one device`]})]}),(0,V.jsxs)(`span`,{className:`flex gap-1`,children:[(0,V.jsx)(U,{size:`sm`,variant:`ghost`,onClick:()=>{p(e.name??``),d({kind:`rename`,passkey:e})},children:`Rename`}),(0,V.jsx)(U,{size:`sm`,variant:`ghost`,disabled:m,title:m?`Passkeys are required: add another one before removing this one.`:void 0,onClick:()=>d({kind:`remove`,passkey:e}),children:`Remove`})]})]},e.id))}),e!==`forbidden`&&(0,V.jsxs)(U,{loading:a&&!u,onClick:()=>void h(n),children:[(0,V.jsx)(an,{className:`size-3.5`}),`Add a passkey`]}),u?.kind===`rename`&&(0,V.jsxs)(wf,{title:`Rename passkey`,description:`A name that tells you where this passkey lives, such as the device or password manager.`,onClose:()=>d(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>d(void 0),children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,loading:a,disabled:!f.trim(),onClick:()=>void h(()=>r(u.passkey.id,f.trim())),children:`Save`})]}),children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Name`,(0,V.jsx)(sd,{autoFocus:!0,value:f,maxLength:60,onChange:e=>p(e.target.value)})]}),(0,V.jsx)(Ef,{message:c})]}),u?.kind===`remove`&&(0,V.jsx)(wf,{title:`Remove passkey?`,description:`${u.passkey.name??`This passkey`} will no longer sign you in here. It stays on the device until you delete it there.`,onClose:()=>d(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>d(void 0),children:`Cancel`}),(0,V.jsx)(U,{variant:`danger`,loading:a,onClick:()=>void h(()=>i(u.passkey.id)),children:`Remove`})]}),children:c&&(0,V.jsx)(Ef,{message:c})})]})},kf=({providers:e,linked:t,onConnect:n,error:r})=>{let[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(r),l=async e=>{a(e),c(void 0);try{await n(e)}catch(e){if(!(e instanceof pc))throw e;c(xd(e)),a(void 0)}};return(0,V.jsxs)(Tf,{title:`Connected accounts`,description:`Sign in with these instead of your password. Connecting one asks you to sign in there; its address may differ from yours here.`,children:[(0,V.jsx)(Ef,{message:s}),(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`flex flex-wrap items-center gap-3 px-3 py-2.5`,children:[(0,V.jsx)(Ot,{className:`size-4 shrink-0 text-muted-foreground`}),(0,V.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-medium`,children:e.name}),t.includes(e.id)?(0,V.jsx)(Au,{tone:`green`,children:`Connected`}):(0,V.jsxs)(U,{size:`sm`,loading:i===e.id,disabled:i!==void 0,onClick:()=>void l(e.id),children:[`Connect `,e.name]})]},e.id))})]})},Af=(e,t,n=`text/plain`)=>{let r=URL.createObjectURL(new Blob([e],{type:n}));Object.assign(document.createElement(`a`),{href:r,download:t}).click(),URL.revokeObjectURL(r)},jf=({codes:e})=>{let[t,n]=(0,o.useState)(!1),r=`${e.join(`
|
|
7
|
-
`)}\n`;return(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,V.jsx)(`ul`,{"aria-label":`Backup codes`,className:`grid grid-cols-2 gap-x-4 gap-y-1 rounded-md border bg-surface p-3 font-mono`,children:e.map(e=>(0,V.jsx)(`li`,{children:e},e))}),(0,V.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,V.jsxs)(U,{size:`sm`,onClick:()=>{navigator.clipboard.writeText(r).then(()=>{n(!0),setTimeout(()=>n(!1),2e3)})},children:[t?(0,V.jsx)(ge,{className:`size-3.5 text-success`}):(0,V.jsx)(Re,{className:`size-3.5`}),t?`Copied`:`Copy`]}),(0,V.jsxs)(U,{size:`sm`,onClick:()=>Af(r,`backup-codes.txt`),children:[(0,V.jsx)(We,{className:`size-3.5`}),`Download`]})]})]})},Mf=({title:e,description:t,confirmLabel:n,danger:r,needsPassword:i,onConfirm:a,onClose:s})=>{let[c,l]=(0,o.useState)(``),[u,d]=(0,o.useState)(!1),[f,p]=(0,o.useState)(),m=async()=>{d(!0),p(void 0);try{await a(i?c:void 0)}catch(e){if(!(e instanceof pc))throw e;p(xd(e)),d(!1)}};return(0,V.jsxs)(wf,{title:e,description:t,onClose:s,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:s,children:`Cancel`}),(0,V.jsx)(U,{variant:r?`danger`:`primary`,loading:u,disabled:i&&!c,onClick:()=>void m(),children:n})]}),children:[i&&(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your password`,(0,V.jsx)(sd,{type:`password`,autoComplete:`current-password`,autoFocus:!0,value:c,invalid:!!f,onChange:e=>l(e.target.value),onKeyDown:e=>e.key===`Enter`&&c&&void m()})]}),f&&(0,V.jsx)(`p`,{role:`alert`,className:`mt-2 text-xs font-medium text-danger-text`,children:f})]})},Nf=(e,t)=>e.replace(/\D/g,``).slice(0,t),Pf=(e,t,n)=>{let r=Nf(t??``,n);return r.length===n?r:Nf(e,n)},Ff=(e,t,n,r)=>{let i=t.replace(/\D/g,``);return i.length>=r?i.slice(0,r):Nf(e.slice(0,n)+i+e.slice(n+i.length),r)},If=({value:e,onChange:t,onComplete:n,length:r=6,invalid:i,disabled:a,className:s,ref:c,onFocus:l,onBlur:u,onSelect:d,onKeyDown:f,onClick:p,onPaste:m,...h})=>{let g=(0,o.useRef)(null),[_,v]=(0,o.useState)(!1),[y,b]=(0,o.useState)(e.length),x=e.slice(0,r),S=Math.min(y,r-1),C=e=>{g.current=e,typeof c==`function`?c(e):c&&(c.current=e)},w=e=>{e!==x&&(t(e),e.length===r&&n?.(e))},T=e=>{let t=g.current;if(!t)return;let n=Math.max(0,Math.min(e,x.length));t.setSelectionRange(n,n<x.length?n+1:n),b(n)},E=e=>{if(f?.(e),e.defaultPrevented||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey)return;let t=e.currentTarget.selectionStart??x.length,n={ArrowLeft:t-1,ArrowRight:t+1,Home:0,End:x.length}[e.key];n!==void 0&&(e.preventDefault(),T(n))},D=e=>{p?.(e);let t=e.currentTarget.getBoundingClientRect();e.clientX<=t.left||e.clientX>=t.right||T(Math.floor((e.clientX-t.left)/t.width*r))};return(0,V.jsxs)(`div`,{className:B(`relative`,a&&`opacity-50`,s),children:[(0,V.jsx)(`div`,{"aria-hidden":!0,className:`flex justify-center gap-2`,children:Array.from({length:r},(e,t)=>{let n=_&&t===S;return(0,V.jsx)(`div`,{"data-slot":t,"data-digit":x[t],className:B(`flex h-12 min-w-0 max-w-12 flex-1 items-center justify-center rounded-md border bg-background font-mono text-xl font-semibold text-foreground shadow-sm transition-colors before:content-[attr(data-digit)]`,i?`border-danger`:n?`border-primary`:`border-border-strong`,n&&(i?`ring-2 ring-danger/20`:`ring-2 ring-primary/20`)),children:x[t]===void 0&&(n?(0,V.jsx)(`span`,{className:`h-6 w-px animate-pulse bg-foreground`}):(0,V.jsx)(`span`,{className:`size-1.5 rounded-full bg-border-strong`}))},t)})}),(0,V.jsx)(`input`,{ref:C,type:`text`,inputMode:`numeric`,autoComplete:`one-time-code`,pattern:`[0-9]{${r}}`,spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,"aria-invalid":i||void 0,disabled:a,value:x,className:`absolute inset-0 size-full cursor-text bg-transparent text-transparent caret-transparent outline-none selection:bg-transparent disabled:cursor-not-allowed`,...h,onChange:e=>{let{data:t,dataTransfer:n}=e.nativeEvent;w(Pf(e.target.value,t??n?.getData(`text/plain`),r))},onPaste:e=>{if(m?.(e),e.defaultPrevented)return;e.preventDefault();let t=e.currentTarget,n=Ff(x,e.clipboardData.getData(`text`),t.selectionStart??x.length,r);w(n),b(n.length)},onSelect:e=>{d?.(e);let t=e.currentTarget,n=t.selectionStart??x.length;n===t.selectionEnd&&n<t.value.length&&t.setSelectionRange(n,n+1),b(n)},onKeyDown:E,onClick:D,onFocus:e=>{v(!0),l?.(e)},onBlur:e=>{v(!1),u?.(e)}})]})},Lf=(e=>(e[e.Border=-1]=`Border`,e[e.Data=0]=`Data`,e[e.Function=1]=`Function`,e[e.Position=2]=`Position`,e[e.Timing=3]=`Timing`,e[e.Alignment=4]=`Alignment`,e))(Lf||{}),Rf=[0,1],zf=[1,0],Bf=[2,3],Vf=[3,2],Hf={L:Rf,M:zf,Q:Bf,H:Vf},Uf=/^\d*$/,Wf=/^[A-Z0-9 $%*+./:-]*$/,Gf=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`,Kf=1,qf=40,Jf=3,Yf=3,Xf=40,Zf=10,Qf=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],$f=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],ep=class{constructor(e,t,n,r){if(this.version=e,this.ecc=t,e<Kf||e>qf)throw RangeError(`Version value out of range`);if(r<-1||r>7)throw RangeError(`Mask value out of range`);this.size=e*4+17;let i=Array.from({length:this.size}).fill(!1);for(let e=0;e<this.size;e++)this.modules.push(i.slice()),this.types.push(i.map(()=>0));this.drawFunctionPatterns();let a=this.addEccAndInterleave(n);if(this.drawCodewords(a),r===-1){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);let n=this.getPenaltyScore();n<e&&(r=t,e=n),this.applyMask(t)}}this.mask=r,this.applyMask(r),this.drawFormatBits(r)}size;mask;modules=[];types=[];getModule(e,t){return e>=0&&e<this.size&&t>=0&&t<this.size&&this.modules[t][e]}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0,Lf.Timing),this.setFunctionModule(e,6,e%2==0,Lf.Timing);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let n=0;n<t;n++)for(let r=0;r<t;r++)n===0&&r===0||n===0&&r===t-1||n===t-1&&r===0||this.drawAlignmentPattern(e[n],e[r]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.ecc[1]<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let r=(t<<10|n)^21522;for(let e=0;e<=5;e++)this.setFunctionModule(8,e,np(r,e));this.setFunctionModule(8,7,np(r,6)),this.setFunctionModule(8,8,np(r,7)),this.setFunctionModule(7,8,np(r,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,np(r,e));for(let e=0;e<8;e++)this.setFunctionModule(this.size-1-e,8,np(r,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,np(r,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;for(let e=0;e<18;e++){let n=np(t,e),r=this.size-11+e%3,i=Math.floor(e/3);this.setFunctionModule(r,i,n),this.setFunctionModule(i,r,n)}}drawFinderPattern(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let i=Math.max(Math.abs(r),Math.abs(n)),a=e+r,o=t+n;a>=0&&a<this.size&&o>=0&&o<this.size&&this.setFunctionModule(a,o,i!==2&&i!==4,Lf.Position)}}drawAlignmentPattern(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.setFunctionModule(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!==1,Lf.Alignment)}setFunctionModule(e,t,n,r=Lf.Function){this.modules[t][e]=n,this.types[t][e]=r}addEccAndInterleave(e){let t=this.version,n=this.ecc;if(e.length!==_p(t,n))throw RangeError(`Invalid argument`);let r=$f[n[0]][t],i=Qf[n[0]][t],a=Math.floor(gp(t)/8),o=r-a%r,s=Math.floor(a/r),c=[],l=vp(i);for(let t=0,n=0;t<r;t++){let r=e.slice(n,n+s-i+(t<o?0:1));n+=r.length;let a=yp(r,l);t<o&&r.push(0),c.push(r.concat(a))}let u=[];for(let e=0;e<c[0].length;e++)c.forEach((t,n)=>{(e!==s-i||n>=o)&&u.push(t[e])});return u}drawCodewords(e){if(e.length!==Math.floor(gp(this.version)/8))throw RangeError(`Invalid argument`);let t=0;for(let n=this.size-1;n>=1;n-=2){n===6&&(n=5);for(let r=0;r<this.size;r++)for(let i=0;i<2;i++){let a=n-i,o=n+1&2?r:this.size-1-r;!this.types[o][a]&&t<e.length*8&&(this.modules[o][a]=np(e[t>>>3],7-(t&7)),t++)}}}applyMask(e){if(e<0||e>7)throw RangeError(`Mask value out of range`);for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;case 7:r=((n+t)%2+n*t%3)%2==0;break;default:throw Error(`Unreachable`)}!this.types[t][n]&&r&&(this.modules[t][n]=!this.modules[t][n])}}getPenaltyScore(){let e=0;for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[t][a]===n?(r++,r===5?e+=Jf:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*Xf),n=this.modules[t][a],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*Xf}for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[a][t]===n?(r++,r===5?e+=Jf:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*Xf),n=this.modules[a][t],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*Xf}for(let t=0;t<this.size-1;t++)for(let n=0;n<this.size-1;n++){let r=this.modules[t][n];r===this.modules[t][n+1]&&r===this.modules[t+1][n]&&r===this.modules[t+1][n+1]&&(e+=Yf)}let t=0;for(let e of this.modules)t=e.reduce((e,t)=>e+ +!!t,t);let n=this.size*this.size,r=Math.ceil(Math.abs(t*20-n*10)/n)-1;return e+=r*Zf,e}getAlignmentPatternPositions(){if(this.version===1)return[];{let e=Math.floor(this.version/7)+2,t=this.version===32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}}finderPenaltyCountPatterns(e){let t=e[1],n=t>0&&e[2]===t&&e[3]===t*3&&e[4]===t&&e[5]===t;return(n&&e[0]>=t*4&&e[6]>=t?1:0)+(n&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,n){return e&&(this.finderPenaltyAddHistory(t,n),t=0),t+=this.size,this.finderPenaltyAddHistory(t,n),this.finderPenaltyCountPatterns(n)}finderPenaltyAddHistory(e,t){t[0]===0&&(e+=this.size),t.pop(),t.unshift(e)}};function tp(e,t,n){if(t<0||t>31||e>>>t)throw RangeError(`Value out of range`);for(let r=t-1;r>=0;r--)n.push(e>>>r&1)}function np(e,t){return!!(e>>>t&1)}var rp=class{constructor(e,t,n){if(this.mode=e,this.numChars=t,this.bitData=n,t<0)throw RangeError(`Invalid argument`);this.bitData=n.slice()}getData(){return this.bitData.slice()}},ip=[1,10,12,14],ap=[2,9,11,13],op=[4,8,16,16];function sp(e,t){return e[Math.floor((t+7)/17)+1]}function cp(e){let t=[];for(let n of e)tp(n,8,t);return new rp(op,e.length,t)}function lp(e){if(!fp(e))throw RangeError(`String contains non-numeric characters`);let t=[];for(let n=0;n<e.length;){let r=Math.min(e.length-n,3);tp(Number.parseInt(e.substring(n,n+r),10),r*3+1,t),n+=r}return new rp(ip,e.length,t)}function up(e){if(!pp(e))throw RangeError(`String contains unencodable characters in alphanumeric mode`);let t=[],n=0;for(;n+2<=e.length;n+=2){let r=Gf.indexOf(e.charAt(n))*45;r+=Gf.indexOf(e.charAt(n+1)),tp(r,11,t)}return n<e.length&&tp(Gf.indexOf(e.charAt(n)),6,t),new rp(ap,e.length,t)}function dp(e){return e===``?[]:fp(e)?[lp(e)]:pp(e)?[up(e)]:[cp(hp(e))]}function fp(e){return Uf.test(e)}function pp(e){return Wf.test(e)}function mp(e,t){let n=0;for(let r of e){let e=sp(r.mode,t);if(r.numChars>=1<<e)return 1/0;n+=4+e+r.bitData.length}return n}function hp(e){e=encodeURI(e);let t=[];for(let n=0;n<e.length;n++)e.charAt(n)===`%`?(t.push(Number.parseInt(e.substring(n+1,n+3),16)),n+=2):t.push(e.charCodeAt(n));return t}function gp(e){if(e<Kf||e>qf)throw RangeError(`Version number out of range`);let t=(16*e+128)*e+64;if(e>=2){let n=Math.floor(e/7)+2;t-=(25*n-10)*n-55,e>=7&&(t-=36)}return t}function _p(e,t){return Math.floor(gp(e)/8)-Qf[t[0]][e]*$f[t[0]][e]}function vp(e){if(e<1||e>255)throw RangeError(`Degree out of range`);let t=[];for(let n=0;n<e-1;n++)t.push(0);t.push(1);let n=1;for(let r=0;r<e;r++){for(let e=0;e<t.length;e++)t[e]=bp(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=bp(n,2)}return t}function yp(e,t){let n=t.map(e=>0);for(let r of e){let e=r^n.shift();n.push(0),t.forEach((t,r)=>n[r]^=bp(t,e))}return n}function bp(e,t){if(e>>>8||t>>>8)throw RangeError(`Byte out of range`);let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n}function xp(e,t,n=1,r=40,i=-1,a=!0){if(!(Kf<=n&&n<=r&&r<=qf)||i<-1||i>7)throw RangeError(`Invalid value`);let o,s;for(o=n;;o++){let n=_p(o,t)*8,i=mp(e,o);if(i<=n){s=i;break}if(o>=r)throw RangeError(`Data too long`)}for(let e of[zf,Bf,Vf])a&&s<=_p(o,e)*8&&(t=e);let c=[];for(let t of e){tp(t.mode[0],4,c),tp(t.numChars,sp(t.mode,o),c);for(let e of t.getData())c.push(e)}let l=_p(o,t)*8;tp(0,Math.min(4,l-c.length),c),tp(0,(8-c.length%8)%8,c);for(let e=236;c.length<l;e^=253)tp(e,8,c);let u=Array.from({length:Math.ceil(c.length/8)},()=>0);return c.forEach((e,t)=>u[t>>>3]|=e<<7-(t&7)),new ep(o,t,u,i)}function Sp(e,t){let{ecc:n=`L`,boostEcc:r=!1,minVersion:i=1,maxVersion:a=40,maskPattern:o=-1,border:s=1}=t||{},c=typeof e==`string`?dp(e):Array.isArray(e)?[cp(e)]:void 0;if(!c)throw Error(`uqr only supports encoding string and binary data, but got: ${typeof e}`);let l=xp(c,Hf[n],i,a,o,r),u=Cp({version:l.version,maskPattern:l.mask,size:l.size,data:l.modules,types:l.types},s);return t?.invert&&(u.data=u.data.map(e=>e.map(e=>!e))),t?.onEncoded?.(u),u}function Cp(e,t=1){if(!t)return e;let{size:n}=e,r=n+t*2;e.size=r,e.data.forEach(e=>{for(let n=0;n<t;n++)e.unshift(!1),e.push(!1)});for(let n=0;n<t;n++)e.data.unshift(Array.from({length:r},e=>!1)),e.data.push(Array.from({length:r},e=>!1));let i=Lf.Border;e.types.forEach(e=>{for(let n=0;n<t;n++)e.unshift(i),e.push(i)});for(let n=0;n<t;n++)e.types.unshift(Array.from({length:r},e=>i)),e.types.push(Array.from({length:r},e=>i));return e}var wp=({uri:e,className:t})=>{let{size:n,path:r}=(0,o.useMemo)(()=>{let t=Sp(e,{ecc:`M`,border:2}),n=t.data.flatMap((e,t)=>e.flatMap((e,n)=>e?[`M${n} ${t}h1v1h-1z`]:[]));return{size:t.size,path:n.join(``)}},[e]);return(0,V.jsxs)(`svg`,{viewBox:`0 0 ${n} ${n}`,role:`img`,"aria-label":`QR code for your authenticator app`,shapeRendering:`crispEdges`,className:t,children:[(0,V.jsx)(`rect`,{width:n,height:n,fill:`#fff`}),(0,V.jsx)(`path`,{d:r,fill:`#000`})]})},Tp=e=>(new URL(e).searchParams.get(`secret`)??``).replace(/(.{4})(?=.)/g,`$1 `),Ep=[{value:`app`,label:`Authenticator app`,description:`A code from an app such as Google Authenticator, Microsoft Authenticator or 1Password. Comes with backup codes.`},{value:`email`,label:`Emailed code`,description:`A code mailed to your address each time you sign in with a password or an emailed sign-in code.`}],Dp=({offerEmailedCodes:e,needsPassword:t,onStartApp:n,onConfirmApp:r,onEmailedCodes:i,onDone:a,onCancel:s})=>{let[c,l]=(0,o.useState)({kind:`choose`}),[u,d]=(0,o.useState)(`app`),[f,p]=(0,o.useState)(``),[m,h]=(0,o.useState)(``),[g,_]=(0,o.useState)(!1),[v,y]=(0,o.useState)(),b=e?Ep:Ep.filter(e=>e.value===`app`),x=async e=>{_(!0),y(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;y(xd(e))}_(!1)},S=()=>x(async()=>{let e=t?f:void 0;if(u===`email`)return await i(e),a();l({kind:`scan`,setup:await n(e)})}),C=(e,t=m)=>x(async()=>{await r(t),l({kind:`backup-codes`,codes:e.backupCodes})}),w=v&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:v});return c.kind===`backup-codes`?(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Two-factor authentication is on. Keep these backup codes somewhere safe: each one signs you in once if you lose your phone. They are not shown again.`}),(0,V.jsx)(jf,{codes:c.codes}),(0,V.jsx)(U,{variant:`primary`,onClick:a,className:`min-h-10`,children:`I saved my backup codes`})]}):c.kind===`scan`?(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),C(c.setup)},children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Scan this code with your authenticator app, then enter the 6-digit code it shows.`}),(0,V.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,V.jsx)(wp,{uri:c.setup.totpURI,className:`size-44 rounded-md border`}),(0,V.jsxs)(`p`,{className:`text-center text-xs text-muted-foreground`,children:[`Can't scan it? Enter this key in the app:`,(0,V.jsx)(`span`,{className:`mt-1 block break-all font-mono text-body text-foreground`,children:Tp(c.setup.totpURI)})]})]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Code from the app`,(0,V.jsx)(If,{name:`code`,required:!0,autoFocus:!0,value:m,invalid:!!v,onChange:h,onComplete:e=>!g&&void C(c.setup,e)})]}),w,(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:g,className:`min-h-10`,children:`Turn on`}),s&&(0,V.jsx)(U,{variant:`ghost`,onClick:s,className:`min-h-10`,children:`Cancel`})]}):(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),S()},children:[(0,V.jsx)(`div`,{role:`radiogroup`,"aria-label":`Second step`,className:`flex flex-col gap-2`,children:b.map(e=>(0,V.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":u===e.value,onClick:()=>d(e.value),className:B(`rounded-md border p-3 text-left transition-colors`,u===e.value?`border-primary bg-primary-soft`:`border-border-strong hover:bg-muted`),children:[(0,V.jsx)(`span`,{className:`block font-medium`,children:e.label}),(0,V.jsx)(`span`,{className:`mt-0.5 block text-xs text-muted-foreground`,children:e.description})]},e.value))}),t&&(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your password`,(0,V.jsx)(sd,{type:`password`,name:`password`,autoComplete:`current-password`,required:!0,value:f,invalid:!!v,onChange:e=>p(e.target.value),className:`min-h-6`})]}),w,(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:g,className:`min-h-10`,children:`Continue`}),s&&(0,V.jsx)(U,{variant:`ghost`,onClick:s,className:`min-h-10`,children:`Cancel`})]})},Op={allowed:`Ask for a second step after your password or an emailed sign-in code: a code from an authenticator app, or one emailed to you. A passkey needs no second step.`,required:`This app requires two-factor authentication for every account. Turn it on to keep using the app.`,forbidden:`Your admin turned two-factor authentication off for this app.`},kp=e=>{let{rule:t,enabled:n,authenticatorApp:r,mail:i,needsPassword:a,onTurnOff:s,onNewBackupCodes:c,onChanged:l}=e,[u,d]=(0,o.useState)(),f=()=>d(void 0),p=n?(0,V.jsx)(Au,{tone:`green`,children:`On`}):t===`required`?(0,V.jsx)(Au,{tone:`amber`,children:`Required`}):(0,V.jsx)(Au,{children:`Off`}),m=n?r?`Signing in with a password or an emailed sign-in code also asks for a code from your authenticator app${i?`, or one emailed to you`:``}. Backup codes work when you do not have the app.`:`Signing in with a password or an emailed sign-in code also asks for a code emailed to you.`:Op[t];return u?.kind===`setup`?(0,V.jsx)(Tf,{title:`Two-factor authentication`,status:p,description:m,children:(0,V.jsx)(`div`,{className:`max-w-sm`,children:(0,V.jsx)(Dp,{offerEmailedCodes:i&&!u.appOnly,needsPassword:a,onStartApp:e.onStartApp,onConfirmApp:e.onConfirmApp,onEmailedCodes:e.onEmailedCodes,onCancel:f,onDone:()=>{f(),l()}})})}):(0,V.jsxs)(Tf,{title:`Two-factor authentication`,status:p,description:m,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[!n&&t!==`forbidden`&&(0,V.jsx)(U,{variant:`primary`,onClick:()=>d({kind:`setup`,appOnly:!1}),children:`Turn on`}),n&&!r&&t!==`forbidden`&&(0,V.jsx)(U,{onClick:()=>d({kind:`setup`,appOnly:!0}),children:`Add an authenticator app`}),n&&r&&(0,V.jsx)(U,{onClick:()=>d({kind:`new-codes`}),children:`New backup codes`}),n&&(0,V.jsx)(U,{variant:`danger`,disabled:t===`required`,title:t===`required`?`This app requires two-factor authentication.`:void 0,onClick:()=>d({kind:`turn-off`}),children:`Turn off`})]}),u?.kind===`turn-off`&&(0,V.jsx)(Mf,{title:`Turn off two-factor authentication?`,description:`Signing in then needs only your password or an emailed code. Your backup codes stop working.`,confirmLabel:`Turn off`,danger:!0,needsPassword:a,onClose:f,onConfirm:async e=>{await s(e),f(),l()}}),u?.kind===`new-codes`&&(0,V.jsx)(Mf,{title:`Make new backup codes?`,description:`Your current backup codes stop working, and you get ten new ones.`,confirmLabel:`Make new codes`,needsPassword:a,onClose:f,onConfirm:async e=>d({kind:`codes`,codes:await c(e)})}),u?.kind===`codes`&&(0,V.jsx)(wf,{title:`Your new backup codes`,description:`Keep them somewhere safe: each one signs you in once if you lose your phone. They are not shown again.`,onClose:f,actions:(0,V.jsx)(U,{variant:`primary`,onClick:f,children:`I saved my backup codes`}),children:(0,V.jsx)(jf,{codes:u.codes})})]})},Ap=()=>{let e=Ad(window.location.href);return e&&window.history.replaceState(window.history.state,``,jd(window.location.href)),e},jp=({email:e})=>{let{session:t,signInProviders:n,linkProvider:r}=H(),{account:i}=t,[a,s]=(0,o.useState)(),[c,l]=(0,o.useState)(),[u]=(0,o.useState)(Ap),d=(0,o.useCallback)(()=>{Promise.all([i.signInMethods(),i.passkeys(),i.linkedProviders()]).then(([e,t,n])=>s({methods:e,passkeys:t,linked:n}),e=>l(e instanceof pc?xd(e):`Could not read your sign-in methods`))},[i]);(0,o.useEffect)(d,[d]);let f=e=>e.then(e=>(d(),e));return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:`Sign-in & security`,subtitle:e}),a?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Of,{rule:a.methods.policy.passkey,passkeys:a.passkeys,onAdd:()=>f(i.addPasskey()),onRename:(e,t)=>f(i.renamePasskey(e,t)),onRemove:e=>f(i.removePasskey(e))}),(0,V.jsx)(kp,{rule:a.methods.policy.twoFactor,enabled:a.methods.account.twoFactor,authenticatorApp:a.methods.account.authenticatorApp,mail:a.methods.mail,needsPassword:a.methods.account.password,onStartApp:e=>i.startAuthenticatorApp(e),onConfirmApp:e=>i.confirmAuthenticatorApp(e),onEmailedCodes:e=>i.turnOnEmailedCodes(e),onTurnOff:e=>i.turnOffTwoFactor(e),onNewBackupCodes:e=>i.newBackupCodes(e),onChanged:d}),n.length>0&&(0,V.jsx)(kf,{providers:n,linked:a.linked,onConnect:r,error:u&&Ed(u,n.length===1?n[0].name:`the provider`)})]}):c?(0,V.jsx)(`p`,{role:`alert`,className:`text-danger-text`,children:c}):(0,V.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})]})},Mp=[{value:`allowed`,label:`On`},{value:`forbidden`,label:`Off`}],Np=[{value:`allowed`,label:`Optional`},{value:`required`,label:`Required`},{value:`forbidden`,label:`Off`}],Pp=[{method:`password`,label:`Password`,description:`Sign in with the email address and a password.`,rules:Mp},{method:`emailCode`,label:`Emailed sign-in code`,description:`Sign in with a one-time code mailed to the account's address.`,rules:Mp},{method:`passkey`,label:`Passkeys`,description:`Sign in with Face ID, Touch ID, Windows Hello, a phone or a security key. Required: everyone adds one after signing in.`,rules:Np},{method:`twoFactor`,label:`Two-factor authentication`,description:`A code from an authenticator app, or an emailed one, after a password or an emailed sign-in code. Required: everyone turns it on after signing in.`,rules:Np},{method:`staffAccess`,label:`Staff sign-in as a person`,description:`The team that runs this app signs in as someone to help them, with a reason, for a short session. Each time is in the log below; with "Email the person" they are told too.`,rules:[{value:`allowed`,label:`On`},{value:`notify`,label:`Email the person`},{value:`forbidden`,label:`Off`}]},{method:`platformSignIn`,label:`Sign-in through the platform`,description:`The sign-in provider the platform that runs this app adds, for people who have an account here already. It never creates accounts.`,rules:Mp}],Fp=(e,t)=>{let n=Pp.find(t=>t.method===e)?.rules.find(e=>e.value===t)?.label;if(n===void 0)throw Error(`No label for the ${t} rule of ${e}`);return n},Ip=({row:e,value:t,onChange:n})=>(0,V.jsx)(`span`,{role:`radiogroup`,"aria-label":e.label,className:`inline-flex h-8 shrink-0 rounded-md bg-muted p-0.5`,children:e.rules.map(e=>(0,V.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e.value===t,onClick:()=>n(e.value),className:B(`rounded px-3 text-xs font-medium transition-colors`,e.value===t?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`),children:e.label},e.value))}),Lp=({method:e},t,{mail:n,effective:r,policy:i})=>{if(e===`emailCode`&&!n)return`Needs mail settings (PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM): off until they are set.`;if(e===`password`&&!n&&t.password===`forbidden`)return`Without mail settings, password sign-in stays on so nobody is locked out.`;if(e===`staffAccess`&&!n&&t.staffAccess===`notify`)return`Needs mail settings (PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM): staff cannot sign in until they are set.`;if(e===`platformSignIn`&&t.platformSignIn===`allowed`&&(t.passkey===`required`||t.twoFactor===`required`))return`Off while passkeys or two-factor authentication are required: it skips the second step.`;if(t[e]===i[e]&&r[e]!==i[e])return`Applies as ${Fp(e,r[e])} for now.`},Rp=({operator:e,platformSignIn:t})=>Pp.flatMap(n=>n.method===`staffAccess`&&!e?[]:n.method===`platformSignIn`?t?[{...n,label:`Sign in with ${t} through the platform`}]:[]:[n]),zp=({state:e,onSave:t,busy:n,error:r,notice:i})=>{let[a,s]=(0,o.useState)(e.policy),c=Rp(e),l=c.some(({method:t})=>a[t]!==e.policy[t]);return(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t(a)},children:[(0,V.jsx)(`ul`,{className:`divide-y rounded-lg border bg-background`,children:c.map(t=>{let n=Lp(t,a,e);return(0,V.jsxs)(`li`,{className:`flex flex-col gap-3 p-4 sm:flex-row sm:items-start sm:justify-between`,children:[(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsx)(`h2`,{className:`font-semibold`,children:t.label}),(0,V.jsx)(`p`,{className:`mt-0.5 text-muted-foreground`,children:t.description}),n&&(0,V.jsx)(`p`,{className:`mt-1.5 text-xs font-medium text-warning-text`,children:n})]}),(0,V.jsx)(Ip,{row:t,value:a[t.method],onChange:e=>s({...a,[t.method]:e})})]},t.method)})}),r&&(0,V.jsx)(`p`,{role:`alert`,className:`rounded-md bg-danger-soft px-3 py-2 text-xs font-medium text-danger-text`,children:r}),i&&!l&&(0,V.jsx)(`p`,{role:`status`,className:`rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:i}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.savedAt?`Last saved${e.savedBy?` by ${e.savedBy}`:``} on ${df(Date.parse(e.savedAt))}.`:`Never changed: everything is on, nothing is required.`}),(0,V.jsxs)(`div`,{className:`flex gap-2`,children:[l&&(0,V.jsx)(U,{onClick:()=>s(e.policy),children:`Reset`}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:n,disabled:!l,children:`Save`})]})]})]})},Bp=(e,t)=>e.endedAt?(0,V.jsxs)(Au,{tone:`neutral`,children:[`Stopped `,df(Date.parse(e.endedAt))]}):Date.parse(e.expiresAt)<=t?(0,V.jsxs)(Au,{tone:`neutral`,children:[`Ended `,df(Date.parse(e.expiresAt))]}):(0,V.jsxs)(Au,{tone:`amber`,children:[`Signed in until `,df(Date.parse(e.expiresAt))]}),Vp=({signIns:e,operator:t,error:n,now:r=Date.now()})=>(0,V.jsxs)(Tf,{title:`Staff sign-ins`,description:`Each time staff of ${t} signed in as someone here, newest first.`,children:[(0,V.jsx)(Ef,{message:n}),e&&e.length===0&&(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`No staff has signed in as anyone yet.`}),e&&e.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`flex flex-col gap-1.5 p-3`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,V.jsx)(`span`,{className:`font-medium break-all`,children:e.staffName?`${e.staffName} (${e.staff})`:e.staff}),(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`as`}),(0,V.jsx)(`span`,{className:`font-medium break-all`,children:e.user})]}),(0,V.jsx)(`p`,{className:`break-words`,children:e.reason}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[(0,V.jsx)(`span`,{children:df(Date.parse(e.startedAt))}),Bp(e,r)]})]},e.id))})]}),Hp=({operator:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)();return(0,o.useEffect)(()=>{t.staff.log().then(r,e=>a(e instanceof pc?xd(e):`Could not read the staff sign-ins`))},[t]),(0,V.jsx)(Vp,{operator:e,signIns:n,error:i})},Up=()=>{let{session:e}=H(),[t,n]=(0,o.useState)(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(),[c,l]=(0,o.useState)();(0,o.useEffect)(()=>{e.signInPolicy.read().then(n,e=>s(e instanceof pc?xd(e):`Could not read the sign-in policy`))},[e]);let u=async t=>{i(!0),s(void 0),l(void 0);try{n(await e.signInPolicy.save(t)),l(`Saved. It applies to every sign-in from now on.`)}catch(e){if(!(e instanceof pc))throw e;s(xd(e))}i(!1)};return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:`Sign-in policy`,subtitle:`How people sign in to this app. Signed-in people keep their session, and are asked for what is newly required within 15 minutes.`}),t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(zp,{state:t,busy:r,error:a,notice:c,onSave:e=>void u(e)},t.savedAt??`default`),t.operator&&(0,V.jsx)(Hp,{operator:t.operator})]}):a?(0,V.jsx)(`p`,{role:`alert`,className:`text-danger-text`,children:a}):(0,V.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})]})},Wp=o.createContext(void 0),Gp=e=>{let t=o.useContext(Wp);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Kp=({client:e,children:t})=>(o.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,V.jsx)(Wp.Provider,{value:e,children:t})),qp={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Jp=new class{#e=qp;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function Yp(e){setTimeout(e,0)}var Xp=typeof window>`u`||`Deno`in globalThis;function Zp(){}function Qp(e,t){return typeof e==`function`?e(t):e}function $p(e){return typeof e==`number`&&e>=0&&e!==1/0}function em(e,t){return Math.max(e+(t||0)-Date.now(),0)}function tm(e,t){return typeof e==`function`?e(t):e}function nm(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==im(o,t.options))return!1}else if(!om(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function rm(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(am(t.options.mutationKey)!==am(a))return!1}else if(!om(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function im(e,t){return(t?.queryKeyHashFn||am)(e)}function am(e){return JSON.stringify(e,(e,t)=>dm(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function om(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!om(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!om(e[r],t[r]))return!1;return!0}return!1}var sm=Object.prototype.hasOwnProperty;function cm(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=um(e)&&um(t);if(!r&&!(dm(e)&&dm(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:sm.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=cm(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function lm(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function um(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function dm(e){if(!fm(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!fm(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function fm(e){return Object.prototype.toString.call(e)===`[object Object]`}function pm(e){return new Promise(t=>{Jp.setTimeout(t,e)})}function mm(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:cm(e,t)}function hm(e){return e}function gm(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function _m(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var vm=Symbol();function ym(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===vm?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function bm(e,t){return typeof e==`function`?e(...t):!!e}function xm(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var Sm=()=>Xp,Cm=()=>Sm(),wm=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Tm=new class extends wm{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},Em=Yp;function Dm(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=Em,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var Om=Dm(),km=new class extends wm{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function Am(e){return Math.min(1e3*2**e,3e4)}function jm(e){return(e??`online`)!==`online`||km.isOnline()}var Mm=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Nm(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(Zp);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new Mm(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>Tm.isFocused()&&(e.networkMode===`always`||km.isOnline())&&e.canRun(),p=()=>jm(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=()=>new Promise(t=>{r=e=>{(c()||f())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(Cm()?0:3),a=e.retryDelay??Am,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!s){h(r);return}n++,e.onFail?.(n,r),pm(o).then(()=>f()?void 0:g()).then(()=>{t?h(r):_()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g().then(_),s)}}var Pm=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),$p(this.gcTime)&&(this.#e=Jp.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Cm()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Jp.clearTimeout(this.#e),this.#e=void 0)}};function Fm(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{xm(e,()=>t.signal,()=>n=!0)},u=ym(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?_m:gm;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Lm:Im,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:Im(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Im(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Lm(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Rm(e,t){return t?Im(e,t)!=null:!1}function zm(e,t){return!t||!e.getPreviousPageParam?!1:Lm(e,t)!=null}var Bm=class extends Pm{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Um(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Um(this.options);e.data!==void 0&&(this.setState(Hm(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=mm(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(Zp).catch(Zp):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(e=>tm(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===vm||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>tm(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!em(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=ym(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?Fm(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=Nm({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Mm&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof Mm){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Vm(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Hm(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),Om.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Vm(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:jm(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Hm(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Um(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Wm=class extends wm{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Km(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return qm(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return qm(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof tm(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!lm(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Jm(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||tm(this.options.enabled,this.#t)!==tm(t.enabled,this.#t)||tm(this.options.staleTime,this.#t)!==tm(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||tm(this.options.enabled,this.#t)!==tm(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return lm(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Zp)),t}#h(e){return!Cm()&&tm(this.options.enabled,this.#t)!==!1&&$p(e)}#g(){this.#b();let e=tm(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=em(this.#r.dataUpdatedAt,e)+1;this.#u=Jp.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return tm(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=Jp.setInterval(()=>{(this.options.refetchIntervalInBackground||Tm.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(Jp.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(Jp.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Km(e,t),o=i&&Jm(e,n,t,r);(a||o)&&(l={...l,...Vm(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=mm(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=mm(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:Ym(e,t),refetch:this.refetch,isEnabled:tm(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),lm(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();Om.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function Gm(e,t){return tm(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||tm(t.retryOnMount,e)!==!1)}function Km(e,t){return Gm(e,t)||e.state.data!==void 0&&qm(e,t,t.refetchOnMount)}function qm(e,t,n){if(tm(t.enabled,e)!==!1&&tm(t.staleTime,e)!==`static`){let r=tm(n,e);return r===`always`||r!==!1&&Ym(e,t)}return!1}function Jm(e,t,n,r){return(e!==t||tm(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Ym(e,n)}function Ym(e,t){return tm(t.enabled,e)!==!1&&e.isStaleByTime(tm(t.staleTime,e))}var Xm=class extends Wm{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type=`infinite`,super.setOptions(e)}getOptimisticResult(e){return e._type=`infinite`,super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`forward`}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`backward`}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:a,isError:o,isRefetchError:s}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c===`forward`,u=i&&c===`forward`,d=o&&c===`backward`,f=i&&c===`backward`;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Rm(t,n.data),hasPreviousPage:zm(t,n.data),isFetchNextPageError:l,isFetchingNextPage:u,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:s&&!l&&!d,isRefetching:a&&!u&&!f}}},Zm=class extends Pm{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Qm(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=Nm({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),Om.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Qm(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var $m=class extends wm{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new Zm({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=eh(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=eh(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=eh(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=eh(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){Om.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>rm(t,e))}findAll(e={}){return this.getAll().filter(t=>rm(e,t))}notify(e){Om.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return Om.batch(()=>Promise.all(e.map(e=>e.continue().catch(Zp))))}};function eh(e){return e.options.scope?.id}var th=class extends wm{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),lm(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&am(t.mutationKey)!==am(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??Qm();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){Om.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}};function nh(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var kne=class extends wm{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,Om.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,s=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!lm(e,n)});(o||s)&&(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(nh(e,n).forEach(e=>{e.destroy()}),nh(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=cm(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new Wm(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&Om.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},Ane=class extends wm{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??im(r,t),a=this.get(i);return a||(a=new Bm({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){this.#e.get(e.queryHash)===e&&(e.destroy(),this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){Om.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>nm(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>nm(e,t)):t}notify(e){Om.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Om.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Om.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},jne=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Ane,this.#t=e.mutationCache||new $m,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Tm.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=km.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(tm(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=Qp(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return Om.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;Om.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return Om.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=Om.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(Zp).catch(Zp)}invalidateQueries(e,t={}){return Om.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=Om.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(Zp)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(Zp)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(tm(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(tm(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Zp).catch(Zp)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Zp).catch(Zp)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return km.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(am(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{om(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(am(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{om(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=im(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===vm&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},rh=o.createContext(!1),ih=()=>o.useContext(rh);rh.Provider;function Mne(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Nne=o.createContext(Mne()),ah=()=>o.useContext(Nne),oh=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?bm(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},sh=e=>{o.useEffect(()=>{e.clearReset()},[e])},ch=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||bm(n,[e.error,r])),lh=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},uh=(e,t)=>e?.suspense&&t.isPending,dh=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function fh({queries:e,...t},n){let r=Gp(n),i=ih(),a=ah(),s=t.subscribed!==!1,c=o.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:s?`optimistic`:void 0,t}),[e,r,i,s]);c.forEach(e=>{lh(e);let t=r.getQueryCache().get(e.queryHash);oh(e,a,t)}),sh(a);let[l]=o.useState(()=>new kne(r,c,t)),[u,d,f]=l.getOptimisticResult(c,t.combine),p=!i&&s;o.useSyncExternalStore(o.useCallback(e=>p?l.subscribe(Om.batchCalls(e)):Zp,[l,p]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),o.useEffect(()=>{l.setQueries(c,t)},[c,t,l]);let m=u.some((e,t)=>uh(c[t],e))?u.flatMap((e,t)=>{let n=c[t];return n&&uh(n,e)?dh(n,new Wm(r,n),a):[]}):[];if(m.length>0)throw Promise.all(m);let h=u.find((e,t)=>{let n=c[t];return n&&ch({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(h)throw h.error;return d(f())}function ph(e,t,n){let r=ih(),i=ah(),a=Gp(n),s=a.defaultQueryOptions(e),c=a.getQueryCache().get(s.queryHash),l=e.subscribed!==!1;s._optimisticResults=r?`isRestoring`:l?`optimistic`:void 0,lh(s),oh(s,i,c),sh(i);let[u]=o.useState(()=>new t(a,s)),d=u.getOptimisticResult(s),f=!r&&l;if(o.useSyncExternalStore(o.useCallback(e=>{let t=f?u.subscribe(Om.batchCalls(e)):Zp;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),o.useEffect(()=>{u.setOptions(s)},[s,u]),uh(s,d))throw dh(s,u,i);if(ch({result:d,errorResetBoundary:i,throwOnError:s.throwOnError,query:c,suspense:s.suspense}))throw d.error;return s.notifyOnChangeProps?d:u.trackResult(d)}function mh(e,t){return ph(e,Wm,t)}function hh(e,t){let n=Gp(t),[r]=o.useState(()=>new th(n,e));o.useEffect(()=>{r.setOptions(e)},[r,e]);let i=o.useSyncExternalStore(o.useCallback(e=>r.subscribe(Om.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=o.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(Zp)},[r]);if(i.error&&bm(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function gh(e,t){return ph(e,Xm,t)}var Pne=()=>{let e=0;return{refetchOnWindowFocus:()=>e>0?!1:`always`,pause:()=>{e+=1;let t=!1;return()=>{t||(t=!0,--e)}}}},_h=(0,o.createContext)(null),Fne=e=>{let t=(0,o.useContext)(_h);(0,o.useEffect)(()=>e&&t?t.pause():void 0,[e,t])},Ine=e=>{let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),window.addEventListener(`focus`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t),window.removeEventListener(`focus`,t)}},W={meta:[`meta`],sourceMeta:(e,t)=>[`source-meta`,e,t.join(`,`)],sourceMetas:e=>[`source-meta`,e],list:(e,t,n,r,i)=>[`list`,e,t,n,r,i],page:(e,t,n,r,i)=>[`page`,e,t,n,r,i],pages:(e,t,n)=>[`page`,e,t,n],navRecent:(e,t,n,r)=>[`list`,e,t,n,r,`nav-recent`],first:(e,t,n)=>[`first-page`,e,t,n],record:(e,t)=>[`record`,e,t],recordPreview:(e,t)=>[`record-preview`,e,t],history:(e,t,n)=>[`record`,e,t,`history`,n],comments:(e,t)=>[`record`,e,t,`comments`],mentionable:(e,t,n)=>[`record`,e,t,`mentionable`,n],facets:(e,t,n)=>[`facets`,e,t,n],series:(e,t,n,r,i)=>[`series`,e,t,n,r,i],aggregate:(e,t)=>[`aggregate`,e,t],histogram:(e,t,n,r)=>[`histogram`,e,t,n,r],map:(e,t,n,r,i)=>[`map`,e,t,n,r,i],relatedLabel:(e,t)=>[`related-label`,e,t],labels:(e,t)=>[`labels`,e,t],count:(e,t)=>[`count`,e,t],exportCount:(e,t)=>[`list`,e,t,`export-count`],firstRecord:(e,t,n)=>[`first-record`,e,t,n],pathValue:(e,t,n)=>[`path-value`,e,t,n],publicForm:e=>[`public-form`,e]},vh=(0,o.createContext)(null),yh=(0,o.createContext)(null),bh=(0,o.createContext)(null),G=()=>{let e=(0,o.useContext)(vh);if(!e)throw Error(`useClient must be used inside ApiProvider`);return e},xh=e=>{let t=G();return(0,o.useContext)(bh)?.(e)??t},Lne=()=>{let e=G(),t=(0,o.useContext)(bh);return(0,o.useCallback)(n=>t?.(n)??e,[e,t])},Rne=()=>{let e=(0,o.useContext)(yh);if(!e)throw Error(`useSourceClients must be used inside ApiProvider`);return e},zne=({client:e,resourceClient:t,children:n})=>(0,V.jsx)(vh.Provider,{value:e,children:(0,V.jsx)(bh.Provider,{value:t,children:n})}),Sh=({baseUrl:e,client:t,sources:n,fetch:r,queryClient:i,token:a,onUnauthenticated:s,children:c})=>{let[l]=(0,o.useState)(Pne),[u]=(0,o.useState)(()=>i??new jne({defaultOptions:{queries:{staleTime:3e4,retry:!1,refetchOnWindowFocus:l.refetchOnWindowFocus}}}));(0,o.useEffect)(()=>Tm.setEventListener(Ine),[]);let d=(0,o.useRef)(void 0),f=(0,o.useMemo)(()=>t??Zs({baseUrl:e,fetch:r,token:a,onUnauthenticated:s,onMetaVersion:e=>{let t=d.current;d.current=e,t!==void 0&&t!==e&&u.invalidateQueries({queryKey:W.meta},{cancelRefetch:!1})}}),[t,e,r,u,a,s]),p=(0,o.useMemo)(()=>{let e=new Map;return t=>{let i=n?.[t.url]??e.get(t.url);if(i)return i;let o,s=Zs({baseUrl:t.url,fetch:r,token:a,onMetaVersion:e=>{let n=o;o=e,n!==void 0&&n!==e&&u.invalidateQueries({queryKey:W.sourceMetas(t.url)},{cancelRefetch:!1})}});return e.set(t.url,s),s}},[n,r,a,u]);return(0,V.jsx)(Kp,{client:u,children:(0,V.jsx)(vh.Provider,{value:f,children:(0,V.jsx)(yh.Provider,{value:p,children:(0,V.jsx)(_h.Provider,{value:l,children:c})})})})},Ch=(0,o.createContext)(null),wh=()=>{let e=(0,o.useContext)(Ch);if(!e)throw Error(`useRouter must be used inside Router`);return e},Th=()=>`${window.location.pathname}${window.location.search}`,Eh=e=>new URL(e,`http://local`).pathname,Dh=()=>window.history.state?.protobaseIndex??0,Bne=({basePath:e=``,initialUrl:t,children:n})=>{let r=t!==void 0,[i,a]=(0,o.useState)(t??Th()),s=(0,o.useRef)(new Set),c=(0,o.useRef)(i);c.current=i;let l=(0,o.useRef)(r?0:Dh()),u=(0,o.useRef)(!1),d=(0,o.useRef)(!1),[f,p]=(0,o.useState)();(0,o.useEffect)(()=>{if(r)return;window.history.replaceState({protobaseIndex:l.current},``);let e=()=>{let e=Dh();if(u.current){u.current=!1,l.current=e;return}let t=e-l.current,n=Eh(Th())!==Eh(c.current);if(!d.current&&s.current.size>0&&n){u.current=!0,window.history.go(-t),p({kind:`history`,delta:t});return}d.current=!1,l.current=e,a(Th())};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[r]);let m=(0,o.useCallback)((e,t)=>{r||(l.current+=+!t,window.history[t?`replaceState`:`pushState`]({protobaseIndex:l.current},``,e)),a(e)},[r]),h=(0,o.useCallback)((t,{replace:n=!1}={})=>{let r=`${e}${t}`;if(Eh(r)!==Eh(c.current)&&s.current.size>0)return p({kind:`link`,full:r,replace:n});m(r,n)},[e,m]),g=(0,o.useCallback)(()=>{let e=Symbol(`guard`);return s.current.add(e),()=>void s.current.delete(e)},[]),_=()=>{if(f){if(p(void 0),f.kind===`link`)return m(f.full,f.replace);d.current=!0,window.history.go(f.delta)}},v=(0,o.useMemo)(()=>{let t=new URL(i,`http://local`);return{path:t.pathname.slice(e.length)||`/`,params:t.searchParams,basePath:e,entry:l.current,navigate:h,registerGuard:g}},[i,e,h,g]);return(0,V.jsxs)(Ch.Provider,{value:v,children:[n,f&&(0,V.jsx)(wf,{title:`Leave without saving?`,description:`You have unsaved changes on this page. They stay in this browser, and come back when you open the record again.`,onClose:()=>p(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>p(void 0),children:`Stay`}),(0,V.jsx)(U,{variant:`primary`,onClick:_,children:`Leave`})]})})]})},Vne=({to:e,replace:t,...n})=>{let{navigate:r,basePath:i}=wh();return(0,V.jsx)(du,{to:{href:`${i}${e}`,onFollow:()=>r(e,{replace:t})},...n})},Hne=e=>{let{registerGuard:t}=wh();(0,o.useEffect)(()=>e?t():void 0,[e,t]),(0,o.useEffect)(()=>{if(!e)return;let t=e=>e.preventDefault();return window.addEventListener(`beforeunload`,t),()=>window.removeEventListener(`beforeunload`,t)},[e])},Oh=({title:e,description:t,size:n=`sm`,children:r})=>(0,V.jsx)(`div`,{className:`flex min-h-full w-full items-center justify-center bg-surface px-4 py-10`,children:(0,V.jsxs)(`div`,{className:B(`w-full`,n===`sm`?`max-w-sm`:`max-w-lg`),children:[(0,V.jsxs)(`div`,{className:`mb-6 flex flex-col items-center text-center`,children:[(0,V.jsx)(hu,{className:`size-10`}),(0,V.jsx)(`h1`,{className:`mt-4 text-xl font-semibold tracking-tight`,children:e}),t&&(0,V.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:t})]}),(0,V.jsx)(`div`,{className:`rounded-lg border bg-background p-5 shadow-sm`,children:r})]})}),kh=({onResend:e,cooldown:t=30,disabled:n})=>{let[r,i]=(0,o.useState)(()=>Date.now()+t*1e3),[a,s]=(0,o.useState)(()=>Date.now()),c=Math.max(0,Math.ceil((r-a)/1e3));return(0,o.useEffect)(()=>{if(c===0)return;let e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[c]),(0,V.jsx)(U,{variant:`ghost`,disabled:n||c>0,onClick:()=>{let n=Date.now();i(n+t*1e3),s(n),e()},className:`min-h-10`,children:c>0?`Send a new code in ${c}s`:`Send a new code`})},Ah=({title:e,description:t,explanation:n,submitLabel:r,onSubmit:i,onResend:a,onChangeAddress:s,changeAddressLabel:c,busy:l,error:u,notice:d,resendCooldown:f})=>{let[p,m]=(0,o.useState)(``);return(0,V.jsxs)(Oh,{title:e,description:t,children:[(0,V.jsx)(`p`,{className:`mb-4 text-muted-foreground`,children:n}),d&&(0,V.jsx)(`p`,{role:`status`,className:`mb-4 rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:d}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),i(p)},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Code`,(0,V.jsx)(If,{name:`code`,required:!0,autoFocus:!0,value:p,invalid:!!u,onChange:m,onComplete:e=>!l&&i(e)})]}),u&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:u}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:l,className:`min-h-10`,children:r}),(0,V.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-x-2 sm:justify-between`,children:[(0,V.jsx)(U,{variant:`ghost`,onClick:s,className:`min-h-10`,children:c}),(0,V.jsx)(kh,{onResend:a,disabled:l,cooldown:f})]})]})]})},Une=({email:e,onBack:t,...n})=>(0,V.jsx)(Ah,{title:`Check your email`,description:`Enter the code we sent to sign in.`,explanation:(0,V.jsxs)(V.Fragment,{children:[`If `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),` has an account, a 6-digit code is on its way. It works for 5 minutes, once.`]}),submitLabel:`Sign in`,onChangeAddress:t,changeAddressLabel:`Back to sign in`,...n}),Wne=({email:e,onBack:t})=>{let{signInWithCode:n,sendSignInCode:r}=H(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(),d=async e=>{a(!0),c(void 0),u(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;c(xd(e))}a(!1)};return(0,V.jsx)(Une,{email:e,busy:i,error:s,notice:l,onBack:t,onSubmit:t=>void d(()=>n(e,t)),onResend:()=>void d(async()=>{await r(e),u(`A new code is on its way. Only the newest one works.`)})})},Gne=`protobase users create you@example.com`,Kne=({command:e=Gne,onCheckAgain:t,busy:n})=>{let[r,i]=(0,o.useState)(!1);return(0,V.jsxs)(Oh,{title:`No admin yet`,description:`This Protobase has no users to sign in with.`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Run this in the terminal where Protobase runs, then reload. The first admin is created on the server, not in the browser, so nobody else can claim a fresh URL.`}),(0,V.jsxs)(`div`,{className:`mt-4 flex items-center gap-2 rounded-md border bg-surface py-1.5 pl-3 pr-1.5`,children:[(0,V.jsx)(`code`,{className:`min-w-0 flex-1 break-all font-mono text-xs`,children:e}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Copy command`,onClick:()=>{navigator.clipboard.writeText(e).then(()=>{i(!0),setTimeout(()=>i(!1),2e3)})},className:`inline-flex size-8 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted pointer-coarse:size-11`,children:r?(0,V.jsx)(ge,{className:`size-4 text-success`}):(0,V.jsx)(Re,{className:`size-4`})})]}),(0,V.jsx)(U,{variant:`primary`,className:`mt-4 min-h-10 w-full`,loading:n,onClick:t,children:`Reload`})]})},qne=({onSubmit:e,back:t,busy:n,error:r,sentTo:i})=>{let[a,s]=(0,o.useState)(``);return i?(0,V.jsxs)(Oh,{title:`Check your email`,children:[(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`If `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:i}),` has an account, an email with a link to choose a new password is on its way. The link works once, for a limited time.`]}),(0,V.jsx)(du,{to:t,className:B(Cf({variant:`primary`}),`mt-4 min-h-10 w-full`),children:`Back to sign in`})]}):(0,V.jsx)(Oh,{title:`Reset your password`,description:`We email you a link to choose a new one.`,children:(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),e(a.trim())},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,V.jsx)(sd,{type:`email`,name:`email`,autoComplete:`username`,required:!0,autoFocus:!0,value:a,invalid:!!r,onChange:e=>s(e.target.value),className:`min-h-6`})]}),r&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:r}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:n,className:`min-h-10`,children:`Send reset link`}),(0,V.jsx)(du,{to:t,className:B(Cf({variant:`ghost`}),`min-h-10`),children:`Back to sign in`})]})})},jh=`password-reset`,Jne=e=>{let t=new URL(e);return`${t.origin}${t.pathname}?${jh}`},Yne=e=>{let t=new URL(e).searchParams;if(t.has(`password-reset`))return{token:t.get(`token`)||void 0}},Xne=e=>{let t=new URL(e);for(let e of[jh,`token`,`error`])t.searchParams.delete(e);return`${t.pathname}${t.search}${t.hash}`},Zne=({back:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(!1),[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(),l=async e=>{r(!0),a(void 0);try{await t.requestPasswordReset(e,Jne(window.location.href)),c(e)}catch(e){if(!(e instanceof pc))throw e;a(e.status===429?`Too many requests. Wait a minute and try again.`:e.message)}r(!1)};return(0,V.jsx)(qne,{busy:n,error:i,sentTo:s,back:e,onSubmit:e=>void l(e)})},Qne=({name:e,workspace:t})=>(0,V.jsx)(Oh,{title:`Signing in with ${e}`,description:t,children:(0,V.jsxs)(`p`,{role:`status`,className:`flex items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Taking you to `,e,`…`]})}),$ne=({provider:e,workspace:t,onFailed:n})=>{let{signInProviders:r,signInSocial:i}=H(),a=r.find(t=>t.id===e),s=a?.name??Nd(e),c=(0,o.useRef)(!1);return(0,o.useEffect)(()=>{if(!c.current){if(c.current=!0,!a)return n(`Signing in with ${s} is not offered here. Sign in another way.`);i(e).catch(e=>{if(!(e instanceof pc))throw e;n(Sd(e))})}},[a,s,e,i,n]),(0,V.jsx)(Qne,{name:s,workspace:t})},ere=({onSubmit:e,invalidLink:t,onRequestNewLink:n,onBack:r,busy:i,error:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),[d,f]=(0,o.useState)(!1);if(t)return(0,V.jsxs)(Oh,{title:`This link no longer works`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`A reset link works once, for a limited time. Ask for a new one to choose your password.`}),(0,V.jsxs)(`div`,{className:`mt-4 flex flex-col gap-2`,children:[n&&(0,V.jsx)(U,{variant:`primary`,className:`min-h-10`,onClick:n,children:`Send a new link`}),(0,V.jsx)(U,{variant:n?`ghost`:`primary`,className:`min-h-10`,onClick:r,children:`Back to sign in`})]})]});let p=d?`The passwords are not the same.`:a;return(0,V.jsx)(Oh,{title:`Choose a new password`,description:`At least 12 characters.`,children:(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),f(s!==l),s===l&&e(s)},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`New password`,(0,V.jsx)(sd,{type:`password`,name:`new-password`,autoComplete:`new-password`,required:!0,minLength:12,autoFocus:!0,value:s,invalid:!!p,onChange:e=>c(e.target.value),className:`min-h-6`})]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Repeat new password`,(0,V.jsx)(sd,{type:`password`,name:`repeat-password`,autoComplete:`new-password`,required:!0,minLength:12,value:l,invalid:!!p,onChange:e=>u(e.target.value),className:`min-h-6`})]}),p&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:p}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Set new password`})]})})},tre=e=>e.status===429?`Too many attempts. Wait a minute and try again.`:e.code===`PASSWORD_TOO_SHORT`?`Use at least 12 characters.`:e.code===`PASSWORD_TOO_LONG`?`That password is too long.`:e.message,nre=({token:e,onDone:t,onRequestNewLink:n,onBack:r})=>{let{session:i}=H(),[a,s]=(0,o.useState)(!1),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(!e),f=async n=>{s(!0),l(void 0);try{await i.resetPassword(e,n),t()}catch(e){if(!(e instanceof pc))throw e;e.code===`INVALID_TOKEN`?d(!0):l(tre(e)),s(!1)}};return(0,V.jsx)(ere,{busy:a,error:c,invalidLink:u,onRequestNewLink:n,onBack:r,onSubmit:e=>void f(e)})},rre={twoFactor:`Turn on two-factor authentication`,passkey:`Add a passkey`},ire=({step:e,twoFactor:t,onAddPasskey:n,busy:r,error:i,onSignOut:a})=>(0,V.jsxs)(Oh,{title:rre[e],description:`This app requires it for every account.`,children:[e===`twoFactor`?(0,V.jsx)(Dp,{...t}):(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`A passkey signs you in with Face ID, Touch ID, Windows Hello, your phone or a security key. Your browser asks which one to use.`}),i&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,V.jsxs)(U,{variant:`primary`,loading:r,onClick:n,className:`min-h-10`,children:[(0,V.jsx)(_t,{className:`size-4`}),`Add a passkey`]})]}),(0,V.jsx)(`button`,{type:`button`,onClick:a,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:underline`,children:`Sign out`})]}),are=({missing:e})=>{let{session:t,recheck:n,signOut:r}=H(),[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(!1),[l,u]=(0,o.useState)();(0,o.useEffect)(()=>{t.account.signInMethods().then(a,e=>u(e instanceof pc?xd(e):`Could not read your account`))},[t]);let d=async()=>{c(!0),u(void 0);try{await t.account.addPasskey(),n()}catch(e){if(!(e instanceof pc))throw e;u(xd(e)),c(!1)}};return!i&&!l?(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]}):(0,V.jsx)(ire,{step:e[0],busy:s,error:l,onAddPasskey:()=>void d(),onSignOut:()=>void r(),twoFactor:{offerEmailedCodes:i?.mail??!1,needsPassword:i?.account.password??!0,onStartApp:e=>t.account.startAuthenticatorApp(e),onConfirmApp:e=>t.account.confirmAuthenticatorApp(e),onEmailedCodes:e=>t.account.turnOnEmailedCodes(e),onDone:n}})},ore=({className:e})=>(0,V.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`currentColor`,className:B(`size-4 shrink-0`,e),"aria-hidden":!0,children:(0,V.jsx)(`path`,{d:`M10.226 17.284c-2.965-.36-5.054-2.493-5.054-5.256 0-1.123.404-2.336 1.078-3.144-.292-.741-.247-2.314.09-2.965.898-.112 2.111.36 2.83 1.01.853-.269 1.752-.404 2.853-.404 1.1 0 1.999.135 2.807.382.696-.629 1.932-1.1 2.83-.988.315.606.36 2.179.067 2.942.72.854 1.101 2 1.101 3.167 0 2.763-2.089 4.852-5.098 5.234.763.494 1.28 1.572 1.28 2.807v2.336c0 .674.561 1.056 1.235.786 4.066-1.55 7.255-5.615 7.255-10.646C23.5 6.188 18.334 1 11.978 1 5.62 1 .5 6.188.5 12.545c0 4.986 3.167 9.12 7.435 10.669.606.225 1.19-.18 1.19-.786V20.63a2.9 2.9 0 0 1-1.078.224c-1.483 0-2.359-.808-2.987-2.313-.247-.607-.517-.966-1.034-1.033-.27-.023-.359-.135-.359-.27 0-.27.45-.471.898-.471.652 0 1.213.404 1.797 1.235.45.651.921.943 1.483.943.561 0 .92-.202 1.437-.719.382-.381.674-.718.944-.943`})}),sre=({id:e,className:t})=>e===`github`?(0,V.jsx)(ore,{className:t}):null,cre=()=>(0,V.jsxs)(`div`,{className:`my-4 flex items-center gap-3 text-xs text-muted-foreground`,children:[(0,V.jsx)(`span`,{className:`h-px flex-1 bg-border`}),`or`,(0,V.jsx)(`span`,{className:`h-px flex-1 bg-border`})]}),lre=({onSubmit:e,busy:t,error:n,workspace:r,notice:i,methods:a=[`password`],onSendCode:s,onPasskey:c,passkeyDomains:l=[],forgotPassword:u,providers:d=[],onContinueWith:f,signUp:p,onBrowse:m})=>{let[h,g]=(0,o.useState)(``),[_,v]=(0,o.useState)(``),y=(0,o.useRef)(null),b=a.includes(`password`),x=a.includes(`emailCode`)&&s!==void 0,S=a.includes(`passkey`)&&c!==void 0,C=f?d:[],w=()=>{y.current?.reportValidity()&&s?.(h.trim())};return(0,V.jsxs)(Oh,{title:`Sign in to Protobase`,description:r,children:[i&&(0,V.jsx)(`p`,{role:`status`,className:`mb-4 rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:i}),(C.length>0||S)&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[C.map(e=>(0,V.jsxs)(U,{onClick:()=>f?.(e.id),disabled:t,className:`min-h-10 w-full`,children:[(0,V.jsx)(sre,{id:e.id}),`Continue with `,e.name]},e.id)),S&&(0,V.jsxs)(U,{onClick:()=>c?.(),disabled:t,className:`min-h-10 w-full`,children:[(0,V.jsx)(_t,{className:`size-4`}),`Sign in with a passkey`]}),S&&l.slice(1).map(e=>(0,V.jsxs)(U,{variant:`ghost`,size:`sm`,onClick:()=>c?.(e),disabled:t,className:`w-full`,children:[`Use a passkey made for `,e]},e))]}),b||x?(0,V.jsx)(cre,{}):n&&(0,V.jsx)(`p`,{role:`alert`,className:`mt-4 text-xs font-medium text-danger-text`,children:n})]}),(b||x)&&(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),b?e(h.trim(),_):w()},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,V.jsx)(sd,{ref:y,type:`email`,name:`email`,autoComplete:`username webauthn`,required:!0,autoFocus:!0,value:h,invalid:!!n,onChange:e=>g(e.target.value),className:`min-h-6`})]}),b&&(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Password`,(0,V.jsx)(sd,{type:`password`,name:`password`,autoComplete:`current-password`,required:!0,value:_,invalid:!!n,onChange:e=>v(e.target.value),className:`min-h-6`})]}),n&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:n}),b&&(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:t,className:`min-h-10`,children:`Sign in`}),x&&(0,V.jsxs)(U,{variant:b?`secondary`:`primary`,type:b?`button`:`submit`,onClick:b?w:void 0,loading:t&&!b,disabled:t,className:`min-h-10`,children:[(0,V.jsx)(Bt,{className:`size-4`}),`Email me a sign-in code`]}),b&&u&&(0,V.jsx)(du,{to:u,className:`self-center font-medium text-primary-text hover:underline`,children:`Forgot password?`})]}),p&&(0,V.jsxs)(`p`,{className:`mt-4 text-center text-muted-foreground`,children:[`New here?`,` `,(0,V.jsx)(du,{to:p,className:`font-medium text-primary-text hover:underline`,children:`Create an account`})]}),m&&(0,V.jsx)(`button`,{type:`button`,onClick:m,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:text-foreground hover:underline`,children:`Continue without signing in`})]})},ure=({workspace:e,notice:t,forgotPassword:n,signUp:r,onBrowse:i,onCodeSent:a,error:s})=>{let{signIn:c,signInSocial:l,signInProviders:u,signInMethods:d,passkeyDomains:f,sendSignInCode:p,signInWithPasskey:m}=H(),[h,g]=(0,o.useState)(!1),[_,v]=(0,o.useState)(s),y=async(e,t)=>{g(!0),v(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;v(t(e)),g(!1)}};return(0,V.jsx)(lre,{busy:h,error:_,workspace:e,notice:t,methods:d,forgotPassword:n,signUp:r,onBrowse:i,providers:u,onContinueWith:e=>void y(()=>l(e),Sd),passkeyDomains:f,onPasskey:e=>void y(()=>m(e),xd),onSendCode:e=>void y(async()=>{await p(e),a(e)},xd),onSubmit:(e,t)=>void y(()=>c(e,t),Sd)})},dre=({email:e,onBack:t,...n})=>(0,V.jsx)(Ah,{title:`Check your email`,description:`Enter the code we sent to create your account.`,explanation:(0,V.jsxs)(V.Fragment,{children:[`A 6-digit code is on its way to `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),`. It works for 5 minutes, once. If the address has an account already, the email says so instead.`]}),submitLabel:`Continue`,onChangeAddress:t,changeAddressLabel:`Use another address`,...n}),fre=({email:e,onSubmit:t,onBack:n,methods:r,busy:i,error:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),d=(0,o.useId)(),f=r.includes(`password`),p=r.includes(`emailCode`);return(0,V.jsxs)(Oh,{title:`Your details`,description:`One last step to create your account.`,children:[(0,V.jsxs)(`p`,{className:`mb-4 text-muted-foreground`,children:[`The code was right: the account is for `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),`.`]}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t({name:s.trim(),...f&&l&&{password:l}})},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your name`,(0,V.jsx)(sd,{name:`name`,autoComplete:`name`,required:!0,autoFocus:!0,maxLength:200,value:s,onChange:e=>c(e.target.value),className:`min-h-6`})]}),f&&(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[p?`Password (optional)`:`Password`,(0,V.jsx)(sd,{type:`password`,name:`password`,autoComplete:`new-password`,"aria-describedby":d,required:!p,minLength:12,maxLength:128,value:l,onChange:e=>u(e.target.value),className:`min-h-6`})]}),(0,V.jsxs)(`p`,{id:d,className:`text-xs text-muted-foreground`,children:[`At least `,12,` characters.`,p&&` Without one, you sign in with a code we email you.`]})]}),a&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Create account`}),(0,V.jsx)(U,{variant:`ghost`,onClick:n,className:`min-h-10`,children:`Use another address`})]})]})},pre=({onSubmit:e,onSignIn:t,onBrowse:n,busy:r,error:i,workspace:a})=>{let[s,c]=(0,o.useState)(``);return(0,V.jsxs)(Oh,{title:`Create an account`,description:a,children:[(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),e(s.trim())},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,V.jsx)(sd,{type:`email`,name:`email`,autoComplete:`email`,required:!0,autoFocus:!0,value:s,invalid:!!i,onChange:e=>c(e.target.value),className:`min-h-6`})]}),(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`We email you a code to make sure the address is yours.`}),i&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,V.jsxs)(U,{variant:`primary`,type:`submit`,loading:r,className:`min-h-10`,children:[(0,V.jsx)(Bt,{className:`size-4`}),`Email me a code`]}),(0,V.jsxs)(`p`,{className:`text-center text-muted-foreground`,children:[`Have an account?`,` `,(0,V.jsx)(`button`,{type:`button`,onClick:t,className:`font-medium text-primary-text hover:underline`,children:`Sign in`})]})]}),n&&(0,V.jsx)(`button`,{type:`button`,onClick:n,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:text-foreground hover:underline`,children:`Continue without an account`})]})},mre=({workspace:e,email:t,ticket:n,onCodeSent:r,onVerified:i,onBack:a,onSignIn:s,onBrowse:c})=>{let{signInMethods:l,sendSignUpCode:u,verifySignUpCode:d,signUp:f}=H(),[p,m]=(0,o.useState)(!1),[h,g]=(0,o.useState)(),[_,v]=(0,o.useState)(),y=async e=>{m(!0),g(void 0),v(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;g(xd(e))}m(!1)};return t===void 0?(0,V.jsx)(pre,{workspace:e,busy:p,error:h,onSignIn:s,onBrowse:c,onSubmit:e=>void y(async()=>{await u(e),r(e)})}):n===void 0?(0,V.jsx)(dre,{email:t,busy:p,error:h,notice:_,onBack:a,onSubmit:e=>void y(async()=>i(await d(t,e))),onResend:()=>void y(async()=>{await u(t),v(`A new code is on its way. Only the newest one works.`)})}):(0,V.jsx)(fre,{email:t,methods:l,busy:p,error:h,onBack:a,onSubmit:e=>void y(()=>f({ticket:n,...e}))})},Mh=`staff-sign-in`,Nh=`staff-error`,hre=e=>{let t=new URL(e).searchParams,n=t.get(Nh);if(!t.has(`staff-sign-in`)&&!n)return;let r=t.has(Mh);return{email:r&&t.get(`email`)||``,reason:r&&t.get(`reason`)||``,...n&&{error:n}}},Ph=e=>{let t=new URL(e);if(t.searchParams.has(`staff-sign-in`))for(let e of[Mh,`email`,`reason`])t.searchParams.delete(e);return t.searchParams.delete(Nh),`${t.pathname}${t.search}${t.hash}`},gre=10,_re=({operator:e,email:t=``,reason:n=``,onSubmit:r,onBack:i,busy:a,error:s})=>{let[c,l]=(0,o.useState)(t),[u,d]=(0,o.useState)(n);return e?(0,V.jsx)(Oh,{title:`Sign in as a person`,description:`For staff of ${e}, to help someone with this app.`,children:(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),r(c.trim(),u.trim())},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Their email`,(0,V.jsx)(sd,{type:`email`,name:`email`,required:!0,autoFocus:!t,value:c,onChange:e=>l(e.target.value),className:`min-h-6`})]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Reason`,(0,V.jsx)(`textarea`,{name:`reason`,required:!0,minLength:gre,rows:3,value:u,placeholder:`Ticket 4211: the invoice totals look wrong`,onChange:e=>d(e.target.value),className:B(`resize-y rounded-md border bg-background px-2.5 py-1.5 font-normal shadow-sm outline-none placeholder:text-faint-foreground focus:border-primary focus:ring-2 focus:ring-primary/20`,s?`border-danger`:`border-border-strong`)})]}),(0,V.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`You sign in at `,e,` with a passkey or a second step. The session is short, shows a banner, and cannot change their sign-in. The app's admins see who signed in as whom, and why.`]}),s&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:s}),(0,V.jsxs)(U,{variant:`primary`,type:`submit`,loading:a,className:`min-h-10`,children:[`Continue with `,e]}),(0,V.jsx)(U,{variant:`ghost`,onClick:i,className:`min-h-10`,children:`Back to sign in`})]})}):(0,V.jsxs)(Oh,{title:`Staff sign-in`,description:`Staff of the team that runs this app cannot sign in as people here.`,children:[s&&(0,V.jsx)(`p`,{role:`alert`,className:`mb-4 text-xs font-medium text-danger-text`,children:s}),(0,V.jsx)(U,{variant:`primary`,className:`min-h-10 w-full`,onClick:i,children:`Back to sign in`})]})},vre=({link:e,onBack:t})=>{let{session:n,staffSignIn:r}=H(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(e.error&&wd(e.error)),l=async(e,t)=>{a(!0),c(void 0);try{let r=`${window.location.origin}${Ph(window.location.href)}`;window.location.assign(await n.staff.start({email:e,reason:t,callbackURL:r}))}catch(e){if(!(e instanceof pc))throw e;c(wd(e)),a(!1)}};return(0,V.jsx)(_re,{operator:r,email:e.email,reason:e.reason,busy:i,error:s,onBack:t,onSubmit:(e,t)=>void l(e,t)})},Fh=({checked:e,indeterminate:t,onChange:n,label:r,disabled:i,className:a})=>(0,V.jsx)(`button`,{type:`button`,role:`checkbox`,"aria-checked":t?`mixed`:e,"aria-label":r,disabled:i,onClick:()=>n?.(!e),className:B(`relative inline-flex size-4 shrink-0 items-center justify-center rounded border transition-colors after:absolute after:-inset-1 after:content-[""] pointer-coarse:after:-inset-3.5`,e||t?`border-primary bg-primary text-primary-foreground`:`border-border-strong bg-background hover:border-faint-foreground`,a),children:t?(0,V.jsx)(Wt,{className:`size-3`,strokeWidth:3}):e&&(0,V.jsx)(ge,{className:`size-3`,strokeWidth:3})}),yre={totp:`Enter the 6-digit code from your authenticator app.`,otp:`Enter the 6-digit code we emailed you. It works for 5 minutes.`,backup:`Enter one of the backup codes you saved when you set up the authenticator app. Each works once.`},bre=({methods:e,onVerify:t,onSendCode:n,onBack:r,busy:i,error:a,codeSent:s,initialStep:c})=>{let[l,u]=(0,o.useState)(c??(e.includes(`totp`)?`totp`:`otp`)),[d,f]=(0,o.useState)(``),[p,m]=(0,o.useState)(!1),h=l===`otp`&&!s,g=e=>{u(e),f(``),e===`otp`&&!s&&n()};return(0,V.jsxs)(Oh,{title:`Two-factor authentication`,description:`One more step to sign in.`,children:[h?(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`We email you a code to finish signing in.`}),a&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,V.jsx)(U,{variant:`primary`,loading:i,onClick:n,className:`min-h-10`,children:`Email me a code`})]}):(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t({method:l,code:d.trim(),trustDevice:p})},children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:yre[l]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[l===`backup`?`Backup code`:`Code`,l===`backup`?(0,V.jsx)(sd,{name:`code`,autoComplete:`off`,spellCheck:!1,required:!0,autoFocus:!0,value:d,invalid:!!a,onChange:e=>f(e.target.value),className:`min-h-6 font-mono`}):(0,V.jsx)(If,{name:`code`,required:!0,autoFocus:!0,value:d,invalid:!!a,onChange:f})]}),(0,V.jsxs)(`label`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Fh,{checked:p,onChange:m,label:`Trust this browser`}),`Don't ask again in this browser for 30 days`]}),a&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Verify`})]}),(0,V.jsxs)(`div`,{className:`mt-4 flex flex-col items-center gap-2 border-t pt-4`,children:[l!==`totp`&&e.includes(`totp`)&&(0,V.jsx)(`button`,{type:`button`,onClick:()=>g(`totp`),className:`font-medium text-primary-text hover:underline`,children:`Use the authenticator app`}),l!==`otp`&&e.includes(`otp`)&&(0,V.jsx)(`button`,{type:`button`,onClick:()=>g(`otp`),className:`font-medium text-primary-text hover:underline`,children:`Email me a code instead`}),l!==`backup`&&e.includes(`totp`)&&(0,V.jsx)(`button`,{type:`button`,onClick:()=>g(`backup`),className:`font-medium text-primary-text hover:underline`,children:`Use a backup code`}),(0,V.jsx)(`button`,{type:`button`,onClick:r,className:`font-medium text-muted-foreground hover:underline`,children:`Back to sign in`})]})]})},xre=({methods:e,onBack:t})=>{let{verifyTwoFactor:n,session:r}=H(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(!1),d=async e=>{a(!0),c(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;c(xd(e))}a(!1)};return(0,V.jsx)(bre,{methods:e,busy:i,error:s,codeSent:l,onBack:t,onVerify:e=>void d(()=>n(e)),onSendCode:()=>void d(async()=>{await r.sendTwoFactorCode(),u(!0)})})},Ih=()=>{let{path:e,params:t,basePath:n,navigate:r}=wh(),i=(0,o.useMemo)(()=>ws(e,t),[e,t]),a=jd(new URL(t.size>0?`${e}?${t}`:e,`http://local`).href),s=i?i.next:a,c=(0,o.useCallback)((e=`sign-in`,t)=>r(Cs({step:e,next:s}),t),[r,s]);return{address:i,next:s,open:c,link:(0,o.useCallback)((e=`sign-in`,t)=>({href:`${n}${Cs({step:e,next:s})}`,onFollow:()=>c(e,t)}),[n,s,c]),leave:(0,o.useCallback)(()=>r(s??`/`,{replace:!0}),[r,s])}},Sre=e=>{let t=new URL(e),n=t.searchParams.get(`token`);return t.pathname.endsWith(`/-/invitation`)&&n?{token:n}:void 0},Cre=e=>`${new URL(e).pathname.slice(0,-13)}/`,Lh=`/-/organizations`,Rh=`/-/organization`,zh=`/-/organization/members`,Bh=`/-/organization/invitations`,wre={[Lh]:`Organizations`,[Rh]:`Organization`,[zh]:`Members`,[Bh]:`Invitations`},Vh={owner:`Owner`,admin:`Admin`,member:`Member`},Hh=(e,t)=>e.find(e=>e.name===t)?.label??t,Uh=e=>e?.role===`owner`||e?.role===`admin`,Tre=(e,t,n)=>{let r=(n,r,i,a)=>({id:n,label:r,icon:i,href:`${e}${a}`,active:t===a});return[r(`organizations`,`Organizations`,Xt,Lh),...n?.organization?[r(`organization`,`Organization`,ue,Rh)]:[],...Uh(n)?[r(`members`,`Members`,Jn,zh),r(`invitations`,`Invitations`,Bt,Bh)]:[]]},Wh=(e,t)=>{let n=[...t?.globalRoles??[],...t?.appRoles??[]],r=e.filter(e=>e.membership).map(e=>e.name);if(n.includes(`admin`))return new Set(r);let i=n.flatMap(t=>e.find(e=>e.name===t)?.grants??[]);return new Set([...n,...i].filter(e=>r.includes(e)))},Gh=()=>{let[e,t]=(0,o.useState)(!1),[n,r]=(0,o.useState)();return{busy:e,error:n,run:async e=>{t(!0),r(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;r(xd(e))}t(!1)},setError:r}},Ere=({token:e,preview:t,onDone:n})=>{let{session:r,signInMethods:i,recheck:a}=H(),[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),{busy:d,error:f,run:p}=Gh(),m=i.includes(`password`),h=i.includes(`emailCode`),g=()=>p(async()=>{await r.organizations.signUpFromInvitation(e,{name:s.trim(),...m&&l&&{password:l}}),n(),a()});return(0,V.jsxs)(`form`,{className:`flex flex-col gap-3`,onSubmit:e=>{e.preventDefault(),g()},children:[(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Make your account for `,t.email,` to join.`]}),f&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:f}),(0,V.jsx)(sd,{"aria-label":`Your name`,placeholder:`Your name`,autoComplete:`name`,value:s,onChange:e=>c(e.target.value)}),m&&(0,V.jsx)(sd,{"aria-label":`Password`,type:`password`,autoComplete:`new-password`,placeholder:h?`Password (optional, 12+ characters)`:`Password (12+ characters)`,value:l,onChange:e=>u(e.target.value)}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:d,disabled:!s.trim()||m&&!h&&l.length<12,children:`Create account and join`})]})},Dre=({token:e,onDone:t,signIn:n})=>{let{session:r,state:i,signOut:a,organizations:s}=H(),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(),{busy:f,error:p,run:m}=Gh();if((0,o.useEffect)(()=>{r.organizations.invitation(e).then(l,e=>d(e instanceof pc?xd(e):`This invitation link is not valid`))},[r,e]),u)return(0,V.jsx)(Oh,{title:`Invitation`,description:u,children:(0,V.jsx)(U,{className:`w-full`,onClick:t,children:`Go to the app`})});if(!c)return(0,V.jsx)(Oh,{title:`Invitation`,children:(0,V.jsxs)(`div`,{className:`flex items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})});let h=c.appRoles.map(e=>Hh(s?.roles??[],e)),g=`${c.inviter.name} invites you to ${c.organization.name} as ${Vh[c.role].toLowerCase()}${h.length>0?`, with ${h.join(`, `)}`:``}.`,_=i.kind===`signed-in`?i.user:void 0;return _&&_.email.toLowerCase()!==c.email.toLowerCase()?(0,V.jsxs)(Oh,{title:`Join ${c.organization.name}`,description:g,children:[(0,V.jsxs)(`p`,{className:`mb-3 text-muted-foreground`,children:[`This invitation is for `,c.email,`, and you are signed in as `,_.email,`.`]}),(0,V.jsx)(U,{className:`w-full`,onClick:()=>void a(),children:`Sign out to accept it`})]}):(0,V.jsx)(Oh,{title:`Join ${c.organization.name}`,description:g,children:_?(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[p&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:p}),(0,V.jsxs)(U,{variant:`primary`,className:`w-full`,loading:f,onClick:()=>void m(async()=>{await r.organizations.accept(e),t()}),children:[`Join `,c.organization.name]})]}):c.hasAccount?(0,V.jsxs)(du,{to:n,className:B(Cf({variant:`primary`}),`w-full`),children:[`Sign in as `,c.email,` to join`]}):(0,V.jsx)(Ere,{token:e,preview:c,onDone:t})})},Ore=`modulepreload`,kre=function(e){return`/`+e},Kh={},Are=function(e){return e.pathname.endsWith(`.css`)},qh=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=kre(t,n);let r=s(t);if(r.href in Kh)return;Kh[r.href]=!0;let i=Are(r);if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let o=document.createElement(`link`);if(o.rel=i?`stylesheet`:Ore,i||(o.as=`script`),o.crossOrigin=``,o.href=r.href,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),i)return new Promise((e,t)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>t(Error(`Unable to preload CSS for ${r}`)))})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Jh,Yh,jre=({dsn:e,environment:t})=>(Jh??=qh(()=>import(`./prod-YZ9ZMG1O.js`).then(n=>{n.init({dsn:e,...t&&{environment:t},integrations:e=>e.filter(e=>e.name!==`BrowserSession`),beforeSend:e=>Ko(e)}),Yh=(e,t)=>n.captureException(e,t?{contexts:{react:{componentStack:t}}}:void 0)}),[]),Jh),Xh=(e,t)=>Yh?.(e,t??void 0),Zh=({children:e})=>(0,V.jsx)(`div`,{role:`alert`,className:`rounded-lg border border-dashed border-warning bg-warning-soft p-3 text-warning-text`,children:e}),Qh=class extends o.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e,t){Xh(e,t.componentStack)}render(){return this.state.failed?this.props.fallback===void 0?(0,V.jsxs)(Zh,{children:[this.props.name,` could not be drawn.`]}):this.props.fallback:this.props.children}},Mre=/^[A-Z][A-Za-z0-9]*$/,Nre=e=>typeof e==`function`||typeof e==`object`&&!!e&&`$$typeof`in e,$h=e=>{let t=e.default??{},n=Object.entries(e).filter(e=>e[0]!=="default"&&Mre.test(e[0])&&Nre(e[1]));if(n.length===0)return t;for(let[e,r]of n)if(t.components&&Object.hasOwn(t.components,e)&&t.components[e]!==r)throw Error(`The component "${e}" is exported by name and given in components as another one; keep the export`);return{...t,components:{...t.components,...Object.fromEntries(n)}}},eg=class extends Error{name=`UiConflictError`},Pre=e=>Object.keys(e).some(e=>e==="default"||/^[A-Z]/.test(e))?$h(e):e,tg=(e,t)=>[...(e.extends??[]).map(Pre).flatMap((e,n)=>tg(e,e.name??`${t} extends[${n}]`)),{ui:e,label:t}],ng=(e,t,n)=>{let r={},i=new Map;for(let{ui:a,label:o}of t)for(let[t,s]of Object.entries(n(a)??{})){if(Object.hasOwn(r,t)&&r[t]!==s)throw new eg(`${e} "${t}" is defined twice, by ${i.get(t)} and by ${o}; rename one of them`);r[t]=s,i.set(t,i.get(t)??o)}return r},rg=e=>e.length<=1?e[0]:()=>e.map((e,t)=>(0,V.jsx)(e,{},t)),Fre=e=>e.length<=1?e[0]:({children:t,...n})=>e.reduceRight((e,t)=>(0,V.jsx)(t,{...n,children:e}),t),ig=(...e)=>{let t=e.flatMap((e,t)=>tg(e,e.name??`UI config ${t+1}`)),n=ng(`The component`,t,e=>e.components),r=ng(`The action handler`,t,e=>e.actions),i=ng(`The field type`,t,e=>e.fields),a=rg(t.flatMap(({ui:e})=>e.shell?.actions?[e.shell.actions]:[])),o=rg(t.flatMap(({ui:e})=>e.shell?.rightPanel?[e.shell.rightPanel]:[])),s=t.findLast(({ui:e})=>e.shell?.logo)?.ui.shell?.logo,c=Fre(t.flatMap(({ui:e})=>e.beforeSignIn?[e.beforeSignIn]:[])),l=e.at(-1)?.name;return{...l&&{name:l},components:n,actions:r,...Object.keys(i).length>0&&{fields:i},...(a||o||s)&&{shell:{...a&&{actions:a},...o&&{rightPanel:o},...s&&{logo:s}}},...c&&{beforeSignIn:c}}},ag=(e,t)=>{let n=ig(e??{}),r=[],i=[];for(let e of t){if(e.kind===`off`){i.push(e);continue}try{ig(...r,e.ui,n),r.push(e.ui)}catch(t){if(!(t instanceof eg))throw t;i.push({kind:`off`,url:e.plugin.url,name:e.plugin.name,reason:t.message})}}return{ui:r.length===0?n:ig(...r,n),off:i}},og=e=>typeof e==`string`&&e.trim()!==``,Ire=e=>{if(typeof e!=`object`||!e||Array.isArray(e))return{problem:`its plugin.json is not an object`};let{name:t,version:n,api:r,protobase:i,entry:a,css:o}=e;return og(t)?Number.isInteger(r)?og(i)?og(a)?o!==void 0&&!og(o)?{problem:`its plugin.json names a stylesheet that is no URL`}:n!==void 0&&!og(n)?{problem:`its plugin.json has a version that is no text`}:{manifest:{name:t,api:r,protobase:i,entry:a,...n!==void 0&&{version:n},...o!==void 0&&{css:o}}}:{problem:`its plugin.json names no module`}:{problem:`its plugin.json names no Protobase versions`}:{problem:`its plugin.json names no plugin API`}:{problem:`its plugin.json names no plugin`}},sg=(0,o.createContext)(null),Lre=sg.Provider,Rre=()=>{let e=(0,o.useContext)(sg);if(!e)throw Error(`usePlugin is for the components of a plugin the app loaded`);return e},cg=(e,t,n)=>{let r=n=>(0,V.jsx)(Lre,{value:e,children:(0,V.jsx)(t,{...n})});return r.displayName=`${e.name}:${n}`,r},zre=(e,t,n)=>({of:n.of,display:cg(e,n.display,`fields.${t}.display`),...n.editor&&{editor:cg(e,n.editor,`fields.${t}.editor`)},...n.cell&&{cell:cg(e,n.cell,`fields.${t}.cell`)}}),Bre=(e,t)=>{let n=ig({...$h(t),name:e.name}),r=Object.fromEntries(Object.entries(n.components??{}).map(([t,n])=>[t,cg(e,n,t)])),i=n.fields&&Object.fromEntries(Object.entries(n.fields).map(([t,n])=>[t,zre(e,t,n)])),a=n.shell&&{...n.shell.actions&&{actions:cg(e,n.shell.actions,`shell.actions`)},...n.shell.rightPanel&&{rightPanel:cg(e,n.shell.rightPanel,`shell.rightPanel`)}},o=n.beforeSignIn&&cg(e,n.beforeSignIn,`beforeSignIn`);return{name:e.name,components:r,...n.actions&&{actions:n.actions},...i&&{fields:i},...a&&{shell:a},...o&&{beforeSignIn:o}}},lg={name:`@protobase/ui`,version:`0.21.9`,description:`The Protobase admin app and the React hooks and components for custom UI.`,license:`Apache-2.0`,repository:{type:`git`,url:`git+https://github.com/PrototeamHQ/protobase.git`,directory:`packages/ui`},homepage:`https://docs.protobase.net`,type:`module`,protobase:{pluginApi:1},sideEffects:[`*.css`,`./dist/app/main.js`],engines:{node:`>=22.12.0`},exports:{".":`./src/index.ts`,"./theme.css":`./src/theme.css`,"./styles.css":`./src/styles.css`},types:`./src/index.ts`,files:[`dist`],scripts:{build:`tsdown && protobase build-shell dist/shell`,prepack:`tsdown && protobase build-shell dist/shell`},publishConfig:{access:`public`,exports:{".":`./dist/index.js`,"./theme.css":`./dist/theme.css`,"./styles.css":`./dist/styles.css`},types:`./dist/index.d.ts`},dependencies:{"@dnd-kit/core":`^6.3.1`,"@dnd-kit/sortable":`^10.0.0`,"@protobase/client":`workspace:*`,"@protobase/layout":`workspace:*`,"@protobase/schema":`workspace:*`,"@sentry/browser":`^11.7.0`,"@tanstack/react-query":`^5.104.1`,"@tanstack/react-table":`^9.2.6`,"altcha-lib":`^2.6.0`,dompurify:`^3.4.17`,fflate:`^0.8.3`,"lucide-react":`^1.52.0`,"maplibre-gl":`^6.14.0`,marked:`^18.1.1`,pmtiles:`^4.5.0`,react:`^19.3.0`,"react-dom":`^19.3.0`,"react-map-gl":`^8.1.3`,recharts:`^3.10.1`,tailwindcss:`^4.3.3`,thumbhash:`^0.1.1`,uqr:`^0.1.3`}},ug=lg.protobase.pluginApi,dg=lg.version,Vre={readJson:async e=>{let t=await fetch(e,{cache:`no-cache`,credentials:`same-origin`});return t.ok?{json:await t.json()}:{status:t.status}},addStylesheet:e=>{if([...document.querySelectorAll(`link[rel="stylesheet"]`)].some(t=>t.href===e))return;let t=document.createElement(`link`);t.rel=`stylesheet`,t.href=e,document.head.append(t)},importModule:e=>qh(()=>import(e),[])},Hre={api:ug,version:dg},Ure=e=>e instanceof Error?e.message:String(e),Wre=async(e,t,n,r=Hre)=>{let i=new URL(e.url,n).href,a=(e,t)=>({kind:`off`,url:i,...t&&{name:t},reason:e}),o;try{let n=await t.readJson(i);if(`status`in n)return a(`its plugin.json answered ${n.status}`);let s=Ire(n.json);if(`problem`in s)return a(s.problem);let{manifest:c}=s;o=c.name;let l=Lo(c,r);if(l)return a(l,o);c.css&&t.addStylesheet(new URL(c.css,i).href);let u=await t.importModule(new URL(c.entry,i).href),d={name:o,...c.version&&{version:c.version},url:i,settings:e.settings??{}};return{kind:`loaded`,plugin:d,ui:Bre(d,u)}}catch(e){return a(`it could not be loaded: ${Ure(e)}`,o)}},Gre=e=>{let t=new Map;return{load:n=>{let r=JSON.stringify(n),i=t.get(r);if(i)return i;let a=Wre(n,e,window.location.href);return t.set(r,a),a}}},fg=(0,o.createContext)(null),Kre=({loader:e=Vre,children:t})=>{let n=(0,o.useMemo)(()=>Gre(e),[e]);return(0,V.jsx)(fg.Provider,{value:n,children:t})},pg=()=>{let e=(0,o.useContext)(fg);if(!e)throw Error(`usePluginSource must be used inside PluginSourceProvider`);return e},qre=1e4,mg=[],hg=(e,t)=>{let n=JSON.stringify(e),[r,i]=(0,o.useState)({key:`[]`,loads:mg,settled:!0});return(0,o.useEffect)(()=>{if(e.length===0)return;let r=!0,a=!1,o=e.map(()=>void 0),s=()=>{if(!r)return;let t=o.filter(e=>e!==void 0);i({key:n,loads:t,settled:a||t.length===e.length})},c=setTimeout(()=>{a=!0,s()},qre);return e.forEach((e,n)=>{t.load(e).then(e=>{o[n]=e,s()})}),()=>{r=!1,clearTimeout(c)}},[n,t]),e.length===0?{loads:mg,settled:!0}:r.key===n?r:{loads:mg,settled:!1}},Jre=({children:e})=>{let{state:t,beforeSignIn:n,adoptSession:r}=H(),{path:i,params:a,navigate:s}=wh(),{loads:c,settled:l}=hg(n,pg()),u=(0,o.useMemo)(()=>ag(void 0,c).ui.beforeSignIn,[c]),d=(0,o.useCallback)(e=>{let t=new URLSearchParams(a);for(let n of e)t.delete(n);s(t.size>0?`${i}?${t}`:i,{replace:!0})},[i,a,s]);return t.kind!==`signed-out`&&t.kind!==`visitor`?e:l?u?(0,V.jsx)(Qh,{name:`beforeSignIn`,fallback:e,children:(0,V.jsx)(u,{signedIn:r,params:a,removeParams:d,children:e})}):e:(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})},Yre=()=>{let e=window.location.href,t=Yne(e);if(t)return{kind:`reset-password`,token:t.token};let n=hre(e);if(n)return{kind:`staff-sign-in`,link:n};let r=Sre(e);if(r)return{kind:`invitation`,token:r.token};let i=kd(e);if(i)return{kind:`provider-sign-in`,provider:i};let a=Ad(e);return a?{kind:`sign-in`,providerError:a}:{kind:`sign-in`}},gg=({to:e})=>{let{navigate:t}=wh();return(0,o.useEffect)(()=>t(e,{replace:!0}),[t,e]),null},Xre=({workspace:e,children:t})=>{let n=Zre(e,t);return(0,V.jsx)(Jre,{children:n})},Zre=(e,t)=>{let{state:n,recheck:r,passwordReset:i,signOut:a,signInProviders:s,canSignUp:c,browse:l}=H(),{path:u,params:d,basePath:f,navigate:p}=wh(),{address:m,next:h,open:g,link:_,leave:v}=Ih(),[y,b]=(0,o.useState)(Yre),[x,S]=(0,o.useState)(),[C,w]=(0,o.useState)(),[T,E]=(0,o.useState)(),D=new URL(`${f}${u}${d.size>0?`?${d}`:``}`,window.location.origin).href,O=(0,o.useCallback)(e=>{let t=e(D).slice(f.length);p(t.startsWith(`/`)?t:`/${t}`,{replace:!0})},[D,f,p]),k=n.kind===`signed-in`||n.kind===`two-factor`||n.kind===`setup-required`;(0,o.useEffect)(()=>{k&&(y.kind===`provider-sign-in`&&O(jd),(y.kind===`provider-sign-in`||y.kind===`sign-in`&&(y.notice||y.error||y.providerError))&&b({kind:`sign-in`}),S(void 0),w(void 0),E(void 0))},[k,y,O]);let A=m!==void 0&&Ad(D)!==void 0;(0,o.useEffect)(()=>{!k&&y.kind===`sign-in`&&y.providerError&&A&&O(jd)},[k,y,A,O]);let j=(0,o.useCallback)(e=>b({kind:`sign-in`,error:e}),[]),M=e=>{O(Xne),b(e)},N=async()=>{n.kind===`signed-in`&&await a(),M({kind:`sign-in`,notice:`Your password is changed. Sign in with the new one.`})},ee=()=>{b({kind:`sign-in`}),a().then(()=>g(`sign-in`,{replace:!0}))};switch(n.kind){case`loading`:return(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]});case`error`:return(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Cannot reach the server: `,n.message]}),(0,V.jsx)(U,{onClick:r,children:`Try again`})]});case`needs-admin`:return(0,V.jsx)(Kne,{onCheckAgain:r})}if(n.kind===`signed-in`&&m)return(0,V.jsx)(gg,{to:h??`/`});if(y.kind===`reset-password`)return(0,V.jsx)(nre,{token:y.token,onDone:()=>void N(),onRequestNewLink:i?()=>{b({kind:`sign-in`}),p(Cs({step:`forgot-password`}),{replace:!0})}:void 0,onBack:()=>M({kind:`sign-in`})});if(y.kind===`staff-sign-in`)return(0,V.jsx)(vre,{link:y.link,onBack:()=>{O(Ph),b({kind:`sign-in`})}});let P=n.kind===`signed-out`||n.kind===`visitor`;if(y.kind===`invitation`&&(n.kind===`signed-in`||P&&!m))return(0,V.jsx)(Dre,{token:y.token,onDone:()=>{O(Cre),b({kind:`sign-in`})},signIn:_()});if(n.kind===`signed-in`)return t;if(n.kind===`two-factor`)return(0,V.jsx)(xre,{methods:n.methods,onBack:ee});if(n.kind===`setup-required`)return(0,V.jsx)(are,{missing:n.missing},n.missing.join());if(y.kind===`provider-sign-in`)return(0,V.jsx)($ne,{provider:y.provider,workspace:e,onFailed:j});let te=y.kind===`sign-in`?y:{kind:`sign-in`};if(!m){let e=te.notice||te.error||te.providerError;return n.kind===`visitor`&&!e?t:(0,V.jsx)(gg,{to:Cs({next:h})})}let F={"sign-in":!0,"forgot-password":i,"email-code":x!==void 0,"sign-up":c,"sign-up-code":c&&C!==void 0,"sign-up-details":c&&T!==void 0}[m.step]?m.step:`sign-in`,ne=e=>()=>g(e,{replace:!0}),re=l&&(()=>{l(),v()});if(F===`forgot-password`)return(0,V.jsx)(Zne,{back:_(`sign-in`,{replace:!0})});if(F===`email-code`)return(0,V.jsx)(Wne,{email:x,onBack:ne(`sign-in`)});if(F===`sign-up`||F===`sign-up-code`||F===`sign-up-details`)return(0,V.jsx)(mre,{workspace:e,email:F===`sign-up`?void 0:C,ticket:F===`sign-up-details`?T:void 0,onCodeSent:e=>{w(e),E(void 0),g(`sign-up-code`)},onVerified:e=>{E(e),g(`sign-up-details`,{replace:!0})},onBack:ne(`sign-up`),onSignIn:()=>g(`sign-in`),onBrowse:re},F);let ie=te.providerError&&Ed(te.providerError,s.length===1?s[0].name:`the provider`),I=te.error??ie;return(0,V.jsx)(ure,{workspace:e,notice:te.notice,error:I,forgotPassword:i?_(`forgot-password`):void 0,onCodeSent:e=>{S(e),g(`email-code`)},signUp:c?_(`sign-up`):void 0,onBrowse:re},I)},_g=e=>[...e].reduce((e,t)=>(e*31+t.charCodeAt(0))%360,7),vg=e=>e.split(/[\s@.]+/).filter(Boolean).slice(0,2).map(e=>e[0].toUpperCase()).join(``),yg=e=>(e.role??`user`).split(`,`).map(e=>e.trim()),bg=e=>yg(e).includes(`admin`),Qre=e=>{let t=yg(e),n=t.includes(`admin`);return{name:e.name||e.email,email:e.email,initials:vg(e.name||e.email)||`?`,hue:_g(e.id||e.email),role:n?`Admin`:(t[0]??`user`).replace(/^./,e=>e.toUpperCase()),roleTone:n?`violet`:`blue`}},$re=3e4,eie=(e,t=Date.now())=>Math.max(1e3,Fl(e)-t-$re),xg=()=>{let{state:e,session:t}=H(),n=e.kind===`signed-in`,[r,i]=(0,o.useState)();return(0,o.useEffect)(()=>{if(!n)return;let e=!0,r,a=async n=>{let o=await t.token(),s=o!==void 0&&o===n?await t.token({refresh:!0}):o;e&&(i(s),s&&(r=setTimeout(()=>void a(s),eie(s))))};return a(),()=>{e=!1,clearTimeout(r)}},[t,n]),n?r:void 0},Sg=(e,t,n=!0)=>{let r=G(),i=Ao(t);return mh({queryKey:W.record(e,i),enabled:n,queryFn:()=>r.get(e,t)})},Cg=(e,t,n=!0)=>{let r=G(),i=Gp(),a=Ao(t);return mh({queryKey:W.record(e,a),enabled:n,queryFn:()=>r.get(e,t),placeholderData:()=>i.getQueryData(W.recordPreview(e,a))})},tie=e=>e.charAt(0).toUpperCase()+e.slice(1),K=e=>tie(e.replace(/(Id|Code|_id|_code)$/,``).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/_+/g,` `).trim().toLowerCase()||e);function nie(){var e=[...arguments];return(0,o.useMemo)(()=>t=>{e.forEach(e=>e(t))},e)}var wg=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function Tg(e){let t=Object.prototype.toString.call(e);return t===`[object Window]`||t===`[object global]`}function Eg(e){return`nodeType`in e}function Dg(e){return e?Tg(e)?e:Eg(e)?e.ownerDocument?.defaultView??window:window:window}function Og(e){let{Document:t}=Dg(e);return e instanceof t}function kg(e){return!Tg(e)&&e instanceof Dg(e).HTMLElement}function Ag(e){return e instanceof Dg(e).SVGElement}function jg(e){return e?Tg(e)?e.document:Eg(e)?Og(e)?e:kg(e)||Ag(e)?e.ownerDocument:document:document:document}var Mg=wg?o.useLayoutEffect:o.useEffect;function Ng(e){let t=(0,o.useRef)(e);return Mg(()=>{t.current=e}),(0,o.useCallback)(function(){var e=[...arguments];return t.current==null?void 0:t.current(...e)},[])}function rie(){let e=(0,o.useRef)(null);return[(0,o.useCallback)((t,n)=>{e.current=setInterval(t,n)},[]),(0,o.useCallback)(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[])]}function Pg(e,t){t===void 0&&(t=[e]);let n=(0,o.useRef)(e);return Mg(()=>{n.current!==e&&(n.current=e)},t),n}function Fg(e,t){let n=(0,o.useRef)();return(0,o.useMemo)(()=>{let t=e(n.current);return n.current=t,t},[...t])}function Ig(e){let t=Ng(e),n=(0,o.useRef)(null);return[n,(0,o.useCallback)(e=>{e!==n.current&&t?.(e,n.current),n.current=e},[])]}function Lg(e){let t=(0,o.useRef)();return(0,o.useEffect)(()=>{t.current=e},[e]),t.current}var Rg={};function zg(e,t){return(0,o.useMemo)(()=>{if(t)return t;let n=Rg[e]==null?0:Rg[e]+1;return Rg[e]=n,e+`-`+n},[e,t])}function Bg(e){return function(t){return[...arguments].slice(1).reduce((t,n)=>{let r=Object.entries(n);for(let[n,i]of r){let r=t[n];r!=null&&(t[n]=r+e*i)}return t},{...t})}}var Vg=Bg(1),Hg=Bg(-1);function iie(e){return`clientX`in e&&`clientY`in e}function Ug(e){if(!e)return!1;let{KeyboardEvent:t}=Dg(e.target);return t&&e instanceof t}function aie(e){if(!e)return!1;let{TouchEvent:t}=Dg(e.target);return t&&e instanceof t}function Wg(e){if(aie(e)){if(e.touches&&e.touches.length){let{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}if(e.changedTouches&&e.changedTouches.length){let{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return iie(e)?{x:e.clientX,y:e.clientY}:null}var Gg=Object.freeze({Translate:{toString(e){if(!e)return;let{x:t,y:n}=e;return`translate3d(`+(t?Math.round(t):0)+`px, `+(n?Math.round(n):0)+`px, 0)`}},Scale:{toString(e){if(!e)return;let{scaleX:t,scaleY:n}=e;return`scaleX(`+t+`) scaleY(`+n+`)`}},Transform:{toString(e){if(e)return[Gg.Translate.toString(e),Gg.Scale.toString(e)].join(` `)}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+` `+n+`ms `+r}}}),Kg=`a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]`;function oie(e){return e.matches(Kg)?e:e.querySelector(Kg)}var sie={display:`none`};function cie(e){let{id:t,value:n}=e;return o.createElement(`div`,{id:t,style:sie},n)}function lie(e){let{id:t,announcement:n,ariaLiveType:r=`assertive`}=e;return o.createElement(`div`,{id:t,style:{position:`fixed`,top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:`hidden`,clip:`rect(0 0 0 0)`,clipPath:`inset(100%)`,whiteSpace:`nowrap`},role:`status`,"aria-live":r,"aria-atomic":!0},n)}function uie(){let[e,t]=(0,o.useState)(``);return{announce:(0,o.useCallback)(e=>{e!=null&&t(e)},[]),announcement:e}}var qg=(0,o.createContext)(null);function die(e){let t=(0,o.useContext)(qg);(0,o.useEffect)(()=>{if(!t)throw Error(`useDndMonitor must be used within a children of <DndContext>`);return t(e)},[e,t])}function fie(){let[e]=(0,o.useState)(()=>new Set),t=(0,o.useCallback)(t=>(e.add(t),()=>e.delete(t)),[e]);return[(0,o.useCallback)(t=>{let{type:n,event:r}=t;e.forEach(e=>e[n]?.call(e,r))},[e]),t]}var pie={draggable:`
|
|
6
|
+
at `))}function gte(e,t){class n extends e{#e;constructor(...e){if(mte()){let t=Error.stackTraceLimit;Error.stackTraceLimit=0,super(...e),Error.stackTraceLimit=t}else super(...e);let t=Error().stack;t&&(this.#e=hte(t.replace(/^Error/,this.name)))}get errorStack(){return this.#e}}return Object.defineProperty(n.prototype,"constructor",{get(){return t},enumerable:!1,configurable:!0}),n}var _te={OK:200,CREATED:201,ACCEPTED:202,NO_CONTENT:204,MULTIPLE_CHOICES:300,MOVED_PERMANENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TOO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,"I'M_A_TEAPOT":418,MISDIRECTED_REQUEST:421,UNPROCESSABLE_ENTITY:422,LOCKED:423,FAILED_DEPENDENCY:424,TOO_EARLY:425,UPGRADE_REQUIRED:426,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,LOOP_DETECTED:508,NOT_EXTENDED:510,NETWORK_AUTHENTICATION_REQUIRED:511};gte(class extends Error{status;body;headers;statusCode;constructor(e=`INTERNAL_SERVER_ERROR`,t=void 0,n={},r=typeof e==`number`?e:_te[e]){super(t?.message,t?.cause?{cause:t.cause}:void 0),this.status=e,this.body=t,this.headers=n,this.statusCode=r,this.name=`APIError`,this.status=e,this.headers=n,this.statusCode=r,this.body=t}},Error);var ll=class extends Error{constructor(e,t){super(e,t),this.name=`BetterAuthError`,this.message=e,this.stack=``}},vte=47;function ul(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===vte;)t--;return t===e.length?e:e.slice(0,t)}function yte(e){try{return(ul(new URL(e).pathname)||`/`)!==`/`}catch{throw new ll(`Invalid base URL: ${e}. Please provide a valid base URL.`)}}function bte(e){try{let t=new URL(e);if(t.protocol!==`http:`&&t.protocol!==`https:`)throw new ll(`Invalid base URL: ${e}. URL must include 'http://' or 'https://'`)}catch(t){throw t instanceof ll?t:new ll(`Invalid base URL: ${e}. Please provide a valid base URL.`,{cause:t})}}function dl(e,t=`/api/auth`){if(bte(e),yte(e))return e;let n=ul(e);return!t||t===`/`?n:(t=t.startsWith(`/`)?t:`/${t}`,`${n}${t}`)}function fl(e,t){return!e||e.trim()===``?!1:t===`proto`?e===`http`||e===`https`:t===`host`?[/\.\./,/\0/,/[\s]/,/^[.]/,/[<>'"]/,/javascript:/i,/file:/i,/data:/i].some(t=>t.test(e))?!1:/^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*(:[0-9]{1,5})?$/.test(e)||/^(\d{1,3}\.){3}\d{1,3}(:[0-9]{1,5})?$/.test(e)||/^\[[0-9a-fA-F:]+\](:[0-9]{1,5})?$/.test(e)||/^localhost(:[0-9]{1,5})?$/i.test(e):!1}function xte(e,t,n,r,i){if(e)return dl(e,t);if(r!==!1){let e=sl.BETTER_AUTH_URL||sl.NEXT_PUBLIC_BETTER_AUTH_URL||sl.PUBLIC_BETTER_AUTH_URL||sl.NUXT_PUBLIC_BETTER_AUTH_URL||sl.NUXT_PUBLIC_AUTH_URL||(sl.BASE_URL===`/`?void 0:sl.BASE_URL);if(e)return dl(e,t)}let a=n?.headers.get(`x-forwarded-host`),o=n?.headers.get(`x-forwarded-proto`);if(a&&o&&i&&fl(o,`proto`)&&fl(a,`host`))try{return dl(`${o}://${a}`,t)}catch{}if(n){let e=Ste(n.url);if(!e)throw new ll(`Could not get origin from request. Please provide a valid base URL.`);return dl(e,t)}if(typeof window<`u`&&window.location)return dl(window.location.origin,t)}function Ste(e){try{let t=new URL(e);return t.origin===`null`?null:t.origin}catch{return null}}var Cte=[`javascript:`,`data:`,`vbscript:`];function pl(e){let t;try{t=new URL(e)}catch{return!0}return!Cte.includes(t.protocol)}var wte={id:`redirect`,name:`Redirect`,hooks:{onSuccess(e){if(e.data?.url&&e.data?.redirect&&pl(e.data.url)&&typeof window<`u`&&window.location&&window.location)try{window.location.href=e.data.url}catch{}}}},Tte=()=>typeof window>`u`,Ete=qc;function Dte(e,t){if(typeof window>`u`)return;let n=e.get();n.data===null&&t!==null&&e.set({...n,data:t,error:null,isPending:!1})}function ml(e){return typeof e==`object`&&e&&`data`in e&&`error`in e?e:{data:e,error:null}}function Ote(e){return!e||e.session===null&&e.user===null?null:e}function kte(e,t){return Xc(e.data,t.data)&&e.error===t.error&&e.isPending===t.isPending&&e.isRefetching===t.isRefetching&&e.refetch===t.refetch}function Ate(e,t){let n=Uc(!1),r,i=0,a=0;n.listen(()=>{a++,i=0});let o=e=>u(e),s=rl({data:null,error:null,isPending:!0,isRefetching:!1,refetch:o});Zc(s,kte);let c=async(t,n)=>{let r=s.value;if(s.set({...r,isPending:r.data===null,isRefetching:!0,error:null,refetch:o}),t.aborted)return`aborted`;try{let r=await e(`/get-session`,{method:`GET`,query:n?.query,signal:t});if(t.aborted)return`aborted`;let{data:i,error:a}=ml(r),c=`fresh`;if(i?.needsRefresh)try{let n=await e(`/get-session`,{method:`POST`,signal:t});if(t.aborted)return`aborted`;({data:i,error:a}=ml(n))}catch{if(t.aborted)return`aborted`;c=`stale`}if(a){let e=s.value,t=a?.status===401;return s.set({data:t?null:e.data,error:a,isPending:!1,isRefetching:!1,refetch:o}),`failed`}let l=Ote(i),u=s.value,d=u.data!=null&&l!=null&&Xc(u.data,l)?u.data:l;return s.set({data:d,error:null,isPending:!1,isRefetching:!1,refetch:o}),c}catch(e){if(t.aborted)return`aborted`;let n=s.value;return s.set({data:n.data,error:e,isPending:!1,isRefetching:!1,refetch:o}),`failed`}},l=()=>{let e=s.value.data?.session?.expiresAt,t=e instanceof Date?e.getTime():1/0;return Math.min(Date.now()+Ete,t)},u=e=>{i=0,r?.cancel();let t=new AbortController,n={cancel:()=>t.abort(),promise:Promise.resolve().then(()=>t.signal.aborted?`aborted`:c(t.signal,e)),revision:a};r=n;let o=e=>{r===n&&(r=void 0,e===`fresh`&&n.revision===a&&(i=l()))};return n.promise.then(o,()=>o(`failed`)),n.promise.then(()=>void 0)},d=()=>r?.revision===a?r.promise.then(()=>void 0):Date.now()<i?Promise.resolve():u(),f=()=>{};return Jc(s,()=>{let e;Tte()||(e=setTimeout(()=>{d()},0));let r=pte({fetchSession:u,shouldPollSession:()=>s.value.data!=null,sessionSignal:n,options:t});return r.init(),f=r.broadcastSessionUpdate,()=>{e&&clearTimeout(e),r.cleanup()}}),{session:s,$sessionSignal:n,broadcastSessionUpdate:e=>f(e)}}function hl(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t!==null&&t!==Object.prototype&&Object.getPrototypeOf(t)!==null||Symbol.iterator in e?!1:Symbol.toStringTag in e?Object.prototype.toString.call(e)===`[object Module]`:!0}function gl(e,t,n=`.`,r){if(!hl(t))return gl(e,{},n,r);let i={...t};for(let t of Object.keys(e)){if(t===`__proto__`||t===`constructor`)continue;let a=e[t];a!=null&&(r&&r(i,t,a,n)||(i[t]=Array.isArray(a)&&Array.isArray(i[t])?[...a,...i[t]]:hl(a)&&hl(i[t])?gl(a,i[t],(n?`${n}.`:``)+t.toString(),r):a))}return i}function jte(e){return(...t)=>t.reduce((t,n)=>gl(t,n,``,e),{})}var Mte=jte(),Nte=class extends Error{constructor(e,t,n){super(t||e.toString(),{cause:n}),this.status=e,this.statusText=t,this.error=n,Error.captureStackTrace(this,this.constructor)}},Pte=async(e,t)=>{let n=t||{},r={onRequest:[t?.onRequest],onResponse:[t?.onResponse],onSuccess:[t?.onSuccess],onError:[t?.onError],onRetry:[t?.onRetry]};if(!t||!t?.plugins)return{url:e,options:n,hooks:r};for(let i of t?.plugins||[]){if(i.init){let t=await i.init?.call(i,e.toString(),n);n=t.options||n,e=t.url}r.onRequest.push(i.hooks?.onRequest),r.onResponse.push(i.hooks?.onResponse),r.onSuccess.push(i.hooks?.onSuccess),r.onError.push(i.hooks?.onError),r.onRetry.push(i.hooks?.onRetry)}return{url:e,options:n,hooks:r}},_l=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(){return this.options.delay}},Fte=class{constructor(e){this.options=e}shouldAttemptRetry(e,t){return this.options.shouldRetry?Promise.resolve(e<this.options.attempts&&this.options.shouldRetry(t)):Promise.resolve(e<this.options.attempts)}getDelay(e){return Math.min(this.options.maxDelay,this.options.baseDelay*2**e)}};function Ite(e){if(typeof e==`number`)return new _l({type:`linear`,attempts:e,delay:1e3});switch(e.type){case`linear`:return new _l(e);case`exponential`:return new Fte(e);default:throw Error(`Invalid retry strategy`)}}var Lte=[`get`,`post`,`put`,`patch`,`delete`];function vl(e){if(!e.startsWith(`@`))return{method:void 0,path:e};let t=e.indexOf(`/`),n=e.slice(1,t===-1?void 0:t);return Lte.includes(n)?{method:n,path:t===-1?e:e.slice(t+1)}:{method:void 0,path:e}}var Rte=e=>e===`.`||e===`..`,zte=e=>e.split(`:`).map(e=>encodeURIComponent(e)).join(`:`);function Bte(e,t){let n=t.get(e);if(n===void 0)return zte(e);if(Rte(n))throw TypeError(`Path parameters cannot be reserved path segments`);return encodeURIComponent(n)}function Vte(e,t){let{baseURL:n,params:r,query:i}=t||{query:{},params:{},baseURL:``},a=e.startsWith(`http`)?e.split(`/`).slice(0,3).join(`/`):n||``,{path:o}=vl(e);o!==e&&(e=`/${o}`),a.endsWith(`/`)||(a+=`/`);let[s,c]=e.replace(a,``).split(`?`),l=new URLSearchParams(c);for(let[e,t]of Object.entries(i||{})){if(t==null)continue;let n;if(typeof t==`string`)n=t;else if(Array.isArray(t)){for(let n of t)l.append(e,n);continue}else n=JSON.stringify(t);l.set(e,n)}let u=new Map;if(r){if(Array.isArray(r)){let e=s.split(`/`).filter(e=>e.startsWith(`:`));for(let[t,n]of e.entries()){let e=r[t];u.set(n,String(e))}}else for(let[e,t]of Object.entries(r))u.set(`:${e}`,String(t))}s=s.split(`/`).map(e=>Bte(e,u)).join(`/`),s=s.replace(/^\/+/,``);let d=l.toString();return d=d.length>0?`?${d}`.replace(/\+/g,`%20`):``,a.startsWith(`http`)?new URL(`${s}${d}`,a):`${a}${s}${d}`}var Hte=async e=>{let t={},n=async e=>typeof e==`function`?await e():e;if(e?.auth){if(e.auth.type===`Bearer`){let r=await n(e.auth.token);if(!r)return t;t.authorization=`Bearer ${r}`}else if(e.auth.type===`Basic`){let[r,i]=await Promise.all([n(e.auth.username),n(e.auth.password)]);if(!r||!i)return t;t.authorization=`Basic ${btoa(`${r}:${i}`)}`}else if(e.auth.type===`Custom`){let[r,i]=await Promise.all([n(e.auth.prefix),n(e.auth.value)]);if(!i)return t;t.authorization=`${r??``} ${i}`}}return t},Ute=/^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;function Wte(e){let t=e.headers.get(`content-type`),n=new Set([`image/svg`,`application/xml`,`application/xhtml`,`application/html`]);if(!t)return`json`;let r=t.split(`;`).shift()||``;return Ute.test(r)?`json`:n.has(r)||r.startsWith(`text/`)?`text`:`blob`}function Gte(e){try{return JSON.parse(e),!0}catch{return!1}}function yl(e){if(e===void 0)return!1;let t=typeof e;return t===`string`||t===`number`||t===`boolean`||t===null?!0:t===`object`?Array.isArray(e)?!0:e.buffer?!1:e.constructor&&e.constructor.name===`Object`||typeof e.toJSON==`function`:!1}function bl(e){try{return JSON.parse(e)}catch{return e}}function xl(e){return typeof e==`function`}function Kte(e){if(e?.customFetchImpl)return e.customFetchImpl;if(typeof globalThis<`u`&&xl(globalThis.fetch))return globalThis.fetch;if(typeof window<`u`&&xl(window.fetch))return window.fetch;throw Error(`No fetch implementation found`)}function Sl(...e){let t={};for(let n of e)if(n){if(n instanceof Headers)n.forEach((e,n)=>{t[n]=e});else{let e=Array.isArray(n)?n:Object.entries(n);for(let[n,r]of e)r!=null&&(t[n]=r)}}return t}async function qte(e){let t=new Headers(Sl(e?.headers,await Hte(e)));if(!t.has(`content-type`)){let n=Jte(e?.body);n&&t.set(`content-type`,n)}return t}function Jte(e){return yl(e)?`application/json`:null}function Yte(e){let t=e.get(`content-type`);return t?t.split(`;`)[0].trim().toLowerCase():null}function Xte(e,t){let{body:n}=e;return n?!yl(n)||typeof n==`string`?n:Yte(t)===`application/x-www-form-urlencoded`?new URLSearchParams(n).toString():JSON.stringify(n):null}function Zte(e,t){if(t?.method)return t.method.toUpperCase();let{method:n}=vl(e);return n?n.toUpperCase():t?.body?`POST`:`GET`}function Qte(e,t){let n;return!e?.signal&&e?.timeout&&(n=setTimeout(()=>t?.abort(),e?.timeout)),{abortTimeout:n,clearTimeout:()=>{n&&clearTimeout(n)}}}var $te=class e extends Error{constructor(t,n){super(n||JSON.stringify(t,null,2)),this.issues=t,Object.setPrototypeOf(this,e.prototype)}};async function Cl(e,t){let n=await e[`~standard`].validate(t);if(n.issues)throw new $te(n.issues);return n.value}function wl(e){"@babel/helpers - typeof";return wl=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},wl(e)}function ene(e,t){if(wl(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(wl(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function tne(e){var t=ene(e,`string`);return wl(t)==`symbol`?t:t+``}function nne(e,t,n){return(t=tne(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Tl(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function El(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Tl(Object(n),!0).forEach(function(t){nne(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Tl(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var Dl=async(e,t)=>{var n;let{hooks:r,url:i,options:a}=await Pte(e,t),o=Kte(a),s=new AbortController,c=a.signal??s.signal,l=Vte(i,a),u=await qte(a),d=Xte(a,u),f=Zte(i,a),p=El(El({},a),{},{url:l,headers:u,body:d,method:f,signal:c});for(let e of r.onRequest)if(e){let t=await e(p);typeof t==`object`&&t&&Object.assign(p,t)}(`pipeTo`in p&&typeof p.pipeTo==`function`||typeof(t==null||(n=t.body)==null?void 0:n.pipe)==`function`)&&(`duplex`in p||(p.duplex=`half`));let{clearTimeout:m}=Qte(a,s),h=await o(p.url,p);m();let g={response:h,request:p};for(let e of r.onResponse)if(e){var _;let n=await e(El(El({},g),{},{response:t!=null&&(_=t.hookOptions)!=null&&_.cloneResponse?h.clone():h}));n instanceof Response?h=n:typeof n==`object`&&n&&(h=n.response)}if(h.ok){if(p.method===`HEAD`)return{data:``,error:null};let e=Wte(h),n={data:null,response:h,request:p};if(e===`json`||e===`text`){let e=await h.text();n.data=await(p.jsonParser??bl)(e)}else n.data=await h[e]();p?.output&&p.output&&!p.disableValidation&&(n.data=await Cl(p.output,n.data));for(let e of r.onSuccess)if(e){var v;await e(El(El({},n),{},{response:t!=null&&(v=t.hookOptions)!=null&&v.cloneResponse?h.clone():h}))}return t?.throw?n.data:{data:n.data,error:null}}let y=t?.jsonParser??bl,b=await h.text(),x=Gte(b),S=x?await y(b):null,C={response:h,responseText:b,request:p,error:El(El({},S),{},{status:h.status,statusText:h.statusText})};for(let e of r.onError)if(e){var w;await e(El(El({},C),{},{response:t!=null&&(w=t.hookOptions)!=null&&w.cloneResponse?h.clone():h}))}if(t?.retry){let n=Ite(t.retry),i=t.retryAttempt??0;if(await n.shouldAttemptRetry(i,h)){for(let e of r.onRetry)e&&await e(g);let a=n.getDelay(i);return await new Promise(e=>setTimeout(e,a)),await Dl(e,El(El({},t),{},{retryAttempt:i+1}))}}if(t?.throw)throw new Nte(h.status,h.statusText,x?S:b);return{data:null,error:El(El({},S),{},{status:h.status,statusText:h.statusText})}},rne=e=>({id:`apply-schema`,name:`Apply Schema`,version:`1.0.0`,async init(t,n){var r;let i=El(El({},n),e.query!==void 0&&{query:El(El({},e.query),n?.query)}),a=((r=e.plugins)==null||(r=r.find(e=>e.schema?.config?t.startsWith(e.schema.config.baseURL||``)||t.startsWith(e.schema.config.prefix||``):!1))==null?void 0:r.schema)||e.schema;if(a){let r=t;a.config?.prefix&&r.startsWith(a.config.prefix)&&(r=r.replace(a.config.prefix,``),a.config.baseURL&&(t=t.replace(a.config.prefix,a.config.baseURL))),a.config?.baseURL&&r.startsWith(a.config.baseURL)&&(r=r.replace(a.config.baseURL,``)),r.startsWith(`/`)&&r.charAt(1)===`@`&&(r=r.substring(1));let o=a.schema[r];if(o){let{method:a,path:s}=vl(r);a&&(t=t.slice(0,t.length-r.length)+s);let c=n?.headers;if(o.headers&&!n?.disableValidation){let e={};if(n?.headers){if(n.headers instanceof Headers)n.headers.forEach((t,n)=>{e[n.toLowerCase()]=t});else if(typeof n.headers==`object`)for(let[t,r]of Object.entries(n.headers))r!=null&&(e[t.toLowerCase()]=r)}let t=await Cl(o.headers,e),r={};for(let[e,n]of Object.entries(t))r[e.toLowerCase()]=n;c=r}let l=o.method??a;if(i=El(El(El(El({},i),l!==void 0&&{method:l}),o.output!==void 0&&{output:o.output}),c!==void 0&&{headers:c}),!n?.disableValidation){if(o.query&&(i.query=await Cl(o.query,n?.query),i.query!==null&&typeof i.query==`object`)){let t=El({},e.query);for(let e of Object.keys(t))n?.query&&Object.prototype.hasOwnProperty.call(n.query,e)&&(t[e]=n.query[e]);i.query=El(El({},t),i.query)}i=El(El({},i),{},{body:o.input?await Cl(o.input,n?.body):n?.body,params:o.params?await Cl(o.params,n?.params):n?.params})}return{url:t,options:i}}}return El({url:t},(n!==void 0||e.query!==void 0)&&{options:i})}}),ine=e=>{async function t(t,n){let r=El(El(El({},e),n),{},{headers:Sl(e?.headers,n?.headers),plugins:[...e?.plugins||[],rne(e||{}),...n?.plugins||[]]});if(e?.catchAllError)try{return await Dl(t,r)}catch(e){return{data:null,error:{status:500,statusText:`Fetch Error`,message:`Fetch related error. Captured by catchAllError option. See error property for more details.`,error:e}}}return await Dl(t,r)}return t},ane=e=>{if(typeof process>`u`)return;let t=e??`/api/auth`;if({}.NEXT_PUBLIC_AUTH_URL)return{}.NEXT_PUBLIC_AUTH_URL;if(typeof window>`u`){if({}.NEXTAUTH_URL)try{return{}.NEXTAUTH_URL}catch{}if({}.VERCEL_URL)try{let e={}.VERCEL_URL.startsWith(`http`)?``:`https://`;return`${new URL(`${e}${{}.VERCEL_URL}`).origin}${t}`}catch{}}},one=e=>e===`/sign-out`||e===`/update-user`||e===`/update-session`||e===`/sign-up/email`||e===`/sign-in/email`||e===`/delete-user`||e===`/verify-email`||e===`/revoke-sessions`||e===`/revoke-session`||e===`/revoke-other-sessions`||e===`/change-email`||e===`/change-password`,sne=(e,t)=>{let n=`credentials`in Request.prototype,r=xte(e?.baseURL,e?.basePath,void 0,t)??ane(e?.basePath)??`/api/auth`,i=e?.plugins?.flatMap(e=>e.fetchPlugins).filter(e=>e!==void 0)||[],a={id:`lifecycle-hooks`,name:`lifecycle-hooks`,hooks:{onSuccess:e?.fetchOptions?.onSuccess,onError:e?.fetchOptions?.onError,onRequest:e?.fetchOptions?.onRequest,onResponse:e?.fetchOptions?.onResponse}},{onSuccess:o,onError:s,onRequest:c,onResponse:l,...u}=e?.fetchOptions||{},d=ine({baseURL:r,...n?{credentials:`include`}:{},method:`GET`,jsonParser(e){return e?ste(e,{strict:!1}):null},customFetchImpl:fetch,...u,plugins:[a,...u.plugins||[],...e?.disableDefaultFetchPlugins?[]:[wte],...i]}),{$sessionSignal:f,session:p,broadcastSessionUpdate:m}=Ate(d,e),h=!1,g=e=>{h||e===null||(h=!0,Dte(p,e))},_=e?.plugins||[],v={},y={$sessionSignal:f,session:p},b={"/sign-out":`POST`,"/revoke-sessions":`POST`,"/revoke-other-sessions":`POST`,"/delete-user":`POST`},x=[{signal:`$sessionSignal`,matcher:one,callback(e){e===`/sign-out`?m(`signout`):(e===`/update-user`||e===`/update-session`)&&m(`updateUser`)}}];for(let e of _)e.getAtoms&&Object.assign(y,e.getAtoms?.(d)),e.pathMethods&&Object.assign(b,e.pathMethods),e.atomListeners&&x.push(...e.atomListeners);let S={notify:e=>{y[e].set(!y[e].get())},listen:(e,t)=>{y[e].subscribe(t)},atoms:y};for(let t of _)t.getActions&&(v=Mte(t.getActions?.(d,S,e)??{},v));return{get baseURL(){return r},pluginsActions:v,pluginsAtoms:y,pluginPathMethods:b,atomListeners:x,hydrateSession:g,$sessionSignal:f,$fetch:d,$store:S}};function cne(e){return typeof e==`object`&&!!e&&`get`in e&&typeof e.get==`function`&&`lc`in e&&typeof e.lc==`number`}function lne(e){return e.charAt(0).toUpperCase()+e.slice(1)}var une=/[\p{Ll}\d]+|\p{Lu}+(?!\p{Ll})|\p{Lu}[\p{Ll}\d]+|\p{Lo}+/gu,dne=/['\u2019]/g;function fne(e){return e.replace(dne,``).match(une)??[]}function pne(e){return fne(e).map(e=>e.toLowerCase()).join(`-`)}function mne(e,t,n){let r=t[e],{fetchOptions:i,query:a,...o}=n||{};return r||(i?.method?i.method:o&&Object.keys(o).length>0?`POST`:`GET`)}function hne(e,t,n,r,i){function a(o=[]){return new Proxy(function(){},{get(t,n){if(typeof n!=`string`||n===`then`||n===`catch`||n===`finally`)return;let r=[...o,n],i=e;for(let e of r)if(i&&typeof i==`object`&&e in i)i=i[e];else{i=void 0;break}return typeof i==`function`||cne(i)?i:a(r)},apply:async(e,a,s)=>{let c=`/`+o.map(pne).join(`/`),l=s[0]||{},u=s[1]||{},{query:d,fetchOptions:f,...p}=l,m={...u,...f},h=mne(c,n,l);return await t(c,{...m,body:h===`GET`?void 0:{...p,...m?.body||{}},query:d||m?.query,method:h,async onSuccess(e){if(await m?.onSuccess?.(e),!i||m.disableSignal)return;let t=i.filter(e=>e.matcher(c));if(!t.length)return;let n=new Set;for(let e of t){let t=r[e.signal];if(!t)return;if(n.has(e.signal))continue;n.add(e.signal);let i=t.get();setTimeout(()=>{t.set(!i)},10),e.callback?.(c)}}})}})}return a()}function gne(e){let{pluginPathMethods:t,pluginsActions:n,pluginsAtoms:r,hydrateSession:i,$fetch:a,atomListeners:o,$store:s}=sne(e),c={};for(let[e,t]of Object.entries(r))c[`use${lne(e)}`]=t;return hne({...n,...c,hydrateSession:i,$fetch:a,$store:s},a,t,r,o)}var _ne=(e,{$listPasskeys:t,$store:n})=>({signIn:{passkey:async(r,i)=>{let a=await e(`/passkey/generate-authenticate-options`,{method:`GET`,throw:!1});if(!a.data)return a;let o=a.data.extensions||r?.extensions?{...a.data.extensions||{},...r?.extensions||{}}:void 0,s;try{s=await Pc({optionsJSON:{...a.data,extensions:o},useBrowserAutofill:r?.autoFill})}catch(e){return{data:null,error:{code:e instanceof wc?e.code:`AUTH_CANCELLED`,message:gc.AUTH_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}}try{let{clientExtensionResults:a,...o}=s,c=await e(`/passkey/verify-authentication`,{body:{response:o},...r?.fetchOptions,...i,method:`POST`,throw:!1});return t.set(Math.random()),n.notify(`$sessionSignal`),r?.returnWebAuthnResponse?{...c,webauthn:{response:s,clientExtensionResults:a}}:c}catch(e){return console.error(`[Better Auth] Error verifying passkey`,e),{data:null,error:{code:`AUTH_CANCELLED`,message:gc.AUTH_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}}}},passkey:{addPasskey:async(r,i)=>{let a=await e(`/passkey/generate-register-options`,{method:`GET`,query:{...r?.authenticatorAttachment&&{authenticatorAttachment:r.authenticatorAttachment},...r?.name&&{name:r.name},...r?.context&&{context:r.context}},throw:!1});if(!a.data)return a;try{let o=a.data.extensions||r?.extensions?{...a.data.extensions||{},...r?.extensions||{}}:void 0,s=await kc({optionsJSON:{...a.data,extensions:o},useAutoRegister:r?.useAutoRegister}),{clientExtensionResults:c,...l}=s,u=await e(`/passkey/verify-registration`,{...r?.fetchOptions,...i,body:{response:l,name:r?.name,...r?.createSession&&{createSession:!0}},method:`POST`,throw:!1});return u.data?(t.set(Math.random()),u.data.session&&n.notify(`$sessionSignal`),r?.returnWebAuthnResponse?{...u,webauthn:{response:s,clientExtensionResults:c}}:u):u}catch(e){return e instanceof wc?e.code===`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`?{data:null,error:{code:e.code,message:gc.PREVIOUSLY_REGISTERED.message,status:400,statusText:`BAD_REQUEST`}}:e.code===`ERROR_CEREMONY_ABORTED`?{data:null,error:{code:e.code,message:gc.REGISTRATION_CANCELLED.message,status:400,statusText:`BAD_REQUEST`}}:{data:null,error:{code:e.code,message:e.message,status:400,statusText:`BAD_REQUEST`}}:{data:null,error:{code:`UNKNOWN_ERROR`,message:e instanceof Error?e.message:gc.UNKNOWN_ERROR.message,status:500,statusText:`INTERNAL_SERVER_ERROR`}}}}},$Infer:{}}),vne=()=>{let e=Uc();return{id:`passkey`,version:_c,$InferServerPlugin:{},getActions:(t,n)=>_ne(t,{$listPasskeys:e,$store:n}),getAtoms(t){return{listPasskeys:dte(e,`/passkey/list-user-passkeys`,t,{method:`GET`}),$listPasskeys:e}},pathMethods:{"/passkey/register":`POST`,"/passkey/authenticate":`POST`},atomListeners:[{matcher(e){return e===`/passkey/verify-registration`||e===`/passkey/delete-passkey`||e===`/passkey/update-passkey`||e===`/sign-out`},signal:`$listPasskeys`},{matcher:e=>e===`/passkey/verify-authentication`,signal:`$sessionSignal`}],$ERROR_CODES:gc}},yne=hc({OTP_EXPIRED:`OTP expired`,INVALID_OTP:`Invalid OTP`,TOO_MANY_ATTEMPTS:`Too many attempts`}),bne=()=>({id:`email-otp`,version:Fc,$InferServerPlugin:{},atomListeners:[{matcher:e=>e===`/email-otp/verify-email`||e===`/sign-in/email-otp`||e===`/email-otp/request-email-change`,signal:`$sessionSignal`}],$ERROR_CODES:yne}),xne=e=>{let t=e?.jwks?.jwksPath??`/jwks`;return{id:`better-auth-client`,version:Fc,$InferServerPlugin:{},pathMethods:{[t]:`GET`},getActions:(e,n,r)=>({jwks:async n=>await e(t,{method:`GET`,...n})})}},Sne=hc({OTP_NOT_ENABLED:`OTP not enabled`,OTP_NOT_CONFIGURED:`OTP is not available`,OTP_HAS_EXPIRED:`OTP has expired`,TOTP_NOT_ENABLED:`TOTP not enabled`,TOTP_ALREADY_ENABLED:`TOTP is already enabled`,TOTP_NOT_CONFIGURED:`TOTP is not available`,TWO_FACTOR_NOT_ENABLED:`Two factor isn't enabled`,BACKUP_CODES_NOT_ENABLED:`Backup codes aren't enabled`,INVALID_BACKUP_CODE:`Invalid backup code`,INVALID_CODE:`Invalid code`,TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:`Too many attempts. Please request a new code.`,ACCOUNT_TEMPORARILY_LOCKED:`Too many failed verification attempts. Your account is temporarily locked. Please try again later.`,INVALID_TWO_FACTOR_COOKIE:`Invalid two factor cookie`}),Cne=e=>({id:`two-factor`,version:Fc,$InferServerPlugin:{},atomListeners:[{matcher:e=>e.startsWith(`/two-factor/`),signal:`$sessionSignal`}],pathMethods:{"/two-factor/disable":`POST`,"/two-factor/enable":`POST`,"/two-factor/send-otp":`POST`,"/two-factor/generate-backup-codes":`POST`,"/two-factor/get-totp-uri":`POST`,"/two-factor/verify-totp":`POST`,"/two-factor/verify-otp":`POST`,"/two-factor/verify-backup-code":`POST`},fetchPlugins:[{id:`two-factor`,name:`two-factor`,hooks:{async onSuccess(t){if(t.data?.twoFactorRedirect){if(e?.onTwoFactorRedirect){await e.onTwoFactorRedirect({twoFactorMethods:t.data.twoFactorMethods});return}e?.twoFactorPage&&typeof window<`u`&&pl(e.twoFactorPage)&&(window.location.href=e.twoFactorPage)}}}}],$ERROR_CODES:Sne}),wne=(e,t,n)=>gne({baseURL:e,basePath:t,plugins:[xne(),bne(),Cne(),vne()],fetchOptions:{customFetchImpl:n}}),Ol=e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?JSON.parse(e):[],kl=e=>{let t=e.split(`,`);return t.includes(`owner`)?`owner`:t.includes(`admin`)?`admin`:`member`},Tne=e=>({id:e.id,userId:e.userId,name:e.user.name||e.user.email,email:e.user.email,role:kl(e.role),appRoles:Ol(e.appRoles),createdAt:new Date(e.createdAt).toISOString()}),Al=e=>({id:e.id,email:e.email,role:kl(e.role),appRoles:Ol(e.appRoles),status:e.status,expiresAt:new Date(e.expiresAt).toISOString(),...e.organizationName&&{organizationName:e.organizationName}}),Ene=(e,t)=>{let n=async(t,n,r={})=>{let{data:i,error:a}=await e.$fetch(t,{method:r.method??(r.body?`POST`:`GET`),...r.body&&{body:r.body},...r.query&&{query:r.query}});if(a)throw z(a,n);return i},r=async e=>(await t(),e);return{list:async()=>await n(`/organization/list`,`Could not read your organizations`)??[],current:()=>n(`/organization/current`,`Could not read the current organization`),switchTo:async e=>r(await n(`/organization/switch`,`Could not switch the organization`,{body:{organizationId:e}})),search:async e=>(await n(`/organization/search`,`Could not search the organizations`,{query:{query:e}})).organizations,create:async e=>r(await n(`/organization/create`,`Could not create the organization`,{body:e})),rename:(e,t)=>n(`/organization/update`,`Could not change the organization`,{body:{organizationId:e,data:t}}),remove:async e=>r(await n(`/organization/delete`,`Could not delete the organization`,{body:{organizationId:e}})),leave:async e=>r(await n(`/organization/leave`,`Could not leave the organization`,{body:{organizationId:e}})),members:async e=>(await n(`/organization/list-members`,`Could not read the members`,{query:{organizationId:e,limit:`1000`}})).members.map(Tne),setRole:(e,t,r)=>n(`/organization/update-member-role`,`Could not change the role`,{body:{organizationId:e,memberId:t,role:r}}),setAppRoles:(e,t)=>n(`/organization/set-app-roles`,`Could not change the app roles`,{body:{memberId:e,appRoles:t}}),removeMember:(e,t)=>n(`/organization/remove-member`,`Could not remove the member`,{body:{organizationId:e,memberIdOrEmail:t}}),transferOwnership:(e,t=`admin`)=>n(`/organization/transfer-ownership`,`Could not hand the organization over`,{body:{memberId:e,keepAs:t}}),invitations:async e=>(await n(`/organization/list-invitations`,`Could not read the invitations`,{query:{organizationId:e}})??[]).map(Al),invite:async(e,t)=>{let r=await n(`/organization/invite-member`,`Could not send the invitation`,{body:{organizationId:e,...t}});return{invitation:Al(r),...r.link&&{link:r.link}}},resend:async(e,t)=>{let r=await n(`/organization/invite-member`,`Could not send the invitation again`,{body:{organizationId:e,email:t.email,role:t.role,resend:!0}});return{invitation:Al(r),...r.link&&{link:r.link}}},revoke:e=>n(`/organization/cancel-invitation`,`Could not revoke the invitation`,{body:{invitationId:e}}),myInvitations:async()=>(await n(`/organization/list-user-invitations`,`Could not read your invitations`)??[]).map(Al),invitation:e=>n(`/invitation`,`This invitation link is not valid`,{query:{token:e}}),accept:async e=>r(await n(`/invitation/accept`,`Could not accept the invitation`,{body:{token:e}})),signUpFromInvitation:async(e,t)=>r(await n(`/invitation/sign-up`,`Could not create your account`,{body:{token:e,...t}}))}},Dne=(e,t)=>({current:async()=>{let{data:t,error:n}=await e.$fetch(`/role/current`,{method:`GET`});if(n)throw z(n,`Could not read your roles`);return t},switchTo:async n=>{let{error:r}=await e.$fetch(`/role/switch`,{method:`POST`,body:{role:n}});if(r)throw z(r,`Could not switch the role`);await t()}}),One=(e,t)=>{let n=async e=>e?.twoFactorRedirect?{kind:`two-factor`,methods:e.twoFactorMethods??[]}:(await t(),{kind:`signed-in`,user:e?.user});return{signIn:async(t,r)=>{let{data:i,error:a}=await e.signIn.email({email:t,password:r});if(a||!i)throw z(a,`Sign-in failed`);return n(i)},sendSignInCode:async t=>{let{error:n}=await e.emailOtp.sendVerificationOtp({email:t,type:`sign-in`});if(n)throw z(n,`Could not send the code`)},signInWithCode:async(t,r)=>{let{data:i,error:a}=await e.signIn.emailOtp({email:t,otp:r});if(a||!i)throw z(a,`Sign-in failed`);return n(i)},sendSignUpCode:async t=>{let{error:n}=await e.$fetch(`/sign-up/send-code`,{method:`POST`,body:{email:t}});if(n)throw z(n,`Could not send the code`)},verifySignUpCode:async(t,n)=>{let{data:r,error:i}=await e.$fetch(`/sign-up/verify-code`,{method:`POST`,body:{email:t,code:n}});if(i||!r)throw z(i,`Could not check the code`);return r.ticket},signUp:async n=>{let{data:r,error:i}=await e.$fetch(`/sign-up/create`,{method:`POST`,body:n});if(i||!r)throw z(i,`Could not create your account`);return await t(),r.user},signInWithPasskey:async n=>{let r=await e.$fetch(`/passkey/generate-authenticate-options`,{method:`GET`,...n&&{query:{rpId:n}}});if(r.error||!r.data)throw z(r.error,`Sign-in failed`);let{clientExtensionResults:i,...a}=await Pc({optionsJSON:r.data}).catch(e=>{throw new pc(`Auth cancelled`,400,e instanceof wc?e.code:`AUTH_CANCELLED`)}),o=await e.$fetch(`/passkey/verify-authentication`,{method:`POST`,body:{response:a}});if(o.error||!o.data)throw z(o.error,`Sign-in failed`);return await t(),o.data.user},sendTwoFactorCode:async()=>{let{error:t}=await e.twoFactor.sendOtp();if(t)throw z(t,`Could not send the code`)},verifyTwoFactor:async({method:n,code:r,trustDevice:i=!1})=>{let{data:a,error:o}=await(n===`totp`?e.twoFactor.verifyTotp:n===`otp`?e.twoFactor.verifyOtp:e.twoFactor.verifyBackupCode)({code:r,trustDevice:i});if(o||!a)throw z(o,`The code did not work`);return await t(),a.user}}},jl=e=>({read:async()=>{let{data:t,error:n}=await e.$fetch(`/policy/sign-in`);if(n||!t)throw z(n,`Could not read the sign-in policy`);return t},save:async t=>{let{data:n,error:r}=await e.$fetch(`/policy/sign-in`,{method:`POST`,body:t});if(r||!n)throw z(r,`Could not save the sign-in policy`);return n}}),Ml=e=>new Date(e).toISOString(),Nl=({startedAt:e,expiresAt:t,endedAt:n,...r})=>({...r,startedAt:Ml(e),expiresAt:Ml(t),...n&&{endedAt:Ml(n)}}),Pl=e=>({start:async t=>{let{data:n,error:r}=await e.$fetch(`/staff/sign-in`,{method:`POST`,body:t});if(r||!n?.url)throw z(r,`Could not start the staff sign-in`);return n.url},current:async()=>{let{data:t,error:n}=await e.$fetch(`/staff/session`);if(n||!t)throw z(n,`Could not read the session`);return t.staff?Nl(t.staff):void 0},stop:async()=>{let{error:t}=await e.$fetch(`/staff/stop`,{method:`POST`,body:{}});if(t)throw z(t,`Could not end the staff session`)},log:async()=>{let{data:t,error:n}=await e.$fetch(`/staff/sign-ins`);if(n||!t)throw z(n,`Could not read the staff sign-ins`);return t.signIns.map(Nl)}}),Fl=e=>{let t=e.split(`.`)[1];if(!t)throw Error(`Not a JWT`);let n=JSON.parse(atob(t.replace(/-/g,`+`).replace(/_/g,`/`)));if(typeof n.exp!=`number`)throw Error(`The token has no expiry`);return n.exp*1e3},Il=(e={})=>{let t=e.origin??globalThis.location?.origin??`http://localhost`,n=e.basePath??`/api/auth`,r=e.refreshMarginMs??6e4,i=e.fetch??((e,t)=>fetch(e,t)),a=wne(t,n,i),o=Pl(a),s,c,l,u=()=>{s=void 0,clearTimeout(l)},d=async()=>{let{data:t}=await a.$fetch(`/token`);if(!t?.token){u();return}return s={token:t.token,expiresAt:Fl(t.token)},clearTimeout(l),l=setTimeout(()=>void f({refresh:!0}).then(t=>t||e.onSignedOut?.()),Math.max(1e3,s.expiresAt-Date.now()-r)),s.token},f=async({refresh:e=!1}={})=>!e&&s&&s.expiresAt-Date.now()>r?s.token:(c??=d().finally(()=>{c=void 0}),c);return{token:f,status:async()=>{let e=await i(`${t}${n}/status`);if(e.status===404)throw new pc(`This server has no sign-in. Is the API URL right?`,404);if(!e.ok)throw new pc(`Could not read the sign-in status`,e.status);let r=await e.json();return{needsAdmin:!!r.needsAdmin,signInMethods:r.signInMethods??[`password`],passwordReset:!!r.passwordReset,...r.signUp&&{signUp:!0},socialProviders:r.socialProviders??[],...r.platformSignIn&&{platformSignIn:r.platformSignIn},samlProviders:r.samlProviders??[],...r.staffSignIn&&{staffSignIn:r.staffSignIn},...r.passkeyDomains&&{passkeyDomains:r.passkeyDomains},...r.organizations&&{organizations:r.organizations},...r.anonymous&&{anonymous:!0},...r.plugins&&r.plugins.length>0&&{plugins:r.plugins}}},session:async()=>{let{data:e}=await a.getSession();return e?.user},...One(a,()=>f({refresh:!0})),signInSocial:async(e,t)=>{let{data:n,error:r}=await a.signIn.social({provider:e,callbackURL:t,errorCallbackURL:t,disableRedirect:!0});if(r||!n?.url)throw z(r,`Sign-in failed`);return n.url},signInSaml:async(e,t)=>{let{data:n,error:r}=await a.$fetch(`/sign-in/sso`,{method:`POST`,body:{providerId:e,callbackURL:t,errorCallbackURL:t}});if(r||!n?.url)throw z(r,`Sign-in failed`);return n.url},signOut:async()=>{u(),await a.signOut()},requestPasswordReset:async(e,t)=>{let{error:n}=await a.requestPasswordReset({email:e,redirectTo:t});if(n)throw z(n,`Could not send the reset link`)},resetPassword:async(e,t)=>{let{error:n}=await a.resetPassword({token:e,newPassword:t});if(n)throw z(n,`Could not set the password`)},account:mc(a),organizations:Ene(a,()=>f({refresh:!0})),roles:Dne(a,()=>f({refresh:!0})),signInPolicy:jl(a),staff:{...o,stop:async()=>{u(),await o.stop()}}}},Ll=e=>Math.min(3e4,1e3*2**e),Rl=(e,t)=>new Promise(n=>{let r=setTimeout(n,e);t.addEventListener(`abort`,()=>{clearTimeout(r),n()},{once:!0})}),zl=`http://same-origin.invalid`,Bl=(e,t)=>{let n=new URL(e,zl),r=new URL(t,`${n.href}/`);if(r.origin!==n.origin)throw Error(`${t} is not on the assistant backend's origin`);return n.origin===zl?`${r.pathname}${r.search}`:r.href},Vl=e=>{let t=e.url.replace(/\/+$/,``),n=e.fetch??((e,t)=>fetch(e,t)),r=e.retryDelayMs??Ll,i=async(r,i)=>{let a=await e.token(),o=await n(`${t}${r}`,{method:i.method,headers:{...i.body===void 0?{accept:`text/event-stream`}:{"content-type":`application/json`},...a&&{authorization:`Bearer ${a}`}},body:i.body===void 0?void 0:JSON.stringify(i.body),signal:i.signal});if(!o.ok)throw await Bs(o);return o},a=async(e,t,n)=>{let r=await i(`/events`,{method:`GET`,signal:e});if(!r.body)throw Error(`The assistant backend answered the event stream without a body`);n(),await ns(r.body,e=>t(JSON.parse(e)),e)};return{connect:(e,t)=>{let n=new AbortController,{signal:i}=n;return(async()=>{let n=0;for(;!i.aborted;){t?.({state:`connecting`});let o=await a(i,e,()=>{n=0,t?.({state:`open`})}).then(()=>void 0,e=>e??Error(`The assistant stream failed`));if(i.aborted)return;t?.({state:`retrying`,...o!==void 0&&{error:o}}),await Rl(r(n++),i)}})(),()=>n.abort()},send:async(e,t)=>{await i(`/messages`,{method:`POST`,body:{text:e,...t&&{page:t}}})},act:async(e,t)=>{await i(`/actions`,{method:`POST`,body:{partId:e,actionId:t}})},fetch:async(r,i={})=>{let a=Bl(t,r),o=await e.token(),s=new Headers(i.headers);o&&s.set(`authorization`,`Bearer ${o}`);let c=await n(a,{...i,headers:s});if(!c.ok)throw await Bs(c);return c}}},Hl=e=>typeof e==`object`&&!!e&&`error`in e&&typeof e.error==`object`&&e.error!==null&&`code`in e.error&&`message`in e.error,Ul=async e=>{let t=e.headers.get(`content-type`)?.includes(`json`)??!1?await e.clone().json():void 0;return Hl(t)?new Is({type:`urn:protobase:problem:${t.error.code}`,title:e.statusText||`Request failed`,status:e.status,detail:t.error.message}):Bs(e)},Wl=e=>{let t=e.url.replace(/\/+$/,``),n=e.fetch??((e,t)=>fetch(e,t)),r=async(r,i)=>{let a=await e.token(),o=await n(`${t}${r}`,{method:i,headers:{accept:`application/json`,...a&&{authorization:`Bearer ${a}`}}});if(!o.ok)throw await Ul(o);return await o.json()};return{status:()=>r(``,`GET`),update:()=>r(`/update`,`POST`)}},B=(...e)=>e.filter(Boolean).join(` `),Gl=e=>(0,o.useSyncExternalStore)(t=>{let n=window.matchMedia(e);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)},()=>window.matchMedia(e).matches,()=>!1),Kl=()=>Gl(`(min-width: 768px)`),ql=()=>Gl(`not all and (min-width: 640px)`),V=t(a(),1),Jl=e=>e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey,Yl=`flex min-h-[49px] min-w-0 flex-1 flex-col items-center justify-center gap-1 pb-1 pt-1.5 text-[10px] font-medium leading-none`,Xl=({tabs:e,onNavigate:t,onMore:n,moreOpen:r,moreControls:i,sticky:a,ref:o})=>{let s=!e.some(e=>e.active);return(0,V.jsxs)(`nav`,{ref:o,"aria-label":`Tabs`,className:B(`flex shrink-0 border-t bg-background pb-[env(safe-area-inset-bottom)] md:hidden`,a&&`sticky bottom-0 z-30`),children:[e.map(e=>{let n=e.icon;return(0,V.jsxs)(`a`,{href:e.href,"aria-current":e.active?`page`:void 0,...e.external?{target:`_blank`,rel:`noreferrer`}:{},onClick:n=>{!e.external&&t&&Jl(n)&&(n.preventDefault(),t(e.href))},className:B(Yl,e.active?`text-primary-text`:`text-muted-foreground`),children:[(0,V.jsx)(n,{className:`size-6`,strokeWidth:e.active?2.2:1.9,"aria-hidden":!0}),(0,V.jsx)(`span`,{className:`max-w-full truncate px-0.5`,children:e.label})]},e.id)}),(0,V.jsxs)(`button`,{type:`button`,"aria-expanded":r,"aria-controls":i,"data-current":s||void 0,onClick:n,className:B(Yl,s?`text-primary-text`:`text-muted-foreground`),children:[(0,V.jsx)(Xe,{className:`size-6`,strokeWidth:s?2.2:1.9,"aria-hidden":!0}),`More`]})]})},Zl=`data-pb-scroll-locked`,Ql=()=>{let{body:e,documentElement:t}=document,n=e.style.overflow,r=t.hasAttribute(Zl);return window.innerWidth>t.clientWidth&&t.setAttribute(Zl,``),e.style.overflow=`hidden`,()=>{e.style.overflow=n,r||t.removeAttribute(Zl)}},$l=`a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`,eu=[],tu=(e,t,n)=>{let r=(0,o.useRef)(n);r.current=n,(0,o.useEffect)(()=>{if(!t||!e.current)return;let n=e.current,i=document.activeElement instanceof HTMLElement?document.activeElement:null,a=Ql(),o={};eu.push(o);let s=()=>[...n.querySelectorAll($l)];(s()[0]??n).focus();let c=e=>{if(eu.at(-1)!==o)return;if(e.key===`Escape`)return r.current();if(e.key!==`Tab`)return;let t=s();if(t.length===0)return e.preventDefault();let i=t[0],a=t[t.length-1];e.shiftKey&&document.activeElement===i?(e.preventDefault(),a.focus()):!e.shiftKey&&document.activeElement===a?(e.preventDefault(),i.focus()):n.contains(document.activeElement)||(e.preventDefault(),i.focus())};return document.addEventListener(`keydown`,c),()=>{document.removeEventListener(`keydown`,c),eu.splice(eu.indexOf(o),1),a(),i?.focus()}},[t,e])},nu=({id:e,open:t,onClose:n,children:r})=>{let i=(0,o.useRef)(null);return tu(i,t,n),t?(0,V.jsxs)(`div`,{className:`fixed inset-0 z-50 md:hidden`,children:[(0,V.jsx)(`div`,{className:`absolute inset-0 bg-backdrop/40`,onClick:n,"aria-hidden":!0}),(0,V.jsx)(`div`,{ref:i,id:e,role:`dialog`,"aria-modal":`true`,"aria-label":`Navigation`,tabIndex:-1,className:`absolute inset-y-0 left-0 flex w-60 max-w-[85vw] bg-sidebar shadow-pop outline-none`,onClick:e=>e.target.closest(`a`)&&n(),children:r})]}):null},ru=(0,o.createContext)(()=>{}),iu=e=>{let t=(0,o.useContext)(ru);(0,o.useLayoutEffect)(()=>(t(e),()=>t(void 0)),[t,e])},au=e=>{(0,o.useLayoutEffect)(()=>{if(!e)return;let t=document.documentElement;return t.style.setProperty(`scrollbar-gutter`,`stable`),()=>{t.style.removeProperty(`scrollbar-gutter`)}},[e])},ou=[`--pb-sticky-top`,`--pb-sticky-bottom`,`scroll-padding-top`,`scroll-padding-bottom`],su=(e,t,n,r)=>{(0,o.useLayoutEffect)(()=>{if(!e)return;let r=document.documentElement,i=()=>{let e=`${t.current?.offsetHeight??0}px`,i=`${n.current?.offsetHeight??0}px`;r.style.setProperty(`--pb-sticky-top`,e),r.style.setProperty(`--pb-sticky-bottom`,i),r.style.setProperty(`scroll-padding-top`,e),r.style.setProperty(`scroll-padding-bottom`,i)},a=new ResizeObserver(i);for(let e of[t.current,n.current])e&&a.observe(e);return i(),()=>{a.disconnect();for(let e of ou)r.style.removeProperty(e)}},[e,t,n,r])},cu=({className:e})=>(0,V.jsx)(`span`,{className:B(`block h-3 rounded bg-muted [animation:pb-shimmer_1.4s_ease-in-out_infinite]`,e)}),lu=e=>e.button===0&&!e.metaKey&&!e.ctrlKey&&!e.shiftKey&&!e.altKey,uu=({parts:e,onNavigate:t})=>(0,V.jsx)(`nav`,{"aria-label":`Breadcrumb`,className:`flex min-w-0 items-center gap-1.5`,children:e.map((n,r)=>{let i=r===e.length-1,{label:a,href:o,loading:s}=typeof n==`string`?{label:n,href:void 0,loading:!1}:n,c=s?(0,V.jsx)(cu,{className:`w-24`}):a,l=B(`truncate`,i?`font-semibold`:`text-muted-foreground`);return(0,V.jsxs)(`span`,{className:B(`min-w-0 items-center gap-1.5`,i?`flex`:`hidden md:flex`),children:[r>0&&(0,V.jsx)(Se,{className:`hidden size-3.5 shrink-0 text-faint-foreground md:block`}),o?(0,V.jsx)(`a`,{href:o,"aria-current":i?`page`:void 0,"aria-label":s?a:void 0,"aria-busy":s||void 0,onClick:e=>{t&&lu(e)&&(e.preventDefault(),t(o))},className:B(l,`rounded-sm hover:text-foreground hover:underline`),children:c}):(0,V.jsx)(`span`,{className:l,"aria-label":s?a:void 0,"aria-busy":s||void 0,children:c})]},`${r}-${a}`)})}),du=({to:e,onClick:t,...n})=>(0,V.jsx)(`a`,{href:e.href,onClick:n=>{t?.(n),!n.defaultPrevented&&lu(n)&&(n.preventDefault(),e.onFollow())},...n}),fu=`M312.3 9.9Q257 9.9 217.1 -21.1Q177.3 -52.1 168.4 -108.8L181.1 -110.3V205H54.8V-510H176.7V-404.5L168.3 -407Q179.7 -460.8 221.2 -490.4Q262.7 -520 319.8 -520Q376.2 -520 417 -488.4Q457.8 -456.8 479.8 -398.6Q501.8 -340.5 501.8 -259.9Q501.8 -177.6 478.3 -116.8Q454.9 -55.9 412.5 -23Q370.1 9.9 312.3 9.9ZM274.4 -92.6Q320.2 -92.6 345.8 -133.8Q371.4 -175.1 371.4 -256.4Q371.4 -337.7 345.7 -377.6Q320.1 -417.5 274 -417.5Q228.6 -417.5 202.7 -376.4Q176.9 -335.3 176.9 -254Q176.9 -173.3 202.7 -132.9Q228.4 -92.6 274.4 -92.6Z M549.8 0V-510H671.7V-388.3H676.1V0H549.8ZM676.1 -286.5 661.3 -386.2Q677.9 -455.2 711.8 -487.6Q745.7 -520 794.3 -520Q809 -520 818 -516.6V-394.2Q814.2 -395.6 807.1 -396.1Q800 -396.6 789.4 -396.6Q734.6 -396.6 705.3 -370.5Q676.1 -344.4 676.1 -286.5Z M1043.8 10Q974.7 10 922.6 -23.6Q870.6 -57.2 842.1 -117.5Q813.6 -177.8 813.6 -257Q813.6 -336.5 842.2 -395.5Q870.8 -454.5 922.5 -487.2Q974.2 -520 1043.8 -520Q1113.7 -520 1165.4 -487.2Q1217.1 -454.5 1245.6 -395.5Q1274 -336.5 1274 -257Q1274 -177.8 1245.5 -117.5Q1217 -57.2 1165.3 -23.6Q1113.6 10 1043.8 10ZM1043.8 -90.5Q1073.5 -90.5 1095.9 -108.9Q1118.2 -127.3 1130.9 -164.4Q1143.6 -201.5 1143.6 -257.5Q1143.6 -339.8 1116 -379.7Q1088.4 -419.5 1043.8 -419.5Q999.3 -419.5 971.6 -379.5Q944 -339.5 944 -257.5Q944 -201.5 956.7 -164.4Q969.4 -127.3 991.8 -108.9Q1014.3 -90.5 1043.8 -90.5Z M1509 10.2Q1427.2 10.2 1387.6 -29.2Q1348 -68.6 1348 -147.7V-613.8L1474.2 -666.1V-146.7Q1474.2 -118.4 1489.9 -104.3Q1505.6 -90.3 1539.2 -90.3Q1552 -90.3 1562.7 -92.5Q1573.3 -94.8 1582.5 -98.7V-1.9Q1571.6 4 1552 7.1Q1532.4 10.2 1509 10.2ZM1270.1 -411V-510H1580.6V-411H1270.1Z M1810.8 10Q1741.7 10 1689.6 -23.6Q1637.6 -57.2 1609.1 -117.5Q1580.6 -177.8 1580.6 -257Q1580.6 -336.5 1609.2 -395.5Q1637.8 -454.5 1689.5 -487.2Q1741.2 -520 1810.8 -520Q1880.7 -520 1932.4 -487.2Q1984.1 -454.5 2012.6 -395.5Q2041 -336.5 2041 -257Q2041 -177.8 2012.5 -117.5Q1984 -57.2 1932.3 -23.6Q1880.6 10 1810.8 10ZM1810.8 -90.5Q1840.5 -90.5 1862.9 -108.9Q1885.2 -127.3 1897.9 -164.4Q1910.6 -201.5 1910.6 -257.5Q1910.6 -339.8 1883 -379.7Q1855.4 -419.5 1810.8 -419.5Q1766.3 -419.5 1738.6 -379.5Q1711 -339.5 1711 -257.5Q1711 -201.5 1723.7 -164.4Q1736.4 -127.3 1758.8 -108.9Q1781.3 -90.5 1810.8 -90.5Z M2343.3 9.9Q2288 9.9 2247.7 -21.1Q2207.4 -52.1 2198.5 -108.8L2205.8 -110.3V0H2085.8V-720H2212.1V-404.5L2203.7 -407Q2215.1 -460.8 2255.6 -490.4Q2296.2 -520 2351 -520Q2407.3 -520 2448 -488.4Q2488.8 -456.8 2510.8 -398.6Q2532.8 -340.5 2532.8 -259.9Q2532.8 -177.6 2509.3 -116.8Q2485.9 -55.9 2443.5 -23Q2401.1 9.9 2343.3 9.9ZM2305.4 -92.6Q2350.7 -92.6 2376.6 -133.8Q2402.4 -175.1 2402.4 -256.4Q2402.4 -337.7 2376.5 -377.6Q2350.6 -417.5 2305 -417.5Q2260.5 -417.5 2234.2 -376.4Q2207.9 -335.3 2207.9 -254Q2207.9 -173.3 2234.1 -132.9Q2260.3 -92.6 2305.4 -92.6Z M2834 0Q2828 -19.1 2825.7 -41.7Q2823.3 -64.2 2823.3 -91.8H2818.6V-356Q2818.6 -391.9 2803.1 -409.1Q2787.5 -426.3 2756.2 -426.3Q2724.2 -426.3 2706.4 -408.7Q2688.7 -391.2 2686.3 -358.9H2571.2Q2574.6 -429.6 2625.4 -474.8Q2676.1 -520 2763.5 -520Q2850.2 -520 2896.1 -476.5Q2941.9 -432.9 2941.9 -352.2V-91.8Q2941.9 -69.5 2944.7 -46.7Q2947.5 -23.8 2954.1 0H2834ZM2690.6 10Q2631.9 10 2595.4 -26.3Q2558.9 -62.5 2558.9 -124.5Q2558.9 -185 2594.3 -224Q2629.8 -263 2704.5 -287.6L2845.4 -337.4V-248.7L2753.4 -219.3Q2716.5 -206.1 2699.3 -186.6Q2682.2 -167.2 2682.2 -139Q2682.2 -112.4 2697.5 -98.4Q2712.9 -84.3 2739.4 -84.3Q2773.2 -84.3 2795.9 -104.1Q2818.6 -123.9 2818.6 -153.1L2829.9 -85.8Q2812.6 -37.4 2776.8 -13.7Q2741 10 2690.6 10Z M3168 10Q3080.6 10 3030.1 -34.2Q2979.6 -78.4 2974.7 -158.1H3082.4Q3086.3 -120 3108.9 -100.5Q3131.5 -80.9 3169.8 -80.9Q3202 -80.9 3218.9 -93.9Q3235.8 -106.9 3235.8 -131.3Q3235.8 -151.1 3224.3 -165.6Q3212.9 -180.1 3178.9 -195.4L3111.2 -224.8Q3053 -247.7 3023.8 -284.2Q2994.5 -320.8 2994.5 -373.9Q2994.5 -440.1 3040.1 -480Q3085.7 -520 3162.8 -520Q3242.2 -520 3288.4 -480Q3334.6 -440 3339.5 -367.9H3231.8Q3228.6 -399.7 3211.3 -414.4Q3194 -429.1 3164 -429.1Q3136.1 -429.1 3120.5 -417Q3104.8 -405 3104.8 -382.7Q3104.8 -364.2 3117.7 -349.8Q3130.6 -335.5 3162.4 -321.6L3236.6 -289.6Q3288.6 -269.2 3317.4 -229.2Q3346.1 -189.1 3346.1 -136.9Q3346.1 -69 3299.2 -29.5Q3252.3 10 3168 10Z M3587.8 10Q3520 10 3469.2 -23.3Q3418.5 -56.6 3390.5 -116.5Q3362.6 -176.3 3362.6 -255.8Q3362.6 -336.4 3390.9 -395.7Q3419.3 -454.9 3470.7 -487.5Q3522 -520 3591.1 -520Q3656.6 -520 3702.7 -489.8Q3748.8 -459.7 3773.7 -403.1Q3798.6 -346.5 3798.6 -266.5Q3798.6 -253.7 3798 -242.5Q3797.5 -231.3 3795.8 -221.4H3440V-306.9H3709L3681.8 -277.9Q3681.6 -355.2 3657.7 -390.7Q3633.8 -426.3 3589.3 -426.3Q3541.7 -426.3 3515.6 -384Q3489.5 -341.7 3489.5 -255Q3489.5 -168.4 3515 -126.1Q3540.5 -83.7 3590.6 -83.7Q3623.7 -83.7 3644.6 -102Q3665.5 -120.3 3673.8 -156.3H3788.9Q3772.2 -81.6 3721.5 -35.8Q3670.8 10 3587.8 10Z`,pu=`fill-[#ff5a1f] dark:fill-[#ff6a33]`,mu=`fill-[#14161a] dark:fill-[#f1f0ea]`,hu=({className:e})=>(0,V.jsxs)(`svg`,{viewBox:`0 0 32 32`,className:B(`size-7 shrink-0`,e),"aria-hidden":!0,children:[(0,V.jsx)(`path`,{className:pu,fillRule:`evenodd`,d:`M0 5a5 5 0 0 1 5-5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2zM4 5a1 1 0 0 1 1-1h5v6H4z`}),(0,V.jsx)(`path`,{className:mu,d:`M17 0h10a5 5 0 0 1 5 5v22a5 5 0 0 1-5 5H5a5 5 0 0 1-5-5V17h17z`})]}),gu=({className:e})=>(0,V.jsx)(`svg`,{viewBox:`54.8 -720 3743.8 925`,className:B(`h-3.5 w-auto`,e),role:`img`,"aria-label":`Protobase`,children:(0,V.jsx)(`path`,{className:mu,d:fu})}),_u=`Protobase`,vu=({compact:e,workspace:t,appName:n})=>(0,V.jsxs)(`div`,{className:`flex items-center gap-2.5 overflow-hidden`,children:[(0,V.jsx)(hu,{}),!e&&(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-0.5 leading-tight`,children:[n&&n!==_u?(0,V.jsx)(`div`,{className:`truncate text-sm font-semibold text-foreground`,children:n}):(0,V.jsx)(gu,{className:`self-start`}),t&&(0,V.jsx)(`div`,{className:`truncate text-[11px] text-muted-foreground`,children:t})]})]}),yu=[{label:`Sales`,items:[{id:`orders`,label:`Orders`,icon:xn,count:12},{id:`customers`,label:`Customers`,icon:ue},{id:`invoices`,label:`Invoices`,icon:ot,count:3}]},{label:`Inventory`,items:[{id:`products`,label:`Products`,icon:Qt},{id:`stock-moves`,label:`Stock moves`,icon:ce},{id:`warehouses`,label:`Warehouses`,icon:Zn},{id:`shipments`,label:`Shipments`,icon:Un}]},{label:`Finance`,items:[{id:`payments`,label:`Payments`,icon:Be},{id:`credit-notes`,label:`Credit notes`,icon:ln},{id:`reports`,label:`Reports`,icon:me}]},{label:`Admin`,items:[{id:`users`,label:`Users`,icon:Jn},{id:`settings`,label:`Settings`,icon:_n}]}],bu={xs:`size-5 text-[9px]`,sm:`size-6 text-[10px]`,md:`size-8 text-xs`},xu=({initials:e,hue:t,size:n=`sm`,className:r})=>(0,V.jsx)(`span`,{className:B(`inline-flex shrink-0 select-none items-center justify-center rounded-full font-semibold text-white ring-2 ring-background`,bu[n],r),style:{background:`oklch(0.58 0.13 ${t})`},children:e}),Su=({people:e,size:t=`sm`})=>(0,V.jsx)(`span`,{className:`inline-flex -space-x-1`,children:e.map(e=>(0,V.jsx)(xu,{...e,size:t},e.initials))}),Cu=e=>{let t=e.slice(1),n=t.length===3?[...t].map(e=>e+e).join(``):t,[r,i,a]=[0,2,4].map(e=>{let t=Number.parseInt(n.slice(e,e+2),16)/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4});return .2126*r+.7152*i+.0722*a},wu=`#ffffff`,Tu=`#111827`,Eu=e=>{let t=Cu(e);return 1.05/(t+.05)>=(t+.05)/(Cu(Tu)+.05)?wu:Tu},Du={neutral:`bg-muted text-muted-foreground`,blue:`bg-primary-soft text-primary-text`,green:`bg-success-soft text-success-text`,amber:`bg-warning-soft text-warning-text`,red:`bg-danger-soft text-danger-text`,violet:`bg-violet-soft text-violet-text`},Ou={neutral:`bg-faint-foreground`,blue:`bg-primary`,green:`bg-success`,amber:`bg-warning`,red:`bg-danger`,violet:`bg-violet`},ku=`polygon(0 0, calc(100% - 0.625rem) 0, 100% 50%, calc(100% - 0.625rem) 100%, 0 100%)`,Au=({tone:e=`neutral`,dot:t=!0,color:n,shape:r,children:i,className:a})=>(0,V.jsxs)(`span`,{style:{...n!==void 0&&{backgroundColor:n,color:Eu(n)},...r===`arrow`&&{clipPath:ku}},className:B(r===`arrow`?`inline-flex h-5 items-center gap-1.5 rounded-l-sm pr-4 pl-2 text-xs font-semibold whitespace-nowrap`:`inline-flex h-5 items-center gap-1.5 rounded-full px-2 text-xs font-medium whitespace-nowrap`,n===void 0&&Du[e],a),children:[t&&n===void 0&&r===void 0&&(0,V.jsx)(`span`,{className:B(`size-1.5 rounded-full`,Ou[e])}),i]}),ju=({label:e,current:t,others:n,rowClassName:r,onSwitch:i})=>(0,V.jsxs)(`div`,{className:`border-b py-1`,role:`group`,"aria-label":e,children:[t&&(0,V.jsxs)(`div`,{className:B(r,`text-foreground hover:bg-transparent`),"aria-current":`true`,children:[(0,V.jsx)(ge,{className:`size-4`}),(0,V.jsx)(`span`,{className:`truncate`,children:t.label})]}),n.map(e=>(0,V.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>i(e.id),className:r,children:[(0,V.jsx)(`span`,{className:`size-4`}),(0,V.jsx)(`span`,{className:`truncate`,children:e.label})]},e.id))]}),Mu={sm:{group:`h-7`,option:`px-2.5 text-xs`},md:{group:`h-8`,option:`px-3 text-body`}},Nu={group:(e=`sm`)=>B(`inline-flex`,Mu[e].group,`rounded-md bg-muted p-0.5`),option:(e,t=`sm`)=>B(`inline-flex items-center gap-1.5 rounded`,Mu[t].option,`font-medium transition-colors`,e?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`)},Pu=({value:e,options:t,onChange:n,label:r,size:i=`sm`,iconOnly:a=!1})=>(0,V.jsx)(`span`,{role:`group`,"aria-label":r,className:Nu.group(i),children:t.map(t=>(0,V.jsxs)(`button`,{type:`button`,"aria-pressed":t.value===e,...a&&{"aria-label":t.label,title:t.label},onClick:()=>n(t.value),className:Nu.option(t.value===e,i),children:[t.icon&&(0,V.jsx)(t.icon,{className:`size-3.5`}),!a&&t.label]},t.value))}),Fu=[{value:`light`,label:`Light`,icon:jn},{value:`dark`,label:`Dark`,icon:Jt},{value:`system`,label:`System`,icon:Kt}],Iu=({theme:e,className:t})=>(0,V.jsxs)(`div`,{className:t,children:[(0,V.jsx)(kn,{className:`size-4`}),(0,V.jsx)(`span`,{className:`flex-1`,children:`Theme`}),(0,V.jsx)(Pu,{label:`Theme`,iconOnly:!0,value:e.preference,options:Fu,onChange:e.onChange})]}),Lu=`flex min-h-11 w-full items-center gap-2.5 px-3 py-1.5 text-left text-muted-foreground hover:bg-muted md:min-h-0`,Ru=({user:e,compact:t,open:n,items:r=[],onNavigate:i,onSignOut:a,organizations:s,roles:c,theme:l})=>{let u=c?.roles.find(e=>e.name===c.active),[d,f]=(0,o.useState)(!1),p=n??d,m=(0,o.useRef)(null),[h,g]=(0,o.useState)();return(0,o.useEffect)(()=>{if(!p||n!==void 0)return;let e=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!m.current?.contains(e.target))&&f(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,e)}},[p,n]),(0,V.jsxs)(`div`,{ref:m,className:`relative`,children:[(0,V.jsxs)(`button`,{type:`button`,className:`flex min-h-11 w-full items-center gap-2.5 rounded-md p-1 text-left hover:bg-muted md:min-h-0`,"aria-label":`Profile menu`,"aria-haspopup":`menu`,"aria-expanded":p,onClick:()=>{let e=m.current?.getBoundingClientRect();e&&g({left:e.left,bottom:window.innerHeight-e.top+8}),f(!d)},children:[(0,V.jsx)(xu,{initials:e.initials,hue:e.hue,size:`md`,className:`ring-0`}),!t&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1 leading-tight`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.name}),(0,V.jsx)(Au,{tone:e.roleTone,dot:!1,className:`mt-0.5 h-4 px-1.5 text-[10px]`,children:e.role})]}),(0,V.jsx)(we,{className:`size-3.5 shrink-0 text-faint-foreground`})]})]}),p&&(0,V.jsxs)(`div`,{role:`menu`,className:n===void 0?`fixed z-[60] w-56 overflow-hidden rounded-lg border bg-background py-1 shadow-pop`:`absolute bottom-full left-0 z-50 mb-2 w-56 overflow-hidden rounded-lg border bg-background py-1 shadow-pop`,style:n===void 0&&h?{left:h.left,bottom:h.bottom}:void 0,children:[(0,V.jsxs)(`div`,{className:`border-b px-3 pb-2 pt-1.5`,children:[(0,V.jsx)(`div`,{className:`font-medium`,children:e.name}),(0,V.jsx)(`div`,{className:`truncate text-xs text-muted-foreground`,children:e.email})]}),s&&(s.current||s.others.length>0)&&(0,V.jsx)(ju,{label:`Organizations`,...s.current&&{current:{id:s.current.id,label:s.current.name}},others:s.others.map(({id:e,name:t})=>({id:e,label:t})),rowClassName:Lu,onSwitch:e=>{f(!1),s.onSwitch(e)}}),c&&c.roles.length>1&&(0,V.jsx)(ju,{label:`Roles`,...u&&{current:{id:u.name,label:u.label}},others:c.roles.filter(e=>e!==u).map(({name:e,label:t})=>({id:e,label:t})),rowClassName:Lu,onSwitch:e=>{f(!1),c.onSwitch(e)}}),r.length>0&&(0,V.jsx)(`div`,{className:B((l||a)&&`border-b`),children:r.map(e=>{let t=e.icon;return(0,V.jsxs)(`a`,{role:`menuitem`,href:e.href,"aria-current":e.active?`page`:void 0,...e.external?{target:`_blank`,rel:`noreferrer`}:{},onClick:t=>{f(!1),!e.external&&i&&(t.preventDefault(),i(e.href))},className:B(Lu,e.active&&`bg-muted text-foreground`),children:[(0,V.jsx)(t,{className:`size-4`}),e.label]},e.id)})}),l&&(0,V.jsx)(`div`,{className:B(a&&`border-b`),children:(0,V.jsx)(Iu,{theme:l,className:B(Lu,`hover:bg-transparent`)})}),a&&(0,V.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:a,className:Lu,children:[(0,V.jsx)(Rt,{className:`size-4`}),`Sign out`]})]})]})},zu=(e,t)=>{try{return e()}catch(e){if(!(e instanceof DOMException))throw e;return t}},Bu=`protobase:nav-open:`,Vu=e=>`${Bu}${e}`,Hu=(e,t)=>zu(()=>e.getItem(t)!==`false`,!0),Uu=(e,t,n)=>zu(()=>n?e.removeItem(t):e.setItem(t,`false`),void 0),Wu=({label:e,side:t=`right`,visible:n,children:r})=>(0,V.jsxs)(`span`,{className:`group/tooltip relative inline-flex`,children:[r,(0,V.jsx)(`span`,{role:`tooltip`,className:B(`pointer-events-none absolute z-50 whitespace-nowrap rounded-md bg-foreground px-2 py-1 text-xs font-medium text-background opacity-0 shadow-md transition-opacity group-hover/tooltip:opacity-100`,n&&`opacity-100`,t===`right`&&`left-full top-1/2 ml-2 -translate-y-1/2`,t===`top`&&`bottom-full left-1/2 mb-2 -translate-x-1/2`,t===`bottom`&&`left-1/2 top-full mt-2 -translate-x-1/2`),children:e})]}),Gu=e=>e===`text-large`||e===`text-small`||e===`icon-expand`,Ku=e=>e===`text-large`||e===`text-small`,qu={"text-large":`w-60`,"text-small":`w-52`,icon:`w-14`,"icon-label":`w-[76px]`,"icon-tooltip":`w-14`,"icon-expand":`w-14`},Ju={"text-large":`h-9 gap-3 px-3 text-sm`,"text-small":`h-7 gap-2.5 px-2.5 text-xs`,icon:`size-9 justify-center`,"icon-label":`w-full flex-col gap-0.5 py-1.5 text-[10px]`,"icon-tooltip":`size-9 justify-center`,"icon-expand":`h-8 gap-3 px-3`},Yu=({item:e,mode:t,active:n,onNavigate:r,className:i})=>{let a=e.icon,o=(0,V.jsxs)(`a`,{onClick:r&&(t=>{t.preventDefault(),r(e.href??`#${e.id}`)}),href:e.href??`#${e.id}`,"aria-label":e.problem?`${e.label}: ${e.problem}`:e.label,"aria-current":n?`page`:void 0,title:e.problem,className:B(`flex shrink-0 items-center rounded-md font-medium transition-colors`,Ju[t],n?`bg-primary-soft text-primary-text`:`text-muted-foreground hover:bg-muted hover:text-foreground`,i),children:[(0,V.jsx)(a,{className:B(`shrink-0`,t===`text-small`?`size-4`:`size-[18px]`),strokeWidth:n?2.2:1.9}),(Gu(t)||t===`icon-label`)&&(0,V.jsx)(`span`,{className:`whitespace-nowrap`,children:e.label}),Ku(t)&&e.count&&(0,V.jsx)(`span`,{className:`ml-auto rounded bg-muted px-1.5 text-[11px] tabular-nums text-muted-foreground`,children:e.count}),Ku(t)&&e.problem&&(0,V.jsx)(Vn,{"aria-hidden":!0,className:`ml-auto size-3.5 shrink-0 text-warning-text`})]});return t===`icon-tooltip`?(0,V.jsx)(Wu,{label:e.label,children:o}):o},Xu={neutral:`bg-faint-foreground`,info:`bg-primary`,success:`bg-success`,warning:`bg-warning`,danger:`bg-danger`},Zu=({tone:e,pulse:t=!1,className:n})=>(0,V.jsxs)(`span`,{"aria-hidden":!0,className:B(`relative flex size-2 shrink-0`,n),"data-tone":e,"data-pulse":t||void 0,children:[t&&(0,V.jsx)(`span`,{className:B(`absolute inset-0 animate-ping rounded-full opacity-60 motion-reduce:animate-none`,Xu[e])}),(0,V.jsx)(`span`,{className:B(`relative size-2 rounded-full`,Xu[e])})]}),Qu={"text-large":`h-8 gap-2.5 px-2.5`,"text-small":`h-7 gap-2 px-2 text-xs`},$u={"text-large":`ml-[20px]`,"text-small":`ml-[17px]`},ed=({item:e,recent:t,mode:n,active:r,onNavigate:i})=>{let a=Vu(e.id),[s,c]=(0,o.useState)(()=>Hu(localStorage,a)),l=(0,o.useId)(),u=e.href??`#${e.id}`,d=()=>{Uu(localStorage,a,!s),c(!s)},f=e=>({href:e,onClick:i&&(t=>{t.preventDefault(),i(e)})});return(0,V.jsxs)(`div`,{className:`flex flex-col gap-0.5`,children:[(0,V.jsxs)(`div`,{className:`relative`,children:[(0,V.jsx)(Yu,{item:e,mode:n,active:r,onNavigate:i,className:`pr-8`}),(0,V.jsx)(`button`,{type:`button`,"aria-expanded":s,"aria-controls":l,"aria-label":`Recent ${e.label.toLowerCase()}`,onClick:d,className:`absolute right-1 top-1/2 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground`,children:(0,V.jsx)(Se,{className:B(`size-3.5 transition-transform`,s&&`rotate-90`)})})]}),s&&(0,V.jsxs)(`ul`,{id:l,"aria-label":`Recent ${e.label.toLowerCase()}`,className:B(`flex flex-col gap-0.5 border-l pl-1.5`,$u[n]),children:[t.state===`loading`&&(0,V.jsx)(`li`,{className:B(`flex items-center text-faint-foreground`,Qu[n]),children:`Loading...`}),t.state===`error`&&(0,V.jsx)(`li`,{className:B(`flex items-center text-faint-foreground`,Qu[n]),children:`Could not load`}),t.state===`ready`&&t.records.map(e=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(`a`,{...f(e.href),"aria-label":`${e.label}, ${e.status}`,title:`${e.label} (${e.status})`,"aria-current":e.active?`page`:void 0,className:B(`flex min-w-0 items-center rounded-md font-medium transition-colors`,Qu[n],e.active?`bg-muted text-foreground`:`text-muted-foreground hover:bg-muted hover:text-foreground`),children:[(0,V.jsx)(Zu,{tone:e.tone,pulse:e.pulse}),(0,V.jsx)(`span`,{className:`truncate`,children:e.label})]})},e.id)),(0,V.jsx)(`li`,{children:(0,V.jsx)(`a`,{...f(u),className:B(`flex items-center rounded-md text-faint-foreground transition-colors hover:bg-muted hover:text-foreground`,Qu[n]),children:`View all`})})]})]})},td=({mode:e,activeItem:t,user:n,workspace:r,appName:i,forceExpanded:a,profileMenuOpen:o,groups:s=yu,userMenu:c,onNavigate:l,onSignOut:u,signIn:d,organizations:f,roles:p,theme:m,sticky:h,logo:g=vu})=>{let _=e===`icon-expand`,v=_&&a,y=Ku(e)||_;return(0,V.jsx)(`nav`,{"aria-label":`Resources`,className:B(h?`sticky top-0 h-dvh self-start`:`relative`,`z-30 shrink-0`,qu[e]),children:(0,V.jsxs)(`div`,{className:B(`group/side absolute inset-y-0 left-0 flex flex-col overflow-hidden border-r bg-sidebar`,_?`w-14 transition-[width,box-shadow] duration-150 hover:w-60 hover:shadow-pop focus-within:w-60 focus-within:shadow-pop`:`w-full`,v&&`w-60 shadow-pop`),children:[(0,V.jsx)(`div`,{className:B(`flex h-12 shrink-0 items-center px-3.5`,e===`icon-label`&&`justify-center px-0`),children:(0,V.jsx)(g,{compact:!y,workspace:r,appName:i})}),(0,V.jsx)(`div`,{className:B(`flex-1 overflow-y-auto overflow-x-hidden pb-2`,`px-2`),children:s.map((n,r)=>(0,V.jsxs)(`div`,{className:B(`flex flex-col gap-0.5`,r>0&&`mt-3`),children:[y?(0,V.jsx)(`div`,{className:B(`px-3 pb-1 pt-1 text-[11px] font-medium uppercase tracking-wide text-faint-foreground`,_&&`h-4 whitespace-nowrap py-0 opacity-0 transition-opacity group-hover/side:opacity-100 group-focus-within/side:opacity-100`,v&&`opacity-100`),children:n.label}):r>0&&(0,V.jsx)(`div`,{className:`mx-auto mb-1 h-px w-6 bg-border`}),n.items.map(n=>n.recent&&Ku(e)?(0,V.jsx)(ed,{item:n,recent:n.recent,mode:e,active:n.id===t,onNavigate:l},n.id):(0,V.jsx)(Yu,{item:n,mode:e,active:n.id===t,onNavigate:l},n.id))]},n.label))}),(0,V.jsx)(`div`,{className:B(`shrink-0 border-t p-2`,e!==`text-large`&&e!==`text-small`&&!_&&`flex justify-center`),children:n?(0,V.jsx)(Ru,{user:n,compact:!y,open:o,items:c,onNavigate:l,onSignOut:u,organizations:f,roles:p,theme:m}):(0,V.jsxs)(V.Fragment,{children:[m&&y&&(0,V.jsx)(Iu,{theme:m,className:`flex min-h-11 w-full items-center gap-2.5 whitespace-nowrap p-1.5 text-muted-foreground md:min-h-0`}),d&&(0,V.jsxs)(du,{to:d,"aria-label":`Sign in`,className:`flex min-h-11 w-full items-center gap-2.5 rounded-md p-1.5 text-left font-medium text-muted-foreground hover:bg-muted hover:text-foreground md:min-h-0`,children:[(0,V.jsx)(It,{className:`size-4 shrink-0`}),y&&(0,V.jsx)(`span`,{className:`whitespace-nowrap`,children:`Sign in`})]})]})})]})})},nd=(0,o.createContext)(null),rd=()=>(0,o.useContext)(nd),id=e=>{let t=e.at(-2);if(typeof t==`object`&&t.href&&!t.loading)return{label:t.label,href:t.href}},ad=(0,o.createContext)(void 0),od=()=>{let e=(0,o.useContext)(ad);return e?{id:e.id,name:e.name,"aria-describedby":e.describedBy,"aria-invalid":e.invalid||void 0,"aria-required":e.required||void 0}:{}},sd=({leading:e,trailing:t,invalid:n,className:r,wrapperClassName:i,...a})=>{let o=od();return(0,V.jsxs)(`span`,{className:B(`flex h-8 items-center gap-2 rounded-md border bg-background px-2.5 text-muted-foreground shadow-sm focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20`,n?`border-danger`:`border-border-strong`,i),children:[e,(0,V.jsx)(`input`,{className:B(`min-w-0 flex-1 bg-transparent text-body text-foreground outline-none placeholder:text-faint-foreground`,r),...o,...n&&{"aria-invalid":!0},...a}),t]})},cd=({children:e})=>(0,V.jsx)(`kbd`,{className:`inline-flex h-5 items-center rounded border border-border-strong bg-background px-1.5 font-sans text-[11px] font-medium text-muted-foreground`,children:e}),ld=({className:e})=>(0,V.jsx)(Mt,{"aria-label":`Loading`,className:B(`size-4 animate-spin`,e)}),ud=(e,t,n)=>t===0?-1:e<0?n===1?0:t-1:(e+n+t)%t,dd=e=>e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0,fd=({search:e,className:t=`w-96`,autoFocus:n,showShortcut:r=!0,ref:i})=>{let a=(0,o.useId)(),s=(0,o.useRef)(null),[c,l]=(0,o.useState)(!1),[u,d]=(0,o.useState)(-1),f=e.groups.flatMap(e=>e.hits),p=c&&(e.query!==``||e.loading),m=e=>`${a}-${e}`,h=e=>{s.current=e,typeof i==`function`?i(e):i&&(i.current=e)},g=t=>{e.onSelect(t),d(-1),s.current?.blur()},_=()=>{e.onTextChange(``),d(-1),s.current?.focus()},v=t=>{if(t.key===`ArrowDown`||t.key===`ArrowUp`)t.preventDefault(),d(e=>ud(e,f.length,t.key===`ArrowDown`?1:-1));else if(t.key===`Enter`){let e=f[u]??f[0];if(!e)return;t.preventDefault(),g(e.href)}else t.key===`Escape`&&(e.text?e.onTextChange(``):t.currentTarget.blur(),d(-1))},y=-1;return(0,V.jsxs)(`div`,{className:B(`relative`,t),children:[(0,V.jsx)(sd,{ref:h,wrapperClassName:`w-full bg-surface shadow-none`,leading:e.loading?(0,V.jsx)(ld,{className:`size-4`}):(0,V.jsx)(pn,{className:`size-4`}),trailing:e.text?(0,V.jsx)(`button`,{type:`button`,"aria-label":`Clear search`,className:`-mr-1 inline-flex size-6 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground`,onMouseDown:e=>e.preventDefault(),onClick:_,children:(0,V.jsx)($n,{className:`size-3.5`})}):r?(0,V.jsx)(`span`,{className:`hidden md:inline-flex`,children:(0,V.jsx)(cd,{children:`⌘K`})}):void 0,placeholder:e.placeholder,"aria-label":`Global search`,role:`combobox`,"aria-autocomplete":`list`,"aria-expanded":p,"aria-controls":a,"aria-activedescendant":p&&f[u]?m(u):void 0,autoFocus:n,value:e.text,onChange:t=>{e.onTextChange(t.target.value),d(-1)},onFocus:()=>l(!0),onBlur:()=>l(!1),onKeyDown:v}),p&&(0,V.jsxs)(`div`,{id:a,role:`listbox`,"aria-label":`Search results`,className:`absolute right-0 top-full z-40 mt-1 max-h-96 w-full min-w-72 overflow-y-auto rounded-lg border bg-background py-1 shadow-pop`,children:[e.groups.length===0&&(0,V.jsx)(`p`,{className:`px-3 py-2 text-muted-foreground`,children:e.loading?`Searching`:`No matches for “${e.query}”`}),e.groups.map(e=>(0,V.jsxs)(`div`,{role:`group`,"aria-label":e.label,children:[(0,V.jsx)(`div`,{className:`px-3 pb-1 pt-2 text-[11px] font-medium uppercase tracking-wide text-faint-foreground`,children:e.label}),e.failed&&(0,V.jsxs)(`p`,{className:`px-3 py-1.5 text-danger-text`,children:[`Could not search `,e.label.toLowerCase()]}),e.hits.map(e=>{y+=1;let t=y;return(0,V.jsxs)(`a`,{id:m(t),href:e.href,tabIndex:-1,role:`option`,"aria-selected":t===u,className:B(`block px-3 py-1.5`,t===u?`bg-primary-soft text-primary-text`:`hover:bg-muted`),onMouseDown:e=>e.preventDefault(),onClick:t=>{dd(t)||(t.preventDefault(),g(e.href))},onMouseEnter:()=>d(t),children:[(0,V.jsx)(`span`,{className:`block truncate font-semibold`,children:e.title}),e.subtitle&&(0,V.jsx)(`span`,{className:B(`block truncate text-xs`,t===u?`text-primary-text/80`:`text-muted-foreground`),children:e.subtitle})]},e.id)})]},e.id))]})]})},pd=({breadcrumb:e,onNavigate:t,actions:n,onMenu:r,menuOpen:i,menuControls:a,search:s,sticky:c,slotRef:l,ref:u})=>{let[d,f]=(0,o.useState)(!1),p=id(e),m=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(!s)return;let e=e=>{if(e.key.toLowerCase()!==`k`||!(e.metaKey||e.ctrlKey))return;e.preventDefault();let t=m.current;t&&t.offsetParent!==null?t.focus():f(!0)};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[s]),(0,V.jsxs)(`header`,{ref:u,className:B(c?`sticky top-0 z-30`:`relative`,`flex h-12 shrink-0 items-center gap-1 border-b bg-background pl-4 pr-2 md:gap-4 md:px-5`),children:[r&&(0,V.jsx)(`button`,{type:`button`,"aria-label":`Open navigation`,"aria-expanded":!!i,"aria-controls":a,onClick:r,className:B(`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`,`-ml-3`),children:(0,V.jsx)(aee,{className:`size-5`})}),p&&(0,V.jsx)(`a`,{href:p.href,"aria-label":`Back to ${p.label}`,onClick:e=>{t&&lu(e)&&(e.preventDefault(),t(p.href))},className:B(`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`,!r&&`-ml-3`),children:(0,V.jsx)(be,{className:`size-5`})}),(0,V.jsx)(uu,{parts:e,onNavigate:t}),(0,V.jsxs)(`div`,{className:`ml-auto flex items-center gap-1 md:gap-3`,children:[s&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`div`,{className:`hidden md:block`,children:(0,V.jsx)(fd,{ref:m,search:s})}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Search`,"aria-expanded":d,onClick:()=>f(!0),className:`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`,children:(0,V.jsx)(pn,{className:`size-5`})})]}),n,(0,V.jsx)(`div`,{ref:l,className:`contents md:hidden`})]}),s&&d&&(0,V.jsxs)(`div`,{className:`absolute inset-0 z-20 flex items-center gap-1 bg-background px-3 md:hidden`,children:[(0,V.jsx)(fd,{className:`min-w-0 flex-1`,autoFocus:!0,showShortcut:!1,search:{...s,onSelect:e=>{s.onSelect(e),f(!1)}}}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Close search`,onClick:()=>f(!1),className:`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`,children:(0,V.jsx)($n,{className:`size-5`})})]})]})},md=`app-drawer`,hd=({sidebarMode:e,activeItem:t,breadcrumb:n,user:r,workspace:i,appName:a,logo:s,actions:c,rightPanel:l,forceExpanded:u,profileMenuOpen:d,navGroups:f,userMenu:p,bottomBar:m,onNavigate:h,onSignOut:g,signIn:_,organizations:v,roles:y,theme:b,search:x,pageScroll:S=!1,className:C,children:w})=>{let T=Kl(),[E,D]=(0,o.useState)(!1);(0,o.useEffect)(()=>{T&&D(!1)},[T]);let O=!T&&m&&m.length>0?m:void 0,[k,A]=(0,o.useState)(),j=k??S,M=(0,o.useRef)(null),[N,ee]=(0,o.useState)(null),P=(0,o.useRef)(null);su(j,M,P,!!O),au(j);let te=(e,n=!1)=>(0,V.jsx)(td,{mode:e,sticky:n,activeItem:t,user:r,workspace:i,appName:a,forceExpanded:u,profileMenuOpen:d,groups:f,userMenu:p,onNavigate:h,onSignOut:g,signIn:_,organizations:v,roles:y,theme:b,logo:s});return(0,V.jsx)(ru.Provider,{value:A,children:(0,V.jsxs)(`div`,{className:B(j?`flex min-h-full w-full overflow-x-clip bg-background`:`relative flex h-full min-h-0 w-full overflow-hidden bg-background`,C),children:[T?te(e,j):(0,V.jsx)(nu,{id:md,open:E,onClose:()=>D(!1),children:te(`text-large`)}),(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,V.jsx)(pd,{ref:M,slotRef:ee,sticky:j,breadcrumb:n,onNavigate:h,actions:c,onMenu:T||O?void 0:()=>D(!0),menuOpen:E,menuControls:md,search:x}),(0,V.jsx)(`main`,{className:j?`flex flex-1 flex-col`:`flex min-h-0 flex-1 flex-col`,children:(0,V.jsx)(nd.Provider,{value:N,children:w})}),O&&(0,V.jsx)(Xl,{ref:P,sticky:j,tabs:O,onNavigate:h,onMore:()=>D(!0),moreOpen:E,moreControls:md})]}),l&&(0,V.jsx)(`div`,{className:j?`sticky top-0 flex h-dvh shrink-0 self-start`:`flex shrink-0`,children:l})]})})},gd=({title:e,subtitle:t,aside:n,actions:r})=>{let i=(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight`,children:e}),t&&(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:t})]});return(0,V.jsxs)(`div`,{className:`flex flex-wrap items-end justify-between gap-x-4 gap-y-2`,children:[n?(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center justify-between gap-3`,children:[i,n]}):i,r&&(0,V.jsx)(`div`,{className:`flex w-full flex-wrap items-center gap-2 sm:w-auto`,children:r})]})},_d=`Too many attempts. Wait a minute and try again.`,vd=`The passkey prompt closed before it finished. Try again.`,yd={INVALID_EMAIL_OR_PASSWORD:`The email or password is not right.`,INVALID_PASSWORD:`The password is not right.`,INVALID_OTP:`The code is not right.`,OTP_EXPIRED:`The code has expired. Ask for a new one.`,TOO_MANY_ATTEMPTS:`Too many wrong codes. Ask for a new one.`,INVALID_CODE:`The code is not right.`,INVALID_BACKUP_CODE:`The backup code is not right, or was used before.`,TOO_MANY_ATTEMPTS_REQUEST_NEW_CODE:`Too many wrong codes. Sign in again.`,ACCOUNT_TEMPORARILY_LOCKED:`Too many wrong codes. Wait 15 minutes and try again.`,INVALID_TWO_FACTOR_COOKIE:`This sign-in took too long. Sign in again.`,AUTH_CANCELLED:vd,ERROR_CEREMONY_ABORTED:vd,REGISTRATION_CANCELLED:vd,PASSKEY_NOT_FOUND:`This passkey is not registered for an account here.`,AUTHENTICATION_FAILED:`The passkey could not be checked. Try again.`,PREVIOUSLY_REGISTERED:`This passkey is added already.`,ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED:`This passkey is added already.`,SESSION_NOT_FRESH:`For this change, sign out and sign in again first.`},bd=e=>e.code?yd[e.code]:void 0,xd=e=>bd(e)??(e.status===429?_d:e.message),Sd=e=>bd(e)??(e.status===429?_d:e.status===401?yd.INVALID_EMAIL_OR_PASSWORD:e.message),Cd={STAFF_PERMISSION_MISSING:`Your staff account has no permission to sign in as people here.`,STAFF_SIGN_IN_NOT_STRONG:`Sign in to your staff account with a passkey or a second step, then try again.`,STAFF_SIGN_IN_STALE:`Your staff sign-in is too old. Sign in to your staff account again.`,STAFF_SIGN_IN_EXPIRED:`This staff sign-in took too long or was used already. Start again.`,STAFF_SIGN_IN_FAILED:`The staff sign-in did not go through at the provider. Try again.`,STAFF_USER_UNAVAILABLE:`There is no account with this address, or it is disabled.`,STAFF_REASON_REQUIRED:`Say why you sign in as this person, in at least 10 characters.`,SIGN_IN_METHOD_FORBIDDEN:`Staff sign-in is turned off for this app.`,INVALID_CALLBACK_URL:`This page is not on an address the server trusts.`},wd=e=>{let t=typeof e==`string`?e:e.code;return t&&Cd[t]?Cd[t]:typeof e==`string`?`The staff sign-in did not go through. Try again.`:e.status===429?_d:e.message},Td={signup_disabled:e=>`No account here belongs to this ${e} account. Ask an admin to add you, or sign in another way.`,account_not_linked:e=>`Your ${e} account is not linked to your account here. Sign in another way, then connect ${e} on the Sign-in & security page.`,account_already_linked_to_different_user:e=>`This ${e} account is linked to someone else here already.`,unable_to_link_account:e=>`Your ${e} account could not be linked. Try again.`,access_denied:e=>`${e} did not let you in, or you cancelled.`,EMAIL_DOMAIN_NOT_ALLOWED:e=>`${e} signed you in with an address this app does not accept from it. Sign in another way.`},Ed=(e,t)=>Td[e]?.(t)??`Signing in with ${t} did not go through. Try again.`,Dd=`sign-in`,Od=`error`,kd=e=>{let t=new URL(e).searchParams;if(!t.has(Od))return t.get(`sign-in`)||void 0},Ad=e=>new URL(e).searchParams.get(Od)||void 0,jd=e=>{let t=new URL(e);for(let e of[Dd,Od])t.searchParams.delete(e);return`${t.pathname}${t.search}${t.hash}`},Md={github:`GitHub`,gitlab:`GitLab`,google:`Google`,microsoft:`Microsoft`,apple:`Apple`},Nd=(e,t)=>t?.provider===e?t.name:Md[e]??e.charAt(0).toUpperCase()+e.slice(1),Pd=(0,o.createContext)(null),H=()=>{let e=(0,o.useContext)(Pd);if(!e)throw Error(`useAuth must be used inside AuthProvider`);return e},Fd=({session:e,children:t})=>{let[n,r]=(0,o.useState)({kind:`loading`}),[i,a]=(0,o.useState)([`password`]),[s,c]=(0,o.useState)(!1),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)([]),[p,m]=(0,o.useState)([]),[h,g]=(0,o.useState)(),[_,v]=(0,o.useState)([]),[y,b]=(0,o.useState)(),[x,S]=(0,o.useState)(),[C,w]=(0,o.useState)(!1),[T,E]=(0,o.useState)([]),D=(0,o.useCallback)(()=>C?{kind:`visitor`}:{kind:`signed-out`},[C]),O=(0,o.useCallback)(()=>r(e=>e.kind===`signed-in`?{kind:`signed-out`}:e),[]),k=(0,o.useRef)(O);k.current=O;let A=(0,o.useMemo)(()=>e??Il({onSignedOut:()=>k.current()}),[e]),j=(0,o.useCallback)(async e=>{let[{missing:t},n]=await Promise.all([A.account.signInMethods(),A.staff.current()]);r(t.length>0?{kind:`setup-required`,user:e,missing:t}:{kind:`signed-in`,user:e,...n&&{staff:n}})},[A]),M=(0,o.useCallback)(async e=>e.kind===`two-factor`?r({kind:`two-factor`,methods:e.methods}):j(e.user),[j]),N=(0,o.useCallback)(()=>{r({kind:`loading`}),A.status().then(async e=>{if(a(e.signInMethods),c(e.passwordReset),u(!!e.signUp),f(e.passkeyDomains??[]),m(e.socialProviders),g(e.platformSignIn),v(e.samlProviders),b(e.staffSignIn),S(e.organizations),w(!!e.anonymous),E(e.plugins??[]),e.needsAdmin)return r({kind:`needs-admin`});let t=await A.session();return t?j(t):r({kind:e.anonymous?`visitor`:`signed-out`})}).catch(e=>r({kind:`error`,message:e instanceof Error?e.message:`The server did not answer`}))},[A,j]);(0,o.useEffect)(N,[N]);let ee=(0,o.useMemo)(()=>({state:n,session:A,signInMethods:i,passwordReset:s,canSignUp:l,passkeyDomains:d,socialProviders:p,signInProviders:[...p.map(e=>({id:e,name:Nd(e,h)})),..._],staffSignIn:y,...x&&{organizations:x},markSignedOut:O,recheck:N,beforeSignIn:T,adoptSession:async()=>{let e=await A.session();return e?(await j(e),!0):!1},...C&&{browse:()=>{r(e=>e.kind===`signed-out`?{kind:`visitor`}:e)}},signIn:async(e,t)=>M(await A.signIn(e,t)),sendSignInCode:e=>A.sendSignInCode(e),signInWithCode:async(e,t)=>M(await A.signInWithCode(e,t)),sendSignUpCode:e=>A.sendSignUpCode(e),verifySignUpCode:(e,t)=>A.verifySignUpCode(e,t),signUp:async e=>j(await A.signUp(e)),signInWithPasskey:async e=>j(await A.signInWithPasskey(e)),verifyTwoFactor:async e=>j(await A.verifyTwoFactor(e)),signInSocial:async e=>{let t=new URL(jd(window.location.href),window.location.href).href,n=_.some(t=>t.id===e);window.location.assign(await(n?A.signInSaml(e,t):A.signInSocial(e,t)))},linkProvider:async e=>{window.location.assign(await A.account.linkProvider(e,new URL(jd(window.location.href),window.location.href).href))},stopStaffSession:async()=>{await A.staff.stop(),r(D())},signOut:async()=>{await A.signOut(),r(D())}}),[n,A,i,s,l,d,p,h,_,y,x,C,T,D,O,N,M,j]);return(0,V.jsx)(Pd.Provider,{value:ee,children:t})},Id=new Map,Ld=(e,t)=>{let n=`${e}:${t??``}`,r=Id.get(n);if(r)return r;let i=new Intl.NumberFormat(`en-IE`,{style:`currency`,currency:e,...t!==void 0&&{minimumFractionDigits:t,maximumFractionDigits:t}});return Id.set(n,i),i},Rd=(e,t=`EUR`,n)=>Ld(t,n).format(e/100),zd=new Intl.NumberFormat(`en-IE`),Bd=e=>zd.format(e),Vd=e=>e>0?`+${zd.format(e)}`:zd.format(e).replace(`-`,`−`),Hd=e=>`${e}%`,Ud=e=>{if(e<1e4)return`${Bd(e)} rows`;let t=10**(Math.floor(Math.log10(e))-3);return`about ${Bd(Math.round(e/t)*t)} rows`},Wd=()=>Intl.DateTimeFormat().resolvedOptions().timeZone,Gd=new Map,Kd=e=>{let t=Gd.get(e);if(t)return t;let n=new Intl.DateTimeFormat(`en-US`,{timeZone:e,hourCycle:`h23`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`});return Gd.set(e,n),n},qd=(e,t)=>{let n=Object.fromEntries(Kd(t).formatToParts(e).map(e=>[e.type,e.value]));return{year:Number(n.year),month:Number(n.month),day:Number(n.day),hour:Number(n.hour),minute:Number(n.minute),second:Number(n.second)}},Jd=(e,t)=>{let n=qd(e,t);return Date.UTC(n.year,n.month-1,n.day,n.hour,n.minute,n.second)-Math.floor(e/1e3)*1e3},Yd=e=>String(e).padStart(2,`0`),Xd=(e,t)=>{let n=qd(e,t);return`${n.year}-${Yd(n.month)}-${Yd(n.day)}`},Zd=(e,t)=>e-Jd(e-Jd(e,t),t),Qd=(e,t)=>Zd(Date.parse(`${e}T00:00:00Z`),t),$d=new Map,ef=(e,t)=>{let n=$d.get(t)??new Intl.DateTimeFormat(`en-GB`,{timeZone:t,timeZoneName:`shortOffset`});$d.set(t,n);let r=n.formatToParts(e).find(e=>e.type===`timeZoneName`)?.value??t;return t===`UTC`||t===`Etc/UTC`?`UTC`:`${t} (${r})`},tf=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),nf=new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,timeZone:`UTC`}),rf=new Intl.DateTimeFormat(`en-GB`,{month:`long`,year:`numeric`,timeZone:`UTC`}),af=new Intl.DateTimeFormat(`en-GB`,{weekday:`short`,timeZone:`UTC`}),of=new Intl.DateTimeFormat(`en-GB`,{weekday:`long`,day:`numeric`,month:`short`,year:`numeric`,timeZone:`UTC`}),sf=e=>tf.format(e),cf=e=>nf.format(e),lf=new Map,uf=e=>{let t=lf.get(e);if(t)return t;let n={day:new Intl.DateTimeFormat(`en-GB`,{day:`numeric`,month:`short`,year:`numeric`,timeZone:e}),time:new Intl.DateTimeFormat(`en-GB`,{hour:`2-digit`,minute:`2-digit`,hour12:!1,timeZone:e})};return lf.set(e,n),n},df=(e,t=Wd())=>{let n=uf(t);return`${n.day.format(e)}, ${n.time.format(e)}`},ff=e=>rf.format(e),pf=e=>af.format(e),mf=e=>of.format(e),hf=(e,t)=>tf.formatRange(e,t),gf=(e,t=Wd())=>uf(t).time.format(e),_f=e=>e<60?`${e} s ago`:e<3600?`${Math.floor(e/60)} min ago`:e<86400?`${Math.floor(e/3600)} h ago`:`${Math.floor(e/86400)} d ago`,vf=new Intl.RelativeTimeFormat(`en`,{numeric:`auto`}),yf=[[`year`,31536e3],[`month`,2592e3],[`day`,86400],[`hour`,3600],[`minute`,60]],bf=e=>{let[t,n]=yf.find(([,t])=>e>=t)??[`second`,1];return t===`second`&&e<45?`just now`:vf.format(-Math.floor(e/n),t)},xf={primary:`bg-primary text-primary-foreground hover:bg-primary-hover shadow-sm`,secondary:`bg-background text-foreground border border-border-strong hover:bg-muted shadow-sm`,ghost:`text-muted-foreground hover:bg-muted hover:text-foreground`,danger:`bg-background text-danger-text border border-border-strong hover:bg-danger-soft shadow-sm`},Sf={sm:`h-7 px-2.5 text-xs gap-1.5`,md:`h-8 px-3 text-body gap-2`},Cf=({variant:e=`secondary`,size:t=`md`}={})=>B(`inline-flex shrink-0 items-center justify-center rounded-md font-medium transition-colors focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary disabled:opacity-60 disabled:cursor-default`,xf[e],Sf[t]),U=({variant:e=`secondary`,size:t=`md`,loading:n,className:r,children:i,disabled:a,...o})=>(0,V.jsxs)(`button`,{type:`button`,disabled:a||n,className:B(Cf({variant:e,size:t}),r),...o,children:[n&&(0,V.jsx)(ld,{className:`size-3.5`}),i]}),wf=({title:e,description:t,onClose:n,actions:r,children:i,wide:a=!1})=>{let s=(0,o.useRef)(null);return tu(s,!0,n),(0,V.jsx)(`div`,{className:`fixed inset-0 z-[90] flex items-center justify-center bg-backdrop/30 p-4`,onMouseDown:e=>e.target===e.currentTarget&&n(),children:(0,V.jsxs)(`div`,{ref:s,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":e,className:B(`outline-none max-h-[90vh] w-full overflow-y-auto rounded-lg border bg-background p-4 shadow-pop sm:p-5`,a?`max-w-3xl`:`max-w-md`),children:[(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:e}),t&&(0,V.jsx)(`p`,{className:`mt-1.5 text-muted-foreground`,children:t}),i&&(0,V.jsx)(`div`,{className:`mt-4`,children:i}),(0,V.jsx)(`div`,{className:`mt-5 flex flex-col-reverse gap-2 sm:flex-row sm:justify-end [&>*]:min-h-11 sm:[&>*]:min-h-0`,children:r})]})})},Tf=({title:e,status:t,description:n,children:r})=>(0,V.jsxs)(`section`,{"aria-label":e,className:`rounded-lg border bg-background p-4 sm:p-5`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:e}),t]}),(0,V.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:n}),r&&(0,V.jsx)(`div`,{className:`mt-4`,children:r})]}),Ef=({message:e})=>e?(0,V.jsx)(`p`,{role:`alert`,className:`mb-3 text-xs font-medium text-danger-text`,children:e}):null,Df={allowed:`Sign in with Face ID, Touch ID, Windows Hello, your phone or a security key instead of a password.`,required:`This app requires a passkey for every account. Sign in with Face ID, Touch ID, Windows Hello, your phone or a security key.`,forbidden:`Your admin turned passkeys off for this app, so they cannot be used to sign in.`},Of=({rule:e,passkeys:t,onAdd:n,onRename:r,onRemove:i})=>{let[a,s]=(0,o.useState)(!1),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(``),m=e===`required`&&t.length<=1,h=async e=>{s(!0),l(void 0);try{await e(),d(void 0)}catch(e){if(!(e instanceof pc))throw e;l(xd(e))}s(!1)};return(0,V.jsxs)(Tf,{title:`Passkeys`,status:e===`required`&&(0,V.jsx)(Au,{tone:`blue`,children:`Required`}),description:Df[e],children:[(0,V.jsx)(Ef,{message:u?void 0:c}),t.length>0&&(0,V.jsx)(`ul`,{className:`mb-3 divide-y rounded-md border`,children:t.map(e=>(0,V.jsxs)(`li`,{className:`flex flex-wrap items-center gap-3 px-3 py-2.5`,children:[(0,V.jsx)(_t,{className:`size-4 shrink-0 text-muted-foreground`}),(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.name??`Passkey`}),(0,V.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[e.createdAt?`Added ${sf(Date.parse(e.createdAt))}`:`Added earlier`,` · `,e.backedUp?`Synced across your devices`:`On one device`]})]}),(0,V.jsxs)(`span`,{className:`flex gap-1`,children:[(0,V.jsx)(U,{size:`sm`,variant:`ghost`,onClick:()=>{p(e.name??``),d({kind:`rename`,passkey:e})},children:`Rename`}),(0,V.jsx)(U,{size:`sm`,variant:`ghost`,disabled:m,title:m?`Passkeys are required: add another one before removing this one.`:void 0,onClick:()=>d({kind:`remove`,passkey:e}),children:`Remove`})]})]},e.id))}),e!==`forbidden`&&(0,V.jsxs)(U,{loading:a&&!u,onClick:()=>void h(n),children:[(0,V.jsx)(an,{className:`size-3.5`}),`Add a passkey`]}),u?.kind===`rename`&&(0,V.jsxs)(wf,{title:`Rename passkey`,description:`A name that tells you where this passkey lives, such as the device or password manager.`,onClose:()=>d(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>d(void 0),children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,loading:a,disabled:!f.trim(),onClick:()=>void h(()=>r(u.passkey.id,f.trim())),children:`Save`})]}),children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Name`,(0,V.jsx)(sd,{autoFocus:!0,value:f,maxLength:60,onChange:e=>p(e.target.value)})]}),(0,V.jsx)(Ef,{message:c})]}),u?.kind===`remove`&&(0,V.jsx)(wf,{title:`Remove passkey?`,description:`${u.passkey.name??`This passkey`} will no longer sign you in here. It stays on the device until you delete it there.`,onClose:()=>d(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>d(void 0),children:`Cancel`}),(0,V.jsx)(U,{variant:`danger`,loading:a,onClick:()=>void h(()=>i(u.passkey.id)),children:`Remove`})]}),children:c&&(0,V.jsx)(Ef,{message:c})})]})},kf=({providers:e,linked:t,onConnect:n,error:r})=>{let[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(r),l=async e=>{a(e),c(void 0);try{await n(e)}catch(e){if(!(e instanceof pc))throw e;c(xd(e)),a(void 0)}};return(0,V.jsxs)(Tf,{title:`Connected accounts`,description:`Sign in with these instead of your password. Connecting one asks you to sign in there; its address may differ from yours here.`,children:[(0,V.jsx)(Ef,{message:s}),(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`flex flex-wrap items-center gap-3 px-3 py-2.5`,children:[(0,V.jsx)(Ot,{className:`size-4 shrink-0 text-muted-foreground`}),(0,V.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-medium`,children:e.name}),t.includes(e.id)?(0,V.jsx)(Au,{tone:`green`,children:`Connected`}):(0,V.jsxs)(U,{size:`sm`,loading:i===e.id,disabled:i!==void 0,onClick:()=>void l(e.id),children:[`Connect `,e.name]})]},e.id))})]})},Af=(e,t,n=`text/plain`)=>{let r=URL.createObjectURL(new Blob([e],{type:n}));Object.assign(document.createElement(`a`),{href:r,download:t}).click(),URL.revokeObjectURL(r)},jf=({codes:e})=>{let[t,n]=(0,o.useState)(!1),r=`${e.join(`
|
|
7
|
+
`)}\n`;return(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,V.jsx)(`ul`,{"aria-label":`Backup codes`,className:`grid grid-cols-2 gap-x-4 gap-y-1 rounded-md border bg-surface p-3 font-mono`,children:e.map(e=>(0,V.jsx)(`li`,{children:e},e))}),(0,V.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[(0,V.jsxs)(U,{size:`sm`,onClick:()=>{navigator.clipboard.writeText(r).then(()=>{n(!0),setTimeout(()=>n(!1),2e3)})},children:[t?(0,V.jsx)(ge,{className:`size-3.5 text-success`}):(0,V.jsx)(Re,{className:`size-3.5`}),t?`Copied`:`Copy`]}),(0,V.jsxs)(U,{size:`sm`,onClick:()=>Af(r,`backup-codes.txt`),children:[(0,V.jsx)(We,{className:`size-3.5`}),`Download`]})]})]})},Mf=({title:e,description:t,confirmLabel:n,danger:r,needsPassword:i,onConfirm:a,onClose:s})=>{let[c,l]=(0,o.useState)(``),[u,d]=(0,o.useState)(!1),[f,p]=(0,o.useState)(),m=async()=>{d(!0),p(void 0);try{await a(i?c:void 0)}catch(e){if(!(e instanceof pc))throw e;p(xd(e)),d(!1)}};return(0,V.jsxs)(wf,{title:e,description:t,onClose:s,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:s,children:`Cancel`}),(0,V.jsx)(U,{variant:r?`danger`:`primary`,loading:u,disabled:i&&!c,onClick:()=>void m(),children:n})]}),children:[i&&(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your password`,(0,V.jsx)(sd,{type:`password`,autoComplete:`current-password`,autoFocus:!0,value:c,invalid:!!f,onChange:e=>l(e.target.value),onKeyDown:e=>e.key===`Enter`&&c&&void m()})]}),f&&(0,V.jsx)(`p`,{role:`alert`,className:`mt-2 text-xs font-medium text-danger-text`,children:f})]})},Nf=(e,t)=>e.replace(/\D/g,``).slice(0,t),Pf=(e,t,n)=>{let r=Nf(t??``,n);return r.length===n?r:Nf(e,n)},Ff=(e,t,n,r)=>{let i=t.replace(/\D/g,``);return i.length>=r?i.slice(0,r):Nf(e.slice(0,n)+i+e.slice(n+i.length),r)},If=({value:e,onChange:t,onComplete:n,length:r=6,invalid:i,disabled:a,className:s,ref:c,onFocus:l,onBlur:u,onSelect:d,onKeyDown:f,onClick:p,onPaste:m,...h})=>{let g=(0,o.useRef)(null),[_,v]=(0,o.useState)(!1),[y,b]=(0,o.useState)(e.length),x=e.slice(0,r),S=Math.min(y,r-1),C=e=>{g.current=e,typeof c==`function`?c(e):c&&(c.current=e)},w=e=>{e!==x&&(t(e),e.length===r&&n?.(e))},T=e=>{let t=g.current;if(!t)return;let n=Math.max(0,Math.min(e,x.length));t.setSelectionRange(n,n<x.length?n+1:n),b(n)},E=e=>{if(f?.(e),e.defaultPrevented||e.shiftKey||e.altKey||e.metaKey||e.ctrlKey)return;let t=e.currentTarget.selectionStart??x.length,n={ArrowLeft:t-1,ArrowRight:t+1,Home:0,End:x.length}[e.key];n!==void 0&&(e.preventDefault(),T(n))},D=e=>{p?.(e);let t=e.currentTarget.getBoundingClientRect();e.clientX<=t.left||e.clientX>=t.right||T(Math.floor((e.clientX-t.left)/t.width*r))};return(0,V.jsxs)(`div`,{className:B(`relative`,a&&`opacity-50`,s),children:[(0,V.jsx)(`div`,{"aria-hidden":!0,className:`flex justify-center gap-2`,children:Array.from({length:r},(e,t)=>{let n=_&&t===S;return(0,V.jsx)(`div`,{"data-slot":t,"data-digit":x[t],className:B(`flex h-12 min-w-0 max-w-12 flex-1 items-center justify-center rounded-md border bg-background font-mono text-xl font-semibold text-foreground shadow-sm transition-colors before:content-[attr(data-digit)]`,i?`border-danger`:n?`border-primary`:`border-border-strong`,n&&(i?`ring-2 ring-danger/20`:`ring-2 ring-primary/20`)),children:x[t]===void 0&&(n?(0,V.jsx)(`span`,{className:`h-6 w-px animate-pulse bg-foreground`}):(0,V.jsx)(`span`,{className:`size-1.5 rounded-full bg-border-strong`}))},t)})}),(0,V.jsx)(`input`,{ref:C,type:`text`,inputMode:`numeric`,autoComplete:`one-time-code`,pattern:`[0-9]{${r}}`,spellCheck:!1,autoCorrect:`off`,autoCapitalize:`off`,"aria-invalid":i||void 0,disabled:a,value:x,className:`absolute inset-0 size-full cursor-text bg-transparent text-transparent caret-transparent outline-none selection:bg-transparent disabled:cursor-not-allowed`,...h,onChange:e=>{let{data:t,dataTransfer:n}=e.nativeEvent;w(Pf(e.target.value,t??n?.getData(`text/plain`),r))},onPaste:e=>{if(m?.(e),e.defaultPrevented)return;e.preventDefault();let t=e.currentTarget,n=Ff(x,e.clipboardData.getData(`text`),t.selectionStart??x.length,r);w(n),b(n.length)},onSelect:e=>{d?.(e);let t=e.currentTarget,n=t.selectionStart??x.length;n===t.selectionEnd&&n<t.value.length&&t.setSelectionRange(n,n+1),b(n)},onKeyDown:E,onClick:D,onFocus:e=>{v(!0),l?.(e)},onBlur:e=>{v(!1),u?.(e)}})]})},Lf=(e=>(e[e.Border=-1]=`Border`,e[e.Data=0]=`Data`,e[e.Function=1]=`Function`,e[e.Position=2]=`Position`,e[e.Timing=3]=`Timing`,e[e.Alignment=4]=`Alignment`,e))(Lf||{}),Rf=[0,1],zf=[1,0],Bf=[2,3],Vf=[3,2],Hf={L:Rf,M:zf,Q:Bf,H:Vf},Uf=/^\d*$/,Wf=/^[A-Z0-9 $%*+./:-]*$/,Gf=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`,Kf=1,qf=40,Jf=3,Yf=3,Xf=40,Zf=10,Qf=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],$f=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],ep=class{constructor(e,t,n,r){if(this.version=e,this.ecc=t,e<Kf||e>qf)throw RangeError(`Version value out of range`);if(r<-1||r>7)throw RangeError(`Mask value out of range`);this.size=e*4+17;let i=Array.from({length:this.size}).fill(!1);for(let e=0;e<this.size;e++)this.modules.push(i.slice()),this.types.push(i.map(()=>0));this.drawFunctionPatterns();let a=this.addEccAndInterleave(n);if(this.drawCodewords(a),r===-1){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);let n=this.getPenaltyScore();n<e&&(r=t,e=n),this.applyMask(t)}}this.mask=r,this.applyMask(r),this.drawFormatBits(r)}size;mask;modules=[];types=[];getModule(e,t){return e>=0&&e<this.size&&t>=0&&t<this.size&&this.modules[t][e]}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0,Lf.Timing),this.setFunctionModule(e,6,e%2==0,Lf.Timing);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let n=0;n<t;n++)for(let r=0;r<t;r++)n===0&&r===0||n===0&&r===t-1||n===t-1&&r===0||this.drawAlignmentPattern(e[n],e[r]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.ecc[1]<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let r=(t<<10|n)^21522;for(let e=0;e<=5;e++)this.setFunctionModule(8,e,np(r,e));this.setFunctionModule(8,7,np(r,6)),this.setFunctionModule(8,8,np(r,7)),this.setFunctionModule(7,8,np(r,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,np(r,e));for(let e=0;e<8;e++)this.setFunctionModule(this.size-1-e,8,np(r,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,np(r,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;for(let e=0;e<18;e++){let n=np(t,e),r=this.size-11+e%3,i=Math.floor(e/3);this.setFunctionModule(r,i,n),this.setFunctionModule(i,r,n)}}drawFinderPattern(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let i=Math.max(Math.abs(r),Math.abs(n)),a=e+r,o=t+n;a>=0&&a<this.size&&o>=0&&o<this.size&&this.setFunctionModule(a,o,i!==2&&i!==4,Lf.Position)}}drawAlignmentPattern(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.setFunctionModule(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!==1,Lf.Alignment)}setFunctionModule(e,t,n,r=Lf.Function){this.modules[t][e]=n,this.types[t][e]=r}addEccAndInterleave(e){let t=this.version,n=this.ecc;if(e.length!==_p(t,n))throw RangeError(`Invalid argument`);let r=$f[n[0]][t],i=Qf[n[0]][t],a=Math.floor(gp(t)/8),o=r-a%r,s=Math.floor(a/r),c=[],l=vp(i);for(let t=0,n=0;t<r;t++){let r=e.slice(n,n+s-i+(t<o?0:1));n+=r.length;let a=yp(r,l);t<o&&r.push(0),c.push(r.concat(a))}let u=[];for(let e=0;e<c[0].length;e++)c.forEach((t,n)=>{(e!==s-i||n>=o)&&u.push(t[e])});return u}drawCodewords(e){if(e.length!==Math.floor(gp(this.version)/8))throw RangeError(`Invalid argument`);let t=0;for(let n=this.size-1;n>=1;n-=2){n===6&&(n=5);for(let r=0;r<this.size;r++)for(let i=0;i<2;i++){let a=n-i,o=n+1&2?r:this.size-1-r;!this.types[o][a]&&t<e.length*8&&(this.modules[o][a]=np(e[t>>>3],7-(t&7)),t++)}}}applyMask(e){if(e<0||e>7)throw RangeError(`Mask value out of range`);for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;case 7:r=((n+t)%2+n*t%3)%2==0;break;default:throw Error(`Unreachable`)}!this.types[t][n]&&r&&(this.modules[t][n]=!this.modules[t][n])}}getPenaltyScore(){let e=0;for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[t][a]===n?(r++,r===5?e+=Jf:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*Xf),n=this.modules[t][a],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*Xf}for(let t=0;t<this.size;t++){let n=!1,r=0,i=[0,0,0,0,0,0,0];for(let a=0;a<this.size;a++)this.modules[a][t]===n?(r++,r===5?e+=Jf:r>5&&e++):(this.finderPenaltyAddHistory(r,i),n||(e+=this.finderPenaltyCountPatterns(i)*Xf),n=this.modules[a][t],r=1);e+=this.finderPenaltyTerminateAndCount(n,r,i)*Xf}for(let t=0;t<this.size-1;t++)for(let n=0;n<this.size-1;n++){let r=this.modules[t][n];r===this.modules[t][n+1]&&r===this.modules[t+1][n]&&r===this.modules[t+1][n+1]&&(e+=Yf)}let t=0;for(let e of this.modules)t=e.reduce((e,t)=>e+ +!!t,t);let n=this.size*this.size,r=Math.ceil(Math.abs(t*20-n*10)/n)-1;return e+=r*Zf,e}getAlignmentPatternPositions(){if(this.version===1)return[];{let e=Math.floor(this.version/7)+2,t=this.version===32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}}finderPenaltyCountPatterns(e){let t=e[1],n=t>0&&e[2]===t&&e[3]===t*3&&e[4]===t&&e[5]===t;return(n&&e[0]>=t*4&&e[6]>=t?1:0)+(n&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,n){return e&&(this.finderPenaltyAddHistory(t,n),t=0),t+=this.size,this.finderPenaltyAddHistory(t,n),this.finderPenaltyCountPatterns(n)}finderPenaltyAddHistory(e,t){t[0]===0&&(e+=this.size),t.pop(),t.unshift(e)}};function tp(e,t,n){if(t<0||t>31||e>>>t)throw RangeError(`Value out of range`);for(let r=t-1;r>=0;r--)n.push(e>>>r&1)}function np(e,t){return!!(e>>>t&1)}var rp=class{constructor(e,t,n){if(this.mode=e,this.numChars=t,this.bitData=n,t<0)throw RangeError(`Invalid argument`);this.bitData=n.slice()}getData(){return this.bitData.slice()}},ip=[1,10,12,14],ap=[2,9,11,13],op=[4,8,16,16];function sp(e,t){return e[Math.floor((t+7)/17)+1]}function cp(e){let t=[];for(let n of e)tp(n,8,t);return new rp(op,e.length,t)}function lp(e){if(!fp(e))throw RangeError(`String contains non-numeric characters`);let t=[];for(let n=0;n<e.length;){let r=Math.min(e.length-n,3);tp(Number.parseInt(e.substring(n,n+r),10),r*3+1,t),n+=r}return new rp(ip,e.length,t)}function up(e){if(!pp(e))throw RangeError(`String contains unencodable characters in alphanumeric mode`);let t=[],n=0;for(;n+2<=e.length;n+=2){let r=Gf.indexOf(e.charAt(n))*45;r+=Gf.indexOf(e.charAt(n+1)),tp(r,11,t)}return n<e.length&&tp(Gf.indexOf(e.charAt(n)),6,t),new rp(ap,e.length,t)}function dp(e){return e===``?[]:fp(e)?[lp(e)]:pp(e)?[up(e)]:[cp(hp(e))]}function fp(e){return Uf.test(e)}function pp(e){return Wf.test(e)}function mp(e,t){let n=0;for(let r of e){let e=sp(r.mode,t);if(r.numChars>=1<<e)return 1/0;n+=4+e+r.bitData.length}return n}function hp(e){e=encodeURI(e);let t=[];for(let n=0;n<e.length;n++)e.charAt(n)===`%`?(t.push(Number.parseInt(e.substring(n+1,n+3),16)),n+=2):t.push(e.charCodeAt(n));return t}function gp(e){if(e<Kf||e>qf)throw RangeError(`Version number out of range`);let t=(16*e+128)*e+64;if(e>=2){let n=Math.floor(e/7)+2;t-=(25*n-10)*n-55,e>=7&&(t-=36)}return t}function _p(e,t){return Math.floor(gp(e)/8)-Qf[t[0]][e]*$f[t[0]][e]}function vp(e){if(e<1||e>255)throw RangeError(`Degree out of range`);let t=[];for(let n=0;n<e-1;n++)t.push(0);t.push(1);let n=1;for(let r=0;r<e;r++){for(let e=0;e<t.length;e++)t[e]=bp(t[e],n),e+1<t.length&&(t[e]^=t[e+1]);n=bp(n,2)}return t}function yp(e,t){let n=t.map(e=>0);for(let r of e){let e=r^n.shift();n.push(0),t.forEach((t,r)=>n[r]^=bp(t,e))}return n}function bp(e,t){if(e>>>8||t>>>8)throw RangeError(`Byte out of range`);let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return n}function xp(e,t,n=1,r=40,i=-1,a=!0){if(!(Kf<=n&&n<=r&&r<=qf)||i<-1||i>7)throw RangeError(`Invalid value`);let o,s;for(o=n;;o++){let n=_p(o,t)*8,i=mp(e,o);if(i<=n){s=i;break}if(o>=r)throw RangeError(`Data too long`)}for(let e of[zf,Bf,Vf])a&&s<=_p(o,e)*8&&(t=e);let c=[];for(let t of e){tp(t.mode[0],4,c),tp(t.numChars,sp(t.mode,o),c);for(let e of t.getData())c.push(e)}let l=_p(o,t)*8;tp(0,Math.min(4,l-c.length),c),tp(0,(8-c.length%8)%8,c);for(let e=236;c.length<l;e^=253)tp(e,8,c);let u=Array.from({length:Math.ceil(c.length/8)},()=>0);return c.forEach((e,t)=>u[t>>>3]|=e<<7-(t&7)),new ep(o,t,u,i)}function Sp(e,t){let{ecc:n=`L`,boostEcc:r=!1,minVersion:i=1,maxVersion:a=40,maskPattern:o=-1,border:s=1}=t||{},c=typeof e==`string`?dp(e):Array.isArray(e)?[cp(e)]:void 0;if(!c)throw Error(`uqr only supports encoding string and binary data, but got: ${typeof e}`);let l=xp(c,Hf[n],i,a,o,r),u=Cp({version:l.version,maskPattern:l.mask,size:l.size,data:l.modules,types:l.types},s);return t?.invert&&(u.data=u.data.map(e=>e.map(e=>!e))),t?.onEncoded?.(u),u}function Cp(e,t=1){if(!t)return e;let{size:n}=e,r=n+t*2;e.size=r,e.data.forEach(e=>{for(let n=0;n<t;n++)e.unshift(!1),e.push(!1)});for(let n=0;n<t;n++)e.data.unshift(Array.from({length:r},e=>!1)),e.data.push(Array.from({length:r},e=>!1));let i=Lf.Border;e.types.forEach(e=>{for(let n=0;n<t;n++)e.unshift(i),e.push(i)});for(let n=0;n<t;n++)e.types.unshift(Array.from({length:r},e=>i)),e.types.push(Array.from({length:r},e=>i));return e}var wp=({uri:e,className:t})=>{let{size:n,path:r}=(0,o.useMemo)(()=>{let t=Sp(e,{ecc:`M`,border:2}),n=t.data.flatMap((e,t)=>e.flatMap((e,n)=>e?[`M${n} ${t}h1v1h-1z`]:[]));return{size:t.size,path:n.join(``)}},[e]);return(0,V.jsxs)(`svg`,{viewBox:`0 0 ${n} ${n}`,role:`img`,"aria-label":`QR code for your authenticator app`,shapeRendering:`crispEdges`,className:t,children:[(0,V.jsx)(`rect`,{width:n,height:n,fill:`#fff`}),(0,V.jsx)(`path`,{d:r,fill:`#000`})]})},Tp=e=>(new URL(e).searchParams.get(`secret`)??``).replace(/(.{4})(?=.)/g,`$1 `),Ep=[{value:`app`,label:`Authenticator app`,description:`A code from an app such as Google Authenticator, Microsoft Authenticator or 1Password. Comes with backup codes.`},{value:`email`,label:`Emailed code`,description:`A code mailed to your address each time you sign in with a password or an emailed sign-in code.`}],Dp=({offerEmailedCodes:e,needsPassword:t,onStartApp:n,onConfirmApp:r,onEmailedCodes:i,onDone:a,onCancel:s})=>{let[c,l]=(0,o.useState)({kind:`choose`}),[u,d]=(0,o.useState)(`app`),[f,p]=(0,o.useState)(``),[m,h]=(0,o.useState)(``),[g,_]=(0,o.useState)(!1),[v,y]=(0,o.useState)(),b=e?Ep:Ep.filter(e=>e.value===`app`),x=async e=>{_(!0),y(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;y(xd(e))}_(!1)},S=()=>x(async()=>{let e=t?f:void 0;if(u===`email`)return await i(e),a();l({kind:`scan`,setup:await n(e)})}),C=(e,t=m)=>x(async()=>{await r(t),l({kind:`backup-codes`,codes:e.backupCodes})}),w=v&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:v});return c.kind===`backup-codes`?(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Two-factor authentication is on. Keep these backup codes somewhere safe: each one signs you in once if you lose your phone. They are not shown again.`}),(0,V.jsx)(jf,{codes:c.codes}),(0,V.jsx)(U,{variant:`primary`,onClick:a,className:`min-h-10`,children:`I saved my backup codes`})]}):c.kind===`scan`?(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),C(c.setup)},children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Scan this code with your authenticator app, then enter the 6-digit code it shows.`}),(0,V.jsxs)(`div`,{className:`flex flex-col items-center gap-2`,children:[(0,V.jsx)(wp,{uri:c.setup.totpURI,className:`size-44 rounded-md border`}),(0,V.jsxs)(`p`,{className:`text-center text-xs text-muted-foreground`,children:[`Can't scan it? Enter this key in the app:`,(0,V.jsx)(`span`,{className:`mt-1 block break-all font-mono text-body text-foreground`,children:Tp(c.setup.totpURI)})]})]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Code from the app`,(0,V.jsx)(If,{name:`code`,required:!0,autoFocus:!0,value:m,invalid:!!v,onChange:h,onComplete:e=>!g&&void C(c.setup,e)})]}),w,(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:g,className:`min-h-10`,children:`Turn on`}),s&&(0,V.jsx)(U,{variant:`ghost`,onClick:s,className:`min-h-10`,children:`Cancel`})]}):(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),S()},children:[(0,V.jsx)(`div`,{role:`radiogroup`,"aria-label":`Second step`,className:`flex flex-col gap-2`,children:b.map(e=>(0,V.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":u===e.value,onClick:()=>d(e.value),className:B(`rounded-md border p-3 text-left transition-colors`,u===e.value?`border-primary bg-primary-soft`:`border-border-strong hover:bg-muted`),children:[(0,V.jsx)(`span`,{className:`block font-medium`,children:e.label}),(0,V.jsx)(`span`,{className:`mt-0.5 block text-xs text-muted-foreground`,children:e.description})]},e.value))}),t&&(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your password`,(0,V.jsx)(sd,{type:`password`,name:`password`,autoComplete:`current-password`,required:!0,value:f,invalid:!!v,onChange:e=>p(e.target.value),className:`min-h-6`})]}),w,(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:g,className:`min-h-10`,children:`Continue`}),s&&(0,V.jsx)(U,{variant:`ghost`,onClick:s,className:`min-h-10`,children:`Cancel`})]})},Op={allowed:`Ask for a second step after your password or an emailed sign-in code: a code from an authenticator app, or one emailed to you. A passkey needs no second step.`,required:`This app requires two-factor authentication for every account. Turn it on to keep using the app.`,forbidden:`Your admin turned two-factor authentication off for this app.`},kp=e=>{let{rule:t,enabled:n,authenticatorApp:r,mail:i,needsPassword:a,onTurnOff:s,onNewBackupCodes:c,onChanged:l}=e,[u,d]=(0,o.useState)(),f=()=>d(void 0),p=n?(0,V.jsx)(Au,{tone:`green`,children:`On`}):t===`required`?(0,V.jsx)(Au,{tone:`amber`,children:`Required`}):(0,V.jsx)(Au,{children:`Off`}),m=n?r?`Signing in with a password or an emailed sign-in code also asks for a code from your authenticator app${i?`, or one emailed to you`:``}. Backup codes work when you do not have the app.`:`Signing in with a password or an emailed sign-in code also asks for a code emailed to you.`:Op[t];return u?.kind===`setup`?(0,V.jsx)(Tf,{title:`Two-factor authentication`,status:p,description:m,children:(0,V.jsx)(`div`,{className:`max-w-sm`,children:(0,V.jsx)(Dp,{offerEmailedCodes:i&&!u.appOnly,needsPassword:a,onStartApp:e.onStartApp,onConfirmApp:e.onConfirmApp,onEmailedCodes:e.onEmailedCodes,onCancel:f,onDone:()=>{f(),l()}})})}):(0,V.jsxs)(Tf,{title:`Two-factor authentication`,status:p,description:m,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap gap-2`,children:[!n&&t!==`forbidden`&&(0,V.jsx)(U,{variant:`primary`,onClick:()=>d({kind:`setup`,appOnly:!1}),children:`Turn on`}),n&&!r&&t!==`forbidden`&&(0,V.jsx)(U,{onClick:()=>d({kind:`setup`,appOnly:!0}),children:`Add an authenticator app`}),n&&r&&(0,V.jsx)(U,{onClick:()=>d({kind:`new-codes`}),children:`New backup codes`}),n&&(0,V.jsx)(U,{variant:`danger`,disabled:t===`required`,title:t===`required`?`This app requires two-factor authentication.`:void 0,onClick:()=>d({kind:`turn-off`}),children:`Turn off`})]}),u?.kind===`turn-off`&&(0,V.jsx)(Mf,{title:`Turn off two-factor authentication?`,description:`Signing in then needs only your password or an emailed code. Your backup codes stop working.`,confirmLabel:`Turn off`,danger:!0,needsPassword:a,onClose:f,onConfirm:async e=>{await s(e),f(),l()}}),u?.kind===`new-codes`&&(0,V.jsx)(Mf,{title:`Make new backup codes?`,description:`Your current backup codes stop working, and you get ten new ones.`,confirmLabel:`Make new codes`,needsPassword:a,onClose:f,onConfirm:async e=>d({kind:`codes`,codes:await c(e)})}),u?.kind===`codes`&&(0,V.jsx)(wf,{title:`Your new backup codes`,description:`Keep them somewhere safe: each one signs you in once if you lose your phone. They are not shown again.`,onClose:f,actions:(0,V.jsx)(U,{variant:`primary`,onClick:f,children:`I saved my backup codes`}),children:(0,V.jsx)(jf,{codes:u.codes})})]})},Ap=()=>{let e=Ad(window.location.href);return e&&window.history.replaceState(window.history.state,``,jd(window.location.href)),e},jp=({email:e})=>{let{session:t,signInProviders:n,socialProviders:r,linkProvider:i}=H(),a=n.filter(e=>r.includes(e.id)),{account:s}=t,[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(),[f]=(0,o.useState)(Ap),p=(0,o.useCallback)(()=>{Promise.all([s.signInMethods(),s.passkeys(),s.linkedProviders()]).then(([e,t,n])=>l({methods:e,passkeys:t,linked:n}),e=>d(e instanceof pc?xd(e):`Could not read your sign-in methods`))},[s]);(0,o.useEffect)(p,[p]);let m=e=>e.then(e=>(p(),e));return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:`Sign-in & security`,subtitle:e}),c?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(Of,{rule:c.methods.policy.passkey,passkeys:c.passkeys,onAdd:()=>m(s.addPasskey()),onRename:(e,t)=>m(s.renamePasskey(e,t)),onRemove:e=>m(s.removePasskey(e))}),(0,V.jsx)(kp,{rule:c.methods.policy.twoFactor,enabled:c.methods.account.twoFactor,authenticatorApp:c.methods.account.authenticatorApp,mail:c.methods.mail,needsPassword:c.methods.account.password,onStartApp:e=>s.startAuthenticatorApp(e),onConfirmApp:e=>s.confirmAuthenticatorApp(e),onEmailedCodes:e=>s.turnOnEmailedCodes(e),onTurnOff:e=>s.turnOffTwoFactor(e),onNewBackupCodes:e=>s.newBackupCodes(e),onChanged:p}),a.length>0&&(0,V.jsx)(kf,{providers:a,linked:c.linked,onConnect:i,error:f&&Ed(f,a.length===1?a[0].name:`the provider`)})]}):u?(0,V.jsx)(`p`,{role:`alert`,className:`text-danger-text`,children:u}):(0,V.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})]})},Mp=[{value:`allowed`,label:`On`},{value:`forbidden`,label:`Off`}],Np=[{value:`allowed`,label:`Optional`},{value:`required`,label:`Required`},{value:`forbidden`,label:`Off`}],Pp=[{method:`password`,label:`Password`,description:`Sign in with the email address and a password.`,rules:Mp},{method:`emailCode`,label:`Emailed sign-in code`,description:`Sign in with a one-time code mailed to the account's address.`,rules:Mp},{method:`passkey`,label:`Passkeys`,description:`Sign in with Face ID, Touch ID, Windows Hello, a phone or a security key. Required: everyone adds one after signing in.`,rules:Np},{method:`twoFactor`,label:`Two-factor authentication`,description:`A code from an authenticator app, or an emailed one, after a password or an emailed sign-in code. Required: everyone turns it on after signing in.`,rules:Np},{method:`staffAccess`,label:`Staff sign-in as a person`,description:`The team that runs this app signs in as someone to help them, with a reason, for a short session. Each time is in the log below; with "Email the person" they are told too.`,rules:[{value:`allowed`,label:`On`},{value:`notify`,label:`Email the person`},{value:`forbidden`,label:`Off`}]},{method:`platformSignIn`,label:`Sign-in through the platform`,description:`The sign-in provider the platform that runs this app adds, for people who have an account here already. It never creates accounts.`,rules:Mp}],Fp=(e,t)=>{let n=Pp.find(t=>t.method===e)?.rules.find(e=>e.value===t)?.label;if(n===void 0)throw Error(`No label for the ${t} rule of ${e}`);return n},Ip=({row:e,value:t,onChange:n})=>(0,V.jsx)(`span`,{role:`radiogroup`,"aria-label":e.label,className:`inline-flex h-8 shrink-0 rounded-md bg-muted p-0.5`,children:e.rules.map(e=>(0,V.jsx)(`button`,{type:`button`,role:`radio`,"aria-checked":e.value===t,onClick:()=>n(e.value),className:B(`rounded px-3 text-xs font-medium transition-colors`,e.value===t?`bg-background text-foreground shadow-sm`:`text-muted-foreground hover:text-foreground`),children:e.label},e.value))}),Lp=({method:e},t,{mail:n,effective:r,policy:i})=>{if(e===`emailCode`&&!n)return`Needs mail settings (PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM): off until they are set.`;if(e===`password`&&!n&&t.password===`forbidden`)return`Without mail settings, password sign-in stays on so nobody is locked out.`;if(e===`staffAccess`&&!n&&t.staffAccess===`notify`)return`Needs mail settings (PROTOBASE_SMTP_URL and PROTOBASE_MAIL_FROM): staff cannot sign in until they are set.`;if(e===`platformSignIn`&&t.platformSignIn===`allowed`&&(t.passkey===`required`||t.twoFactor===`required`))return`Off while passkeys or two-factor authentication are required: it skips the second step.`;if(t[e]===i[e]&&r[e]!==i[e])return`Applies as ${Fp(e,r[e])} for now.`},Rp=({operator:e,platformSignIn:t})=>Pp.flatMap(n=>n.method===`staffAccess`&&!e?[]:n.method===`platformSignIn`?t?[{...n,label:`Sign in with ${t} through the platform`}]:[]:[n]),zp=({state:e,onSave:t,busy:n,error:r,notice:i})=>{let[a,s]=(0,o.useState)(e.policy),c=Rp(e),l=c.some(({method:t})=>a[t]!==e.policy[t]);return(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t(a)},children:[(0,V.jsx)(`ul`,{className:`divide-y rounded-lg border bg-background`,children:c.map(t=>{let n=Lp(t,a,e);return(0,V.jsxs)(`li`,{className:`flex flex-col gap-3 p-4 sm:flex-row sm:items-start sm:justify-between`,children:[(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsx)(`h2`,{className:`font-semibold`,children:t.label}),(0,V.jsx)(`p`,{className:`mt-0.5 text-muted-foreground`,children:t.description}),n&&(0,V.jsx)(`p`,{className:`mt-1.5 text-xs font-medium text-warning-text`,children:n})]}),(0,V.jsx)(Ip,{row:t,value:a[t.method],onChange:e=>s({...a,[t.method]:e})})]},t.method)})}),r&&(0,V.jsx)(`p`,{role:`alert`,className:`rounded-md bg-danger-soft px-3 py-2 text-xs font-medium text-danger-text`,children:r}),i&&!l&&(0,V.jsx)(`p`,{role:`status`,className:`rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:i}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-3`,children:[(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e.savedAt?`Last saved${e.savedBy?` by ${e.savedBy}`:``} on ${df(Date.parse(e.savedAt))}.`:`Never changed: everything is on, nothing is required.`}),(0,V.jsxs)(`div`,{className:`flex gap-2`,children:[l&&(0,V.jsx)(U,{onClick:()=>s(e.policy),children:`Reset`}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:n,disabled:!l,children:`Save`})]})]})]})},Bp=(e,t)=>e.endedAt?(0,V.jsxs)(Au,{tone:`neutral`,children:[`Stopped `,df(Date.parse(e.endedAt))]}):Date.parse(e.expiresAt)<=t?(0,V.jsxs)(Au,{tone:`neutral`,children:[`Ended `,df(Date.parse(e.expiresAt))]}):(0,V.jsxs)(Au,{tone:`amber`,children:[`Signed in until `,df(Date.parse(e.expiresAt))]}),Vp=({signIns:e,operator:t,error:n,now:r=Date.now()})=>(0,V.jsxs)(Tf,{title:`Staff sign-ins`,description:`Each time staff of ${t} signed in as someone here, newest first.`,children:[(0,V.jsx)(Ef,{message:n}),e&&e.length===0&&(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`No staff has signed in as anyone yet.`}),e&&e.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`flex flex-col gap-1.5 p-3`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[(0,V.jsx)(`span`,{className:`font-medium break-all`,children:e.staffName?`${e.staffName} (${e.staff})`:e.staff}),(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`as`}),(0,V.jsx)(`span`,{className:`font-medium break-all`,children:e.user})]}),(0,V.jsx)(`p`,{className:`break-words`,children:e.reason}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 text-xs text-muted-foreground`,children:[(0,V.jsx)(`span`,{children:df(Date.parse(e.startedAt))}),Bp(e,r)]})]},e.id))})]}),Hp=({operator:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)();return(0,o.useEffect)(()=>{t.staff.log().then(r,e=>a(e instanceof pc?xd(e):`Could not read the staff sign-ins`))},[t]),(0,V.jsx)(Vp,{operator:e,signIns:n,error:i})},Up=()=>{let{session:e}=H(),[t,n]=(0,o.useState)(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(),[c,l]=(0,o.useState)();(0,o.useEffect)(()=>{e.signInPolicy.read().then(n,e=>s(e instanceof pc?xd(e):`Could not read the sign-in policy`))},[e]);let u=async t=>{i(!0),s(void 0),l(void 0);try{n(await e.signInPolicy.save(t)),l(`Saved. It applies to every sign-in from now on.`)}catch(e){if(!(e instanceof pc))throw e;s(xd(e))}i(!1)};return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:`Sign-in policy`,subtitle:`How people sign in to this app. Signed-in people keep their session, and are asked for what is newly required within 15 minutes.`}),t?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(zp,{state:t,busy:r,error:a,notice:c,onSave:e=>void u(e)},t.savedAt??`default`),t.operator&&(0,V.jsx)(Hp,{operator:t.operator})]}):a?(0,V.jsx)(`p`,{role:`alert`,className:`text-danger-text`,children:a}):(0,V.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})]})},Wp=o.createContext(void 0),Gp=e=>{let t=o.useContext(Wp);if(e)return e;if(!t)throw Error(`No QueryClient set, use QueryClientProvider to set one`);return t},Kp=({client:e,children:t})=>(o.useEffect(()=>(e.mount(),()=>{e.unmount()}),[e]),(0,V.jsx)(Wp.Provider,{value:e,children:t})),qp={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),setInterval:(e,t)=>setInterval(e,t),clearInterval:e=>clearInterval(e)},Jp=new class{#e=qp;setTimeoutProvider(e){this.#e=e}setTimeout(e,t){return this.#e.setTimeout(e,t)}clearTimeout(e){this.#e.clearTimeout(e)}setInterval(e,t){return this.#e.setInterval(e,t)}clearInterval(e){this.#e.clearInterval(e)}};function Yp(e){setTimeout(e,0)}var Xp=typeof window>`u`||`Deno`in globalThis;function Zp(){}function Qp(e,t){return typeof e==`function`?e(t):e}function $p(e){return typeof e==`number`&&e>=0&&e!==1/0}function em(e,t){return Math.max(e+(t||0)-Date.now(),0)}function tm(e,t){return typeof e==`function`?e(t):e}function nm(e,t){let{type:n=`all`,exact:r,fetchStatus:i,predicate:a,queryKey:o,stale:s}=e;if(o){if(r){if(t.queryHash!==im(o,t.options))return!1}else if(!om(t.queryKey,o))return!1}if(n!==`all`){let e=t.isActive();if(n===`active`&&!e||n===`inactive`&&e)return!1}return!(typeof s==`boolean`&&t.isStale()!==s||i&&i!==t.state.fetchStatus||a&&!a(t))}function rm(e,t){let{exact:n,status:r,predicate:i,mutationKey:a}=e;if(a){if(!t.options.mutationKey)return!1;if(n){if(am(t.options.mutationKey)!==am(a))return!1}else if(!om(t.options.mutationKey,a))return!1}return!(r&&t.state.status!==r||i&&!i(t))}function im(e,t){return(t?.queryKeyHashFn||am)(e)}function am(e){return JSON.stringify(e,(e,t)=>dm(t)?Object.keys(t).sort().reduce((e,n)=>(e[n]=t[n],e),{}):t)}function om(e,t){if(e===t)return!0;if(typeof e!=typeof t)return!1;if(e&&t&&typeof e==`object`&&typeof t==`object`){if(Array.isArray(e)&&Array.isArray(t)){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(!om(e[n],t[n]))return!1;return!0}let n=Object.keys(t);for(let r of n)if(!om(e[r],t[r]))return!1;return!0}return!1}var sm=Object.prototype.hasOwnProperty;function cm(e,t,n=0){if(e===t)return e;if(n>500)return t;let r=um(e)&&um(t);if(!r&&!(dm(e)&&dm(t)))return t;let i=(r?e:Object.keys(e)).length,a=r?t:Object.keys(t),o=a.length,s=r?Array(o):{},c=0;for(let l=0;l<o;l++){let o=r?l:a[l],u=e[o],d=t[o];if(u===d){s[o]=u,(r?l<i:sm.call(e,o))&&c++;continue}if(u===null||d===null||typeof u!=`object`||typeof d!=`object`){s[o]=d;continue}let f=cm(u,d,n+1);s[o]=f,f===u&&c++}return i===o&&c===i?e:s}function lm(e,t){if(!t||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e)if(e[n]!==t[n])return!1;return!0}function um(e){return Array.isArray(e)&&e.length===Object.keys(e).length}function dm(e){if(!fm(e))return!1;let t=Object.getPrototypeOf(e),n=t?.constructor;if(n===void 0)return!0;if(typeof n!=`function`)return!1;let r=n.prototype;return!(!fm(r)||!r.hasOwnProperty(`isPrototypeOf`)||t!==Object.prototype)}function fm(e){return Object.prototype.toString.call(e)===`[object Object]`}function pm(e){return new Promise(t=>{Jp.setTimeout(t,e)})}function mm(e,t,n){return typeof n.structuralSharing==`function`?n.structuralSharing(e,t):n.structuralSharing===!1?t:cm(e,t)}function hm(e){return e}function gm(e,t,n=0){let r=[...e,t];return n&&r.length>n?r.slice(1):r}function _m(e,t,n=0){let r=[t,...e];return n&&r.length>n?r.slice(0,-1):r}var vm=Symbol();function ym(e,t){return!e.queryFn&&t?.initialPromise?()=>t.initialPromise:!e.queryFn||e.queryFn===vm?()=>Promise.reject(Error(`Missing queryFn: '${e.queryHash}'`)):e.queryFn}function bm(e,t){return typeof e==`function`?e(...t):!!e}function xm(e,t,n){let r=!1,i;return Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(i??=t(),r?i:(r=!0,i.aborted?n():i.addEventListener(`abort`,n,{once:!0}),i))}),e}var Sm=()=>Xp,Cm=()=>Sm(),wm=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(e){return this.listeners.add(e),this.onSubscribe(),()=>{this.listeners.delete(e),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}},Tm=new class extends wm{#e;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(e=>{typeof e==`boolean`?this.setFocused(e):this.onFocus()})}setFocused(e){this.#e!==e&&(this.#e=e,this.onFocus())}onFocus(){let e=this.isFocused();this.listeners.forEach(t=>{t(e)})}isFocused(){return typeof this.#e==`boolean`?this.#e:globalThis.document?.visibilityState!==`hidden`}},Em=Yp;function Dm(){let e=[],t=0,n=e=>{e()},r=e=>{e()},i=Em,a=r=>{t?e.push(r):i(()=>{n(r)})},o=()=>{let t=e;e=[],t.length&&i(()=>{r(()=>{t.forEach(e=>{n(e)})})})};return{batch:e=>{let n;t++;try{n=e()}finally{t--,t||o()}return n},batchCalls:e=>(...t)=>{a(()=>{e(...t)})},schedule:a,setNotifyFunction:e=>{n=e},setBatchNotifyFunction:e=>{r=e},setScheduler:e=>{i=e}}}var Om=Dm(),km=new class extends wm{#e=!0;#t;#n;constructor(){super(),this.#n=e=>{if(typeof window<`u`&&window.addEventListener){let t=()=>e(!0),n=()=>e(!1);return window.addEventListener(`online`,t,!1),window.addEventListener(`offline`,n,!1),()=>{window.removeEventListener(`online`,t),window.removeEventListener(`offline`,n)}}}}onSubscribe(){this.#t||this.setEventListener(this.#n)}onUnsubscribe(){this.hasListeners()||(this.#t?.(),this.#t=void 0)}setEventListener(e){this.#n=e,this.#t?.(),this.#t=e(this.setOnline.bind(this))}setOnline(e){this.#e!==e&&(this.#e=e,this.listeners.forEach(t=>{t(e)}))}isOnline(){return this.#e}};function Am(e){return Math.min(1e3*2**e,3e4)}function jm(e){return(e??`online`)!==`online`||km.isOnline()}var Mm=class extends Error{constructor(e){super(`CancelledError`),this.revert=e?.revert,this.silent=e?.silent}};function Nm(e){let t=!1,n=0,r,i=`pending`,a,o,s=new Promise((e,t)=>{a=e,o=t});s.catch(Zp);let c=()=>i!==`pending`,l=t=>{if(!c()){let n=new Mm(t);h(n),e.onCancel?.(n)}},u=()=>{t=!0},d=()=>{t=!1},f=()=>Tm.isFocused()&&(e.networkMode===`always`||km.isOnline())&&e.canRun(),p=()=>jm(e.networkMode)&&e.canRun(),m=e=>{c()||(r?.(),i=`resolved`,a(e))},h=e=>{c()||(r?.(),i=`rejected`,o(e))},g=()=>new Promise(t=>{r=e=>{(c()||f())&&t(e)},e.onPause?.()}).then(()=>{r=void 0,c()||e.onContinue?.()}),_=()=>{if(c())return;let r,i=n===0?e.initialPromise:void 0;try{r=i??e.fn()}catch(e){r=Promise.reject(e)}Promise.resolve(r).then(m).catch(r=>{if(c())return;let i=e.retry??(Cm()?0:3),a=e.retryDelay??Am,o=typeof a==`function`?a(n,r):a,s=i===!0||typeof i==`number`&&n<i||typeof i==`function`&&i(n,r);if(t||!s){h(r);return}n++,e.onFail?.(n,r),pm(o).then(()=>f()?void 0:g()).then(()=>{t?h(r):_()})})};return{promise:s,status:()=>i,cancel:l,continue:()=>(r?.(),s),cancelRetry:u,continueRetry:d,canStart:p,start:()=>(p()?_():g().then(_),s)}}var Pm=class{#e;destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),$p(this.gcTime)&&(this.#e=Jp.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(e){this.gcTime=Math.max(this.gcTime||0,e??(Cm()?1/0:3e5))}clearGcTimeout(){this.#e!==void 0&&(Jp.clearTimeout(this.#e),this.#e=void 0)}};function Fm(e){return{onFetch:(t,n)=>{let r=t.options,i=t.fetchOptions?.meta?.fetchMore?.direction,a=t.state.data?.pages||[],o=t.state.data?.pageParams||[],s={pages:[],pageParams:[]},c=0,l=async()=>{let n=!1,l=e=>{xm(e,()=>t.signal,()=>n=!0)},u=ym(t.options,t.fetchOptions),d=async(e,r,i)=>{if(n)return Promise.reject(t.signal.reason);if(r==null&&e.pages.length)return Promise.resolve(e);let a=(()=>{let e={client:t.client,queryKey:t.queryKey,pageParam:r,direction:i?`backward`:`forward`,meta:t.options.meta};return l(e),e})(),o=await u(a),{maxPages:s}=t.options,c=i?_m:gm;return{pages:c(e.pages,o,s),pageParams:c(e.pageParams,r,s)}};if(i&&a.length){let e=i===`backward`,t=e?Lm:Im,n={pages:a,pageParams:o};s=await d(n,t(r,n),e)}else{let t=e??a.length;do{let e=c===0?o[0]??r.initialPageParam:Im(r,s);if(c>0&&e==null)break;s=await d(s,e),c++}while(c<t)}return s};t.fetchFn=t.options.persister?()=>t.options.persister?.(l,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n):l}}}function Im(e,{pages:t,pageParams:n}){let r=t.length-1;return t.length>0?e.getNextPageParam(t[r],t,n[r],n):void 0}function Lm(e,{pages:t,pageParams:n}){return t.length>0?e.getPreviousPageParam?.(t[0],t,n[0],n):void 0}function Rm(e,t){return t?Im(e,t)!=null:!1}function zm(e,t){return!t||!e.getPreviousPageParam?!1:Lm(e,t)!=null}var Bm=class extends Pm{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e){super(),this.#s=!1,this.#o=e.defaultOptions,this.setOptions(e.options),this.observers=[],this.#i=e.client,this.#r=this.#i.getQueryCache(),this.queryKey=e.queryKey,this.queryHash=e.queryHash,this.#t=Um(this.options),this.state=e.state??this.#t,this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return this.#e}get promise(){return this.#a?.promise}setOptions(e){if(this.options={...this.#o,...e},e?._type&&(this.#e=e._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let e=Um(this.options);e.data!==void 0&&(this.setState(Hm(e.data,e.dataUpdatedAt)),this.#t=e)}}optionalRemove(){!this.observers.length&&this.state.fetchStatus===`idle`&&this.#r.remove(this)}setData(e,t){let n=mm(this.state.data,e,this.options);return this.#c({data:n,type:`success`,dataUpdatedAt:t?.updatedAt,manual:t?.manual}),n}setState(e){this.#c({type:`setState`,state:e})}cancel(e){let t=this.#a?.promise;return this.#a?.cancel(e),t?t.then(Zp).catch(Zp):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(e=>tm(e.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===vm||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0&&this.observers.some(e=>tm(e.options.staleTime,this)===`static`)}isStale(){return this.getObserversCount()>0?this.observers.some(e=>e.getCurrentResult().isStale):this.state.data===void 0||this.state.isInvalidated}isStaleByTime(e=0){return this.state.data===void 0?!0:e===`static`?!1:this.state.isInvalidated?!0:!em(this.state.dataUpdatedAt,e)}onFocus(){this.observers.find(e=>e.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#a?.continue()}onOnline(){this.observers.find(e=>e.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#a?.continue()}addObserver(e){this.observers.includes(e)||(this.observers.push(e),this.clearGcTimeout(),this.#r.notify({type:`observerAdded`,query:this,observer:e}))}removeObserver(e){let t=this.observers.indexOf(e);t!==-1&&(this.observers.splice(t,1),this.observers.length||(this.#a&&(this.#s||this.state.fetchStatus===`paused`&&this.state.status===`pending`?this.#a.cancel({revert:!0}):this.#a.cancelRetry()),this.scheduleGc()),this.#r.notify({type:`observerRemoved`,query:this,observer:e}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||this.#c({type:`invalidate`})}async fetch(e,t){if(this.state.fetchStatus!==`idle`&&this.#a?.status()!==`rejected`){if(this.state.data!==void 0&&t?.cancelRefetch)this.cancel({silent:!0});else if(this.#a)return this.#a.continueRetry(),this.#a.promise}if(e&&this.setOptions(e),!this.options.queryFn){let e=this.observers.find(e=>e.options.queryFn);e&&this.setOptions(e.options)}let n=new AbortController,r=e=>{Object.defineProperty(e,"signal",{enumerable:!0,get:()=>(this.#s=!0,n.signal)})},i=()=>{let e=ym(this.options,t),n=(()=>{let e={client:this.#i,queryKey:this.queryKey,meta:this.meta};return r(e),e})();return this.#s=!1,this.options.persister?this.options.persister(e,n,this):e(n)},a=(()=>{let e={fetchOptions:t,options:this.options,queryKey:this.queryKey,client:this.#i,state:this.state,fetchFn:i};return r(e),e})();(this.#e===`infinite`?Fm(this.options.pages):this.options.behavior)?.onFetch(a,this),this.#n=this.state,(this.state.fetchStatus===`idle`||this.state.fetchMeta!==a.fetchOptions?.meta)&&this.#c({type:`fetch`,meta:a.fetchOptions?.meta});let o=this.#a=Nm({initialPromise:t?.initialPromise,fn:a.fetchFn,onCancel:e=>{e instanceof Mm&&e.revert&&this.setState({...this.#n,fetchStatus:`idle`}),n.abort()},onFail:(e,t)=>{this.#c({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#c({type:`pause`})},onContinue:()=>{this.#c({type:`continue`})},retry:a.options.retry,retryDelay:a.options.retryDelay,networkMode:a.options.networkMode,canRun:()=>!0});try{let e=await o.start();if(e===void 0)throw Error(`${this.queryHash} data is undefined`);return this.setData(e),this.#r.config.onSuccess?.(e,this),this.#r.config.onSettled?.(e,this.state.error,this),e}catch(e){if(e instanceof Mm){if(e.silent)return this.#a.promise;if(e.revert){if(this.state.data===void 0)throw e;return this.state.data}}throw this.#c({type:`error`,error:e}),this.#r.config.onError?.(e,this),this.#r.config.onSettled?.(this.state.data,e,this),e}finally{this.#a===o&&(this.#a=void 0),this.scheduleGc()}}#c(e){let t=t=>{switch(e.type){case`failed`:return{...t,fetchFailureCount:e.failureCount,fetchFailureReason:e.error};case`pause`:return{...t,fetchStatus:`paused`};case`continue`:return{...t,fetchStatus:`fetching`};case`fetch`:return{...t,...Vm(t.data,this.options),fetchMeta:e.meta??null};case`success`:let n={...t,...Hm(e.data,e.dataUpdatedAt),dataUpdateCount:t.dataUpdateCount+1,...!e.manual&&{fetchStatus:`idle`,fetchFailureCount:0,fetchFailureReason:null}};return this.#n=e.manual?n:void 0,n;case`error`:let r=e.error;return{...t,error:r,errorUpdateCount:t.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:t.fetchFailureCount+1,fetchFailureReason:r,fetchStatus:`idle`,status:`error`,isInvalidated:!0};case`invalidate`:return{...t,isInvalidated:!0};case`setState`:return{...t,...e.state}}};this.state=t(this.state),Om.batch(()=>{this.observers.slice().forEach(e=>{e.onQueryUpdate()}),this.#r.notify({query:this,type:`updated`,action:e})})}};function Vm(e,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:jm(t.networkMode)?`fetching`:`paused`,...e===void 0&&{error:null,status:`pending`}}}function Hm(e,t){return{data:e,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:`success`}}function Um(e){let t=typeof e.initialData==`function`?e.initialData():e.initialData,n=t!==void 0,r=n?typeof e.initialDataUpdatedAt==`function`?e.initialDataUpdatedAt():e.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?`success`:`pending`,fetchStatus:`idle`}}var Wm=class extends wm{#e;#t=void 0;#n=void 0;#r=void 0;#i;#a;#o;#s;#c;#l;#u;#d;#f;#p=new Set;constructor(e,t){super(),this.options=t,this.#e=e,this.#o=null,this.bindMethods(),this.setOptions(t)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(this.#t.addObserver(this),Km(this.#t,this.options)?this.#m():this.updateResult(),this.#y())}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return qm(this.#t,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return qm(this.#t,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#b(),this.#x(),this.#t.removeObserver(this)}setOptions(e){let t=this.options,n=this.#t;if(this.options=this.#e.defaultQueryOptions(e),this.options.enabled!==void 0&&typeof this.options.enabled!=`boolean`&&typeof this.options.enabled!=`function`&&typeof tm(this.options.enabled,this.#t)!=`boolean`)throw Error(`Expected enabled to be a boolean or a callback that returns a boolean`);this.#S(),this.#t.setOptions(this.options),t._defaulted&&!lm(this.options,t)&&this.#e.getQueryCache().notify({type:`observerOptionsUpdated`,query:this.#t,observer:this});let r=this.hasListeners();r&&Jm(this.#t,n,this.options,t)&&this.#m(),this.updateResult(),r&&(this.#t!==n||tm(this.options.enabled,this.#t)!==tm(t.enabled,this.#t)||tm(this.options.staleTime,this.#t)!==tm(t.staleTime,this.#t))&&this.#g();let i=this.#_();r&&(this.#t!==n||tm(this.options.enabled,this.#t)!==tm(t.enabled,this.#t)||i!==this.#f)&&this.#v(i)}getOptimisticResult(e){let t=this.#e.getQueryCache().build(this.#e,e),n=this.createResult(t,e);return lm(this.getCurrentResult(),n)||(this.#r=n,this.#a=this.options,this.#i=this.#t.state),n}getCurrentResult(){return this.#r}trackResult(e,t){return new Proxy(e,{get:(e,n)=>(this.trackProp(n),t?.(n),Reflect.get(e,n))})}trackProp(e){this.#p.add(e)}getCurrentQuery(){return this.#t}refetch({...e}={}){return this.fetch({...e})}fetchOptimistic(e){let t=this.#e.defaultQueryOptions(e),n=this.#e.getQueryCache().build(this.#e,t),r=()=>{},i,a=new Promise(e=>{i=e,r=this.#e.getQueryCache().subscribe(i=>{i.type===`updated`&&i.query.queryHash===n.queryHash&&n.state.data!==void 0&&(r(),e(this.createResult(n,t)))})});return Promise.race([n.fetch().then(()=>{let e=this.createResult(n,t);return i?.(e),e}).finally(()=>{r()}),a])}fetch(e){return this.#m({...e,cancelRefetch:e.cancelRefetch??!0}).then(()=>(this.updateResult(),this.#r))}#m(e){this.#S();let t=this.#t.fetch(this.options,e);return e?.throwOnError||(t=t.catch(Zp)),t}#h(e){return!Cm()&&tm(this.options.enabled,this.#t)!==!1&&$p(e)}#g(){this.#b();let e=tm(this.options.staleTime,this.#t);if(this.#r.isStale||!this.#h(e))return;let t=em(this.#r.dataUpdatedAt,e)+1;this.#u=Jp.setTimeout(()=>{this.#r.isStale||this.updateResult()},t)}#_(){return tm(this.options.refetchInterval,this.#t)??!1}#v(e){this.#x(),this.#f=e,this.#f!==0&&this.#h(this.#f)&&(this.#d=Jp.setInterval(()=>{(this.options.refetchIntervalInBackground||Tm.isFocused())&&this.#m()},this.#f))}#y(){this.#g(),this.#v(this.#_())}#b(){this.#u!==void 0&&(Jp.clearTimeout(this.#u),this.#u=void 0)}#x(){this.#d!==void 0&&(Jp.clearInterval(this.#d),this.#d=void 0)}createResult(e,t){let n=this.#t,r=this.options,i=this.#r,a=this.#i,o=this.#a,s=e===n?this.#n:e.state,{state:c}=e,l={...c},u=!1,d;if(t._optimisticResults){let i=this.hasListeners(),a=!i&&Km(e,t),o=i&&Jm(e,n,t,r);(a||o)&&(l={...l,...Vm(c.data,e.options)}),t._optimisticResults===`isRestoring`&&(l.fetchStatus=`idle`)}let{error:f,errorUpdatedAt:p,status:m}=l;d=l.data;let h=!1;if(t.placeholderData!==void 0&&d===void 0&&m===`pending`){let e;i?.isPlaceholderData&&t.placeholderData===o?.placeholderData?(e=i.data,h=!0):e=typeof t.placeholderData==`function`?t.placeholderData(this.#l?.state.data,this.#l):t.placeholderData,e!==void 0&&(m=`success`,d=mm(i?.data,e,t),u=!0)}if(t.select&&d!==void 0&&!h){if(i&&d===a?.data&&t.select===this.#s)d=this.#c;else try{this.#s=t.select,d=t.select(d),d=mm(i?.data,d,t),this.#c=d,this.#o=null}catch(e){this.#o=e}}else d===void 0&&(this.#o=null);this.#o&&(f=this.#o,d=this.#c,p=Date.now(),m=`error`,u=!1);let g=l.fetchStatus===`fetching`,_=m===`pending`,v=m===`error`,y=_&&g,b=d!==void 0;return{status:m,fetchStatus:l.fetchStatus,isPending:_,isSuccess:m===`success`,isError:v,isInitialLoading:y,isLoading:y,data:d,dataUpdatedAt:l.dataUpdatedAt,error:f,errorUpdatedAt:p,failureCount:l.fetchFailureCount,failureReason:l.fetchFailureReason,errorUpdateCount:l.errorUpdateCount,isFetched:e.isFetched(),isFetchedAfterMount:l.dataUpdateCount>s.dataUpdateCount||l.errorUpdateCount>s.errorUpdateCount,isFetching:g,isRefetching:g&&!_,isLoadingError:v&&!b,isPaused:l.fetchStatus===`paused`,isPlaceholderData:u,isRefetchError:v&&b,isStale:Ym(e,t),refetch:this.refetch,isEnabled:tm(t.enabled,e)!==!1}}updateResult(){let e=this.#r,t=this.createResult(this.#t,this.options);if(this.#i=this.#t.state,this.#a=this.options,this.#i.data!==void 0&&(this.#l=this.#t),lm(t,e))return;this.#r=t;let n=(()=>{if(!e)return!0;let{notifyOnChangeProps:t}=this.options,n=typeof t==`function`?t():t;if(n===`all`||!n&&!this.#p.size)return!0;let r=new Set(n??this.#p);return this.options.throwOnError&&r.add(`error`),Object.keys(this.#r).some(t=>{let n=t;return this.#r[n]!==e[n]&&r.has(n)})})();Om.batch(()=>{n&&this.listeners.forEach(e=>{e(this.#r)}),this.#e.getQueryCache().notify({query:this.#t,type:`observerResultsUpdated`})})}#S(){let e=this.#e.getQueryCache().build(this.#e,this.options);if(e===this.#t)return;let t=this.#t;this.#t=e,this.#n=e.state,this.hasListeners()&&(t?.removeObserver(this),e.addObserver(this))}onQueryUpdate(){this.updateResult(),this.hasListeners()&&this.#y()}};function Gm(e,t){return tm(t.enabled,e)!==!1&&e.state.data===void 0&&(e.state.status!==`error`||tm(t.retryOnMount,e)!==!1)}function Km(e,t){return Gm(e,t)||e.state.data!==void 0&&qm(e,t,t.refetchOnMount)}function qm(e,t,n){if(tm(t.enabled,e)!==!1&&tm(t.staleTime,e)!==`static`){let r=tm(n,e);return r===`always`||r!==!1&&Ym(e,t)}return!1}function Jm(e,t,n,r){return(e!==t||tm(r.enabled,e)===!1)&&(!n.suspense||e.state.status!==`error`)&&Ym(e,n)}function Ym(e,t){return tm(t.enabled,e)!==!1&&e.isStaleByTime(tm(t.staleTime,e))}var Xm=class extends Wm{constructor(e,t){super(e,t)}bindMethods(){super.bindMethods(),this.fetchNextPage=this.fetchNextPage.bind(this),this.fetchPreviousPage=this.fetchPreviousPage.bind(this)}setOptions(e){e._type=`infinite`,super.setOptions(e)}getOptimisticResult(e){return e._type=`infinite`,super.getOptimisticResult(e)}fetchNextPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`forward`}}})}fetchPreviousPage(e){return this.fetch({...e,meta:{fetchMore:{direction:`backward`}}})}createResult(e,t){let{state:n}=e,r=super.createResult(e,t),{isFetching:i,isRefetching:a,isError:o,isRefetchError:s}=r,c=n.fetchMeta?.fetchMore?.direction,l=o&&c===`forward`,u=i&&c===`forward`,d=o&&c===`backward`,f=i&&c===`backward`;return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:Rm(t,n.data),hasPreviousPage:zm(t,n.data),isFetchNextPageError:l,isFetchingNextPage:u,isFetchPreviousPageError:d,isFetchingPreviousPage:f,isRefetchError:s&&!l&&!d,isRefetching:a&&!u&&!f}}},Zm=class extends Pm{#e;#t;#n;#r;constructor(e){super(),this.#e=e.client,this.mutationId=e.mutationId,this.#n=e.mutationCache,this.#t=[],this.state=e.state||Qm(),this.setOptions(e.options),this.scheduleGc()}setOptions(e){this.options=e,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(e){this.#t.includes(e)||(this.#t.push(e),this.clearGcTimeout(),this.#n.notify({type:`observerAdded`,mutation:this,observer:e}))}removeObserver(e){this.#t=this.#t.filter(t=>t!==e),this.scheduleGc(),this.#n.notify({type:`observerRemoved`,mutation:this,observer:e})}optionalRemove(){this.#t.length||(this.state.status===`pending`?this.scheduleGc():this.#n.remove(this))}continue(){return this.#r?.continue()??(this.state.status===`pending`?this.execute(this.state.variables):Promise.resolve())}async execute(e){let t=()=>{this.#i({type:`continue`})},n={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey},r=this.#r=Nm({fn:()=>this.options.mutationFn?this.options.mutationFn(e,n):Promise.reject(Error(`No mutationFn found`)),onFail:(e,t)=>{this.#i({type:`failed`,failureCount:e,error:t})},onPause:()=>{this.#i({type:`pause`})},onContinue:t,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#n.canRun(this)}),i=this.state.status===`pending`,a=!r.canStart();try{if(i)t();else{this.#i({type:`pending`,variables:e,isPaused:a}),this.#n.config.onMutate&&await this.#n.config.onMutate(e,this,n);let t=await this.options.onMutate?.(e,n);t!==this.state.context&&this.#i({type:`pending`,context:t,variables:e,isPaused:a})}let o=await r.start();return await this.#n.config.onSuccess?.(o,e,this.state.context,this,n),await this.options.onSuccess?.(o,e,this.state.context,n),await this.#n.config.onSettled?.(o,null,this.state.variables,this.state.context,this,n),await this.options.onSettled?.(o,null,e,this.state.context,n),this.#i({type:`success`,data:o}),o}catch(t){try{await this.#n.config.onError?.(t,e,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onError?.(t,e,this.state.context,n)}catch(e){Promise.reject(e)}try{await this.#n.config.onSettled?.(void 0,t,this.state.variables,this.state.context,this,n)}catch(e){Promise.reject(e)}try{await this.options.onSettled?.(void 0,t,e,this.state.context,n)}catch(e){Promise.reject(e)}throw this.#i({type:`error`,error:t}),t}finally{this.#r===r&&(this.#r=void 0),this.#n.runNext(this)}}#i(e){let t=t=>{switch(e.type){case`failed`:return{...t,failureCount:e.failureCount,failureReason:e.error};case`pause`:return{...t,isPaused:!0};case`continue`:return{...t,isPaused:!1};case`pending`:return{...t,context:e.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:e.isPaused,status:`pending`,variables:e.variables,submittedAt:Date.now()};case`success`:return{...t,data:e.data,failureCount:0,failureReason:null,error:null,status:`success`,isPaused:!1};case`error`:return{...t,data:void 0,error:e.error,failureCount:t.failureCount+1,failureReason:e.error,isPaused:!1,status:`error`}}};this.state=t(this.state),Om.batch(()=>{this.#t.forEach(t=>{t.onMutationUpdate(e)}),this.#n.notify({mutation:this,type:`updated`,action:e})})}};function Qm(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:`idle`,variables:void 0,submittedAt:0}}var $m=class extends wm{#e;#t;#n;constructor(e={}){super(),this.config=e,this.#e=new Set,this.#t=new Map,this.#n=0}build(e,t,n){let r=new Zm({client:e,mutationCache:this,mutationId:++this.#n,options:e.defaultMutationOptions(t),state:n});return this.add(r),r}add(e){this.#e.add(e);let t=eh(e);if(typeof t==`string`){let n=this.#t.get(t);n?n.push(e):this.#t.set(t,[e])}this.notify({type:`added`,mutation:e})}remove(e){if(this.#e.delete(e)){let t=eh(e);if(typeof t==`string`){let n=this.#t.get(t);if(n){if(n.length>1){let t=n.indexOf(e);t!==-1&&n.splice(t,1)}else n[0]===e&&this.#t.delete(t)}}}this.notify({type:`removed`,mutation:e})}canRun(e){let t=eh(e);if(typeof t==`string`){let n=this.#t.get(t)?.find(e=>e.state.status===`pending`);return!n||n===e}return!0}runNext(e){let t=eh(e);return typeof t==`string`?(this.#t.get(t)?.find(t=>t!==e&&t.state.isPaused))?.continue()??Promise.resolve():Promise.resolve()}clear(){Om.batch(()=>{this.#e.forEach(e=>{this.notify({type:`removed`,mutation:e})}),this.#e.clear(),this.#t.clear()})}getAll(){return Array.from(this.#e)}find(e){let t={exact:!0,...e};return this.getAll().find(e=>rm(t,e))}findAll(e={}){return this.getAll().filter(t=>rm(e,t))}notify(e){Om.batch(()=>{this.listeners.forEach(t=>{t(e)})})}resumePausedMutations(){let e=this.getAll().filter(e=>e.state.isPaused);return Om.batch(()=>Promise.all(e.map(e=>e.continue().catch(Zp))))}};function eh(e){return e.options.scope?.id}var th=class extends wm{#e;#t=void 0;#n;#r;constructor(e,t){super(),this.#e=e,this.setOptions(t),this.bindMethods(),this.#i()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(e){let t=this.options;this.options=this.#e.defaultMutationOptions(e),lm(this.options,t)||this.#e.getMutationCache().notify({type:`observerOptionsUpdated`,mutation:this.#n,observer:this}),t?.mutationKey&&this.options.mutationKey&&am(t.mutationKey)!==am(this.options.mutationKey)?this.reset():this.#n?.state.status===`pending`&&this.#n.setOptions(this.options)}onSubscribe(){this.listeners.size===1&&this.#n&&(this.#n.addObserver(this),this.#i())}onUnsubscribe(){this.hasListeners()||this.#n?.removeObserver(this)}onMutationUpdate(e){this.#i(),this.#a(e)}getCurrentResult(){return this.#t}reset(){this.#n?.removeObserver(this),this.#n=void 0,this.#i(),this.#a()}mutate(e,t){return this.#r=t,this.#n?.removeObserver(this),this.#n=this.#e.getMutationCache().build(this.#e,this.options),this.#n.addObserver(this),this.#n.execute(e)}#i(){let e=this.#n?.state??Qm();this.#t={...e,isPending:e.status===`pending`,isSuccess:e.status===`success`,isError:e.status===`error`,isIdle:e.status===`idle`,mutate:this.mutate,reset:this.reset}}#a(e){Om.batch(()=>{if(this.#r&&this.hasListeners()){let t=this.#t.variables,n=this.#t.context,r={client:this.#e,meta:this.options.meta,mutationKey:this.options.mutationKey};if(e?.type===`success`){try{this.#r.onSuccess?.(e.data,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(e.data,null,t,n,r)}catch(e){Promise.reject(e)}}else if(e?.type===`error`){try{this.#r.onError?.(e.error,t,n,r)}catch(e){Promise.reject(e)}try{this.#r.onSettled?.(void 0,e.error,t,n,r)}catch(e){Promise.reject(e)}}}this.listeners.forEach(e=>{e(this.#t)})})}};function nh(e,t){let n=new Set(t);return e.filter(e=>!n.has(e))}var kne=class extends wm{#e;#t;#n;#r;#i;#a;#o;#s;#c;#l=[];constructor(e,t,n){super(),this.#e=e,this.#r=n,this.#n=[],this.#i=[],this.#t=[],this.setQueries(t)}onSubscribe(){this.listeners.size===1&&this.#i.forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})}onUnsubscribe(){this.listeners.size||this.destroy()}destroy(){this.listeners=new Set,this.#i.forEach(e=>{e.destroy()})}setQueries(e,t){this.#n=e,this.#r=t,Om.batch(()=>{let e=this.#i,t=this.#p(this.#n);t.forEach(e=>e.observer.setOptions(e.defaultedQueryOptions));let n=t.map(e=>e.observer),r=n.map(e=>e.getCurrentResult()),i=e.length!==n.length,a=n.some((t,n)=>t!==e[n]),o=i||a,s=o?!0:r.some((e,t)=>{let n=this.#t[t];return!n||!lm(e,n)});(o||s)&&(o&&(this.#l=t,this.#i=n),this.#t=r,this.hasListeners()&&(o&&(nh(e,n).forEach(e=>{e.destroy()}),nh(n,e).forEach(e=>{e.subscribe(t=>{this.#m(e,t)})})),this.#h()))})}getCurrentResult(){return this.#t}getQueries(){return this.#i.map(e=>e.getCurrentQuery())}getObservers(){return this.#i}getOptimisticResult(e,t){let n=this.#p(e),r=n.map(e=>e.observer.getOptimisticResult(e.defaultedQueryOptions)),i=n.map(e=>e.defaultedQueryOptions.queryHash);return[r,e=>this.#d(e??r,t,i),()=>this.#u(r,n)]}#u(e,t){let n=new Set;return t.map((r,i)=>{let a=e[i];return r.defaultedQueryOptions.notifyOnChangeProps?a:r.observer.trackResult(a,e=>{n.has(e)||(n.add(e),t.forEach(t=>{t.observer.trackProp(e)}))})})}#d(e,t,n){if(t){let r=this.#c,i=n!==void 0&&r!==void 0&&(r.length!==n.length||n.some((e,t)=>e!==r[t]));return(this.#t!==this.#s||i||t!==this.#o)&&(this.#o=t,this.#s=this.#t,n!==void 0&&(this.#c=n),this.#a=cm(this.#a,t(e))),this.#a}return e}#f(){return!this.#r?.combine||this.#i.some((e,t)=>e.options.suspense&&this.#t[t]?.data===void 0)}#p(e){let t=new Map;this.#i.forEach(e=>{let n=e.options.queryHash;if(!n)return;let r=t.get(n);r?r.push(e):t.set(n,[e])});let n=[];return e.forEach(e=>{let r=this.#e.defaultQueryOptions(e),i=t.get(r.queryHash)?.shift()??new Wm(this.#e,r);n.push({defaultedQueryOptions:r,observer:i})}),n}#m(e,t){let n=this.#i.indexOf(e);n!==-1&&(this.#t=this.#t.slice(),this.#t[n]=t,this.#h())}#h(){if(this.hasListeners()){let e=this.#f(),t=this.#a,n=e?t:this.#d(this.#u(this.#t,this.#l),this.#r?.combine);(e||t!==n)&&Om.batch(()=>{this.listeners.forEach(e=>{e(this.#t)})})}}},Ane=class extends wm{#e;constructor(e={}){super(),this.config=e,this.#e=new Map}build(e,t,n){let r=t.queryKey,i=t.queryHash??im(r,t),a=this.get(i);return a||(a=new Bm({client:e,queryKey:r,queryHash:i,options:e.defaultQueryOptions(t),state:n,defaultOptions:e.getQueryDefaults(r)}),this.add(a)),a}add(e){this.#e.has(e.queryHash)||(this.#e.set(e.queryHash,e),this.notify({type:`added`,query:e}))}remove(e){this.#e.get(e.queryHash)===e&&(e.destroy(),this.#e.delete(e.queryHash),this.notify({type:`removed`,query:e}))}clear(){Om.batch(()=>{this.getAll().forEach(e=>{this.remove(e)})})}get(e){return this.#e.get(e)}getAll(){return[...this.#e.values()]}find(e){let t={exact:!0,...e};return this.getAll().find(e=>nm(t,e))}findAll(e={}){let t=this.getAll();return Object.keys(e).length>0?t.filter(t=>nm(e,t)):t}notify(e){Om.batch(()=>{this.listeners.forEach(t=>{t(e)})})}onFocus(){Om.batch(()=>{this.getAll().forEach(e=>{e.onFocus()})})}onOnline(){Om.batch(()=>{this.getAll().forEach(e=>{e.onOnline()})})}},jne=class{#e;#t;#n;#r;#i;#a;#o;#s;constructor(e={}){this.#e=e.queryCache||new Ane,this.#t=e.mutationCache||new $m,this.#n=e.defaultOptions||{},this.#r=new Map,this.#i=new Map,this.#a=0}mount(){this.#a++,this.#a===1&&(this.#o=Tm.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onFocus())}),this.#s=km.subscribe(async e=>{e&&(await this.resumePausedMutations(),this.#e.onOnline())}))}unmount(){this.#a--,this.#a===0&&(this.#o?.(),this.#o=void 0,this.#s?.(),this.#s=void 0)}isFetching(e){return this.#e.findAll({...e,fetchStatus:`fetching`}).length}isMutating(e){return this.#t.findAll({...e,status:`pending`}).length}getQueryData(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state.data}ensureQueryData(e){let t=this.defaultQueryOptions(e),n=this.#e.build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(e):(e.revalidateIfStale&&n.isStaleByTime(tm(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(e){return this.#e.findAll(e).map(({queryKey:e,state:t})=>[e,t.data])}setQueryData(e,t,n){let r=this.defaultQueryOptions({queryKey:e}),i=this.#e.get(r.queryHash)?.state.data,a=Qp(t,i);if(a!==void 0)return this.#e.build(this,r).setData(a,{...n,manual:!0})}setQueriesData(e,t,n){return Om.batch(()=>this.#e.findAll(e).map(({queryKey:e})=>[e,this.setQueryData(e,t,n)]))}getQueryState(e){let t=this.defaultQueryOptions({queryKey:e});return this.#e.get(t.queryHash)?.state}removeQueries(e){let t=this.#e;Om.batch(()=>{t.findAll(e).forEach(e=>{t.remove(e)})})}resetQueries(e,t){let n=this.#e;return Om.batch(()=>{let r=n.findAll(e),i=new Set(r);return r.forEach(e=>{e.reset()}),this.refetchQueries({type:`active`,predicate:e=>i.has(e)},t)})}cancelQueries(e,t={}){let n={revert:!0,...t},r=Om.batch(()=>this.#e.findAll(e).map(e=>e.cancel(n)));return Promise.all(r).then(Zp).catch(Zp)}invalidateQueries(e,t={}){return Om.batch(()=>(this.#e.findAll(e).forEach(e=>{e.invalidate()}),e?.refetchType===`none`?Promise.resolve():this.refetchQueries({...e,type:e?.refetchType??e?.type??`active`},t)))}refetchQueries(e,t={}){let n={...t,cancelRefetch:t.cancelRefetch??!0},r=Om.batch(()=>this.#e.findAll(e).filter(e=>!e.isDisabled()&&!e.isStatic()).map(e=>{let t=e.fetch(void 0,n);return n.throwOnError||(t=t.catch(Zp)),e.state.fetchStatus===`paused`?Promise.resolve():t}));return Promise.all(r).then(Zp)}async query(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t),r=n.isStaleByTime(tm(t.staleTime,n))?await n.fetch(t):n.state.data,i=t.select;return i?i(r):r}fetchQuery(e){let t=this.defaultQueryOptions(e);t.retry===void 0&&(t.retry=!1);let n=this.#e.build(this,t);return n.isStaleByTime(tm(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(e){return this.fetchQuery(e).then(Zp).catch(Zp)}infiniteQuery(e){return e._type=`infinite`,this.query(e)}fetchInfiniteQuery(e){return e._type=`infinite`,this.fetchQuery(e)}prefetchInfiniteQuery(e){return this.fetchInfiniteQuery(e).then(Zp).catch(Zp)}ensureInfiniteQueryData(e){return e._type=`infinite`,this.ensureQueryData(e)}resumePausedMutations(){return km.isOnline()?this.#t.resumePausedMutations():Promise.resolve()}getQueryCache(){return this.#e}getMutationCache(){return this.#t}getDefaultOptions(){return this.#n}setDefaultOptions(e){this.#n=e}setQueryDefaults(e,t){this.#r.set(am(e),{queryKey:e,defaultOptions:t})}getQueryDefaults(e){let t=[...this.#r.values()],n={};return t.forEach(t=>{om(e,t.queryKey)&&Object.assign(n,t.defaultOptions)}),n}setMutationDefaults(e,t){this.#i.set(am(e),{mutationKey:e,defaultOptions:t})}getMutationDefaults(e){let t=[...this.#i.values()],n={};return t.forEach(t=>{om(e,t.mutationKey)&&Object.assign(n,t.defaultOptions)}),n}defaultQueryOptions(e){if(e._defaulted)return e;let t={...this.#n.queries,...this.getQueryDefaults(e.queryKey),...e,_defaulted:!0};return t.queryHash||=im(t.queryKey,t),t.refetchOnReconnect===void 0&&(t.refetchOnReconnect=t.networkMode!==`always`),t.throwOnError===void 0&&(t.throwOnError=!!t.suspense),!t.networkMode&&t.persister&&(t.networkMode=`offlineFirst`),t.queryFn===vm&&(t.enabled=!1),t}defaultMutationOptions(e){return e?._defaulted?e:{...this.#n.mutations,...e?.mutationKey&&this.getMutationDefaults(e.mutationKey),...e,_defaulted:!0}}clear(){this.#e.clear(),this.#t.clear()}},rh=o.createContext(!1),ih=()=>o.useContext(rh);rh.Provider;function Mne(){let e=!1;return{clearReset:()=>{e=!1},reset:()=>{e=!0},isReset:()=>e}}var Nne=o.createContext(Mne()),ah=()=>o.useContext(Nne),oh=(e,t,n)=>{let r=n?.state.error&&typeof e.throwOnError==`function`?bm(e.throwOnError,[n.state.error,n]):e.throwOnError;(e.suspense||r)&&(t.isReset()||(e.retryOnMount=!1))},sh=e=>{o.useEffect(()=>{e.clearReset()},[e])},ch=({result:e,errorResetBoundary:t,throwOnError:n,query:r,suspense:i})=>e.isError&&!t.isReset()&&!e.isFetching&&r&&(i&&e.data===void 0||bm(n,[e.error,r])),lh=e=>{if(e.suspense){let t=1e3,n=e=>e===`static`?e:Math.max(e??t,t),r=e.staleTime;e.staleTime=typeof r==`function`?(...e)=>n(r(...e)):n(r),typeof e.gcTime==`number`&&(e.gcTime=Math.max(e.gcTime,t))}},uh=(e,t)=>e?.suspense&&t.isPending,dh=(e,t,n)=>t.fetchOptimistic(e).catch(()=>{n.clearReset()});function fh({queries:e,...t},n){let r=Gp(n),i=ih(),a=ah(),s=t.subscribed!==!1,c=o.useMemo(()=>e.map(e=>{let t=r.defaultQueryOptions(e);return t._optimisticResults=i?`isRestoring`:s?`optimistic`:void 0,t}),[e,r,i,s]);c.forEach(e=>{lh(e);let t=r.getQueryCache().get(e.queryHash);oh(e,a,t)}),sh(a);let[l]=o.useState(()=>new kne(r,c,t)),[u,d,f]=l.getOptimisticResult(c,t.combine),p=!i&&s;o.useSyncExternalStore(o.useCallback(e=>p?l.subscribe(Om.batchCalls(e)):Zp,[l,p]),()=>l.getCurrentResult(),()=>l.getCurrentResult()),o.useEffect(()=>{l.setQueries(c,t)},[c,t,l]);let m=u.some((e,t)=>uh(c[t],e))?u.flatMap((e,t)=>{let n=c[t];return n&&uh(n,e)?dh(n,new Wm(r,n),a):[]}):[];if(m.length>0)throw Promise.all(m);let h=u.find((e,t)=>{let n=c[t];return n&&ch({result:e,errorResetBoundary:a,throwOnError:n.throwOnError,query:r.getQueryCache().get(n.queryHash),suspense:n.suspense})});if(h)throw h.error;return d(f())}function ph(e,t,n){let r=ih(),i=ah(),a=Gp(n),s=a.defaultQueryOptions(e),c=a.getQueryCache().get(s.queryHash),l=e.subscribed!==!1;s._optimisticResults=r?`isRestoring`:l?`optimistic`:void 0,lh(s),oh(s,i,c),sh(i);let[u]=o.useState(()=>new t(a,s)),d=u.getOptimisticResult(s),f=!r&&l;if(o.useSyncExternalStore(o.useCallback(e=>{let t=f?u.subscribe(Om.batchCalls(e)):Zp;return u.updateResult(),t},[u,f]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),o.useEffect(()=>{u.setOptions(s)},[s,u]),uh(s,d))throw dh(s,u,i);if(ch({result:d,errorResetBoundary:i,throwOnError:s.throwOnError,query:c,suspense:s.suspense}))throw d.error;return s.notifyOnChangeProps?d:u.trackResult(d)}function mh(e,t){return ph(e,Wm,t)}function hh(e,t){let n=Gp(t),[r]=o.useState(()=>new th(n,e));o.useEffect(()=>{r.setOptions(e)},[r,e]);let i=o.useSyncExternalStore(o.useCallback(e=>r.subscribe(Om.batchCalls(e)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),a=o.useCallback((...e)=>{r.mutate(e[0],e[1]).catch(Zp)},[r]);if(i.error&&bm(r.options.throwOnError,[i.error]))throw i.error;return{...i,mutate:a,mutateAsync:i.mutate}}function gh(e,t){return ph(e,Xm,t)}var Pne=()=>{let e=0;return{refetchOnWindowFocus:()=>e>0?!1:`always`,pause:()=>{e+=1;let t=!1;return()=>{t||(t=!0,--e)}}}},_h=(0,o.createContext)(null),Fne=e=>{let t=(0,o.useContext)(_h);(0,o.useEffect)(()=>e&&t?t.pause():void 0,[e,t])},Ine=e=>{let t=()=>e();return window.addEventListener(`visibilitychange`,t,!1),window.addEventListener(`focus`,t,!1),()=>{window.removeEventListener(`visibilitychange`,t),window.removeEventListener(`focus`,t)}},W={meta:[`meta`],sourceMeta:(e,t)=>[`source-meta`,e,t.join(`,`)],sourceMetas:e=>[`source-meta`,e],list:(e,t,n,r,i)=>[`list`,e,t,n,r,i],page:(e,t,n,r,i)=>[`page`,e,t,n,r,i],pages:(e,t,n)=>[`page`,e,t,n],navRecent:(e,t,n,r)=>[`list`,e,t,n,r,`nav-recent`],first:(e,t,n)=>[`first-page`,e,t,n],record:(e,t)=>[`record`,e,t],recordPreview:(e,t)=>[`record-preview`,e,t],history:(e,t,n)=>[`record`,e,t,`history`,n],comments:(e,t)=>[`record`,e,t,`comments`],mentionable:(e,t,n)=>[`record`,e,t,`mentionable`,n],facets:(e,t,n)=>[`facets`,e,t,n],series:(e,t,n,r,i)=>[`series`,e,t,n,r,i],aggregate:(e,t)=>[`aggregate`,e,t],histogram:(e,t,n,r)=>[`histogram`,e,t,n,r],map:(e,t,n,r,i)=>[`map`,e,t,n,r,i],relatedLabel:(e,t)=>[`related-label`,e,t],labels:(e,t)=>[`labels`,e,t],count:(e,t)=>[`count`,e,t],exportCount:(e,t)=>[`list`,e,t,`export-count`],firstRecord:(e,t,n)=>[`first-record`,e,t,n],pathValue:(e,t,n)=>[`path-value`,e,t,n],publicForm:e=>[`public-form`,e]},vh=(0,o.createContext)(null),yh=(0,o.createContext)(null),bh=(0,o.createContext)(null),G=()=>{let e=(0,o.useContext)(vh);if(!e)throw Error(`useClient must be used inside ApiProvider`);return e},xh=e=>{let t=G();return(0,o.useContext)(bh)?.(e)??t},Lne=()=>{let e=G(),t=(0,o.useContext)(bh);return(0,o.useCallback)(n=>t?.(n)??e,[e,t])},Rne=()=>{let e=(0,o.useContext)(yh);if(!e)throw Error(`useSourceClients must be used inside ApiProvider`);return e},zne=({client:e,resourceClient:t,children:n})=>(0,V.jsx)(vh.Provider,{value:e,children:(0,V.jsx)(bh.Provider,{value:t,children:n})}),Sh=({baseUrl:e,client:t,sources:n,fetch:r,queryClient:i,token:a,onUnauthenticated:s,children:c})=>{let[l]=(0,o.useState)(Pne),[u]=(0,o.useState)(()=>i??new jne({defaultOptions:{queries:{staleTime:3e4,retry:!1,refetchOnWindowFocus:l.refetchOnWindowFocus}}}));(0,o.useEffect)(()=>Tm.setEventListener(Ine),[]);let d=(0,o.useRef)(void 0),f=(0,o.useMemo)(()=>t??Zs({baseUrl:e,fetch:r,token:a,onUnauthenticated:s,onMetaVersion:e=>{let t=d.current;d.current=e,t!==void 0&&t!==e&&u.invalidateQueries({queryKey:W.meta},{cancelRefetch:!1})}}),[t,e,r,u,a,s]),p=(0,o.useMemo)(()=>{let e=new Map;return t=>{let i=n?.[t.url]??e.get(t.url);if(i)return i;let o,s=Zs({baseUrl:t.url,fetch:r,token:a,onMetaVersion:e=>{let n=o;o=e,n!==void 0&&n!==e&&u.invalidateQueries({queryKey:W.sourceMetas(t.url)},{cancelRefetch:!1})}});return e.set(t.url,s),s}},[n,r,a,u]);return(0,V.jsx)(Kp,{client:u,children:(0,V.jsx)(vh.Provider,{value:f,children:(0,V.jsx)(yh.Provider,{value:p,children:(0,V.jsx)(_h.Provider,{value:l,children:c})})})})},Ch=(0,o.createContext)(null),wh=()=>{let e=(0,o.useContext)(Ch);if(!e)throw Error(`useRouter must be used inside Router`);return e},Th=()=>`${window.location.pathname}${window.location.search}`,Eh=e=>new URL(e,`http://local`).pathname,Dh=()=>window.history.state?.protobaseIndex??0,Bne=({basePath:e=``,initialUrl:t,children:n})=>{let r=t!==void 0,[i,a]=(0,o.useState)(t??Th()),s=(0,o.useRef)(new Set),c=(0,o.useRef)(i);c.current=i;let l=(0,o.useRef)(r?0:Dh()),u=(0,o.useRef)(!1),d=(0,o.useRef)(!1),[f,p]=(0,o.useState)();(0,o.useEffect)(()=>{if(r)return;window.history.replaceState({protobaseIndex:l.current},``);let e=()=>{let e=Dh();if(u.current){u.current=!1,l.current=e;return}let t=e-l.current,n=Eh(Th())!==Eh(c.current);if(!d.current&&s.current.size>0&&n){u.current=!0,window.history.go(-t),p({kind:`history`,delta:t});return}d.current=!1,l.current=e,a(Th())};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[r]);let m=(0,o.useCallback)((e,t)=>{r||(l.current+=+!t,window.history[t?`replaceState`:`pushState`]({protobaseIndex:l.current},``,e)),a(e)},[r]),h=(0,o.useCallback)((t,{replace:n=!1}={})=>{let r=`${e}${t}`;if(Eh(r)!==Eh(c.current)&&s.current.size>0)return p({kind:`link`,full:r,replace:n});m(r,n)},[e,m]),g=(0,o.useCallback)(()=>{let e=Symbol(`guard`);return s.current.add(e),()=>void s.current.delete(e)},[]),_=()=>{if(f){if(p(void 0),f.kind===`link`)return m(f.full,f.replace);d.current=!0,window.history.go(f.delta)}},v=(0,o.useMemo)(()=>{let t=new URL(i,`http://local`);return{path:t.pathname.slice(e.length)||`/`,params:t.searchParams,basePath:e,entry:l.current,navigate:h,registerGuard:g}},[i,e,h,g]);return(0,V.jsxs)(Ch.Provider,{value:v,children:[n,f&&(0,V.jsx)(wf,{title:`Leave without saving?`,description:`You have unsaved changes on this page. They stay in this browser, and come back when you open the record again.`,onClose:()=>p(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>p(void 0),children:`Stay`}),(0,V.jsx)(U,{variant:`primary`,onClick:_,children:`Leave`})]})})]})},Vne=({to:e,replace:t,...n})=>{let{navigate:r,basePath:i}=wh();return(0,V.jsx)(du,{to:{href:`${i}${e}`,onFollow:()=>r(e,{replace:t})},...n})},Hne=e=>{let{registerGuard:t}=wh();(0,o.useEffect)(()=>e?t():void 0,[e,t]),(0,o.useEffect)(()=>{if(!e)return;let t=e=>e.preventDefault();return window.addEventListener(`beforeunload`,t),()=>window.removeEventListener(`beforeunload`,t)},[e])},Oh=({title:e,description:t,size:n=`sm`,children:r})=>(0,V.jsx)(`div`,{className:`flex min-h-full w-full items-center justify-center bg-surface px-4 py-10`,children:(0,V.jsxs)(`div`,{className:B(`w-full`,n===`sm`?`max-w-sm`:`max-w-lg`),children:[(0,V.jsxs)(`div`,{className:`mb-6 flex flex-col items-center text-center`,children:[(0,V.jsx)(hu,{className:`size-10`}),(0,V.jsx)(`h1`,{className:`mt-4 text-xl font-semibold tracking-tight`,children:e}),t&&(0,V.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:t})]}),(0,V.jsx)(`div`,{className:`rounded-lg border bg-background p-5 shadow-sm`,children:r})]})}),kh=({onResend:e,cooldown:t=30,disabled:n})=>{let[r,i]=(0,o.useState)(()=>Date.now()+t*1e3),[a,s]=(0,o.useState)(()=>Date.now()),c=Math.max(0,Math.ceil((r-a)/1e3));return(0,o.useEffect)(()=>{if(c===0)return;let e=setInterval(()=>s(Date.now()),1e3);return()=>clearInterval(e)},[c]),(0,V.jsx)(U,{variant:`ghost`,disabled:n||c>0,onClick:()=>{let n=Date.now();i(n+t*1e3),s(n),e()},className:`min-h-10`,children:c>0?`Send a new code in ${c}s`:`Send a new code`})},Ah=({title:e,description:t,explanation:n,submitLabel:r,onSubmit:i,onResend:a,onChangeAddress:s,changeAddressLabel:c,busy:l,error:u,notice:d,resendCooldown:f})=>{let[p,m]=(0,o.useState)(``);return(0,V.jsxs)(Oh,{title:e,description:t,children:[(0,V.jsx)(`p`,{className:`mb-4 text-muted-foreground`,children:n}),d&&(0,V.jsx)(`p`,{role:`status`,className:`mb-4 rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:d}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),i(p)},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Code`,(0,V.jsx)(If,{name:`code`,required:!0,autoFocus:!0,value:p,invalid:!!u,onChange:m,onComplete:e=>!l&&i(e)})]}),u&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:u}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:l,className:`min-h-10`,children:r}),(0,V.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-x-2 sm:justify-between`,children:[(0,V.jsx)(U,{variant:`ghost`,onClick:s,className:`min-h-10`,children:c}),(0,V.jsx)(kh,{onResend:a,disabled:l,cooldown:f})]})]})]})},Une=({email:e,onBack:t,...n})=>(0,V.jsx)(Ah,{title:`Check your email`,description:`Enter the code we sent to sign in.`,explanation:(0,V.jsxs)(V.Fragment,{children:[`If `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),` has an account, a 6-digit code is on its way. It works for 5 minutes, once.`]}),submitLabel:`Sign in`,onChangeAddress:t,changeAddressLabel:`Back to sign in`,...n}),Wne=({email:e,onBack:t})=>{let{signInWithCode:n,sendSignInCode:r}=H(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(),d=async e=>{a(!0),c(void 0),u(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;c(xd(e))}a(!1)};return(0,V.jsx)(Une,{email:e,busy:i,error:s,notice:l,onBack:t,onSubmit:t=>void d(()=>n(e,t)),onResend:()=>void d(async()=>{await r(e),u(`A new code is on its way. Only the newest one works.`)})})},Gne=`protobase users create you@example.com`,Kne=({command:e=Gne,onCheckAgain:t,busy:n})=>{let[r,i]=(0,o.useState)(!1);return(0,V.jsxs)(Oh,{title:`No admin yet`,description:`This Protobase has no users to sign in with.`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Run this in the terminal where Protobase runs, then reload. The first admin is created on the server, not in the browser, so nobody else can claim a fresh URL.`}),(0,V.jsxs)(`div`,{className:`mt-4 flex items-center gap-2 rounded-md border bg-surface py-1.5 pl-3 pr-1.5`,children:[(0,V.jsx)(`code`,{className:`min-w-0 flex-1 break-all font-mono text-xs`,children:e}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Copy command`,onClick:()=>{navigator.clipboard.writeText(e).then(()=>{i(!0),setTimeout(()=>i(!1),2e3)})},className:`inline-flex size-8 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-muted pointer-coarse:size-11`,children:r?(0,V.jsx)(ge,{className:`size-4 text-success`}):(0,V.jsx)(Re,{className:`size-4`})})]}),(0,V.jsx)(U,{variant:`primary`,className:`mt-4 min-h-10 w-full`,loading:n,onClick:t,children:`Reload`})]})},qne=({onSubmit:e,back:t,busy:n,error:r,sentTo:i})=>{let[a,s]=(0,o.useState)(``);return i?(0,V.jsxs)(Oh,{title:`Check your email`,children:[(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`If `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:i}),` has an account, an email with a link to choose a new password is on its way. The link works once, for a limited time.`]}),(0,V.jsx)(du,{to:t,className:B(Cf({variant:`primary`}),`mt-4 min-h-10 w-full`),children:`Back to sign in`})]}):(0,V.jsx)(Oh,{title:`Reset your password`,description:`We email you a link to choose a new one.`,children:(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),e(a.trim())},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,V.jsx)(sd,{type:`email`,name:`email`,autoComplete:`username`,required:!0,autoFocus:!0,value:a,invalid:!!r,onChange:e=>s(e.target.value),className:`min-h-6`})]}),r&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:r}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:n,className:`min-h-10`,children:`Send reset link`}),(0,V.jsx)(du,{to:t,className:B(Cf({variant:`ghost`}),`min-h-10`),children:`Back to sign in`})]})})},jh=`password-reset`,Jne=e=>{let t=new URL(e);return`${t.origin}${t.pathname}?${jh}`},Yne=e=>{let t=new URL(e).searchParams;if(t.has(`password-reset`))return{token:t.get(`token`)||void 0}},Xne=e=>{let t=new URL(e);for(let e of[jh,`token`,`error`])t.searchParams.delete(e);return`${t.pathname}${t.search}${t.hash}`},Zne=({back:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(!1),[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(),l=async e=>{r(!0),a(void 0);try{await t.requestPasswordReset(e,Jne(window.location.href)),c(e)}catch(e){if(!(e instanceof pc))throw e;a(e.status===429?`Too many requests. Wait a minute and try again.`:e.message)}r(!1)};return(0,V.jsx)(qne,{busy:n,error:i,sentTo:s,back:e,onSubmit:e=>void l(e)})},Qne=({name:e,workspace:t})=>(0,V.jsx)(Oh,{title:`Signing in with ${e}`,description:t,children:(0,V.jsxs)(`p`,{role:`status`,className:`flex items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Taking you to `,e,`…`]})}),$ne=({provider:e,workspace:t,onFailed:n})=>{let{signInProviders:r,signInSocial:i}=H(),a=r.find(t=>t.id===e),s=a?.name??Nd(e),c=(0,o.useRef)(!1);return(0,o.useEffect)(()=>{if(!c.current){if(c.current=!0,!a)return n(`Signing in with ${s} is not offered here. Sign in another way.`);i(e).catch(e=>{if(!(e instanceof pc))throw e;n(Sd(e))})}},[a,s,e,i,n]),(0,V.jsx)(Qne,{name:s,workspace:t})},ere=({onSubmit:e,invalidLink:t,onRequestNewLink:n,onBack:r,busy:i,error:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),[d,f]=(0,o.useState)(!1);if(t)return(0,V.jsxs)(Oh,{title:`This link no longer works`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`A reset link works once, for a limited time. Ask for a new one to choose your password.`}),(0,V.jsxs)(`div`,{className:`mt-4 flex flex-col gap-2`,children:[n&&(0,V.jsx)(U,{variant:`primary`,className:`min-h-10`,onClick:n,children:`Send a new link`}),(0,V.jsx)(U,{variant:n?`ghost`:`primary`,className:`min-h-10`,onClick:r,children:`Back to sign in`})]})]});let p=d?`The passwords are not the same.`:a;return(0,V.jsx)(Oh,{title:`Choose a new password`,description:`At least 12 characters.`,children:(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),f(s!==l),s===l&&e(s)},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`New password`,(0,V.jsx)(sd,{type:`password`,name:`new-password`,autoComplete:`new-password`,required:!0,minLength:12,autoFocus:!0,value:s,invalid:!!p,onChange:e=>c(e.target.value),className:`min-h-6`})]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Repeat new password`,(0,V.jsx)(sd,{type:`password`,name:`repeat-password`,autoComplete:`new-password`,required:!0,minLength:12,value:l,invalid:!!p,onChange:e=>u(e.target.value),className:`min-h-6`})]}),p&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:p}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Set new password`})]})})},tre=e=>e.status===429?`Too many attempts. Wait a minute and try again.`:e.code===`PASSWORD_TOO_SHORT`?`Use at least 12 characters.`:e.code===`PASSWORD_TOO_LONG`?`That password is too long.`:e.message,nre=({token:e,onDone:t,onRequestNewLink:n,onBack:r})=>{let{session:i}=H(),[a,s]=(0,o.useState)(!1),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(!e),f=async n=>{s(!0),l(void 0);try{await i.resetPassword(e,n),t()}catch(e){if(!(e instanceof pc))throw e;e.code===`INVALID_TOKEN`?d(!0):l(tre(e)),s(!1)}};return(0,V.jsx)(ere,{busy:a,error:c,invalidLink:u,onRequestNewLink:n,onBack:r,onSubmit:e=>void f(e)})},rre={twoFactor:`Turn on two-factor authentication`,passkey:`Add a passkey`},ire=({step:e,twoFactor:t,onAddPasskey:n,busy:r,error:i,onSignOut:a})=>(0,V.jsxs)(Oh,{title:rre[e],description:`This app requires it for every account.`,children:[e===`twoFactor`?(0,V.jsx)(Dp,{...t}):(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`A passkey signs you in with Face ID, Touch ID, Windows Hello, your phone or a security key. Your browser asks which one to use.`}),i&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,V.jsxs)(U,{variant:`primary`,loading:r,onClick:n,className:`min-h-10`,children:[(0,V.jsx)(_t,{className:`size-4`}),`Add a passkey`]})]}),(0,V.jsx)(`button`,{type:`button`,onClick:a,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:underline`,children:`Sign out`})]}),are=({missing:e})=>{let{session:t,recheck:n,signOut:r}=H(),[i,a]=(0,o.useState)(),[s,c]=(0,o.useState)(!1),[l,u]=(0,o.useState)();(0,o.useEffect)(()=>{t.account.signInMethods().then(a,e=>u(e instanceof pc?xd(e):`Could not read your account`))},[t]);let d=async()=>{c(!0),u(void 0);try{await t.account.addPasskey(),n()}catch(e){if(!(e instanceof pc))throw e;u(xd(e)),c(!1)}};return!i&&!l?(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]}):(0,V.jsx)(ire,{step:e[0],busy:s,error:l,onAddPasskey:()=>void d(),onSignOut:()=>void r(),twoFactor:{offerEmailedCodes:i?.mail??!1,needsPassword:i?.account.password??!0,onStartApp:e=>t.account.startAuthenticatorApp(e),onConfirmApp:e=>t.account.confirmAuthenticatorApp(e),onEmailedCodes:e=>t.account.turnOnEmailedCodes(e),onDone:n}})},ore=({className:e})=>(0,V.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`currentColor`,className:B(`size-4 shrink-0`,e),"aria-hidden":!0,children:(0,V.jsx)(`path`,{d:`M10.226 17.284c-2.965-.36-5.054-2.493-5.054-5.256 0-1.123.404-2.336 1.078-3.144-.292-.741-.247-2.314.09-2.965.898-.112 2.111.36 2.83 1.01.853-.269 1.752-.404 2.853-.404 1.1 0 1.999.135 2.807.382.696-.629 1.932-1.1 2.83-.988.315.606.36 2.179.067 2.942.72.854 1.101 2 1.101 3.167 0 2.763-2.089 4.852-5.098 5.234.763.494 1.28 1.572 1.28 2.807v2.336c0 .674.561 1.056 1.235.786 4.066-1.55 7.255-5.615 7.255-10.646C23.5 6.188 18.334 1 11.978 1 5.62 1 .5 6.188.5 12.545c0 4.986 3.167 9.12 7.435 10.669.606.225 1.19-.18 1.19-.786V20.63a2.9 2.9 0 0 1-1.078.224c-1.483 0-2.359-.808-2.987-2.313-.247-.607-.517-.966-1.034-1.033-.27-.023-.359-.135-.359-.27 0-.27.45-.471.898-.471.652 0 1.213.404 1.797 1.235.45.651.921.943 1.483.943.561 0 .92-.202 1.437-.719.382-.381.674-.718.944-.943`})}),sre=({id:e,className:t})=>e===`github`?(0,V.jsx)(ore,{className:t}):null,cre=()=>(0,V.jsxs)(`div`,{className:`my-4 flex items-center gap-3 text-xs text-muted-foreground`,children:[(0,V.jsx)(`span`,{className:`h-px flex-1 bg-border`}),`or`,(0,V.jsx)(`span`,{className:`h-px flex-1 bg-border`})]}),lre=({onSubmit:e,busy:t,error:n,workspace:r,notice:i,methods:a=[`password`],onSendCode:s,onPasskey:c,passkeyDomains:l=[],forgotPassword:u,providers:d=[],onContinueWith:f,signUp:p,onBrowse:m})=>{let[h,g]=(0,o.useState)(``),[_,v]=(0,o.useState)(``),y=(0,o.useRef)(null),b=a.includes(`password`),x=a.includes(`emailCode`)&&s!==void 0,S=a.includes(`passkey`)&&c!==void 0,C=f?d:[],w=()=>{y.current?.reportValidity()&&s?.(h.trim())};return(0,V.jsxs)(Oh,{title:`Sign in to Protobase`,description:r,children:[i&&(0,V.jsx)(`p`,{role:`status`,className:`mb-4 rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:i}),(C.length>0||S)&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[C.map(e=>(0,V.jsxs)(U,{onClick:()=>f?.(e.id),disabled:t,className:`min-h-10 w-full`,children:[(0,V.jsx)(sre,{id:e.id}),`Continue with `,e.name]},e.id)),S&&(0,V.jsxs)(U,{onClick:()=>c?.(),disabled:t,className:`min-h-10 w-full`,children:[(0,V.jsx)(_t,{className:`size-4`}),`Sign in with a passkey`]}),S&&l.slice(1).map(e=>(0,V.jsxs)(U,{variant:`ghost`,size:`sm`,onClick:()=>c?.(e),disabled:t,className:`w-full`,children:[`Use a passkey made for `,e]},e))]}),b||x?(0,V.jsx)(cre,{}):n&&(0,V.jsx)(`p`,{role:`alert`,className:`mt-4 text-xs font-medium text-danger-text`,children:n})]}),(b||x)&&(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),b?e(h.trim(),_):w()},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,V.jsx)(sd,{ref:y,type:`email`,name:`email`,autoComplete:`username webauthn`,required:!0,autoFocus:!0,value:h,invalid:!!n,onChange:e=>g(e.target.value),className:`min-h-6`})]}),b&&(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Password`,(0,V.jsx)(sd,{type:`password`,name:`password`,autoComplete:`current-password`,required:!0,value:_,invalid:!!n,onChange:e=>v(e.target.value),className:`min-h-6`})]}),n&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:n}),b&&(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:t,className:`min-h-10`,children:`Sign in`}),x&&(0,V.jsxs)(U,{variant:b?`secondary`:`primary`,type:b?`button`:`submit`,onClick:b?w:void 0,loading:t&&!b,disabled:t,className:`min-h-10`,children:[(0,V.jsx)(Bt,{className:`size-4`}),`Email me a sign-in code`]}),b&&u&&(0,V.jsx)(du,{to:u,className:`self-center font-medium text-primary-text hover:underline`,children:`Forgot password?`})]}),p&&(0,V.jsxs)(`p`,{className:`mt-4 text-center text-muted-foreground`,children:[`New here?`,` `,(0,V.jsx)(du,{to:p,className:`font-medium text-primary-text hover:underline`,children:`Create an account`})]}),m&&(0,V.jsx)(`button`,{type:`button`,onClick:m,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:text-foreground hover:underline`,children:`Continue without signing in`})]})},ure=({workspace:e,notice:t,forgotPassword:n,signUp:r,onBrowse:i,onCodeSent:a,error:s})=>{let{signIn:c,signInSocial:l,signInProviders:u,signInMethods:d,passkeyDomains:f,sendSignInCode:p,signInWithPasskey:m}=H(),[h,g]=(0,o.useState)(!1),[_,v]=(0,o.useState)(s),y=async(e,t)=>{g(!0),v(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;v(t(e)),g(!1)}};return(0,V.jsx)(lre,{busy:h,error:_,workspace:e,notice:t,methods:d,forgotPassword:n,signUp:r,onBrowse:i,providers:u,onContinueWith:e=>void y(()=>l(e),Sd),passkeyDomains:f,onPasskey:e=>void y(()=>m(e),xd),onSendCode:e=>void y(async()=>{await p(e),a(e)},xd),onSubmit:(e,t)=>void y(()=>c(e,t),Sd)})},dre=({email:e,onBack:t,...n})=>(0,V.jsx)(Ah,{title:`Check your email`,description:`Enter the code we sent to create your account.`,explanation:(0,V.jsxs)(V.Fragment,{children:[`A 6-digit code is on its way to `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),`. It works for 5 minutes, once. If the address has an account already, the email says so instead.`]}),submitLabel:`Continue`,onChangeAddress:t,changeAddressLabel:`Use another address`,...n}),fre=({email:e,onSubmit:t,onBack:n,methods:r,busy:i,error:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),d=(0,o.useId)(),f=r.includes(`password`),p=r.includes(`emailCode`);return(0,V.jsxs)(Oh,{title:`Your details`,description:`One last step to create your account.`,children:[(0,V.jsxs)(`p`,{className:`mb-4 text-muted-foreground`,children:[`The code was right: the account is for `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:e}),`.`]}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t({name:s.trim(),...f&&l&&{password:l}})},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Your name`,(0,V.jsx)(sd,{name:`name`,autoComplete:`name`,required:!0,autoFocus:!0,maxLength:200,value:s,onChange:e=>c(e.target.value),className:`min-h-6`})]}),f&&(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[p?`Password (optional)`:`Password`,(0,V.jsx)(sd,{type:`password`,name:`password`,autoComplete:`new-password`,"aria-describedby":d,required:!p,minLength:12,maxLength:128,value:l,onChange:e=>u(e.target.value),className:`min-h-6`})]}),(0,V.jsxs)(`p`,{id:d,className:`text-xs text-muted-foreground`,children:[`At least `,12,` characters.`,p&&` Without one, you sign in with a code we email you.`]})]}),a&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Create account`}),(0,V.jsx)(U,{variant:`ghost`,onClick:n,className:`min-h-10`,children:`Use another address`})]})]})},pre=({onSubmit:e,onSignIn:t,onBrowse:n,busy:r,error:i,workspace:a})=>{let[s,c]=(0,o.useState)(``);return(0,V.jsxs)(Oh,{title:`Create an account`,description:a,children:[(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:t=>{t.preventDefault(),e(s.trim())},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Email`,(0,V.jsx)(sd,{type:`email`,name:`email`,autoComplete:`email`,required:!0,autoFocus:!0,value:s,invalid:!!i,onChange:e=>c(e.target.value),className:`min-h-6`})]}),(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`We email you a code to make sure the address is yours.`}),i&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,V.jsxs)(U,{variant:`primary`,type:`submit`,loading:r,className:`min-h-10`,children:[(0,V.jsx)(Bt,{className:`size-4`}),`Email me a code`]}),(0,V.jsxs)(`p`,{className:`text-center text-muted-foreground`,children:[`Have an account?`,` `,(0,V.jsx)(`button`,{type:`button`,onClick:t,className:`font-medium text-primary-text hover:underline`,children:`Sign in`})]})]}),n&&(0,V.jsx)(`button`,{type:`button`,onClick:n,className:`mt-4 w-full text-center font-medium text-muted-foreground hover:text-foreground hover:underline`,children:`Continue without an account`})]})},mre=({workspace:e,email:t,ticket:n,onCodeSent:r,onVerified:i,onBack:a,onSignIn:s,onBrowse:c})=>{let{signInMethods:l,sendSignUpCode:u,verifySignUpCode:d,signUp:f}=H(),[p,m]=(0,o.useState)(!1),[h,g]=(0,o.useState)(),[_,v]=(0,o.useState)(),y=async e=>{m(!0),g(void 0),v(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;g(xd(e))}m(!1)};return t===void 0?(0,V.jsx)(pre,{workspace:e,busy:p,error:h,onSignIn:s,onBrowse:c,onSubmit:e=>void y(async()=>{await u(e),r(e)})}):n===void 0?(0,V.jsx)(dre,{email:t,busy:p,error:h,notice:_,onBack:a,onSubmit:e=>void y(async()=>i(await d(t,e))),onResend:()=>void y(async()=>{await u(t),v(`A new code is on its way. Only the newest one works.`)})}):(0,V.jsx)(fre,{email:t,methods:l,busy:p,error:h,onBack:a,onSubmit:e=>void y(()=>f({ticket:n,...e}))})},Mh=`staff-sign-in`,Nh=`staff-error`,hre=e=>{let t=new URL(e).searchParams,n=t.get(Nh);if(!t.has(`staff-sign-in`)&&!n)return;let r=t.has(Mh);return{email:r&&t.get(`email`)||``,reason:r&&t.get(`reason`)||``,...n&&{error:n}}},Ph=e=>{let t=new URL(e);if(t.searchParams.has(`staff-sign-in`))for(let e of[Mh,`email`,`reason`])t.searchParams.delete(e);return t.searchParams.delete(Nh),`${t.pathname}${t.search}${t.hash}`},gre=10,_re=({operator:e,email:t=``,reason:n=``,onSubmit:r,onBack:i,busy:a,error:s})=>{let[c,l]=(0,o.useState)(t),[u,d]=(0,o.useState)(n);return e?(0,V.jsx)(Oh,{title:`Sign in as a person`,description:`For staff of ${e}, to help someone with this app.`,children:(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),r(c.trim(),u.trim())},children:[(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Their email`,(0,V.jsx)(sd,{type:`email`,name:`email`,required:!0,autoFocus:!t,value:c,onChange:e=>l(e.target.value),className:`min-h-6`})]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[`Reason`,(0,V.jsx)(`textarea`,{name:`reason`,required:!0,minLength:gre,rows:3,value:u,placeholder:`Ticket 4211: the invoice totals look wrong`,onChange:e=>d(e.target.value),className:B(`resize-y rounded-md border bg-background px-2.5 py-1.5 font-normal shadow-sm outline-none placeholder:text-faint-foreground focus:border-primary focus:ring-2 focus:ring-primary/20`,s?`border-danger`:`border-border-strong`)})]}),(0,V.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`You sign in at `,e,` with a passkey or a second step. The session is short, shows a banner, and cannot change their sign-in. The app's admins see who signed in as whom, and why.`]}),s&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:s}),(0,V.jsxs)(U,{variant:`primary`,type:`submit`,loading:a,className:`min-h-10`,children:[`Continue with `,e]}),(0,V.jsx)(U,{variant:`ghost`,onClick:i,className:`min-h-10`,children:`Back to sign in`})]})}):(0,V.jsxs)(Oh,{title:`Staff sign-in`,description:`Staff of the team that runs this app cannot sign in as people here.`,children:[s&&(0,V.jsx)(`p`,{role:`alert`,className:`mb-4 text-xs font-medium text-danger-text`,children:s}),(0,V.jsx)(U,{variant:`primary`,className:`min-h-10 w-full`,onClick:i,children:`Back to sign in`})]})},vre=({link:e,onBack:t})=>{let{session:n,staffSignIn:r}=H(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(e.error&&wd(e.error)),l=async(e,t)=>{a(!0),c(void 0);try{let r=`${window.location.origin}${Ph(window.location.href)}`;window.location.assign(await n.staff.start({email:e,reason:t,callbackURL:r}))}catch(e){if(!(e instanceof pc))throw e;c(wd(e)),a(!1)}};return(0,V.jsx)(_re,{operator:r,email:e.email,reason:e.reason,busy:i,error:s,onBack:t,onSubmit:(e,t)=>void l(e,t)})},Fh=({checked:e,indeterminate:t,onChange:n,label:r,disabled:i,className:a})=>(0,V.jsx)(`button`,{type:`button`,role:`checkbox`,"aria-checked":t?`mixed`:e,"aria-label":r,disabled:i,onClick:()=>n?.(!e),className:B(`relative inline-flex size-4 shrink-0 items-center justify-center rounded border transition-colors after:absolute after:-inset-1 after:content-[""] pointer-coarse:after:-inset-3.5`,e||t?`border-primary bg-primary text-primary-foreground`:`border-border-strong bg-background hover:border-faint-foreground`,a),children:t?(0,V.jsx)(Wt,{className:`size-3`,strokeWidth:3}):e&&(0,V.jsx)(ge,{className:`size-3`,strokeWidth:3})}),yre={totp:`Enter the 6-digit code from your authenticator app.`,otp:`Enter the 6-digit code we emailed you. It works for 5 minutes.`,backup:`Enter one of the backup codes you saved when you set up the authenticator app. Each works once.`},bre=({methods:e,onVerify:t,onSendCode:n,onBack:r,busy:i,error:a,codeSent:s,initialStep:c})=>{let[l,u]=(0,o.useState)(c??(e.includes(`totp`)?`totp`:`otp`)),[d,f]=(0,o.useState)(``),[p,m]=(0,o.useState)(!1),h=l===`otp`&&!s,g=e=>{u(e),f(``),e===`otp`&&!s&&n()};return(0,V.jsxs)(Oh,{title:`Two-factor authentication`,description:`One more step to sign in.`,children:[h?(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`We email you a code to finish signing in.`}),a&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,V.jsx)(U,{variant:`primary`,loading:i,onClick:n,className:`min-h-10`,children:`Email me a code`})]}):(0,V.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),t({method:l,code:d.trim(),trustDevice:p})},children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:yre[l]}),(0,V.jsxs)(`label`,{className:`flex flex-col gap-1.5 font-medium`,children:[l===`backup`?`Backup code`:`Code`,l===`backup`?(0,V.jsx)(sd,{name:`code`,autoComplete:`off`,spellCheck:!1,required:!0,autoFocus:!0,value:d,invalid:!!a,onChange:e=>f(e.target.value),className:`min-h-6 font-mono`}):(0,V.jsx)(If,{name:`code`,required:!0,autoFocus:!0,value:d,invalid:!!a,onChange:f})]}),(0,V.jsxs)(`label`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(Fh,{checked:p,onChange:m,label:`Trust this browser`}),`Don't ask again in this browser for 30 days`]}),a&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:a}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:i,className:`min-h-10`,children:`Verify`})]}),(0,V.jsxs)(`div`,{className:`mt-4 flex flex-col items-center gap-2 border-t pt-4`,children:[l!==`totp`&&e.includes(`totp`)&&(0,V.jsx)(`button`,{type:`button`,onClick:()=>g(`totp`),className:`font-medium text-primary-text hover:underline`,children:`Use the authenticator app`}),l!==`otp`&&e.includes(`otp`)&&(0,V.jsx)(`button`,{type:`button`,onClick:()=>g(`otp`),className:`font-medium text-primary-text hover:underline`,children:`Email me a code instead`}),l!==`backup`&&e.includes(`totp`)&&(0,V.jsx)(`button`,{type:`button`,onClick:()=>g(`backup`),className:`font-medium text-primary-text hover:underline`,children:`Use a backup code`}),(0,V.jsx)(`button`,{type:`button`,onClick:r,className:`font-medium text-muted-foreground hover:underline`,children:`Back to sign in`})]})]})},xre=({methods:e,onBack:t})=>{let{verifyTwoFactor:n,session:r}=H(),[i,a]=(0,o.useState)(!1),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(!1),d=async e=>{a(!0),c(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;c(xd(e))}a(!1)};return(0,V.jsx)(bre,{methods:e,busy:i,error:s,codeSent:l,onBack:t,onVerify:e=>void d(()=>n(e)),onSendCode:()=>void d(async()=>{await r.sendTwoFactorCode(),u(!0)})})},Ih=()=>{let{path:e,params:t,basePath:n,navigate:r}=wh(),i=(0,o.useMemo)(()=>ws(e,t),[e,t]),a=jd(new URL(t.size>0?`${e}?${t}`:e,`http://local`).href),s=i?i.next:a,c=(0,o.useCallback)((e=`sign-in`,t)=>r(Cs({step:e,next:s}),t),[r,s]);return{address:i,next:s,open:c,link:(0,o.useCallback)((e=`sign-in`,t)=>({href:`${n}${Cs({step:e,next:s})}`,onFollow:()=>c(e,t)}),[n,s,c]),leave:(0,o.useCallback)(()=>r(s??`/`,{replace:!0}),[r,s])}},Sre=e=>{let t=new URL(e),n=t.searchParams.get(`token`);return t.pathname.endsWith(`/-/invitation`)&&n?{token:n}:void 0},Cre=e=>`${new URL(e).pathname.slice(0,-13)}/`,Lh=`/-/organizations`,Rh=`/-/organization`,zh=`/-/organization/members`,Bh=`/-/organization/invitations`,wre={[Lh]:`Organizations`,[Rh]:`Organization`,[zh]:`Members`,[Bh]:`Invitations`},Vh={owner:`Owner`,admin:`Admin`,member:`Member`},Hh=(e,t)=>e.find(e=>e.name===t)?.label??t,Uh=e=>e?.role===`owner`||e?.role===`admin`,Tre=(e,t,n)=>{let r=(n,r,i,a)=>({id:n,label:r,icon:i,href:`${e}${a}`,active:t===a});return[r(`organizations`,`Organizations`,Xt,Lh),...n?.organization?[r(`organization`,`Organization`,ue,Rh)]:[],...Uh(n)?[r(`members`,`Members`,Jn,zh),r(`invitations`,`Invitations`,Bt,Bh)]:[]]},Wh=(e,t)=>{let n=[...t?.globalRoles??[],...t?.appRoles??[]],r=e.filter(e=>e.membership).map(e=>e.name);if(n.includes(`admin`))return new Set(r);let i=n.flatMap(t=>e.find(e=>e.name===t)?.grants??[]);return new Set([...n,...i].filter(e=>r.includes(e)))},Gh=()=>{let[e,t]=(0,o.useState)(!1),[n,r]=(0,o.useState)();return{busy:e,error:n,run:async e=>{t(!0),r(void 0);try{await e()}catch(e){if(!(e instanceof pc))throw e;r(xd(e))}t(!1)},setError:r}},Ere=({token:e,preview:t,onDone:n})=>{let{session:r,signInMethods:i,recheck:a}=H(),[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(``),{busy:d,error:f,run:p}=Gh(),m=i.includes(`password`),h=i.includes(`emailCode`),g=()=>p(async()=>{await r.organizations.signUpFromInvitation(e,{name:s.trim(),...m&&l&&{password:l}}),n(),a()});return(0,V.jsxs)(`form`,{className:`flex flex-col gap-3`,onSubmit:e=>{e.preventDefault(),g()},children:[(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Make your account for `,t.email,` to join.`]}),f&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:f}),(0,V.jsx)(sd,{"aria-label":`Your name`,placeholder:`Your name`,autoComplete:`name`,value:s,onChange:e=>c(e.target.value)}),m&&(0,V.jsx)(sd,{"aria-label":`Password`,type:`password`,autoComplete:`new-password`,placeholder:h?`Password (optional, 12+ characters)`:`Password (12+ characters)`,value:l,onChange:e=>u(e.target.value)}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:d,disabled:!s.trim()||m&&!h&&l.length<12,children:`Create account and join`})]})},Dre=({token:e,onDone:t,signIn:n})=>{let{session:r,state:i,signOut:a,organizations:s}=H(),[c,l]=(0,o.useState)(),[u,d]=(0,o.useState)(),{busy:f,error:p,run:m}=Gh();if((0,o.useEffect)(()=>{r.organizations.invitation(e).then(l,e=>d(e instanceof pc?xd(e):`This invitation link is not valid`))},[r,e]),u)return(0,V.jsx)(Oh,{title:`Invitation`,description:u,children:(0,V.jsx)(U,{className:`w-full`,onClick:t,children:`Go to the app`})});if(!c)return(0,V.jsx)(Oh,{title:`Invitation`,children:(0,V.jsxs)(`div`,{className:`flex items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})});let h=c.appRoles.map(e=>Hh(s?.roles??[],e)),g=`${c.inviter.name} invites you to ${c.organization.name} as ${Vh[c.role].toLowerCase()}${h.length>0?`, with ${h.join(`, `)}`:``}.`,_=i.kind===`signed-in`?i.user:void 0;return _&&_.email.toLowerCase()!==c.email.toLowerCase()?(0,V.jsxs)(Oh,{title:`Join ${c.organization.name}`,description:g,children:[(0,V.jsxs)(`p`,{className:`mb-3 text-muted-foreground`,children:[`This invitation is for `,c.email,`, and you are signed in as `,_.email,`.`]}),(0,V.jsx)(U,{className:`w-full`,onClick:()=>void a(),children:`Sign out to accept it`})]}):(0,V.jsx)(Oh,{title:`Join ${c.organization.name}`,description:g,children:_?(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[p&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:p}),(0,V.jsxs)(U,{variant:`primary`,className:`w-full`,loading:f,onClick:()=>void m(async()=>{await r.organizations.accept(e),t()}),children:[`Join `,c.organization.name]})]}):c.hasAccount?(0,V.jsxs)(du,{to:n,className:B(Cf({variant:`primary`}),`w-full`),children:[`Sign in as `,c.email,` to join`]}):(0,V.jsx)(Ere,{token:e,preview:c,onDone:t})})},Ore=`modulepreload`,kre=function(e){return`/`+e},Kh={},Are=function(e){return e.pathname.endsWith(`.css`)},qh=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=kre(t,n);let r=s(t);if(r.href in Kh)return;Kh[r.href]=!0;let i=Are(r);if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}if((i?e.styles:e.all).has(r.href))return;let o=document.createElement(`link`);if(o.rel=i?`stylesheet`:Ore,i||(o.as=`script`),o.crossOrigin=``,o.href=r.href,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),i)return new Promise((e,t)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>t(Error(`Unable to preload CSS for ${r}`)))})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Jh,Yh,jre=({dsn:e,environment:t})=>(Jh??=qh(()=>import(`./prod-YZ9ZMG1O.js`).then(n=>{n.init({dsn:e,...t&&{environment:t},integrations:e=>e.filter(e=>e.name!==`BrowserSession`),beforeSend:e=>Ko(e)}),Yh=(e,t)=>n.captureException(e,t?{contexts:{react:{componentStack:t}}}:void 0)}),[]),Jh),Xh=(e,t)=>Yh?.(e,t??void 0),Zh=({children:e})=>(0,V.jsx)(`div`,{role:`alert`,className:`rounded-lg border border-dashed border-warning bg-warning-soft p-3 text-warning-text`,children:e}),Qh=class extends o.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e,t){Xh(e,t.componentStack)}render(){return this.state.failed?this.props.fallback===void 0?(0,V.jsxs)(Zh,{children:[this.props.name,` could not be drawn.`]}):this.props.fallback:this.props.children}},Mre=/^[A-Z][A-Za-z0-9]*$/,Nre=e=>typeof e==`function`||typeof e==`object`&&!!e&&`$$typeof`in e,$h=e=>{let t=e.default??{},n=Object.entries(e).filter(e=>e[0]!=="default"&&Mre.test(e[0])&&Nre(e[1]));if(n.length===0)return t;for(let[e,r]of n)if(t.components&&Object.hasOwn(t.components,e)&&t.components[e]!==r)throw Error(`The component "${e}" is exported by name and given in components as another one; keep the export`);return{...t,components:{...t.components,...Object.fromEntries(n)}}},eg=class extends Error{name=`UiConflictError`},Pre=e=>Object.keys(e).some(e=>e==="default"||/^[A-Z]/.test(e))?$h(e):e,tg=(e,t)=>[...(e.extends??[]).map(Pre).flatMap((e,n)=>tg(e,e.name??`${t} extends[${n}]`)),{ui:e,label:t}],ng=(e,t,n)=>{let r={},i=new Map;for(let{ui:a,label:o}of t)for(let[t,s]of Object.entries(n(a)??{})){if(Object.hasOwn(r,t)&&r[t]!==s)throw new eg(`${e} "${t}" is defined twice, by ${i.get(t)} and by ${o}; rename one of them`);r[t]=s,i.set(t,i.get(t)??o)}return r},rg=e=>e.length<=1?e[0]:()=>e.map((e,t)=>(0,V.jsx)(e,{},t)),Fre=e=>e.length<=1?e[0]:({children:t,...n})=>e.reduceRight((e,t)=>(0,V.jsx)(t,{...n,children:e}),t),ig=(...e)=>{let t=e.flatMap((e,t)=>tg(e,e.name??`UI config ${t+1}`)),n=ng(`The component`,t,e=>e.components),r=ng(`The action handler`,t,e=>e.actions),i=ng(`The field type`,t,e=>e.fields),a=rg(t.flatMap(({ui:e})=>e.shell?.actions?[e.shell.actions]:[])),o=rg(t.flatMap(({ui:e})=>e.shell?.rightPanel?[e.shell.rightPanel]:[])),s=t.findLast(({ui:e})=>e.shell?.logo)?.ui.shell?.logo,c=Fre(t.flatMap(({ui:e})=>e.beforeSignIn?[e.beforeSignIn]:[])),l=e.at(-1)?.name;return{...l&&{name:l},components:n,actions:r,...Object.keys(i).length>0&&{fields:i},...(a||o||s)&&{shell:{...a&&{actions:a},...o&&{rightPanel:o},...s&&{logo:s}}},...c&&{beforeSignIn:c}}},ag=(e,t)=>{let n=ig(e??{}),r=[],i=[];for(let e of t){if(e.kind===`off`){i.push(e);continue}try{ig(...r,e.ui,n),r.push(e.ui)}catch(t){if(!(t instanceof eg))throw t;i.push({kind:`off`,url:e.plugin.url,name:e.plugin.name,reason:t.message})}}return{ui:r.length===0?n:ig(...r,n),off:i}},og=e=>typeof e==`string`&&e.trim()!==``,Ire=e=>{if(typeof e!=`object`||!e||Array.isArray(e))return{problem:`its plugin.json is not an object`};let{name:t,version:n,api:r,protobase:i,entry:a,css:o}=e;return og(t)?Number.isInteger(r)?og(i)?og(a)?o!==void 0&&!og(o)?{problem:`its plugin.json names a stylesheet that is no URL`}:n!==void 0&&!og(n)?{problem:`its plugin.json has a version that is no text`}:{manifest:{name:t,api:r,protobase:i,entry:a,...n!==void 0&&{version:n},...o!==void 0&&{css:o}}}:{problem:`its plugin.json names no module`}:{problem:`its plugin.json names no Protobase versions`}:{problem:`its plugin.json names no plugin API`}:{problem:`its plugin.json names no plugin`}},sg=(0,o.createContext)(null),Lre=sg.Provider,Rre=()=>{let e=(0,o.useContext)(sg);if(!e)throw Error(`usePlugin is for the components of a plugin the app loaded`);return e},cg=(e,t,n)=>{let r=n=>(0,V.jsx)(Lre,{value:e,children:(0,V.jsx)(t,{...n})});return r.displayName=`${e.name}:${n}`,r},zre=(e,t,n)=>({of:n.of,display:cg(e,n.display,`fields.${t}.display`),...n.editor&&{editor:cg(e,n.editor,`fields.${t}.editor`)},...n.cell&&{cell:cg(e,n.cell,`fields.${t}.cell`)}}),Bre=(e,t)=>{let n=ig({...$h(t),name:e.name}),r=Object.fromEntries(Object.entries(n.components??{}).map(([t,n])=>[t,cg(e,n,t)])),i=n.fields&&Object.fromEntries(Object.entries(n.fields).map(([t,n])=>[t,zre(e,t,n)])),a=n.shell&&{...n.shell.actions&&{actions:cg(e,n.shell.actions,`shell.actions`)},...n.shell.rightPanel&&{rightPanel:cg(e,n.shell.rightPanel,`shell.rightPanel`)}},o=n.beforeSignIn&&cg(e,n.beforeSignIn,`beforeSignIn`);return{name:e.name,components:r,...n.actions&&{actions:n.actions},...i&&{fields:i},...a&&{shell:a},...o&&{beforeSignIn:o}}},lg={name:`@protobase/ui`,version:`0.21.10`,description:`The Protobase admin app and the React hooks and components for custom UI.`,license:`Apache-2.0`,repository:{type:`git`,url:`git+https://github.com/PrototeamHQ/protobase.git`,directory:`packages/ui`},homepage:`https://docs.protobase.net`,type:`module`,protobase:{pluginApi:1},sideEffects:[`*.css`,`./dist/app/main.js`],engines:{node:`>=22.12.0`},exports:{".":`./src/index.ts`,"./theme.css":`./src/theme.css`,"./styles.css":`./src/styles.css`},types:`./src/index.ts`,files:[`dist`],scripts:{build:`tsdown && protobase build-shell dist/shell`,prepack:`tsdown && protobase build-shell dist/shell`},publishConfig:{access:`public`,exports:{".":`./dist/index.js`,"./theme.css":`./dist/theme.css`,"./styles.css":`./dist/styles.css`},types:`./dist/index.d.ts`},dependencies:{"@dnd-kit/core":`^6.3.1`,"@dnd-kit/sortable":`^10.0.0`,"@protobase/client":`workspace:*`,"@protobase/layout":`workspace:*`,"@protobase/schema":`workspace:*`,"@sentry/browser":`^11.7.0`,"@tanstack/react-query":`^5.104.1`,"@tanstack/react-table":`^9.2.6`,"altcha-lib":`^2.6.0`,dompurify:`^3.4.17`,fflate:`^0.8.3`,"lucide-react":`^1.52.0`,"maplibre-gl":`^6.14.0`,marked:`^18.1.1`,pmtiles:`^4.5.0`,react:`^19.3.0`,"react-dom":`^19.3.0`,"react-map-gl":`^8.1.3`,recharts:`^3.10.1`,tailwindcss:`^4.3.3`,thumbhash:`^0.1.1`,uqr:`^0.1.3`}},ug=lg.protobase.pluginApi,dg=lg.version,Vre={readJson:async e=>{let t=await fetch(e,{cache:`no-cache`,credentials:`same-origin`});return t.ok?{json:await t.json()}:{status:t.status}},addStylesheet:e=>{if([...document.querySelectorAll(`link[rel="stylesheet"]`)].some(t=>t.href===e))return;let t=document.createElement(`link`);t.rel=`stylesheet`,t.href=e,document.head.append(t)},importModule:e=>qh(()=>import(e),[])},Hre={api:ug,version:dg},Ure=e=>e instanceof Error?e.message:String(e),Wre=async(e,t,n,r=Hre)=>{let i=new URL(e.url,n).href,a=(e,t)=>({kind:`off`,url:i,...t&&{name:t},reason:e}),o;try{let n=await t.readJson(i);if(`status`in n)return a(`its plugin.json answered ${n.status}`);let s=Ire(n.json);if(`problem`in s)return a(s.problem);let{manifest:c}=s;o=c.name;let l=Lo(c,r);if(l)return a(l,o);c.css&&t.addStylesheet(new URL(c.css,i).href);let u=await t.importModule(new URL(c.entry,i).href),d={name:o,...c.version&&{version:c.version},url:i,settings:e.settings??{}};return{kind:`loaded`,plugin:d,ui:Bre(d,u)}}catch(e){return a(`it could not be loaded: ${Ure(e)}`,o)}},Gre=e=>{let t=new Map;return{load:n=>{let r=JSON.stringify(n),i=t.get(r);if(i)return i;let a=Wre(n,e,window.location.href);return t.set(r,a),a}}},fg=(0,o.createContext)(null),Kre=({loader:e=Vre,children:t})=>{let n=(0,o.useMemo)(()=>Gre(e),[e]);return(0,V.jsx)(fg.Provider,{value:n,children:t})},pg=()=>{let e=(0,o.useContext)(fg);if(!e)throw Error(`usePluginSource must be used inside PluginSourceProvider`);return e},qre=1e4,mg=[],hg=(e,t)=>{let n=JSON.stringify(e),[r,i]=(0,o.useState)({key:`[]`,loads:mg,settled:!0});return(0,o.useEffect)(()=>{if(e.length===0)return;let r=!0,a=!1,o=e.map(()=>void 0),s=()=>{if(!r)return;let t=o.filter(e=>e!==void 0);i({key:n,loads:t,settled:a||t.length===e.length})},c=setTimeout(()=>{a=!0,s()},qre);return e.forEach((e,n)=>{t.load(e).then(e=>{o[n]=e,s()})}),()=>{r=!1,clearTimeout(c)}},[n,t]),e.length===0?{loads:mg,settled:!0}:r.key===n?r:{loads:mg,settled:!1}},Jre=({children:e})=>{let{state:t,beforeSignIn:n,adoptSession:r}=H(),{path:i,params:a,navigate:s}=wh(),{loads:c,settled:l}=hg(n,pg()),u=(0,o.useMemo)(()=>ag(void 0,c).ui.beforeSignIn,[c]),d=(0,o.useCallback)(e=>{let t=new URLSearchParams(a);for(let n of e)t.delete(n);s(t.size>0?`${i}?${t}`:i,{replace:!0})},[i,a,s]);return t.kind!==`signed-out`&&t.kind!==`visitor`?e:l?u?(0,V.jsx)(Qh,{name:`beforeSignIn`,fallback:e,children:(0,V.jsx)(u,{signedIn:r,params:a,removeParams:d,children:e})}):e:(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})},Yre=()=>{let e=window.location.href,t=Yne(e);if(t)return{kind:`reset-password`,token:t.token};let n=hre(e);if(n)return{kind:`staff-sign-in`,link:n};let r=Sre(e);if(r)return{kind:`invitation`,token:r.token};let i=kd(e);if(i)return{kind:`provider-sign-in`,provider:i};let a=Ad(e);return a?{kind:`sign-in`,providerError:a}:{kind:`sign-in`}},gg=({to:e})=>{let{navigate:t}=wh();return(0,o.useEffect)(()=>t(e,{replace:!0}),[t,e]),null},Xre=({workspace:e,children:t})=>{let n=Zre(e,t);return(0,V.jsx)(Jre,{children:n})},Zre=(e,t)=>{let{state:n,recheck:r,passwordReset:i,signOut:a,signInProviders:s,canSignUp:c,browse:l}=H(),{path:u,params:d,basePath:f,navigate:p}=wh(),{address:m,next:h,open:g,link:_,leave:v}=Ih(),[y,b]=(0,o.useState)(Yre),[x,S]=(0,o.useState)(),[C,w]=(0,o.useState)(),[T,E]=(0,o.useState)(),D=new URL(`${f}${u}${d.size>0?`?${d}`:``}`,window.location.origin).href,O=(0,o.useCallback)(e=>{let t=e(D).slice(f.length);p(t.startsWith(`/`)?t:`/${t}`,{replace:!0})},[D,f,p]),k=n.kind===`signed-in`||n.kind===`two-factor`||n.kind===`setup-required`;(0,o.useEffect)(()=>{k&&(y.kind===`provider-sign-in`&&O(jd),(y.kind===`provider-sign-in`||y.kind===`sign-in`&&(y.notice||y.error||y.providerError))&&b({kind:`sign-in`}),S(void 0),w(void 0),E(void 0))},[k,y,O]);let A=m!==void 0&&Ad(D)!==void 0;(0,o.useEffect)(()=>{!k&&y.kind===`sign-in`&&y.providerError&&A&&O(jd)},[k,y,A,O]);let j=(0,o.useCallback)(e=>b({kind:`sign-in`,error:e}),[]),M=e=>{O(Xne),b(e)},N=async()=>{n.kind===`signed-in`&&await a(),M({kind:`sign-in`,notice:`Your password is changed. Sign in with the new one.`})},ee=()=>{b({kind:`sign-in`}),a().then(()=>g(`sign-in`,{replace:!0}))};switch(n.kind){case`loading`:return(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]});case`error`:return(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 flex-col items-center justify-center gap-3 p-8 text-center`,children:[(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`Cannot reach the server: `,n.message]}),(0,V.jsx)(U,{onClick:r,children:`Try again`})]});case`needs-admin`:return(0,V.jsx)(Kne,{onCheckAgain:r})}if(n.kind===`signed-in`&&m)return(0,V.jsx)(gg,{to:h??`/`});if(y.kind===`reset-password`)return(0,V.jsx)(nre,{token:y.token,onDone:()=>void N(),onRequestNewLink:i?()=>{b({kind:`sign-in`}),p(Cs({step:`forgot-password`}),{replace:!0})}:void 0,onBack:()=>M({kind:`sign-in`})});if(y.kind===`staff-sign-in`)return(0,V.jsx)(vre,{link:y.link,onBack:()=>{O(Ph),b({kind:`sign-in`})}});let P=n.kind===`signed-out`||n.kind===`visitor`;if(y.kind===`invitation`&&(n.kind===`signed-in`||P&&!m))return(0,V.jsx)(Dre,{token:y.token,onDone:()=>{O(Cre),b({kind:`sign-in`})},signIn:_()});if(n.kind===`signed-in`)return t;if(n.kind===`two-factor`)return(0,V.jsx)(xre,{methods:n.methods,onBack:ee});if(n.kind===`setup-required`)return(0,V.jsx)(are,{missing:n.missing},n.missing.join());if(y.kind===`provider-sign-in`)return(0,V.jsx)($ne,{provider:y.provider,workspace:e,onFailed:j});let te=y.kind===`sign-in`?y:{kind:`sign-in`};if(!m){let e=te.notice||te.error||te.providerError;return n.kind===`visitor`&&!e?t:(0,V.jsx)(gg,{to:Cs({next:h})})}let F={"sign-in":!0,"forgot-password":i,"email-code":x!==void 0,"sign-up":c,"sign-up-code":c&&C!==void 0,"sign-up-details":c&&T!==void 0}[m.step]?m.step:`sign-in`,ne=e=>()=>g(e,{replace:!0}),re=l&&(()=>{l(),v()});if(F===`forgot-password`)return(0,V.jsx)(Zne,{back:_(`sign-in`,{replace:!0})});if(F===`email-code`)return(0,V.jsx)(Wne,{email:x,onBack:ne(`sign-in`)});if(F===`sign-up`||F===`sign-up-code`||F===`sign-up-details`)return(0,V.jsx)(mre,{workspace:e,email:F===`sign-up`?void 0:C,ticket:F===`sign-up-details`?T:void 0,onCodeSent:e=>{w(e),E(void 0),g(`sign-up-code`)},onVerified:e=>{E(e),g(`sign-up-details`,{replace:!0})},onBack:ne(`sign-up`),onSignIn:()=>g(`sign-in`),onBrowse:re},F);let ie=te.providerError&&Ed(te.providerError,s.length===1?s[0].name:`the provider`),I=te.error??ie;return(0,V.jsx)(ure,{workspace:e,notice:te.notice,error:I,forgotPassword:i?_(`forgot-password`):void 0,onCodeSent:e=>{S(e),g(`email-code`)},signUp:c?_(`sign-up`):void 0,onBrowse:re},I)},_g=e=>[...e].reduce((e,t)=>(e*31+t.charCodeAt(0))%360,7),vg=e=>e.split(/[\s@.]+/).filter(Boolean).slice(0,2).map(e=>e[0].toUpperCase()).join(``),yg=e=>(e.role??`user`).split(`,`).map(e=>e.trim()),bg=e=>yg(e).includes(`admin`),Qre=e=>{let t=yg(e),n=t.includes(`admin`);return{name:e.name||e.email,email:e.email,initials:vg(e.name||e.email)||`?`,hue:_g(e.id||e.email),role:n?`Admin`:(t[0]??`user`).replace(/^./,e=>e.toUpperCase()),roleTone:n?`violet`:`blue`}},$re=3e4,eie=(e,t=Date.now())=>Math.max(1e3,Fl(e)-t-$re),xg=()=>{let{state:e,session:t}=H(),n=e.kind===`signed-in`,[r,i]=(0,o.useState)();return(0,o.useEffect)(()=>{if(!n)return;let e=!0,r,a=async n=>{let o=await t.token(),s=o!==void 0&&o===n?await t.token({refresh:!0}):o;e&&(i(s),s&&(r=setTimeout(()=>void a(s),eie(s))))};return a(),()=>{e=!1,clearTimeout(r)}},[t,n]),n?r:void 0},Sg=(e,t,n=!0)=>{let r=G(),i=Ao(t);return mh({queryKey:W.record(e,i),enabled:n,queryFn:()=>r.get(e,t)})},Cg=(e,t,n=!0)=>{let r=G(),i=Gp(),a=Ao(t);return mh({queryKey:W.record(e,a),enabled:n,queryFn:()=>r.get(e,t),placeholderData:()=>i.getQueryData(W.recordPreview(e,a))})},tie=e=>e.charAt(0).toUpperCase()+e.slice(1),K=e=>tie(e.replace(/(Id|Code|_id|_code)$/,``).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/_+/g,` `).trim().toLowerCase()||e);function nie(){var e=[...arguments];return(0,o.useMemo)(()=>t=>{e.forEach(e=>e(t))},e)}var wg=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function Tg(e){let t=Object.prototype.toString.call(e);return t===`[object Window]`||t===`[object global]`}function Eg(e){return`nodeType`in e}function Dg(e){return e?Tg(e)?e:Eg(e)?e.ownerDocument?.defaultView??window:window:window}function Og(e){let{Document:t}=Dg(e);return e instanceof t}function kg(e){return!Tg(e)&&e instanceof Dg(e).HTMLElement}function Ag(e){return e instanceof Dg(e).SVGElement}function jg(e){return e?Tg(e)?e.document:Eg(e)?Og(e)?e:kg(e)||Ag(e)?e.ownerDocument:document:document:document}var Mg=wg?o.useLayoutEffect:o.useEffect;function Ng(e){let t=(0,o.useRef)(e);return Mg(()=>{t.current=e}),(0,o.useCallback)(function(){var e=[...arguments];return t.current==null?void 0:t.current(...e)},[])}function rie(){let e=(0,o.useRef)(null);return[(0,o.useCallback)((t,n)=>{e.current=setInterval(t,n)},[]),(0,o.useCallback)(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[])]}function Pg(e,t){t===void 0&&(t=[e]);let n=(0,o.useRef)(e);return Mg(()=>{n.current!==e&&(n.current=e)},t),n}function Fg(e,t){let n=(0,o.useRef)();return(0,o.useMemo)(()=>{let t=e(n.current);return n.current=t,t},[...t])}function Ig(e){let t=Ng(e),n=(0,o.useRef)(null);return[n,(0,o.useCallback)(e=>{e!==n.current&&t?.(e,n.current),n.current=e},[])]}function Lg(e){let t=(0,o.useRef)();return(0,o.useEffect)(()=>{t.current=e},[e]),t.current}var Rg={};function zg(e,t){return(0,o.useMemo)(()=>{if(t)return t;let n=Rg[e]==null?0:Rg[e]+1;return Rg[e]=n,e+`-`+n},[e,t])}function Bg(e){return function(t){return[...arguments].slice(1).reduce((t,n)=>{let r=Object.entries(n);for(let[n,i]of r){let r=t[n];r!=null&&(t[n]=r+e*i)}return t},{...t})}}var Vg=Bg(1),Hg=Bg(-1);function iie(e){return`clientX`in e&&`clientY`in e}function Ug(e){if(!e)return!1;let{KeyboardEvent:t}=Dg(e.target);return t&&e instanceof t}function aie(e){if(!e)return!1;let{TouchEvent:t}=Dg(e.target);return t&&e instanceof t}function Wg(e){if(aie(e)){if(e.touches&&e.touches.length){let{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}if(e.changedTouches&&e.changedTouches.length){let{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return iie(e)?{x:e.clientX,y:e.clientY}:null}var Gg=Object.freeze({Translate:{toString(e){if(!e)return;let{x:t,y:n}=e;return`translate3d(`+(t?Math.round(t):0)+`px, `+(n?Math.round(n):0)+`px, 0)`}},Scale:{toString(e){if(!e)return;let{scaleX:t,scaleY:n}=e;return`scaleX(`+t+`) scaleY(`+n+`)`}},Transform:{toString(e){if(e)return[Gg.Translate.toString(e),Gg.Scale.toString(e)].join(` `)}},Transition:{toString(e){let{property:t,duration:n,easing:r}=e;return t+` `+n+`ms `+r}}}),Kg=`a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]`;function oie(e){return e.matches(Kg)?e:e.querySelector(Kg)}var sie={display:`none`};function cie(e){let{id:t,value:n}=e;return o.createElement(`div`,{id:t,style:sie},n)}function lie(e){let{id:t,announcement:n,ariaLiveType:r=`assertive`}=e;return o.createElement(`div`,{id:t,style:{position:`fixed`,top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:`hidden`,clip:`rect(0 0 0 0)`,clipPath:`inset(100%)`,whiteSpace:`nowrap`},role:`status`,"aria-live":r,"aria-atomic":!0},n)}function uie(){let[e,t]=(0,o.useState)(``);return{announce:(0,o.useCallback)(e=>{e!=null&&t(e)},[]),announcement:e}}var qg=(0,o.createContext)(null);function die(e){let t=(0,o.useContext)(qg);(0,o.useEffect)(()=>{if(!t)throw Error(`useDndMonitor must be used within a children of <DndContext>`);return t(e)},[e,t])}function fie(){let[e]=(0,o.useState)(()=>new Set),t=(0,o.useCallback)(t=>(e.add(t),()=>e.delete(t)),[e]);return[(0,o.useCallback)(t=>{let{type:n,event:r}=t;e.forEach(e=>e[n]?.call(e,r))},[e]),t]}var pie={draggable:`
|
|
8
8
|
To pick up a draggable item, press the space bar.
|
|
9
9
|
While dragging, use the arrow keys to move the item.
|
|
10
10
|
Press space again to drop the item in its new position, or press escape to cancel.
|
|
11
11
|
`},mie={onDragStart(e){let{active:t}=e;return`Picked up draggable item `+t.id+`.`},onDragOver(e){let{active:t,over:n}=e;return n?`Draggable item `+t.id+` was moved over droppable area `+n.id+`.`:`Draggable item `+t.id+` is no longer over a droppable area.`},onDragEnd(e){let{active:t,over:n}=e;return n?`Draggable item `+t.id+` was dropped over droppable area `+n.id:`Draggable item `+t.id+` was dropped.`},onDragCancel(e){let{active:t}=e;return`Dragging was cancelled. Draggable item `+t.id+` was dropped.`}};function hie(e){let{announcements:t=mie,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=pie}=e,{announce:a,announcement:s}=uie(),c=zg(`DndLiveRegion`),[l,u]=(0,o.useState)(!1);if((0,o.useEffect)(()=>{u(!0)},[]),die((0,o.useMemo)(()=>({onDragStart(e){let{active:n}=e;a(t.onDragStart({active:n}))},onDragMove(e){let{active:n,over:r}=e;t.onDragMove&&a(t.onDragMove({active:n,over:r}))},onDragOver(e){let{active:n,over:r}=e;a(t.onDragOver({active:n,over:r}))},onDragEnd(e){let{active:n,over:r}=e;a(t.onDragEnd({active:n,over:r}))},onDragCancel(e){let{active:n,over:r}=e;a(t.onDragCancel({active:n,over:r}))}}),[a,t])),!l)return null;let d=o.createElement(o.Fragment,null,o.createElement(cie,{id:r,value:i.draggable}),o.createElement(lie,{id:c,announcement:s}));return n?(0,nr.createPortal)(d,n):d}var Jg;(function(e){e.DragStart=`dragStart`,e.DragMove=`dragMove`,e.DragEnd=`dragEnd`,e.DragCancel=`dragCancel`,e.DragOver=`dragOver`,e.RegisterDroppable=`registerDroppable`,e.SetDroppableDisabled=`setDroppableDisabled`,e.UnregisterDroppable=`unregisterDroppable`})(Jg||={});function Yg(){}function Xg(e,t){return(0,o.useMemo)(()=>({sensor:e,options:t??{}}),[e,t])}function Zg(){var e=[...arguments];return(0,o.useMemo)(()=>[...e].filter(e=>e!=null),[...e])}var Qg=Object.freeze({x:0,y:0});function $g(e,t){return Math.sqrt((e.x-t.x)**2+(e.y-t.y)**2)}function gie(e,t){let n=Wg(e);if(!n)return`0 0`;let r={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return r.x+`% `+r.y+`%`}function e_(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return n-r}function _ie(e,t){let{data:{value:n}}=e,{data:{value:r}}=t;return r-n}function t_(e){let{left:t,top:n,height:r,width:i}=e;return[{x:t,y:n},{x:t+i,y:n},{x:t,y:n+r},{x:t+i,y:n+r}]}function n_(e,t){if(!e||e.length===0)return null;let[n]=e;return t?n[t]:n}function r_(e,t,n){return t===void 0&&(t=e.left),n===void 0&&(n=e.top),{x:t+e.width*.5,y:n+e.height*.5}}var i_=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e,i=r_(t,t.left,t.top),a=[];for(let e of r){let{id:t}=e,r=n.get(t);if(r){let n=$g(r_(r),i);a.push({id:t,data:{droppableContainer:e,value:n}})}}return a.sort(e_)},vie=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e,i=t_(t),a=[];for(let e of r){let{id:t}=e,r=n.get(t);if(r){let n=t_(r),o=i.reduce((e,t,r)=>e+$g(n[r],t),0),s=Number((o/4).toFixed(4));a.push({id:t,data:{droppableContainer:e,value:s}})}}return a.sort(e_)};function yie(e,t){let n=Math.max(t.top,e.top),r=Math.max(t.left,e.left),i=Math.min(t.left+t.width,e.left+e.width),a=Math.min(t.top+t.height,e.top+e.height),o=i-r,s=a-n;if(r<i&&n<a){let n=t.width*t.height,r=e.width*e.height,i=o*s,a=i/(n+r-i);return Number(a.toFixed(4))}return 0}var a_=e=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=e,i=[];for(let e of r){let{id:r}=e,a=n.get(r);if(a){let n=yie(a,t);n>0&&i.push({id:r,data:{droppableContainer:e,value:n}})}}return i.sort(_ie)};function bie(e,t){let{top:n,left:r,bottom:i,right:a}=t;return n<=e.y&&e.y<=i&&r<=e.x&&e.x<=a}var xie=e=>{let{droppableContainers:t,droppableRects:n,pointerCoordinates:r}=e;if(!r)return[];let i=[];for(let e of t){let{id:t}=e,a=n.get(t);if(a&&bie(r,a)){let n=t_(a).reduce((e,t)=>e+$g(r,t),0),o=Number((n/4).toFixed(4));i.push({id:t,data:{droppableContainer:e,value:o}})}}return i.sort(e_)};function Sie(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function o_(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Qg}function Cie(e){return function(t){return[...arguments].slice(1).reduce((t,n)=>({...t,top:t.top+e*n.y,bottom:t.bottom+e*n.y,left:t.left+e*n.x,right:t.right+e*n.x}),{...t})}}var wie=Cie(1);function s_(e){if(e.startsWith(`matrix3d(`)){let t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}if(e.startsWith(`matrix(`)){let t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function Tie(e,t,n){let r=s_(t);if(!r)return e;let{scaleX:i,scaleY:a,x:o,y:s}=r,c=e.left-o-(1-i)*parseFloat(n),l=e.top-s-(1-a)*parseFloat(n.slice(n.indexOf(` `)+1)),u=i?e.width/i:e.width,d=a?e.height/a:e.height;return{width:u,height:d,top:l,right:c+u,bottom:l+d,left:c}}var Eie={ignoreTransform:!1};function c_(e,t){t===void 0&&(t=Eie);let n=e.getBoundingClientRect();if(t.ignoreTransform){let{transform:t,transformOrigin:r}=Dg(e).getComputedStyle(e);t&&(n=Tie(n,t,r))}let{top:r,left:i,width:a,height:o,bottom:s,right:c}=n;return{top:r,left:i,width:a,height:o,bottom:s,right:c}}function l_(e){return c_(e,{ignoreTransform:!0})}function Die(e){let t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function Oie(e,t){return t===void 0&&(t=Dg(e).getComputedStyle(e)),t.position===`fixed`}function kie(e,t){t===void 0&&(t=Dg(e).getComputedStyle(e));let n=/(auto|scroll|overlay)/;return[`overflow`,`overflowX`,`overflowY`].some(e=>{let r=t[e];return typeof r==`string`&&n.test(r)})}function u_(e,t){let n=[];function r(i){if(t!=null&&n.length>=t||!i)return n;if(Og(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!kg(i)||Ag(i)||n.includes(i))return n;let a=Dg(e).getComputedStyle(i);return i!==e&&kie(i,a)&&n.push(i),Oie(i,a)?n:r(i.parentNode)}return e?r(e):n}function d_(e){let[t]=u_(e,1);return t??null}function f_(e){return!wg||!e?null:Tg(e)?e:Eg(e)?Og(e)||e===jg(e).scrollingElement?window:kg(e)?e:null:null}function p_(e){return Tg(e)?e.scrollX:e.scrollLeft}function m_(e){return Tg(e)?e.scrollY:e.scrollTop}function h_(e){return{x:p_(e),y:m_(e)}}var g_;(function(e){e[e.Forward=1]=`Forward`,e[e.Backward=-1]=`Backward`})(g_||={});function __(e){return!wg||!e?!1:e===document.scrollingElement}function v_(e){let t={x:0,y:0},n=__(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},r={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height};return{isTop:e.scrollTop<=t.y,isLeft:e.scrollLeft<=t.x,isBottom:e.scrollTop>=r.y,isRight:e.scrollLeft>=r.x,maxScroll:r,minScroll:t}}var Aie={x:.2,y:.2};function jie(e,t,n,r,i){let{top:a,left:o,right:s,bottom:c}=n;r===void 0&&(r=10),i===void 0&&(i=Aie);let{isTop:l,isBottom:u,isLeft:d,isRight:f}=v_(e),p={x:0,y:0},m={x:0,y:0},h={height:t.height*i.y,width:t.width*i.x};return!l&&a<=t.top+h.height?(p.y=g_.Backward,m.y=r*Math.abs((t.top+h.height-a)/h.height)):!u&&c>=t.bottom-h.height&&(p.y=g_.Forward,m.y=r*Math.abs((t.bottom-h.height-c)/h.height)),!f&&s>=t.right-h.width?(p.x=g_.Forward,m.x=r*Math.abs((t.right-h.width-s)/h.width)):!d&&o<=t.left+h.width&&(p.x=g_.Backward,m.x=r*Math.abs((t.left+h.width-o)/h.width)),{direction:p,speed:m}}function Mie(e){if(e===document.scrollingElement){let{innerWidth:e,innerHeight:t}=window;return{top:0,left:0,right:e,bottom:t,width:e,height:t}}let{top:t,left:n,right:r,bottom:i}=e.getBoundingClientRect();return{top:t,left:n,right:r,bottom:i,width:e.clientWidth,height:e.clientHeight}}function y_(e){return e.reduce((e,t)=>Vg(e,h_(t)),Qg)}function Nie(e){return e.reduce((e,t)=>e+p_(t),0)}function Pie(e){return e.reduce((e,t)=>e+m_(t),0)}function b_(e,t){if(t===void 0&&(t=c_),!e)return;let{top:n,left:r,bottom:i,right:a}=t(e);d_(e)&&(i<=0||a<=0||n>=window.innerHeight||r>=window.innerWidth)&&e.scrollIntoView({block:`center`,inline:`center`})}var Fie=[[`x`,[`left`,`right`],Nie],[`y`,[`top`,`bottom`],Pie]],x_=class{constructor(e,t){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;let n=u_(t),r=y_(n);this.rect={...e},this.width=e.width,this.height=e.height;for(let[e,t,i]of Fie)for(let a of t)Object.defineProperty(this,a,{get:()=>{let t=i(n),o=r[e]-t;return this.rect[a]+o},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}},S_=class{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(e=>this.target?.removeEventListener(...e))},this.target=e}add(e,t,n){var r;(r=this.target)==null||r.addEventListener(e,t,n),this.listeners.push([e,t,n])}};function Iie(e){let{EventTarget:t}=Dg(e);return e instanceof t?e:jg(e)}function C_(e,t){let n=Math.abs(e.x),r=Math.abs(e.y);return typeof t==`number`?Math.sqrt(n**2+r**2)>t:`x`in t&&`y`in t?n>t.x&&r>t.y:`x`in t?n>t.x:`y`in t&&r>t.y}var w_;(function(e){e.Click=`click`,e.DragStart=`dragstart`,e.Keydown=`keydown`,e.ContextMenu=`contextmenu`,e.Resize=`resize`,e.SelectionChange=`selectionchange`,e.VisibilityChange=`visibilitychange`})(w_||={});function T_(e){e.preventDefault()}function Lie(e){e.stopPropagation()}var q;(function(e){e.Space=`Space`,e.Down=`ArrowDown`,e.Right=`ArrowRight`,e.Left=`ArrowLeft`,e.Up=`ArrowUp`,e.Esc=`Escape`,e.Enter=`Enter`,e.Tab=`Tab`})(q||={});var E_={start:[q.Space,q.Enter],cancel:[q.Esc],end:[q.Space,q.Enter,q.Tab]},Rie=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case q.Right:return{...n,x:n.x+25};case q.Left:return{...n,x:n.x-25};case q.Down:return{...n,y:n.y+25};case q.Up:return{...n,y:n.y-25}}},D_=class{constructor(e){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=e;let{event:{target:t}}=e;this.props=e,this.listeners=new S_(jg(t)),this.windowListeners=new S_(Dg(t)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(w_.Resize,this.handleCancel),this.windowListeners.add(w_.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(w_.Keydown,this.handleKeyDown))}handleStart(){let{activeNode:e,onStart:t}=this.props,n=e.node.current;n&&b_(n),t(Qg)}handleKeyDown(e){if(Ug(e)){let{active:t,context:n,options:r}=this.props,{keyboardCodes:i=E_,coordinateGetter:a=Rie,scrollBehavior:o=`smooth`}=r,{code:s}=e;if(i.end.includes(s)){this.handleEnd(e);return}if(i.cancel.includes(s)){this.handleCancel(e);return}let{collisionRect:c}=n.current,l=c?{x:c.left,y:c.top}:Qg;this.referenceCoordinates||=l;let u=a(e,{active:t,context:n.current,currentCoordinates:l});if(u){let t=Hg(u,l),r={x:0,y:0},{scrollableAncestors:i}=n.current;for(let n of i){let i=e.code,{isTop:a,isRight:s,isLeft:c,isBottom:l,maxScroll:d,minScroll:f}=v_(n),p=Mie(n),m={x:Math.min(i===q.Right?p.right-p.width/2:p.right,Math.max(i===q.Right?p.left:p.left+p.width/2,u.x)),y:Math.min(i===q.Down?p.bottom-p.height/2:p.bottom,Math.max(i===q.Down?p.top:p.top+p.height/2,u.y))},h=i===q.Right&&!s||i===q.Left&&!c,g=i===q.Down&&!l||i===q.Up&&!a;if(h&&m.x!==u.x){let e=n.scrollLeft+t.x,a=i===q.Right&&e<=d.x||i===q.Left&&e>=f.x;if(a&&!t.y){n.scrollTo({left:e,behavior:o});return}r.x=a?n.scrollLeft-e:i===q.Right?n.scrollLeft-d.x:n.scrollLeft-f.x,r.x&&n.scrollBy({left:-r.x,behavior:o});break}if(g&&m.y!==u.y){let e=n.scrollTop+t.y,a=i===q.Down&&e<=d.y||i===q.Up&&e>=f.y;if(a&&!t.x){n.scrollTo({top:e,behavior:o});return}r.y=a?n.scrollTop-e:i===q.Down?n.scrollTop-d.y:n.scrollTop-f.y,r.y&&n.scrollBy({top:-r.y,behavior:o});break}}this.handleMove(e,Vg(Hg(u,this.referenceCoordinates),r))}}}handleMove(e,t){let{onMove:n}=this.props;e.preventDefault(),n(t)}handleEnd(e){let{onEnd:t}=this.props;e.preventDefault(),this.detach(),t()}handleCancel(e){let{onCancel:t}=this.props;e.preventDefault(),this.detach(),t()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}};D_.activators=[{eventName:`onKeyDown`,handler:(e,t,n)=>{let{keyboardCodes:r=E_,onActivation:i}=t,{active:a}=n,{code:o}=e.nativeEvent;if(r.start.includes(o)){let t=a.activatorNode.current;return t&&e.target!==t?!1:(e.preventDefault(),i?.({event:e.nativeEvent}),!0)}return!1}}];function O_(e){return!!(e&&`distance`in e)}function k_(e){return!!(e&&`delay`in e)}var A_=class{constructor(e,t,n){n===void 0&&(n=Iie(e.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=e,this.events=t;let{event:r}=e,{target:i}=r;this.props=e,this.events=t,this.document=jg(i),this.documentListeners=new S_(this.document),this.listeners=new S_(n),this.windowListeners=new S_(Dg(i)),this.initialCoordinates=Wg(r)??Qg,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){let{events:e,props:{options:{activationConstraint:t,bypassActivationConstraint:n}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(w_.Resize,this.handleCancel),this.windowListeners.add(w_.DragStart,T_),this.windowListeners.add(w_.VisibilityChange,this.handleCancel),this.windowListeners.add(w_.ContextMenu,T_),this.documentListeners.add(w_.Keydown,this.handleKeydown),t){if(n!=null&&n({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(k_(t)){this.timeoutId=setTimeout(this.handleStart,t.delay),this.handlePending(t);return}if(O_(t)){this.handlePending(t);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(e,t){let{active:n,onPending:r}=this.props;r(n,e,this.initialCoordinates,t)}handleStart(){let{initialCoordinates:e}=this,{onStart:t}=this.props;e&&(this.activated=!0,this.documentListeners.add(w_.Click,Lie,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(w_.SelectionChange,this.removeTextSelection),t(e))}handleMove(e){let{activated:t,initialCoordinates:n,props:r}=this,{onMove:i,options:{activationConstraint:a}}=r;if(!n)return;let o=Wg(e)??Qg,s=Hg(n,o);if(!t&&a){if(O_(a)){if(a.tolerance!=null&&C_(s,a.tolerance))return this.handleCancel();if(C_(s,a.distance))return this.handleStart()}if(k_(a)&&C_(s,a.tolerance))return this.handleCancel();this.handlePending(a,s);return}e.cancelable&&e.preventDefault(),i(o)}handleEnd(){let{onAbort:e,onEnd:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleCancel(){let{onAbort:e,onCancel:t}=this.props;this.detach(),this.activated||e(this.props.active),t()}handleKeydown(e){e.code===q.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}},j_={cancel:{name:`pointercancel`},move:{name:`pointermove`},end:{name:`pointerup`}},M_=class extends A_{constructor(e){let{event:t}=e,n=jg(t.target);super(e,j_,n)}};M_.activators=[{eventName:`onPointerDown`,handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];var N_={move:{name:`mousemove`},end:{name:`mouseup`}},P_;(function(e){e[e.RightClick=2]=`RightClick`})(P_||={});var F_=class extends A_{constructor(e){super(e,N_,jg(e.event.target))}};F_.activators=[{eventName:`onMouseDown`,handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t;return n.button!==P_.RightClick&&(r?.({event:n}),!0)}}];var I_={cancel:{name:`touchcancel`},move:{name:`touchmove`},end:{name:`touchend`}},L_=class extends A_{constructor(e){super(e,I_)}static setup(){return window.addEventListener(I_.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(I_.move.name,e)};function e(){}}};L_.activators=[{eventName:`onTouchStart`,handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:r}=t,{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var R_;(function(e){e[e.Pointer=0]=`Pointer`,e[e.DraggableRect=1]=`DraggableRect`})(R_||={});var z_;(function(e){e[e.TreeOrder=0]=`TreeOrder`,e[e.ReversedTreeOrder=1]=`ReversedTreeOrder`})(z_||={});function B_(e){let{acceleration:t,activator:n=R_.Pointer,canScroll:r,draggingRect:i,enabled:a,interval:s=5,order:c=z_.TreeOrder,pointerCoordinates:l,scrollableAncestors:u,scrollableAncestorRects:d,delta:f,threshold:p}=e,m=H_({delta:f,disabled:!a}),[h,g]=rie(),_=(0,o.useRef)({x:0,y:0}),v=(0,o.useRef)({x:0,y:0}),y=(0,o.useMemo)(()=>{switch(n){case R_.Pointer:return l?{top:l.y,bottom:l.y,left:l.x,right:l.x}:null;case R_.DraggableRect:return i}},[n,i,l]),b=(0,o.useRef)(null),x=(0,o.useCallback)(()=>{let e=b.current;if(!e)return;let t=_.current.x*v.current.x,n=_.current.y*v.current.y;e.scrollBy(t,n)},[]),S=(0,o.useMemo)(()=>c===z_.TreeOrder?[...u].reverse():u,[c,u]);(0,o.useEffect)(()=>{if(!a||!u.length||!y){g();return}for(let e of S){if(r?.(e)===!1)continue;let n=u.indexOf(e),i=d[n];if(!i)continue;let{direction:a,speed:o}=jie(e,i,y,t,p);for(let e of[`x`,`y`])m[e][a[e]]||(o[e]=0,a[e]=0);if(o.x>0||o.y>0){g(),b.current=e,h(x,s),_.current=o,v.current=a;return}}_.current={x:0,y:0},v.current={x:0,y:0},g()},[t,x,r,g,a,s,JSON.stringify(y),JSON.stringify(m),h,u,S,d,JSON.stringify(p)])}var V_={x:{[g_.Backward]:!1,[g_.Forward]:!1},y:{[g_.Backward]:!1,[g_.Forward]:!1}};function H_(e){let{delta:t,disabled:n}=e,r=Lg(t);return Fg(e=>{if(n||!r||!e)return V_;let i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[g_.Backward]:e.x[g_.Backward]||i.x===-1,[g_.Forward]:e.x[g_.Forward]||i.x===1},y:{[g_.Backward]:e.y[g_.Backward]||i.y===-1,[g_.Forward]:e.y[g_.Forward]||i.y===1}}},[n,t,r])}function U_(e,t){let n=t==null?void 0:e.get(t),r=n?n.node.current:null;return Fg(e=>t==null?null:r??e??null,[r,t])}function W_(e,t){return(0,o.useMemo)(()=>e.reduce((e,n)=>{let{sensor:r}=n,i=r.activators.map(e=>({eventName:e.eventName,handler:t(e.handler,n)}));return[...e,...i]},[]),[e,t])}var G_;(function(e){e[e.Always=0]=`Always`,e[e.BeforeDragging=1]=`BeforeDragging`,e[e.WhileDragging=2]=`WhileDragging`})(G_||={});var K_;(function(e){e.Optimized=`optimized`})(K_||={});var q_=new Map;function J_(e,t){let{dragging:n,dependencies:r,config:i}=t,[a,s]=(0,o.useState)(null),{frequency:c,measure:l,strategy:u}=i,d=(0,o.useRef)(e),f=_(),p=Pg(f),m=(0,o.useCallback)(function(e){e===void 0&&(e=[]),!p.current&&s(t=>t===null?e:t.concat(e.filter(e=>!t.includes(e))))},[p]),h=(0,o.useRef)(null),g=Fg(t=>{if(f&&!n)return q_;if(!t||t===q_||d.current!==e||a!=null){let t=new Map;for(let n of e){if(!n)continue;if(a&&a.length>0&&!a.includes(n.id)&&n.rect.current){t.set(n.id,n.rect.current);continue}let e=n.node.current,r=e?new x_(l(e),e):null;n.rect.current=r,r&&t.set(n.id,r)}return t}return t},[e,a,n,f,l]);return(0,o.useEffect)(()=>{d.current=e},[e]),(0,o.useEffect)(()=>{f||m()},[n,f]),(0,o.useEffect)(()=>{a&&a.length>0&&s(null)},[JSON.stringify(a)]),(0,o.useEffect)(()=>{f||typeof c!=`number`||h.current!==null||(h.current=setTimeout(()=>{m(),h.current=null},c))},[c,f,m,...r]),{droppableRects:g,measureDroppableContainers:m,measuringScheduled:a!=null};function _(){switch(u){case G_.Always:return!1;case G_.BeforeDragging:return n;default:return!n}}}function Y_(e,t){return Fg(n=>e?n||(typeof t==`function`?t(e):e):null,[t,e])}function X_(e,t){return Y_(e,t)}function Z_(e){let{callback:t,disabled:n}=e,r=Ng(t),i=(0,o.useMemo)(()=>{if(n||typeof window>`u`||window.MutationObserver===void 0)return;let{MutationObserver:e}=window;return new e(r)},[r,n]);return(0,o.useEffect)(()=>()=>i?.disconnect(),[i]),i}function Q_(e){let{callback:t,disabled:n}=e,r=Ng(t),i=(0,o.useMemo)(()=>{if(n||typeof window>`u`||window.ResizeObserver===void 0)return;let{ResizeObserver:e}=window;return new e(r)},[n]);return(0,o.useEffect)(()=>()=>i?.disconnect(),[i]),i}function $_(e){return new x_(c_(e),e)}function ev(e,t,n){t===void 0&&(t=$_);let[r,i]=(0,o.useState)(null);function a(){i(r=>{if(!e)return null;if(e.isConnected===!1)return r??n??null;let i=t(e);return JSON.stringify(r)===JSON.stringify(i)?r:i})}let s=Z_({callback(t){if(e)for(let n of t){let{type:t,target:r}=n;if(t===`childList`&&r instanceof HTMLElement&&r.contains(e)){a();break}}}}),c=Q_({callback:a});return Mg(()=>{a(),e?(c?.observe(e),s?.observe(document.body,{childList:!0,subtree:!0})):(c?.disconnect(),s?.disconnect())},[e]),r}function tv(e){return o_(e,Y_(e))}var nv=[];function rv(e){let t=(0,o.useRef)(e),n=Fg(n=>e?n&&n!==nv&&e&&t.current&&e.parentNode===t.current.parentNode?n:u_(e):nv,[e]);return(0,o.useEffect)(()=>{t.current=e},[e]),n}function iv(e){let[t,n]=(0,o.useState)(null),r=(0,o.useRef)(e),i=(0,o.useCallback)(e=>{let t=f_(e.target);t&&n(e=>e?(e.set(t,h_(t)),new Map(e)):null)},[]);return(0,o.useEffect)(()=>{let t=r.current;if(e!==t){a(t);let o=e.map(e=>{let t=f_(e);return t?(t.addEventListener(`scroll`,i,{passive:!0}),[t,h_(t)]):null}).filter(e=>e!=null);n(o.length?new Map(o):null),r.current=e}return()=>{a(e),a(t)};function a(e){e.forEach(e=>{f_(e)?.removeEventListener(`scroll`,i)})}},[i,e]),(0,o.useMemo)(()=>e.length?t?Array.from(t.values()).reduce((e,t)=>Vg(e,t),Qg):y_(e):Qg,[e,t])}function av(e,t){t===void 0&&(t=[]);let n=(0,o.useRef)(null);return(0,o.useEffect)(()=>{n.current=null},t),(0,o.useEffect)(()=>{let t=e!==Qg;t&&!n.current&&(n.current=e),!t&&n.current&&(n.current=null)},[e]),n.current?Hg(e,n.current):Qg}function ov(e){(0,o.useEffect)(()=>{if(!wg)return;let t=e.map(e=>{let{sensor:t}=e;return t.setup==null?void 0:t.setup()});return()=>{for(let e of t)e?.()}},e.map(e=>{let{sensor:t}=e;return t}))}function sv(e,t){return(0,o.useMemo)(()=>e.reduce((e,n)=>{let{eventName:r,handler:i}=n;return e[r]=e=>{i(e,t)},e},{}),[e,t])}function cv(e){return(0,o.useMemo)(()=>e?Die(e):null,[e])}var lv=[];function uv(e,t){t===void 0&&(t=c_);let[n]=e,r=cv(n?Dg(n):null),[i,a]=(0,o.useState)(lv);function s(){a(()=>e.length?e.map(e=>__(e)?r:new x_(t(e),e)):lv)}let c=Q_({callback:s});return Mg(()=>{c?.disconnect(),s(),e.forEach(e=>c?.observe(e))},[e]),i}function dv(e){if(!e)return null;if(e.children.length>1)return e;let t=e.children[0];return kg(t)?t:e}function fv(e){let{measure:t}=e,[n,r]=(0,o.useState)(null),i=Q_({callback:(0,o.useCallback)(e=>{for(let{target:n}of e)if(kg(n)){r(e=>{let r=t(n);return e?{...e,width:r.width,height:r.height}:r});break}},[t])}),[a,s]=Ig((0,o.useCallback)(e=>{let n=dv(e);i?.disconnect(),n&&i?.observe(n),r(n?t(n):null)},[t,i]));return(0,o.useMemo)(()=>({nodeRef:a,rect:n,setRef:s}),[n,a,s])}var pv=[{sensor:M_,options:{}},{sensor:D_,options:{}}],mv={current:{}},hv={draggable:{measure:l_},droppable:{measure:l_,strategy:G_.WhileDragging,frequency:K_.Optimized},dragOverlay:{measure:c_}},gv=class extends Map{get(e){return e==null?void 0:super.get(e)??void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:t}=e;return!t})}getNodeFor(e){return this.get(e)?.node.current??void 0}},_v={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new gv,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Yg},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:hv,measureDroppableContainers:Yg,windowRect:null,measuringScheduled:!1},vv={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:``},dispatch:Yg,draggableNodes:new Map,over:null,measureDroppableContainers:Yg},yv=(0,o.createContext)(vv),bv=(0,o.createContext)(_v);function xv(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new gv}}}function Sv(e,t){switch(t.type){case Jg.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Jg.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case Jg.DragEnd:case Jg.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Jg.RegisterDroppable:{let{element:n}=t,{id:r}=n,i=new gv(e.droppable.containers);return i.set(r,n),{...e,droppable:{...e.droppable,containers:i}}}case Jg.SetDroppableDisabled:{let{id:n,key:r,disabled:i}=t,a=e.droppable.containers.get(n);if(!a||r!==a.key)return e;let o=new gv(e.droppable.containers);return o.set(n,{...a,disabled:i}),{...e,droppable:{...e.droppable,containers:o}}}case Jg.UnregisterDroppable:{let{id:n,key:r}=t,i=e.droppable.containers.get(n);if(!i||r!==i.key)return e;let a=new gv(e.droppable.containers);return a.delete(n),{...e,droppable:{...e.droppable,containers:a}}}default:return e}}function Cv(e){let{disabled:t}=e,{active:n,activatorEvent:r,draggableNodes:i}=(0,o.useContext)(yv),a=Lg(r),s=Lg(n?.id);return(0,o.useEffect)(()=>{if(!t&&!r&&a&&s!=null){if(!Ug(a)||document.activeElement===a.target)return;let e=i.get(s);if(!e)return;let{activatorNode:t,node:n}=e;if(!t.current&&!n.current)return;requestAnimationFrame(()=>{for(let e of[t.current,n.current]){if(!e)continue;let t=oie(e);if(t){t.focus();break}}})}},[r,t,i,s,a]),null}function wv(e,t){let{transform:n,...r}=t;return e!=null&&e.length?e.reduce((e,t)=>t({transform:e,...r}),n):n}function Tv(e){return(0,o.useMemo)(()=>({draggable:{...hv.draggable,...e?.draggable},droppable:{...hv.droppable,...e?.droppable},dragOverlay:{...hv.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function Ev(e){let{activeNode:t,measure:n,initialRect:r,config:i=!0}=e,a=(0,o.useRef)(!1),{x:s,y:c}=typeof i==`boolean`?{x:i,y:i}:i;Mg(()=>{if(!s&&!c||!t){a.current=!1;return}if(a.current||!r)return;let e=t?.node.current;if(!e||e.isConnected===!1)return;let i=o_(n(e),r);if(s||(i.x=0),c||(i.y=0),a.current=!0,Math.abs(i.x)>0||Math.abs(i.y)>0){let t=d_(e);t&&t.scrollBy({top:i.y,left:i.x})}},[t,s,c,r,n])}var Dv=(0,o.createContext)({...Qg,scaleX:1,scaleY:1}),Ov;(function(e){e[e.Uninitialized=0]=`Uninitialized`,e[e.Initializing=1]=`Initializing`,e[e.Initialized=2]=`Initialized`})(Ov||={});var kv=(0,o.memo)(function(e){let{id:t,accessibility:n,autoScroll:r=!0,children:i,sensors:a=pv,collisionDetection:s=a_,measuring:c,modifiers:l,...u}=e,[d,f]=(0,o.useReducer)(Sv,void 0,xv),[p,m]=fie(),[h,g]=(0,o.useState)(Ov.Uninitialized),_=h===Ov.Initialized,{draggable:{active:v,nodes:y,translate:b},droppable:{containers:x}}=d,S=v==null?null:y.get(v),C=(0,o.useRef)({initial:null,translated:null}),w=(0,o.useMemo)(()=>v==null?null:{id:v,data:S?.data??mv,rect:C},[v,S]),T=(0,o.useRef)(null),[E,D]=(0,o.useState)(null),[O,k]=(0,o.useState)(null),A=Pg(u,Object.values(u)),j=zg(`DndDescribedBy`,t),M=(0,o.useMemo)(()=>x.getEnabled(),[x]),N=Tv(c),{droppableRects:ee,measureDroppableContainers:P,measuringScheduled:te}=J_(M,{dragging:_,dependencies:[b.x,b.y],config:N.droppable}),F=U_(y,v),ne=(0,o.useMemo)(()=>O?Wg(O):null,[O]),re=Me(),ie=X_(F,N.draggable.measure);Ev({activeNode:v==null?null:y.get(v),config:re.layoutShiftCompensation,initialRect:ie,measure:N.draggable.measure});let I=ev(F,N.draggable.measure,ie),ae=ev(F?F.parentElement:null),oe=(0,o.useRef)({activatorEvent:null,active:null,activeNode:F,collisionRect:null,collisions:null,droppableRects:ee,draggableNodes:y,draggingNode:null,draggingNodeRect:null,droppableContainers:x,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),se=x.getNodeFor(oe.current.over?.id),L=fv({measure:N.dragOverlay.measure}),ce=L.nodeRef.current??F,le=_?L.rect??I:null,ue=!!(L.nodeRef.current&&L.rect),de=tv(ue?null:I),fe=cv(ce?Dg(ce):null),pe=rv(_?se??F:null),me=uv(pe),he=wv(l,{transform:{x:b.x-de.x,y:b.y-de.y,scaleX:1,scaleY:1},activatorEvent:O,active:w,activeNodeRect:I,containerNodeRect:ae,draggingNodeRect:le,over:oe.current.over,overlayNodeRect:L.rect,scrollableAncestors:pe,scrollableAncestorRects:me,windowRect:fe}),ge=ne?Vg(ne,b):null,_e=iv(pe),ve=av(_e),ye=av(_e,[I]),be=Vg(he,ve),xe=le?wie(le,he):null,Se=w&&xe?s({active:w,collisionRect:xe,droppableRects:ee,droppableContainers:M,pointerCoordinates:ge}):null,Ce=n_(Se,`id`),[we,Te]=(0,o.useState)(null),Ee=Sie(ue?he:Vg(he,ye),we?.rect??null,I),De=(0,o.useRef)(null),Oe=(0,o.useCallback)((e,t)=>{let{sensor:n,options:r}=t;if(T.current==null)return;let i=y.get(T.current);if(!i)return;let a=e.nativeEvent,o=new n({active:T.current,activeNode:i,event:a,options:r,context:oe,onAbort(e){if(!y.get(e))return;let{onDragAbort:t}=A.current,n={id:e};t?.(n),p({type:`onDragAbort`,event:n})},onPending(e,t,n,r){if(!y.get(e))return;let{onDragPending:i}=A.current,a={id:e,constraint:t,initialCoordinates:n,offset:r};i?.(a),p({type:`onDragPending`,event:a})},onStart(e){let t=T.current;if(t==null)return;let n=y.get(t);if(!n)return;let{onDragStart:r}=A.current,i={activatorEvent:a,active:{id:t,data:n.data,rect:C}};(0,nr.unstable_batchedUpdates)(()=>{r?.(i),g(Ov.Initializing),f({type:Jg.DragStart,initialCoordinates:e,active:t}),p({type:`onDragStart`,event:i}),D(De.current),k(a)})},onMove(e){f({type:Jg.DragMove,coordinates:e})},onEnd:s(Jg.DragEnd),onCancel:s(Jg.DragCancel)});De.current=o;function s(e){return async function(){let{active:t,collisions:n,over:r,scrollAdjustedTranslate:i}=oe.current,o=null;if(t&&i){let{cancelDrop:s}=A.current;o={activatorEvent:a,active:t,collisions:n,delta:i,over:r},e===Jg.DragEnd&&typeof s==`function`&&await Promise.resolve(s(o))&&(e=Jg.DragCancel)}T.current=null,(0,nr.unstable_batchedUpdates)(()=>{f({type:e}),g(Ov.Uninitialized),Te(null),D(null),k(null),De.current=null;let t=e===Jg.DragEnd?`onDragEnd`:`onDragCancel`;if(o){let e=A.current[t];e?.(o),p({type:t,event:o})}})}}},[y]),ke=W_(a,(0,o.useCallback)((e,t)=>(n,r)=>{let i=n.nativeEvent,a=y.get(r);if(T.current!==null||!a||i.dndKit||i.defaultPrevented)return;let o={active:a};e(n,t.options,o)===!0&&(i.dndKit={capturedBy:t.sensor},T.current=r,Oe(n,t))},[y,Oe]));ov(a),Mg(()=>{I&&h===Ov.Initializing&&g(Ov.Initialized)},[I,h]),(0,o.useEffect)(()=>{let{onDragMove:e}=A.current,{active:t,activatorEvent:n,collisions:r,over:i}=oe.current;if(!t||!n)return;let a={active:t,activatorEvent:n,collisions:r,delta:{x:be.x,y:be.y},over:i};(0,nr.unstable_batchedUpdates)(()=>{e?.(a),p({type:`onDragMove`,event:a})})},[be.x,be.y]),(0,o.useEffect)(()=>{let{active:e,activatorEvent:t,collisions:n,droppableContainers:r,scrollAdjustedTranslate:i}=oe.current;if(!e||T.current==null||!t||!i)return;let{onDragOver:a}=A.current,o=r.get(Ce),s=o&&o.rect.current?{id:o.id,rect:o.rect.current,data:o.data,disabled:o.disabled}:null,c={active:e,activatorEvent:t,collisions:n,delta:{x:i.x,y:i.y},over:s};(0,nr.unstable_batchedUpdates)(()=>{Te(s),a?.(c),p({type:`onDragOver`,event:c})})},[Ce]),Mg(()=>{oe.current={activatorEvent:O,active:w,activeNode:F,collisionRect:xe,collisions:Se,droppableRects:ee,draggableNodes:y,draggingNode:ce,draggingNodeRect:le,droppableContainers:x,over:we,scrollableAncestors:pe,scrollAdjustedTranslate:be},C.current={initial:le,translated:xe}},[w,F,Se,xe,y,ce,le,ee,x,we,pe,be]),B_({...re,delta:b,draggingRect:xe,pointerCoordinates:ge,scrollableAncestors:pe,scrollableAncestorRects:me});let Ae=(0,o.useMemo)(()=>({active:w,activeNode:F,activeNodeRect:I,activatorEvent:O,collisions:Se,containerNodeRect:ae,dragOverlay:L,draggableNodes:y,droppableContainers:x,droppableRects:ee,over:we,measureDroppableContainers:P,scrollableAncestors:pe,scrollableAncestorRects:me,measuringConfiguration:N,measuringScheduled:te,windowRect:fe}),[w,F,I,O,Se,ae,L,y,x,ee,we,P,pe,me,N,te,fe]),je=(0,o.useMemo)(()=>({activatorEvent:O,activators:ke,active:w,activeNodeRect:I,ariaDescribedById:{draggable:j},dispatch:f,draggableNodes:y,over:we,measureDroppableContainers:P}),[O,ke,w,I,f,j,y,we,P]);return o.createElement(qg.Provider,{value:m},o.createElement(yv.Provider,{value:je},o.createElement(bv.Provider,{value:Ae},o.createElement(Dv.Provider,{value:Ee},i)),o.createElement(Cv,{disabled:n?.restoreFocus===!1})),o.createElement(hie,{...n,hiddenTextDescribedById:j}));function Me(){let e=E?.autoScrollEnabled===!1,t=typeof r==`object`?r.enabled===!1:r===!1,n=_&&!e&&!t;return typeof r==`object`?{...r,enabled:n}:{enabled:n}}}),Av=(0,o.createContext)(null),jv=`button`,Mv=`Draggable`;function Nv(e){let{id:t,data:n,disabled:r=!1,attributes:i}=e,a=zg(Mv),{activators:s,activatorEvent:c,active:l,activeNodeRect:u,ariaDescribedById:d,draggableNodes:f,over:p}=(0,o.useContext)(yv),{role:m=jv,roleDescription:h=`draggable`,tabIndex:g=0}=i??{},_=l?.id===t,v=(0,o.useContext)(_?Dv:Av),[y,b]=Ig(),[x,S]=Ig(),C=sv(s,t),w=Pg(n);return Mg(()=>(f.set(t,{id:t,key:a,node:y,activatorNode:x,data:w}),()=>{let e=f.get(t);e&&e.key===a&&f.delete(t)}),[f,t]),{active:l,activatorEvent:c,activeNodeRect:u,attributes:(0,o.useMemo)(()=>({role:m,tabIndex:g,"aria-disabled":r,"aria-pressed":_&&m===jv?!0:void 0,"aria-roledescription":h,"aria-describedby":d.draggable}),[r,m,g,_,h,d.draggable]),isDragging:_,listeners:r?void 0:C,node:y,over:p,setNodeRef:b,setActivatorNodeRef:S,transform:v}}function Pv(){return(0,o.useContext)(bv)}var Fv=`Droppable`,Iv={timeout:25};function Lv(e){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:i}=e,a=zg(Fv),{active:s,dispatch:c,over:l,measureDroppableContainers:u}=(0,o.useContext)(yv),d=(0,o.useRef)({disabled:n}),f=(0,o.useRef)(!1),p=(0,o.useRef)(null),m=(0,o.useRef)(null),{disabled:h,updateMeasurementsFor:g,timeout:_}={...Iv,...i},v=Pg(g??r),y=Q_({callback:(0,o.useCallback)(()=>{if(!f.current){f.current=!0;return}m.current!=null&&clearTimeout(m.current),m.current=setTimeout(()=>{u(Array.isArray(v.current)?v.current:[v.current]),m.current=null},_)},[_]),disabled:h||!s}),[b,x]=Ig((0,o.useCallback)((e,t)=>{y&&(t&&(y.unobserve(t),f.current=!1),e&&y.observe(e))},[y])),S=Pg(t);return(0,o.useEffect)(()=>{y&&b.current&&(y.disconnect(),f.current=!1,y.observe(b.current))},[b,y]),(0,o.useEffect)(()=>(c({type:Jg.RegisterDroppable,element:{id:r,key:a,disabled:n,node:b,rect:p,data:S}}),()=>c({type:Jg.UnregisterDroppable,key:a,id:r})),[r]),(0,o.useEffect)(()=>{n!==d.current.disabled&&(c({type:Jg.SetDroppableDisabled,id:r,key:a,disabled:n}),d.current.disabled=n)},[r,a,n,c]),{active:s,rect:p,isOver:l?.id===r,node:b,over:l,setNodeRef:x}}function Rv(e){let{animation:t,children:n}=e,[r,i]=(0,o.useState)(null),[a,s]=(0,o.useState)(null),c=Lg(n);return!n&&!r&&c&&i(c),Mg(()=>{if(!a)return;let e=r?.key,n=r?.props.id;if(e==null||n==null){i(null);return}Promise.resolve(t(n,a)).then(()=>{i(null)})},[t,r,a]),o.createElement(o.Fragment,null,n,r?(0,o.cloneElement)(r,{ref:s}):null)}var zv={x:0,y:0,scaleX:1,scaleY:1};function Bv(e){let{children:t}=e;return o.createElement(yv.Provider,{value:vv},o.createElement(Dv.Provider,{value:zv},t))}var Vv={position:`fixed`,touchAction:`none`},Hv=e=>Ug(e)?`transform 250ms ease`:void 0,Uv=(0,o.forwardRef)((e,t)=>{let{as:n,activatorEvent:r,adjustScale:i,children:a,className:s,rect:c,style:l,transform:u,transition:d=Hv}=e;if(!c)return null;let f=i?u:{...u,scaleX:1,scaleY:1},p={...Vv,width:c.width,height:c.height,top:c.top,left:c.left,transform:Gg.Transform.toString(f),transformOrigin:i&&r?gie(r,c):void 0,transition:typeof d==`function`?d(r):d,...l};return o.createElement(n,{className:s,style:p,ref:t},a)}),Wv={duration:250,easing:`ease`,keyframes:e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Gg.Transform.toString(t)},{transform:Gg.Transform.toString(n)}]},sideEffects:(e=>t=>{let{active:n,dragOverlay:r}=t,i={},{styles:a,className:o}=e;if(a!=null&&a.active)for(let[e,t]of Object.entries(a.active))t!==void 0&&(i[e]=n.node.style.getPropertyValue(e),n.node.style.setProperty(e,t));if(a!=null&&a.dragOverlay)for(let[e,t]of Object.entries(a.dragOverlay))t!==void 0&&r.node.style.setProperty(e,t);return o!=null&&o.active&&n.node.classList.add(o.active),o!=null&&o.dragOverlay&&r.node.classList.add(o.dragOverlay),function(){for(let[e,t]of Object.entries(i))n.node.style.setProperty(e,t);o!=null&&o.active&&n.node.classList.remove(o.active)}})({styles:{active:{opacity:`0`}}})};function Gv(e){let{config:t,draggableNodes:n,droppableContainers:r,measuringConfiguration:i}=e;return Ng((e,a)=>{if(t===null)return;let o=n.get(e);if(!o)return;let s=o.node.current;if(!s)return;let c=dv(a);if(!c)return;let{transform:l}=Dg(a).getComputedStyle(a),u=s_(l);if(!u)return;let d=typeof t==`function`?t:Kv(t);return b_(s,i.draggable.measure),d({active:{id:e,data:o.data,node:s,rect:i.draggable.measure(s)},draggableNodes:n,dragOverlay:{node:a,rect:i.dragOverlay.measure(c)},droppableContainers:r,measuringConfiguration:i,transform:u})})}function Kv(e){let{duration:t,easing:n,sideEffects:r,keyframes:i}={...Wv,...e};return e=>{let{active:a,dragOverlay:o,transform:s,...c}=e;if(!t)return;let l={x:o.rect.left-a.rect.left,y:o.rect.top-a.rect.top},u={scaleX:s.scaleX===1?1:a.rect.width*s.scaleX/o.rect.width,scaleY:s.scaleY===1?1:a.rect.height*s.scaleY/o.rect.height},d={x:s.x-l.x,y:s.y-l.y,...u},f=i({...c,active:a,dragOverlay:o,transform:{initial:s,final:d}}),[p]=f,m=f[f.length-1];if(JSON.stringify(p)===JSON.stringify(m))return;let h=r?.({active:a,dragOverlay:o,...c}),g=o.node.animate(f,{duration:t,easing:n,fill:`forwards`});return new Promise(e=>{g.onfinish=()=>{h?.(),e()}})}}var qv=0;function Jv(e){return(0,o.useMemo)(()=>{if(e!=null)return qv++,qv},[e])}var Yv=o.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:r,style:i,transition:a,modifiers:s,wrapperElement:c=`div`,className:l,zIndex:u=999}=e,{activatorEvent:d,active:f,activeNodeRect:p,containerNodeRect:m,draggableNodes:h,droppableContainers:g,dragOverlay:_,over:v,measuringConfiguration:y,scrollableAncestors:b,scrollableAncestorRects:x,windowRect:S}=Pv(),C=(0,o.useContext)(Dv),w=Jv(f?.id),T=wv(s,{activatorEvent:d,active:f,activeNodeRect:p,containerNodeRect:m,draggingNodeRect:_.rect,over:v,overlayNodeRect:_.rect,scrollableAncestors:b,scrollableAncestorRects:x,transform:C,windowRect:S}),E=Y_(p),D=Gv({config:r,draggableNodes:h,droppableContainers:g,measuringConfiguration:y}),O=E?_.setRef:void 0;return o.createElement(Bv,null,o.createElement(Rv,{animation:D},f&&w?o.createElement(Uv,{key:w,id:f.id,ref:O,as:c,activatorEvent:d,adjustScale:t,className:l,transition:a,rect:E,style:{zIndex:u,...i},transform:T},n):null))});function Xv(e,t,n){let r=e.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function Zv(e,t){return e.reduce((e,n,r)=>{let i=t.get(n);return i&&(e[r]=i),e},Array(e.length))}function Qv(e){return e!==null&&e>=0}function $v(e,t){if(e===t)return!0;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function ey(e){return typeof e==`boolean`?{draggable:e,droppable:e}:e}var ty=e=>{let{rects:t,activeIndex:n,overIndex:r,index:i}=e,a=Xv(t,r,n),o=t[i],s=a[i];return!s||!o?null:{x:s.left-o.left,y:s.top-o.top,scaleX:s.width/o.width,scaleY:s.height/o.height}},ny={scaleX:1,scaleY:1},ry=e=>{let{activeIndex:t,activeNodeRect:n,index:r,rects:i,overIndex:a}=e,o=i[t]??n;if(!o)return null;if(r===t){let e=i[a];return e?{x:0,y:t<a?e.top+e.height-(o.top+o.height):e.top-o.top,...ny}:null}let s=iy(i,r,t);return r>t&&r<=a?{x:0,y:-o.height-s,...ny}:r<t&&r>=a?{x:0,y:o.height+s,...ny}:{x:0,y:0,...ny}};function iy(e,t,n){let r=e[t],i=e[t-1],a=e[t+1];return r?n<t?i?r.top-(i.top+i.height):a?a.top-(r.top+r.height):0:a?a.top-(r.top+r.height):i?r.top-(i.top+i.height):0:0}var ay=`Sortable`,oy=o.createContext({activeIndex:-1,containerId:ay,disableTransforms:!1,items:[],overIndex:-1,useDragOverlay:!1,sortedRects:[],strategy:ty,disabled:{draggable:!1,droppable:!1}});function sy(e){let{children:t,id:n,items:r,strategy:i=ty,disabled:a=!1}=e,{active:s,dragOverlay:c,droppableRects:l,over:u,measureDroppableContainers:d}=Pv(),f=zg(ay,n),p=c.rect!==null,m=(0,o.useMemo)(()=>r.map(e=>typeof e==`object`&&`id`in e?e.id:e),[r]),h=s!=null,g=s?m.indexOf(s.id):-1,_=u?m.indexOf(u.id):-1,v=(0,o.useRef)(m),y=!$v(m,v.current),b=_!==-1&&g===-1||y,x=ey(a);Mg(()=>{y&&h&&d(m)},[y,m,h,d]),(0,o.useEffect)(()=>{v.current=m},[m]);let S=(0,o.useMemo)(()=>({activeIndex:g,containerId:f,disabled:x,disableTransforms:b,items:m,overIndex:_,useDragOverlay:p,sortedRects:Zv(m,l),strategy:i}),[g,f,x.draggable,x.droppable,b,m,_,l,p,i]);return o.createElement(oy.Provider,{value:S},t)}var cy=e=>{let{id:t,items:n,activeIndex:r,overIndex:i}=e;return Xv(n,r,i).indexOf(t)},ly=e=>{let{containerId:t,isSorting:n,wasDragging:r,index:i,items:a,newIndex:o,previousItems:s,previousContainerId:c,transition:l}=e;return!l||!r||s!==a&&i===o?!1:n?!0:o!==i&&t===c},uy={duration:200,easing:`ease`},dy=`transform`,fy=Gg.Transition.toString({property:dy,duration:0,easing:`linear`}),py={roleDescription:`sortable`};function my(e){let{disabled:t,index:n,node:r,rect:i}=e,[a,s]=(0,o.useState)(null),c=(0,o.useRef)(n);return Mg(()=>{if(!t&&n!==c.current&&r.current){let e=i.current;if(e){let t=c_(r.current,{ignoreTransform:!0}),n={x:e.left-t.left,y:e.top-t.top,scaleX:e.width/t.width,scaleY:e.height/t.height};(n.x||n.y)&&s(n)}}n!==c.current&&(c.current=n)},[t,n,r,i]),(0,o.useEffect)(()=>{a&&s(null)},[a]),a}function hy(e){let{animateLayoutChanges:t=ly,attributes:n,disabled:r,data:i,getNewIndex:a=cy,id:s,strategy:c,resizeObserverConfig:l,transition:u=uy}=e,{items:d,containerId:f,activeIndex:p,disabled:m,disableTransforms:h,sortedRects:g,overIndex:_,useDragOverlay:v,strategy:y}=(0,o.useContext)(oy),b=gy(r,m),x=d.indexOf(s),S=(0,o.useMemo)(()=>({sortable:{containerId:f,index:x,items:d},...i}),[f,i,x,d]),C=(0,o.useMemo)(()=>d.slice(d.indexOf(s)),[d,s]),{rect:w,node:T,isOver:E,setNodeRef:D}=Lv({id:s,data:S,disabled:b.droppable,resizeObserverConfig:{updateMeasurementsFor:C,...l}}),{active:O,activatorEvent:k,activeNodeRect:A,attributes:j,setNodeRef:M,listeners:N,isDragging:ee,over:P,setActivatorNodeRef:te,transform:F}=Nv({id:s,data:S,attributes:{...py,...n},disabled:b.draggable}),ne=nie(D,M),re=!!O,ie=re&&!h&&Qv(p)&&Qv(_),I=!v&&ee,ae=ie?(I&&ie?F:null)??(c??y)({rects:g,activeNodeRect:A,activeIndex:p,overIndex:_,index:x}):null,oe=Qv(p)&&Qv(_)?a({id:s,items:d,activeIndex:p,overIndex:_}):x,se=O?.id,L=(0,o.useRef)({activeId:se,items:d,newIndex:oe,containerId:f}),ce=d!==L.current.items,le=t({active:O,containerId:f,isDragging:ee,isSorting:re,id:s,index:x,items:d,newIndex:L.current.newIndex,previousItems:L.current.items,previousContainerId:L.current.containerId,transition:u,wasDragging:L.current.activeId!=null}),ue=my({disabled:!le,index:x,node:T,rect:w});return(0,o.useEffect)(()=>{re&&L.current.newIndex!==oe&&(L.current.newIndex=oe),f!==L.current.containerId&&(L.current.containerId=f),d!==L.current.items&&(L.current.items=d)},[re,oe,f,d]),(0,o.useEffect)(()=>{if(se===L.current.activeId)return;if(se!=null&&L.current.activeId==null){L.current.activeId=se;return}let e=setTimeout(()=>{L.current.activeId=se},50);return()=>clearTimeout(e)},[se]),{active:O,activeIndex:p,attributes:j,data:S,rect:w,index:x,newIndex:oe,items:d,isOver:E,isSorting:re,isDragging:ee,listeners:N,node:T,overIndex:_,over:P,setNodeRef:ne,setActivatorNodeRef:te,setDroppableNodeRef:D,setDraggableNodeRef:M,transform:ue??ae,transition:de()};function de(){if(ue||ce&&L.current.newIndex===x)return fy;if(!(I&&!Ug(k)||!u)&&(re||le))return Gg.Transition.toString({...u,property:dy})}}function gy(e,t){return typeof e==`boolean`?{draggable:e,droppable:!1}:{draggable:e?.draggable??t.draggable,droppable:e?.droppable??t.droppable}}function _y(e){if(!e)return!1;let t=e.data.current;return!!(t&&`sortable`in t&&typeof t.sortable==`object`&&`containerId`in t.sortable&&`items`in t.sortable&&`index`in t.sortable)}var vy=[q.Down,q.Right,q.Up,q.Left],yy=(e,t)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:a,over:o,scrollableAncestors:s}}=t;if(vy.includes(e.code)){if(e.preventDefault(),!n||!r)return;let t=[];a.getEnabled().forEach(n=>{if(!n||n!=null&&n.disabled)return;let a=i.get(n.id);if(a)switch(e.code){case q.Down:r.top<a.top&&t.push(n);break;case q.Up:r.top>a.top&&t.push(n);break;case q.Left:r.left>a.left&&t.push(n);break;case q.Right:r.left<a.left&&t.push(n)}});let c=vie({active:n,collisionRect:r,droppableRects:i,droppableContainers:t,pointerCoordinates:null}),l=n_(c,`id`);if(l===o?.id&&c.length>1&&(l=c[1].id),l!=null){let e=a.get(n.id),t=a.get(l),o=t?i.get(t.id):null,c=t?.node.current;if(c&&o&&e&&t){let n=u_(c).some((e,t)=>s[t]!==e),i=by(e,t),a=xy(e,t),l=n||!i?{x:0,y:0}:{x:a?r.width-o.width:0,y:a?r.height-o.height:0},u={x:o.left,y:o.top};return l.x&&l.y?u:Hg(u,l)}}}};function by(e,t){return!_y(e)||!_y(t)?!1:e.data.current.sortable.containerId===t.data.current.sortable.containerId}function xy(e,t){return!_y(e)||!_y(t)||!by(e,t)?!1:e.data.current.sortable.index<t.data.current.sortable.index}var Sy=Date.UTC(2026,9,6,9,41),Cy=(e,t)=>{let n=(e^Math.imul(t+2654435769,2246822507))>>>0;return n=Math.imul(n^n>>>16,2246822507),n=Math.imul(n^n>>>13,3266489909),(n^n>>>16)>>>0},wy=(e,t)=>{let n=Cy(e,t);return()=>{n=n+1831565813>>>0;let e=n;return e=Math.imul(e^e>>>15,e|1),e^=e+Math.imul(e^e>>>7,e|61),((e^e>>>14)>>>0)/4294967296}},Ty=[{id:`u1`,name:`Sanne M.`,initials:`SM`,hue:250,role:`Admin`},{id:`u2`,name:`Jonas K.`,initials:`JK`,hue:160,role:`Sales`},{id:`u3`,name:`Lieke D.`,initials:`LD`,hue:20,role:`Finance`},{id:`u4`,name:`Tobias R.`,initials:`TR`,hue:310,role:`Warehouse`},{id:`u5`,name:`Imke V.`,initials:`IV`,hue:200,role:`Sales`},{id:`u6`,name:`Marek W.`,initials:`MW`,hue:80,role:`Warehouse`},{id:`u7`,name:`Hanna B.`,initials:`HB`,hue:350,role:`Finance`},{id:`u8`,name:`Daan P.`,initials:`DP`,hue:120,role:`Sales`}],Ey=e=>Ty.find(t=>t.id===e)??Ty[0];Ty.filter(e=>e.role===`Sales`);var Dy=[[`M8 hex bolt A2, 100 pcs`,`FST`,1890],[`M10 hex nut A2, 100 pcs`,`FST`,1240],[`Stainless washer 8 mm, 250 pcs`,`FST`,990],[`Cable tie 300 mm, 100 pcs`,`ELC`,650],[`Cable gland M20, 25 pcs`,`ELC`,2340],[`Junction box IP65`,`ELC`,1480],[`Hydraulic hose 1/2 in, 5 m`,`HYD`,8650],[`Hydraulic coupling 3/8 in`,`HYD`,1895],[`Pallet wrap 500 mm`,`PKG`,740],[`Corrugated box 400 x 300`,`PKG`,215],[`Bubble wrap roll 50 m`,`PKG`,1990],[`Safety gloves, size L`,`PPE`,395],[`Safety glasses, clear`,`PPE`,450],[`Ear defenders SNR 31`,`PPE`,1295],[`Ball bearing 6204-2RS`,`BRG`,685],[`Taper roller bearing 30205`,`BRG`,1420],[`Timing belt HTD 5M, 600 mm`,`BLT`,2780],[`V-belt SPA 1250`,`BLT`,1360],[`Grease cartridge, 400 g`,`LUB`,920],[`Machine oil ISO 68, 5 l`,`LUB`,3950],[`Angle grinder disc 125 mm, 10 pcs`,`ABR`,1880],[`Drill bit set HSS, 19 pcs`,`TLS`,3490],[`Torque wrench 20-100 Nm`,`TLS`,14900],[`Pneumatic cylinder 40 x 100`,`PNE`,6120],[`Air hose PU 8 mm, 20 m`,`PNE`,2475],[`LED panel 600 x 600, 40 W`,`LGT`,3290],[`Pallet label roll 100 x 150`,`LBL`,1175],[`Thermal printer ribbon`,`LBL`,890],[`Euro pallet EPAL, used`,`PLT`,1150],[`Roll container, galvanised`,`PLT`,9800]];Dy.length;var Oy=e=>{let[t,n,r]=Dy[e%Dy.length],i=e%Dy.length;return{id:`P-${200+i}`,sku:`${n}-${String(1e3+i*7).padStart(4,`0`)}`,name:t,category:n,priceCents:r}},ky=e=>e.quantity*e.unitPriceCents,Ay=(e,t=.21)=>{let n=e.reduce((e,t)=>e+ky(t),0),r=Math.round(n*t);return{subtotalCents:n,vatCents:r,totalCents:n+r}},jy=864e5,My=e=>Array.from({length:e},(t,n)=>{let r=Sy-(e-1-n)*jy,i=new Date(r).getUTCDay();return{at:r,count:Math.round((i===0||i===6?120:410)*(.8+wy(71,n)()*.45)*(1+n/e/3))}}),Ny=e=>{if(e===`day`)return My(30);let t=My(84);return Array.from({length:12},(e,n)=>{let r=t.slice(n*7,n*7+7);return{at:r[0].at,count:r.reduce((e,t)=>e+t.count,0)}})},Py=`grid grid-cols-[28px_minmax(0,1fr)_88px_112px_112px_32px] items-center gap-2 pointer-coarse:grid-cols-[44px_minmax(0,1fr)_88px_112px_112px_44px]`,Fy=({items:e,label:t})=>{let[n,r]=(0,o.useState)(!1),i=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(!n)return;let e=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!i.current?.contains(e.target))&&r(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,e)}},[n]),(0,V.jsxs)(`div`,{ref:i,className:`relative flex justify-center`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":t,"aria-haspopup":`menu`,"aria-expanded":n,onClick:()=>r(!n),className:`inline-flex size-7 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-11`,children:(0,V.jsx)(Xe,{className:`size-4`})}),n&&(0,V.jsx)(`ul`,{role:`menu`,className:`absolute right-0 top-full z-30 mt-1 min-w-36 rounded-md border bg-background py-1 shadow-pop`,children:e.map(e=>(0,V.jsx)(`li`,{role:`none`,children:(0,V.jsx)(`button`,{type:`button`,role:`menuitem`,disabled:e.disabled,className:B(`block min-h-9 w-full whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted disabled:text-faint-foreground disabled:hover:bg-transparent`,e.destructive&&`text-danger-text`),onClick:()=>{r(!1),e.onSelect()},children:e.label})},e.label))})]})},Iy=({value:e,onCommit:t,format:n,parse:r,label:i,width:a=`w-full`})=>{let[s,c]=(0,o.useState)(null);return(0,V.jsx)(`input`,{"aria-label":i,inputMode:`decimal`,value:s??n(e),onFocus:e=>e.currentTarget.select(),onChange:e=>c(e.target.value),onBlur:()=>{if(s===null)return;let e=r(s);c(null),Number.isFinite(e)&&e>=0&&t(e)},onKeyDown:e=>e.key===`Enter`&&e.currentTarget.blur(),className:B(`h-7 rounded-md border border-transparent bg-transparent px-2 text-right tabular-nums text-foreground outline-none hover:border-border-strong focus:border-primary focus:bg-background focus:ring-2 focus:ring-primary/20`,a)})},Ly=e=>Math.round(Number(e.replace(`,`,`.`).replace(/[^0-9.]/g,``))*100),Ry=({line:e,position:t,count:n,reorderable:r,editable:i,onChange:a,onRemove:o,onMove:s})=>{let{attributes:c,listeners:l,setNodeRef:u,setActivatorNodeRef:d,transform:f,transition:p,isDragging:m}=hy({id:e.id,disabled:!r}),h=[...r?[{label:`Move up`,disabled:t===0,onSelect:()=>s(t-1)},{label:`Move down`,disabled:t===n-1,onSelect:()=>s(t+1)}]:[],...i?[{label:`Remove line`,destructive:!0,onSelect:o}]:[]];return(0,V.jsxs)(`div`,{ref:u,"data-line-id":e.id,style:{transform:f?`translate3d(0, ${f.y}px, 0)`:void 0,transition:p},className:B(`group relative border-b border-border bg-background px-2 py-1 last:border-b-0 hover:bg-surface`,Py,m&&`z-10 bg-surface opacity-80 shadow-pop`),children:[r?(0,V.jsx)(`button`,{ref:d,type:`button`,"aria-label":`Drag to reorder ${e.description}`,...c,...l,style:{touchAction:`none`},className:`flex size-7 cursor-grab items-center justify-center rounded text-faint-foreground opacity-60 hover:bg-muted hover:opacity-100 focus-visible:opacity-100 active:cursor-grabbing pointer-coarse:size-11`,children:(0,V.jsx)(ct,{className:`size-4`})}):(0,V.jsx)(`span`,{}),(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsx)(`p`,{className:`truncate text-foreground`,children:e.description}),(0,V.jsx)(`p`,{className:`font-mono text-[11px] text-faint-foreground`,children:e.productId})]}),i?(0,V.jsx)(Iy,{label:`Quantity`,value:e.quantity,format:String,parse:e=>Math.round(Number(e)),onCommit:e=>a({quantity:e})}):(0,V.jsx)(`span`,{className:`px-2 text-right tabular-nums`,children:e.quantity}),i?(0,V.jsx)(Iy,{label:`Unit price`,value:e.unitPriceCents,format:e=>(e/100).toFixed(2),parse:Ly,onCommit:e=>a({unitPriceCents:e})}):(0,V.jsx)(`span`,{className:`px-2 text-right tabular-nums`,children:(e.unitPriceCents/100).toFixed(2)}),(0,V.jsx)(`span`,{className:`px-2 text-right font-medium tabular-nums text-foreground`,children:Rd(ky(e))}),h.length>0?(0,V.jsx)(Fy,{label:`Actions for ${e.description}`,items:h}):(0,V.jsx)(`span`,{})]})},zy=(e,t,n)=>{if(t===n||t<0||t>=e.length)return[...e];let r=[...e],[i]=r.splice(t,1);return r.splice(Math.min(Math.max(n,0),r.length),0,i),r},By=({lines:e,vatRate:t})=>{let n=Ay(e,t);return(0,V.jsxs)(`dl`,{className:`ml-auto grid w-64 grid-cols-[1fr_auto] gap-x-6 gap-y-1 px-2 pt-3 tabular-nums`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:`Subtotal`}),(0,V.jsx)(`dd`,{className:`text-right text-foreground`,children:Rd(n.subtotalCents)}),(0,V.jsxs)(`dt`,{className:`text-muted-foreground`,children:[`VAT `,Math.round(t*100),`%`]}),(0,V.jsx)(`dd`,{className:`text-right text-foreground`,children:Rd(n.vatCents)}),(0,V.jsx)(`dt`,{className:`mt-1 border-t border-border pt-2 font-semibold text-foreground`,children:`Total`}),(0,V.jsx)(`dd`,{className:`mt-1 border-t border-border pt-2 text-right text-[16px] font-semibold text-foreground`,children:Rd(n.totalCents)})]})},Vy=`px-2 text-[11px] font-medium uppercase tracking-wide text-muted-foreground`,Hy=`To pick up a line, press space or enter on its drag handle. Use the up and down arrow keys to move it, space or enter to drop it, and escape to cancel. The row menu also has Move up and Move down.`,Uy=e=>{let t=t=>e.find(e=>e.id===t)?.description??`line`,n=t=>e.findIndex(e=>e.id===t)+1;return{onDragStart:({active:r})=>`Picked up ${t(r.id)}, line ${n(r.id)} of ${e.length}.`,onDragOver:({active:r,over:i})=>i?`${t(r.id)} is over line ${n(i.id)} of ${e.length}.`:void 0,onDragEnd:({active:r,over:i})=>i?`${t(r.id)} was dropped at line ${n(i.id)} of ${e.length}.`:`${t(r.id)} was dropped where it started.`,onDragCancel:({active:e})=>`Moving ${t(e.id)} was cancelled. It is back at line ${n(e.id)}.`}},Wy=({lines:e,onChange:t,onReorder:n,vatRate:r=.21,readOnly:i,reorderable:a=!i})=>{let o=Zg(Xg(F_,{activationConstraint:{distance:4}}),Xg(L_,{activationConstraint:{delay:250,tolerance:5}}),Xg(D_,{coordinateGetter:yy})),s=(r,i)=>{let a=e[r];!a||i<0||i>=e.length||r===i||(n??(e=>t(e)))(zy(e,r,i),{id:a.id,from:r,to:i})};return(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:[(0,V.jsxs)(`div`,{className:`${Py} border-b border-border bg-surface px-2 py-2`,children:[(0,V.jsx)(`span`,{}),(0,V.jsx)(`span`,{className:Vy,children:`Item`}),(0,V.jsx)(`span`,{className:`${Vy} text-right`,children:`Qty`}),(0,V.jsx)(`span`,{className:`${Vy} text-right`,children:`Unit price`}),(0,V.jsx)(`span`,{className:`${Vy} text-right`,children:`Line total`}),(0,V.jsx)(`span`,{})]}),(0,V.jsx)(kv,{sensors:o,collisionDetection:i_,onDragEnd:({active:t,over:n})=>{n&&t.id!==n.id&&s(e.findIndex(e=>e.id===t.id),e.findIndex(e=>e.id===n.id))},accessibility:{announcements:Uy(e),screenReaderInstructions:{draggable:Hy}},children:(0,V.jsx)(sy,{items:e.map(e=>e.id),strategy:ry,children:e.map((n,r)=>(0,V.jsx)(Ry,{line:n,position:r,count:e.length,reorderable:a,editable:!i,onChange:r=>t(e.map(e=>e.id===n.id?{...e,...r}:e)),onRemove:()=>t(e.filter(e=>e.id!==n.id)),onMove:e=>s(r,e)},n.id))})}),!i&&(0,V.jsx)(`div`,{className:`border-t border-border bg-surface px-2 py-1.5`,children:(0,V.jsxs)(U,{variant:`ghost`,size:`sm`,onClick:()=>{let n=Oy(e.length*3+1);t([...e,{id:`new-${e.length}-${n.id}`,productId:n.id,description:n.name,quantity:1,unitPriceCents:n.priceCents}])},children:[(0,V.jsx)(an,{className:`size-3.5`}),`Add line`]})})]}),(0,V.jsx)(By,{lines:e,vatRate:r})]})},Gy=`-my-0.5 rounded px-1.5 py-0.5 font-medium text-primary-text hover:bg-primary-soft`,Ky=({action:e})=>{if(`onClick`in e)return(0,V.jsx)(`button`,{type:`button`,onClick:e.onClick,className:Gy,children:e.label});let{href:t,onNavigate:n}=e;return(0,V.jsx)(`a`,{href:t,onClick:e=>{n&&lu(e)&&(e.preventDefault(),n(t))},className:Gy,children:e.label})},qy={loading:(0,V.jsx)(ld,{className:`text-primary`}),success:(0,V.jsx)(Oe,{className:`size-4 text-success`}),error:(0,V.jsx)(Me,{className:`size-4 text-danger`})},Jy=({state:e,title:t,description:n,action:r,onDismiss:i})=>(0,V.jsxs)(`div`,{role:e===`error`?`alert`:`status`,className:B(`flex w-full max-w-80 items-start gap-3 rounded-lg border bg-background p-3 shadow-pop [animation:pb-slide-in_160ms_ease-out]`,e===`error`&&`border-danger/40`),children:[(0,V.jsx)(`span`,{className:`mt-0.5`,children:qy[e]}),(0,V.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`p`,{className:`font-medium text-foreground`,children:t}),n&&(0,V.jsx)(`p`,{className:`mt-0.5 text-xs text-muted-foreground`,children:n})]}),r&&(0,V.jsx)(Ky,{action:r}),i&&(0,V.jsx)(`button`,{type:`button`,"aria-label":`Dismiss`,onClick:i,className:`inline-flex items-center justify-center rounded p-0.5 text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-9`,children:(0,V.jsx)($n,{className:`size-3.5`})})]}),Yy={loading:1/0,success:3500,error:8e3},Xy=8e3,Zy=(0,o.createContext)(null),Qy=()=>{let e=(0,o.useContext)(Zy);if(!e)throw Error(`useToast must be used inside ToastProvider`);return e},$y=({children:e})=>{let[t,n]=(0,o.useState)([]),r=(0,o.useRef)(1),i=(0,o.useRef)(new Map),a=(0,o.useCallback)(e=>{clearTimeout(i.current.get(e)),i.current.delete(e),n(t=>t.filter(t=>t.id!==e))},[]),s=(0,o.useCallback)((e,t,n=!1)=>{clearTimeout(i.current.get(e));let r=n?Xy:Yy[t];r!==1/0&&i.current.set(e,setTimeout(()=>a(e),r))},[a]),c=(0,o.useMemo)(()=>({show:e=>{let t=r.current++;return n(n=>[...n,{...e,id:t}]),s(t,e.state,!!e.action),t},update:(e,t)=>{n(n=>n.map(n=>n.id===e?{...n,...t}:n)),t.state&&s(e,t.state,!!t.action)},dismiss:a}),[a,s]);return(0,V.jsxs)(Zy.Provider,{value:c,children:[e,(0,V.jsx)(`div`,{className:`pointer-events-none fixed inset-x-4 bottom-24 z-[100] flex flex-col items-end gap-2 md:inset-x-auto md:bottom-4 md:right-4`,children:t.map(e=>(0,V.jsx)(`div`,{className:`pointer-events-auto`,children:(0,V.jsx)(Jy,{state:e.state,title:e.title,description:e.description,action:e.action,onDismiss:()=>a(e.id)})},e.id))})]})},eb=({name:e,label:t,required:n,help:r,example:i,error:a,conflict:s,wide:c,children:l})=>{let u=(0,o.useId)(),d=[r&&`${u}-help`,i&&`${u}-example`,a&&`${u}-error`].filter(Boolean).join(` `)||void 0;return(0,V.jsxs)(`div`,{className:c?`sm:col-span-2`:void 0,children:[(0,V.jsxs)(`div`,{className:`mb-1.5 flex items-center gap-2`,children:[(0,V.jsxs)(`label`,{htmlFor:u,className:`font-medium text-foreground`,children:[t,n&&(0,V.jsx)(`span`,{className:`ml-0.5 text-danger-text`,"aria-hidden":`true`,children:`*`})]}),s&&(0,V.jsxs)(`span`,{className:`inline-flex items-center gap-1.5 text-warning-text`,title:`${s.user.name} saved a different value`,children:[(0,V.jsx)(Vn,{className:`size-3.5`}),(0,V.jsx)(xu,{initials:s.user.initials,hue:s.user.hue,size:`xs`})]})]}),(0,V.jsx)(ad,{value:{id:u,name:e,describedBy:d,invalid:!!a,required:!!n},children:l}),r&&(0,V.jsx)(`p`,{id:`${u}-help`,className:`mt-1.5 text-xs text-muted-foreground`,children:r}),i&&(0,V.jsxs)(`p`,{id:`${u}-example`,className:`mt-0.5 text-xs text-faint-foreground`,children:[`Example: `,i]}),a&&(0,V.jsx)(`p`,{id:`${u}-error`,className:`mt-1.5 text-xs font-medium text-danger-text`,children:a}),s&&(0,V.jsxs)(`div`,{className:`mt-2 flex items-center justify-between gap-3 rounded-md border border-warning/30 bg-warning-soft px-3 py-2 text-xs text-warning-text`,children:[(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`strong`,{children:s.user.name}),` saved this `,s.ago,`: `,(0,V.jsx)(`strong`,{children:s.theirValue})]}),(0,V.jsxs)(`span`,{className:`flex gap-1.5`,children:[(0,V.jsx)(U,{size:`sm`,onClick:s.onKeepMine,children:`Keep mine`}),(0,V.jsx)(U,{size:`sm`,onClick:s.onUseTheirs,children:`Use theirs`})]})]})]})},tb=({title:e,help:t,actions:n,children:r})=>{let i=(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold text-foreground`,children:e});return(0,V.jsxs)(`section`,{className:`py-8 first:pt-8`,children:[n?(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-4 gap-y-2`,children:[i,n]}):i,t&&(0,V.jsx)(`p`,{className:`mt-1 max-w-xl leading-6 text-muted-foreground`,children:t}),(0,V.jsx)(`div`,{className:`mt-5`,children:r})]})},nb=`flex min-h-11 items-center gap-2 rounded-md border border-border-strong px-3 text-left hover:bg-surface disabled:cursor-default disabled:opacity-60 md:min-h-0 md:w-full md:items-start md:gap-3 md:rounded-none md:border-0 md:px-4 md:py-3`,rb=({actions:e})=>(0,V.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-border bg-background`,children:[(0,V.jsx)(`h3`,{className:`hidden border-b border-border px-4 py-2.5 text-xs font-semibold uppercase tracking-wide text-muted-foreground md:block`,children:`Actions`}),(0,V.jsx)(`ul`,{className:`flex flex-wrap gap-2 p-2 md:block md:divide-y md:divide-border md:p-0`,children:e.map(({name:e,description:t,icon:n,onRun:r,blocked:i,running:a,tone:o,render:s})=>{let c=(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(n,{className:B(`size-4 shrink-0 md:mt-0.5`,o===`danger`?`text-danger-text`:`text-muted-foreground`),"aria-hidden":!0}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`span`,{className:B(`block font-medium`,o===`danger`?`text-danger-text`:`text-foreground`),children:e}),t&&(0,V.jsx)(`span`,{className:`mt-0.5 hidden text-xs leading-snug text-muted-foreground md:block`,children:t})]})]});return(0,V.jsx)(`li`,{children:s?s({className:nb,children:c}):(0,V.jsx)(`button`,{type:`button`,onClick:r,disabled:!!i||a,title:i,className:nb,children:c})},e)})})]}),ib=({rows:e})=>(0,V.jsx)(`dl`,{className:`grid grid-cols-[auto_1fr] gap-x-4 gap-y-2`,children:e.map(e=>(0,V.jsxs)(`div`,{className:`contents`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:e.label}),(0,V.jsx)(`dd`,{className:`text-right tabular-nums text-foreground`,children:e.value})]},e.label))}),ab=({title:e,children:t})=>(0,V.jsxs)(`div`,{className:`rounded-lg border border-border bg-background p-4`,children:[(0,V.jsx)(`h3`,{className:`mb-3 text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e}),t]}),ob=({title:e,rows:t})=>t.length===0?null:(0,V.jsx)(ab,{title:e,children:(0,V.jsx)(ib,{rows:t})}),sb=({collection:e,title:t,status:n,lastEditedBy:r,presence:i=[],actions:a})=>(0,V.jsxs)(`header`,{className:`flex flex-col gap-4 border-b border-border pb-6 md:flex-row md:items-end md:justify-between md:gap-6`,children:[(0,V.jsxs)(`div`,{children:[e&&(0,V.jsx)(`p`,{className:`mb-1 text-xs text-muted-foreground`,children:e}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-1`,children:[(0,V.jsx)(`h1`,{className:`text-xl font-semibold tracking-tight text-foreground md:text-2xl`,children:t}),n&&(0,V.jsx)(Au,{tone:n.tone,children:n.label})]}),r&&(0,V.jsx)(`p`,{className:`mt-1.5 text-xs text-muted-foreground`,children:r.name?(0,V.jsxs)(V.Fragment,{children:[`Last edited by `,(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:r.name}),` `,r.ago]}):(0,V.jsxs)(V.Fragment,{children:[`Last updated `,r.ago]})})]}),(0,V.jsxs)(`div`,{className:`flex items-center gap-4`,children:[i.length>0&&(0,V.jsxs)(`span`,{className:`flex items-center gap-2 text-xs text-muted-foreground`,children:[(0,V.jsx)(Su,{people:i,size:`md`}),i.length,` viewing`]}),a]})]}),cb=({rows:e})=>(0,V.jsx)(`dl`,{className:`border-t border-border`,children:e.map(e=>(0,V.jsxs)(`div`,{className:B(`grid gap-x-4 border-b border-border py-2.5`,e.wide?`grid-cols-1 gap-y-1.5`:`grid-cols-[minmax(0,2fr)_minmax(0,3fr)]`),children:[(0,V.jsxs)(`dt`,{className:`min-w-0 text-muted-foreground`,children:[e.label,e.help&&(0,V.jsx)(`span`,{className:`mt-0.5 block text-xs text-faint-foreground`,children:e.help})]}),(0,V.jsx)(`dd`,{className:`min-w-0 break-words text-foreground`,children:e.value})]},e.label))}),lb=({facts:e})=>(0,V.jsx)(`dl`,{className:`grid grid-cols-2 gap-x-4 gap-y-5 sm:flex sm:flex-wrap sm:gap-x-10`,children:e.map(({label:e,value:t,icon:n})=>(0,V.jsxs)(`div`,{title:e,className:`flex min-w-0 flex-col gap-1.5`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:n?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(n,{className:`size-5`,"aria-hidden":!0}),(0,V.jsx)(`span`,{className:`sr-only`,children:e})]}):e}),(0,V.jsx)(`dd`,{className:`min-w-0 break-words text-[16px] font-semibold text-foreground`,children:t})]},e))}),ub=4,db=(e,t)=>{let n=e.bottom+ub;return{top:n+t>window.innerHeight-ub?Math.max(ub,e.top-ub-t):n,right:window.innerWidth-e.right}},fb=()=>{let[e,t]=(0,o.useState)(!1),[n,r]=(0,o.useState)(),i=(0,o.useRef)(null),a=(0,o.useRef)(null);return(0,o.useLayoutEffect)(()=>{if(!e||!i.current||!a.current){r(void 0);return}r(db(i.current.getBoundingClientRect(),a.current.offsetHeight))},[e]),(0,o.useEffect)(()=>{if(!e)return;let n=e=>i.current?.contains(e)||a.current?.contains(e),r=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!n(e.target))&&t(!1)},o=()=>t(!1);return document.addEventListener(`mousedown`,r),document.addEventListener(`keydown`,r),document.addEventListener(`scroll`,o,!0),window.addEventListener(`resize`,o),()=>{document.removeEventListener(`mousedown`,r),document.removeEventListener(`keydown`,r),document.removeEventListener(`scroll`,o,!0),window.removeEventListener(`resize`,o)}},[e]),{open:e,setOpen:t,place:n,button:i,menu:a}},pb=`flex w-full items-center gap-2 px-3 py-2.5 text-left hover:bg-muted disabled:cursor-default disabled:opacity-60`,mb=({actions:e,label:t=`Actions`,className:n})=>{let{open:r,setOpen:i,place:a,button:o,menu:s}=fb();return e.length===0?null:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{ref:o,type:`button`,"aria-label":t,"aria-haspopup":`menu`,"aria-expanded":r,onClick:()=>i(!r),className:n,children:(0,V.jsx)(Je,{className:`size-5`})}),r&&(0,nr.createPortal)((0,V.jsx)(`ul`,{ref:s,role:`menu`,"aria-label":t,style:a??{visibility:`hidden`},className:`fixed z-50 min-w-48 rounded-md border bg-background py-1 shadow-pop`,children:e.map(({name:e,icon:t,onRun:n,blocked:r,running:a,tone:o,render:s})=>{let c=(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(t,{className:B(`size-4 shrink-0`,o===`danger`?`text-danger-text`:`text-muted-foreground`),"aria-hidden":!0}),(0,V.jsx)(`span`,{className:B(`font-medium`,o===`danger`&&`text-danger-text`),children:e})]});return(0,V.jsx)(`li`,{role:`none`,onClick:()=>i(!1),children:s?s({className:pb,children:c,role:`menuitem`}):(0,V.jsx)(`button`,{type:`button`,role:`menuitem`,onClick:n,disabled:!!r||a,title:r,className:pb,children:c})},e)})}),document.body)]})},hb=e=>new Intl.NumberFormat(e).formatToParts(1.5).find(e=>e.type===`decimal`)?.value===`,`?`,`:`.`,gb=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),_b=(e,t)=>{let n=`[${gb(t===`.`?`,`:`.`)}\\s\\u00a0\\u202f']`,r=RegExp(`^([-+]?)(\\d{1,3}(?:${n}\\d{3})+|\\d+)(?:${gb(t)}(\\d+))?$`).exec(e.trim());if(r)return`${r[1]===`-`?`-`:``}${r[2].replace(/\D/g,``)}${r[3]?`.${r[3]}`:``}`;if(t===`.`&&/^[-+]?\d+(\.\d+)?e[-+]?\d+$/i.test(e.trim()))return String(Number(e.trim()))},vb=e=>typeof e==`object`&&!!e&&typeof e.uri==`string`,yb=e=>typeof e==`object`&&!!e&&typeof e.uploaded?.value==`string`,bb=e=>{if(yb(e))return{...e.uploaded.file,...e.preview&&{url:e.preview},corrected:e.uploaded.corrected};if(vb(e))return`missing`in e?{name:`File missing`,type:``,missing:!0}:e},xb=[`bytes`,`kB`,`MB`,`GB`],Sb=e=>{let t=e,n=0;for(;t>=1e3&&n<xb.length-1;)t/=1e3,n+=1;return n===0?`${e} ${e===1?`byte`:`bytes`}`:`${t<10?t.toFixed(1):Math.round(t)} ${xb[n]}`},Cb=e=>e.startsWith(`image/`)&&e!==`image/svg+xml`,wb=2,Tb=1e5,Eb=(e,t)=>(e.width!==void 0||e.height!==void 0)&&(e.width??Tb)>=t.width*wb&&(e.height??Tb)>=t.height*wb,Db=e=>(e.width??Tb)*(e.height??Tb),Ob=(e,t)=>{let n=bb(e);if(!(!n||`missing`in n||!n.url||!Cb(n.type)))return{url:(`variants`in n&&n.variants?Object.values(n.variants):[]).filter(e=>Eb(e,t)).sort((e,t)=>Db(e)-Db(t))[0]?.url??n.url,...`placeholder`in n&&n.placeholder!==void 0&&{placeholder:n.placeholder}}},kb=e=>{let t=e.file?.accept??[];return t.length===0||t.includes(`*/*`)?void 0:t.join(`,`)},Ab=e=>yb(e)?e.uploaded.value:vb(e)?e.uri:null,jb=(e,t)=>{if(yb(e))return!0;let n=e=>vb(e)?e.uri:null;return n(e)!==n(t)},Mb=e=>e==null?``:typeof e==`object`?JSON.stringify(e):String(e),Nb=new Set([`text`,`integer`,`bigint`,`decimal`,`date`,`currency`,`country`]),Pb=e=>!e.readOnly&&e.type!==`json`&&e.type!==`uuid`&&e.type!==`timestamp`&&e.type!==`relation`,Fb=e=>!e.readOnly&&!e.nullable&&e.type!==`boolean`,Ib=new Set([`integer`,`bigint`,`decimal`]),Lb=(e,t)=>_b(e,t)??e,Rb=(e,t,n=hb())=>{if(e.type===`boolean`)return!!t;if(e.type===`file`)return Ab(t);let r=String(t).trim();if(r===``)return e.nullable?null:``;let i=Ib.has(e.type)?Lb(r,n):r;if(e.type===`integer`)return Number(i);if(e.type===`relation`)return typeof t==`number`?t:i;if(Nb.has(e.type)||e.type===`enum`)return i;throw Error(`Not implemented: editing ${e.type} fields`)},zb=(e,t,n=hb())=>e.type===`boolean`?!!t:String(t??``).trim()===``?null:Rb(e,t,n),Bb=(e,t)=>e.type===`boolean`?!!t:Mb(t),Vb=(e,t,n,r=hb())=>{if(e.type===`boolean`)return!!t!=!!n;if(e.type===`file`)return jb(t,n);let i=String(t??``).trim(),a=Mb(n);return e.type===`decimal`||e.type===`integer`?i===``||a===``?i!==a:Number(Lb(i,r))!==Number(a):i!==a},Hb=(e,t,n)=>t?e===void 0||e===`edit`||n?{shown:`form`,offersEdit:!1,editing:!0}:{shown:e,offersEdit:t,editing:!1}:{shown:`read`,offersEdit:!1,editing:!1},Ub=(e,t,n)=>(e??t?.helpWhen??`always`)===`always`||n,Wb=(e,t,n)=>e?.help!==void 0&&Ub(e.helpWhen,t,n)?e.help:void 0,Gb=(e,t)=>e===`editing`?t:e!==`reading`||!t,Kb=e=>typeof e==`object`&&!!e&&`key`in e,qb=(e,t)=>t.name!==e.tenant&&!t.readOnly&&(t.type===`relation`||Pb(t)),Jb=(e,t)=>{let n=Object.values(e.fields).filter(t=>qb(e,t)).map(e=>e.name),r=new Set,i=(t?.layout??[]).flatMap(e=>{if(e.kind!==`section`||!Gb(e.when,!0))return[];let i=e.fields.filter(e=>n.includes(e)&&!r.has(e)&&Gb(t?.fields[e]?.when,!0));return i.forEach(e=>r.add(e)),i.length>0?[{title:e.title,help:e.help,fields:i}]:[]}),a=n.filter(e=>!r.has(e));return a.length===0?i:[...i,{title:i.length===0?`Details`:`Other fields`,fields:a}]},Yb=(e,t)=>(e?.primaryKey.length===1?e.fields[e.primaryKey[0]]?.type:void 0)===`integer`?Number(t):t,Xb=(e,t,n)=>Object.fromEntries(Object.entries(n).flatMap(([n,r])=>{let i=e.fields[n];return i?Kb(r)?[[n,Yb(t[i.relation?.resource??``],r.key)]]:i.type===`boolean`?[[n,!!r]]:i.type===`file`?r?[[n,Rb(i,r)]]:[]:String(r).trim()===``?[]:[[n,Rb(i,r)]]:[]})),Zb=e=>!e.nullable&&!e.default&&e.type!==`boolean`,Qb=(e,t)=>e.type===`relation`?{key:t,label:t}:e.type===`boolean`?t===`true`:t,$b=(e,t,n={})=>Object.fromEntries(t.flatMap(t=>t.fields.flatMap(t=>{let r=e.fields[t];if(Object.hasOwn(n,t))return[[t,Qb(r,n[t])]];let i=r.default;return!i||!(`value`in i)||i.value===null||i.value===void 0?[]:[[t,typeof i.value==`boolean`?i.value:String(i.value)]]}))),ex=e=>!!(e.default&&`db`in e.default),tx=({address:e,page:t,accountPage:n,resourceLabel:r,singular:i,recordTitle:a,recordLoading:o})=>{if(n)return[n];if(t)return[t.title];if(!e||e.kind===`page`)return[];let s=r?[r]:[];if(e.kind===`list`)return s;if(e.kind===`create`)return[...i?[`New ${i.toLowerCase()}`]:[],...s];let c=a??(o?void 0:e.key);return[...c?[c]:[],...s]},nx=(e,t)=>[...e.filter(Boolean),t].join(` · `),rx=e=>{(0,o.useEffect)(()=>{let t=document.title;return document.title=e,()=>{document.title=t}},[e])},ix=e=>{if(!Rs(e))return[{message:e instanceof Error?e.message:`Something went wrong`}];let t=e.errors.map(e=>({message:e.message,hint:e.hint}));return t.length>0?t:[{message:e.message}]},ax=({error:e,title:t})=>(0,V.jsxs)(`div`,{role:`alert`,className:`flex gap-2.5 rounded-lg border border-danger/30 bg-danger-soft px-3 py-2 text-danger-text`,children:[(0,V.jsx)(Vn,{className:`mt-0.5 size-4 shrink-0`}),(0,V.jsxs)(`div`,{children:[(0,V.jsx)(`p`,{className:`font-medium`,children:t}),ix(e).map(e=>(0,V.jsxs)(`p`,{className:`text-xs`,children:[e.message,e.hint&&(0,V.jsxs)(`span`,{className:`text-muted-foreground`,children:[` `,e.hint]})]},e.message))]})]}),ox=({checked:e,onChange:t,label:n})=>{let r=od();return(0,V.jsx)(`button`,{type:`button`,role:`switch`,id:r.id,"aria-describedby":r[`aria-describedby`],"aria-checked":e,"aria-label":n,onClick:()=>t?.(!e),className:B(`relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors`,e?`bg-primary`:`bg-border-strong`),children:(0,V.jsx)(`span`,{className:B(`size-4 rounded-full bg-white shadow transition-transform`,e?`translate-x-[18px]`:`translate-x-0.5`)})})},sx=e=>{e.style.height=`auto`,e.style.height=`${e.scrollHeight+e.offsetHeight-e.clientHeight}px`},cx=({invalid:e,className:t,rows:n=3,value:r,ref:i,...a})=>{let s=(0,o.useRef)(null),c=(0,o.useCallback)(e=>{s.current=e,typeof i==`function`?i(e):i&&(i.current=e)},[i]),l=od();return(0,o.useLayoutEffect)(()=>{s.current&&sx(s.current)},[r]),(0,o.useEffect)(()=>{let e=s.current;if(!e)return;let t=e.clientWidth,n=new ResizeObserver(()=>{e.clientWidth!==t&&(t=e.clientWidth,sx(e))});return n.observe(e),()=>n.disconnect()},[]),(0,V.jsx)(`textarea`,{ref:c,rows:n,value:r,className:B(`block w-full resize-none overflow-hidden rounded-md border bg-background px-2.5 py-1.5 text-body text-foreground shadow-sm outline-none placeholder:text-faint-foreground focus:border-primary focus:ring-2 focus:ring-primary/20`,e?`border-danger`:`border-border-strong`,t),...l,...e&&{"aria-invalid":!0},...a})},lx=e=>typeof e==`object`&&e&&`name`in e?String(e.name):String(e),ux=(e,t)=>{if(t==null)return`—`;switch(e.kind){case`text`:case`id`:return String(t);case`money`:return`${Rd(Number(t),e.currency,e.decimals)}${e.suffix??``}`;case`date`:return sf(Number(t));case`datetime`:return df(Number(t));case`number`:return`${Bd(Number(t))}${e.suffix??``}`;case`signed`:return`${Vd(Number(t))}${e.suffix??``}`;case`percent`:return Number(t)===0?`—`:Hd(Number(t));case`status`:return rs(String(t),e.labels);case`relation`:return lx(t);case`boolean`:return t?void 0:`No`;case`file`:return bb(t)?.name??`—`;case`user`:return Ey(String(t)).name}},dx=(e,t)=>Math.ceil(e.length*7.2)+24+(t?16:0)+28,fx=e=>Math.ceil(Math.max(0,...e.map(e=>e.length))*7.2)+56,px={body:7.5,mono:7.2,numeric:8},mx=24,hx=24,gx=16,_x=new Set([`status`,`money`,`number`,`signed`,`percent`,`date`,`datetime`,`boolean`]),vx=new Set([`money`,`number`,`signed`,`percent`,`date`,`datetime`]),yx=80,bx=400,xx=240,Sx=e=>e===`id`?px.mono:vx.has(e)?px.numeric:px.body,Cx=(e,t)=>e.value?e.value(t):t[e.id],wx=(e,t)=>{let n=t.map(t=>ux(e,Cx(e,t)));if(e.kind===`status`)return fx(n.map(e=>e??``));let r=e.kind===`user`||e.kind===`file`?hx:0;return Math.max(0,...n.map(t=>t===void 0?gx:Math.ceil(t.length*Sx(e.kind))))+r+mx},Tx=(e,t,n)=>Math.min(n,Math.max(t,e)),Ex=(e,t)=>{if(_x.has(e.kind)&&!e.title)return{...e,fixed:!0,width:Math.max(e.minWidth??0,t)};let n={...e,fixed:!1,width:Tx(t,yx,bx)};return e.kind===`id`?{...n,minWidth:Math.max(dx(e.header,e.sortable??!1),Math.min(t,xx))}:n},Dx=(e,t)=>{if(t.length===0)return e;let n=e.map(e=>e.render?e:Ex(e,wx(e,t))),r=n.filter((t,n)=>!t.fixed&&!t.title&&!e[n].render).map(e=>e.width),i=Math.max(0,...r);return n.map((t,n)=>t.title&&!e[n].render?{...t,width:Math.max(t.width,i)}:t)},Ox=[[/^\s*(```|~~~).*$/,``],[/^\s*\[[^\]]+\]:\s+\S.*$/,``],[/^\s*([-*_]\s*){3,}$/,``],[/^\s*\|?(\s*:?-+:?\s*\|)+\s*:?-*:?\s*$/,``],[/^\s*#{1,6}\s+/,``],[/^\s*(>\s?)+/,``],[/^\s*([-*+]|\d+[.)])\s+(\[[ xX]\]\s+)?/,``]],kx=[[/!\[([^\]]*)\]\([^)]*\)/g,`$1`],[/\[([^\]]*)\]\([^)]*\)/g,`$1`],[/\[([^\]]+)\]\[[^\]]*\]/g,`$1`],[/<((?:https?|mailto):[^>\s]+)>/gi,`$1`],[/<\/?[a-z][^>]*>/gi,``],[/`([^`]+)`/g,`$1`],[/(?<!\\)(\*\*|__)(?=\S)(.+?)(?<=\S)\1/g,`$2`],[/(?<![\\\w*])\*(?=\S)(.+?)(?<=\S)\*/g,`$1`],[/(?<![\\\w])_(?=\S)(.+?)(?<=\S)_(?!\w)/g,`$1`],[/(?<!\\)~~(.+?)~~/g,`$1`],[/\s*\|\s*/g,` `],[/\\([\\`*_{}[\]()#+\-.!>~|])/g,`$1`]],Ax=200,jx=e=>{let t=e.split(/\r?\n/).map(e=>Ox.reduce((e,[t,n])=>e.replace(t,n),e)),n=kx.reduce((e,[t,n])=>e.replace(t,n),t.join(`
|
|
12
|
-
`)).replace(/\s+/g,` `).trim();return n.length>Ax?`${n.slice(0,199).trimEnd()}…`:n},Mx=(e,t)=>e.type===`text`&&!!t?.markdown,Nx=[`name`,`title`,`number`,`sku`,`email`,`code`,`description`],Px=(e,t)=>t?.title??Nx.find(t=>e.fields[t]?.type===`text`)??Object.values(e.fields).find(e=>e.type===`text`)?.name??e.primaryKey[0],Fx=(e,t)=>t?.title??t?.list?.columns.find(t=>e.fields[t]?.type===`text`)??Px(e),Ix=(e,t,n,r)=>{let i=Fx(e,t),a=n[i];return a==null?r:e.fields[i]?.type===`enum`?rs(String(a),t?.fields[i]?.valueLabels):String(a)},Lx=(e,t,n)=>{let r=t[n];return e.fields[n]?.type===`relation`&&typeof r==`object`&&r&&`id`in r?r.id:r},Rx=(e,t)=>e.primaryKey.map(n=>String(Lx(e,t,n))).join(`,`),zx=(e,t)=>{let n=e.primaryKey.map(n=>Lx(e,t,n));return n.length===1?n[0]:n},Bx=new Set([`email`,`phone`,`url`]),Vx=e=>e?.format!==void 0&&Bx.has(e.format)?e.format:void 0,Hx=(e,t)=>{let n=t.trim();if(e===`email`)return/^[^\s@]+@[^\s@]+$/.test(n)?`mailto:${n}`:void 0;if(e===`phone`){let e=n.replace(/[^\d+]/g,``).replace(/(?!^)\+/g,``);return/\d/.test(e)?`tel:${e}`:void 0}return/^https?:\/\/\S+$/i.test(n)?n:void 0},Ux=e=>e===`email`?{type:`email`,inputMode:`email`,autoComplete:`email`}:e===`phone`?{type:`tel`,inputMode:`tel`,autoComplete:`tel`}:e===`url`?{type:`url`,inputMode:`url`,autoComplete:`url`}:{},Wx={draft:`neutral`,confirmed:`blue`,picking:`amber`,shipped:`violet`,delivered:`green`,cancelled:`red`,sent:`blue`,paid:`green`,overdue:`red`,lead:`blue`,active:`green`,dormant:`neutral`,receipt:`green`,issue:`blue`,transfer:`violet`,adjustment:`amber`},Gx=e=>Wx[e]??`neutral`,Kx={text:200,id:140,money:120,date:110,datetime:170,status:150,relation:200,boolean:64,number:100,signed:110,percent:110,user:130,file:180},qx=new Set([`datetime`,`date`,`boolean`,`percent`]),Jx=/^(number|sku|reference|code)$/,Yx=(e,t,n)=>{switch(e.type){case`relation`:return`relation`;case`file`:return`file`;case`enum`:return`status`;case`boolean`:return`boolean`;case`timestamp`:return`datetime`;case`date`:return`date`;case`decimal`:return t?.format===`percent`?`percent`:t?.prefix===`€`?`money`:`number`;case`integer`:case`bigint`:return/quantity|delta/.test(e.name)?`signed`:`number`;default:return Jx.test(e.name)||n===0&&e.name===`id`?`id`:`text`}},Xx=e=>Math.round(Number.parseFloat(String(e))*100),Zx=(e,t)=>t?.list?.columns??Object.keys(e.fields).slice(0,6),Qx=(e,t,n=[],r=Zx(e,t))=>{let i=Fx(e,t);return r.flatMap((r,a)=>{let o=e.fields[r];if(!o)return[];let s=t?.fields[r],c=Yx(o,s,a),l=Object.fromEntries((o.enumValues??[]).map(e=>[e,rs(e,s?.valueLabels)])),u=s?.suffix?Math.ceil(s.suffix.length*7.2):0;return[{id:r,header:s?.label??K(r),kind:c,width:(r===`name`?260:Kx[c])+u,sortable:o.sortable,minWidth:Math.max(c===`id`?150:0,dx(s?.label??K(r),o.sortable),c===`status`?fx(Object.values(l)):0,u>0?Kx[c]+u:0),...qx.has(c)&&{fixed:!0},...r===i&&{title:!0},...c===`text`&&r!==i&&Vx(s)&&{link:Vx(s)},...n.includes(r)&&{highlight:!0},...o.type===`enum`&&{tones:Object.fromEntries((o.enumValues??[]).map(e=>[e,Gx(e)])),labels:l},...o.type===`enum`&&s?.valueColors&&{colors:s.valueColors},...o.type===`enum`&&s?.badgeShape&&{shape:s.badgeShape},...s?.suffix!==void 0&&{suffix:s.suffix},...c===`money`&&s?.decimals!==void 0&&{decimals:s.decimals},...c===`money`&&{currency:`EUR`,value:e=>e[r]==null?null:Xx(e[r])},...(c===`datetime`||c===`date`)&&{value:e=>e[r]==null?null:Date.parse(String(e[r]))},...Mx(o,s)&&{value:e=>typeof e[r]==`string`?jx(e[r]):e[r]},...(c===`percent`||c===`number`&&o.type===`decimal`)&&{value:e=>e[r]==null?null:Number(e[r])}}]})},$x=(e,t)=>`${t.prefix??``}${e}${t.suffix??``}`,eS=(e,t,n={},r=Wd())=>{if(t==null||t===``)return`—`;switch(e.type){case`boolean`:return t?`Yes`:`No`;case`file`:return bb(t)?.name??`—`;case`enum`:return rs(String(t),n.valueLabels);case`timestamp`:return df(Date.parse(String(t)),r);case`date`:return sf(Date.parse(String(t)));case`decimal`:{let e=n.decimals===void 0?String(t):Number(t).toFixed(n.decimals);return n.format===`percent`?`${Number(t)}%`:$x(Number(e).toLocaleString(`en-IE`,{minimumFractionDigits:n.decimals??0,maximumFractionDigits:n.decimals??20}),n)}case`integer`:case`bigint`:return $x(String(t),n);default:return typeof t==`object`?JSON.stringify(t):String(t)}},tS=(e,t,n=Wd())=>{if(e.type!==`timestamp`||typeof t!=`string`)return;let r=Date.parse(t);return Number.isNaN(r)?void 0:`Shown in ${ef(r,n)}`},nS=`$photos`,rS=e=>{for(let t of e?.list?.displays??[])if(t.kind===`cards`&&t.photos)return t.photos},iS=(e,t,n)=>{if(n===void 0||e.primaryKey.length!==1)return t;let r=e.primaryKey[0];return t.map(e=>({...e,[nS]:n[String(e[r])]??[]}))},aS=(e,t)=>t.filter(t=>e[t]!==null&&e[t]!==void 0&&e[t]!==``),oS=(e,t,n)=>{let r=e.fields[n.by];if(!r)return[];let i=t?.fields[n.by],a=(r.enumValues??[]).map(e=>({value:e,label:rs(e,i?.valueLabels)}));return r.nullable?[...a,{value:null,label:`No ${(i?.label??K(n.by)).toLowerCase()}`}]:a},sS=(e,t,n)=>{let r=qa(n===null?lo.isNull(t):lo.eq(t,n));return e===``?r:`(${e}) AND ${r}`},cS=(e,t,n)=>({kind:`cards`,name:n.name,title:n.title??Fx(e,t),...n.subtitle!==void 0&&{subtitle:n.subtitle},...n.badge!==void 0&&{badge:n.badge},...n.meta&&{meta:n.meta}}),lS=e=>{if(!Rs(e))return e instanceof Error?e.message:`Something went wrong`;let t=e.errors.map(e=>e.message);return t.length>0?t.join(`; `):e.message},uS=e=>e?.list?.displays??[],dS=(e,t,n)=>{let r=n??e?.list?.default??`table`;if(!t)return r;let i=uS(e).filter(e=>e.kind===`cards`);return i.find(e=>e.name===r)?.name??i[0]?.name??r},fS=`rows`,pS=(e,t)=>{if(uS(t).some(e=>e.kind===`cards`||e.name===`rows`))return;let n=Fx(e,t),r=Zx(e,t).filter(t=>t!==n&&e.fields[t]!==void 0),i=r.find(t=>e.fields[t].type===`enum`),a=r.filter(t=>t!==i&&e.fields[t].type!==`boolean`).slice(0,2);return{kind:`cards`,name:fS,label:`List`,icon:`list`,title:n,...i!==void 0&&{badge:i},footer:a}},mS=(e,t)=>t.name===`rows`&&!uS(e).some(e=>e.name===`rows`),hS=(e,t,n)=>{let r=dS(t,n);return n&&r===`table`&&pS(e,t)?fS:r},gS=(e,t,n)=>(n===`rows`?pS(e,t):void 0)??_S(t,n),_S=(e,t)=>{if(t===`table`)return;let n=t=>uS(e).find(e=>e.name===t);return n(t)??n(e?.list?.default)},vS={cards:`cards`,map:`map`,board:`kanban`,calendar:`calendar`},yS=e=>[{name:xo,label:`Table`,icon:`table`},...uS(e).map(e=>({name:e.name,label:e.label??K(e.name),icon:e.icon??vS[e.kind]}))],bS=(e,t,n)=>{let r=yS(t);return n&&pS(e,t)?[...r,{name:fS,label:`List`,icon:`list`}]:r},xS=(e,t,n)=>({image:n.image,title:n.title??Fx(e,t),subtitle:n.subtitle,amount:n.amount??[],badge:n.badge,meta:n.meta??[],footer:n.footer??[],flags:n.flags??[]}),SS=(e,t)=>aS(e.record,t),CS=(e,t)=>SS(e,t)[0],wS=(e,t,n={})=>{let{suffix:r,...i}=n;return e.type!==`decimal`&&e.type!==`integer`&&e.type!==`bigint`||r===void 0||n.format===`percent`?{amount:eS(e,t,n)}:{amount:eS(e,t,i),suffix:r}},TS=(e,t)=>{let n=uS(e).filter(e=>e.kind===`cards`);return(t.cards===void 0?n[0]:n.find(e=>e.name===t.cards))??{kind:`cards`,name:t.name}},ES=(e,t,n)=>{if(n.kind===`custom`)return n.fields;if(n.kind===`map`)return[n.latitude,n.longitude,...ES(e,t,TS(t,n))];if(n.kind===`board`){let r=cS(e,t,n);return[n.by,r.title,r.subtitle,r.badge,...r.meta??[]].filter(e=>e!==void 0)}if(n.kind===`calendar`)return[n.start,n.end,n.title??Fx(e,t)].filter(e=>e!==void 0);let{image:r,title:i,subtitle:a,amount:o,badge:s,meta:c,footer:l,flags:u}=xS(e,t,n);return[r,i,a,...o,s,...c,...l,...u].filter(e=>e!==void 0)},DS=(e,t,n)=>{let r=pS(e,t),i=r?[...uS(t),r]:uS(t);return[...new Set([...n,...i.flatMap(n=>ES(e,t,n))])]},OS=(e,t,n)=>{let r=mS(t,n)?[Fx(e,t),...Zx(e,t)]:ES(e,t,n);return[...new Set(r)].filter(t=>e.fields[t]?.sortable)},kS=e=>typeof e==`object`&&!!e&&`id`in e&&`name`in e,AS=(e,t)=>{let n={},r={},i=Array.isArray(t.$photos)?t[nS]:void 0;for(let[i,a]of Object.entries(t))(i!==`id`&&i!==`$photos`||Object.hasOwn(e.fields,i))&&(e.fields[i]?.type===`relation`&&kS(a)?(n[i]=a.id,r[i]=a.name):n[i]=a);return{key:Ao(zx(e,n)),record:n,labels:r,...i&&{photos:i}}},jS=(e,t)=>{let n=t?.list?.sort?.[0];return n?`${n[0]} ${n[1]}`:`${e.primaryKey[0]} asc`},MS=e=>{let[t=``,n]=e.trim().split(/\s+/);return{columnId:t,direction:n===`desc`?`desc`:`asc`}},NS=e=>`${e.columnId} ${e.direction}`,PS=(e,t,n)=>{let r=e[n],i=t[n]?.listOf,a=i===void 0?void 0:r?.fields[i]?.relation?.resource;return a!==void 0&&e[a]?{model:e[a],view:t[a],listOf:!0}:{model:r,view:t[n],listOf:!1}},FS=(e,t,n=!1)=>({display:e?hS(e,t,n):dS(t,n),orderBy:e?jS(e,t):``,filterLayout:`bar`}),IS=(e,t)=>e?.kind===`record`?{kind:`record`,resource:e.resource,key:Ao(e.key),...e.edit&&{edit:!0}}:e?.kind===`list`?{...t(e.resource),filter:``,...e}:e,LS=(e,t,n)=>{let r={...e,...t},i=e=>r[e]!==void 0&&r[e]!==n[e];return{kind:`list`,resource:e.resource,...r.filter&&{filter:r.filter},...i(`display`)&&{display:r.display},...i(`orderBy`)&&{orderBy:r.orderBy},...i(`filterLayout`)&&{filterLayout:r.filterLayout},...r.map&&{map:r.map},...r.calendar&&{calendar:r.calendar},...r.savedSearch&&{savedSearch:r.savedSearch}}},RS=(0,o.createContext)(null),zS={create:!0,update:!0,delete:!0,conditional:[]},BS=()=>{let e=G(),t=Gp(),n=(0,o.useContext)(RS),r=mh({queryKey:W.meta,staleTime:0,refetchOnWindowFocus:`always`,queryFn:async()=>{let n=t.getQueryData(W.meta),r=await e.meta(n?.etag);if(r.status===`unchanged`){if(!n)throw Error(`The server answered 304 to a request without If-None-Match`);return n}return{etag:r.etag,appName:r.meta.appName,resources:Object.fromEntries(r.meta.resources.map(e=>[e.name,e])),views:Object.fromEntries(r.meta.views.map(e=>[e.resource,e])),pages:Object.fromEntries((r.meta.pages??[]).map(e=>[e.name,e])),permissions:r.meta.permissions??{},...r.meta.userMenu&&{userMenu:r.meta.userMenu},...r.meta.signIn&&{signIn:Object.fromEntries(r.meta.signIn.map(e=>[e.resource,e]))},...r.meta.bottomBar&&{bottomBar:r.meta.bottomBar},...r.meta.assistant&&{assistant:r.meta.assistant},...r.meta.runtime&&{runtime:r.meta.runtime},...r.meta.errorReporting&&{errorReporting:r.meta.errorReporting},...r.meta.maps&&{maps:r.meta.maps},...r.meta.files&&{files:r.meta.files},...r.meta.plugins&&{plugins:r.meta.plugins},...r.meta.sources&&{sources:r.meta.sources.map(e=>({source:e,state:`loading`}))}}}});return(0,o.useMemo)(()=>n&&r.data?{...r,data:n}:r,[n,r])},VS=1e4,HS=e=>e.map(e=>({data:e.data?.meta,error:e.error})),US=(e,t)=>{let n=Gp(),r=fh({queries:e.map(e=>{let r=W.sourceMeta(e.url,e.resources);return{queryKey:r,staleTime:0,refetchOnWindowFocus:`always`,queryFn:async()=>{let i=n.getQueryData(r),a=await t(e).meta(i?.etag,{signal:AbortSignal.timeout(VS)});if(a.status===`unchanged`){if(!i)throw Error(`${e.label} answered 304 to a request without If-None-Match`);return i}return{etag:a.etag,meta:fc(a.meta,e)}}}}),combine:HS});return(0,o.useMemo)(()=>e.map((e,t)=>{let{data:n,error:i}=r[t];return n?{source:e,state:`ready`,meta:n}:i?{source:e,state:`error`,error:i}:{source:e,state:`loading`}}),[e,r])},WS=(e,t)=>{if(t.length===0)return e;let n=t.flatMap(e=>e.state===`ready`?[e.meta]:[]),r=t.map(e=>e.state===`error`?{source:e.source,state:`error`,error:e.error}:{source:e.source,state:e.state});return{...e,resources:{...e.resources,...Object.fromEntries(n.flatMap(e=>e.resources.map(e=>[e.name,e])))},views:{...e.views,...Object.fromEntries(n.flatMap(e=>e.views.map(e=>[e.resource,e])))},permissions:{...e.permissions,...Object.assign({},...n.map(e=>e.permissions))},sources:r}},GS=(e,t)=>e.sources?.find(e=>e.source.resources.includes(t)),J=()=>{let e=(0,o.useContext)(RS);if(!e)throw Error(`useAdminMeta must be used inside MetaGate`);return e},KS=({title:e,children:t})=>(0,V.jsx)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center p-8`,children:(0,V.jsxs)(`div`,{className:`max-w-md text-center`,children:[(0,V.jsx)(`h1`,{className:`text-[16px] font-semibold`,children:e}),(0,V.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:t})]})}),qS=({meta:e,children:t})=>{let n=G(),r=Rne(),i=(0,o.useMemo)(()=>(e.sources??[]).map(e=>e.source),[e.sources]),a=US(i,r),s=(0,o.useMemo)(()=>WS(e,a),[e,a]),c=(0,o.useMemo)(()=>{let e=new Map(i.flatMap(e=>e.resources.map(t=>[t,e]))),t=t=>{let n=e.get(t);return n&&r(n)};return{client:$s(n,t),resourceClient:t}},[i,n,r]);return(0,V.jsx)(zne,{client:c.client,resourceClient:c.resourceClient,children:(0,V.jsx)(RS.Provider,{value:s,children:t})})},JS=({children:e})=>{let t=BS();return t.isPending?(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]}):t.error?(0,V.jsx)(KS,{title:`Cannot reach the API`,children:Rs(t.error)?t.error.message:`The server did not answer. Is it running?`}):(0,V.jsx)(qS,{meta:t.data,children:e})},YS=e=>J().permissions[e]??zS,XS=()=>{let{path:e,params:t,basePath:n,navigate:r}=wh(),{pages:i,resources:a,views:s}=J(),c=ql(),l=(0,o.useMemo)(()=>new Set(Object.keys(i)),[i]),u=t.toString(),d=(0,o.useMemo)(()=>_s(u?`${e}?${u}`:e,l),[e,u,l]),f=(0,o.useCallback)(e=>{let t=PS(a,s,e);return FS(t.model,t.view,c)},[a,s,c]),p=(0,o.useMemo)(()=>IS(d,f),[d,f]),m=(0,o.useCallback)((e,t)=>r(ps(e),t),[r]),h=(0,o.useCallback)(e=>{if(d?.kind!==`list`)throw Error(`listTo and set change the list the app shows; use go to move to another address`);return LS(d,e,f(d.resource))},[d,f]);return{address:p,set:(0,o.useCallback)(e=>m(h(e),{replace:!0}),[h,m]),listTo:h,go:m,href:(0,o.useCallback)(e=>ps(e,n),[n]),open:(0,o.useCallback)(e=>r(e.startsWith(`${n}/`)?e.slice(n.length):e),[n,r])}},ZS=({to:e,...t})=>(0,V.jsx)(Vne,{to:ps(e),...t}),QS=(e,{filter:t,orderBy:n,pageSize:r=50,fields:i,startToken:a=``,enabled:o=!0}={})=>{let s=G(),c=Ts(t)??``,l=gh({queryKey:[...W.list(e,c,n??``,r,a),i?.join(`,`)??``],enabled:o,initialPageParam:a,queryFn:({pageParam:t})=>s.list(e,{filter:c,orderBy:n,pageSize:r,fields:i,pageToken:t}),getNextPageParam:e=>e.nextPageToken||void 0}),u=l.data?.pages??[];return{...l,items:u.flatMap(e=>e.items),totalEstimate:u[0]?.totalSizeEstimate}},$S=co(),eC=e=>e.split(/\s+/).filter(Boolean),tC=(e,t,n,r=!1)=>{let i=eC(n);if(i.length===0)return{filter:void 0,local:!1};if(r)return{filter:void 0,local:!0};if(e.search?.length)return{filter:qa($S.search(n)),local:!1};let a=e.fields[t];if(a?.type!==`text`||!a.filterable)return{filter:void 0,local:!0};let o=i.map(e=>$S.eq(t,`*${e.replaceAll(`*`,``)}*`));return{filter:qa($S.and(...o)),local:!1}},nC=(e,t)=>{if(e==null)return!1;let n=String(e).toLowerCase();return eC(t).every(e=>n.includes(e.toLowerCase()))},rC=(e,t,n,r)=>{(0,o.useEffect)(()=>{if(!e||!t)return;let n=new IntersectionObserver(e=>e.some(e=>e.isIntersecting)&&r(),{root:e});return n.observe(t),()=>n.disconnect()},[e,t,n,r])},iC=({target:e,view:t,value:n,label:r,invalid:i,onChange:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)(-1),[p,m]=(0,o.useState)(null),[h,g]=(0,o.useState)(null),_=(0,o.useId)(),v=e.primaryKey[0],y=Px(e,t),[b,x]=(0,o.useState)(!1),S=tC(e,y,s,b),C=QS(e.name,{filter:S.filter,fields:[v,y],enabled:l}),w=S.filter!==void 0&&C.error instanceof Is&&C.error.slug===`expensive-query`;(0,o.useEffect)(()=>{w&&x(!0)},[w]);let T=S.local?C.items.filter(e=>nC(e[y],s)):C.items,E=!!C.hasNextPage,D=C.isPending||C.isFetchingNextPage,{fetchNextPage:O}=C;rC(p,h,C.items.length,(0,o.useCallback)(()=>O({cancelRefetch:!1}),[O]));let k=e=>`${_}-${e}`,A=(0,o.useRef)(null);(0,o.useEffect)(()=>{!l&&document.activeElement===A.current&&A.current?.select()},[l]),(0,o.useEffect)(()=>{l&&d>=0&&document.getElementById(k(d))?.scrollIntoView({block:`nearest`})});let j=()=>{c(``),f(-1),u(!1)},M=e=>{a(String(e[v]),String(e[y])),j()};return(0,V.jsxs)(`div`,{className:`relative`,children:[(0,V.jsx)(sd,{ref:A,role:`combobox`,"aria-autocomplete":`list`,"aria-expanded":l,"aria-controls":_,"aria-activedescendant":l&&T[d]?k(d):void 0,invalid:i,placeholder:`Search ${(t?.names?.plural??K(e.name)).toLowerCase()}`,value:l?s:r??n,onFocus:()=>u(!0),onBlur:j,onKeyDown:e=>{if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),!l)return u(!0);let t=e.key===`ArrowDown`?1:-1;f(e=>Math.min(Math.max(e+t,0),T.length-1));return}if(e.key===`Enter`&&l&&T[d]){e.preventDefault(),M(T[d]);return}e.key===`Escape`&&l&&(e.preventDefault(),e.stopPropagation(),j())},onChange:e=>{c(e.target.value),f(e.target.value.trim()?0:-1),u(!0)}}),l&&(0,V.jsxs)(`ul`,{ref:m,id:_,role:`listbox`,className:`absolute z-30 mt-1 max-h-60 w-full overflow-y-auto rounded-md border bg-background py-1 shadow-pop`,onMouseDown:e=>e.preventDefault(),children:[T.map((e,t)=>(0,V.jsx)(`li`,{id:k(t),role:`option`,"aria-selected":t===d,className:B(`cursor-pointer truncate px-3 py-1.5`,t===d&&`bg-muted`,String(e[v])===n&&`font-medium`),onMouseMove:()=>t!==d&&f(t),onClick:()=>M(e),children:String(e[y])},String(e[v]))),E&&(0,V.jsx)(`li`,{ref:g,"aria-hidden":!0,className:`h-px`}),C.error&&!w&&(0,V.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`Could not load the options`}),!E&&!D&&!C.error&&T.length===0&&(0,V.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`No matches`}),D&&(0,V.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`Loading`})]})]})},aC=`••••••••••`,oC=({field:e,hints:t,value:n,reveal:r,locked:i,invalid:a,placeholder:s,onChange:c})=>{let[l,u]=(0,o.useState)(!1),d=hh({mutationFn:async()=>r(),onSuccess:()=>u(!0)}),f=Mb(n)!==``,p=t?.label??K(e.name),m=(0,V.jsx)(U,{variant:`ghost`,size:`sm`,className:`-mr-1.5 px-1.5`,"aria-label":`${l?`Hide`:`Show`} ${p}`,"aria-pressed":l,loading:d.isPending,onClick:()=>{l||f||!r||d.isSuccess?u(!l):d.mutate()},children:!d.isPending&&(l?(0,V.jsx)(eee,{className:`size-3.5`}):(0,V.jsx)(tt,{className:`size-3.5`}))}),h=d.error&&(0,V.jsx)(`div`,{className:`mt-2`,children:(0,V.jsx)(ax,{title:`Could not show the ${p}`,error:d.error})});if(i)return(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2 py-1`,children:[(0,V.jsx)(`span`,{className:B(l?t?.format===`code`?`font-mono text-xs`:``:`tracking-widest text-muted-foreground`),children:l?eS(e,d.data,t):aC}),r&&m]}),h]});let g=f?Mb(n):l&&d.isSuccess?Mb(d.data):``;return(0,V.jsxs)(`div`,{children:[(0,V.jsx)(sd,{type:l?`text`:`password`,autoComplete:`off`,invalid:a,"aria-label":p,className:B(t?.format===`code`&&`font-mono text-xs`),placeholder:f||!r?s:aC,value:g,trailing:m,onChange:e=>c(e.target.value)}),h]})};function sC(e){let{PI:t,min:n,max:r,cos:i,round:a}=Math,o=e[0]|e[1]<<8|e[2]<<16,s=e[3]|e[4]<<8,c=(o&63)/63,l=(o>>6&63)/31.5-1,u=(o>>12&63)/31.5-1,d=(o>>18&31)/31,f=o>>23,p=(s>>3&63)/63,m=(s>>9&63)/63,h=s>>15,g=r(3,h?f?5:7:s&7),_=r(3,h?s&7:f?5:7),v=f?(e[5]&15)/15:1,y=(e[5]>>4)/15,b=f?6:5,x=0,S=(t,n,r)=>{let i=[];for(let a=0;a<n;a++)for(let o=+!a;o*n<t*(n-a);o++)i.push(((e[b+(x>>1)]>>((x++&1)<<2)&15)/7.5-1)*r);return i},C=S(g,_,d),w=S(3,3,p*1.25),T=S(3,3,m*1.25),E=f&&S(5,5,y),D=cC(e),O=a(D>1?32:32*D),k=a(D>1?32/D:32),A=new Uint8Array(O*k*4),j=[],M=[];for(let e=0,a=0;e<k;e++)for(let o=0;o<O;o++,a+=4){let s=c,d=l,p=u,m=v;for(let e=0,n=r(g,f?5:3);e<n;e++)j[e]=i(t/O*(o+.5)*e);for(let n=0,a=r(_,f?5:3);n<a;n++)M[n]=i(t/k*(e+.5)*n);for(let e=0,t=0;e<_;e++)for(let n=+!e,r=M[e]*2;n*_<g*(_-e);n++,t++)s+=C[t]*j[n]*r;for(let e=0,t=0;e<3;e++)for(let n=+!e,r=M[e]*2;n<3-e;n++,t++){let e=j[n]*r;d+=w[t]*e,p+=T[t]*e}if(f)for(let e=0,t=0;e<5;e++)for(let n=+!e,r=M[e]*2;n<5-e;n++,t++)m+=E[t]*j[n]*r;let h=s-2/3*d,y=(3*s-h+p)/2,b=y-p;A[a]=r(0,255*n(1,y)),A[a+1]=r(0,255*n(1,b)),A[a+2]=r(0,255*n(1,h)),A[a+3]=r(0,255*n(1,m))}return{w:O,h:k,rgba:A}}function cC(e){let t=e[3],n=e[2]&128,r=e[4]&128;return(r?n?5:7:t&7)/(r?t&7:n?5:7)}function lC(e,t,n){let r=e*4+1,i=6+t*(5+r),a=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,e>>8,e&255,0,0,t>>8,t&255,8,6,0,0,0,0,0,0,0,i>>>24,i>>16&255,i>>8&255,i&255,73,68,65,84,120,1],o=[0,498536548,997073096,651767980,1994146192,1802195444,1303535960,1342533948,-306674912,-267414716,-690576408,-882789492,-1687895376,-2032938284,-1609899400,-1111625188],s=1,c=0;for(let e=0,i=0,o=r-1;e<t;e++,o+=r-1)for(a.push(e+1<t?0:1,r&255,r>>8,~r&255,r>>8^255,0),c=(c+s)%65521;i<o;i++){let e=n[i]&255;a.push(e),s=(s+e)%65521,c=(c+s)%65521}a.push(c>>8,c&255,s>>8,s&255,0,0,0,0,0,0,0,0,73,69,78,68,174,66,96,130);for(let[e,t]of[[12,29],[37,41+i]]){let n=-1;for(let r=e;r<t;r++)n^=a[r],n=n>>>4^o[n&15],n=n>>>4^o[n&15];n=~n,a[t++]=n>>>24,a[t++]=n>>16&255,a[t++]=n>>8&255,a[t++]=n&255}return`data:image/png;base64,`+btoa(String.fromCharCode(...a))}function uC(e){let t=sC(e);return lC(t.w,t.h,t.rgba)}var dC=(e,t,n)=>{if(!URL.canParse(e,t))return`no-referrer`;let r=new URL(e,t);if((r.protocol===`http:`||r.protocol===`https:`)&&!(r.origin===new URL(t).origin||n.includes(r.hostname)))return`no-referrer`},fC=e=>URL.canParse(e)?[new URL(e).hostname]:[],pC=()=>{let e=(0,o.useContext)(RS);return(0,o.useMemo)(()=>[...e?.files?.trustedHosts??[],...(e?.sources??[]).flatMap(({source:e})=>fC(e.url))],[e?.files,e?.sources])},mC=e=>{let t;try{t=atob(e)}catch(e){if(e instanceof DOMException&&e.name===`InvalidCharacterError`)return;throw e}return uC(Uint8Array.from(t,e=>e.charCodeAt(0)))},hC=({image:e,className:t,loading:n})=>{let[r,i]=(0,o.useState)(),a=pC(),s=(0,o.useMemo)(()=>e.placeholder===void 0?void 0:mC(e.placeholder),[e.placeholder]),c=s!==void 0&&r!==e.url;return(0,V.jsx)(`img`,{src:e.url,alt:``,loading:n,decoding:`async`,referrerPolicy:dC(e.url,window.location.href,a),onLoad:()=>i(e.url),className:t,style:c?{backgroundImage:`url("${s}")`,backgroundSize:`cover`,backgroundPosition:`center`}:void 0})},gC=({value:e})=>{let t=Ob(e,{width:40,height:40});return t?(0,V.jsx)(hC,{image:t,className:`size-10 shrink-0 rounded border border-border object-cover`}):(0,V.jsx)(`span`,{className:`flex size-10 shrink-0 items-center justify-center rounded border border-border bg-muted text-muted-foreground`,children:(0,V.jsx)(ot,{className:`size-4`})})},_C=({value:e})=>{let t=bb(e);if(!t)return(0,V.jsx)(`div`,{className:`py-1.5 text-muted-foreground`,children:`—`});if(`missing`in t)return(0,V.jsx)(`div`,{className:`py-1.5 text-danger-text`,children:`The file is missing from storage`});let n=`url`in t?t.url:void 0,r=`corrected`in t?t.corrected:void 0;return(0,V.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3 py-1`,children:[(0,V.jsx)(gC,{value:e}),(0,V.jsxs)(`div`,{className:`min-w-0`,children:[n&&!n.startsWith(`blob:`)?(0,V.jsx)(`a`,{href:n,target:`_blank`,rel:`noreferrer`,className:`block truncate font-medium text-primary-text hover:underline`,children:t.name}):(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:t.name}),(0,V.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t.type,t.size!==void 0&&` · ${Sb(t.size)}`,r&&` · sent as ${r.from}`]})]})]})},vC=({field:e,hints:t,resource:n,value:r,locked:i,invalid:a,onChange:s})=>{let c=G(),l=(0,o.useRef)(null),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(!1),m=t?.label??K(e.name),h=hh({mutationFn:async t=>{d(0);let r=await c.upload(n,e.name,t,{onProgress:(e,t)=>d(t>0?e/t:0)});return{uploaded:r,...Cb(r.file.type)&&{preview:URL.createObjectURL(t)}}},onSuccess:e=>s(e),onSettled:()=>d(void 0)});if(i||e.readOnly)return(0,V.jsx)(_C,{value:r});let g=e=>{let t=e?.[0];t&&h.mutate(t)},_=e=>{e.preventDefault(),p(!1),g(e.dataTransfer.files)},v=(0,V.jsx)(`input`,{ref:l,type:`file`,hidden:!0,accept:kb(e),"aria-label":`Choose a file for ${m}`,onChange:e=>g(e.target.files)}),y=h.error&&(0,V.jsx)(`div`,{className:`mt-2`,children:(0,V.jsx)(ax,{title:`Not uploaded`,error:h.error})});return h.isPending?(0,V.jsxs)(`div`,{className:`py-1.5`,role:`status`,"aria-label":`Uploading ${m}`,children:[(0,V.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-muted`,children:(0,V.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-[width]`,style:{width:`${Math.round((u??0)*100)}%`}})}),(0,V.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`Uploading… `,Math.round((u??0)*100),`%`]})]}):bb(r)?(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,V.jsx)(_C,{value:r})}),(0,V.jsx)(U,{size:`sm`,onClick:()=>l.current?.click(),children:`Replace`}),e.nullable&&(0,V.jsx)(U,{size:`sm`,variant:`ghost`,onClick:()=>s(null),children:`Remove`})]}),v,y]}):(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),p(!0)},onDragLeave:()=>p(!1),onDrop:_,className:B(`flex items-center gap-3 rounded-md border border-dashed px-3 py-2.5 text-muted-foreground`,f?`border-primary bg-primary/5`:a?`border-danger`:`border-border-strong`),children:[(0,V.jsx)(Gn,{className:`size-4 shrink-0`}),(0,V.jsx)(`span`,{className:`flex-1`,children:`Drop a file here or`}),(0,V.jsxs)(U,{size:`sm`,onClick:()=>l.current?.click(),children:[(0,V.jsx)(en,{className:`size-3.5`}),`Choose a file`]})]}),v,y]})},yC=e=>e,bC=e=>e,xC=(0,o.createContext)({}),SC=()=>(0,o.useContext)(xC),CC=(e,t,n)=>{let r=n?.widget;if(!r||t.sensitive||!e||!Object.hasOwn(e,r.name))return;let i=e[r.name];return i.of.includes(t.type)?{name:r.name,widget:i,props:r.props??{}}:void 0},wC=(e,t)=>CC(SC().fields,e,t),TC=({shown:e,part:t,field:n,value:r,onChange:i,invalid:a=!1})=>{let{widget:o,props:s}=e,c={field:n,value:r??null,props:s};if(t!==`editor`){let e=t===`cell`?o.cell??o.display:o.display;return(0,V.jsx)(e,{...c})}let l=o.editor;return l&&i?(0,V.jsx)(l,{...c,onChange:i,invalid:a}):void 0},EC=({fallback:e,...t})=>{let n=TC(t);return n?(0,V.jsx)(Qh,{name:`The field type ${t.shown.name}`,fallback:e,children:n}):e},DC=(0,o.lazy)(()=>qh(()=>import(`./markdown-content-DT_18T89.js`).then(e=>({default:e.MarkdownContent})),__vite__mapDeps([0,1,2,3]))),OC=e=>(0,V.jsx)(o.Suspense,{fallback:(0,V.jsx)(`div`,{className:B(`whitespace-pre-line break-words`,e.className),children:e.source}),children:(0,V.jsx)(DC,{...e})}),kC=[{value:`write`,label:`Write`},{value:`preview`,label:`Preview`}],AC=({value:e,onChange:t,label:n,invalid:r,placeholder:i})=>{let[a,s]=(0,o.useState)(`write`);return(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsx)(`span`,{className:`self-start`,children:(0,V.jsx)(Pu,{value:a,options:kC,onChange:s,label:n})}),a===`write`?(0,V.jsx)(cx,{rows:5,invalid:r,placeholder:i,value:e,onChange:e=>t(e.target.value)}):(0,V.jsx)(`div`,{className:`min-h-[7.5rem] rounded-md border border-border px-2.5 py-1.5`,children:e.trim()===``?(0,V.jsx)(`span`,{className:`text-faint-foreground`,children:`Nothing to preview`}):(0,V.jsx)(OC,{source:e})})]})},jC=new Set([`integer`,`bigint`,`decimal`]),MC=e=>e===`integer`||e===`bigint`?{inputMode:`numeric`,enterKeyHint:`done`}:e===`decimal`?{inputMode:`decimal`,enterKeyHint:`done`}:{},NC=e=>e.stopPropagation(),PC=({format:e,value:t,className:n})=>{let r=Hx(e,t);return r?(0,V.jsx)(`a`,{href:r,...e===`url`?{target:`_blank`,rel:`noreferrer`}:{},onClick:NC,className:B(`font-medium text-primary-text hover:underline`,n),children:t}):(0,V.jsx)(`span`,{className:n,children:t})},FC=({field:e,hints:t,value:n,stored:r,relationLabel:i,relationTo:a,relationPicker:o,invalid:s,locked:c,placeholder:l,reveal:u,resource:d,onChange:f})=>{let p=od();if(e.type===`file`)return(0,V.jsx)(vC,{field:e,hints:t,resource:d??``,value:n,locked:c||!d,invalid:s,onChange:f});if(e.sensitive)return(0,V.jsx)(oC,{field:e,hints:t,value:n,reveal:u,locked:c||e.readOnly,invalid:s,placeholder:l,onChange:f});if(e.type===`relation`&&o&&!e.readOnly&&!c){let e=(0,V.jsx)(iC,{target:o.target,view:o.view,value:String(n),label:i,invalid:s,onChange:(e,t)=>f({key:e,label:t})});return a?(0,V.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,V.jsx)(`div`,{className:`min-w-0 flex-1`,children:e}),(0,V.jsx)(ZS,{to:a,"aria-label":`Open ${i??String(n)}`,title:`Open`,className:B(Cf({variant:`ghost`}),`w-8 px-0`),children:(0,V.jsx)(O,{className:`size-4`})})]}):e}if(e.type===`boolean`&&c)return(0,V.jsx)(`div`,{className:`py-1.5 text-muted-foreground`,children:eS(e,r,t)});if(e.type===`boolean`)return(0,V.jsx)(ox,{checked:!!n,onChange:f,label:t?.label??K(e.name)});if(e.type===`relation`){let e=i??String(r??`—`);return(0,V.jsx)(`div`,{className:`py-1.5`,children:a?(0,V.jsx)(ZS,{to:a,className:`font-medium text-primary-text hover:underline`,children:e}):e})}let m=!!t?.multiline&&e.type===`text`,h=Mx(e,t);if((!Pb(e)||c)&&h&&typeof r==`string`&&r!==``)return(0,V.jsx)(OC,{source:r,className:`py-1.5`});let g=e.type===`text`?Vx(t):void 0;return(!Pb(e)||c)&&g&&typeof r==`string`&&r!==``?(0,V.jsx)(`div`,{className:`min-w-0 break-words py-1.5`,children:(0,V.jsx)(PC,{format:g,value:r})}):!Pb(e)||c?(0,V.jsx)(`div`,{title:tS(e,r),className:B(`py-1.5 tabular-nums`,e.type===`decimal`||e.type===`integer`?`font-medium`:`text-muted-foreground`,m&&`whitespace-pre-line break-words`),children:eS(e,r,t)}):e.type===`enum`?(0,V.jsxs)(`select`,{...p,...s&&{"aria-invalid":!0},value:String(n),onChange:e=>f(e.target.value),className:`h-8 w-full rounded-md border border-border-strong bg-background px-2 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,children:[n===``&&(0,V.jsx)(`option`,{value:``,children:`Choose...`}),(e.enumValues??[]).map(e=>(0,V.jsx)(`option`,{value:e,children:rs(e,t?.valueLabels)},e))]}):h?(0,V.jsx)(AC,{label:t?.label??K(e.name),invalid:s,placeholder:l,value:String(n),onChange:f}):m?(0,V.jsx)(cx,{invalid:s,placeholder:l,value:String(n),onChange:e=>f(e.target.value)}):(0,V.jsx)(sd,{invalid:s,leading:t?.prefix?(0,V.jsx)(`span`,{children:t.prefix}):void 0,trailing:t?.suffix?(0,V.jsx)(`span`,{children:t.suffix.trim()}):void 0,placeholder:l,className:B(jC.has(e.type)&&`text-right tabular-nums`),...MC(e.type),...Ux(g),value:String(n),onChange:e=>f(e.target.value)})},IC=e=>{let{field:t,hints:n,value:r,stored:i,invalid:a,locked:o,onChange:s}=e,c=wC(t,n),l=(0,V.jsx)(FC,{...e});return c?o||!Pb(t)?(0,V.jsx)(EC,{shown:c,part:`display`,field:t,value:i,fallback:l}):t.type===`file`||t.type===`relation`?l:(0,V.jsx)(EC,{shown:c,part:`editor`,field:t,value:zb(t,r),invalid:!!a,onChange:e=>s(Bb(t,e)),fallback:l}):l},LC=(e,t)=>typeof e?.[t]==`number`?e[t]:void 0,RC=e=>`${Bd(e)} character${e===1?``:`s`}`,zC=(e,t)=>{let n=LC(t,`min`),r=LC(t,`max`);if(n!==void 0)return`${e} needs at least ${RC(n)}`;if(r!==void 0)return`${e} can have at most ${RC(r)}`},BC=e=>{let t=LC(e,`min`),n=LC(e,`max`);return t===void 0?n===void 0?`Enter a whole number`:`Enter a whole number of at most ${Bd(n)}`:`Enter a whole number of at least ${Bd(t)}`},VC=e=>{let t=LC(e,`precision`),n=LC(e,`scale`);if(t===void 0||n===void 0)return`Enter a number`;let r=Bd(10**(t-n));return n===0?`Enter a whole number below ${r}`:`Enter a number with at most ${n} decimal${n===1?``:`s`}, below ${r}`},HC={text:zC,integer:(e,t)=>BC(t),bigint:()=>`Enter a whole number`,decimal:(e,t)=>VC(t),date:()=>`Enter a date`,timestamp:()=>`Enter a date and time`,country:()=>`Enter a two-letter country code, such as NL`,currency:()=>`Enter a three-letter currency code, such as EUR`,uuid:()=>`Enter a valid ID`,enum:()=>`Choose one of the options`,relation:()=>`Choose a record`,json:()=>`Enter valid JSON`},UC=(e,t,n)=>n.code===`required`?`${t} is required`:n.code!==`invalid-value`||!e?n.message:HC[e.type]?.(t,n.params)??n.message,WC=e=>{if(!Rs(e))return{};let t={};for(let n of e.errors)n.field&&n.field!==`_record`&&!Object.hasOwn(t,n.field)&&(t[n.field]=n);return t},GC=e=>{if(e.operation!==void 0)return e.message;let t=new Set(e.errors.flatMap(e=>e.field&&e.field!==`_record`?[e.field]:[])),n=e.errors.flatMap(e=>e.field===`_record`?[e.message]:[]);return t.size===0&&n.length===0?e.message:[...t.size===0?[]:[`Check ${t.size===1?`the marked field`:`${t.size} fields`}.`],...n].join(` `)},KC=e=>{let t=(0,o.useRef)(null);return(0,o.useEffect)(()=>{e!==0&&t.current?.querySelector(`[aria-invalid="true"]`)?.focus()},[e]),t};function qC(e,t){if(!t.includes(e))throw Error(`Unsupported algorithm: ${String(e)}. Expected one of: ${t.join(`, `)}.`)}function JC(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function YC(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function XC(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function ZC(e){if(e.length%2!=0)throw Error(`Hex string must have an even length. Got: ${e}`);if(!/^[0-9a-fA-F]*$/.test(e))throw Error(`Hex string contains non-hex characters.`);let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substring(n*2,n*2+2),16);return t}async function QC(e){await new Promise(t=>setTimeout(t,e))}function $C(e){return Math.floor((performance.now()-e)*10)/10}var ew;(function(e){e.SHA_256=`SHA-256`,e.SHA_384=`SHA-384`,e.SHA_512=`SHA-512`})(ew||={});var tw;(function(e){e.CODE=`code`,e.ERROR=`error`,e.VERIFIED=`verified`,e.VERIFYING=`verifying`,e.UNVERIFIED=`unverified`,e.EXPIRED=`expired`})(tw||={}),Object.values(ew);var nw={string:2**53-1,uint32:4294967295};function rw(e,t){return Number.isInteger(e)&&e>=0&&e<=nw[t]}var iw=class{nonce;mode;COUNTER_BYTES=4;buffer;dataView;encoder=new TextEncoder;constructor(e,t=`uint32`){this.nonce=e,this.mode=t,this.buffer=new Uint8Array(this.nonce.length+this.COUNTER_BYTES),this.buffer.set(this.nonce,0),this.dataView=new DataView(this.buffer.buffer)}setCounter(e){if(!rw(e,this.mode))throw RangeError(`counter must be an integer from 0 to ${nw[this.mode]}. Got: ${e}`);return this.mode===`string`?XC(this.nonce,this.encoder.encode(e.toString())):(this.dataView.setUint32(this.nonce.length,e,!1),this.buffer)}};function aw(e,t){if(typeof e!=`string`||!/^[0-9a-fA-F]+$/.test(e))throw Error(`keyPrefix must be a non-empty hex string.`);if(e.length>t*2)throw Error(`keyPrefix (${e.length} hex characters) must not be longer than the key (keyLength: ${t} bytes).`)}async function ow(e){let{challenge:t,controller:n,counterMode:r=`uint32`,counterStart:i=0,counterStep:a=1,deriveKey:o,timeout:s=9e4}=e,{nonce:c,keyLength:l=32,keyPrefix:u,salt:d}=t.parameters;aw(u,l);let f=ZC(c),p=ZC(d),m=u.toLowerCase(),h=u.length%2==0?ZC(u):null,g=new iw(f,r),_=performance.now(),v=i,y=0,b=``,x=_;for(;;){if(n?.signal.aborted||s&&y%10==0&&performance.now()-_>s)return null;let{derivedKey:e}=await o(t.parameters,p,g.setCounter(v));if(y%10==0&&performance.now()-x>200&&(await QC(0),x=performance.now()),h?JC(e,h):YC(e).startsWith(m)){b=YC(e);break}v+=a,y+=1}return{counter:v,derivedKey:b,time:$C(_)}}[...Object.values(ew)];async function sw(e,t,n){let{algorithm:r,keyLength:i=32}=e;qC(r,[`SHA-256`,`SHA-384`,`SHA-512`]);let a=Math.max(1,e.cost),o=XC(t,n);for(let e=0;e<a;e++)o=new Uint8Array(await crypto.subtle.digest(r,o));return{parameters:{},derivedKey:o.slice(0,i)}}var cw=async(e,t)=>{let n=await e.formChallenge(t),r=await ow({challenge:n,deriveKey:sw});if(!r)throw Error(`The check that you are not a bot took too long; send the form again`);return{challenge:n,solution:{counter:r.counter,derivedKey:r.derivedKey}}},lw=({name:e})=>{let t=G(),n=mh({queryKey:W.publicForm(e),queryFn:()=>t.form(e)});return n.isPending?(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]}):n.error?Rs(n.error)&&n.error.status===404?(0,V.jsx)(KS,{title:`Not found`,children:`There is no form at this address.`}):(0,V.jsx)(KS,{title:`Cannot reach the API`,children:Rs(n.error)?n.error.message:`The server did not answer. Is it running?`}):(0,V.jsx)(uw,{form:n.data})},uw=({form:e})=>{let t=G(),{resource:n,view:r}=e,i=e.title??r.names?.singular??K(r.resource);rx(i);let[a,s]=(0,o.useState)(()=>$b(n,[{title:i,fields:e.fields}])),[c,l]=(0,o.useState)({}),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(!1),[m,h]=(0,o.useState)(!1),[g,_]=(0,o.useState)(0),v=KC(g);if(m)return(0,V.jsx)(Oh,{title:i,size:`md`,children:(0,V.jsx)(`p`,{role:`status`,className:`rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:e.thanks})});let y=(e,t)=>{l(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e))),s(n=>({...n,[e]:t}))},b=async()=>{p(!0),d(void 0);try{await t.submitForm(e.name,Xb(n,{},a),await cw(t,e.name)),h(!0)}catch(e){let t=WC(e);l(t),Object.keys(t).length>0?_(e=>e+1):d(e)}finally{p(!1)}};return(0,V.jsx)(Oh,{title:i,size:`md`,children:(0,V.jsxs)(`form`,{ref:v,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),b()},children:[e.fields.map(e=>{let t=n.fields[e],i=r.fields[e],o=i?.label??K(e),s=c[e];return(0,V.jsx)(eb,{name:e,label:o,help:i?.help,required:Zb(t),error:s&&UC(t,o,s),children:(0,V.jsx)(IC,{field:t,hints:i,value:a[e]??(t.type!==`boolean`&&``),stored:void 0,placeholder:ex(t)?`Set by the database`:void 0,invalid:!!s,onChange:t=>y(e,t)})},e)}),u!==void 0&&(0,V.jsx)(ax,{title:`Not sent`,error:u}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:f,className:`min-h-10`,children:`Send`})]})})},dw=()=>{let{path:e}=wh();return(0,o.useMemo)(()=>ko(e),[e])},fw=[`light`,`dark`,`system`],pw=`protobase:theme`,mw=`(prefers-color-scheme: dark)`,hw=e=>fw.includes(e),gw=e=>zu(()=>{let t=e.getItem(pw);return hw(t)?t:`system`},`system`),_w=(e,t)=>zu(()=>t===`system`?e.removeItem(pw):e.setItem(pw,t),void 0),vw=(e,t)=>e===`system`?t?`dark`:`light`:e,yw=(0,o.createContext)(void 0),bw=({children:e})=>{let[t,n]=(0,o.useState)(()=>gw(localStorage)),r=vw(t,Gl(mw));return(0,o.useEffect)(()=>{document.documentElement.dataset.theme=r},[r]),(0,o.useEffect)(()=>{let e=e=>{(e.key===`protobase:theme`||e.key===null)&&n(gw(localStorage))};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),(0,V.jsx)(yw.Provider,{value:{preference:t,theme:r,choose:e=>{_w(localStorage,e),n(e)}},children:e})},xw=()=>{let e=(0,o.useContext)(yw);if(!e)throw Error(`useTheme needs a ThemeProvider above it`);return e},Sw=({from:e,children:t})=>(0,V.jsx)(`div`,{"data-from":e,className:B(`flex min-w-0 flex-col gap-2 whitespace-pre-wrap break-words`,e===`user`?`ml-8 self-end rounded-lg rounded-br-sm bg-primary px-3 py-2 text-primary-foreground shadow-sm`:`mr-4 text-foreground`),children:t}),Cw=({children:e,empty:t,length:n})=>{let r=(0,o.useRef)(null);return(0,o.useEffect)(()=>{let e=r.current;e&&(e.scrollTop=e.scrollHeight)},[n]),(0,V.jsx)(`div`,{ref:r,role:`log`,"aria-live":`polite`,className:`flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4`,children:n===0&&t?(0,V.jsx)(`div`,{className:`m-auto max-w-60 text-center text-muted-foreground`,children:t}):e})},ww=({onSend:e,busy:t,placeholder:n,inputRef:r})=>{let[i,a]=(0,o.useState)(``),s=i.trim(),c=()=>{s&&!t&&(e?.(s),a(``))};return(0,V.jsxs)(`form`,{className:`flex gap-2`,onSubmit:e=>{e.preventDefault(),c()},children:[(0,V.jsx)(sd,{ref:r,"aria-label":`Message`,placeholder:n,value:i,onChange:e=>a(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,className:`w-8 px-0`,"aria-label":`Send`,disabled:!s||t,children:(0,V.jsx)(cee,{className:`size-4`})})]})},Tw=e=>{let[t,n]=(0,o.useState)();return(0,o.useEffect)(()=>{let t=window.visualViewport;if(!e||!t)return n(void 0);let r=()=>n({top:t.offsetTop,height:t.height});return r(),t.addEventListener(`resize`,r),t.addEventListener(`scroll`,r),()=>{t.removeEventListener(`resize`,r),t.removeEventListener(`scroll`,r)}},[e]),e?t:void 0},Ew=({title:e,icon:t,status:n,onClose:r,footer:i,children:a})=>{let o=Tw(!Kl());return(0,V.jsxs)(`aside`,{"aria-label":e,className:`flex h-full w-[380px] max-w-full shrink-0 flex-col border-l border-border bg-surface max-md:fixed max-md:inset-0 max-md:z-40 max-md:w-full max-md:border-l-0`,style:o&&{top:o.top,bottom:`auto`,height:o.height},children:[(0,V.jsxs)(`header`,{className:`flex h-12 shrink-0 items-center gap-2 border-b border-border bg-background px-4`,children:[t,(0,V.jsx)(`h2`,{className:`flex-1 font-semibold`,children:e}),n&&(0,V.jsx)(`span`,{className:`truncate text-xs font-medium text-muted-foreground`,children:n}),r&&(0,V.jsx)(U,{variant:`ghost`,size:`sm`,className:`w-7 px-0`,"aria-label":`Close`,onClick:r,children:(0,V.jsx)($n,{className:`size-4`})})]}),a,i&&(0,V.jsx)(`footer`,{className:`shrink-0 space-y-2 border-t border-border bg-background p-3`,children:i})]})},Dw={neutral:{border:`border-border-strong`,header:`bg-surface text-foreground`},info:{border:`border-primary-border`,header:`bg-primary-soft text-primary-text`},success:{border:`border-success/40`,header:`bg-success-soft text-success-text`},warning:{border:`border-warning/40`,header:`bg-warning-soft text-warning-text`},danger:{border:`border-danger/40`,header:`bg-danger-soft text-danger-text`}},Ow=({title:e,tone:t=`neutral`,badge:n,note:r,actions:i=[],onAction:a,children:s,frameless:c=!1})=>{let[l,u]=(0,o.useState)(),d=i.flatMap(e=>e.hint?[e.hint]:[]),f=e=>e.confirm?u(e):a?.(e.id);return(0,V.jsxs)(`section`,{"aria-label":e,className:c?`whitespace-normal text-foreground`:B(`shrink-0 overflow-hidden rounded-lg border bg-background whitespace-normal text-foreground shadow-sm`,Dw[t].border),children:[!c&&(0,V.jsxs)(`header`,{className:B(`flex items-center gap-2 px-3 py-2`,Dw[t].header),children:[(0,V.jsx)(`h3`,{className:`min-w-0 flex-1 font-semibold`,children:e}),n&&(0,V.jsx)(`span`,{className:`shrink-0 text-xs font-medium`,children:n})]}),(s||r||i.length>0)&&(0,V.jsxs)(`div`,{className:B(`space-y-2.5`,!c&&`px-3 py-2.5`),children:[s,r&&(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:r}),i.length>0&&(0,V.jsx)(`div`,{className:`flex flex-wrap gap-2 pt-0.5`,children:i.map(e=>(0,V.jsx)(U,{size:`sm`,variant:e.style??`secondary`,className:B(e.style===`primary`&&`flex-1`),disabled:e.disabled,onClick:()=>f(e),children:e.label},e.id))}),d.map(e=>(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e},e))]}),l&&(0,V.jsx)(wf,{title:`${l.label}?`,description:l.confirm,onClose:()=>u(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>u(void 0),children:`Cancel`}),(0,V.jsx)(U,{variant:l.style===`danger`?`danger`:`primary`,onClick:()=>{u(void 0),a?.(l.id)},children:l.label})]})})]})},kw=({fields:e})=>(0,V.jsx)(`dl`,{className:`grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs`,children:e.map((e,t)=>(0,V.jsxs)(`div`,{className:`contents`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:e.label}),(0,V.jsx)(`dd`,{className:`min-w-0 break-words`,children:e.value})]},`${t}-${e.label}`))}),Aw=e=>e==null?`null`:typeof e==`object`?JSON.stringify(e):String(e),jw=({columns:e,rows:t,caption:n,truncated:r,className:i})=>(0,V.jsxs)(`section`,{"aria-label":n??`Table`,className:B(`shrink-0 overflow-hidden rounded-lg border border-border-strong bg-background shadow-sm`,i),children:[n&&(0,V.jsx)(`code`,{className:`block whitespace-pre-wrap break-words bg-surface px-3 py-2 font-mono text-[11px] text-foreground`,children:n}),t.length===0?(0,V.jsx)(`p`,{className:`px-3 py-2 text-xs text-muted-foreground`,children:`No rows.`}):(0,V.jsx)(`div`,{className:`max-h-64 overflow-auto`,children:(0,V.jsxs)(`table`,{className:`w-full border-collapse text-left text-[11px]`,children:[(0,V.jsx)(`thead`,{className:`sticky top-0 bg-background`,children:(0,V.jsx)(`tr`,{children:e.map(e=>(0,V.jsx)(`th`,{scope:`col`,className:`border-b border-border px-2 py-1 font-semibold whitespace-nowrap`,children:e},e))})}),(0,V.jsx)(`tbody`,{children:t.map((e,t)=>(0,V.jsx)(`tr`,{className:`border-b border-border last:border-b-0`,children:e.map((e,t)=>(0,V.jsx)(`td`,{className:B(`px-2 py-1 whitespace-nowrap`,e===null&&`text-faint-foreground`),children:Aw(e)},t))},t))})]})}),(0,V.jsxs)(`footer`,{className:`border-t border-border px-3 py-1.5 text-[11px] text-muted-foreground`,children:[t.length,` `,t.length===1?`row`:`rows`,r&&`, cut off at the limit`]})]}),Mw=(e,t=1)=>{let n=t,r=t;return e.split(`
|
|
12
|
+
`)).replace(/\s+/g,` `).trim();return n.length>Ax?`${n.slice(0,199).trimEnd()}…`:n},Mx=(e,t)=>e.type===`text`&&!!t?.markdown,Nx=[`name`,`title`,`number`,`sku`,`email`,`code`,`description`],Px=(e,t)=>t?.title??Nx.find(t=>e.fields[t]?.type===`text`)??Object.values(e.fields).find(e=>e.type===`text`)?.name??e.primaryKey[0],Fx=(e,t)=>t?.title??t?.list?.columns.find(t=>e.fields[t]?.type===`text`)??Px(e),Ix=(e,t,n,r)=>{let i=Fx(e,t),a=n[i];return a==null?r:e.fields[i]?.type===`enum`?rs(String(a),t?.fields[i]?.valueLabels):String(a)},Lx=(e,t,n)=>{let r=t[n];return e.fields[n]?.type===`relation`&&typeof r==`object`&&r&&`id`in r?r.id:r},Rx=(e,t)=>e.primaryKey.map(n=>String(Lx(e,t,n))).join(`,`),zx=(e,t)=>{let n=e.primaryKey.map(n=>Lx(e,t,n));return n.length===1?n[0]:n},Bx=new Set([`email`,`phone`,`url`]),Vx=e=>e?.format!==void 0&&Bx.has(e.format)?e.format:void 0,Hx=(e,t)=>{let n=t.trim();if(e===`email`)return/^[^\s@]+@[^\s@]+$/.test(n)?`mailto:${n}`:void 0;if(e===`phone`){let e=n.replace(/[^\d+]/g,``).replace(/(?!^)\+/g,``);return/\d/.test(e)?`tel:${e}`:void 0}return/^https?:\/\/\S+$/i.test(n)?n:void 0},Ux=e=>e===`email`?{type:`email`,inputMode:`email`,autoComplete:`email`}:e===`phone`?{type:`tel`,inputMode:`tel`,autoComplete:`tel`}:e===`url`?{type:`url`,inputMode:`url`,autoComplete:`url`}:{},Wx={draft:`neutral`,confirmed:`blue`,picking:`amber`,shipped:`violet`,delivered:`green`,cancelled:`red`,sent:`blue`,paid:`green`,overdue:`red`,lead:`blue`,active:`green`,dormant:`neutral`,receipt:`green`,issue:`blue`,transfer:`violet`,adjustment:`amber`},Gx=e=>Wx[e]??`neutral`,Kx={text:200,id:140,money:120,date:110,datetime:170,status:150,relation:200,boolean:64,number:100,signed:110,percent:110,user:130,file:180},qx=new Set([`datetime`,`date`,`boolean`,`percent`]),Jx=/^(number|sku|reference|code)$/,Yx=(e,t,n)=>{switch(e.type){case`relation`:return`relation`;case`file`:return`file`;case`enum`:return`status`;case`boolean`:return`boolean`;case`timestamp`:return`datetime`;case`date`:return`date`;case`decimal`:return t?.format===`percent`?`percent`:t?.prefix===`€`?`money`:`number`;case`integer`:case`bigint`:return/quantity|delta/.test(e.name)?`signed`:`number`;default:return Jx.test(e.name)||n===0&&e.name===`id`?`id`:`text`}},Xx=e=>Math.round(Number.parseFloat(String(e))*100),Zx=(e,t)=>t?.list?.columns??Object.keys(e.fields).slice(0,6),Qx=(e,t,n=[],r=Zx(e,t))=>{let i=Fx(e,t);return r.flatMap((r,a)=>{let o=e.fields[r];if(!o)return[];let s=t?.fields[r],c=Yx(o,s,a),l=Object.fromEntries((o.enumValues??[]).map(e=>[e,rs(e,s?.valueLabels)])),u=s?.suffix?Math.ceil(s.suffix.length*7.2):0;return[{id:r,header:s?.label??K(r),kind:c,width:(r===`name`?260:Kx[c])+u,sortable:o.sortable,minWidth:Math.max(c===`id`?150:0,dx(s?.label??K(r),o.sortable),c===`status`?fx(Object.values(l)):0,u>0?Kx[c]+u:0),...qx.has(c)&&{fixed:!0},...r===i&&{title:!0},...c===`text`&&r!==i&&Vx(s)&&{link:Vx(s)},...n.includes(r)&&{highlight:!0},...o.type===`enum`&&{tones:Object.fromEntries((o.enumValues??[]).map(e=>[e,Gx(e)])),labels:l},...o.type===`enum`&&s?.valueColors&&{colors:s.valueColors},...o.type===`enum`&&s?.badgeShape&&{shape:s.badgeShape},...s?.suffix!==void 0&&{suffix:s.suffix},...c===`money`&&s?.decimals!==void 0&&{decimals:s.decimals},...c===`money`&&{currency:`EUR`,value:e=>e[r]==null?null:Xx(e[r])},...(c===`datetime`||c===`date`)&&{value:e=>e[r]==null?null:Date.parse(String(e[r]))},...Mx(o,s)&&{value:e=>typeof e[r]==`string`?jx(e[r]):e[r]},...(c===`percent`||c===`number`&&o.type===`decimal`)&&{value:e=>e[r]==null?null:Number(e[r])}}]})},$x=(e,t)=>`${t.prefix??``}${e}${t.suffix??``}`,eS=(e,t,n={},r=Wd())=>{if(t==null||t===``)return`—`;switch(e.type){case`boolean`:return t?`Yes`:`No`;case`file`:return bb(t)?.name??`—`;case`enum`:return rs(String(t),n.valueLabels);case`timestamp`:return df(Date.parse(String(t)),r);case`date`:return sf(Date.parse(String(t)));case`decimal`:{let e=n.decimals===void 0?String(t):Number(t).toFixed(n.decimals);return n.format===`percent`?`${Number(t)}%`:$x(Number(e).toLocaleString(`en-IE`,{minimumFractionDigits:n.decimals??0,maximumFractionDigits:n.decimals??20}),n)}case`integer`:case`bigint`:return $x(String(t),n);default:return typeof t==`object`?JSON.stringify(t):String(t)}},tS=(e,t,n=Wd())=>{if(e.type!==`timestamp`||typeof t!=`string`)return;let r=Date.parse(t);return Number.isNaN(r)?void 0:`Shown in ${ef(r,n)}`},nS=`$photos`,rS=e=>{for(let t of e?.list?.displays??[])if(t.kind===`cards`&&t.photos)return t.photos},iS=(e,t,n)=>{if(n===void 0||e.primaryKey.length!==1)return t;let r=e.primaryKey[0];return t.map(e=>({...e,[nS]:n[String(e[r])]??[]}))},aS=(e,t)=>t.filter(t=>e[t]!==null&&e[t]!==void 0&&e[t]!==``),oS=(e,t,n)=>{let r=e.fields[n.by];if(!r)return[];let i=t?.fields[n.by],a=(r.enumValues??[]).map(e=>({value:e,label:rs(e,i?.valueLabels)}));return r.nullable?[...a,{value:null,label:`No ${(i?.label??K(n.by)).toLowerCase()}`}]:a},sS=(e,t,n)=>{let r=qa(n===null?lo.isNull(t):lo.eq(t,n));return e===``?r:`(${e}) AND ${r}`},cS=(e,t,n)=>({kind:`cards`,name:n.name,title:n.title??Fx(e,t),...n.subtitle!==void 0&&{subtitle:n.subtitle},...n.badge!==void 0&&{badge:n.badge},...n.meta&&{meta:n.meta}}),lS=e=>{if(!Rs(e))return e instanceof Error?e.message:`Something went wrong`;let t=e.errors.map(e=>e.message);return t.length>0?t.join(`; `):e.message},uS=e=>e?.list?.displays??[],dS=(e,t,n)=>{let r=n??e?.list?.default??`table`;if(!t)return r;let i=uS(e).filter(e=>e.kind===`cards`);return i.find(e=>e.name===r)?.name??i[0]?.name??r},fS=`rows`,pS=(e,t)=>{if(uS(t).some(e=>e.kind===`cards`||e.name===`rows`))return;let n=Fx(e,t),r=Zx(e,t).filter(t=>t!==n&&e.fields[t]!==void 0),i=r.find(t=>e.fields[t].type===`enum`),a=r.filter(t=>t!==i&&e.fields[t].type!==`boolean`).slice(0,2);return{kind:`cards`,name:fS,label:`List`,icon:`list`,title:n,...i!==void 0&&{badge:i},footer:a}},mS=(e,t)=>t.name===`rows`&&!uS(e).some(e=>e.name===`rows`),hS=(e,t,n)=>{let r=dS(t,n);return n&&r===`table`&&pS(e,t)?fS:r},gS=(e,t,n)=>(n===`rows`?pS(e,t):void 0)??_S(t,n),_S=(e,t)=>{if(t===`table`)return;let n=t=>uS(e).find(e=>e.name===t);return n(t)??n(e?.list?.default)},vS={cards:`cards`,map:`map`,board:`kanban`,calendar:`calendar`},yS=e=>[{name:xo,label:`Table`,icon:`table`},...uS(e).map(e=>({name:e.name,label:e.label??K(e.name),icon:e.icon??vS[e.kind]}))],bS=(e,t,n)=>{let r=yS(t);return n&&pS(e,t)?[...r,{name:fS,label:`List`,icon:`list`}]:r},xS=(e,t,n)=>({image:n.image,title:n.title??Fx(e,t),subtitle:n.subtitle,amount:n.amount??[],badge:n.badge,meta:n.meta??[],footer:n.footer??[],flags:n.flags??[]}),SS=(e,t)=>aS(e.record,t),CS=(e,t)=>SS(e,t)[0],wS=(e,t,n={})=>{let{suffix:r,...i}=n;return e.type!==`decimal`&&e.type!==`integer`&&e.type!==`bigint`||r===void 0||n.format===`percent`?{amount:eS(e,t,n)}:{amount:eS(e,t,i),suffix:r}},TS=(e,t)=>{let n=uS(e).filter(e=>e.kind===`cards`);return(t.cards===void 0?n[0]:n.find(e=>e.name===t.cards))??{kind:`cards`,name:t.name}},ES=(e,t,n)=>{if(n.kind===`custom`)return n.fields;if(n.kind===`map`)return[n.latitude,n.longitude,...ES(e,t,TS(t,n))];if(n.kind===`board`){let r=cS(e,t,n);return[n.by,r.title,r.subtitle,r.badge,...r.meta??[]].filter(e=>e!==void 0)}if(n.kind===`calendar`)return[n.start,n.end,n.title??Fx(e,t)].filter(e=>e!==void 0);let{image:r,title:i,subtitle:a,amount:o,badge:s,meta:c,footer:l,flags:u}=xS(e,t,n);return[r,i,a,...o,s,...c,...l,...u].filter(e=>e!==void 0)},DS=(e,t,n)=>{let r=pS(e,t),i=r?[...uS(t),r]:uS(t);return[...new Set([...n,...i.flatMap(n=>ES(e,t,n))])]},OS=(e,t,n)=>{let r=mS(t,n)?[Fx(e,t),...Zx(e,t)]:ES(e,t,n);return[...new Set(r)].filter(t=>e.fields[t]?.sortable)},kS=e=>typeof e==`object`&&!!e&&`id`in e&&`name`in e,AS=(e,t)=>{let n={},r={},i=Array.isArray(t.$photos)?t[nS]:void 0;for(let[i,a]of Object.entries(t))(i!==`id`&&i!==`$photos`||Object.hasOwn(e.fields,i))&&(e.fields[i]?.type===`relation`&&kS(a)?(n[i]=a.id,r[i]=a.name):n[i]=a);return{key:Ao(zx(e,n)),record:n,labels:r,...i&&{photos:i}}},jS=(e,t)=>{let n=t?.list?.sort?.[0];return n?`${n[0]} ${n[1]}`:`${e.primaryKey[0]} asc`},MS=e=>{let[t=``,n]=e.trim().split(/\s+/);return{columnId:t,direction:n===`desc`?`desc`:`asc`}},NS=e=>`${e.columnId} ${e.direction}`,PS=(e,t,n)=>{let r=e[n],i=t[n]?.listOf,a=i===void 0?void 0:r?.fields[i]?.relation?.resource;return a!==void 0&&e[a]?{model:e[a],view:t[a],listOf:!0}:{model:r,view:t[n],listOf:!1}},FS=(e,t,n=!1)=>({display:e?hS(e,t,n):dS(t,n),orderBy:e?jS(e,t):``,filterLayout:`bar`}),IS=(e,t)=>e?.kind===`record`?{kind:`record`,resource:e.resource,key:Ao(e.key),...e.edit&&{edit:!0}}:e?.kind===`list`?{...t(e.resource),filter:``,...e}:e,LS=(e,t,n)=>{let r={...e,...t},i=e=>r[e]!==void 0&&r[e]!==n[e];return{kind:`list`,resource:e.resource,...r.filter&&{filter:r.filter},...i(`display`)&&{display:r.display},...i(`orderBy`)&&{orderBy:r.orderBy},...i(`filterLayout`)&&{filterLayout:r.filterLayout},...r.map&&{map:r.map},...r.calendar&&{calendar:r.calendar},...r.savedSearch&&{savedSearch:r.savedSearch}}},RS=(0,o.createContext)(null),zS={create:!0,update:!0,delete:!0,conditional:[]},BS=()=>{let e=G(),t=Gp(),n=(0,o.useContext)(RS),r=mh({queryKey:W.meta,staleTime:0,refetchOnWindowFocus:`always`,queryFn:async()=>{let n=t.getQueryData(W.meta),r=await e.meta(n?.etag);if(r.status===`unchanged`){if(!n)throw Error(`The server answered 304 to a request without If-None-Match`);return n}return{etag:r.etag,appName:r.meta.appName,resources:Object.fromEntries(r.meta.resources.map(e=>[e.name,e])),views:Object.fromEntries(r.meta.views.map(e=>[e.resource,e])),pages:Object.fromEntries((r.meta.pages??[]).map(e=>[e.name,e])),permissions:r.meta.permissions??{},...r.meta.userMenu&&{userMenu:r.meta.userMenu},...r.meta.signIn&&{signIn:Object.fromEntries(r.meta.signIn.map(e=>[e.resource,e]))},...r.meta.bottomBar&&{bottomBar:r.meta.bottomBar},...r.meta.assistant&&{assistant:r.meta.assistant},...r.meta.runtime&&{runtime:r.meta.runtime},...r.meta.errorReporting&&{errorReporting:r.meta.errorReporting},...r.meta.maps&&{maps:r.meta.maps},...r.meta.files&&{files:r.meta.files},...r.meta.plugins&&{plugins:r.meta.plugins},...r.meta.sources&&{sources:r.meta.sources.map(e=>({source:e,state:`loading`}))}}}});return(0,o.useMemo)(()=>n&&r.data?{...r,data:n}:r,[n,r])},VS=1e4,HS=e=>e.map(e=>({data:e.data?.meta,error:e.error})),US=(e,t)=>{let n=Gp(),r=fh({queries:e.map(e=>{let r=W.sourceMeta(e.url,e.resources);return{queryKey:r,staleTime:0,refetchOnWindowFocus:`always`,queryFn:async()=>{let i=n.getQueryData(r),a=await t(e).meta(i?.etag,{signal:AbortSignal.timeout(VS)});if(a.status===`unchanged`){if(!i)throw Error(`${e.label} answered 304 to a request without If-None-Match`);return i}return{etag:a.etag,meta:fc(a.meta,e)}}}}),combine:HS});return(0,o.useMemo)(()=>e.map((e,t)=>{let{data:n,error:i}=r[t];return n?{source:e,state:`ready`,meta:n}:i?{source:e,state:`error`,error:i}:{source:e,state:`loading`}}),[e,r])},WS=(e,t)=>{if(t.length===0)return e;let n=t.flatMap(e=>e.state===`ready`?[e.meta]:[]),r=t.map(e=>e.state===`error`?{source:e.source,state:`error`,error:e.error}:{source:e.source,state:e.state});return{...e,resources:{...e.resources,...Object.fromEntries(n.flatMap(e=>e.resources.map(e=>[e.name,e])))},views:{...e.views,...Object.fromEntries(n.flatMap(e=>e.views.map(e=>[e.resource,e])))},permissions:{...e.permissions,...Object.assign({},...n.map(e=>e.permissions))},sources:r}},GS=(e,t)=>e.sources?.find(e=>e.source.resources.includes(t)),J=()=>{let e=(0,o.useContext)(RS);if(!e)throw Error(`useAdminMeta must be used inside MetaGate`);return e},KS=({title:e,children:t})=>(0,V.jsx)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center p-8`,children:(0,V.jsxs)(`div`,{className:`max-w-md text-center`,children:[(0,V.jsx)(`h1`,{className:`text-[16px] font-semibold`,children:e}),(0,V.jsx)(`p`,{className:`mt-1 text-muted-foreground`,children:t})]})}),qS=({meta:e,children:t})=>{let n=G(),r=Rne(),i=(0,o.useMemo)(()=>(e.sources??[]).map(e=>e.source),[e.sources]),a=US(i,r),s=(0,o.useMemo)(()=>WS(e,a),[e,a]),c=(0,o.useMemo)(()=>{let e=new Map(i.flatMap(e=>e.resources.map(t=>[t,e]))),t=t=>{let n=e.get(t);return n&&r(n)};return{client:$s(n,t),resourceClient:t}},[i,n,r]);return(0,V.jsx)(zne,{client:c.client,resourceClient:c.resourceClient,children:(0,V.jsx)(RS.Provider,{value:s,children:t})})},JS=({children:e})=>{let t=BS();return t.isPending?(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]}):t.error?(0,V.jsx)(KS,{title:`Cannot reach the API`,children:Rs(t.error)?t.error.message:`The server did not answer. Is it running?`}):(0,V.jsx)(qS,{meta:t.data,children:e})},YS=e=>J().permissions[e]??zS,XS=()=>{let{path:e,params:t,basePath:n,navigate:r}=wh(),{pages:i,resources:a,views:s}=J(),c=ql(),l=(0,o.useMemo)(()=>new Set(Object.keys(i)),[i]),u=t.toString(),d=(0,o.useMemo)(()=>_s(u?`${e}?${u}`:e,l),[e,u,l]),f=(0,o.useCallback)(e=>{let t=PS(a,s,e);return FS(t.model,t.view,c)},[a,s,c]),p=(0,o.useMemo)(()=>IS(d,f),[d,f]),m=(0,o.useCallback)((e,t)=>r(ps(e),t),[r]),h=(0,o.useCallback)(e=>{if(d?.kind!==`list`)throw Error(`listTo and set change the list the app shows; use go to move to another address`);return LS(d,e,f(d.resource))},[d,f]);return{address:p,set:(0,o.useCallback)(e=>m(h(e),{replace:!0}),[h,m]),listTo:h,go:m,href:(0,o.useCallback)(e=>ps(e,n),[n]),open:(0,o.useCallback)(e=>r(e.startsWith(`${n}/`)?e.slice(n.length):e),[n,r])}},ZS=({to:e,...t})=>(0,V.jsx)(Vne,{to:ps(e),...t}),QS=(e,{filter:t,orderBy:n,pageSize:r=50,fields:i,startToken:a=``,enabled:o=!0}={})=>{let s=G(),c=Ts(t)??``,l=gh({queryKey:[...W.list(e,c,n??``,r,a),i?.join(`,`)??``],enabled:o,initialPageParam:a,queryFn:({pageParam:t})=>s.list(e,{filter:c,orderBy:n,pageSize:r,fields:i,pageToken:t}),getNextPageParam:e=>e.nextPageToken||void 0}),u=l.data?.pages??[];return{...l,items:u.flatMap(e=>e.items),totalEstimate:u[0]?.totalSizeEstimate}},$S=co(),eC=e=>e.split(/\s+/).filter(Boolean),tC=(e,t,n,r=!1)=>{let i=eC(n);if(i.length===0)return{filter:void 0,local:!1};if(r)return{filter:void 0,local:!0};if(e.search?.length)return{filter:qa($S.search(n)),local:!1};let a=e.fields[t];if(a?.type!==`text`||!a.filterable)return{filter:void 0,local:!0};let o=i.map(e=>$S.eq(t,`*${e.replaceAll(`*`,``)}*`));return{filter:qa($S.and(...o)),local:!1}},nC=(e,t)=>{if(e==null)return!1;let n=String(e).toLowerCase();return eC(t).every(e=>n.includes(e.toLowerCase()))},rC=(e,t,n,r)=>{(0,o.useEffect)(()=>{if(!e||!t)return;let n=new IntersectionObserver(e=>e.some(e=>e.isIntersecting)&&r(),{root:e});return n.observe(t),()=>n.disconnect()},[e,t,n,r])},iC=({target:e,view:t,value:n,label:r,invalid:i,onChange:a})=>{let[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)(-1),[p,m]=(0,o.useState)(null),[h,g]=(0,o.useState)(null),_=(0,o.useId)(),v=e.primaryKey[0],y=Px(e,t),[b,x]=(0,o.useState)(!1),S=tC(e,y,s,b),C=QS(e.name,{filter:S.filter,fields:[v,y],enabled:l}),w=S.filter!==void 0&&C.error instanceof Is&&C.error.slug===`expensive-query`;(0,o.useEffect)(()=>{w&&x(!0)},[w]);let T=S.local?C.items.filter(e=>nC(e[y],s)):C.items,E=!!C.hasNextPage,D=C.isPending||C.isFetchingNextPage,{fetchNextPage:O}=C;rC(p,h,C.items.length,(0,o.useCallback)(()=>O({cancelRefetch:!1}),[O]));let k=e=>`${_}-${e}`,A=(0,o.useRef)(null);(0,o.useEffect)(()=>{!l&&document.activeElement===A.current&&A.current?.select()},[l]),(0,o.useEffect)(()=>{l&&d>=0&&document.getElementById(k(d))?.scrollIntoView({block:`nearest`})});let j=()=>{c(``),f(-1),u(!1)},M=e=>{a(String(e[v]),String(e[y])),j()};return(0,V.jsxs)(`div`,{className:`relative`,children:[(0,V.jsx)(sd,{ref:A,role:`combobox`,"aria-autocomplete":`list`,"aria-expanded":l,"aria-controls":_,"aria-activedescendant":l&&T[d]?k(d):void 0,invalid:i,placeholder:`Search ${(t?.names?.plural??K(e.name)).toLowerCase()}`,value:l?s:r??n,onFocus:()=>u(!0),onBlur:j,onKeyDown:e=>{if(e.key===`ArrowDown`||e.key===`ArrowUp`){if(e.preventDefault(),!l)return u(!0);let t=e.key===`ArrowDown`?1:-1;f(e=>Math.min(Math.max(e+t,0),T.length-1));return}if(e.key===`Enter`&&l&&T[d]){e.preventDefault(),M(T[d]);return}e.key===`Escape`&&l&&(e.preventDefault(),e.stopPropagation(),j())},onChange:e=>{c(e.target.value),f(e.target.value.trim()?0:-1),u(!0)}}),l&&(0,V.jsxs)(`ul`,{ref:m,id:_,role:`listbox`,className:`absolute z-30 mt-1 max-h-60 w-full overflow-y-auto rounded-md border bg-background py-1 shadow-pop`,onMouseDown:e=>e.preventDefault(),children:[T.map((e,t)=>(0,V.jsx)(`li`,{id:k(t),role:`option`,"aria-selected":t===d,className:B(`cursor-pointer truncate px-3 py-1.5`,t===d&&`bg-muted`,String(e[v])===n&&`font-medium`),onMouseMove:()=>t!==d&&f(t),onClick:()=>M(e),children:String(e[y])},String(e[v]))),E&&(0,V.jsx)(`li`,{ref:g,"aria-hidden":!0,className:`h-px`}),C.error&&!w&&(0,V.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`Could not load the options`}),!E&&!D&&!C.error&&T.length===0&&(0,V.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`No matches`}),D&&(0,V.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`Loading`})]})]})},aC=`••••••••••`,oC=({field:e,hints:t,value:n,reveal:r,locked:i,invalid:a,placeholder:s,onChange:c})=>{let[l,u]=(0,o.useState)(!1),d=hh({mutationFn:async()=>r(),onSuccess:()=>u(!0)}),f=Mb(n)!==``,p=t?.label??K(e.name),m=(0,V.jsx)(U,{variant:`ghost`,size:`sm`,className:`-mr-1.5 px-1.5`,"aria-label":`${l?`Hide`:`Show`} ${p}`,"aria-pressed":l,loading:d.isPending,onClick:()=>{l||f||!r||d.isSuccess?u(!l):d.mutate()},children:!d.isPending&&(l?(0,V.jsx)(eee,{className:`size-3.5`}):(0,V.jsx)(tt,{className:`size-3.5`}))}),h=d.error&&(0,V.jsx)(`div`,{className:`mt-2`,children:(0,V.jsx)(ax,{title:`Could not show the ${p}`,error:d.error})});if(i)return(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2 py-1`,children:[(0,V.jsx)(`span`,{className:B(l?t?.format===`code`?`font-mono text-xs`:``:`tracking-widest text-muted-foreground`),children:l?eS(e,d.data,t):aC}),r&&m]}),h]});let g=f?Mb(n):l&&d.isSuccess?Mb(d.data):``;return(0,V.jsxs)(`div`,{children:[(0,V.jsx)(sd,{type:l?`text`:`password`,autoComplete:`off`,invalid:a,"aria-label":p,className:B(t?.format===`code`&&`font-mono text-xs`),placeholder:f||!r?s:aC,value:g,trailing:m,onChange:e=>c(e.target.value)}),h]})};function sC(e){let{PI:t,min:n,max:r,cos:i,round:a}=Math,o=e[0]|e[1]<<8|e[2]<<16,s=e[3]|e[4]<<8,c=(o&63)/63,l=(o>>6&63)/31.5-1,u=(o>>12&63)/31.5-1,d=(o>>18&31)/31,f=o>>23,p=(s>>3&63)/63,m=(s>>9&63)/63,h=s>>15,g=r(3,h?f?5:7:s&7),_=r(3,h?s&7:f?5:7),v=f?(e[5]&15)/15:1,y=(e[5]>>4)/15,b=f?6:5,x=0,S=(t,n,r)=>{let i=[];for(let a=0;a<n;a++)for(let o=+!a;o*n<t*(n-a);o++)i.push(((e[b+(x>>1)]>>((x++&1)<<2)&15)/7.5-1)*r);return i},C=S(g,_,d),w=S(3,3,p*1.25),T=S(3,3,m*1.25),E=f&&S(5,5,y),D=cC(e),O=a(D>1?32:32*D),k=a(D>1?32/D:32),A=new Uint8Array(O*k*4),j=[],M=[];for(let e=0,a=0;e<k;e++)for(let o=0;o<O;o++,a+=4){let s=c,d=l,p=u,m=v;for(let e=0,n=r(g,f?5:3);e<n;e++)j[e]=i(t/O*(o+.5)*e);for(let n=0,a=r(_,f?5:3);n<a;n++)M[n]=i(t/k*(e+.5)*n);for(let e=0,t=0;e<_;e++)for(let n=+!e,r=M[e]*2;n*_<g*(_-e);n++,t++)s+=C[t]*j[n]*r;for(let e=0,t=0;e<3;e++)for(let n=+!e,r=M[e]*2;n<3-e;n++,t++){let e=j[n]*r;d+=w[t]*e,p+=T[t]*e}if(f)for(let e=0,t=0;e<5;e++)for(let n=+!e,r=M[e]*2;n<5-e;n++,t++)m+=E[t]*j[n]*r;let h=s-2/3*d,y=(3*s-h+p)/2,b=y-p;A[a]=r(0,255*n(1,y)),A[a+1]=r(0,255*n(1,b)),A[a+2]=r(0,255*n(1,h)),A[a+3]=r(0,255*n(1,m))}return{w:O,h:k,rgba:A}}function cC(e){let t=e[3],n=e[2]&128,r=e[4]&128;return(r?n?5:7:t&7)/(r?t&7:n?5:7)}function lC(e,t,n){let r=e*4+1,i=6+t*(5+r),a=[137,80,78,71,13,10,26,10,0,0,0,13,73,72,68,82,0,0,e>>8,e&255,0,0,t>>8,t&255,8,6,0,0,0,0,0,0,0,i>>>24,i>>16&255,i>>8&255,i&255,73,68,65,84,120,1],o=[0,498536548,997073096,651767980,1994146192,1802195444,1303535960,1342533948,-306674912,-267414716,-690576408,-882789492,-1687895376,-2032938284,-1609899400,-1111625188],s=1,c=0;for(let e=0,i=0,o=r-1;e<t;e++,o+=r-1)for(a.push(e+1<t?0:1,r&255,r>>8,~r&255,r>>8^255,0),c=(c+s)%65521;i<o;i++){let e=n[i]&255;a.push(e),s=(s+e)%65521,c=(c+s)%65521}a.push(c>>8,c&255,s>>8,s&255,0,0,0,0,0,0,0,0,73,69,78,68,174,66,96,130);for(let[e,t]of[[12,29],[37,41+i]]){let n=-1;for(let r=e;r<t;r++)n^=a[r],n=n>>>4^o[n&15],n=n>>>4^o[n&15];n=~n,a[t++]=n>>>24,a[t++]=n>>16&255,a[t++]=n>>8&255,a[t++]=n&255}return`data:image/png;base64,`+btoa(String.fromCharCode(...a))}function uC(e){let t=sC(e);return lC(t.w,t.h,t.rgba)}var dC=(e,t,n)=>{if(!URL.canParse(e,t))return`no-referrer`;let r=new URL(e,t);if((r.protocol===`http:`||r.protocol===`https:`)&&!(r.origin===new URL(t).origin||n.includes(r.hostname)))return`no-referrer`},fC=e=>URL.canParse(e)?[new URL(e).hostname]:[],pC=()=>{let e=(0,o.useContext)(RS);return(0,o.useMemo)(()=>[...e?.files?.trustedHosts??[],...(e?.sources??[]).flatMap(({source:e})=>fC(e.url))],[e?.files,e?.sources])},mC=e=>{let t;try{t=atob(e)}catch(e){if(e instanceof DOMException&&e.name===`InvalidCharacterError`)return;throw e}return uC(Uint8Array.from(t,e=>e.charCodeAt(0)))},hC=({image:e,className:t,loading:n})=>{let[r,i]=(0,o.useState)(),a=pC(),s=(0,o.useMemo)(()=>e.placeholder===void 0?void 0:mC(e.placeholder),[e.placeholder]),c=s!==void 0&&r!==e.url;return(0,V.jsx)(`img`,{src:e.url,alt:``,loading:n,decoding:`async`,referrerPolicy:dC(e.url,window.location.href,a),onLoad:()=>i(e.url),className:t,style:c?{backgroundImage:`url("${s}")`,backgroundSize:`cover`,backgroundPosition:`center`}:void 0})},gC=({value:e})=>{let t=Ob(e,{width:40,height:40});return t?(0,V.jsx)(hC,{image:t,className:`size-10 shrink-0 rounded border border-border object-cover`}):(0,V.jsx)(`span`,{className:`flex size-10 shrink-0 items-center justify-center rounded border border-border bg-muted text-muted-foreground`,children:(0,V.jsx)(ot,{className:`size-4`})})},_C=({value:e})=>{let t=bb(e);if(!t)return(0,V.jsx)(`div`,{className:`py-1.5 text-muted-foreground`,children:`—`});if(`missing`in t)return(0,V.jsx)(`div`,{className:`py-1.5 text-danger-text`,children:`The file is missing from storage`});let n=`url`in t?t.url:void 0,r=`corrected`in t?t.corrected:void 0;return(0,V.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3 py-1`,children:[(0,V.jsx)(gC,{value:e}),(0,V.jsxs)(`div`,{className:`min-w-0`,children:[n&&!n.startsWith(`blob:`)?(0,V.jsx)(`a`,{href:n,target:`_blank`,rel:`noreferrer`,className:`block truncate font-medium text-primary-text hover:underline`,children:t.name}):(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:t.name}),(0,V.jsxs)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:[t.type,t.size!==void 0&&` · ${Sb(t.size)}`,r&&` · sent as ${r.from}`]})]})]})},vC=({field:e,hints:t,resource:n,value:r,locked:i,invalid:a,onChange:s})=>{let c=G(),l=(0,o.useRef)(null),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(!1),m=t?.label??K(e.name),h=hh({mutationFn:async t=>{d(0);let r=await c.upload(n,e.name,t,{onProgress:(e,t)=>d(t>0?e/t:0)});return{uploaded:r,...Cb(r.file.type)&&{preview:URL.createObjectURL(t)}}},onSuccess:e=>s(e),onSettled:()=>d(void 0)});if(i||e.readOnly)return(0,V.jsx)(_C,{value:r});let g=e=>{let t=e?.[0];t&&h.mutate(t)},_=e=>{e.preventDefault(),p(!1),g(e.dataTransfer.files)},v=(0,V.jsx)(`input`,{ref:l,type:`file`,hidden:!0,accept:kb(e),"aria-label":`Choose a file for ${m}`,onChange:e=>g(e.target.files)}),y=h.error&&(0,V.jsx)(`div`,{className:`mt-2`,children:(0,V.jsx)(ax,{title:`Not uploaded`,error:h.error})});return h.isPending?(0,V.jsxs)(`div`,{className:`py-1.5`,role:`status`,"aria-label":`Uploading ${m}`,children:[(0,V.jsx)(`div`,{className:`h-1.5 overflow-hidden rounded-full bg-muted`,children:(0,V.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-[width]`,style:{width:`${Math.round((u??0)*100)}%`}})}),(0,V.jsxs)(`span`,{className:`text-xs text-muted-foreground`,children:[`Uploading… `,Math.round((u??0)*100),`%`]})]}):bb(r)?(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,V.jsx)(_C,{value:r})}),(0,V.jsx)(U,{size:`sm`,onClick:()=>l.current?.click(),children:`Replace`}),e.nullable&&(0,V.jsx)(U,{size:`sm`,variant:`ghost`,onClick:()=>s(null),children:`Remove`})]}),v,y]}):(0,V.jsxs)(`div`,{children:[(0,V.jsxs)(`div`,{onDragOver:e=>{e.preventDefault(),p(!0)},onDragLeave:()=>p(!1),onDrop:_,className:B(`flex items-center gap-3 rounded-md border border-dashed px-3 py-2.5 text-muted-foreground`,f?`border-primary bg-primary/5`:a?`border-danger`:`border-border-strong`),children:[(0,V.jsx)(Gn,{className:`size-4 shrink-0`}),(0,V.jsx)(`span`,{className:`flex-1`,children:`Drop a file here or`}),(0,V.jsxs)(U,{size:`sm`,onClick:()=>l.current?.click(),children:[(0,V.jsx)(en,{className:`size-3.5`}),`Choose a file`]})]}),v,y]})},yC=e=>e,bC=e=>e,xC=(0,o.createContext)({}),SC=()=>(0,o.useContext)(xC),CC=(e,t,n)=>{let r=n?.widget;if(!r||t.sensitive||!e||!Object.hasOwn(e,r.name))return;let i=e[r.name];return i.of.includes(t.type)?{name:r.name,widget:i,props:r.props??{}}:void 0},wC=(e,t)=>CC(SC().fields,e,t),TC=({shown:e,part:t,field:n,value:r,onChange:i,invalid:a=!1})=>{let{widget:o,props:s}=e,c={field:n,value:r??null,props:s};if(t!==`editor`){let e=t===`cell`?o.cell??o.display:o.display;return(0,V.jsx)(e,{...c})}let l=o.editor;return l&&i?(0,V.jsx)(l,{...c,onChange:i,invalid:a}):void 0},EC=({fallback:e,...t})=>{let n=TC(t);return n?(0,V.jsx)(Qh,{name:`The field type ${t.shown.name}`,fallback:e,children:n}):e},DC=(0,o.lazy)(()=>qh(()=>import(`./markdown-content-B410ow-t.js`).then(e=>({default:e.MarkdownContent})),__vite__mapDeps([0,1,2,3]))),OC=e=>(0,V.jsx)(o.Suspense,{fallback:(0,V.jsx)(`div`,{className:B(`whitespace-pre-line break-words`,e.className),children:e.source}),children:(0,V.jsx)(DC,{...e})}),kC=[{value:`write`,label:`Write`},{value:`preview`,label:`Preview`}],AC=({value:e,onChange:t,label:n,invalid:r,placeholder:i})=>{let[a,s]=(0,o.useState)(`write`);return(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsx)(`span`,{className:`self-start`,children:(0,V.jsx)(Pu,{value:a,options:kC,onChange:s,label:n})}),a===`write`?(0,V.jsx)(cx,{rows:5,invalid:r,placeholder:i,value:e,onChange:e=>t(e.target.value)}):(0,V.jsx)(`div`,{className:`min-h-[7.5rem] rounded-md border border-border px-2.5 py-1.5`,children:e.trim()===``?(0,V.jsx)(`span`,{className:`text-faint-foreground`,children:`Nothing to preview`}):(0,V.jsx)(OC,{source:e})})]})},jC=new Set([`integer`,`bigint`,`decimal`]),MC=e=>e===`integer`||e===`bigint`?{inputMode:`numeric`,enterKeyHint:`done`}:e===`decimal`?{inputMode:`decimal`,enterKeyHint:`done`}:{},NC=e=>e.stopPropagation(),PC=({format:e,value:t,className:n})=>{let r=Hx(e,t);return r?(0,V.jsx)(`a`,{href:r,...e===`url`?{target:`_blank`,rel:`noreferrer`}:{},onClick:NC,className:B(`font-medium text-primary-text hover:underline`,n),children:t}):(0,V.jsx)(`span`,{className:n,children:t})},FC=({field:e,hints:t,value:n,stored:r,relationLabel:i,relationTo:a,relationPicker:o,invalid:s,locked:c,placeholder:l,reveal:u,resource:d,onChange:f})=>{let p=od();if(e.type===`file`)return(0,V.jsx)(vC,{field:e,hints:t,resource:d??``,value:n,locked:c||!d,invalid:s,onChange:f});if(e.sensitive)return(0,V.jsx)(oC,{field:e,hints:t,value:n,reveal:u,locked:c||e.readOnly,invalid:s,placeholder:l,onChange:f});if(e.type===`relation`&&o&&!e.readOnly&&!c){let e=(0,V.jsx)(iC,{target:o.target,view:o.view,value:String(n),label:i,invalid:s,onChange:(e,t)=>f({key:e,label:t})});return a?(0,V.jsxs)(`div`,{className:`flex items-center gap-1`,children:[(0,V.jsx)(`div`,{className:`min-w-0 flex-1`,children:e}),(0,V.jsx)(ZS,{to:a,"aria-label":`Open ${i??String(n)}`,title:`Open`,className:B(Cf({variant:`ghost`}),`w-8 px-0`),children:(0,V.jsx)(O,{className:`size-4`})})]}):e}if(e.type===`boolean`&&c)return(0,V.jsx)(`div`,{className:`py-1.5 text-muted-foreground`,children:eS(e,r,t)});if(e.type===`boolean`)return(0,V.jsx)(ox,{checked:!!n,onChange:f,label:t?.label??K(e.name)});if(e.type===`relation`){let e=i??String(r??`—`);return(0,V.jsx)(`div`,{className:`py-1.5`,children:a?(0,V.jsx)(ZS,{to:a,className:`font-medium text-primary-text hover:underline`,children:e}):e})}let m=!!t?.multiline&&e.type===`text`,h=Mx(e,t);if((!Pb(e)||c)&&h&&typeof r==`string`&&r!==``)return(0,V.jsx)(OC,{source:r,className:`py-1.5`});let g=e.type===`text`?Vx(t):void 0;return(!Pb(e)||c)&&g&&typeof r==`string`&&r!==``?(0,V.jsx)(`div`,{className:`min-w-0 break-words py-1.5`,children:(0,V.jsx)(PC,{format:g,value:r})}):!Pb(e)||c?(0,V.jsx)(`div`,{title:tS(e,r),className:B(`py-1.5 tabular-nums`,e.type===`decimal`||e.type===`integer`?`font-medium`:`text-muted-foreground`,m&&`whitespace-pre-line break-words`),children:eS(e,r,t)}):e.type===`enum`?(0,V.jsxs)(`select`,{...p,...s&&{"aria-invalid":!0},value:String(n),onChange:e=>f(e.target.value),className:`h-8 w-full rounded-md border border-border-strong bg-background px-2 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,children:[n===``&&(0,V.jsx)(`option`,{value:``,children:`Choose...`}),(e.enumValues??[]).map(e=>(0,V.jsx)(`option`,{value:e,children:rs(e,t?.valueLabels)},e))]}):h?(0,V.jsx)(AC,{label:t?.label??K(e.name),invalid:s,placeholder:l,value:String(n),onChange:f}):m?(0,V.jsx)(cx,{invalid:s,placeholder:l,value:String(n),onChange:e=>f(e.target.value)}):(0,V.jsx)(sd,{invalid:s,leading:t?.prefix?(0,V.jsx)(`span`,{children:t.prefix}):void 0,trailing:t?.suffix?(0,V.jsx)(`span`,{children:t.suffix.trim()}):void 0,placeholder:l,className:B(jC.has(e.type)&&`text-right tabular-nums`),...MC(e.type),...Ux(g),value:String(n),onChange:e=>f(e.target.value)})},IC=e=>{let{field:t,hints:n,value:r,stored:i,invalid:a,locked:o,onChange:s}=e,c=wC(t,n),l=(0,V.jsx)(FC,{...e});return c?o||!Pb(t)?(0,V.jsx)(EC,{shown:c,part:`display`,field:t,value:i,fallback:l}):t.type===`file`||t.type===`relation`?l:(0,V.jsx)(EC,{shown:c,part:`editor`,field:t,value:zb(t,r),invalid:!!a,onChange:e=>s(Bb(t,e)),fallback:l}):l},LC=(e,t)=>typeof e?.[t]==`number`?e[t]:void 0,RC=e=>`${Bd(e)} character${e===1?``:`s`}`,zC=(e,t)=>{let n=LC(t,`min`),r=LC(t,`max`);if(n!==void 0)return`${e} needs at least ${RC(n)}`;if(r!==void 0)return`${e} can have at most ${RC(r)}`},BC=e=>{let t=LC(e,`min`),n=LC(e,`max`);return t===void 0?n===void 0?`Enter a whole number`:`Enter a whole number of at most ${Bd(n)}`:`Enter a whole number of at least ${Bd(t)}`},VC=e=>{let t=LC(e,`precision`),n=LC(e,`scale`);if(t===void 0||n===void 0)return`Enter a number`;let r=Bd(10**(t-n));return n===0?`Enter a whole number below ${r}`:`Enter a number with at most ${n} decimal${n===1?``:`s`}, below ${r}`},HC={text:zC,integer:(e,t)=>BC(t),bigint:()=>`Enter a whole number`,decimal:(e,t)=>VC(t),date:()=>`Enter a date`,timestamp:()=>`Enter a date and time`,country:()=>`Enter a two-letter country code, such as NL`,currency:()=>`Enter a three-letter currency code, such as EUR`,uuid:()=>`Enter a valid ID`,enum:()=>`Choose one of the options`,relation:()=>`Choose a record`,json:()=>`Enter valid JSON`},UC=(e,t,n)=>n.code===`required`?`${t} is required`:n.code!==`invalid-value`||!e?n.message:HC[e.type]?.(t,n.params)??n.message,WC=e=>{if(!Rs(e))return{};let t={};for(let n of e.errors)n.field&&n.field!==`_record`&&!Object.hasOwn(t,n.field)&&(t[n.field]=n);return t},GC=e=>{if(e.operation!==void 0)return e.message;let t=new Set(e.errors.flatMap(e=>e.field&&e.field!==`_record`?[e.field]:[])),n=e.errors.flatMap(e=>e.field===`_record`?[e.message]:[]);return t.size===0&&n.length===0?e.message:[...t.size===0?[]:[`Check ${t.size===1?`the marked field`:`${t.size} fields`}.`],...n].join(` `)},KC=e=>{let t=(0,o.useRef)(null);return(0,o.useEffect)(()=>{e!==0&&t.current?.querySelector(`[aria-invalid="true"]`)?.focus()},[e]),t};function qC(e,t){if(!t.includes(e))throw Error(`Unsupported algorithm: ${String(e)}. Expected one of: ${t.join(`, `)}.`)}function JC(e,t){if(t.length>e.length)return!1;for(let n=0;n<t.length;n++)if(e[n]!==t[n])return!1;return!0}function YC(e){return Array.from(new Uint8Array(e)).map(e=>e.toString(16).padStart(2,`0`)).join(``)}function XC(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e,0),n.set(t,e.length),n}function ZC(e){if(e.length%2!=0)throw Error(`Hex string must have an even length. Got: ${e}`);if(!/^[0-9a-fA-F]*$/.test(e))throw Error(`Hex string contains non-hex characters.`);let t=new Uint8Array(e.length/2);for(let n=0;n<t.length;n++)t[n]=parseInt(e.substring(n*2,n*2+2),16);return t}async function QC(e){await new Promise(t=>setTimeout(t,e))}function $C(e){return Math.floor((performance.now()-e)*10)/10}var ew;(function(e){e.SHA_256=`SHA-256`,e.SHA_384=`SHA-384`,e.SHA_512=`SHA-512`})(ew||={});var tw;(function(e){e.CODE=`code`,e.ERROR=`error`,e.VERIFIED=`verified`,e.VERIFYING=`verifying`,e.UNVERIFIED=`unverified`,e.EXPIRED=`expired`})(tw||={}),Object.values(ew);var nw={string:2**53-1,uint32:4294967295};function rw(e,t){return Number.isInteger(e)&&e>=0&&e<=nw[t]}var iw=class{nonce;mode;COUNTER_BYTES=4;buffer;dataView;encoder=new TextEncoder;constructor(e,t=`uint32`){this.nonce=e,this.mode=t,this.buffer=new Uint8Array(this.nonce.length+this.COUNTER_BYTES),this.buffer.set(this.nonce,0),this.dataView=new DataView(this.buffer.buffer)}setCounter(e){if(!rw(e,this.mode))throw RangeError(`counter must be an integer from 0 to ${nw[this.mode]}. Got: ${e}`);return this.mode===`string`?XC(this.nonce,this.encoder.encode(e.toString())):(this.dataView.setUint32(this.nonce.length,e,!1),this.buffer)}};function aw(e,t){if(typeof e!=`string`||!/^[0-9a-fA-F]+$/.test(e))throw Error(`keyPrefix must be a non-empty hex string.`);if(e.length>t*2)throw Error(`keyPrefix (${e.length} hex characters) must not be longer than the key (keyLength: ${t} bytes).`)}async function ow(e){let{challenge:t,controller:n,counterMode:r=`uint32`,counterStart:i=0,counterStep:a=1,deriveKey:o,timeout:s=9e4}=e,{nonce:c,keyLength:l=32,keyPrefix:u,salt:d}=t.parameters;aw(u,l);let f=ZC(c),p=ZC(d),m=u.toLowerCase(),h=u.length%2==0?ZC(u):null,g=new iw(f,r),_=performance.now(),v=i,y=0,b=``,x=_;for(;;){if(n?.signal.aborted||s&&y%10==0&&performance.now()-_>s)return null;let{derivedKey:e}=await o(t.parameters,p,g.setCounter(v));if(y%10==0&&performance.now()-x>200&&(await QC(0),x=performance.now()),h?JC(e,h):YC(e).startsWith(m)){b=YC(e);break}v+=a,y+=1}return{counter:v,derivedKey:b,time:$C(_)}}[...Object.values(ew)];async function sw(e,t,n){let{algorithm:r,keyLength:i=32}=e;qC(r,[`SHA-256`,`SHA-384`,`SHA-512`]);let a=Math.max(1,e.cost),o=XC(t,n);for(let e=0;e<a;e++)o=new Uint8Array(await crypto.subtle.digest(r,o));return{parameters:{},derivedKey:o.slice(0,i)}}var cw=async(e,t)=>{let n=await e.formChallenge(t),r=await ow({challenge:n,deriveKey:sw});if(!r)throw Error(`The check that you are not a bot took too long; send the form again`);return{challenge:n,solution:{counter:r.counter,derivedKey:r.derivedKey}}},lw=({name:e})=>{let t=G(),n=mh({queryKey:W.publicForm(e),queryFn:()=>t.form(e)});return n.isPending?(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]}):n.error?Rs(n.error)&&n.error.status===404?(0,V.jsx)(KS,{title:`Not found`,children:`There is no form at this address.`}):(0,V.jsx)(KS,{title:`Cannot reach the API`,children:Rs(n.error)?n.error.message:`The server did not answer. Is it running?`}):(0,V.jsx)(uw,{form:n.data})},uw=({form:e})=>{let t=G(),{resource:n,view:r}=e,i=e.title??r.names?.singular??K(r.resource);rx(i);let[a,s]=(0,o.useState)(()=>$b(n,[{title:i,fields:e.fields}])),[c,l]=(0,o.useState)({}),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(!1),[m,h]=(0,o.useState)(!1),[g,_]=(0,o.useState)(0),v=KC(g);if(m)return(0,V.jsx)(Oh,{title:i,size:`md`,children:(0,V.jsx)(`p`,{role:`status`,className:`rounded-md bg-success-soft px-3 py-2 text-xs font-medium text-success-text`,children:e.thanks})});let y=(e,t)=>{l(t=>Object.fromEntries(Object.entries(t).filter(([t])=>t!==e))),s(n=>({...n,[e]:t}))},b=async()=>{p(!0),d(void 0);try{await t.submitForm(e.name,Xb(n,{},a),await cw(t,e.name)),h(!0)}catch(e){let t=WC(e);l(t),Object.keys(t).length>0?_(e=>e+1):d(e)}finally{p(!1)}};return(0,V.jsx)(Oh,{title:i,size:`md`,children:(0,V.jsxs)(`form`,{ref:v,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),b()},children:[e.fields.map(e=>{let t=n.fields[e],i=r.fields[e],o=i?.label??K(e),s=c[e];return(0,V.jsx)(eb,{name:e,label:o,help:i?.help,required:Zb(t),error:s&&UC(t,o,s),children:(0,V.jsx)(IC,{field:t,hints:i,value:a[e]??(t.type!==`boolean`&&``),stored:void 0,placeholder:ex(t)?`Set by the database`:void 0,invalid:!!s,onChange:t=>y(e,t)})},e)}),u!==void 0&&(0,V.jsx)(ax,{title:`Not sent`,error:u}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,loading:f,className:`min-h-10`,children:`Send`})]})})},dw=()=>{let{path:e}=wh();return(0,o.useMemo)(()=>ko(e),[e])},fw=[`light`,`dark`,`system`],pw=`protobase:theme`,mw=`(prefers-color-scheme: dark)`,hw=e=>fw.includes(e),gw=e=>zu(()=>{let t=e.getItem(pw);return hw(t)?t:`system`},`system`),_w=(e,t)=>zu(()=>t===`system`?e.removeItem(pw):e.setItem(pw,t),void 0),vw=(e,t)=>e===`system`?t?`dark`:`light`:e,yw=(0,o.createContext)(void 0),bw=({children:e})=>{let[t,n]=(0,o.useState)(()=>gw(localStorage)),r=vw(t,Gl(mw));return(0,o.useEffect)(()=>{document.documentElement.dataset.theme=r},[r]),(0,o.useEffect)(()=>{let e=e=>{(e.key===`protobase:theme`||e.key===null)&&n(gw(localStorage))};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[]),(0,V.jsx)(yw.Provider,{value:{preference:t,theme:r,choose:e=>{_w(localStorage,e),n(e)}},children:e})},xw=()=>{let e=(0,o.useContext)(yw);if(!e)throw Error(`useTheme needs a ThemeProvider above it`);return e},Sw=({from:e,children:t})=>(0,V.jsx)(`div`,{"data-from":e,className:B(`flex min-w-0 flex-col gap-2 whitespace-pre-wrap break-words`,e===`user`?`ml-8 self-end rounded-lg rounded-br-sm bg-primary px-3 py-2 text-primary-foreground shadow-sm`:`mr-4 text-foreground`),children:t}),Cw=({children:e,empty:t,length:n})=>{let r=(0,o.useRef)(null);return(0,o.useEffect)(()=>{let e=r.current;e&&(e.scrollTop=e.scrollHeight)},[n]),(0,V.jsx)(`div`,{ref:r,role:`log`,"aria-live":`polite`,className:`flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto p-4`,children:n===0&&t?(0,V.jsx)(`div`,{className:`m-auto max-w-60 text-center text-muted-foreground`,children:t}):e})},ww=({onSend:e,busy:t,placeholder:n,inputRef:r})=>{let[i,a]=(0,o.useState)(``),s=i.trim(),c=()=>{s&&!t&&(e?.(s),a(``))};return(0,V.jsxs)(`form`,{className:`flex gap-2`,onSubmit:e=>{e.preventDefault(),c()},children:[(0,V.jsx)(sd,{ref:r,"aria-label":`Message`,placeholder:n,value:i,onChange:e=>a(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,className:`w-8 px-0`,"aria-label":`Send`,disabled:!s||t,children:(0,V.jsx)(cee,{className:`size-4`})})]})},Tw=e=>{let[t,n]=(0,o.useState)();return(0,o.useEffect)(()=>{let t=window.visualViewport;if(!e||!t)return n(void 0);let r=()=>n({top:t.offsetTop,height:t.height});return r(),t.addEventListener(`resize`,r),t.addEventListener(`scroll`,r),()=>{t.removeEventListener(`resize`,r),t.removeEventListener(`scroll`,r)}},[e]),e?t:void 0},Ew=({title:e,icon:t,status:n,onClose:r,footer:i,children:a})=>{let o=Tw(!Kl());return(0,V.jsxs)(`aside`,{"aria-label":e,className:`flex h-full w-[380px] max-w-full shrink-0 flex-col border-l border-border bg-surface max-md:fixed max-md:inset-0 max-md:z-40 max-md:w-full max-md:border-l-0`,style:o&&{top:o.top,bottom:`auto`,height:o.height},children:[(0,V.jsxs)(`header`,{className:`flex h-12 shrink-0 items-center gap-2 border-b border-border bg-background px-4`,children:[t,(0,V.jsx)(`h2`,{className:`flex-1 font-semibold`,children:e}),n&&(0,V.jsx)(`span`,{className:`truncate text-xs font-medium text-muted-foreground`,children:n}),r&&(0,V.jsx)(U,{variant:`ghost`,size:`sm`,className:`w-7 px-0`,"aria-label":`Close`,onClick:r,children:(0,V.jsx)($n,{className:`size-4`})})]}),a,i&&(0,V.jsx)(`footer`,{className:`shrink-0 space-y-2 border-t border-border bg-background p-3`,children:i})]})},Dw={neutral:{border:`border-border-strong`,header:`bg-surface text-foreground`},info:{border:`border-primary-border`,header:`bg-primary-soft text-primary-text`},success:{border:`border-success/40`,header:`bg-success-soft text-success-text`},warning:{border:`border-warning/40`,header:`bg-warning-soft text-warning-text`},danger:{border:`border-danger/40`,header:`bg-danger-soft text-danger-text`}},Ow=({title:e,tone:t=`neutral`,badge:n,note:r,actions:i=[],onAction:a,children:s,frameless:c=!1})=>{let[l,u]=(0,o.useState)(),d=i.flatMap(e=>e.hint?[e.hint]:[]),f=e=>e.confirm?u(e):a?.(e.id);return(0,V.jsxs)(`section`,{"aria-label":e,className:c?`whitespace-normal text-foreground`:B(`shrink-0 overflow-hidden rounded-lg border bg-background whitespace-normal text-foreground shadow-sm`,Dw[t].border),children:[!c&&(0,V.jsxs)(`header`,{className:B(`flex items-center gap-2 px-3 py-2`,Dw[t].header),children:[(0,V.jsx)(`h3`,{className:`min-w-0 flex-1 font-semibold`,children:e}),n&&(0,V.jsx)(`span`,{className:`shrink-0 text-xs font-medium`,children:n})]}),(s||r||i.length>0)&&(0,V.jsxs)(`div`,{className:B(`space-y-2.5`,!c&&`px-3 py-2.5`),children:[s,r&&(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:r}),i.length>0&&(0,V.jsx)(`div`,{className:`flex flex-wrap gap-2 pt-0.5`,children:i.map(e=>(0,V.jsx)(U,{size:`sm`,variant:e.style??`secondary`,className:B(e.style===`primary`&&`flex-1`),disabled:e.disabled,onClick:()=>f(e),children:e.label},e.id))}),d.map(e=>(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:e},e))]}),l&&(0,V.jsx)(wf,{title:`${l.label}?`,description:l.confirm,onClose:()=>u(void 0),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>u(void 0),children:`Cancel`}),(0,V.jsx)(U,{variant:l.style===`danger`?`danger`:`primary`,onClick:()=>{u(void 0),a?.(l.id)},children:l.label})]})})]})},kw=({fields:e})=>(0,V.jsx)(`dl`,{className:`grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 gap-y-1 text-xs`,children:e.map((e,t)=>(0,V.jsxs)(`div`,{className:`contents`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:e.label}),(0,V.jsx)(`dd`,{className:`min-w-0 break-words`,children:e.value})]},`${t}-${e.label}`))}),Aw=e=>e==null?`null`:typeof e==`object`?JSON.stringify(e):String(e),jw=({columns:e,rows:t,caption:n,truncated:r,className:i})=>(0,V.jsxs)(`section`,{"aria-label":n??`Table`,className:B(`shrink-0 overflow-hidden rounded-lg border border-border-strong bg-background shadow-sm`,i),children:[n&&(0,V.jsx)(`code`,{className:`block whitespace-pre-wrap break-words bg-surface px-3 py-2 font-mono text-[11px] text-foreground`,children:n}),t.length===0?(0,V.jsx)(`p`,{className:`px-3 py-2 text-xs text-muted-foreground`,children:`No rows.`}):(0,V.jsx)(`div`,{className:`max-h-64 overflow-auto`,children:(0,V.jsxs)(`table`,{className:`w-full border-collapse text-left text-[11px]`,children:[(0,V.jsx)(`thead`,{className:`sticky top-0 bg-background`,children:(0,V.jsx)(`tr`,{children:e.map(e=>(0,V.jsx)(`th`,{scope:`col`,className:`border-b border-border px-2 py-1 font-semibold whitespace-nowrap`,children:e},e))})}),(0,V.jsx)(`tbody`,{children:t.map((e,t)=>(0,V.jsx)(`tr`,{className:`border-b border-border last:border-b-0`,children:e.map((e,t)=>(0,V.jsx)(`td`,{className:B(`px-2 py-1 whitespace-nowrap`,e===null&&`text-faint-foreground`),children:Aw(e)},t))},t))})]})}),(0,V.jsxs)(`footer`,{className:`border-t border-border px-3 py-1.5 text-[11px] text-muted-foreground`,children:[t.length,` `,t.length===1?`row`:`rows`,r&&`, cut off at the limit`]})]}),Mw=(e,t=1)=>{let n=t,r=t;return e.split(`
|
|
13
13
|
`).map(e=>e.startsWith(`+`)?{kind:`add`,text:e.slice(1),newNo:r++}:e.startsWith(`-`)?{kind:`del`,text:e.slice(1),oldNo:n++}:{kind:`ctx`,text:e.startsWith(` `)?e.slice(1):e,oldNo:n++,newNo:r++})},Nw=e=>({added:e.filter(e=>e.kind===`add`).length,removed:e.filter(e=>e.kind===`del`).length}),Pw={add:`bg-success-soft text-success-text`,del:`bg-danger-soft text-danger-text`,ctx:`text-muted-foreground`},Fw={add:`+`,del:`−`,ctx:``},Iw=({source:e,start:t,path:n,className:r})=>{let i=Mw(e,t),a=Nw(i);return(0,V.jsxs)(`div`,{className:B(`overflow-hidden`,r),children:[n&&(0,V.jsxs)(`div`,{className:`flex items-center gap-2 border-b border-border bg-surface px-3 py-1.5`,children:[(0,V.jsx)(rt,{className:`size-3.5 text-muted-foreground`}),(0,V.jsx)(`span`,{className:`min-w-0 flex-1 truncate font-mono text-[11px] text-foreground`,children:n}),(0,V.jsxs)(`span`,{className:`text-[11px] font-medium text-success-text`,children:[`+`,a.added]}),a.removed>0&&(0,V.jsxs)(`span`,{className:`text-[11px] font-medium text-danger-text`,children:[`−`,a.removed]})]}),(0,V.jsx)(`pre`,{className:`overflow-x-auto bg-background py-1 font-mono text-[11px] leading-[18px]`,children:i.map((e,t)=>(0,V.jsxs)(`div`,{className:B(`flex`,Pw[e.kind]),children:[(0,V.jsx)(`span`,{className:`w-8 shrink-0 select-none pr-2 text-right opacity-60`,children:e.newNo??e.oldNo}),(0,V.jsx)(`span`,{className:`w-3 shrink-0 select-none`,children:Fw[e.kind]}),(0,V.jsx)(`span`,{className:`min-w-0 whitespace-pre-wrap break-words pr-3`,children:e.text})]},t))})]})},Lw={pending:(0,V.jsx)(Pe,{className:`size-3 text-faint-foreground`}),running:(0,V.jsx)(ld,{className:`size-3.5 text-primary`}),done:(0,V.jsx)(ge,{className:`size-3.5 text-success`,strokeWidth:2.5}),failed:(0,V.jsx)($n,{className:`size-3.5 text-danger`,strokeWidth:2.5})},Rw={pending:`text-muted-foreground`,running:`text-foreground`,done:`text-muted-foreground`,failed:`text-danger-text`},zw=({steps:e,className:t})=>(0,V.jsx)(`ul`,{className:B(`shrink-0 space-y-2`,t),children:e.map((e,t)=>(0,V.jsxs)(`li`,{className:`flex items-start gap-2.5`,"data-state":e.state,children:[(0,V.jsx)(`span`,{className:`mt-0.5 flex size-4 shrink-0 items-center justify-center`,children:Lw[e.state]}),(0,V.jsx)(`span`,{className:Rw[e.state],children:e.label})]},`${t}-${e.label}`))}),Bw=({part:e,note:t})=>e.fallback?(0,V.jsx)(Ow,{title:e.fallback.title,note:t,children:e.fallback.body&&(0,V.jsx)(`p`,{children:e.fallback.body})}):(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`${e.name}: ${t}`}),Vw=class extends o.Component{state={failed:!1};static getDerivedStateFromError(){return{failed:!0}}componentDidCatch(e,t){Xh(e,t.componentStack)}render(){return this.state.failed?(0,V.jsx)(Bw,{part:this.props.part,note:`It could not be drawn.`}):this.props.children}},Hw=({part:e})=>{let{components:t={}}=SC(),n=Object.hasOwn(t,e.name)?t[e.name]:void 0;return n?(0,V.jsx)(Vw,{part:e,children:(0,V.jsx)(n,{...e.props})}):(0,V.jsx)(Bw,{part:e,note:`This version of the app cannot show it live.`})},Uw=({part:e,onAction:t})=>{switch(e.type){case`text`:return(0,V.jsx)(`p`,{children:e.text});case`table`:return(0,V.jsx)(jw,{columns:e.columns,rows:e.rows,caption:e.caption,truncated:e.truncated});case`card`:return(0,V.jsxs)(Ow,{title:e.title,tone:e.tone,badge:e.badge,note:e.note,actions:e.actions,onAction:n=>t?.(e.id,n),children:[e.body&&(0,V.jsx)(`p`,{children:e.body}),e.code&&(0,V.jsx)(`pre`,{className:`overflow-x-auto rounded-md bg-surface px-2.5 py-2 font-mono text-[11px] whitespace-pre-wrap break-words`,children:e.code}),e.fields&&e.fields.length>0&&(0,V.jsx)(kw,{fields:e.fields}),e.steps&&e.steps.length>0&&(0,V.jsx)(zw,{steps:e.steps}),e.diffs?.map((e,t)=>(0,V.jsx)(Iw,{source:e.source,start:e.start,path:e.path,className:`rounded-md border border-border`},`${t}-${e.path}`))]});case`widget`:return(0,V.jsx)(Hw,{part:e})}},Ww=(0,o.createContext)(void 0),Gw=e=>e instanceof Error?e:Error(`The assistant backend did not answer`),Kw=(e,t)=>typeof e==`function`?e(t):e,qw=(e,{refreshMs:t=!1}={})=>{let n=(0,o.useContext)(Ww),[r,i]=(0,o.useState)({}),[a,s]=(0,o.useState)(0),c=(0,o.useRef)(t);c.current=t;let l=(0,o.useRef)(void 0);return(0,o.useEffect)(()=>{if(!n){i({error:Error(`useBackendData works only in a widget the assistant dock draws`)});return}let t=!0,r,a=async()=>{let o=await n.fetch(e).then(e=>e.json()).then(e=>({data:e}),e=>({data:l.current,error:Gw(e)}));if(!t)return;l.current=o.data,i(o);let s=Kw(c.current,o.data);s!==!1&&(r=setTimeout(a,s))};return a(),()=>{t=!1,clearTimeout(r)}},[n,e,a]),{...r,reload:()=>s(e=>e+1),post:async(e,t)=>{if(!n)throw Error(`useBackendData works only in a widget the assistant dock draws`);let r={method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(t??{})},a=await n.fetch(e,r).then(e=>e.json()).then(e=>({data:e}),e=>({data:l.current,error:Gw(e)}));l.current=a.data,i(a)}}},Jw=`Ask a question...`,Yw=({state:e,offline:t,error:n,onSend:r,onAction:i,onClose:a,client:s})=>{let c=(0,o.useRef)(null);return(0,o.useEffect)(()=>{e.placeholder&&c.current?.focus()},[e.placeholder]),(0,V.jsx)(Ew,{title:`Assistant`,icon:(0,V.jsx)(Tn,{className:`size-4 text-primary`}),status:t?`Reconnecting...`:e.status,onClose:a,footer:(0,V.jsxs)(V.Fragment,{children:[n&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs text-danger-text`,children:n}),(0,V.jsx)(ww,{inputRef:c,onSend:r,busy:e.replying,placeholder:e.placeholder??Jw})]}),children:(0,V.jsx)(Ww.Provider,{value:s,children:(0,V.jsx)(Cw,{length:e.messages.reduce((e,t)=>e+t.parts.length,0),empty:`Ask a question about this app or its data.`,children:e.messages.map(e=>(0,V.jsx)(Sw,{from:e.from,children:e.parts.map(e=>(0,V.jsx)(Uw,{part:e,onAction:i},e.id))},e.id))})})})},Xw=e=>e instanceof Error?e.message:`The assistant did not answer`,Zw=e=>{let[t,n]=(0,o.useState)(Qo),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)();(0,o.useEffect)(()=>{if(e)return e.connect(e=>n(t=>ts(t,e)),e=>i(e.state===`retrying`))},[e]);let c=e=>{s(void 0),e.catch(e=>s(Xw(e)))};return{state:t,offline:r,error:a,send:(t,n)=>e&&c(e.send(t,n)),act:(t,n)=>e&&c(e.act(t,n))}},Qw=e=>{let t=xg(),n=(0,o.useRef)(t);n.current=t;let r=t!==void 0;return(0,o.useMemo)(()=>r?Vl({url:e,token:()=>n.current}):void 0,[e,r])},$w=({open:e,onToggle:t})=>(0,V.jsxs)(U,{size:`sm`,variant:e?`primary`:`secondary`,"aria-pressed":e,onClick:t,className:`max-md:size-9 max-md:p-0`,children:[(0,V.jsx)(Tn,{className:`size-3.5`}),(0,V.jsx)(`span`,{className:`max-md:sr-only`,children:`Assistant`})]}),eT=({client:e,page:t,onClose:n})=>{let{state:r,offline:i,error:a,send:o,act:s}=Zw(e);return(0,V.jsx)(Yw,{state:r,offline:i,error:a,onSend:e=>o(e,t),onAction:s,onClose:n,client:e})},tT=({url:e,...t})=>(0,V.jsx)(eT,{client:Qw(e),...t}),nT=({url:e,client:t,...n})=>t?(0,V.jsx)(eT,{client:t,...n}):(0,V.jsx)(tT,{url:e,...n}),rT={orders:xn,orderLines:xn,companies:ue,invoices:ot,invoiceLines:ln,products:Qt,categories:Ln,tags:Ln,companyTags:Ln,stockMoves:ce,stockLevels:ce,warehouses:Zn,locations:Zn,people:Jn,users:Jn,empMaster:Jn,organizations:_n,countries:Ke,currencies:Be,shipments:Un},iT=e=>rT[e]??Nn,aT={bell:te,"book-open":ne,bookmark:se,building:ue,"credit-card":Be,"external-link":Qe,"file-text":ot,heart:ut,key:_t,"layout-dashboard":xt,"life-buoy":Et,mail:Bt,receipt:ln,settings:_n,shield:yn,users:Jn};Object.keys(aT);var oT=(e,t)=>e?aT[e]??t:t,sT=(e,t,n)=>(e.bottomBar?.items??[]).map((r,i)=>r.kind===`link`?{id:`link-${i}`,label:r.label,icon:oT(r.icon,Qe),href:r.href,external:!0}:r.kind===`page`?{id:r.page,label:r.label,icon:oT(r.icon??e.pages[r.page]?.icon,xt),href:ps({kind:`page`,page:r.page},t),active:r.page===n}:{id:r.resource,label:r.label,icon:oT(r.icon,iT(r.resource)),href:ps({kind:`list`,resource:r.resource},t),active:r.resource===n}),cT=({basePath:e,address:t,group:n,page:r,resourceLabel:i,recordTitle:a,recordLoading:o})=>{let s=n?[n]:[];if(r)return[...s,{label:r.title,href:ps({kind:`page`,page:r.name},e)}];if(!t||t.kind===`page`)return[`Admin`];let c=i?[{label:i,href:ps({kind:`list`,resource:t.resource},e)}]:[];if(t.kind===`list`)return[...s,...c];let l=ps(t,e),u=t.kind===`create`?{label:`New`,href:l}:a===void 0&&o?{label:`Loading record`,href:l,loading:!0}:{label:a??t.key,href:l};return[...s,...c,u]},lT=(e,t)=>t>=60&&t>Math.abs(e),uT=({title:e,open:t,onClose:n,children:r})=>{let i=(0,o.useRef)(null),a=(0,o.useRef)(void 0);return tu(i,t,n),t?(0,V.jsxs)(`div`,{className:`fixed inset-0 z-[80]`,children:[(0,V.jsx)(`div`,{className:`absolute inset-0 bg-backdrop/40`,onClick:n,"aria-hidden":!0}),(0,V.jsxs)(`div`,{ref:i,role:`dialog`,"aria-modal":`true`,"aria-label":e,tabIndex:-1,className:`absolute inset-x-0 bottom-0 flex max-h-[85vh] flex-col rounded-t-xl border-t bg-background shadow-pop outline-none`,children:[(0,V.jsxs)(`header`,{className:`relative flex shrink-0 touch-none items-center justify-between border-b px-4`,onPointerDown:e=>{e.pointerType===`touch`&&(a.current={x:e.clientX,y:e.clientY})},onPointerUp:e=>{if(!a.current)return;let t=lT(e.clientX-a.current.x,e.clientY-a.current.y);a.current=void 0,t&&n()},onPointerCancel:()=>a.current=void 0,children:[(0,V.jsx)(`span`,{className:`absolute left-1/2 top-1.5 h-1 w-9 -translate-x-1/2 rounded-full bg-border-strong`,"aria-hidden":!0}),(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:e}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Close`,onClick:n,className:`-mr-2 inline-flex size-11 items-center justify-center rounded-md text-muted-foreground hover:bg-muted`,children:(0,V.jsx)($n,{className:`size-5`})})]}),(0,V.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto overscroll-contain px-4 pb-6`,children:r})]})]}):null},dT=({title:e,description:t,open:n,onClose:r,actions:i,children:a,wide:o})=>{let s=Kl();return n?s?(0,V.jsx)(wf,{title:e,description:t,onClose:r,actions:i,wide:o,children:a}):(0,V.jsx)(uT,{title:e,open:!0,onClose:r,children:(0,V.jsxs)(`div`,{className:`pt-3`,children:[t&&(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:t}),a&&(0,V.jsx)(`div`,{className:`mt-4`,children:a}),(0,V.jsx)(`div`,{className:`mt-5 flex flex-col-reverse gap-2 [&>*]:min-h-11`,children:i})]})}):null},fT={text:`text`,integer:`integer`,decimal:`decimal`,boolean:`boolean`,date:`date`},pT=e=>{let t={name:e.name,column:e.name,nullable:!0,readOnly:!1,filterable:!1,sortable:!1,aliases:[]};return e.kind===`custom`?{...t,type:`json`}:e.kind===`choice`?e.resource===void 0?{...t,type:`enum`,enumValues:(e.options??[]).map(e=>e.value)}:{...t,type:`relation`,relation:{resource:e.resource,columns:[e.name]}}:{...t,type:fT[e.kind]}},mT=e=>({label:e.label,...e.multiline&&{multiline:!0},...e.options&&{valueLabels:Object.fromEntries(e.options.map(e=>[e.value,e.label]))}}),hT=e=>Object.fromEntries(e.map(e=>e.kind===`custom`?[e.name,e.default??null]:e.kind===`boolean`?[e.name,!!e.default]:[e.name,Mb(e.default)])),gT=(e,t)=>e.kind===`custom`?t??null:Kb(t)?t.key:e.resource===void 0?Rb(pT(e),t):String(t??``)===``?null:String(t),_T=(e,t)=>{let n=Object.fromEntries(e.map(e=>[e.name,gT(e,t[e.name])])),r=Eo(e,n);return{shown:r,values:Object.fromEntries(Object.entries(n).filter(([e])=>r.has(e)))}},vT=/^-?\d+(\.\d+)?$/,yT=/^\d{4}-\d{2}-\d{2}$/,bT=(e,t)=>{if(t===null||t===``)return e.required?`Required`:void 0;if(e.kind===`integer`&&!Number.isInteger(t))return`A whole number`;if(e.kind===`decimal`&&!vT.test(String(t)))return`A number`;if(e.kind===`date`&&!yT.test(String(t)))return`A date as YYYY-MM-DD`;if(e.max!==void 0&&String(t).length>e.max)return`At most ${e.max} characters`},xT=(e,t)=>Object.fromEntries(e.flatMap(e=>{if(!Object.hasOwn(t,e.name))return[];let n=bT(e,t[e.name]);return n?[[e.name,n]]:[]})),ST=class extends Error{errors;constructor(e){super(Object.values(e).join(`; `)),this.errors=e,this.name=`ActionInputError`}},CT=(e,t)=>{let n=new Set(t.map(e=>e.name)),r=e instanceof ST?Object.entries(e.errors):Rs(e)?e.errors.flatMap(e=>e.field?[[e.field,e.message]]:[]):[];return Object.fromEntries(r.filter(([e])=>n.has(e)))},wT=({input:e,held:t,invalid:n,onChange:r})=>{let{resources:i,views:a}=J(),{components:o}=SC();if(e.kind===`custom`){let i=o?.[e.component??``];if(!i)throw Error(`Input "${e.name}": the app has no component "${e.component}"`);return(0,V.jsx)(i,{input:e,value:t??null,onChange:r,invalid:n,props:e.props??{}})}let s=e.resource===void 0?void 0:i[e.resource];return(0,V.jsx)(IC,{field:pT(e),hints:mT(e),value:Kb(t)?t.key:t,stored:void 0,relationLabel:Kb(t)?t.label:void 0,relationPicker:s?{target:s,view:a[s.name]}:void 0,invalid:n,onChange:r})},TT=({action:e,label:t,danger:n,onCancel:r,onSubmit:i})=>{let[a,s]=(0,o.useState)(()=>hT(e.inputs)),[c,l]=(0,o.useState)({}),[u,d]=(0,o.useState)(),[f,p]=(0,o.useState)(!1),m=(0,o.useId)(),{shown:h,values:g}=_T(e.inputs,a),_=async()=>{let t=xT(e.inputs,g);l(t),d(void 0),!(Object.keys(t).length>0)&&(p(!0),await i(g).catch(t=>{l(CT(t,e.inputs)),d(t)}),p(!1))},v=(e,t)=>{l(({[e]:t,...n})=>n),s(n=>({...n,[e]:t}))};return(0,V.jsx)(dT,{title:t,description:e.confirm,open:!0,onClose:r,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:r,children:`Cancel`}),(0,V.jsx)(U,{variant:n?`danger`:`primary`,type:`submit`,form:m,loading:f,children:t})]}),children:(0,V.jsxs)(`form`,{id:m,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),_()},children:[u!==void 0&&Object.keys(c).length===0&&(0,V.jsx)(ax,{title:`${t} failed`,error:u}),e.inputs.filter(e=>h.has(e.name)).map(e=>(0,V.jsx)(eb,{label:e.label,required:e.required,help:e.help,error:c[e.name],children:(0,V.jsx)(wT,{input:e,held:a[e.name],invalid:!!c[e.name],onChange:t=>v(e.name,t)})},e.name))]})})},ET=({action:e,label:t,danger:n,onCancel:r,onConfirm:i})=>(0,V.jsx)(wf,{title:`${t}?`,description:e.confirm,onClose:r,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:r,children:`Cancel`}),(0,V.jsx)(U,{variant:n?`danger`:`primary`,onClick:i,children:t})]})}),DT=e=>!!(e.confirm||e.inputs?.length),OT=({action:e,label:t,danger:n,onCancel:r,onConfirm:i,onSubmit:a})=>{let{inputs:o}=e;return o?.length?(0,V.jsx)(TT,{action:{...e,inputs:o},label:t,danger:n,onCancel:r,onSubmit:a}):(0,V.jsx)(ET,{action:e,label:t,danger:n,onCancel:r,onConfirm:i})},kT=(0,o.createContext)(void 0),AT=({value:e,children:t})=>(0,V.jsx)(kT.Provider,{value:e,children:t}),jT=()=>(0,o.useContext)(kT),MT=(e,t)=>e[t]||e.conditional.includes(t),NT=(e,t)=>e.permissions?.[t]??!0,PT=(e,t)=>e?.fields?e.fields[t]??`hidden`:`edit`,FT=(e,t={})=>e.replace(/\{([A-Za-z_][A-Za-z0-9_]*)\}/g,(e,n)=>encodeURIComponent(t[n]===null||t[n]===void 0?``:String(t[n]))),IT=e=>{if(typeof e!=`string`||!URL.canParse(e))return;let t=new URL(e);return t.protocol===`https:`||t.protocol===`http:`?t.href:void 0},LT=(e,t={})=>{let n=_o(e);return n===void 0?FT(e,t):IT(t[n])},RT=e=>{e!==void 0&&(/^https?:/i.test(e)?window.open(e,`_blank`,`noopener,noreferrer`):window.location.assign(e))},zT=e=>URL.canParse(e)?new URL(e).hostname.replace(/^www\./,``):``,BT=(e,t)=>Object.entries(t).every(([t,n])=>Object.is(e[t],n)),VT=(e,t)=>{let n=e.run;if(n?.kind===`update`)return t&&BT(t,n.values)?void 0:e;if(n?.kind!==`link`||!(`href`in n))return e;let r=LT(n.href,t);if(r!==void 0)return e.label.includes(`{host}`)?{...e,label:e.label.replaceAll(`{host}`,zT(r))}:e},HT=(e,t)=>({model:e,record:t,key:Ao(zx(e,t)),etag:typeof t.etag==`string`?t.etag:void 0,permissions:t.permissions}),UT=(e,t,n=``)=>({queryKey:W.count(t.name,n),queryFn:async()=>{let r=await e.list(t.name,{filter:n||void 0,pageSize:1,count:`exact`,fields:t.primaryKey});return r.totalSize??r.totalSizeEstimate}}),WT=(e,t=``)=>mh(UT(G(),e,t)),GT=(e,{filter:t=``,sort:n=``,key:r})=>{let i=G();return mh({queryKey:r===void 0?W.firstRecord(e.name,t,n):W.record(e.name,r),queryFn:async()=>{if(r!==void 0){let t=await i.get(e.name,r);return{...HT(e,t.record),etag:t.etag,permissions:t.permissions}}let a=await i.list(e.name,{filter:t||void 0,orderBy:n||void 0,pageSize:1});return a.items[0]?HT(e,a.items[0]):null}})},KT=(e,{filter:t=``,sort:n=``,pageSize:r,pageToken:i=``})=>{let a=G();return mh({queryKey:W.list(e.name,t,n,r,i),placeholderData:hm,queryFn:()=>a.list(e.name,{filter:t||void 0,orderBy:n||void 0,pageSize:r,pageToken:i||void 0})})},qT=()=>{let e=Gp();return(0,o.useCallback)(t=>e.invalidateQueries({predicate:e=>e.queryKey[1]===t}),[e])},JT=e=>e instanceof Error?e.message:`Something went wrong`,YT=(e,t,n)=>{let{views:r}=J(),{actions:i,components:a}=SC(),s=YS(e),c=G(),l=xh(e),u=Qy(),d=qT(),{go:f}=XS(),[p,m]=(0,o.useState)(),h=(r[e]?.actions??[]).flatMap(e=>VT(e,t?.record)??[]),g=e=>{let n=e.run?.kind;if((n===`update`||n===`delete`||n===`ai`)&&!t)return`Needs a record`;if((n===`update`||n===`ai`)&&(!MT(s,`update`)||t?.permissions?.update===!1)||e.run?.kind===`ai`&&t?.permissions?.fields?.[e.run.writes]===`read`)return`You cannot change this record`;if(n===`delete`&&(!MT(s,`delete`)||t?.permissions?.delete===!1))return`You cannot delete this record`;if(!e.run&&!i?.[e.name])return`The app has no handler for "${e.name}"`;let r=e.inputs?.find(e=>e.kind===`custom`&&!a?.[e.component??``]);if(r)return`The app has no component "${r.component}" for input "${r.name}"`},_=async(r,a)=>{let{run:o}=r;if(o?.kind===`link`){`to`in o?f(go(o.to,t?.record)):RT(LT(o.href,t?.record));return}o?.kind===`update`?await c.update(e,t.key,o.values,t.etag??`*`):o?.kind===`delete`?await c.remove(e,t.key,{etag:t.etag}):o?.kind===`ai`?await c.generate(e,t.key,r.name):await i[r.name]({resource:e,record:t?.record,recordKey:t?.key,etag:t?.etag,client:l,navigate:f,...a&&{values:a}}),await d(e),u.show({state:`success`,title:`${r.label}: done`}),n?.(r)};return{actions:h,blocked:g,running:p,run:async e=>{g(e)||(m(e.name),await _(e).catch(t=>u.show({state:`error`,title:`${e.label} failed`,description:JT(t)})),m(void 0))},submit:async(e,t)=>{g(e)||(m(e.name),await _(e,t).finally(()=>m(void 0)))}}},XT=(e,t,n)=>{let r=YT(e,n),i=r.actions.find(e=>e.name===t);return{action:i,blocked:i?r.blocked(i):`No action "${t}"`,running:r.running===t,run:()=>i?r.run(i):Promise.resolve(),submit:e=>i?r.submit(i,e):Promise.resolve()}},ZT=e=>e.props,QT=({node:e})=>{let{name:t,resource:n,label:r,variant:i}=ZT(e),a=jT(),s=XT(n??a?.model.name??``,t,n===void 0||n===a?.model.name?a:void 0),[c,l]=(0,o.useState)(!1);if(!s.action)return null;let u=r??s.action.label;return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{size:`sm`,variant:i??`secondary`,loading:s.running,disabled:!!s.blocked,title:s.blocked,onClick:()=>DT(s.action)?l(!0):void s.run(),children:u}),c&&(0,V.jsx)(OT,{action:s.action,label:u,danger:i===`danger`,onCancel:()=>l(!1),onConfirm:()=>{l(!1),s.run()},onSubmit:async e=>{await s.submit(e),l(!1)}})]})},$T=({title:e,description:t,actions:n,className:r,bodyClassName:i,children:a})=>(0,V.jsxs)(`section`,{className:B(`flex min-w-0 flex-col rounded-lg border border-border bg-background`,r),"aria-label":e,children:[(e||t||n)&&(0,V.jsxs)(`header`,{className:`flex flex-wrap items-start justify-between gap-x-4 gap-y-2 px-4 pt-4`,children:[(0,V.jsxs)(`div`,{className:`min-w-0`,children:[e&&(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold tracking-tight`,children:e}),t&&(0,V.jsx)(`p`,{className:`mt-0.5 text-muted-foreground`,children:t})]}),n&&(0,V.jsx)(`div`,{className:`flex flex-wrap items-center gap-2`,children:n})]}),(0,V.jsx)(`div`,{className:B(`min-w-0 flex-1 p-4`,i),children:a})]}),eE=({children:e})=>(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:e}),tE=({node:e,children:t,slots:n})=>{let{title:r,description:i}=ZT(e);return(0,V.jsx)($T,{title:r,description:i,actions:n.actions,className:`h-full`,children:(0,V.jsx)(`div`,{className:`flex flex-col gap-3`,children:t})})},nE=({model:e,filter:t,sort:n,limit:r=12,title:i,description:a,empty:o,actions:s,children:c})=>{let l=KT(e,{filter:t,sort:n,pageSize:r}),u=l.data?.items??[];return(0,V.jsx)($T,{title:i,description:a,actions:s,children:l.isPending?(0,V.jsx)(`div`,{className:`flex gap-3`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-24 w-56`},t))}):l.error?(0,V.jsx)(ax,{title:`Could not load`,error:l.error}):u.length===0?(0,V.jsx)(eE,{children:o??`Nothing here yet.`}):(0,V.jsx)(`ul`,{className:`-mx-4 flex snap-x gap-3 overflow-x-auto px-4 pb-1`,children:u.map(t=>{let n=HT(e,t);return(0,V.jsx)(`li`,{className:`flex w-60 shrink-0 snap-start flex-col gap-2 rounded-lg border border-border bg-surface p-3`,children:(0,V.jsx)(AT,{value:n,children:c})},n.key)})})})},rE=({node:e,children:t,slots:n})=>{let{resource:r,...i}=ZT(e),a=J().resources[r];return a?(0,V.jsx)(nE,{...i,model:a,actions:n.actions,children:t}):null},iE=(e,t,n,r=!0)=>{let i=G(),a=Ts(n)??``;return mh({queryKey:W.facets(e,t,a),enabled:r,queryFn:()=>i.facets(e,t,{filter:a,limit:50})})},aE=(e,t,n=!0)=>{let r=G(),i=Ts(t.filter)??``;return mh({queryKey:W.series(e,t.field,`${t.range??``}${t.from??``}${t.to??``}`,t.granularity??``,i),enabled:n,queryFn:()=>r.series(e,{...t,filter:i})})},oE=(e,t,n,r=20,i=!0)=>{let a=G(),o=Ts(n)??``;return mh({queryKey:W.histogram(e,t,r,o),enabled:i,queryFn:()=>a.histogram(e,t,{filter:o,buckets:r})})},sE=(e,t,n=!0)=>{let r=G(),i={...t,filter:Ts(t.filter)??``};return mh({queryKey:W.aggregate(e,JSON.stringify(i)),enabled:n,queryFn:()=>r.aggregate(e,i)})},cE=co(),lE=e=>e>=0&&e<8?`var(--chart-${e+1})`:`var(--faint-foreground)`,uE=(e,t,n,r)=>{let i=String(n);return n===null?`var(--faint-foreground)`:t?.valueColors&&Object.hasOwn(t.valueColors,i)?t.valueColors[i]:e.type===`enum`?lE(e.enumValues?.indexOf(i)??-1):e.type===`boolean`?lE(+!n):lE(r)},dE=(e,t,n)=>n.value===null?`Not set`:e.type===`enum`?rs(String(n.value),t?.valueLabels):e.type===`boolean`?n.value?`Yes`:`No`:n.label??String(n.value),fE=(e,t,n=``)=>{let r=qa(t===null?cE.isNull(e.name):cE.eq(e.name,t));return n.trim()?`(${n}) AND ${r}`:r},pE=(e,t)=>t.kind===`count`?e.count:e[t.kind]??null,mE=(e,t,n,r,i=``)=>e.map((e,a)=>({key:String(e.value),label:dE(t,n,e),value:pE(e,r),count:e.count,color:uE(t,n,e.value,a),filter:fE(t,e.value,i)})),hE=(e,t)=>e.map(e=>({at:Date.parse(`${String(e.value)}Z`),value:pE(e,t),count:e.count})),gE=(e,t)=>{if(e===null)return`—`;if(t.kind===`count`)return e.toLocaleString(`en-IE`);let n=t.hints?.decimals??(Number.isInteger(e)?0:2),r=e.toLocaleString(`en-IE`,{minimumFractionDigits:n,maximumFractionDigits:n});return`${t.hints?.prefix??``}${r}${t.hints?.suffix??``}`},_E=({resource:e,slices:t,measure:n})=>{let r=Math.max(0,...t.map(e=>e.value??0));return(0,V.jsx)(`ul`,{className:`flex flex-col gap-1`,children:t.map(t=>{let i=r>0&&t.value!==null?Math.max(0,t.value)/r:0;return(0,V.jsx)(`li`,{children:(0,V.jsxs)(ZS,{to:{kind:`list`,resource:e,filter:t.filter},className:`group grid grid-cols-[minmax(6rem,35%)_1fr_auto] items-center gap-3 rounded-md px-1 py-1 hover:bg-muted`,title:n.kind===`count`?void 0:`${gE(t.count,{kind:`count`})} records`,children:[(0,V.jsx)(`span`,{className:`truncate group-hover:text-primary-text`,children:t.label}),(0,V.jsx)(`span`,{className:`h-3 rounded-r bg-muted`,"aria-hidden":!0,children:(0,V.jsx)(`span`,{className:`block h-full rounded-r`,style:{width:`${i*100}%`,background:`var(--chart-1)`}})}),(0,V.jsx)(`span`,{className:`text-right font-medium tabular-nums`,children:gE(t.value,n)})]})},t.key)})})};function vE(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(n=vE(e[t]))&&(r&&(r+=` `),r+=n)}else for(n in e)e[n]&&(r&&(r+=` `),r+=n)}return r}function yE(){for(var e,t,n=0,r=``,i=arguments.length;n<i;n++)(e=arguments[n])&&(t=vE(e))&&(r&&(r+=` `),r+=t);return r}var bE=`dangerouslySetInnerHTML.onCopy.onCopyCapture.onCut.onCutCapture.onPaste.onPasteCapture.onCompositionEnd.onCompositionEndCapture.onCompositionStart.onCompositionStartCapture.onCompositionUpdate.onCompositionUpdateCapture.onFocus.onFocusCapture.onBlur.onBlurCapture.onChange.onChangeCapture.onBeforeInput.onBeforeInputCapture.onInput.onInputCapture.onReset.onResetCapture.onSubmit.onSubmitCapture.onInvalid.onInvalidCapture.onLoad.onLoadCapture.onError.onErrorCapture.onKeyDown.onKeyDownCapture.onKeyPress.onKeyPressCapture.onKeyUp.onKeyUpCapture.onAbort.onAbortCapture.onCanPlay.onCanPlayCapture.onCanPlayThrough.onCanPlayThroughCapture.onDurationChange.onDurationChangeCapture.onEmptied.onEmptiedCapture.onEncrypted.onEncryptedCapture.onEnded.onEndedCapture.onLoadedData.onLoadedDataCapture.onLoadedMetadata.onLoadedMetadataCapture.onLoadStart.onLoadStartCapture.onPause.onPauseCapture.onPlay.onPlayCapture.onPlaying.onPlayingCapture.onProgress.onProgressCapture.onRateChange.onRateChangeCapture.onSeeked.onSeekedCapture.onSeeking.onSeekingCapture.onStalled.onStalledCapture.onSuspend.onSuspendCapture.onTimeUpdate.onTimeUpdateCapture.onVolumeChange.onVolumeChangeCapture.onWaiting.onWaitingCapture.onAuxClick.onAuxClickCapture.onClick.onClickCapture.onContextMenu.onContextMenuCapture.onDoubleClick.onDoubleClickCapture.onDrag.onDragCapture.onDragEnd.onDragEndCapture.onDragEnter.onDragEnterCapture.onDragExit.onDragExitCapture.onDragLeave.onDragLeaveCapture.onDragOver.onDragOverCapture.onDragStart.onDragStartCapture.onDrop.onDropCapture.onMouseDown.onMouseDownCapture.onMouseEnter.onMouseLeave.onMouseMove.onMouseMoveCapture.onMouseOut.onMouseOutCapture.onMouseOver.onMouseOverCapture.onMouseUp.onMouseUpCapture.onSelect.onSelectCapture.onTouchCancel.onTouchCancelCapture.onTouchEnd.onTouchEndCapture.onTouchMove.onTouchMoveCapture.onTouchStart.onTouchStartCapture.onPointerDown.onPointerDownCapture.onPointerMove.onPointerMoveCapture.onPointerUp.onPointerUpCapture.onPointerCancel.onPointerCancelCapture.onPointerEnter.onPointerEnterCapture.onPointerLeave.onPointerLeaveCapture.onPointerOver.onPointerOverCapture.onPointerOut.onPointerOutCapture.onGotPointerCapture.onGotPointerCaptureCapture.onLostPointerCapture.onLostPointerCaptureCapture.onScroll.onScrollCapture.onWheel.onWheelCapture.onAnimationStart.onAnimationStartCapture.onAnimationEnd.onAnimationEndCapture.onAnimationIteration.onAnimationIterationCapture.onTransitionEnd.onTransitionEndCapture`.split(`.`);function xE(e){return typeof e==`string`&&bE.includes(e)}var SE=new Set(`aria-activedescendant.aria-atomic.aria-autocomplete.aria-busy.aria-checked.aria-colcount.aria-colindex.aria-colspan.aria-controls.aria-current.aria-describedby.aria-details.aria-disabled.aria-errormessage.aria-expanded.aria-flowto.aria-haspopup.aria-hidden.aria-invalid.aria-keyshortcuts.aria-label.aria-labelledby.aria-level.aria-live.aria-modal.aria-multiline.aria-multiselectable.aria-orientation.aria-owns.aria-placeholder.aria-posinset.aria-pressed.aria-readonly.aria-relevant.aria-required.aria-roledescription.aria-rowcount.aria-rowindex.aria-rowspan.aria-selected.aria-setsize.aria-sort.aria-valuemax.aria-valuemin.aria-valuenow.aria-valuetext.className.color.height.id.lang.max.media.method.min.name.style.target.width.role.tabIndex.accentHeight.accumulate.additive.alignmentBaseline.allowReorder.alphabetic.amplitude.arabicForm.ascent.attributeName.attributeType.autoReverse.azimuth.baseFrequency.baselineShift.baseProfile.bbox.begin.bias.by.calcMode.capHeight.clip.clipPath.clipPathUnits.clipRule.colorInterpolation.colorInterpolationFilters.colorProfile.colorRendering.contentScriptType.contentStyleType.cursor.cx.cy.d.decelerate.descent.diffuseConstant.direction.display.divisor.dominantBaseline.dur.dx.dy.edgeMode.elevation.enableBackground.end.exponent.externalResourcesRequired.fill.fillOpacity.fillRule.filter.filterRes.filterUnits.floodColor.floodOpacity.focusable.fontFamily.fontSize.fontSizeAdjust.fontStretch.fontStyle.fontVariant.fontWeight.format.from.fx.fy.g1.g2.glyphName.glyphOrientationHorizontal.glyphOrientationVertical.glyphRef.gradientTransform.gradientUnits.hanging.horizAdvX.horizOriginX.href.ideographic.imageRendering.in2.in.intercept.k1.k2.k3.k4.k.kernelMatrix.kernelUnitLength.kerning.keyPoints.keySplines.keyTimes.lengthAdjust.letterSpacing.lightingColor.limitingConeAngle.local.markerEnd.markerHeight.markerMid.markerStart.markerUnits.markerWidth.mask.maskContentUnits.maskUnits.mathematical.mode.numOctaves.offset.opacity.operator.order.orient.orientation.origin.overflow.overlinePosition.overlineThickness.paintOrder.panose1.pathLength.patternContentUnits.patternTransform.patternUnits.pointerEvents.pointsAtX.pointsAtY.pointsAtZ.preserveAlpha.preserveAspectRatio.primitiveUnits.r.radius.refX.refY.renderingIntent.repeatCount.repeatDur.requiredExtensions.requiredFeatures.restart.result.rotate.rx.ry.seed.shapeRendering.slope.spacing.specularConstant.specularExponent.speed.spreadMethod.startOffset.stdDeviation.stemh.stemv.stitchTiles.stopColor.stopOpacity.strikethroughPosition.strikethroughThickness.string.stroke.strokeDasharray.strokeDashoffset.strokeLinecap.strokeLinejoin.strokeMiterlimit.strokeOpacity.strokeWidth.surfaceScale.systemLanguage.tableValues.targetX.targetY.textAnchor.textDecoration.textLength.textRendering.to.transform.u1.u2.underlinePosition.underlineThickness.unicode.unicodeBidi.unicodeRange.unitsPerEm.vAlphabetic.values.vectorEffect.version.vertAdvY.vertOriginX.vertOriginY.vHanging.vIdeographic.viewTarget.visibility.vMathematical.widths.wordSpacing.writingMode.x1.x2.x.xChannelSelector.xHeight.xlinkActuate.xlinkArcrole.xlinkHref.xlinkRole.xlinkShow.xlinkTitle.xlinkType.xmlBase.xmlLang.xmlns.xmlnsXlink.xmlSpace.y1.y2.y.yChannelSelector.z.zoomAndPan.ref.key.angle`.split(`.`));function CE(e){return typeof e==`string`&&SE.has(e)}function wE(e){return typeof e==`string`&&e.startsWith(`data-`)}function TE(e){if(typeof e!=`object`||!e)return{};var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(CE(n)||wE(n))&&(t[n]=e[n]);return t}function EE(e){if(e==null)return null;if((0,o.isValidElement)(e)&&typeof e.props==`object`&&e.props!==null){var t=e.props;return TE(t)}return typeof e==`object`&&!Array.isArray(e)?TE(e):null}function DE(e){var t={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(CE(n)||wE(n)||xE(n))&&(t[n]=e[n]);return t}function OE(e){return e==null?null:(0,o.isValidElement)(e)?DE(e.props):typeof e==`object`&&!Array.isArray(e)?DE(e):null}var kE=[`children`,`width`,`height`,`viewBox`,`className`,`style`,`title`,`desc`];function AE(){return AE=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},AE.apply(null,arguments)}function jE(e,t){if(e==null)return{};var n,r,i=ME(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function ME(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var NE=(0,o.forwardRef)((e,t)=>{var n=e.children,r=e.width,i=e.height,a=e.viewBox,s=e.className,c=e.style,l=e.title,u=e.desc,d=jE(e,kE),f=a||{width:r,height:i,x:0,y:0},p=yE(`recharts-surface`,s);return o.createElement(`svg`,AE({},DE(d),{className:p,width:r,height:i,style:c,viewBox:`${f.x} ${f.y} ${f.width} ${f.height}`,ref:t}),o.createElement(`title`,null,l),o.createElement(`desc`,null,u),n)}),PE=[`children`,`className`];function FE(){return FE=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},FE.apply(null,arguments)}function IE(e,t){if(e==null)return{};var n,r,i=LE(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function LE(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var RE=o.forwardRef((e,t)=>{var n=e.children,r=e.className,i=IE(e,PE),a=yE(`recharts-layer`,r);return o.createElement(`g`,FE({className:a},DE(i),{ref:t}),n)});function zE(e){return e===`__proto__`}var BE=/\.|(\[(?:[^[\]]*|(["'])(?:(?!\2)[^\\]|\\.)*?\2)\])/;function VE(e){switch(typeof e){case`number`:case`symbol`:return!1;case`string`:return e===``||e.startsWith(`.`)||e.endsWith(`.`)?!1:BE.test(e);default:return!1}}function HE(e){return typeof e==`string`||typeof e==`symbol`?e:Object.is(e?.valueOf?.(),-0)?`-0`:String(e)}function UE(e){return typeof e==`symbol`||e instanceof Symbol}function WE(e){return e==null?``:GE(e)}function GE(e){if(typeof e==`string`)return e;if(Array.isArray(e))return e.map(GE).join(`,`);if(UE(e))return e.toString();let t=e+``;return t===`0`&&Object.is(Number(e),-0)?`-0`:t}function KE(e){if(Array.isArray(e))return e.map(HE);if(typeof e==`symbol`)return[e];e=WE(e);let t=[],n=e.length;if(n===0)return t;let r=0,i=``,a=``,o=!1,s=!1,c=/^-?\d+(?:\.\d+)?$/;for(e.charCodeAt(0)===46&&t.push(``);r<n;){let l=e[r];if(a)l===`\\`&&r+1<n?(r++,i+=e[r]):l===a?a=``:i+=l;else if(o){if(l===`"`||l===`'`)a=l,s=!0;else if(l===`]`){if(o=!1,!s&&i.includes(`.`)&&!c.test(i)){let e=i.split(`.`);for(let n=0;n<e.length;n++)e[n]!==``&&t.push(e[n])}else t.push(i);i=``}else i+=l}else if(l===`[`)o=!0,s=!1,i&&=(t.push(i),``);else if(l===`.`){i&&=(t.push(i),``);let n=e[r+1];(n===void 0||n===`.`)&&t.push(``)}else i+=l;r++}return i&&t.push(i),t}function qE(e,t,n){if(e==null)return n;switch(typeof t){case`string`:{if(zE(t))return n;let r=e[t];return r===void 0?VE(t)&&!Object.hasOwn(e,t)?qE(e,KE(t),n):n:r}case`number`:case`symbol`:{typeof t==`number`&&(t=HE(t));let r=e[t];return r===void 0?n:r}default:{if(Array.isArray(t))return JE(e,t,n);if(t=Object.is(t?.valueOf(),-0)?`-0`:String(t),zE(t))return n;let r=e[t];return r===void 0?n:r}}}function JE(e,t,n){if(t.length===0)return n;let r=e;for(let e=0;e<t.length;e++){if(r==null||zE(t[e]))return n;r=r[t[e]]}return r===void 0?n:r}var YE=4;function XE(e){var t=10**(arguments.length>1&&arguments[1]!==void 0?arguments[1]:YE),n=Math.round(e*t)/t;return Object.is(n,-0)?0:n}function ZE(e){var t=[...arguments].slice(1);return e.reduce((e,n,r)=>{var i=t[r-1];return typeof i==`string`?e+i+n:i===void 0?e+n:e+XE(i)+n},``)}var QE=e=>e===0?0:e>0?1:-1,$E=e=>typeof e==`number`&&e!=+e,eD=e=>typeof e==`string`&&e.length>1&&e.indexOf(`%`)===e.length-1,Y=e=>(typeof e==`number`||e instanceof Number)&&!$E(e),tD=e=>Y(e)||typeof e==`string`,nD=0,rD=e=>{var t=++nD;return`${e||``}${t}`},iD=function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,r=arguments.length>3&&arguments[3]!==void 0&&arguments[3];if(!Y(e)&&typeof e!=`string`)return n;var i;if(eD(e)){if(t==null)return n;var a=e.indexOf(`%`);i=t*parseFloat(e.slice(0,a))/100}else i=+e;return $E(i)&&(i=n),r&&t!=null&&i>t&&(i=t),i},aD=e=>{if(!Array.isArray(e))return!1;for(var t=e.length,n={},r=0;r<t;r++)if(!n[String(e[r])])n[String(e[r])]=!0;else return!0;return!1};function oD(e,t,n){return Y(e)&&Y(t)?XE(e+n*(t-e)):t}function sD(e,t,n){if(e&&e.length)return e.find(e=>e&&(typeof t==`function`?t(e):qE(e,t))===n)}var cD=e=>e==null,lD=e=>cD(e)?e:`${e.charAt(0).toUpperCase()}${e.slice(1)}`;function uD(e){return e!=null}function dD(){}function fD(e){if(e)return{x:e.x,y:e.y,upperWidth:`upperWidth`in e?e.upperWidth:e.width,lowerWidth:`lowerWidth`in e?e.lowerWidth:e.width,width:e.width,height:e.height}}function pD(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function mD(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?pD(Object(n),!0).forEach(function(t){hD(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):pD(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function hD(e,t,n){return(t=gD(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function gD(e){var t=_D(e,`string`);return typeof t==`symbol`?t:t+``}function _D(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var vD=e=>{var t=e.viewBox,n=e.position,r=e.offset,i=r===void 0?0:r,a=e.parentViewBox,o=e.clamp,s=fD(t),c=s.x,l=s.y,u=s.height,d=s.upperWidth,f=s.lowerWidth,p=c,m=c+(d-f)/2,h=(p+m)/2,g=(d+f)/2,_=p+d/2,v=u>=0?1:-1,y=v*i,b=v>0?`end`:`start`,x=v>0?`start`:`end`,S=d>=0?1:-1,C=S*i,w=S>0?`end`:`start`,T=S>0?`start`:`end`,E=a;if(n===`top`){var D={x:p+d/2,y:l-y,horizontalAnchor:`middle`,verticalAnchor:b};return o&&E&&(D.height=Math.max(l-E.y,0),D.width=d),D}if(n===`bottom`){var O={x:m+f/2,y:l+u+y,horizontalAnchor:`middle`,verticalAnchor:x};return o&&E&&(O.height=Math.max(E.y+E.height-(l+u),0),O.width=f),O}if(n===`left`){var k={x:h-C,y:l+u/2,horizontalAnchor:w,verticalAnchor:`middle`};return o&&E&&(k.width=Math.max(k.x-E.x,0),k.height=u),k}if(n===`right`){var A={x:h+g+C,y:l+u/2,horizontalAnchor:T,verticalAnchor:`middle`};return o&&E&&(A.width=Math.max(E.x+E.width-A.x,0),A.height=u),A}var j=o&&E?{width:g,height:u}:{};return n===`insideLeft`?mD({x:h+C,y:l+u/2,horizontalAnchor:T,verticalAnchor:`middle`},j):n===`insideRight`?mD({x:h+g-C,y:l+u/2,horizontalAnchor:w,verticalAnchor:`middle`},j):n===`insideTop`?mD({x:p+d/2,y:l+y,horizontalAnchor:`middle`,verticalAnchor:x},j):n===`insideBottom`?mD({x:m+f/2,y:l+u-y,horizontalAnchor:`middle`,verticalAnchor:b},j):n===`insideTopLeft`?mD({x:p+C,y:l+y,horizontalAnchor:T,verticalAnchor:x},j):n===`insideTopRight`?mD({x:p+d-C,y:l+y,horizontalAnchor:w,verticalAnchor:x},j):n===`insideBottomLeft`?mD({x:m+C,y:l+u-y,horizontalAnchor:T,verticalAnchor:b},j):n===`insideBottomRight`?mD({x:m+f-C,y:l+u-y,horizontalAnchor:w,verticalAnchor:b},j):n&&typeof n==`object`&&(Y(n.x)||eD(n.x))&&(Y(n.y)||eD(n.y))?mD({x:c+iD(n.x,g),y:l+iD(n.y,u),horizontalAnchor:`end`,verticalAnchor:`end`},j):mD({x:_,y:l+u/2,horizontalAnchor:`middle`,verticalAnchor:`middle`},j)},yD=[`top`,`left`,`right`,`bottom`];function bD(e){return e==null?!1:typeof e==`object`||yD.includes(e)}var xD=(0,o.createContext)(null);function SD(e){return function(){return e}}var CD=Math.PI,wD=2*CD,TD=1e-6,ED=wD-TD;function DD(e){this._+=e[0];for(let t=1,n=e.length;t<n;++t)this._+=arguments[t]+e[t]}function OD(e){let t=Math.floor(e);if(!(t>=0))throw Error(`invalid digits: ${e}`);if(t>15)return DD;let n=10**t;return function(e){this._+=e[0];for(let t=1,r=e.length;t<r;++t)this._+=Math.round(arguments[t]*n)/n+e[t]}}var kD=class{constructor(e){this._x0=this._y0=this._x1=this._y1=null,this._=``,this._append=e==null?DD:OD(e)}moveTo(e,t){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+t}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(e,t){this._append`L${this._x1=+e},${this._y1=+t}`}quadraticCurveTo(e,t,n,r){this._append`Q${+e},${+t},${this._x1=+n},${this._y1=+r}`}bezierCurveTo(e,t,n,r,i,a){this._append`C${+e},${+t},${+n},${+r},${this._x1=+i},${this._y1=+a}`}arcTo(e,t,n,r,i){if(e=+e,t=+t,n=+n,r=+r,i=+i,i<0)throw Error(`negative radius: ${i}`);let a=this._x1,o=this._y1,s=n-e,c=r-t,l=a-e,u=o-t,d=l*l+u*u;if(this._x1===null)this._append`M${this._x1=e},${this._y1=t}`;else if(d>TD){if(!(Math.abs(u*s-c*l)>TD)||!i)this._append`L${this._x1=e},${this._y1=t}`;else{let f=n-a,p=r-o,m=s*s+c*c,h=f*f+p*p,g=Math.sqrt(m),_=Math.sqrt(d),v=i*Math.tan((CD-Math.acos((m+d-h)/(2*g*_)))/2),y=v/_,b=v/g;Math.abs(y-1)>TD&&this._append`L${e+y*l},${t+y*u}`,this._append`A${i},${i},0,0,${+(u*f>l*p)},${this._x1=e+b*s},${this._y1=t+b*c}`}}}arc(e,t,n,r,i,a){if(e=+e,t=+t,n=+n,a=!!a,n<0)throw Error(`negative radius: ${n}`);let o=n*Math.cos(r),s=n*Math.sin(r),c=e+o,l=t+s,u=1^a,d=a?r-i:i-r;this._x1===null?this._append`M${c},${l}`:(Math.abs(this._x1-c)>TD||Math.abs(this._y1-l)>TD)&&this._append`L${c},${l}`,n&&(d<0&&(d=d%wD+wD),d>ED?this._append`A${n},${n},0,1,${u},${e-o},${t-s}A${n},${n},0,1,${u},${this._x1=c},${this._y1=l}`:d>TD&&this._append`A${n},${n},0,${+(d>=CD)},${u},${this._x1=e+n*Math.cos(i)},${this._y1=t+n*Math.sin(i)}`)}rect(e,t,n,r){this._append`M${this._x0=this._x1=+e},${this._y0=this._y1=+t}h${n=+n}v${+r}h${-n}Z`}toString(){return this._}};kD.prototype;function AD(e){let t=3;return e.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{let e=Math.floor(n);if(!(e>=0))throw RangeError(`invalid digits: ${n}`);t=e}return e},()=>new kD(t)}Array.prototype.slice;function jD(e){return typeof e==`object`&&`length`in e?e:Array.from(e)}function MD(e){this._context=e}MD.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t)}}};function ND(e){return new MD(e)}function PD(e){return e[0]}function FD(e){return e[1]}function ID(e,t){var n=SD(!0),r=null,i=ND,a=null,o=AD(s);e=typeof e==`function`?e:e===void 0?PD:SD(e),t=typeof t==`function`?t:t===void 0?FD:SD(t);function s(s){var c,l=(s=jD(s)).length,u,d=!1,f;for(r??(a=i(f=o())),c=0;c<=l;++c)!(c<l&&n(u=s[c],c,s))===d&&((d=!d)?a.lineStart():a.lineEnd()),d&&a.point(+e(u,c,s),+t(u,c,s));if(f)return a=null,f+``||null}return s.x=function(t){return arguments.length?(e=typeof t==`function`?t:SD(+t),s):e},s.y=function(e){return arguments.length?(t=typeof e==`function`?e:SD(+e),s):t},s.defined=function(e){return arguments.length?(n=typeof e==`function`?e:SD(!!e),s):n},s.curve=function(e){return arguments.length?(i=e,r!=null&&(a=i(r)),s):i},s.context=function(e){return arguments.length?(e==null?r=a=null:a=i(r=e),s):r},s}function LD(e,t,n){var r=null,i=SD(!0),a=null,o=ND,s=null,c=AD(l);e=typeof e==`function`?e:e===void 0?PD:SD(+e),t=typeof t==`function`?t:SD(t===void 0?0:+t),n=typeof n==`function`?n:n===void 0?FD:SD(+n);function l(l){var u,d,f,p=(l=jD(l)).length,m,h=!1,g,_=Array(p),v=Array(p);for(a??(s=o(g=c())),u=0;u<=p;++u){if(!(u<p&&i(m=l[u],u,l))===h){if(h=!h)d=u,s.areaStart(),s.lineStart();else{for(s.lineEnd(),s.lineStart(),f=u-1;f>=d;--f)s.point(_[f],v[f]);s.lineEnd(),s.areaEnd()}}h&&(_[u]=+e(m,u,l),v[u]=+t(m,u,l),s.point(r?+r(m,u,l):_[u],n?+n(m,u,l):v[u]))}if(g)return s=null,g+``||null}function u(){return ID().defined(i).curve(o).context(a)}return l.x=function(t){return arguments.length?(e=typeof t==`function`?t:SD(+t),r=null,l):e},l.x0=function(t){return arguments.length?(e=typeof t==`function`?t:SD(+t),l):e},l.x1=function(e){return arguments.length?(r=e==null?null:typeof e==`function`?e:SD(+e),l):r},l.y=function(e){return arguments.length?(t=typeof e==`function`?e:SD(+e),n=null,l):t},l.y0=function(e){return arguments.length?(t=typeof e==`function`?e:SD(+e),l):t},l.y1=function(e){return arguments.length?(n=e==null?null:typeof e==`function`?e:SD(+e),l):n},l.lineX0=l.lineY0=function(){return u().x(e).y(t)},l.lineY1=function(){return u().x(e).y(n)},l.lineX1=function(){return u().x(r).y(t)},l.defined=function(e){return arguments.length?(i=typeof e==`function`?e:SD(!!e),l):i},l.curve=function(e){return arguments.length?(o=e,a!=null&&(s=o(a)),l):o},l.context=function(e){return arguments.length?(e==null?a=s=null:s=o(a=e),l):a},l}var RD=class{constructor(e,t){this._context=e,this._x=t}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._x?this._context.bezierCurveTo(this._x0=(this._x0+e)/2,this._y0,this._x0,t,e,t):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+t)/2,e,this._y0,e,t)}this._x0=e,this._y0=t}};function zD(e){return new RD(e,!0)}function BD(e){return new RD(e,!1)}function VD(){}function HD(e,t,n){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+n)/6)}function UD(e){this._context=e}UD.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:HD(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1)}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:HD(this,e,t)}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function WD(e){return new UD(e)}function GD(e){this._context=e}GD.prototype={areaStart:VD,areaEnd:VD,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:this._context.moveTo(this._x2,this._y2),this._context.closePath();break;case 2:this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break;case 3:this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4)}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:HD(this,e,t)}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function KD(e){return new GD(e)}function qD(e){this._context=e}qD.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+e)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:HD(this,e,t)}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function JD(e){return new qD(e)}function YD(e){this._context=e}YD.prototype={areaStart:VD,areaEnd:VD,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function XD(e){return new YD(e)}function ZD(e){return e<0?-1:1}function QD(e,t,n){var r=e._x1-e._x0,i=t-e._x1,a=(e._y1-e._y0)/(r||i<0&&-0),o=(n-e._y1)/(i||r<0&&-0),s=(a*i+o*r)/(r+i);return(ZD(a)+ZD(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(s))||0}function $D(e,t){var n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function eO(e,t,n){var r=e._x0,i=e._y0,a=e._x1,o=e._y1,s=(a-r)/3;e._context.bezierCurveTo(r+s,i+s*t,a-s,o-s*n,a,o)}function tO(e){this._context=e}tO.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:eO(this,this._t0,$D(this,this._t0))}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var n=NaN;if(e=+e,t=+t,e!==this._x1||t!==this._y1){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,eO(this,$D(this,n=QD(this,e,t)),n);break;default:eO(this,this._t0,n=QD(this,e,t))}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}}};function nO(e){this._context=new rO(e)}(nO.prototype=Object.create(tO.prototype)).point=function(e,t){tO.prototype.point.call(this,t,e)};function rO(e){this._context=e}rO.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,n,r,i,a){this._context.bezierCurveTo(t,e,r,n,a,i)}};function iO(e){return new tO(e)}function aO(e){return new nO(e)}function oO(e){this._context=e}oO.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,n=e.length;if(n){if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),n===2)this._context.lineTo(e[1],t[1]);else for(var r=sO(e),i=sO(t),a=0,o=1;o<n;++a,++o)this._context.bezierCurveTo(r[0][a],i[0][a],r[1][a],i[1][a],e[o],t[o])}(this._line||this._line!==0&&n===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(e,t){this._x.push(+e),this._y.push(+t)}};function sO(e){var t,n=e.length-1,r,i=Array(n),a=Array(n),o=Array(n);for(i[0]=0,a[0]=2,o[0]=e[0]+2*e[1],t=1;t<n-1;++t)i[t]=1,a[t]=4,o[t]=4*e[t]+2*e[t+1];for(i[n-1]=2,a[n-1]=7,o[n-1]=8*e[n-1]+e[n],t=1;t<n;++t)r=i[t]/a[t-1],a[t]-=r,o[t]-=r*o[t-1];for(i[n-1]=o[n-1]/a[n-1],t=n-2;t>=0;--t)i[t]=(o[t]-i[t+1])/a[t];for(a[n-1]=(e[n]+i[n-1])/2,t=0;t<n-1;++t)a[t]=2*e[t+1]-i[t+1];return[i,a]}function zie(e){return new oO(e)}function cO(e,t){this._context=e,this._t=t}cO.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}}this._x=e,this._y=t}};function Bie(e){return new cO(e,.5)}function Vie(e){return new cO(e,0)}function Hie(e){return new cO(e,1)}function lO(e,t){if((o=e.length)>1)for(var n=1,r,i,a=e[t[0]],o,s=a.length;n<o;++n)for(i=a,a=e[t[n]],r=0;r<s;++r)a[r][1]+=a[r][0]=isNaN(i[r][1])?i[r][0]:i[r][1]}function uO(e){for(var t=e.length,n=Array(t);--t>=0;)n[t]=t;return n}function Uie(e,t){return e[t]}function Wie(e){let t=[];return t.key=e,t}function Gie(){var e=SD([]),t=uO,n=lO,r=Uie;function i(i){var a=Array.from(e.apply(this,arguments),Wie),o,s=a.length,c=-1,l;for(let e of i)for(o=0,++c;o<s;++o)(a[o][c]=[0,+r(e,a[o].key,c,i)]).data=e;for(o=0,l=jD(t(a));o<s;++o)a[l[o]].index=o;return n(a,l),a}return i.keys=function(t){return arguments.length?(e=typeof t==`function`?t:SD(Array.from(t)),i):e},i.value=function(e){return arguments.length?(r=typeof e==`function`?e:SD(+e),i):r},i.order=function(e){return arguments.length?(t=e==null?uO:typeof e==`function`?e:SD(Array.from(e)),i):t},i.offset=function(e){return arguments.length?(n=e??lO,i):n},i}function Kie(e,t){if((r=e.length)>0){for(var n,r,i=0,a=e[0].length,o;i<a;++i){for(o=n=0;n<r;++n)o+=e[n][i][1]||0;if(o)for(n=0;n<r;++n)e[n][i][1]/=o}lO(e,t)}}function qie(e,t){if((i=e.length)>0){for(var n=0,r=e[t[0]],i,a=r.length;n<a;++n){for(var o=0,s=0;o<i;++o)s+=e[o][n][1]||0;r[n][1]+=r[n][0]=-s/2}lO(e,t)}}function Jie(e,t){if((o=e.length)>0&&(a=(i=e[t[0]]).length)>0){for(var n=0,r=1,i,a,o;r<a;++r){for(var s=0,c=0,l=0;s<o;++s){for(var u=e[t[s]],d=u[r][1]||0,f=(d-(u[r-1][1]||0))/2,p=0;p<s;++p){var m=e[t[p]],h=m[r][1]||0,g=m[r-1][1]||0;f+=h-g}c+=d,l+=f*d}i[r-1][1]+=i[r-1][0]=n,c&&(n-=l/c)}i[r-1][1]+=i[r-1][0]=n,lO(e,t)}}var dO=e=>`radius`in e&&`startAngle`in e&&`endAngle`in e,fO=(e,t)=>{if(!e||typeof e==`function`||typeof e==`boolean`)return null;var n=e;if((0,o.isValidElement)(e)&&(n=e.props),typeof n!=`object`&&typeof n!=`function`)return null;var r={};return Object.keys(n).forEach(e=>{xE(e)&&typeof n[e]==`function`&&(r[e]=t||(t=>n[e](n,t)))}),r},Yie=(e,t,n)=>r=>(e(t,n,r),null),pO=(e,t,n)=>{if(e===null||typeof e!=`object`&&typeof e!=`function`)return null;var r=null;return Object.keys(e).forEach(i=>{var a=e[i];xE(i)&&typeof a==`function`&&(r||={},r[i]=Yie(a,t,n))}),r};function mO(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Xie(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?mO(Object(n),!0).forEach(function(t){Zie(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):mO(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Zie(e,t,n){return(t=Qie(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Qie(e){var t=$ie(e,`string`);return typeof t==`symbol`?t:t+``}function $ie(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function hO(e,t){var n=Xie({},e),r=t;return Object.keys(t).reduce((e,t)=>(e[t]===void 0&&r[t]!==void 0&&(e[t]=r[t]),e),n)}function eae(e,t){let n=new Map;for(let r=0;r<e.length;r++){let i=e[r],a=t(i,r,e);n.has(a)||n.set(a,i)}return Array.from(n.values())}function tae(e,t){return function(...n){return e.apply(this,n.slice(0,t))}}function gO(e){return e}function nae(e){return Number.isSafeInteger(e)&&e>=0}function _O(e){return e!=null&&typeof e!=`function`&&nae(e.length)}function rae(e){return function(t){return qE(t,e)}}function vO(e){return e==null||typeof e!=`object`&&typeof e!=`function`}function iae(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function yO(e){return Object.getOwnPropertySymbols(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}function bO(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}var xO=`[object RegExp]`,SO=`[object String]`,CO=`[object Number]`,wO=`[object Boolean]`,TO=`[object Arguments]`,EO=`[object Symbol]`,DO=`[object Date]`,OO=`[object Map]`,kO=`[object Set]`,AO=`[object Array]`,aae=`[object Function]`,jO=`[object ArrayBuffer]`,MO=`[object Object]`,oae=`[object Error]`,NO=`[object DataView]`,PO=`[object Uint8Array]`,FO=`[object Uint8ClampedArray]`,IO=`[object Uint16Array]`,LO=`[object Uint32Array]`,sae=`[object BigUint64Array]`,RO=`[object Int8Array]`,zO=`[object Int16Array]`,BO=`[object Int32Array]`,cae=`[object BigInt64Array]`,VO=`[object Float32Array]`,HO=`[object Float64Array]`,UO=typeof globalThis==`object`&&globalThis||typeof window==`object`&&window||typeof self==`object`&&self||typeof global==`object`&&global||(function(){return this})();function WO(e){return UO.Buffer!==void 0&&UO.Buffer.isBuffer(e)}function lae(e,t){return GO(e,void 0,e,new Map,t)}function GO(e,t,n,r=new Map,i=void 0){let a=i?.(e,t,n,r);if(a!==void 0)return a;if(vO(e))return e;if(r.has(e))return r.get(e);if(Array.isArray(e)){let t=Array(e.length);r.set(e,t);for(let a=0;a<e.length;a++)t[a]=GO(e[a],a,n,r,i);return Object.hasOwn(e,`index`)&&(t.index=e.index),Object.hasOwn(e,`input`)&&(t.input=e.input),t}if(e instanceof Date)return new Date(e.getTime());if(e instanceof RegExp){let t=new RegExp(e.source,e.flags);return t.lastIndex=e.lastIndex,t}if(e instanceof Map){let t=new Map;r.set(e,t);for(let[a,o]of e)t.set(a,GO(o,a,n,r,i));return t}if(e instanceof Set){let t=new Set;r.set(e,t);for(let a of e)t.add(GO(a,void 0,n,r,i));return t}if(WO(e))return e.subarray();if(iae(e)){let t=new(Object.getPrototypeOf(e)).constructor(e.length);r.set(e,t);for(let a=0;a<e.length;a++)t[a]=GO(e[a],a,n,r,i);return t}if(e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer)return e.slice(0);if(e instanceof DataView){let t=new DataView(e.buffer.slice(0),e.byteOffset,e.byteLength);return r.set(e,t),KO(t,e,n,r,i),t}if(typeof File<`u`&&e instanceof File){let t=new File([e],e.name,{type:e.type});return r.set(e,t),KO(t,e,n,r,i),t}if(typeof Blob<`u`&&e instanceof Blob){let t=new Blob([e],{type:e.type});return r.set(e,t),KO(t,e,n,r,i),t}if(e instanceof Error){let t=structuredClone(e);return r.set(e,t),t.message=e.message,t.name=e.name,t.stack=e.stack,t.cause=e.cause,t.constructor=e.constructor,KO(t,e,n,r,i),t}if(e instanceof Boolean){let t=new Boolean(e.valueOf());return r.set(e,t),KO(t,e,n,r,i),t}if(e instanceof Number){let t=new Number(e.valueOf());return r.set(e,t),KO(t,e,n,r,i),t}if(e instanceof String){let t=new String(e.valueOf());return r.set(e,t),KO(t,e,n,r,i),t}if(typeof e==`object`&&uae(e)){let t=Object.create(Object.getPrototypeOf(e));return r.set(e,t),KO(t,e,n,r,i),t}return e}function KO(e,t,n=e,r,i){let a=[...Object.keys(t),...yO(t)];for(let o=0;o<a.length;o++){let s=a[o],c=Object.getOwnPropertyDescriptor(e,s);(c==null||c.writable)&&(e[s]=GO(t[s],s,n,r,i))}}function uae(e){switch(bO(e)){case TO:case AO:case jO:case NO:case wO:case DO:case VO:case HO:case RO:case zO:case BO:case OO:case CO:case MO:case xO:case kO:case SO:case EO:case PO:case FO:case IO:case LO:return!0;default:return!1}}function dae(e){return GO(e,void 0,e,new Map,void 0)}function qO(e,t){return e===t||Number.isNaN(e)&&Number.isNaN(t)}function JO(e){return e!==null&&(typeof e==`object`||typeof e==`function`)}function YO(e,t,n){return typeof n==`function`?XO(e,t,function e(t,r,i,a,o,s){let c=n(t,r,i,a,o,s);return c===void 0?XO(t,r,e,s,!1):!!c},new Map,!0):YO(e,t,()=>void 0)}function XO(e,t,n,r,i=!1){if(t===e)return!0;switch(typeof t){case`object`:return fae(e,t,n,r,i);case`function`:return Object.keys(t).length>0?XO(e,{...t},n,r,i):qO(e,t);default:return JO(e)&&i?typeof t!=`string`||t===``:qO(e,t)}}function fae(e,t,n,r,i=!1){if(t==null)return!0;if(Array.isArray(t))return ZO(e,t,n,r);if(t instanceof Map)return pae(e,t,n,r);if(t instanceof Set)return mae(e,t,n,r);let a=Object.keys(t);if(e==null)return i&&a.length===0;if(i)vO(e)&&(e=Object(e));else{let t=bO(e);if(t!==`[object Object]`&&t!==`[object Arguments]`)return!1}if(a.length===0)return!0;if(r?.has(t))return r.get(t)===e;r?.set(t,e);try{for(let i=0;i<a.length;i++){let o=a[i];if(!(o in e)||t[o]===void 0&&e[o]!==void 0||t[o]===null&&e[o]!==null||!n(e[o],t[o],o,e,t,r))return!1}return!0}finally{r?.delete(t)}}function pae(e,t,n,r){if(t.size===0)return!0;if(!(e instanceof Map))return!1;for(let[i,a]of t.entries())if(n(e.get(i),a,i,e,t,r)===!1)return!1;return!0}function ZO(e,t,n,r){if(t.length===0)return!0;if(!Array.isArray(e))return!1;let i=new Set;for(let a=0;a<t.length;a++){let o=t[a],s=!1;for(let c=0;c<e.length;c++){if(i.has(c))continue;let l=e[c],u=!1;if(n(l,o,a,e,t,r)&&(u=!0),u){i.add(c),s=!0;break}}if(!s)return!1}return!0}function mae(e,t,n,r){return t.size===0||e instanceof Set&&ZO([...e],[...t],n,r)}function QO(e,t){return YO(e,t,()=>void 0)}function hae(e){return e=dae(e),t=>QO(t,e)}function gae(e,t){return lae(e,(n,r,i,a)=>{let o=t?.(n,r,i,a);if(o!==void 0)return o;if(typeof e==`object`){if(bO(e)===`[object Object]`&&typeof e.constructor!=`function`){let t={};return a.set(e,t),KO(t,e,i,a),t}switch(Object.prototype.toString.call(e)){case CO:case SO:case wO:{let t=new e.constructor(e?.valueOf());return KO(t,e),t}case TO:{let t={};return KO(t,e),t.length=e.length,t[Symbol.iterator]=e[Symbol.iterator],t}default:return}}})}function _ae(e){return gae(e)}var vae=/^(?:0|[1-9]\d*)$/;function $O(e,t=2**53-1){switch(typeof e){case`number`:return Number.isInteger(e)&&e>=0&&e<t;case`symbol`:return!1;case`string`:return vae.test(e)}}function yae(e){return typeof e==`object`&&!!e&&bO(e)===`[object Arguments]`}function bae(e,t){let n;if(n=Array.isArray(t)?t:typeof t==`string`&&VE(t)&&!(t in Object(e))?KE(t):[t],n.length===0)return!1;let r=e;for(let e=0;e<n.length;e++){let t=HE(n[e]);if((r==null||!Object.hasOwn(r,t))&&!((Array.isArray(r)||yae(r))&&$O(t)&&Number(t)<r.length))return!1;r=r[t]}return!0}function xae(e,t){switch(typeof e){case`object`:Object.is(e?.valueOf(),-0)&&(e=`-0`);break;case`number`:e=HE(e)}return t=_ae(t),function(n){let r=qE(n,e);return r===void 0?bae(n,e):t===void 0?r===void 0:QO(r,t)}}function Sae(e){if(e==null)return gO;switch(typeof e){case`function`:return e;case`object`:return Array.isArray(e)&&e.length===2?xae(e[0],e[1]):hae(e);default:return rae(e)}}function Cae(e){return e===0?0:e}function ek(e,t=gO){return _O(e)?eae(Array.from(e),tae(Sae(t),1)).map(Cae):[]}function wae(e,t,n){return t===!0?ek(e,n):typeof t==`function`?ek(e,t):e}var Tae=n((e=>{var t=r();function n(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var i=typeof Object.is==`function`?Object.is:n,a=t.useState,o=t.useEffect,s=t.useLayoutEffect,c=t.useDebugValue;function l(e,t){var n=t(),r=a({inst:{value:n,getSnapshot:t}}),i=r[0].inst,l=r[1];return s(function(){i.value=n,i.getSnapshot=t,u(i)&&l({inst:i})},[e,n,t]),o(function(){return u(i)&&l({inst:i}),e(function(){u(i)&&l({inst:i})})},[e]),c(n),n}function u(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!i(e,n)}catch{return!0}}function d(e,t){return t()}var f=typeof window>`u`||window.document===void 0||window.document.createElement===void 0?d:l;e.useSyncExternalStore=t.useSyncExternalStore===void 0?f:t.useSyncExternalStore})),Eae=n(((e,t)=>{t.exports=Tae()})),Dae=n((e=>{var t=r(),n=Eae();function i(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var a=typeof Object.is==`function`?Object.is:i,o=n.useSyncExternalStore,s=t.useRef,c=t.useEffect,l=t.useMemo,u=t.useDebugValue;e.useSyncExternalStoreWithSelector=function(e,t,n,r,i){var d=s(null);if(d.current===null){var f={hasValue:!1,value:null};d.current=f}else f=d.current;d=l(function(){function e(e){if(!o){if(o=!0,s=e,e=r(e),i!==void 0&&f.hasValue){var t=f.value;if(i(t,e))return c=t}return c=e}if(t=c,a(s,e))return t;var n=r(e);return i!==void 0&&i(t,n)?(s=e,t):(s=e,c=n)}var o=!1,s,c,l=n===void 0?null:n;return[function(){return e(t())},l===null?void 0:function(){return e(l())}]},[t,n,r,i]);var p=o(e,d[0],d[1]);return c(function(){f.hasValue=!0,f.value=p},[p]),u(p),p}})),tk=n(((e,t)=>{t.exports=Dae()}))(),nk=(0,o.createContext)(null),Oae=e=>e,rk=()=>{var e=(0,o.useContext)(nk);return e?e.store.dispatch:Oae},ik=()=>{},kae=()=>ik,Aae=(e,t)=>e===t;function X(e){var t=(0,o.useContext)(nk),n=(0,o.useMemo)(()=>t?t=>{if(t!=null)return e(t)}:ik,[t,e]);return(0,tk.useSyncExternalStoreWithSelector)(t?t.subscription.addNestedSub:kae,t?t.store.getState:ik,t?t.store.getState:ik,n,Aae)}function jae(e,t=`expected a function, instead received ${typeof e}`){if(typeof e!=`function`)throw TypeError(t)}function Mae(e,t=`expected all items to be functions, instead received the following types: `){if(!e.every(e=>typeof e==`function`)){let n=e.map(e=>typeof e==`function`?`function ${e.name||`unnamed`}()`:typeof e).join(`, `);throw TypeError(`${t}[${n}]`)}}var ak=e=>Array.isArray(e)?e:[e];function Nae(e){let t=Array.isArray(e[0])?e[0]:e;return Mae(t,`createSelector expects all input-selectors to be functions, but received the following types: `),t}function Pae(e,t){let n=[],{length:r}=e;for(let i=0;i<r;i++)n.push(e[i].apply(null,t));return n}var Fae=class{constructor(e){this.value=e}deref(){return this.value}},ok=typeof WeakRef>`u`?Fae:WeakRef,Iae=0,sk=1;function ck(){return{s:Iae,v:void 0,o:null,p:null}}function Lae(e){return e instanceof ok?e.deref():e}function lk(e,t={}){let n=ck(),{resultEqualityCheck:r}=t,i,a=0;function o(){let t=n,{length:o}=arguments;for(let e=0,n=o;e<n;e++){let n=arguments[e];if(typeof n==`function`||typeof n==`object`&&n){let e=t.o;e===null&&(t.o=e=new WeakMap);let r=e.get(n);r===void 0?(t=ck(),e.set(n,t)):t=r}else{let e=t.p;e===null&&(t.p=e=new Map);let r=e.get(n);r===void 0?(t=ck(),e.set(n,t)):t=r}}let s=t,c;if(t.s===sk)c=t.v;else if(c=e.apply(null,arguments),a++,r){let e=Lae(i);e!=null&&r(e,c)&&(c=e,a!==0&&a--),i=typeof c==`object`&&c||typeof c==`function`?new ok(c):c}return s.s=sk,s.v=c,c}return o.clearCache=()=>{n=ck(),o.resetResultsCount()},o.resultsCount=()=>a,o.resetResultsCount=()=>{a=0},o}function Rae(e,...t){let n=typeof e==`function`?{memoize:e,memoizeOptions:t}:e,r=(...e)=>{let t=0,r=0,i,a={},o=e.pop();typeof o==`object`&&(a=o,o=e.pop()),jae(o,`createSelector expects an output function after the inputs, but received: [${typeof o}]`);let{memoize:s,memoizeOptions:c=[],argsMemoize:l=lk,argsMemoizeOptions:u=[]}={...n,...a},d=ak(c),f=ak(u),p=Nae(e),m=s(function(){return t++,o.apply(null,arguments)},...d),h=l(function(){r++;let e=Pae(p,arguments);return i=m.apply(null,e),i},...f);return Object.assign(h,{resultFunc:o,memoizedResultFunc:m,dependencies:p,dependencyRecomputations:()=>r,resetDependencyRecomputations:()=>{r=0},lastResult:()=>i,recomputations:()=>t,resetRecomputations:()=>{t=0},memoize:s,argsMemoize:l})};return Object.assign(r,{withTypes:()=>r}),r}var Z=Rae(lk);function zae(e,t=1){let n=[],r=Math.floor(t),i=(e,t)=>{for(let a=0;a<e.length;a++){let o=e[a];Array.isArray(o)&&t<r?i(o,t+1):n.push(o)}};return i(e,0),n}function uk(e,t,n){return JO(n)&&(typeof t==`number`&&_O(n)&&$O(t)&&t<n.length||typeof t==`string`&&t in n)?qO(n[t],e):!1}function dk(e){return typeof e==`symbol`?1:e===null?2:e===void 0?3:e===e?0:4}var Bae=(e,t,n)=>{if(e!==t){let r=dk(e),i=dk(t);if(r===i&&r===0){if(e<t)return n===`desc`?1:-1;if(e>t)return n===`desc`?-1:1}return n===`desc`?i-r:r-i}return 0},Vae=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Hae=/^\w*$/;function Uae(e,t){return Array.isArray(e)?!1:typeof e==`number`||typeof e==`boolean`||e==null||UE(e)?!0:typeof e==`string`&&(Hae.test(e)||!Vae.test(e))||t!=null&&Object.hasOwn(t,e)}function Wae(e,t,n,r){if(e==null)return[];n=r?void 0:n,Array.isArray(e)||(e=_O(e)?Array.from(e):Object.values(e)),Array.isArray(t)||(t=t==null?[null]:[t]),t.length===0&&(t=[null]),Array.isArray(n)||(n=n==null?[]:[n]),n=n.map(e=>String(e));let i=(e,t)=>{let n=e,r=0;for(;r<t.length&&n!=null;++r)n=n[t[r]];return r>0&&r===t.length?n:void 0},a=(e,t)=>{if(e==null)return t;if(t!=null)return typeof e==`object`&&`key`in e?Object.hasOwn(t,e.key)?t[e.key]:i(t,e.path):typeof e==`function`?e(t):Array.isArray(e)?i(t,e):t[e]},o=t.map(e=>(Array.isArray(e)&&e.length===1&&(e=e[0]),e==null||typeof e==`function`||Array.isArray(e)||Uae(e)?e:{key:e,path:KE(e)}));return e.map(e=>({original:e,criteria:o.map(t=>a(t,e))})).slice().sort((e,t)=>{for(let r=0;r<o.length;r++){let i=Bae(e.criteria[r],t.criteria[r],n[r]);if(i!==0)return i}return 0}).map(e=>e.original)}function fk(e,...t){let n=t.length;return n>1&&uk(e,t[0],t[1])?t=[]:n>2&&uk(t[0],t[1],t[2])&&(t=[t[0]]),Wae(e,zae(t),[`asc`])}var pk=e=>e.legend.settings,Gae=e=>e.legend.size;Z([e=>e.legend.payload,pk],(e,t)=>{var n=t.itemSorter,r=e.flat(1);return n?fk(r,n):r});function Kae(e,t){return Xae(e)||Yae(e,t)||Jae(e,t)||qae()}function qae(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
14
14
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Jae(e,t){if(e){if(typeof e==`string`)return mk(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?mk(e,t):void 0}}function mk(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Yae(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function Xae(e){if(Array.isArray(e))return e}var hk=1;function gk(e,t){return Math.abs(e.height-t.height)>hk||Math.abs(e.left-t.left)>hk||Math.abs(e.top-t.top)>hk||Math.abs(e.width-t.width)>hk}function _k(e){var t=e.getBoundingClientRect();return{height:t.height,left:t.left,top:t.top,width:t.width}}function Zae(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:[],t=Kae((0,o.useState)({height:0,left:0,top:0,width:0}),2),n=t[0],r=t[1],i=(0,o.useRef)(null),a=(0,o.useRef)(n);a.current=n;var s=(0,o.useCallback)(e=>{if(i.current!=null&&(i.current.disconnect(),i.current=null),e!=null){var t=_k(e);if(gk(t,a.current)&&r(t),typeof ResizeObserver<`u`){var n=new ResizeObserver(()=>{var t=_k(e);gk(t,a.current)&&r(t)});n.observe(e),i.current=n}}},[...e]);return(0,o.useEffect)(()=>()=>{var e;(e=i.current)==null||e.disconnect()},[]),[n,s]}function vk(e){return`Minified Redux error #${e}; visit https://redux.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var yk=typeof Symbol==`function`&&Symbol.observable||`@@observable`,bk=()=>Math.random().toString(36).substring(7).split(``).join(`.`),xk={INIT:`@@redux/INIT${bk()}`,REPLACE:`@@redux/REPLACE${bk()}`,PROBE_UNKNOWN_ACTION:()=>`@@redux/PROBE_UNKNOWN_ACTION${bk()}`};function Sk(e){if(typeof e!=`object`||!e)return!1;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t||Object.getPrototypeOf(e)===null}function Ck(e,t,n){if(typeof e!=`function`)throw Error(vk(2));if(typeof t==`function`&&typeof n==`function`||typeof n==`function`&&typeof arguments[3]==`function`)throw Error(vk(0));if(typeof t==`function`&&n===void 0&&(n=t,t=void 0),n!==void 0){if(typeof n!=`function`)throw Error(vk(1));return n(Ck)(e,t)}let r=e,i=t,a=new Map,o=a,s=0,c=!1;function l(){o===a&&(o=new Map,a.forEach((e,t)=>{o.set(t,e)}))}function u(){if(c)throw Error(vk(3));return i}function d(e){if(typeof e!=`function`)throw Error(vk(4));if(c)throw Error(vk(5));let t=!0;l();let n=s++;return o.set(n,e),function(){if(t){if(c)throw Error(vk(6));t=!1,l(),o.delete(n),a=null}}}function f(e){if(!Sk(e))throw Error(vk(7));if(e.type===void 0)throw Error(vk(8));if(typeof e.type!=`string`)throw Error(vk(17));if(c)throw Error(vk(9));try{c=!0,i=r(i,e)}finally{c=!1}return(a=o).forEach(e=>{e()}),e}function p(e){if(typeof e!=`function`)throw Error(vk(10));r=e,f({type:xk.REPLACE})}function m(){let e=d;return{subscribe(t){if(typeof t!=`object`||!t)throw Error(vk(11));function n(){let e=t;e.next&&e.next(u())}return n(),{unsubscribe:e(n)}},[yk](){return this}}}return f({type:xk.INIT}),{dispatch:f,subscribe:d,getState:u,replaceReducer:p,[yk]:m}}function Qae(e){Object.keys(e).forEach(t=>{let n=e[t];if(n(void 0,{type:xk.INIT})===void 0)throw Error(vk(12));if(n(void 0,{type:xk.PROBE_UNKNOWN_ACTION()})===void 0)throw Error(vk(13))})}function wk(e){let t=Object.keys(e),n={};for(let r=0;r<t.length;r++){let i=t[r];typeof e[i]==`function`&&(n[i]=e[i])}let r=Object.keys(n),i;try{Qae(n)}catch(e){i=e}return function(e={},t){if(i)throw i;let a=!1,o={};for(let i=0;i<r.length;i++){let s=r[i],c=n[s],l=e[s],u=c(l,t);if(u===void 0)throw t&&t.type,Error(vk(14));o[s]=u,a||=u!==l}return a||=r.length!==Object.keys(e).length,a?o:e}}function Tk(...e){return e.length===0?e=>e:e.length===1?e[0]:e.reduce((e,t)=>(...n)=>e(t(...n)))}function $ae(...e){return t=>(n,r)=>{let i=t(n,r),a=()=>{throw Error(vk(15))},o={getState:i.getState,dispatch:(e,...t)=>a(e,...t)};return a=Tk(...e.map(e=>e(o)))(i.dispatch),{...i,dispatch:a}}}function Ek(e){return Sk(e)&&`type`in e&&typeof e.type==`string`}var Dk=Symbol.for(`immer-nothing`),Ok=Symbol.for(`immer-draftable`),kk=Symbol.for(`immer-state`);function Ak(e,...t){throw Error(`[Immer] minified error nr: ${e}. Full error at: https://bit.ly/3cXEKWf`)}var jk=Object,Mk=jk.getPrototypeOf,Nk=`constructor`,Pk=`prototype`,Fk=`configurable`,Ik=`enumerable`,Lk=`writable`,Rk=`value`,zk=e=>!!e&&!!e[kk];function Bk(e){return e?Hk(e)||Jk(e)||!!e[Ok]||!!e[Nk]?.[Ok]||Yk(e)||Xk(e):!1}var eoe=jk[Pk][Nk].toString(),Vk=new WeakMap;function Hk(e){if(!e||!Zk(e))return!1;let t=Mk(e);if(t===null||t===jk[Pk])return!0;let n=jk.hasOwnProperty.call(t,Nk)&&t[Nk];if(n===Object)return!0;if(!Qk(n))return!1;let r=Vk.get(n);return r===void 0&&(r=Function.toString.call(n),Vk.set(n,r)),r===eoe}function Uk(e,t,n=!0){Wk(e)===0?(n?Reflect.ownKeys(e):jk.keys(e)).forEach(n=>{t(n,e[n],e)}):e.forEach((n,r)=>t(r,n,e))}function Wk(e){let t=e[kk];return t?t.type_:Jk(e)?1:Yk(e)?2:Xk(e)?3:0}var Gk=(e,t,n=Wk(e))=>n===2?e.has(t):jk[Pk].hasOwnProperty.call(e,t),Kk=(e,t,n=Wk(e))=>n===2?e.get(t):e[t],qk=(e,t,n,r=Wk(e))=>{r===2?e.set(t,n):r===3?e.add(n):e[t]=n};function toe(e,t){return e===t?e!==0||1/e==1/t:e!==e&&t!==t}var Jk=Array.isArray,Yk=e=>e instanceof Map,Xk=e=>e instanceof Set,Zk=e=>typeof e==`object`,Qk=e=>typeof e==`function`,$k=e=>typeof e==`boolean`;function noe(e){let t=+e;return Number.isInteger(t)&&String(t)===e}var eA=e=>e.copy_||e.base_,tA=e=>e.modified_?e.copy_:e.base_;function nA(e,t){if(Yk(e))return new Map(e);if(Xk(e))return new Set(e);if(Jk(e))return Array[Pk].slice.call(e);let n=Hk(e);if(t===!0||t===`class_only`&&!n){let t=jk.getOwnPropertyDescriptors(e);delete t[kk];let n=Reflect.ownKeys(t);for(let r=0;r<n.length;r++){let i=n[r],a=t[i];a[Lk]===!1&&(a[Lk]=!0,a[Fk]=!0),(a.get||a.set)&&(t[i]={[Fk]:!0,[Lk]:!0,[Ik]:a[Ik],[Rk]:e[i]})}return jk.create(Mk(e),t)}{let t=Mk(e);if(t!==null&&n)return{...e};let r=jk.create(t);return jk.assign(r,e)}}function rA(e,t=!1){return aA(e)||zk(e)||!Bk(e)?e:(Wk(e)>1&&jk.defineProperties(e,{set:iA,add:iA,clear:iA,delete:iA}),jk.freeze(e),t&&Uk(e,(e,t)=>{rA(t,!0)},!1),e)}function roe(){Ak(2)}var iA={[Rk]:roe};function aA(e){return e===null||!Zk(e)||jk.isFrozen(e)}var oA=`MapSet`,sA=`Patches`,cA=`ArrayMethods`,lA={};function uA(e){let t=lA[e];return t||Ak(0,e),t}var dA=e=>!!lA[e],fA,pA=()=>fA,ioe=(e,t)=>({drafts_:[],parent_:e,immer_:t,canAutoFreeze_:!0,unfinalizedDrafts_:0,handledSet_:new Set,processedForPatches_:new Set,mapSetPlugin_:dA(oA)?uA(oA):void 0,arrayMethodsPlugin_:dA(cA)?uA(cA):void 0});function mA(e,t){t&&(e.patchPlugin_=uA(sA),e.patches_=[],e.inversePatches_=[],e.patchListener_=t)}function hA(e){gA(e),e.drafts_.forEach(aoe),e.drafts_=null}function gA(e){e===fA&&(fA=e.parent_)}var _A=e=>fA=ioe(fA,e);function aoe(e){let t=e[kk];t.type_===0||t.type_===1?t.revoke_():t.revoked_=!0}function vA(e,t){t.unfinalizedDrafts_=t.drafts_.length;let n=t.drafts_[0];if(e!==void 0&&e!==n){n[kk].modified_&&(hA(t),Ak(4)),Bk(e)&&(e=yA(t,e));let{patchPlugin_:r}=t;r&&r.generateReplacementPatches_(n[kk].base_,e,t)}else e=yA(t,n);return ooe(t,e,!0),hA(t),t.patches_&&t.patchListener_(t.patches_,t.inversePatches_),e===Dk?void 0:e}function yA(e,t){if(aA(t))return t;let n=t[kk];if(!n)return wA(t,e.handledSet_,e);if(!xA(n,e))return t;if(!n.modified_)return n.base_;if(!n.finalized_){let{callbacks_:t}=n;if(t)for(;t.length>0;)t.pop()(e);CA(n,e)}return n.copy_}function ooe(e,t,n=!1){!e.parent_&&e.immer_.autoFreeze_&&e.canAutoFreeze_&&rA(t,n)}function bA(e){e.finalized_=!0,e.scope_.unfinalizedDrafts_--}var xA=(e,t)=>e.scope_===t,soe=[];function SA(e,t,n,r){let i=eA(e),a=e.type_;if(r!==void 0&&Kk(i,r,a)===t){qk(i,r,n,a);return}if(!e.draftLocations_){let t=e.draftLocations_=new Map;Uk(i,(e,n)=>{if(zk(n)){let r=t.get(n)||[];r.push(e),t.set(n,r)}})}let o=e.draftLocations_.get(t)??soe;for(let e of o)qk(i,e,n,a)}function coe(e,t,n){e.callbacks_.push(function(r){let i=t;if(!i||!xA(i,r))return;r.mapSetPlugin_?.fixSetContents(i);let a=tA(i);SA(e,i.draft_??i,a,n),CA(i,r)})}function CA(e,t){if(e.modified_&&!e.finalized_&&(e.type_===3||e.type_===1&&e.allIndicesReassigned_||(e.assigned_?.size??0)>0)){let{patchPlugin_:n}=t;if(n){let r=n.getPath(e);r&&n.generatePatches_(e,r,t)}bA(e)}}function loe(e,t,n){let{scope_:r}=e;if(zk(n)){let i=n[kk];xA(i,r)&&i.callbacks_.push(function(){AA(e),SA(e,n,tA(i),t)})}else Bk(n)&&e.callbacks_.push(function(){let i=eA(e);e.type_===3?i.has(n)&&wA(n,r.handledSet_,r):Kk(i,t,e.type_)===n&&r.drafts_.length>1&&(e.assigned_.get(t)??!1)===!0&&e.copy_&&wA(Kk(e.copy_,t,e.type_),r.handledSet_,r)})}function wA(e,t,n){return!n.immer_.autoFreeze_&&n.unfinalizedDrafts_<1||zk(e)||t.has(e)||!Bk(e)||aA(e)?e:(t.add(e),Uk(e,(r,i)=>{if(zk(i)){let t=i[kk];xA(t,n)&&(qk(e,r,tA(t),e.type_),bA(t))}else Bk(i)&&wA(i,t,n)}),e)}function uoe(e,t){let n=Jk(e),r={type_:+!!n,scope_:t?t.scope_:pA(),modified_:!1,finalized_:!1,assigned_:void 0,parent_:t,base_:e,draft_:null,copy_:null,revoke_:null,isManual_:!1,callbacks_:void 0},i=r,a=TA;n&&(i=[r],a=EA);let{revoke:o,proxy:s}=Proxy.revocable(i,a);return r.draft_=s,r.revoke_=o,[s,r]}var TA={get(e,t){if(t===kk)return e;let n=e.scope_.arrayMethodsPlugin_,r=e.type_===1&&typeof t==`string`;if(r&&n?.isArrayOperationMethod(t))return n.createMethodInterceptor(e,t);let i=eA(e);if(!Gk(i,t,e.type_))return foe(e,i,t);let a=i[t];if(e.finalized_||!Bk(a)||r&&e.operationMethod&&n?.isMutatingArrayMethod(e.operationMethod)&&noe(t))return a;if(a===DA(e.base_,t)||doe(e,t,a)){AA(e);let n=e.type_===1?+t:t,r=jA(e.scope_,a,e,n);return e.copy_[n]=r}return a},has(e,t){return t in eA(e)},ownKeys(e){return Reflect.ownKeys(eA(e))},set(e,t,n){let r=OA(eA(e),t);if(r?.set)return r.set.call(e.draft_,n),!0;if(!e.modified_){let r=DA(eA(e),t),i=r?.[kk];if(i&&i.base_===n)return e.copy_[t]=n,e.assigned_.delete(t),!0;if(toe(n,r)&&(n!==void 0||Gk(e.base_,t,e.type_)))return!0;AA(e),kA(e)}return e.copy_[t]===n&&(n!==void 0||Gk(e.copy_,t,e.type_))||Number.isNaN(n)&&Number.isNaN(e.copy_[t])?!0:(e.copy_[t]=n,e.assigned_.set(t,!0),loe(e,t,n),!0)},deleteProperty(e,t){return AA(e),DA(e.base_,t)!==void 0||t in e.base_?(e.assigned_.set(t,!1),kA(e)):e.assigned_.delete(t),e.copy_&&delete e.copy_[t],!0},getOwnPropertyDescriptor(e,t){let n=eA(e),r=Reflect.getOwnPropertyDescriptor(n,t);return r&&{[Lk]:!0,[Fk]:e.type_!==1||t!==`length`,[Ik]:r[Ik],[Rk]:n[t]}},defineProperty(){Ak(11)},getPrototypeOf(e){return Mk(e.base_)},setPrototypeOf(){Ak(12)}},EA={};for(let e in TA){let t=TA[e];EA[e]=function(){let e=arguments;return e[0]=e[0][0],t.apply(this,e)}}EA.deleteProperty=function(e,t){return EA.set.call(this,e,t,void 0)},EA.set=function(e,t,n){return TA.set.call(this,e[0],t,n,e[0])};function DA(e,t){let n=e[kk];return(n?eA(n):e)[t]}function doe(e,t,n){return e.type_!==1||!e.allIndicesReassigned_||e.assigned_?.get(t)||!Bk(n)||n[kk]?!1:e.baseRefs_.has(n)}function foe(e,t,n){let r=OA(t,n);return r?Rk in r?r[Rk]:r.get?.call(e.draft_):void 0}function OA(e,t){if(!(t in e))return;let n=Mk(e);for(;n;){let e=Object.getOwnPropertyDescriptor(n,t);if(e)return e;n=Mk(n)}}function kA(e){e.modified_||(e.modified_=!0,e.parent_&&kA(e.parent_))}function AA(e){e.copy_||=(e.assigned_=new Map,nA(e.base_,e.scope_.immer_.useStrictShallowCopy_))}var poe=class{constructor(e){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.useStrictIteration_=!1,this.produce=(e,t,n)=>{if(Qk(e)&&!Qk(t)){let n=t;t=e;let r=this;return function(e=n,...i){return r.produce(e,e=>t.call(this,e,...i))}}Qk(t)||Ak(6),n!==void 0&&!Qk(n)&&Ak(7);let r;if(Bk(e)){let i=_A(this),a=jA(i,e,void 0),o=!0;try{r=t(a),o=!1}finally{o?hA(i):gA(i)}return mA(i,n),vA(r,i)}if(!e||!Zk(e)){if(r=t(e),r===void 0&&(r=e),r===Dk&&(r=void 0),this.autoFreeze_&&rA(r,!0),n){let t=[],i=[];uA(sA).generateReplacementPatches_(e,r,{patches_:t,inversePatches_:i}),n(t,i)}return r}Ak(1,e)},this.produceWithPatches=(e,t)=>{if(Qk(e))return(t,...n)=>this.produceWithPatches(t,t=>e(t,...n));let n,r;return[this.produce(e,t,(e,t)=>{n=e,r=t}),n,r]},$k(e?.autoFreeze)&&this.setAutoFreeze(e.autoFreeze),$k(e?.useStrictShallowCopy)&&this.setUseStrictShallowCopy(e.useStrictShallowCopy),$k(e?.useStrictIteration)&&this.setUseStrictIteration(e.useStrictIteration)}createDraft(e){Bk(e)||Ak(8),zk(e)&&(e=MA(e));let t=_A(this),n=jA(t,e,void 0);return n[kk].isManual_=!0,gA(t),n}finishDraft(e,t){let n=e&&e[kk];(!n||!n.isManual_)&&Ak(9);let{scope_:r}=n;return mA(r,t),vA(void 0,r)}setAutoFreeze(e){this.autoFreeze_=e}setUseStrictShallowCopy(e){this.useStrictShallowCopy_=e}setUseStrictIteration(e){this.useStrictIteration_=e}shouldUseStrictIteration(){return this.useStrictIteration_}applyPatches(e,t){let n;for(n=t.length-1;n>=0;n--){let r=t[n];if(r.path.length===0&&r.op===`replace`){e=r.value;break}}n>-1&&(t=t.slice(n+1));let r=uA(sA).applyPatches_;return zk(e)?r(e,t):this.produce(e,e=>r(e,t))}};function jA(e,t,n,r){let[i,a]=Yk(t)?uA(oA).proxyMap_(t,n):Xk(t)?uA(oA).proxySet_(t,n):uoe(t,n);return(n?.scope_??pA()).drafts_.push(i),a.callbacks_=n?.callbacks_??[],a.key_=r,n&&r!==void 0?coe(n,a,r):a.callbacks_.push(function(e){e.mapSetPlugin_?.fixSetContents(a);let{patchPlugin_:t}=e;a.modified_&&t&&t.generatePatches_(a,[],e)}),i}function MA(e){return zk(e)||Ak(10,e),NA(e)}function NA(e){if(!Bk(e)||aA(e))return e;let t=e[kk],n,r=!0;if(t){if(!t.modified_)return t.base_;t.finalized_=!0,n=nA(e,t.scope_.immer_.useStrictShallowCopy_),r=t.scope_.immer_.shouldUseStrictIteration()}else n=nA(e,!0);return Uk(n,(e,t)=>{qk(n,e,NA(t))},r),t&&(t.finalized_=!1),n}globalThis.Iterator?.from;var PA=new poe().produce,FA=e=>e;function IA(e){return({dispatch:t,getState:n})=>r=>i=>typeof i==`function`?i(t,n,e):r(i)}var moe=IA(),hoe=IA,goe=typeof window<`u`&&window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__?window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__:function(){if(arguments.length!==0)return typeof arguments[0]==`object`?Tk:Tk.apply(null,arguments)};typeof window<`u`&&window.__REDUX_DEVTOOLS_EXTENSION__&&window.__REDUX_DEVTOOLS_EXTENSION__;function LA(e,t){function n(...n){if(t){let r=t(...n);if(!r)throw Error(vj(0));return{type:e,payload:r.payload,...`meta`in r&&{meta:r.meta},...`error`in r&&{error:r.error}}}return{type:e,payload:n[0]}}return n.toString=()=>`${e}`,n.type=e,n.match=t=>Ek(t)&&t.type===e,n}var RA=class e extends Array{constructor(...t){super(...t),Object.setPrototypeOf(this,e.prototype)}static get[Symbol.species](){return e}concat(...e){return super.concat.apply(this,e)}prepend(...t){return t.length===1&&Array.isArray(t[0])?new e(...t[0].concat(this)):new e(...t.concat(this))}};function zA(e){return Bk(e)?PA(e,()=>{}):e}function BA(e,t,n){return e.has(t)?e.get(t):e.set(t,n(t)).get(t)}function _oe(e){return typeof e==`boolean`}var voe=()=>function(e){let{thunk:t=!0,immutableCheck:n=!0,serializableCheck:r=!0,actionCreatorCheck:i=!0}=e??{},a=new RA;return t&&(_oe(t)?a.push(moe):a.push(hoe(t.extraArgument))),a},VA=`RTK_autoBatch`,HA=()=>e=>({payload:e,meta:{[VA]:!0}}),UA=e=>t=>{setTimeout(t,e)},yoe=(e,t)=>n=>{let r=!1,i,a,o=()=>{r||(r=!0,cancelAnimationFrame(i),clearTimeout(a),n())};i=e(o),a=setTimeout(o,t)},WA=(e={type:`raf`})=>t=>(...n)=>{let r=t(...n),i=!0,a=!1,o=!1,s=new Set,c=e.type===`tick`?queueMicrotask:e.type===`raf`?typeof window<`u`&&window.requestAnimationFrame?yoe(window.requestAnimationFrame,100):UA(10):e.type===`callback`?e.queueNotification:UA(e.timeout),l=()=>{o=!1,a&&(a=!1,s.forEach(e=>e()))};return Object.assign({},r,{subscribe(e){let t=r.subscribe(()=>i&&e());return s.add(e),()=>{t(),s.delete(e)}},dispatch(e){try{return i=!e?.meta?.[VA],a=!i,a&&(o||(o=!0,c(l))),r.dispatch(e)}finally{i=!0}}})},boe=e=>function(t){let{autoBatch:n=!0}=t??{},r=new RA(e);return n&&r.push(WA(typeof n==`object`?n:void 0)),r};function xoe(e){let t=voe(),{reducer:n=void 0,middleware:r,devTools:i=!0,duplicateMiddlewareCheck:a=!0,preloadedState:o=void 0,enhancers:s=void 0}=e||{},c;if(typeof n==`function`)c=n;else if(Sk(n))c=wk(n);else throw Error(vj(1));let l;l=typeof r==`function`?r(t):t();let u=Tk;i&&(u=goe({trace:!1,...typeof i==`object`&&i}));let d=boe($ae(...l)),f=typeof s==`function`?s(d):d(),p=u(...f);return Ck(c,o,p)}function GA(e){let t={},n=[],r,i={addCase(e,n){let r=typeof e==`string`?e:e.type;if(!r)throw Error(vj(28));if(r in t)throw Error(vj(29));return t[r]=n,i},addAsyncThunk(e,r){return r.pending&&(t[e.pending.type]=r.pending),r.rejected&&(t[e.rejected.type]=r.rejected),r.fulfilled&&(t[e.fulfilled.type]=r.fulfilled),r.settled&&n.push({matcher:e.settled,reducer:r.settled}),i},addMatcher(e,t){return n.push({matcher:e,reducer:t}),i},addDefaultCase(e){return r=e,i}};return e(i),[t,n,r]}function Soe(e){return typeof e==`function`}function Coe(e,t){let[n,r,i]=GA(t),a;if(Soe(e))a=()=>zA(e());else{let t=zA(e);a=()=>t}function o(e=a(),t){let o=[n[t.type],...r.filter(({matcher:e})=>e(t)).map(({reducer:e})=>e)];return o.filter(e=>!!e).length===0&&(o=[i]),o.reduce((e,n)=>{if(n){if(zk(e)){let r=n(e,t);return r===void 0?e:r}if(Bk(e))return PA(e,e=>n(e,t));{let r=n(e,t);if(r===void 0){if(e===null)return e;throw Error(vj(9))}return r}}return e},e)}return o.getInitialState=a,o}var woe=`ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW`,Toe=(e=21)=>{let t=``,n=e;for(;n--;)t+=woe[Math.random()*64|0];return t},Eoe=Symbol.for(`rtk-slice-createasyncthunk`);function Doe(e,t){return`${e}/${t}`}function Ooe({creators:e}={}){let t=e?.asyncThunk?.[Eoe];return function(e){let{name:n,reducerPath:r=n}=e;if(!n)throw Error(vj(11));let i=(typeof e.reducers==`function`?e.reducers(Aoe()):e.reducers)||{},a=Object.keys(i),o={sliceCaseReducersByName:{},sliceCaseReducersByType:{},actionCreators:{},sliceMatchers:[]},s={addCase(e,t){let n=typeof e==`string`?e:e.type;if(!n)throw Error(vj(12));if(n in o.sliceCaseReducersByType)throw Error(vj(13));return o.sliceCaseReducersByType[n]=t,s},addMatcher(e,t){return o.sliceMatchers.push({matcher:e,reducer:t}),s},exposeAction(e,t){return o.actionCreators[e]=t,s},exposeCaseReducer(e,t){return o.sliceCaseReducersByName[e]=t,s}};a.forEach(r=>{let a=i[r],o={reducerName:r,type:Doe(n,r),createNotation:typeof e.reducers==`function`};Moe(a)?Poe(o,a,s,t):joe(o,a,s)});function c(){let[t={},n=[],r=void 0]=typeof e.extraReducers==`function`?GA(e.extraReducers):[e.extraReducers],i={...t,...o.sliceCaseReducersByType};return Coe(e.initialState,e=>{for(let t in i)e.addCase(t,i[t]);for(let t of o.sliceMatchers)e.addMatcher(t.matcher,t.reducer);for(let t of n)e.addMatcher(t.matcher,t.reducer);r&&e.addDefaultCase(r)})}let l=e=>e,u=new Map,d=new WeakMap,f;function p(e,t){return f||=c(),f(e,t)}function m(){return f||=c(),f.getInitialState()}function h(t,n=!1){function r(e){let i=e[t];return i===void 0&&n&&(i=BA(d,r,m)),i}function i(t=l){return BA(BA(u,n,()=>new WeakMap),t,()=>{let r={};for(let[i,a]of Object.entries(e.selectors??{}))r[i]=koe(a,t,()=>BA(d,t,m),n);return r})}return{reducerPath:t,getSelectors:i,get selectors(){return i(r)},selectSlice:r}}let g={name:n,reducer:p,actions:o.actionCreators,caseReducers:o.sliceCaseReducersByName,getInitialState:m,...h(r),injectInto(e,{reducerPath:t,...n}={}){let i=t??r;return e.inject({reducerPath:i,reducer:p},n),{...g,...h(i,!0)}}};return g}}function koe(e,t,n,r){function i(i,...a){let o=t(i);return o===void 0&&r&&(o=n()),e(o,...a)}return i.unwrapped=e,i}var KA=Ooe();function Aoe(){function e(e,t){return{_reducerDefinitionType:`asyncThunk`,payloadCreator:e,...t}}return e.withTypes=()=>e,{reducer(e){return Object.assign({[e.name](...t){return e(...t)}}[e.name],{_reducerDefinitionType:`reducer`})},preparedReducer(e,t){return{_reducerDefinitionType:`reducerWithPrepare`,prepare:e,reducer:t}},asyncThunk:e}}function joe({type:e,reducerName:t,createNotation:n},r,i){let a,o;if(`reducer`in r){if(n&&!Noe(r))throw Error(vj(17));a=r.reducer,o=r.prepare}else a=r;i.addCase(e,a).exposeCaseReducer(t,a).exposeAction(t,o?LA(e,o):LA(e))}function Moe(e){return e._reducerDefinitionType===`asyncThunk`}function Noe(e){return e._reducerDefinitionType===`reducerWithPrepare`}function Poe({type:e,reducerName:t},n,r,i){if(!i)throw Error(vj(18));let{payloadCreator:a,fulfilled:o,pending:s,rejected:c,settled:l,options:u}=n,d=i(e,a,u);r.exposeAction(t,d),o&&r.addCase(d.fulfilled,o),s&&r.addCase(d.pending,s),c&&r.addCase(d.rejected,c),l&&r.addMatcher(d.settled,l),r.exposeCaseReducer(t,{fulfilled:o||qA,pending:s||qA,rejected:c||qA,settled:l||qA})}function qA(){}var Foe=`task`,JA=`listener`,YA=`completed`,XA=`cancelled`,Ioe=`task-${XA}`,Loe=`task-${YA}`,ZA=`${JA}-${XA}`,Roe=`${JA}-${YA}`,QA=class{code;name=`TaskAbortError`;message;constructor(e){this.code=e,this.message=`${Foe} ${XA} (reason: ${e})`}},$A=(e,t)=>{if(typeof e!=`function`)throw TypeError(vj(32))},ej=()=>{},tj=(e,t=ej)=>(e.catch(t),e),nj=(e,t)=>(e.addEventListener(`abort`,t,{once:!0}),()=>e.removeEventListener(`abort`,t)),rj=e=>{if(e.aborted)throw new QA(e.reason)};function ij(e,t){let n=ej;return new Promise((r,i)=>{let a=()=>i(new QA(e.reason));if(e.aborted){a();return}n=nj(e,a),t.finally(()=>n()).then(r,i)}).finally(()=>{n=ej})}var zoe=async(e,t)=>{try{return await Promise.resolve(),{status:`ok`,value:await e()}}catch(e){return{status:e instanceof QA?`cancelled`:`rejected`,error:e}}finally{t?.()}},aj=e=>t=>tj(ij(e,t).then(t=>(rj(e),t))),oj=e=>{let t=aj(e);return e=>t(new Promise(t=>setTimeout(t,e)))},{assign:sj}=Object,cj={},lj=`listenerMiddleware`,Boe=(e,t)=>{let n=t=>nj(e,()=>t.abort(e.reason));return(r,i)=>{$A(r,`taskExecutor`);let a=new AbortController;n(a);let o=zoe(async()=>{rj(e),rj(a.signal);let t=await r({pause:aj(a.signal),delay:oj(a.signal),signal:a.signal});return rj(a.signal),t},()=>a.abort(Loe));return i?.autoJoin&&t.push(o.catch(ej)),{result:aj(e)(o),cancel(){a.abort(Ioe)}}}},Voe=(e,t)=>{let n=async(n,r)=>{rj(t);let i=()=>{},a=[new Promise((t,r)=>{let a=e({predicate:n,effect:(e,n)=>{n.unsubscribe(),t([e,n.getState(),n.getOriginalState()])}});i=()=>{a(),r()}})];r!=null&&a.push(new Promise(e=>setTimeout(e,r,null)));try{let e=await ij(t,Promise.race(a));return rj(t),e}finally{i()}};return((e,t)=>tj(n(e,t)))},uj=e=>{let{type:t,actionCreator:n,matcher:r,predicate:i,effect:a}=e;if(t)i=LA(t).match;else if(n)t=n.type,i=n.match;else if(r)i=r;else if(!i)throw Error(vj(21));return $A(a,`options.listener`),{predicate:i,type:t,effect:a}},dj=sj(e=>{let{type:t,predicate:n,effect:r}=uj(e);return{id:Toe(),effect:r,type:t,predicate:n,pending:new Set,unsubscribe:()=>{throw Error(vj(22))}}},{withTypes:()=>dj}),fj=(e,t)=>{let{type:n,effect:r,predicate:i}=uj(t);return Array.from(e.values()).find(e=>(typeof n==`string`?e.type===n:e.predicate===i)&&e.effect===r)},pj=e=>{e.pending.forEach(e=>{e.abort(ZA)})},Hoe=(e,t)=>()=>{for(let e of t.keys())pj(e);e.clear()},mj=(e,t,n)=>{try{e(t,n)}catch(e){setTimeout(()=>{throw e},0)}},hj=sj(LA(`${lj}/add`),{withTypes:()=>hj}),Uoe=LA(`${lj}/removeAll`),gj=sj(LA(`${lj}/remove`),{withTypes:()=>gj}),Woe=(...e)=>{console.error(`${lj}/error`,...e)},_j=(e={})=>{let t=new Map,n=new Map,r=e=>{let t=n.get(e)??0;n.set(e,t+1)},i=e=>{let t=n.get(e)??1;t===1?n.delete(e):n.set(e,t-1)},{extra:a,onError:o=Woe}=e;$A(o,`onError`);let s=e=>(e.unsubscribe=()=>t.delete(e.id),t.set(e.id,e),t=>{e.unsubscribe(),t?.cancelActive&&pj(e)}),c=(e=>{let n=fj(t,e)??dj(e);return s(n)});sj(c,{withTypes:()=>c});let l=e=>{let n=fj(t,e);return n&&(n.unsubscribe(),e.cancelActive&&pj(n)),!!n};sj(l,{withTypes:()=>l});let u=async(e,n,s,l)=>{let u=new AbortController,d=Voe(c,u.signal),f=[];try{e.pending.add(u),r(e),await Promise.resolve(e.effect(n,sj({},s,{getOriginalState:l,condition:(e,t)=>d(e,t).then(Boolean),take:d,delay:oj(u.signal),pause:aj(u.signal),extra:a,signal:u.signal,fork:Boe(u.signal,f),unsubscribe:e.unsubscribe,subscribe:()=>{t.set(e.id,e)},cancelActiveListeners:()=>{e.pending.forEach((e,t,n)=>{e!==u&&(e.abort(ZA),n.delete(e))})},cancel:()=>{u.abort(ZA),e.pending.delete(u)},throwIfCancelled:()=>{rj(u.signal)}})))}catch(e){e instanceof QA||mj(o,e,{raisedBy:`effect`})}finally{await Promise.all(f),u.abort(Roe),i(e),e.pending.delete(u)}},d=Hoe(t,n);return{middleware:e=>n=>r=>{if(!Ek(r))return n(r);if(hj.match(r))return c(r.payload);if(Uoe.match(r)){d();return}if(gj.match(r))return l(r.payload);let i=e.getState(),a=()=>{if(i===cj)throw Error(vj(23));return i},s;try{if(s=n(r),t.size>0){let n=e.getState(),s=Array.from(t.values());for(let t of s){let s=!1;try{s=t.predicate(r,n,i)}catch(e){s=!1,mj(o,e,{raisedBy:`predicate`})}s&&u(t,r,e,a)}}}finally{i=cj}return s},startListening:c,stopListening:l,clearListeners:d}};function vj(e){return`Minified Redux Toolkit error #${e}; visit https://redux-toolkit.js.org/Errors?code=${e} for the full message or use the non-minified dev environment for full errors. `}var yj=KA({name:`chartLayout`,initialState:{layoutType:`horizontal`,width:0,height:0,margin:{top:5,right:5,bottom:5,left:5},scale:1},reducers:{setLayout(e,t){e.layoutType=t.payload},setChartSize(e,t){e.width=t.payload.width,e.height=t.payload.height},setMargin(e,t){e.margin.top=t.payload.top??0,e.margin.right=t.payload.right??0,e.margin.bottom=t.payload.bottom??0,e.margin.left=t.payload.left??0},setScale(e,t){e.scale=t.payload}}}),bj=yj.actions,Goe=bj.setMargin,Koe=bj.setLayout,qoe=bj.setChartSize,Joe=bj.setScale,Yoe=yj.reducer;function xj(e,t,n){return Array.isArray(e)&&e&&t+n!==0?e.slice(t,n+1):e}function Q(e){return Number.isFinite(e)}function Sj(e){return typeof e==`number`&&e>0&&Number.isFinite(e)}function Cj(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function wj(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Cj(Object(n),!0).forEach(function(t){Xoe(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Cj(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Xoe(e,t,n){return(t=Zoe(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Zoe(e){var t=Qoe(e,`string`);return typeof t==`symbol`?t:t+``}function Qoe(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Tj(e,t,n){return cD(e)||cD(t)?n:tD(t)?qE(e,t,n):typeof t==`function`?t(e):n}var $oe=(e,t,n)=>{if(t&&n){var r=n.width,i=n.height,a=t.align,o=t.verticalAlign,s=t.layout,c=t.position,l=t.offset,u=l===void 0?0:l;if(c!=null){if(bD(c)){if(c===`top`&&Y(e.top))return wj(wj({},e),{},{top:e.top+(i||0)+u});if(c===`bottom`&&Y(e.bottom))return wj(wj({},e),{},{bottom:e.bottom+(i||0)+u});if(c===`left`&&Y(e.left))return wj(wj({},e),{},{left:e.left+(r||0)+u});if(c===`right`&&Y(e.right))return wj(wj({},e),{},{right:e.right+(r||0)+u})}return e}if((s===`vertical`||s===`horizontal`&&o===`middle`)&&a!==`center`&&Y(e[a]))return wj(wj({},e),{},{[a]:e[a]+(r||0)});if((s===`horizontal`||s===`vertical`&&a===`center`)&&o!==`middle`&&Y(e[o]))return wj(wj({},e),{},{[o]:e[o]+(i||0)})}return e},Ej=(e,t)=>e===`horizontal`&&t===`xAxis`||e===`vertical`&&t===`yAxis`||e===`centric`&&t===`angleAxis`||e===`radial`&&t===`radiusAxis`,Dj=(e,t,n,r)=>{if(r)return e.map(e=>e.coordinate);var i,a,o=e.map(e=>(e.coordinate===t&&(i=!0),e.coordinate===n&&(a=!0),e.coordinate));return i||o.push(t),a||o.push(n),o},Oj=(e,t,n)=>{if(!e)return null;var r=e.duplicateDomain,i=e.type,a=e.range,o=e.scale,s=e.realScaleType,c=e.isCategorical,l=e.categoricalDomain,u=e.tickCount,d=e.ticks,f=e.niceTicks,p=e.axisType;if(!o)return null;var m=s===`scaleBand`&&o.bandwidth?o.bandwidth()/2:2,h=(t||n)&&i===`category`&&o.bandwidth?o.bandwidth()/m:0;return h=p===`angleAxis`&&a&&a.length>=2?QE(a[0]-a[1])*2*h:h,t&&(d||f)?(d||f||[]).map((e,t)=>{var n=r?r.indexOf(e):e,i=o.map(n);return Q(i)?{coordinate:i+h,value:e,offset:h,index:t}:null}).filter(uD):c&&l?l.map((e,t)=>{var n=o.map(e);return Q(n)?{coordinate:n+h,value:e,index:t,offset:h}:null}).filter(uD):o.ticks&&!n&&u!=null?o.ticks(u).map((e,t)=>{var n=o.map(e);return Q(n)?{coordinate:n+h,value:e,index:t,offset:h}:null}).filter(uD):o.domain().map((e,t)=>{var n=o.map(e);return Q(n)?{coordinate:n+h,value:r?r[e]:e,index:t,offset:h}:null}).filter(uD)},ese=(e,t)=>{if(!t||t.length!==2||!Y(t[0])||!Y(t[1]))return e;var n=Math.min(t[0],t[1]),r=Math.max(t[0],t[1]),i=[e[0],e[1]];return(!Y(e[0])||e[0]<n)&&(i[0]=n),(!Y(e[1])||e[1]>r)&&(i[1]=r),i[0]>r&&(i[0]=r),i[1]<n&&(i[1]=n),i},tse={sign:e=>{var t=e.length;if(!(t<=0)){var n=e[0]?.length;if(!(n==null||n<=0))for(var r=0;r<n;++r)for(var i=0,a=0,o=0;o<t;++o){var s=e[o]?.[r];if(s!=null){var c=s[1],l=s[0],u=$E(c)?l:c;u>=0?(s[0]=i,i+=u,s[1]=i):(s[0]=a,a+=u,s[1]=a)}}}},expand:Kie,none:lO,silhouette:qie,wiggle:Jie,positive:e=>{var t=e.length;if(!(t<=0)){var n=e[0]?.length;if(!(n==null||n<=0))for(var r=0;r<n;++r)for(var i=0,a=0;a<t;++a){var o=e[a]?.[r];if(o!=null){var s=$E(o[1])?o[0]:o[1];s>=0?(o[0]=i,i+=s,o[1]=i):(o[0]=0,o[1]=0)}}}}},nse=(e,t,n)=>{var r=tse[n]??lO,i=Gie().keys(t).value((e,t)=>Number(Tj(e,t,0))).order(uO).offset(r)(e);return i.forEach((n,r)=>{n.forEach((n,i)=>{var a=Tj(e[i],t[r],0);Array.isArray(a)&&a.length===2&&Y(a[0])&&Y(a[1])&&(n[0]=a[0],n[1]=a[1])})}),i};function rse(e){return e==null?void 0:String(e)}function kj(e){var t=e.axis,n=e.ticks,r=e.bandSize,i=e.entry,a=e.index,o=e.dataKey;if(t.type===`category`){if(!t.allowDuplicatedCategory&&t.dataKey&&!cD(i[t.dataKey])){var s=sD(n,`value`,i[t.dataKey]);if(s)return s.coordinate+r/2}return n!=null&&n[a]?n[a].coordinate+r/2:null}var c=Tj(i,cD(o)?t.dataKey:o),l=t.scale.map(c);return Y(l)?l:null}var Aj=e=>{var t=e.axis,n=e.ticks,r=e.offset,i=e.bandSize,a=e.entry,o=e.index;if(t.type===`category`)return n[o]?n[o].coordinate+r:null;var s=Tj(a,t.dataKey,t.scale.domain()[o]);if(cD(s))return null;var c=t.scale.map(s);return Y(c)?c-i/2+r:null},ise=e=>{var t=e.numericAxis,n=t.scale.domain();if(t.type===`number`){var r=Math.min(n[0],n[1]),i=Math.max(n[0],n[1]);return r<=0&&i>=0?0:i<0?i:r}return n[0]},ase=e=>{var t=e.flat(2).filter(Y);return[Math.min(...t),Math.max(...t)]},ose=e=>[e[0]===1/0?0:e[0],e[1]===-1/0?0:e[1]],sse=(e,t,n)=>{if(e!=null&&Object.keys(e).length!==0)return ose(Object.keys(e).reduce((r,i)=>{var a=e[i];if(!a)return r;var o=a.stackedData.reduce((e,r)=>{var i=ase(xj(r,t,n));return!Q(i[0])||!Q(i[1])?e:[Math.min(e[0],i[0]),Math.max(e[1],i[1])]},[1/0,-1/0]);return[Math.min(o[0],r[0]),Math.max(o[1],r[1])]},[1/0,-1/0]))},jj=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Mj=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Nj=(e,t,n)=>{if(e&&e.scale&&e.scale.bandwidth){var r=e.scale.bandwidth();if(!n||r>0)return r}if(e&&t&&t.length>=2){for(var i=fk(t,e=>e.coordinate),a=[],o=0,s=1,c=i.length;s<c;s++){var l=(i[s]?.coordinate||0)-(i[s-1]?.coordinate||0);a.push(l),o=Math.max(l,o)}var u=o*1e-4,d=1/0;for(var f of a)f>u&&(d=Math.min(f,d));return d===1/0?0:d}return n?void 0:0};function Pj(e){var t=e.tooltipEntrySettings,n=e.dataKey,r=e.payload,i=e.value,a=e.name;return wj(wj({},t),{},{dataKey:n,payload:r,value:i,name:a})}function Fj(e,t){if(e!=null)return String(e);if(typeof t==`string`)return t}var cse=(e,t)=>{if(t===`horizontal`)return e.relativeX;if(t===`vertical`)return e.relativeY},lse=(e,t)=>t===`centric`?e.angle:e.radius,Ij=e=>e.layout.width,Lj=e=>e.layout.height,use=e=>e.layout.scale,Rj=e=>e.layout.margin,zj=Z(e=>e.cartesianAxis.xAxis,e=>Object.values(e)),Bj=Z(e=>e.cartesianAxis.yAxis,e=>Object.values(e)),Vj=`data-recharts-item-index`,dse=`data-recharts-item-id`;function Hj(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Uj(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Hj(Object(n),!0).forEach(function(t){fse(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Hj(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function fse(e,t,n){return(t=pse(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function pse(e){var t=mse(e,`string`);return typeof t==`symbol`?t:t+``}function mse(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var hse=e=>e.brush.height;function gse(e){return Bj(e).reduce((e,t)=>t.orientation===`left`&&!t.mirror&&!t.hide?e+(typeof t.width==`number`?t.width:60):e,0)}function _se(e){return Bj(e).reduce((e,t)=>t.orientation===`right`&&!t.mirror&&!t.hide?e+(typeof t.width==`number`?t.width:60):e,0)}function vse(e){return zj(e).reduce((e,t)=>t.orientation===`top`&&!t.mirror&&!t.hide?e+(typeof t.height==`number`?t.height:30):e,0)}function yse(e){return zj(e).reduce((e,t)=>t.orientation===`bottom`&&!t.mirror&&!t.hide?e+(typeof t.height==`number`?t.height:30):e,0)}var Wj=Z([Ij,Lj,Rj,hse,gse,_se,vse,yse,pk,Gae],(e,t,n,r,i,a,o,s,c,l)=>{var u={left:(n.left||0)+i,right:(n.right||0)+a},d=Uj(Uj({},{top:(n.top||0)+o,bottom:(n.bottom||0)+s}),u),f=d.bottom;d.bottom+=r,d=$oe(d,c,l);var p=e-d.left-d.right,m=t-d.top-d.bottom;return Uj(Uj({brushBottom:f},d),{},{width:Math.max(p,0),height:Math.max(m,0)})}),bse=Z(Wj,e=>({x:e.left,y:e.top,width:e.width,height:e.height})),Gj=Z(Ij,Lj,(e,t)=>({x:0,y:0,width:e,height:t})),xse=(0,o.createContext)(null),Kj=()=>(0,o.useContext)(xse)!=null,qj=e=>e.brush,Jj=Z([qj,Wj,Rj],(e,t,n)=>({height:e.height,x:Y(e.x)?e.x:t.left,y:Y(e.y)?e.y:t.top+t.height+t.brushBottom-(n?.bottom||0),width:Y(e.width)?e.width:t.width}));function Sse(e,t,{signal:n,edges:r}={}){let i,a=null,o=r!=null&&r.includes(`leading`),s=r==null||r.includes(`trailing`),c=()=>{a!==null&&(e.apply(i,a),i=void 0,a=null)},l=()=>{s&&c(),p()},u=null,d=()=>{u!=null&&clearTimeout(u),u=setTimeout(()=>{u=null,l()},t)},f=()=>{u!==null&&(clearTimeout(u),u=null)},p=()=>{f(),i=void 0,a=null},m=()=>{c()},h=function(...e){if(n?.aborted)return;i=this,a=e;let t=u==null;d(),o&&t&&c()};return h.schedule=d,h.cancel=p,h.flush=m,n?.addEventListener(`abort`,p,{once:!0}),h}function Cse(e,t=0,n={}){typeof n!=`object`&&(n={});let{leading:r=!1,trailing:i=!0,maxWait:a}=n,o=[,,];r&&(o[0]=`leading`),i&&(o[1]=`trailing`);let s,c=null,l=Sse(function(...t){s=e.apply(this,t),c=null},t,{edges:o}),u=function(...t){return a!=null&&(c===null&&(c=Date.now()),Date.now()-c>=a)?((r||i)&&(s=e.apply(this,t)),c=Date.now(),l.cancel(),l.schedule(),s):(l.apply(this,t),s)};return u.cancel=l.cancel,u.flush=()=>(l.flush(),s),u}function wse(e,t=0,n={}){let{leading:r=!0,trailing:i=!0}=n;return Cse(e,t,{leading:r,maxWait:t,trailing:i})}var Yj=function(e,t){var n=[...arguments].slice(2);if(typeof console<`u`&&console.warn&&(t===void 0&&console.warn(`LogUtils requires an error message argument`),!e)){if(t===void 0)console.warn(`Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.`);else{var r=0;console.warn(t.replace(/%s/g,()=>n[r++]))}}},Xj={width:`100%`,height:`100%`,debounce:0,minWidth:0,initialDimension:{width:-1,height:-1}},Zj=(e,t,n)=>{var r=n.width,i=r===void 0?Xj.width:r,a=n.height,o=a===void 0?Xj.height:a,s=n.aspect,c=n.maxHeight,l=eD(i)?e:Number(i),u=eD(o)?t:Number(o);return s&&s>0&&(l?u=l/s:u&&(l=u*s),c&&u!=null&&u>c&&(u=c)),{calculatedWidth:l,calculatedHeight:u}},Tse={width:0,height:0,overflow:`visible`},Ese={width:0,overflowX:`visible`},Dse={height:0,overflowY:`visible`},Ose={},kse=e=>{var t=e.width,n=e.height,r=eD(t),i=eD(n);return r&&i?Tse:r?Ese:i?Dse:Ose};function Ase(e){var t=e.width,n=e.height,r=e.aspect,i=t,a=n;return i===void 0&&a===void 0?(i=Xj.width,a=Xj.height):i===void 0?i=r&&r>0?void 0:Xj.width:a===void 0&&(a=r&&r>0?void 0:Xj.height),{width:i,height:a}}var jse=[`aspect`,`initialDimension`,`width`,`height`,`minWidth`,`minHeight`,`maxHeight`,`children`,`debounce`,`id`,`className`,`onResize`,`style`];function Qj(){return Qj=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Qj.apply(null,arguments)}function $j(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function eM(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?$j(Object(n),!0).forEach(function(t){Mse(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$j(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Mse(e,t,n){return(t=Nse(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Nse(e){var t=Pse(e,`string`);return typeof t==`symbol`?t:t+``}function Pse(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Fse(e,t){return zse(e)||Rse(e,t)||Lse(e,t)||Ise()}function Ise(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
15
15
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Lse(e,t){if(e){if(typeof e==`string`)return tM(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?tM(e,t):void 0}}function tM(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Rse(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function zse(e){if(Array.isArray(e))return e}function Bse(e,t){if(e==null)return{};var n,r,i=Vse(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Vse(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var nM=(0,o.createContext)(Xj.initialDimension);function Hse(e){return Sj(e.width)&&Sj(e.height)}function rM(e){var t=e.children,n=e.width,r=e.height,i=(0,o.useMemo)(()=>({width:n,height:r}),[n,r]);return Hse(i)?o.createElement(nM.Provider,{value:i},t):null}var iM=()=>(0,o.useContext)(nM),Use=(0,o.forwardRef)((e,t)=>{var n=e.aspect,r=e.initialDimension,i=r===void 0?Xj.initialDimension:r,a=e.width,s=e.height,c=e.minWidth,l=c===void 0?Xj.minWidth:c,u=e.minHeight,d=e.maxHeight,f=e.children,p=e.debounce,m=p===void 0?Xj.debounce:p,h=e.id,g=e.className,_=e.onResize,v=e.style,y=v===void 0?{}:v,b=Bse(e,jse),x=(0,o.useRef)(null),S=(0,o.useRef)();S.current=_,(0,o.useImperativeHandle)(t,()=>x.current);var C=Fse((0,o.useState)({containerWidth:i.width,containerHeight:i.height}),2),w=C[0],T=C[1],E=(0,o.useCallback)((e,t)=>{T(n=>{var r=Math.round(e),i=Math.round(t);return n.containerWidth===r&&n.containerHeight===i?n:{containerWidth:r,containerHeight:i}})},[]);(0,o.useEffect)(()=>{if(x.current==null||typeof ResizeObserver>`u`)return dD;var e=e=>{var t,n=e[0];if(n!=null){var r=n.contentRect,i=r.width,a=r.height;E(i,a),(t=S.current)==null||t.call(S,i,a)}};m>0&&(e=wse(e,m,{trailing:!0,leading:!1}));var t=new ResizeObserver(e),n=x.current.getBoundingClientRect(),r=n.width,i=n.height;return E(r,i),t.observe(x.current),()=>{t.disconnect()}},[E,m]);var D=w.containerWidth,O=w.containerHeight;Yj(!n||n>0,`The aspect(%s) must be greater than zero.`,n);var k=Zj(D,O,{width:a,height:s,aspect:n,maxHeight:d}),A=k.calculatedWidth,j=k.calculatedHeight;return Yj(D<0||O<0||A!=null&&A>0||j!=null&&j>0,`The width(%s) and height(%s) of chart should be greater than 0,
|
|
@@ -64,6 +64,6 @@ In order to be iterable, non-array objects must have a [Symbol.iterator]() metho
|
|
|
64
64
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function f1(e,t){if(e){if(typeof e==`string`)return p1(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?p1(e,t):void 0}}function p1(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function m1(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function h1(e){if(Array.isArray(e))return e}function g1(e,t){if(e==null)return{};var n,r,i=_1(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function _1(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function v1(){return v1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},v1.apply(null,arguments)}function y1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function b1(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?y1(Object(n),!0).forEach(function(t){x1(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):y1(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function x1(e,t,n){return(t=S1(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function S1(e){var t=C1(e,`string`);return typeof t==`symbol`?t:t+``}function C1(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var w1={x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:`bottom`,ticks:[],stroke:`#666`,tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:`preserveEnd`,zIndex:VF.axis};function T1(e){var t=e.x,n=e.y,r=e.width,i=e.height,a=e.orientation,s=e.mirror,c=e.axisLine,l=e.otherSvgProps;if(!c)return null;var u=b1(b1(b1({},l),TE(c)),{},{fill:`none`});if(a===`top`||a===`bottom`){var d=+(a===`top`&&!s||a===`bottom`&&s);u=b1(b1({},u),{},{x1:t,y1:n+d*i,x2:t+r,y2:n+d*i})}else{var f=+(a===`left`&&!s||a===`right`&&s);u=b1(b1({},u),{},{x1:t+f*r,y1:n,x2:t+f*r,y2:n+i})}return o.createElement(`line`,v1({},u,{className:yE(`recharts-cartesian-axis-line`,qE(c,`className`))}))}function E1(e,t,n,r,i,a,o,s,c){var l,u,d,f,p,m,h=s?-1:1,g=e.tickSize||o,_=Y(e.tickCoord)?e.tickCoord:e.coordinate;switch(a){case`top`:l=u=e.coordinate,f=n+ +!s*i,d=f-h*g,m=d-h*c,p=_;break;case`left`:d=f=e.coordinate,u=t+ +!s*r,l=u-h*g,p=l-h*c,m=_;break;case`right`:d=f=e.coordinate,u=t+ +s*r,l=u+h*g,p=l+h*c,m=_;break;default:l=u=e.coordinate,f=n+ +s*i,d=f+h*g,m=d+h*c,p=_}return{line:{x1:l,y1:d,x2:u,y2:f},tick:{x:p,y:m}}}function D1(e,t){switch(e){case`left`:return t?`start`:`end`;case`right`:return t?`end`:`start`;default:return`middle`}}function O1(e,t){switch(e){case`left`:case`right`:return`middle`;case`top`:return t?`start`:`end`;default:return t?`end`:`start`}}function k1(e){var t=e.option,n=e.tickProps,r=e.value,i,a=yE(n.className,`recharts-cartesian-axis-tick-value`);if(o.isValidElement(t))i=o.cloneElement(t,b1(b1({},n),{},{className:a}));else if(typeof t==`function`)i=t(b1(b1({},n),{},{className:a}));else{var s=`recharts-cartesian-axis-tick-value`;typeof t!=`boolean`&&(s=yE(s,uX(t))),i=o.createElement(dY,v1({},n,{className:s}),r)}return i}function A1(e){var t=e.ticks,n=e.axisType,r=e.axisId,i=rk(),a=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(r!=null&&n!=null){var e=t.map(e=>({value:e.value,coordinate:e.coordinate,offset:e.offset,index:e.index})),o=a.current;o!=null&&o.axisId===r&&o.axisType===n&&B$(o.ticks,e)||(a.current={ticks:e,axisId:r,axisType:n},i(o1({ticks:e,axisId:r,axisType:n})))}},[i,t,r,n]),(0,o.useEffect)(()=>r==null||n==null?dD:()=>{i(s1({axisId:r,axisType:n}))},[i,r,n]),null}var j1=(0,o.forwardRef)((e,t)=>{var n=e.ticks,r=n===void 0?[]:n,i=e.tick,a=e.tickLine,s=e.stroke,c=e.tickFormatter,l=e.unit,u=e.padding,d=e.tickTextProps,f=e.orientation,p=e.mirror,m=e.x,h=e.y,g=e.width,_=e.height,v=e.tickSize,y=e.tickMargin,b=e.fontSize,x=e.letterSpacing,S=e.getTicksConfig,C=e.events,w=e.axisType,T=e.axisId,E=t1(b1(b1({},S),{},{ticks:r}),b,x),D=TE(S),O=EE(i),k=eY(D.textAnchor)?D.textAnchor:D1(f,p),A=O1(f,p),j={};typeof a==`object`&&(j=a);var M=b1(b1({},D),{},{fill:`none`},j),N=E.map(e=>b1({entry:e},E1(e,m,h,g,_,f,v,p,y))),ee=N.map(e=>{var t=e.entry,n=e.line;return o.createElement(RE,{className:`recharts-cartesian-axis-tick`,key:`tick-${t.value}-${t.coordinate}-${t.tickCoord}`},a&&o.createElement(`line`,v1({},M,n,{className:yE(`recharts-cartesian-axis-tick-line`,qE(a,`className`))})))}),P=N.map((e,t)=>{var n=e.entry,r=e.tick,a=b1(b1({},b1(b1(b1(b1({verticalAnchor:A},D),{},{textAnchor:k,stroke:`none`,fill:s},r),{},{index:t,payload:n,visibleTicksCount:E.length,tickFormatter:c,padding:u},d),{},{angle:d?.angle??D.angle??0})),O);return o.createElement(RE,v1({className:`recharts-cartesian-axis-tick-label`,key:`tick-label-${n.value}-${n.coordinate}-${n.tickCoord}`},pO(C,n,t)),i&&o.createElement(k1,{option:i,tickProps:a,value:`${typeof c==`function`?c(n.value,t):n.value}${l||``}`}))});return o.createElement(`g`,{className:`recharts-cartesian-axis-ticks recharts-${w}-ticks`},o.createElement(A1,{ticks:E,axisId:T,axisType:w}),P.length>0&&o.createElement(QK,{zIndex:VF.label},o.createElement(`g`,{className:`recharts-cartesian-axis-tick-labels recharts-${w}-tick-labels`,ref:t},P)),ee.length>0&&o.createElement(`g`,{className:`recharts-cartesian-axis-tick-lines recharts-${w}-tick-lines`},ee))}),M1=(0,o.forwardRef)((e,t)=>{var n=e.axisLine,r=e.width,i=e.height,a=e.className,s=e.hide,c=e.ticks,l=e.axisType,u=e.axisId,d=g1(e,l1),f=u1((0,o.useState)(``),2),p=f[0],m=f[1],h=u1((0,o.useState)(``),2),g=h[0],_=h[1],v=(0,o.useRef)(null);(0,o.useImperativeHandle)(t,()=>({getCalculatedWidth:()=>n1({ticks:v.current,label:e.labelRef?.current,labelGapWithTick:5,tickSize:e.tickSize,tickMargin:e.tickMargin}),getCalculatedHeight:()=>r1({ticks:v.current,label:e.labelRef?.current,labelGapWithTick:5,tickSize:e.tickSize,tickMargin:e.tickMargin})}));var y=(0,o.useCallback)(e=>{if(e){var t=e.getElementsByClassName(`recharts-cartesian-axis-tick-value`);v.current=t;var n=t[0];if(n){var r=window.getComputedStyle(n),i=r.fontSize,a=r.letterSpacing;(i!==p||a!==g)&&(m(i),_(a))}}},[p,g]);return s||r!=null&&r<=0||i!=null&&i<=0?null:o.createElement(QK,{zIndex:e.zIndex},o.createElement(RE,{className:yE(`recharts-cartesian-axis`,a)},o.createElement(T1,{x:e.x,y:e.y,width:r,height:i,orientation:e.orientation,mirror:e.mirror,axisLine:n,otherSvgProps:TE(e)}),o.createElement(j1,{ref:y,axisType:l,events:d,fontSize:p,getTicksConfig:e,height:e.height,letterSpacing:g,mirror:e.mirror,orientation:e.orientation,padding:e.padding,stroke:e.stroke,tick:e.tick,tickFormatter:e.tickFormatter,tickLine:e.tickLine,tickMargin:e.tickMargin,tickSize:e.tickSize,tickTextProps:e.tickTextProps,ticks:c,unit:e.unit,width:e.width,x:e.x,y:e.y,axisId:u}),o.createElement(CY,{x:e.x,y:e.y,width:e.width,height:e.height,lowerWidth:e.width,upperWidth:e.width},o.createElement(RY,{label:e.label,labelRef:e.labelRef}),e.children)))}),N1=o.forwardRef((e,t)=>{var n=hO(e,w1);return o.createElement(M1,v1({},n,{ref:t}))});N1.displayName=`CartesianAxis`;var P1=(0,o.createContext)({grid:{stroke:`#ccc`,fill:`none`}});P1.Provider;var F1=()=>(0,o.useContext)(P1),I1=[`x1`,`y1`,`x2`,`y2`,`key`],L1=[`offset`],R1=[`xAxisId`,`yAxisId`],z1=[`xAxisId`,`yAxisId`];function B1(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function V1(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?B1(Object(n),!0).forEach(function(t){H1(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):B1(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function H1(e,t,n){return(t=U1(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function U1(e){var t=W1(e,`string`);return typeof t==`symbol`?t:t+``}function W1(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function G1(){return G1=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},G1.apply(null,arguments)}function K1(e,t){if(e==null)return{};var n,r,i=q1(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function q1(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var J1=e=>{var t=e.fill;if(!t||t===`none`)return null;var n=e.fillOpacity,r=e.x,i=e.y,a=e.width,s=e.height,c=e.ry;return o.createElement(`rect`,{x:r,y:i,ry:c,width:a,height:s,stroke:`none`,fill:t,fillOpacity:n,className:`recharts-cartesian-grid-bg`})};function Y1(e){var t=e.option,n=e.lineItemProps,r;if(o.isValidElement(t))r=o.cloneElement(t,n);else if(typeof t==`function`)r=t(n);else{var i=n.x1,a=n.y1,s=n.x2,c=n.y2,l=n.key,u=TE(K1(n,I1))??{};u.offset;var d=K1(u,L1),f=Array.isArray(d.strokeDasharray)?d.strokeDasharray.join(`,`):d.strokeDasharray;r=o.createElement(`line`,G1({},d,{strokeDasharray:f,x1:i,y1:a,x2:s,y2:c,fill:`none`,key:l}))}return r}function X1(e){var t=e.x,n=e.width,r=e.horizontal,i=r===void 0||r,a=e.horizontalPoints;if(!i||!a||!a.length)return null;e.xAxisId,e.yAxisId;var s=K1(e,R1),c=a.map((e,r)=>{var a=V1(V1({},s),{},{x1:t,y1:e,x2:t+n,y2:e,key:`line-${r}`,index:r});return o.createElement(Y1,{key:`line-${r}`,option:i,lineItemProps:a})});return o.createElement(`g`,{className:`recharts-cartesian-grid-horizontal`},c)}function Z1(e){var t=e.y,n=e.height,r=e.vertical,i=r===void 0||r,a=e.verticalPoints;if(!i||!a||!a.length)return null;e.xAxisId,e.yAxisId;var s=K1(e,z1),c=a.map((e,r)=>{var a=V1(V1({},s),{},{x1:e,y1:t,x2:e,y2:t+n,key:`line-${r}`,index:r});return o.createElement(Y1,{option:i,lineItemProps:a,key:`line-${r}`})});return o.createElement(`g`,{className:`recharts-cartesian-grid-vertical`},c)}function Q1(e){var t=e.horizontalFill,n=e.fillOpacity,r=e.x,i=e.y,a=e.width,s=e.height,c=e.horizontalPoints,l=e.horizontal;if(!(l===void 0||l)||!t||!t.length||c==null)return null;var u=c.map(e=>Math.round(e+i-i)).sort((e,t)=>e-t);i!==u[0]&&u.unshift(0);var d=u.map((e,c)=>{var l=u[c+1],d=l==null?i+s-e:l-e;if(d<=0)return null;var f=c%t.length;return o.createElement(`rect`,{key:`react-${c}`,y:e,x:r,height:d,width:a,stroke:`none`,fill:t[f],fillOpacity:n,className:`recharts-cartesian-grid-bg`})});return o.createElement(`g`,{className:`recharts-cartesian-gridstripes-horizontal`},d)}function $1(e){var t=e.vertical,n=t===void 0||t,r=e.verticalFill,i=e.fillOpacity,a=e.x,s=e.y,c=e.width,l=e.height,u=e.verticalPoints;if(!n||!r||!r.length)return null;var d=u.map(e=>Math.round(e+a-a)).sort((e,t)=>e-t);a!==d[0]&&d.unshift(0);var f=d.map((e,t)=>{var n=d[t+1],u=n==null?a+c-e:n-e;if(u<=0)return null;var f=t%r.length;return o.createElement(`rect`,{key:`react-${t}`,x:e,y:s,width:u,height:l,stroke:`none`,fill:r[f],fillOpacity:i,className:`recharts-cartesian-grid-bg`})});return o.createElement(`g`,{className:`recharts-cartesian-gridstripes-vertical`},f)}var e0=(e,t)=>{var n=e.xAxis,r=e.width,i=e.height,a=e.offset;return Dj(t1(V1(V1(V1({},w1),n),{},{ticks:Oj(n,!0),viewBox:{x:0,y:0,width:r,height:i}})),a.left,a.left+a.width,t)},t0=(e,t)=>{var n=e.yAxis,r=e.width,i=e.height,a=e.offset;return Dj(t1(V1(V1(V1({},w1),n),{},{ticks:Oj(n,!0),viewBox:{x:0,y:0,width:r,height:i}})),a.top,a.top+a.height,t)},n0={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],verticalFill:[],horizontalFill:[],xAxisId:0,yAxisId:0,syncWithTicks:!1,zIndex:VF.grid};function r0(e){var t=cM(),n=lM(),r=sM(),i=V1(V1({},hO(e,n0)),{},{x:Y(e.x)?e.x:r.left,y:Y(e.y)?e.y:r.top,width:Y(e.width)?e.width:r.width,height:Y(e.height)?e.height:r.height}),a=i.xAxisId,s=i.yAxisId,c=i.x,l=i.y,u=i.width,d=i.height,f=i.syncWithTicks,p=i.horizontalValues,m=i.verticalValues,h=Kj(),g=X(e=>SW(e,`xAxis`,a,h)),_=X(e=>SW(e,`yAxis`,s,h)),v=F1(),y={stroke:i.stroke??v.grid.stroke,strokeWidth:i.strokeWidth??v.grid.strokeWidth,strokeOpacity:i.strokeOpacity??v.grid.strokeOpacity,strokeDasharray:i.strokeDasharray??v.grid.strokeDasharray};if(!Sj(u)||!Sj(d)||!Y(c)||!Y(l))return null;var b=i.verticalCoordinatesGenerator||e0,x=i.horizontalCoordinatesGenerator||t0,S=i.horizontalPoints,C=i.verticalPoints;if((!S||!S.length)&&typeof x==`function`){var w=p&&p.length,T=x({yAxis:_?V1(V1({},_),{},{ticks:w?p:_.ticks}):void 0,width:t??u,height:n??d,offset:r},w?!0:f);Yj(Array.isArray(T),`horizontalCoordinatesGenerator should return Array but instead it returned [${typeof T}]`),Array.isArray(T)&&(S=T)}if((!C||!C.length)&&typeof b==`function`){var E=m&&m.length,D=b({xAxis:g?V1(V1({},g),{},{ticks:E?m:g.ticks}):void 0,width:t??u,height:n??d,offset:r},E?!0:f);Yj(Array.isArray(D),`verticalCoordinatesGenerator should return Array but instead it returned [${typeof D}]`),Array.isArray(D)&&(C=D)}return o.createElement(QK,{zIndex:i.zIndex},o.createElement(`g`,{className:`recharts-cartesian-grid`},o.createElement(J1,{fill:i.fill??v.grid.fill,fillOpacity:i.fillOpacity??v.grid.fillOpacity,x:i.x,y:i.y,width:i.width,height:i.height,ry:i.ry}),o.createElement(Q1,G1({},i,{horizontalPoints:S})),o.createElement($1,G1({},i,{verticalPoints:C})),o.createElement(X1,G1({},i,y,{offset:r,horizontalPoints:S,xAxis:g,yAxis:_})),o.createElement(Z1,G1({},i,y,{offset:r,verticalPoints:C,xAxis:g,yAxis:_}))))}r0.displayName=`CartesianGrid`;var i0=[`animationElapsedTime`,`isAnimating`,`isEntrance`,`visibleLength`,`strokeDasharray`,`connectNulls`];function a0(){return a0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},a0.apply(null,arguments)}function o0(e,t){if(e==null)return{};var n,r,i=s0(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function s0(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function c0(e){try{return e&&e.getTotalLength&&e.getTotalLength()||0}catch{return 0}}function l0(e,t){return`${t}px ${e}px`}function u0(e){return e.length%2==0?e:[...e,...e]}function Wce(e,t){for(var n=[],r=0;r<t;++r)n.push(...e);return n}function Gce(e,t,n){var r=u0(n),i=r.reduce((e,t)=>e+t,0);if(!i)return l0(t,e);for(var a=Math.floor(e/i),o=e%i,s=[],c=0,l=0;c<r.length;l+=(u=r[c])??0,++c){var u,d=r[c];if(d!=null&&l+d>o){s=[...r.slice(0,c),o-l];break}}var f=s.length%2==0?[0,t]:[t];return[...Wce(r,a),...s,...f].map(e=>`${e}px`).join(`, `)}function Kce(e,t,n){return e?Gce(n,t,`${e}`.split(/[,\s]+/gim).map(e=>parseFloat(e))):l0(t,n)}function qce(e){e.animationElapsedTime,e.isAnimating,e.isEntrance;var t=e.visibleLength,n=e.strokeDasharray,r=e.connectNulls,i=o0(e,i0),a=r??!1,s;if(t!=null){var c=i.pathRef;s=Kce(n,c0(c?.current??null),t)}else n!=null&&(s=String(n));return o.createElement(JM,a0({},i,{connectNulls:a,strokeDasharray:s}))}function Jce(e){var t=(0,o.useRef)(0),n=(0,o.useRef)(0),r=(0,o.useRef)(!1),i=(0,o.useRef)(e);return i.current!==e&&(t.current=n.current,i.current=e),(0,o.useCallback)((e,i)=>{if(r.current)return null;var a=Math.min(XE(t.current+e*i),i);return e>0&&i>0&&(n.current=Math.max(n.current,a),a>=i)?(r.current=!0,null):a},[])}var d0=KA({name:`errorBars`,initialState:{},reducers:{addErrorBar:(e,t)=>{var n=t.payload,r=n.itemId,i=n.errorBar;e[r]||(e[r]=[]),e[r].push(i)},replaceErrorBar:(e,t)=>{var n=t.payload,r=n.itemId,i=n.prev,a=n.next;e[r]&&(e[r]=e[r].map(e=>e.dataKey===i.dataKey&&e.direction===i.direction?a:e))},removeErrorBar:(e,t)=>{var n=t.payload,r=n.itemId,i=n.errorBar;e[r]&&(e[r]=e[r].filter(e=>e.dataKey!==i.dataKey||e.direction!==i.direction))}}}),f0=d0.actions;f0.addErrorBar,f0.replaceErrorBar,f0.removeErrorBar;var Yce=d0.reducer,Xce=[`children`];function Zce(e,t){if(e==null)return{};var n,r,i=Qce(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Qce(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var $ce=(0,o.createContext)({data:[],xAxisId:`xAxis-0`,yAxisId:`yAxis-0`,dataPointFormatter:()=>({x:0,y:0,value:0}),errorBarOffset:0});function p0(e){var t=e.children,n=Zce(e,Xce);return o.createElement($ce.Provider,{value:n},t)}function m0(e,t){var n=X(t=>CH(t,e)),r=X(e=>EH(e,t)),i=n?.allowDataOverflow??xH.allowDataOverflow,a=r?.allowDataOverflow??wH.allowDataOverflow;return{needClip:i||a,needClipX:i,needClipY:a}}function h0(e){var t=e.xAxisId,n=e.yAxisId,r=e.clipPathId,i=GQ(),a=m0(t,n),s=a.needClipX,c=a.needClipY,l=a.needClip,u=X(e=>XU(e,t,!1)),d=X(e=>ZU(e,n,!1));if(!l||!i)return null;var f=i.x,p=i.y,m=i.width,h=i.height,g=s&&u?Math.min(u[0],u[1]):f-m/2,_=c&&d?Math.min(d[0],d[1]):p-h/2,v=s&&u?Math.abs(u[1]-u[0]):m*2,y=c&&d?Math.abs(d[1]-d[0]):h*2;return o.createElement(`clipPath`,{id:`clipPath-${r}`},o.createElement(`rect`,{x:g,y:_,width:v,height:y}))}var g0=(e,t,n,r)=>TW(e,`xAxis`,t,r),_0=(e,t,n,r)=>wW(e,`xAxis`,t,r),v0=(e,t,n,r)=>TW(e,`yAxis`,n,r),y0=(e,t,n,r)=>wW(e,`yAxis`,n,r),ele=Z([uM,g0,v0,_0,y0],(e,t,n,r,i)=>Ej(e,`xAxis`)?Nj(t,r,!1):Nj(n,i,!1)),tle=(e,t,n,r,i)=>i;function nle(e){return e.type===`line`}var rle=Z([uM,g0,v0,_0,y0,Z([PH,tle],(e,t)=>e.filter(nle).find(e=>e.id===t)),ele,tF],(e,t,n,r,i,a,o,s)=>{var c=s.chartData,l=s.dataStartIndex,u=s.dataEndIndex;if(!(a==null||t==null||n==null||r==null||i==null||r.length===0||i.length===0||o==null||e!==`horizontal`&&e!==`vertical`)){var d=a.dataKey,f=a.data,p=f!=null&&f.length>0?f:c?.slice(l,u+1);if(p!=null)return wle({layout:e,xAxis:t,yAxis:n,xAxisTicks:r,yAxisTicks:i,dataKey:d,bandSize:o,displayedData:p})}});function ile(e){var t=EE(e),n=3,r=2;if(t!=null){var i=t.r,a=t.strokeWidth,o=Number(i),s=Number(a);return(Number.isNaN(o)||o<0)&&(o=n),(Number.isNaN(s)||s<0)&&(s=r),{r:o,strokeWidth:s}}return{r:n,strokeWidth:r}}var ale=[`id`],ole=[`type`,`layout`,`connectNulls`,`needClip`,`shape`,`strokeDasharray`],sle=[`activeDot`,`animateNewValues`,`animationBegin`,`animationDuration`,`animationEasing`,`connectNulls`,`dot`,`hide`,`isAnimationActive`,`label`,`legendType`,`xAxisId`,`yAxisId`,`id`];function b0(){return b0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},b0.apply(null,arguments)}function x0(e,t){if(e==null)return{};var n,r,i=cle(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function cle(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function S0(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function C0(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?S0(Object(n),!0).forEach(function(t){lle(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):S0(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function lle(e,t,n){return(t=ule(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ule(e){var t=dle(e,`string`);return typeof t==`symbol`?t:t+``}function dle(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function fle(e){try{return e&&e.getTotalLength&&e.getTotalLength()||0}catch{return 0}}function ple(e){var t=0,n=0;for(var r of e)r.status===`matched`&&r.prev.x!=null&&r.next.x!=null&&(t+=r.next.x-r.prev.x,n++);return n>0?t/n:0}var w0={activeDot:!0,animateNewValues:!0,animationBegin:0,animationDuration:1500,animationEasing:`ease`,animationInterpolateFn:(e,t)=>{if(e==null)return[];if(t===1)return e.flatMap(e=>e.status===`removed`?[]:[e.next]);var n=ple(e),r=[];for(var i of e)if(i.status===`matched`)r.push(C0(C0({},i.next),{},{x:oD(i.prev.x,i.next.x,t),y:oD(i.prev.y,i.next.y,t)}));else if(i.status===`added`){if(i.next.x!=null){var a=i.next.x-n;r.push(C0(C0({},i.next),{},{x:oD(a,i.next.x,t),y:i.next.y}))}else r.push(i.next)}else if(i.status===`removed`&&i.prev.x!=null){var o=i.prev.x+n;r.push(C0(C0({},i.prev),{},{x:oD(i.prev.x,o,t),y:i.prev.y}))}return r},animationMatchBy:$X,connectNulls:!1,dot:!0,fill:`#fff`,hide:!1,isAnimationActive:`auto`,label:!1,legendType:`line`,shape:qce,stroke:`#3182bd`,strokeWidth:1,xAxisId:0,yAxisId:0,zIndex:VF.line,type:`linear`},mle=e=>{var t=e.dataKey,n=e.name,r=e.stroke,i=e.legendType;return[{inactive:e.hide,dataKey:t,type:i,color:r,value:Fj(n,t),payload:e}]},hle=o.memo(e=>{var t=e.dataKey,n=e.data,r=e.stroke,i=e.strokeWidth,a=e.fill,s=e.name,c=e.hide,l=e.unit,u=e.formatter,d=e.tooltipType,f=e.id,p={dataDefinedOnItem:n,getPosition:dD,settings:{stroke:r,strokeWidth:i,fill:a,dataKey:t,nameKey:void 0,name:Fj(s,t),hide:c,type:d,color:r,unit:l,formatter:u,graphicalItemId:f}};return o.createElement(WX,{tooltipEntrySettings:p})});function gle(e){var t=e.clipPathId,n=e.points,r=e.props,i=r.dot,a=r.dataKey,s=r.needClip;r.id;var c=TE(x0(r,ale));return o.createElement(DQ,{points:n,dot:i,className:`recharts-line-dots`,dotClassName:`recharts-line-dot`,dataKey:a,baseProps:c,needClip:s,clipPathId:t})}function _le(e){var t=e.showLabels,n=e.children,r=e.points,i=(0,o.useMemo)(()=>r?.map(e=>{var t={x:e.x??0,y:e.y??0,width:0,lowerWidth:0,upperWidth:0,height:0};return C0(C0({},t),{},{value:e.value,payload:e.payload,viewBox:t,parentViewBox:void 0,fill:void 0})}),[r]);return o.createElement(KY,{value:t?i:void 0},n)}function vle(e){var t=e.clipPathId,n=e.pathRef,r=e.points,i=e.props,a=e.animationElapsedTime,s=e.isAnimating,c=e.isEntrance,l=e.visibleLength,u=i.type,d=i.layout,f=i.connectNulls,p=i.needClip,m=i.shape,h=i.strokeDasharray,g=C0(C0({},DE(x0(i,ole))),{},{fill:`none`,className:`recharts-line-curve`,clipPath:p?`url(#clipPath-${t})`:void 0,points:r,type:u,layout:d,connectNulls:f,strokeDasharray:h??i.strokeDasharray,pathRef:n,animationElapsedTime:a,isAnimating:s,isEntrance:i.animateNewValues?c:!1,visibleLength:l});return o.createElement(o.Fragment,null,r?.length>1&&o.createElement(BX,{option:m,DefaultShape:w0.shape,shapeProps:g}),o.createElement(gle,{points:r,clipPathId:t,props:i}))}function yle(e){var t=e.clipPathId,n=e.props,r=e.pathRef,i=e.previousPointsRef,a=n.points,s=n.isAnimationActive,c=n.animationBegin,l=n.animationDuration,u=n.animationEasing,d=n.animationMatchBy,f=n.animationInterpolateFn,p=n.layout,m=fle(r.current),h=mZ(n.onAnimationStart,n.onAnimationEnd),g=h.isAnimating,_=h.handleAnimationStart,v=h.handleAnimationEnd,y=!g,b=Jce(a),x=(0,o.useCallback)(e=>e>0&&m>0,[m]);return o.createElement(_le,{points:a,showLabels:y},n.children,o.createElement(hZ,{animationInput:a,animationIdPrefix:`recharts-line-`,items:a,previousItemsRef:i,isAnimationActive:s,animationBegin:c,animationDuration:l,animationEasing:u,onAnimationStart:_,onAnimationEnd:v,animationInterpolateFn:f,animationMatchBy:d,shouldUpdatePreviousRef:x,layout:p},(e,i,a)=>{var s=g||i<1,c=s?b(i,m):null;return o.createElement(vle,{props:n,points:e,clipPathId:t,pathRef:r,animationElapsedTime:i,isAnimating:s,isEntrance:a,visibleLength:c})}),o.createElement(QY,{label:n.label}))}function ble(e){var t=e.clipPathId,n=e.props,r=(0,o.useRef)(null),i=(0,o.useRef)(null);return o.createElement(yle,{props:n,clipPathId:t,previousPointsRef:r,pathRef:i})}var xle=(e,t)=>({x:e.x??void 0,y:e.y??void 0,value:e.value,errorVal:Tj(e.payload,t)}),Sle=class extends o.Component{render(){var e=this.props,t=e.hide,n=e.dot,r=e.points,i=e.className,a=e.xAxisId,s=e.yAxisId,c=e.top,l=e.left,u=e.width,d=e.height,f=e.id,p=e.needClip,m=e.zIndex;if(t)return null;var h=yE(`recharts-line`,i),g=f,_=ile(n),v=_.r,y=_.strokeWidth,b=kX(n),x=v*2+y,S=p?`url(#clipPath-${b?``:`dots-`}${g})`:void 0;return o.createElement(QK,{zIndex:m},o.createElement(RE,{className:h},p&&o.createElement(`defs`,null,o.createElement(h0,{clipPathId:g,xAxisId:a,yAxisId:s}),!b&&o.createElement(`clipPath`,{id:`clipPath-dots-${g}`},o.createElement(`rect`,{x:l-x/2,y:c-x/2,width:u+x,height:d+x}))),o.createElement(p0,{xAxisId:a,yAxisId:s,data:r,dataPointFormatter:xle,errorBarOffset:0},o.createElement(ble,{props:this.props,clipPathId:g}))),o.createElement($Q,{activeDot:this.props.activeDot,points:r,mainColor:this.props.stroke,itemDataKey:this.props.dataKey,clipPath:S}))}};function Cle(e){var t=hO(e,w0),n=t.activeDot,r=t.animateNewValues,i=t.animationBegin,a=t.animationDuration,s=t.animationEasing,c=t.connectNulls,l=t.dot,u=t.hide,d=t.isAnimationActive,f=t.label,p=t.legendType,m=t.xAxisId,h=t.yAxisId,g=t.id,_=x0(t,sle),v=m0(m,h).needClip,y=GQ(),b=dM(),x=Kj(),S=X(e=>rle(e,m,h,x,g));if(b!==`horizontal`&&b!==`vertical`||S==null||y==null)return null;var C=y.height,w=y.width,T=y.x,E=y.y;return o.createElement(Sle,b0({},_,{id:g,connectNulls:c,dot:l,activeDot:n,animateNewValues:r,animationBegin:i,animationDuration:a,animationEasing:s,isAnimationActive:d,hide:u,label:f,legendType:p,xAxisId:m,yAxisId:h,points:S,layout:b,height:C,width:w,left:T,top:E,needClip:v}))}function wle(e){var t=e.layout,n=e.xAxis,r=e.yAxis,i=e.xAxisTicks,a=e.yAxisTicks,o=e.dataKey,s=e.bandSize;return e.displayedData.map((e,c)=>{var l=Tj(e,o);if(t===`horizontal`)return{x:kj({axis:n,ticks:i,bandSize:s,entry:e,index:c}),y:(cD(l)?null:r.scale.map(l))??null,value:l,payload:e};var u=cD(l)?null:n.scale.map(l),d=kj({axis:r,ticks:a,bandSize:s,entry:e,index:c});return u==null||d==null?null:{x:u,y:d,value:l,payload:e}}).filter(Boolean)}function Tle(e){var t=hO(e,w0),n=Kj();return o.createElement(TZ,{id:t.id,type:`line`},e=>o.createElement(o.Fragment,null,o.createElement(GX,{legendPayload:mle(t)}),o.createElement(hle,{dataKey:t.dataKey,data:t.data,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,formatter:t.formatter,tooltipType:t.tooltipType,id:e}),o.createElement(FZ,{type:`line`,id:e,data:t.data,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,dataKey:t.dataKey,hide:t.hide,isPanorama:n}),o.createElement(Cle,b0({},t,{id:e}))))}var T0=o.memo(Tle,SM);T0.displayName=`Line`;function E0(e,t){return e.graphicalItems.cartesianItems.find(e=>e.id===t)?.xAxisId??0}function D0(e,t){return e.graphicalItems.cartesianItems.find(e=>e.id===t)?.yAxisId??0}var Ele=`Invariant failed`;function Dle(e,t){if(!e)throw Error(Ele)}var Ole=[`option`];function kle(e,t){if(e==null)return{};var n,r,i=Ale(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Ale(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var O0=vP;function k0(e){var t=e.option,n=kle(e,Ole);return o.createElement(BX,{option:t,DefaultShape:O0,shapeProps:n,activeClassName:`recharts-active-bar`,inActiveClassName:`recharts-inactive-bar`})}var jle=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return(n,r)=>{if(Y(e))return e;var i=Y(n)||cD(n);return i?e(n,r):(!i&&Dle(!1,`minPointSize callback function received a value with type of ${typeof n}. Currently only numbers or null/undefined are supported.`),t)}},Mle=(e,t,n)=>n,A0=Z([PH,(e,t)=>t],(e,t)=>e.filter(e=>e.type===`bar`).find(e=>e.id===t)),Nle=Z([A0],e=>e?.maxBarSize),Ple=(e,t,n,r)=>r,Fle=Z([uM,PH,E0,D0,Mle],(e,t,n,r,i)=>t.filter(t=>e===`horizontal`?t.xAxisId===n:t.yAxisId===r).filter(e=>e.isPanorama===i).filter(e=>e.hide===!1).filter(e=>e.type===`bar`)),Ile=(e,t,n)=>{var r=uM(e),i=E0(e,t),a=D0(e,t);if(i!=null&&a!=null)return r===`horizontal`?oU(e,`yAxis`,a,n):oU(e,`xAxis`,i,n)},Lle=Z([Fle,PF,(e,t)=>{var n=uM(e),r=E0(e,t),i=D0(e,t);if(r!=null&&i!=null)return n===`horizontal`?yW(e,`xAxis`,r):yW(e,`yAxis`,i)}],s$),Rle=(e,t,n)=>{var r=A0(e,t);if(r==null)return 0;var i=E0(e,t),a=D0(e,t);if(i==null||a==null)return 0;var o=uM(e),s=jF(e),c=r.maxBarSize,l=cD(c)?s:c,u,d;return o===`horizontal`?(u=TW(e,`xAxis`,i,n),d=wW(e,`xAxis`,i,n)):(u=TW(e,`yAxis`,a,n),d=wW(e,`yAxis`,a,n)),Nj(u,d,!0)??l??0},j0=(e,t,n)=>{var r=uM(e),i=E0(e,t),a=D0(e,t);if(i!=null&&a!=null){var o,s;return r===`horizontal`?(o=TW(e,`xAxis`,i,n),s=wW(e,`xAxis`,i,n)):(o=TW(e,`yAxis`,a,n),s=wW(e,`yAxis`,a,n)),Nj(o,s)}},zle=Z([Wj,Gj,(e,t,n)=>{var r=E0(e,t);if(r!=null)return TW(e,`xAxis`,r,n)},(e,t,n)=>{var r=D0(e,t);if(r!=null)return TW(e,`yAxis`,r,n)},(e,t,n)=>{var r=E0(e,t);if(r!=null)return wW(e,`xAxis`,r,n)},(e,t,n)=>{var r=D0(e,t);if(r!=null)return wW(e,`yAxis`,r,n)},Z([Z([Lle,jF,MF,NF,Rle,j0,Nle],m$),A0],g$),uM,nF,j0,Z([Ile,A0],h$),A0,Ple],(e,t,n,r,i,a,o,s,c,l,u,d,f)=>{var p=c.chartData,m=c.dataStartIndex,h=c.dataEndIndex;if(!(d==null||o==null||t==null||s!==`horizontal`&&s!==`vertical`||n==null||r==null||i==null||a==null||l==null)){var g=d.data,_=g!=null&&g.length>0?g:p?.slice(m,h+1);if(_!=null)return vue({layout:s,barSettings:d,pos:o,parentViewBox:t,bandSize:l,xAxis:n,yAxis:r,xAxisTicks:i,yAxisTicks:a,stackedData:u,displayedData:_,offset:e,cells:f,dataStartIndex:m})}}),Ble=[`index`];function M0(){return M0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},M0.apply(null,arguments)}function Vle(e,t){if(e==null)return{};var n,r,i=Hle(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Hle(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var N0=(0,o.createContext)(void 0),Ule=e=>{var t=(0,o.useContext)(N0);if(t!=null)return t.stackId;if(e!=null)return rse(e)},Wle=(e,t)=>`recharts-bar-stack-clip-path-${e}-${t}`,Gle=e=>{var t=(0,o.useContext)(N0);if(t!=null){var n=t.stackId;return`url(#${Wle(n,e)})`}},P0=e=>{var t=e.index,n=Vle(e,Ble),r=Gle(t);return o.createElement(RE,M0({className:`recharts-bar-stack-layer`,clipPath:r},n))},Kle=[`onMouseEnter`,`onMouseLeave`,`onClick`],qle=[`value`,`background`,`tooltipPosition`],Jle=[`id`],Yle=[`onMouseEnter`,`onClick`,`onMouseLeave`];function F0(e,t){return $le(e)||Qle(e,t)||Zle(e,t)||Xle()}function Xle(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
65
65
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Zle(e,t){if(e){if(typeof e==`string`)return I0(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?I0(e,t):void 0}}function I0(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function Qle(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function $le(e){if(Array.isArray(e))return e}function L0(){return L0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},L0.apply(null,arguments)}function R0(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function z0(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?R0(Object(n),!0).forEach(function(t){eue(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):R0(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function eue(e,t,n){return(t=tue(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function tue(e){var t=nue(e,`string`);return typeof t==`symbol`?t:t+``}function nue(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function B0(e,t){if(e==null)return{};var n,r,i=rue(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function rue(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var iue=e=>{var t=e.dataKey,n=e.name,r=e.fill,i=e.legendType;return[{inactive:e.hide,dataKey:t,type:i,color:r,value:Fj(n,t),payload:e}]},aue=o.memo(e=>{var t=e.dataKey,n=e.stroke,r=e.strokeWidth,i=e.fill,a=e.name,s=e.hide,c=e.unit,l=e.formatter,u=e.tooltipType,d=e.id,f={dataDefinedOnItem:void 0,getPosition:dD,settings:{stroke:n,strokeWidth:r,fill:i,dataKey:t,nameKey:void 0,name:Fj(a,t),hide:s,type:u,color:i,unit:c,formatter:l,graphicalItemId:d}};return o.createElement(WX,{tooltipEntrySettings:f})});function oue(e){var t=X(JG),n=e.data,r=e.dataKey,i=e.background,a=e.allOtherBarProps,s=a.onMouseEnter,c=a.onMouseLeave,l=a.onClick,u=B0(a,Kle),d=VX(s,r,a.id),f=HX(c),p=UX(l,r,a.id);if(!i||n==null)return null;var m=EE(i);return o.createElement(QK,{zIndex:_$(i,VF.barBackground)},n.map((e,n)=>{e.value;var a=e.background;e.tooltipPosition;var s=B0(e,qle);if(!a)return null;var c=d(e,e.originalDataIndex),l=f(e,e.originalDataIndex),h=p(e,e.originalDataIndex),g=z0(z0(z0(z0(z0({option:i,isActive:String(e.originalDataIndex)===t},s),{},{fill:`#eee`},a),m),pO(u,e,n)),{},{onMouseEnter:c,onMouseLeave:l,onClick:h,dataKey:r,index:n,className:`recharts-bar-background-rectangle`});return o.createElement(k0,L0({key:`background-bar-${n}`},g))}))}function sue(e){var t=e.showLabels,n=e.children,r=e.rects?.map(e=>{var t={x:e.x,y:e.y,width:e.width,lowerWidth:e.width,upperWidth:e.width,height:e.height};return z0(z0({},t),{},{value:e.value,payload:e.payload,parentViewBox:e.parentViewBox,viewBox:t,fill:e.fill})});return o.createElement(KY,{value:t?r:void 0},n)}function cue(e){var t=e.shape,n=e.activeBar,r=e.baseProps,i=e.entry,a=e.index,s=e.dataKey,c=X(JG),l=X(XG),u=n&&String(i.originalDataIndex)===c&&(l==null||s===l),d=c!=null&&(String(i.originalDataIndex)!==c||l!=null&&s!==l),f=F0((0,o.useState)(!1),2),p=f[0],m=f[1],h=F0((0,o.useState)(!1),2),g=h[0],_=h[1];(0,o.useEffect)(()=>{var e;return u?(m(!0),e=requestAnimationFrame(()=>{_(!0)})):(_(!1),d&&m(!1)),()=>{cancelAnimationFrame(e)}},[u,d]);var v=(0,o.useCallback)(()=>{u||m(!1)},[u]),y=u&&g,b=u||p,x=u?n===!0?t:n:t,S=o.createElement(k0,L0({},r,{name:String(r.name)},i,{isActive:y,option:x,index:a,dataKey:s,animationElapsedTime:e.animationElapsedTime,isAnimating:e.isAnimating,isEntrance:e.isEntrance,onTransitionEnd:v}));return b?o.createElement(QK,{zIndex:VF.activeBar},o.createElement(P0,{index:i.originalDataIndex},S)):S}function lue(e){var t=e.shape,n=e.baseProps,r=e.entry,i=e.index,a=e.dataKey;return o.createElement(k0,L0({},n,{name:String(n.name)},r,{isActive:!1,option:t,index:i,dataKey:a,animationElapsedTime:e.animationElapsedTime,isAnimating:e.isAnimating,isEntrance:e.isEntrance}))}function uue(e){var t=e.data,n=e.props,r=e.animationElapsedTime,i=e.isAnimating,a=e.isEntrance,s=TE(n)??{},c=s.id,l=B0(s,Jle),u=n.shape,d=n.dataKey,f=n.activeBar,p=n.onMouseEnter,m=n.onClick,h=n.onMouseLeave,g=B0(n,Yle),_=VX(p,d,c),v=HX(h),y=UX(m,d,c);return t?o.createElement(o.Fragment,null,t.map((e,t)=>o.createElement(P0,L0({index:e.originalDataIndex,key:`rectangle-${e?.x}-${e?.y}-${e?.value}-${t}`,className:`recharts-bar-rectangle`},pO(g,e,t),{onMouseEnter:_(e,e.originalDataIndex),onMouseLeave:v(e,e.originalDataIndex),onClick:y(e,e.originalDataIndex)}),f?o.createElement(cue,{shape:u,activeBar:f,baseProps:l,entry:e,index:t,dataKey:d,animationElapsedTime:r,isAnimating:i,isEntrance:a}):o.createElement(lue,{shape:u,baseProps:l,entry:e,index:t,dataKey:d,animationElapsedTime:r,isAnimating:i,isEntrance:a})))):null}var due=(e,t,n)=>e==null?[]:t===1?e.flatMap(e=>e.status===`removed`?[]:[e.next]):e.flatMap(e=>{if(e.status===`removed`)return n===`horizontal`?[z0(z0({},e.prev),{},{height:oD(e.prev.height,0,t),y:oD(e.prev.y,e.prev.y+e.prev.height,t)})]:[z0(z0({},e.prev),{},{width:oD(e.prev.width,0,t)})];if(e.status===`matched`)return[z0(z0({},e.next),{},{x:oD(e.prev.x,e.next.x,t),y:oD(e.prev.y,e.next.y,t),width:oD(e.prev.width,e.next.width,t),height:oD(e.prev.height,e.next.height,t)})];var r=e.next;return n===`horizontal`?[z0(z0({},r),{},{height:oD(0,r.height,t),y:oD(r.stackedBarStart,r.y,t)})]:[z0(z0({},r),{},{width:oD(0,r.width,t),x:oD(r.stackedBarStart,r.x,t)})]});function fue(e){var t=e.props,n=e.previousRectanglesRef,r=t.data,i=t.isAnimationActive,a=t.animationBegin,s=t.animationDuration,c=t.animationEasing,l=t.animationInterpolateFn,u=t.layout,d=mZ(t.onAnimationStart,t.onAnimationEnd),f=d.isAnimating,p=d.handleAnimationStart,m=d.handleAnimationEnd;return o.createElement(sue,{showLabels:!f,rects:r},o.createElement(hZ,{animationInput:r,animationIdPrefix:`recharts-bar-`,items:r,previousItemsRef:n,isAnimationActive:i,animationBegin:a,animationDuration:s,animationEasing:c,onAnimationStart:p,onAnimationEnd:m,animationInterpolateFn:l,animationMatchBy:t.animationMatchBy,layout:u},(e,n,r)=>o.createElement(RE,null,o.createElement(uue,{props:t,data:e,animationElapsedTime:n,isAnimating:f||n<1,isEntrance:r}))),o.createElement(QY,{label:t.label}),t.children)}function pue(e){var t=(0,o.useRef)(null);return o.createElement(fue,{previousRectanglesRef:t,props:e})}var V0=0,mue=(e,t)=>{var n=Array.isArray(e.value)?e.value[1]:e.value;return{x:e.x,y:e.y,value:n,errorVal:Tj(e,t)}},hue=class extends o.PureComponent{render(){var e=this.props,t=e.hide,n=e.data,r=e.dataKey,i=e.className,a=e.xAxisId,s=e.yAxisId,c=e.needClip,l=e.background,u=e.id;if(t||n==null)return null;var d=yE(`recharts-bar`,i),f=u;return o.createElement(RE,{className:d,id:u},c&&o.createElement(`defs`,null,o.createElement(h0,{clipPathId:f,xAxisId:a,yAxisId:s})),o.createElement(RE,{className:`recharts-bar-rectangles`,clipPath:c?`url(#clipPath-${f})`:void 0},o.createElement(oue,{data:n,dataKey:r,background:l,allOtherBarProps:this.props}),o.createElement(pue,this.props)))}},gue={activeBar:!1,animationBegin:0,animationDuration:400,animationEasing:`ease`,animationInterpolateFn:due,animationMatchBy:eZ,background:!1,hide:!1,isAnimationActive:`auto`,label:!1,legendType:`rect`,minPointSize:V0,shape:O0,xAxisId:0,yAxisId:0,zIndex:VF.bar};function _ue(e){var t=e.xAxisId,n=e.yAxisId,r=e.hide,i=e.legendType,a=e.minPointSize,s=e.activeBar,c=e.animationBegin,l=e.animationDuration,u=e.animationEasing,d=e.isAnimationActive,f=m0(t,n).needClip,p=dM(),m=Kj(),h=OX(e.children,Qq),g=X(t=>zle(t,e.id,m,h));if(p!==`vertical`&&p!==`horizontal`)return null;var _,v=g?.[0];return _=v==null||v.height==null||v.width==null?0:p===`vertical`?v.height/2:v.width/2,o.createElement(p0,{xAxisId:t,yAxisId:n,data:g,dataPointFormatter:mue,errorBarOffset:_},o.createElement(hue,L0({},e,{layout:p,needClip:f,data:g,xAxisId:t,yAxisId:n,hide:r,legendType:i,minPointSize:a,activeBar:s,animationBegin:c,animationDuration:l,animationEasing:u,isAnimationActive:d})))}function vue(e){var t=e.layout,n=e.barSettings,r=n.dataKey,i=n.minPointSize,a=n.hasCustomShape,o=e.pos,s=e.bandSize,c=e.xAxis,l=e.yAxis,u=e.xAxisTicks,d=e.yAxisTicks,f=e.stackedData,p=e.displayedData,m=e.offset,h=e.cells,g=e.parentViewBox,_=e.dataStartIndex,v=t===`horizontal`?l:c,y=f?v.scale.domain():null,b=ise({numericAxis:v}),x=v.scale.map(b);return p.map((e,n)=>{var p,v,S,C,w,T;if(f){var E=f[n+_];if(E==null)return null;p=ese(E,y)}else p=Tj(e,r),Array.isArray(p)||(p=[b,p]);var D=jle(i,V0)(p[1],n);if(t===`horizontal`){var O=l.scale.map(p[0]),k=l.scale.map(p[1]);if(O==null||k==null)return null;v=Aj({axis:c,ticks:u,bandSize:s,offset:o.offset,entry:e,index:n}),S=k??O??void 0,C=o.size;var A=O-k;if(w=$E(A)?0:A,T={x:v,y:m.top,width:C,height:m.height},Math.abs(D)>0&&Math.abs(w)<Math.abs(D)){var j=QE(w||D)*(Math.abs(D)-Math.abs(w));S-=j,w+=j}}else{var M=c.scale.map(p[0]),N=c.scale.map(p[1]);if(M==null||N==null)return null;if(v=M,S=Aj({axis:l,ticks:d,bandSize:s,offset:o.offset,entry:e,index:n}),C=N-M,w=o.size,T={x:m.left,y:S,width:m.width,height:w},Math.abs(D)>0&&Math.abs(C)<Math.abs(D)){var ee=QE(C||D)*(Math.abs(D)-Math.abs(C));C+=ee}}return v==null||S==null||C==null||w==null||!a&&(C===0||w===0)?null:z0(z0({},e),{},{stackedBarStart:x,x:v,y:S,width:C,height:w,value:f?p:p[1],payload:e,background:T,tooltipPosition:{x:v+C/2,y:S+w/2},parentViewBox:g,originalDataIndex:n},h&&h[n]&&h[n].props)}).filter(Boolean)}function yue(e){var t=hO(e,gue),n=Ule(t.stackId),r=Kj();return o.createElement(TZ,{id:t.id,type:`bar`},e=>o.createElement(o.Fragment,null,o.createElement(GX,{legendPayload:iue(t)}),o.createElement(aue,{dataKey:t.dataKey,stroke:t.stroke,strokeWidth:t.strokeWidth,fill:t.fill,name:t.name,hide:t.hide,unit:t.unit,formatter:t.formatter,tooltipType:t.tooltipType,id:e}),o.createElement(FZ,{type:`bar`,id:e,data:void 0,xAxisId:t.xAxisId,yAxisId:t.yAxisId,zAxisId:0,dataKey:t.dataKey,stackId:n,hide:t.hide,barSize:t.barSize,minPointSize:t.minPointSize,maxBarSize:t.maxBarSize,isPanorama:r,hasCustomShape:t.shape!=null&&t.shape!==O0}),o.createElement(QK,{zIndex:t.zIndex},o.createElement(_ue,L0({},t,{id:e})))))}var H0=o.memo(yue,SM);H0.displayName=`Bar`;var bue=[`domain`,`range`],xue=[`domain`,`range`];function U0(e,t){if(e==null)return{};var n,r,i=Sue(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Sue(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function W0(e,t){return e===t?!0:Array.isArray(e)&&e.length===2&&Array.isArray(t)&&t.length===2?e[0]===t[0]&&e[1]===t[1]:!1}function G0(e,t){if(e===t)return!0;var n=e.domain,r=e.range,i=U0(e,bue),a=t.domain,o=t.range,s=U0(t,xue);return!W0(n,a)||!W0(r,o)?!1:SM(i,s)}var Cue=[`type`],wue=[`dangerouslySetInnerHTML`,`ticks`,`scale`],Tue=[`id`,`scale`];function K0(){return K0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},K0.apply(null,arguments)}function q0(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function J0(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?q0(Object(n),!0).forEach(function(t){Eue(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):q0(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Eue(e,t,n){return(t=Due(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Due(e){var t=Oue(e,`string`);return typeof t==`symbol`?t:t+``}function Oue(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Y0(e,t){if(e==null)return{};var n,r,i=kue(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function kue(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Aue(e){var t=rk(),n=(0,o.useRef)(null),r=fM(),i=e.type,a=Y0(e,Cue),s=GF(r,`xAxis`,i),c=(0,o.useMemo)(()=>{if(s!=null)return J0(J0({},a),{},{type:s})},[a,s]);return(0,o.useLayoutEffect)(()=>{c!=null&&(n.current===null?t(FQ(c)):n.current!==c&&t(IQ({prev:n.current,next:c})),n.current=c)},[c,t]),(0,o.useLayoutEffect)(()=>()=>{n.current&&=(t(LQ(n.current)),null)},[t]),null}var jue=e=>{var t=e.xAxisId,n=e.className,r=e.height,i=e.label,a=(0,o.useRef)(null),s=(0,o.useRef)(null),c=X(Gj),l=Kj(),u=rk(),d=`xAxis`,f=X(e=>CW(e,d,t,l)),p=X(e=>dW(e,t)),m=X(e=>gW(e,t)),h=X(e=>SH(e,t));if((0,o.useLayoutEffect)(()=>{if(!(r!==`auto`||!p||kY(i)||(0,o.isValidElement)(i)||h==null)){var e=a.current;if(e){var n=e.getCalculatedHeight();Math.round(p.height)!==Math.round(n)&&u(HQ({id:t,height:n}))}}},[f,p,u,i,t,r,h]),p==null||m==null||h==null)return null;e.dangerouslySetInnerHTML,e.ticks,e.scale;var g=Y0(e,wue);h.id,h.scale;var _=Y0(h,Tue);return o.createElement(N1,K0({},g,_,{ref:a,labelRef:s,x:m.x,y:m.y,width:p.width,height:p.height,className:yE(`recharts-${d} ${d}`,n),viewBox:c,ticks:f,axisType:d,axisId:t}))},Mue={allowDataOverflow:xH.allowDataOverflow,allowDecimals:xH.allowDecimals,allowDuplicatedCategory:xH.allowDuplicatedCategory,angle:xH.angle,axisLine:w1.axisLine,height:xH.height,hide:!1,includeHidden:xH.includeHidden,interval:xH.interval,label:!1,minTickGap:xH.minTickGap,mirror:xH.mirror,orientation:xH.orientation,padding:xH.padding,reversed:xH.reversed,scale:xH.scale,tick:xH.tick,tickCount:xH.tickCount,tickLine:w1.tickLine,tickSize:w1.tickSize,type:xH.type,niceTicks:xH.niceTicks,xAxisId:0},X0=o.memo(e=>{var t=hO(e,Mue);return o.createElement(o.Fragment,null,o.createElement(Aue,{allowDataOverflow:t.allowDataOverflow,allowDecimals:t.allowDecimals,allowDuplicatedCategory:t.allowDuplicatedCategory,angle:t.angle,dataKey:t.dataKey,domain:t.domain,height:t.height,hide:t.hide,id:t.xAxisId,includeHidden:t.includeHidden,interval:t.interval,minTickGap:t.minTickGap,mirror:t.mirror,name:t.name,orientation:t.orientation,padding:t.padding,reversed:t.reversed,scale:t.scale,tick:t.tick,tickCount:t.tickCount,tickFormatter:t.tickFormatter,ticks:t.ticks,type:t.type,unit:t.unit,niceTicks:t.niceTicks}),o.createElement(jue,t))},G0);X0.displayName=`XAxis`;var Nue=[`type`],Pue=[`dangerouslySetInnerHTML`,`ticks`,`scale`],Fue=[`id`,`scale`];function Z0(){return Z0=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},Z0.apply(null,arguments)}function Q0(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function $0(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Q0(Object(n),!0).forEach(function(t){Iue(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Q0(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Iue(e,t,n){return(t=Lue(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Lue(e){var t=Rue(e,`string`);return typeof t==`symbol`?t:t+``}function Rue(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function e2(e,t){if(e==null)return{};var n,r,i=zue(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function zue(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function Bue(e){var t=rk(),n=(0,o.useRef)(null),r=fM(),i=e.type,a=e2(e,Nue),s=GF(r,`yAxis`,i),c=(0,o.useMemo)(()=>{if(s!=null)return $0($0({},a),{},{type:s})},[s,a]);return(0,o.useLayoutEffect)(()=>{c!=null&&(n.current===null?t(RQ(c)):n.current!==c&&t(zQ({prev:n.current,next:c})),n.current=c)},[c,t]),(0,o.useLayoutEffect)(()=>()=>{n.current&&=(t(BQ(n.current)),null)},[t]),null}function Vue(e){var t=e.yAxisId,n=e.className,r=e.width,i=e.label,a=(0,o.useRef)(null),s=(0,o.useRef)(null),c=X(Gj),l=Kj(),u=rk(),d=`yAxis`,f=X(e=>vW(e,t)),p=X(e=>_W(e,t)),m=X(e=>CW(e,d,t,l)),h=X(e=>TH(e,t));if((0,o.useLayoutEffect)(()=>{if(!(r!==`auto`||!f||kY(i)||(0,o.isValidElement)(i)||h==null)){var e=a.current;if(e){var n=e.getCalculatedWidth();Math.round(f.width)!==Math.round(n)&&u(VQ({id:t,width:n}))}}},[m,f,u,i,t,r,h]),f==null||p==null||h==null)return null;e.dangerouslySetInnerHTML,e.ticks,e.scale;var g=e2(e,Pue);h.id,h.scale;var _=e2(h,Fue);return o.createElement(N1,Z0({},g,_,{ref:a,labelRef:s,x:p.x,y:p.y,tickTextProps:r===`auto`?{width:void 0}:{width:r},width:f.width,height:f.height,className:yE(`recharts-${d} ${d}`,n),viewBox:c,ticks:m,axisType:d,axisId:t}))}var Hue={allowDataOverflow:wH.allowDataOverflow,allowDecimals:wH.allowDecimals,allowDuplicatedCategory:wH.allowDuplicatedCategory,angle:wH.angle,axisLine:w1.axisLine,hide:!1,includeHidden:wH.includeHidden,interval:wH.interval,label:!1,minTickGap:wH.minTickGap,mirror:wH.mirror,orientation:wH.orientation,padding:wH.padding,reversed:wH.reversed,scale:wH.scale,tick:wH.tick,tickCount:wH.tickCount,tickLine:w1.tickLine,tickSize:w1.tickSize,type:wH.type,niceTicks:wH.niceTicks,width:wH.width,yAxisId:0},t2=o.memo(e=>{var t=hO(e,Hue);return o.createElement(o.Fragment,null,o.createElement(Bue,{interval:t.interval,id:t.yAxisId,scale:t.scale,type:t.type,domain:t.domain,allowDataOverflow:t.allowDataOverflow,dataKey:t.dataKey,allowDuplicatedCategory:t.allowDuplicatedCategory,allowDecimals:t.allowDecimals,tickCount:t.tickCount,padding:t.padding,includeHidden:t.includeHidden,reversed:t.reversed,ticks:t.ticks,width:t.width,orientation:t.orientation,mirror:t.mirror,hide:t.hide,unit:t.unit,name:t.name,angle:t.angle,minTickGap:t.minTickGap,tick:t.tick,tickFormatter:t.tickFormatter,niceTicks:t.niceTicks}),o.createElement(Vue,t))},G0);t2.displayName=`YAxis`;var n2=Z([(e,t)=>t,uM,sI,gI,VG,UG,SK,Wj],PK);function Uue(e){return`getBBox`in e.currentTarget&&typeof e.currentTarget.getBBox==`function`}function r2(e){var t=e.currentTarget.getBoundingClientRect(),n,r;if(Uue(e)){var i=e.currentTarget.getBBox();n=i.width>0?t.width/i.width:1,r=i.height>0?t.height/i.height:1}else{var a=e.currentTarget;n=a.offsetWidth>0?t.width/a.offsetWidth:1,r=a.offsetHeight>0?t.height/a.offsetHeight:1}var o=(e,i)=>({relativeX:Math.round((e-t.left)/n),relativeY:Math.round((i-t.top)/r)});return`touches`in e?Array.from(e.touches).map(e=>o(e.clientX,e.clientY)):o(e.clientX,e.clientY)}var i2=LA(`mouseClick`),a2=_j();a2.startListening({actionCreator:i2,effect:(e,t)=>{var n=e.payload,r=n2(t.getState(),r2(n));r?.activeIndex!=null&&t.dispatch(KW({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}});var o2=LA(`mouseMove`),s2=_j(),c2=null,l2=null,u2=null;s2.startListening({actionCreator:o2,effect:(e,t)=>{var n=e.payload,r=t.getState().eventSettings,i=r.throttleDelay,a=r.throttledEvents,o=a===`all`||a?.includes(`mousemove`);c2!==null&&(cancelAnimationFrame(c2),c2=null),l2!==null&&(typeof i!=`number`||!o)&&(clearTimeout(l2),l2=null),u2=r2(n);var s=()=>{var e=t.getState(),n=AW(e,e.tooltip.settings.shared);if(!u2){c2=null,l2=null;return}if(n===`axis`){var r=n2(e,u2);r?.activeIndex==null?t.dispatch(UW()):t.dispatch(GW({activeIndex:r.activeIndex,activeDataKey:void 0,activeCoordinate:r.activeCoordinate}))}c2=null,l2=null};if(!o){s();return}i===`raf`?c2=requestAnimationFrame(s):typeof i==`number`&&l2===null&&(l2=setTimeout(s,i))}});function Wue(e,t){return t instanceof HTMLElement?`HTMLElement <${t.tagName} class="${t.className}">`:t===window?`global.window`:e===`children`&&typeof t==`object`&&t?`<<CHILDREN>>`:t}var d2={accessibilityLayer:!0,barCategoryGap:`10%`,barGap:4,barSize:void 0,className:void 0,maxBarSize:void 0,stackOffset:`none`,syncId:void 0,syncMethod:`index`,baseValue:void 0,reverseStackOrder:!1},f2=KA({name:`rootProps`,initialState:d2,reducers:{updateOptions:(e,t)=>{e.accessibilityLayer=t.payload.accessibilityLayer,e.barCategoryGap=t.payload.barCategoryGap,e.barGap=t.payload.barGap??d2.barGap,e.barSize=t.payload.barSize,e.maxBarSize=t.payload.maxBarSize,e.stackOffset=t.payload.stackOffset,e.syncId=t.payload.syncId,e.syncMethod=t.payload.syncMethod,e.className=t.payload.className,e.baseValue=t.payload.baseValue,e.reverseStackOrder=t.payload.reverseStackOrder}}}),Gue=f2.reducer,Kue=f2.actions.updateOptions,p2=KA({name:`polarOptions`,initialState:null,reducers:{updatePolarOptions:(e,t)=>e===null?t.payload:(e.startAngle=t.payload.startAngle,e.endAngle=t.payload.endAngle,e.cx=t.payload.cx,e.cy=t.payload.cy,e.innerRadius=t.payload.innerRadius,e.outerRadius=t.payload.outerRadius,e)}}),que=p2.actions.updatePolarOptions,Jue=p2.reducer,m2=LA(`keyDown`),h2=LA(`focus`),g2=LA(`blur`),_2=_j(),v2=null,y2=null,b2=null;_2.startListening({actionCreator:m2,effect:(e,t)=>{b2=e.payload,v2!==null&&(cancelAnimationFrame(v2),v2=null);var n=t.getState().eventSettings,r=n.throttleDelay,i=n.throttledEvents,a=i===`all`||i.includes(`keydown`);y2!==null&&(typeof r!=`number`||!a)&&(clearTimeout(y2),y2=null);var o=()=>{try{var e=t.getState();if(e.rootProps.accessibilityLayer===!1)return;var n=e.tooltip.keyboardInteraction,r=b2;if(r!==`ArrowRight`&&r!==`ArrowLeft`&&r!==`Enter`)return;var i=sG(n,kG(e),rU(e),RG(e)),a=i==null?-1:Number(i),o=!Number.isFinite(a)||a<0,s=UG(e),c=kG(e),l=AW(e,e.tooltip.settings.shared);if(r===`Enter`){if(o)return;var u=DK(e,l,`hover`,String(n.index));t.dispatch(JW({active:!n.active,activeIndex:n.index,activeCoordinate:u}));return}var d=EW(e)===`left-to-right`?1:-1,f=r===`ArrowRight`?1:-1,p;if(o){var m=rU(e),h=RG(e),g=f*d,_=e=>({active:!1,index:String(e),dataKey:void 0,graphicalItemId:void 0,coordinate:void 0});if(p=-1,g>0){for(var v=0;v<c.length;v++)if(sG(_(v),c,m,h)!=null){p=v;break}}else for(var y=c.length-1;y>=0;y--)if(sG(_(y),c,m,h)!=null){p=y;break}if(p<0)return}else{p=a+f*d;var b=s?.length||c.length;if(b===0||p>=b||p<0)return}var x=DK(e,l,`hover`,String(p));t.dispatch(JW({active:!0,activeIndex:p.toString(),activeCoordinate:x}))}finally{v2=null,y2=null}};if(!a){o();return}r===`raf`?v2=requestAnimationFrame(o):typeof r==`number`&&y2===null&&(o(),b2=null,y2=setTimeout(()=>{b2?o():(y2=null,v2=null)},r))}}),_2.startListening({actionCreator:h2,effect:(e,t)=>{var n=t.getState();if(n.rootProps.accessibilityLayer!==!1){var r=n.tooltip.keyboardInteraction;if(!r.active&&r.index==null){var i=`0`,a=DK(n,AW(n,n.tooltip.settings.shared),`hover`,String(i));t.dispatch(JW({active:!0,activeIndex:i,activeCoordinate:a}))}}}}),_2.startListening({actionCreator:g2,effect:(e,t)=>{var n=t.getState();if(n.rootProps.accessibilityLayer!==!1){var r=n.tooltip.keyboardInteraction;r.active&&t.dispatch(JW({active:!1,activeIndex:r.index,activeCoordinate:r.coordinate}))}}});function x2(e){e.persist();var t=e.currentTarget;return new Proxy(e,{get:(e,n)=>{if(n===`currentTarget`)return t;var r=Reflect.get(e,n);return typeof r==`function`?r.bind(e):r}})}var S2=LA(`externalEvent`),C2=_j(),w2=new Map,T2=new Map,E2=new Map;C2.startListening({actionCreator:S2,effect:(e,t)=>{var n=e.payload,r=n.handler,i=n.reactEvent;if(r!=null){var a=i.type,o=x2(i);E2.set(a,{handler:r,reactEvent:o});var s=w2.get(a);s!==void 0&&(cancelAnimationFrame(s),w2.delete(a));var c=t.getState().eventSettings,l=c.throttleDelay,u=c.throttledEvents,d=u===`all`||u?.includes(a),f=T2.get(a);f!==void 0&&(typeof l!=`number`||!d)&&(clearTimeout(f),T2.delete(a));var p=()=>{var e=E2.get(a);try{if(!e)return;var n=e.handler,r=e.reactEvent,i=t.getState(),o={activeCoordinate:$G(i),activeDataKey:XG(i),activeIndex:JG(i),activeLabel:YG(i),activeTooltipIndex:JG(i),isTooltipActive:eK(i)};n&&n(o,r)}finally{w2.delete(a),T2.delete(a),E2.delete(a)}};if(!d){p();return}if(l===`raf`){var m=requestAnimationFrame(p);w2.set(a,m)}else if(typeof l==`number`){if(!T2.has(a)){p();var h=setTimeout(p,l);T2.set(a,h)}}else p()}}});var Yue=Z([Z([dG],e=>e.tooltipItemPayloads),(e,t)=>t,(e,t,n)=>n],(e,t,n)=>{if(t!=null){var r=e.find(e=>e.settings.graphicalItemId===n);if(r!=null){var i=r.getPosition;if(i!=null)return i(t)}}}),D2=LA(`touchMove`),O2=_j(),k2=null,A2=null,j2=null,M2=null;O2.startListening({actionCreator:D2,effect:(e,t)=>{var n=e.payload;if(n.touches!=null&&n.touches.length!==0){M2=x2(n);var r=t.getState().eventSettings,i=r.throttleDelay,a=r.throttledEvents,o=a===`all`||a.includes(`touchmove`);k2!==null&&(cancelAnimationFrame(k2),k2=null),A2!==null&&(typeof i!=`number`||!o)&&(clearTimeout(A2),A2=null),j2=Array.from(n.touches).map(e=>r2({clientX:e.clientX,clientY:e.clientY,currentTarget:n.currentTarget}));var s=()=>{if(M2!=null){var e=t.getState(),n=AW(e,e.tooltip.settings.shared);if(n===`axis`){var r=j2?.[0];if(r==null){k2=null,A2=null;return}var i=n2(e,r);i?.activeIndex!=null&&t.dispatch(GW({activeIndex:i.activeIndex,activeDataKey:void 0,activeCoordinate:i.activeCoordinate}))}else if(n===`item`){var a=M2.touches[0];if(document.elementFromPoint==null||a==null)return;var o=document.elementFromPoint(a.clientX,a.clientY);if(!o||!o.getAttribute)return;var s=o.getAttribute(Vj),c=o.getAttribute(`data-recharts-item-id`)??void 0,l=TG(e).find(e=>e.id===c);if(s==null||l==null||c==null)return;var u=l.dataKey,d=Yue(e,s,c);t.dispatch(VW({activeDataKey:u,activeIndex:s,activeCoordinate:d,activeGraphicalItemId:c}))}k2=null,A2=null}};if(!o){s();return}i===`raf`?k2=requestAnimationFrame(s):typeof i==`number`&&A2===null&&(s(),M2=null,A2=setTimeout(()=>{M2?s():(A2=null,k2=null)},i))}}});var N2={throttleDelay:`raf`,throttledEvents:[`mousemove`,`touchmove`,`pointermove`,`scroll`,`wheel`]},P2=KA({name:`eventSettings`,initialState:N2,reducers:{setEventSettings:(e,t)=>{t.payload.throttleDelay!=null&&(e.throttleDelay=t.payload.throttleDelay),t.payload.throttledEvents!=null&&(e.throttledEvents=FA(t.payload.throttledEvents))}}}),Xue=P2.actions.setEventSettings,Zue=P2.reducer,Que=wk({brush:x$,cartesianAxis:UQ,chartData:Cq,errorBars:Yce,eventSettings:Zue,graphicalItems:PZ,layout:Yoe,legend:qse,options:gq,polarAxis:lX,polarOptions:Jue,referenceElements:E$,renderedTicks:c1,rootProps:Gue,tooltip:YW,zIndex:ZK}),$ue=function(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Chart`;return xoe({reducer:Que,preloadedState:e,middleware:e=>e({serializableCheck:!1,immutableCheck:![`commonjs`,`es6`,`production`].includes(`es6`)}).concat([a2.middleware,s2.middleware,_2.middleware,C2.middleware,O2.middleware]),enhancers:e=>{var t=e;return typeof e==`function`&&(t=e()),t.concat(WA({type:`raf`}))},devTools:AM.devToolsEnabled&&{serialize:{replacer:Wue},name:`recharts-${t}`}})};function F2(e){var t=e.preloadedState,n=e.children,r=e.reduxStoreName,i=Kj(),a=(0,o.useRef)(null);if(i)return n;a.current??=$ue(t,r);var s=nk;return o.createElement(sce,{context:s,store:a.current},n)}function ede(e){var t=e.layout,n=e.margin,r=rk(),i=Kj();return(0,o.useEffect)(()=>{i||(r(Koe(t)),r(Goe(n)))},[r,i,t,n]),null}var I2=(0,o.memo)(ede,SM);function L2(e){var t=rk();return(0,o.useEffect)(()=>{t(Kue(e))},[t,e]),null}var R2=(0,o.memo)(e=>{var t=rk();return(0,o.useEffect)(()=>{t(Xue(e))},[t,e]),null},SM);function z2(e){var t=e.zIndex,n=e.isPanorama,r=(0,o.useRef)(null),i=rk();return(0,o.useLayoutEffect)(()=>(r.current&&i(YK({zIndex:t,element:r.current,isPanorama:n})),()=>{i(XK({zIndex:t,isPanorama:n}))}),[i,t,n]),o.createElement(`g`,{tabIndex:-1,ref:r,className:`recharts-zIndex-layer_${t}`})}function B2(e){var t=e.children,n=e.isPanorama,r=X(IK);if(!r||r.length===0)return t;var i=r.filter(e=>e<0),a=r.filter(e=>e>0);return o.createElement(o.Fragment,null,i.map(e=>o.createElement(z2,{key:e,zIndex:e,isPanorama:n})),t,a.map(e=>o.createElement(z2,{key:e,zIndex:e,isPanorama:n})))}var tde=[`children`];function nde(e,t){if(e==null)return{};var n,r,i=rde(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function rde(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function V2(){return V2=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},V2.apply(null,arguments)}var ide={width:`100%`,height:`100%`,display:`block`},ade=(0,o.forwardRef)((e,t)=>{var n=cM(),r=lM(),i=IM();if(!Sj(n)||!Sj(r))return null;var a=e.children,s=e.otherAttributes,c=e.title,l=e.desc,u,d;return s!=null&&(u=typeof s.tabIndex==`number`?s.tabIndex:i?0:void 0,d=typeof s.role==`string`?s.role:i?`application`:void 0),o.createElement(NE,V2({},s,{title:c,desc:l,role:d,tabIndex:u,width:n,height:r,style:ide,ref:t}),a)}),ode=e=>{var t=e.children,n=X(Jj);if(!n)return null;var r=n.width,i=n.height,a=n.y,s=n.x;return o.createElement(NE,{width:r,height:i,x:s,y:a},t)},H2=(0,o.forwardRef)((e,t)=>{var n=e.children,r=nde(e,tde);return Kj()?o.createElement(ode,null,o.createElement(B2,{isPanorama:!0},n)):o.createElement(ade,V2({ref:t},r),o.createElement(B2,{isPanorama:!1},n))});function sde(e,t){return dde(e)||ude(e,t)||lde(e,t)||cde()}function cde(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
66
66
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function lde(e,t){if(e){if(typeof e==`string`)return U2(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?U2(e,t):void 0}}function U2(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function ude(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function dde(e){if(Array.isArray(e))return e}function fde(){var e=rk(),t=sde((0,o.useState)(null),2),n=t[0],r=t[1],i=X(use);return(0,o.useEffect)(()=>{if(n!=null){var t=n.getBoundingClientRect().width/n.offsetWidth;Q(t)&&t!==i&&e(Joe(t))}},[n,e,i]),r}function W2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function pde(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?W2(Object(n),!0).forEach(function(t){mde(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):W2(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function mde(e,t,n){return(t=hde(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function hde(e){var t=gde(e,`string`);return typeof t==`symbol`?t:t+``}function gde(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function G2(){return G2=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},G2.apply(null,arguments)}function K2(e,t){return bde(e)||yde(e,t)||vde(e,t)||_de()}function _de(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
|
|
67
|
-
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function vde(e,t){if(e){if(typeof e==`string`)return q2(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?q2(e,t):void 0}}function q2(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function yde(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function bde(e){if(Array.isArray(e))return e}var xde=()=>(Pq(),null);function J2(e){if(typeof e==`number`)return e;if(typeof e==`string`){var t=parseFloat(e);if(!Number.isNaN(t))return t}return 0}var Sde=(0,o.forwardRef)((e,t)=>{var n=(0,o.useRef)(null),r=K2((0,o.useState)({containerWidth:J2(e.style?.width),containerHeight:J2(e.style?.height)}),2),i=r[0],a=r[1],s=(0,o.useCallback)((e,t)=>{a(n=>{var r=Math.round(e),i=Math.round(t);return n.containerWidth===r&&n.containerHeight===i?n:{containerWidth:r,containerHeight:i}})},[]),c=(0,o.useCallback)(e=>{if(typeof t==`function`&&t(e),n.current!=null&&(n.current.disconnect(),n.current=null),e!=null&&typeof ResizeObserver<`u`){var r=e.getBoundingClientRect(),i=r.width,a=r.height;s(i,a);var o=new ResizeObserver(e=>{var t=e[0];if(t!=null){var n=t.contentRect,r=n.width,i=n.height;s(r,i)}});o.observe(e),n.current=o}},[t,s]);return(0,o.useEffect)(()=>()=>{n.current?.disconnect()},[s]),o.createElement(o.Fragment,null,o.createElement(mM,{width:i.containerWidth,height:i.containerHeight}),o.createElement(`div`,G2({ref:c},e)))}),Cde=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height,i=K2((0,o.useState)({containerWidth:J2(n),containerHeight:J2(r)}),2),a=i[0],s=i[1],c=(0,o.useCallback)((e,t)=>{s(n=>{var r=Math.round(e),i=Math.round(t);return n.containerWidth===r&&n.containerHeight===i?n:{containerWidth:r,containerHeight:i}})},[]),l=(0,o.useCallback)(e=>{if(typeof t==`function`&&t(e),e!=null){var n=e.getBoundingClientRect(),r=n.width,i=n.height;c(r,i)}},[t,c]);return o.createElement(o.Fragment,null,o.createElement(mM,{width:a.containerWidth,height:a.containerHeight}),o.createElement(`div`,G2({ref:l},e)))}),wde=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height;return o.createElement(o.Fragment,null,o.createElement(mM,{width:n,height:r}),o.createElement(`div`,G2({ref:t},e)))}),Tde=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height;return typeof n==`string`||typeof r==`string`?o.createElement(Cde,G2({},e,{ref:t})):typeof n==`number`&&typeof r==`number`?o.createElement(wde,G2({},e,{width:n,height:r,ref:t})):o.createElement(o.Fragment,null,o.createElement(mM,{width:n,height:r}),o.createElement(`div`,G2({ref:t},e)))});function Ede(e){return e?Sde:Tde}var Dde=(0,o.forwardRef)((e,t)=>{var n=e.children,r=e.className,i=e.height,a=e.onClick,s=e.onContextMenu,c=e.onDoubleClick,l=e.onMouseDown,u=e.onMouseEnter,d=e.onMouseLeave,f=e.onMouseMove,p=e.onMouseUp,m=e.onTouchEnd,h=e.onTouchMove,g=e.onTouchStart,_=e.style,v=e.width,y=e.responsive,b=e.dispatchTouchEvents,x=b===void 0||b,S=(0,o.useRef)(null),C=rk(),w=K2((0,o.useState)(null),2),T=w[0],E=w[1],D=K2((0,o.useState)(null),2),O=D[0],k=D[1],A=fde(),j=iM(),M=j?.width>0?j.width:v,N=j?.height>0?j.height:i,ee=(0,o.useCallback)(e=>{A(e),typeof t==`function`&&t(e),E(e),k(e),e!=null&&(S.current=e)},[A,t,E,k]),P=(0,o.useCallback)(e=>{C(i2(e)),C(S2({handler:a,reactEvent:e}))},[C,a]),te=(0,o.useCallback)(e=>{C(o2(e)),C(S2({handler:u,reactEvent:e}))},[C,u]),F=(0,o.useCallback)(e=>{C(UW()),C(S2({handler:d,reactEvent:e}))},[C,d]),ne=(0,o.useCallback)(e=>{C(o2(e)),C(S2({handler:f,reactEvent:e}))},[C,f]),re=(0,o.useCallback)(()=>{C(h2())},[C]),ie=(0,o.useCallback)(()=>{C(g2())},[C]),I=(0,o.useCallback)(e=>{C(m2(e.key))},[C]),ae=(0,o.useCallback)(e=>{C(S2({handler:s,reactEvent:e}))},[C,s]),oe=(0,o.useCallback)(e=>{C(S2({handler:c,reactEvent:e}))},[C,c]),se=(0,o.useCallback)(e=>{C(S2({handler:l,reactEvent:e}))},[C,l]),L=(0,o.useCallback)(e=>{C(S2({handler:p,reactEvent:e}))},[C,p]),ce=(0,o.useCallback)(e=>{C(S2({handler:g,reactEvent:e}))},[C,g]),le=(0,o.useCallback)(e=>{x&&C(D2(e)),C(S2({handler:h,reactEvent:e}))},[C,x,h]),ue=(0,o.useCallback)(e=>{C(S2({handler:m,reactEvent:e}))},[C,m]),de=Ede(y);return o.createElement(cq.Provider,{value:T},o.createElement(xD.Provider,{value:O},o.createElement(de,{width:M??_?.width,height:N??_?.height,className:yE(`recharts-wrapper`,r),style:pde({position:`relative`,cursor:`default`,width:M,height:N},_),onClick:P,onContextMenu:ae,onDoubleClick:oe,onFocus:re,onBlur:ie,onKeyDown:I,onMouseDown:se,onMouseEnter:te,onMouseLeave:F,onMouseMove:ne,onMouseUp:L,onTouchEnd:ue,onTouchMove:le,onTouchStart:ce,ref:ee},o.createElement(xde,null),n)))}),Ode=[`width`,`height`,`responsive`,`children`,`className`,`style`,`compact`,`title`,`desc`];function kde(e,t){if(e==null)return{};var n,r,i=Ade(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Ade(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var Y2=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height,i=e.responsive,a=e.children,s=e.className,c=e.style,l=e.compact,u=e.title,d=e.desc,f=TE(kde(e,Ode));return l?o.createElement(o.Fragment,null,o.createElement(mM,{width:n,height:r}),o.createElement(H2,{otherAttributes:f,title:u,desc:d},a)):o.createElement(Dde,{className:s,style:c,width:n,height:r,responsive:i??!1,onClick:e.onClick,onMouseLeave:e.onMouseLeave,onMouseEnter:e.onMouseEnter,onMouseMove:e.onMouseMove,onMouseDown:e.onMouseDown,onMouseUp:e.onMouseUp,onContextMenu:e.onContextMenu,onDoubleClick:e.onDoubleClick,onTouchStart:e.onTouchStart,onTouchMove:e.onTouchMove,onTouchEnd:e.onTouchEnd},o.createElement(H2,{otherAttributes:f,title:u,desc:d,ref:t},o.createElement(P$,null,a)))});function X2(){return X2=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},X2.apply(null,arguments)}function Z2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function jde(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Z2(Object(n),!0).forEach(function(t){Mde(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Z2(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Mde(e,t,n){return(t=Nde(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Nde(e){var t=Pde(e,`string`);return typeof t==`symbol`?t:t+``}function Pde(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var Fde=jde({accessibilityLayer:!0,barCategoryGap:`10%`,barGap:4,layout:`horizontal`,margin:{top:5,right:5,bottom:5,left:5},responsive:!1,reverseStackOrder:!1,stackOffset:`none`,syncMethod:`index`},N2),Q2=(0,o.forwardRef)(function(e,t){var n=hO(e.categoricalChartProps,Fde),r=e.chartName,i=e.defaultTooltipEventType,a=e.validateTooltipEventTypes,s=e.tooltipPayloadSearcher,c=e.categoricalChartProps,l={chartName:r,defaultTooltipEventType:i,validateTooltipEventTypes:a,tooltipPayloadSearcher:s,eventEmitter:void 0};return o.createElement(F2,{preloadedState:{options:l},reduxStoreName:c.id??r},o.createElement(v$,{chartData:c.data}),o.createElement(I2,{layout:n.layout,margin:n.margin}),o.createElement(R2,{throttleDelay:n.throttleDelay,throttledEvents:n.throttledEvents}),o.createElement(L2,{baseValue:n.baseValue,accessibilityLayer:n.accessibilityLayer,barCategoryGap:n.barCategoryGap,maxBarSize:n.maxBarSize,stackOffset:n.stackOffset,barGap:n.barGap,barSize:n.barSize,syncId:n.syncId,syncMethod:n.syncMethod,className:n.className,reverseStackOrder:n.reverseStackOrder}),o.createElement(Y2,X2({},n,{ref:t})))}),Ide=[`axis`],Lde=(0,o.forwardRef)((e,t)=>o.createElement(Q2,{chartName:`LineChart`,defaultTooltipEventType:`axis`,validateTooltipEventTypes:Ide,tooltipPayloadSearcher:mq,categoricalChartProps:e,ref:t})),Rde=[`axis`,`item`],$2=(0,o.forwardRef)((e,t)=>o.createElement(Q2,{chartName:`BarChart`,defaultTooltipEventType:`axis`,validateTooltipEventTypes:Rde,tooltipPayloadSearcher:mq,categoricalChartProps:e,ref:t}));function zde(e){var t=rk();return(0,o.useEffect)(()=>{t(que(e))},[t,e]),null}var Bde=[`layout`];function e4(){return e4=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},e4.apply(null,arguments)}function Vde(e,t){if(e==null)return{};var n,r,i=Hde(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Hde(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function t4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Ude(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?t4(Object(n),!0).forEach(function(t){Wde(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t4(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Wde(e,t,n){return(t=Gde(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Gde(e){var t=Kde(e,`string`);return typeof t==`symbol`?t:t+``}function Kde(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var n4=Ude({accessibilityLayer:!0,stackOffset:`none`,barCategoryGap:`10%`,barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:`index`,layout:`radial`,responsive:!1,cx:`50%`,cy:`50%`,innerRadius:0,outerRadius:`80%`},N2),qde=(0,o.forwardRef)(function(e,t){var n=hO(e.categoricalChartProps,n4),r=n.layout,i=Vde(n,Bde),a=e.chartName,s={chartName:a,defaultTooltipEventType:e.defaultTooltipEventType,validateTooltipEventTypes:e.validateTooltipEventTypes,tooltipPayloadSearcher:e.tooltipPayloadSearcher,eventEmitter:void 0};return o.createElement(F2,{preloadedState:{options:s},reduxStoreName:n.id??a},o.createElement(v$,{chartData:n.data}),o.createElement(I2,{layout:r,margin:n.margin}),o.createElement(R2,{throttleDelay:n.throttleDelay,throttledEvents:n.throttledEvents}),o.createElement(L2,{baseValue:void 0,accessibilityLayer:n.accessibilityLayer,barCategoryGap:n.barCategoryGap,maxBarSize:n.maxBarSize,stackOffset:n.stackOffset,barGap:n.barGap,barSize:n.barSize,syncId:n.syncId,syncMethod:n.syncMethod,className:n.className,reverseStackOrder:n.reverseStackOrder}),o.createElement(zde,{cx:n.cx,cy:n.cy,startAngle:n.startAngle,endAngle:n.endAngle,innerRadius:n.innerRadius,outerRadius:n.outerRadius}),o.createElement(Y2,e4({},i,{ref:t})))});function r4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i4(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?r4(Object(n),!0).forEach(function(t){Jde(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r4(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Jde(e,t,n){return(t=Yde(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yde(e){var t=Xde(e,`string`);return typeof t==`symbol`?t:t+``}function Xde(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var Zde=[`item`],Qde=i4(i4({},n4),{},{layout:`centric`,startAngle:0,endAngle:360}),$de=(0,o.forwardRef)((e,t)=>{var n=hO(e,Qde);return o.createElement(qde,{chartName:`PieChart`,defaultTooltipEventType:`item`,validateTooltipEventTypes:Zde,tooltipPayloadSearcher:mq,categoricalChartProps:n,ref:t})}),efe=(e,t)=>t>0?`${Math.round(e/t*100)}%`:``,tfe=({active:e,payload:t,measure:n})=>{let r=t?.[0]?.payload;return!e||!r?null:(0,V.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,V.jsx)(`div`,{className:`text-muted-foreground`,children:r.label}),(0,V.jsx)(`div`,{className:`font-semibold tabular-nums`,children:gE(r.value,n)})]})},nfe=({resource:e,slices:t,measure:n})=>{let r=t.filter(e=>e.value!==null&&e.value>0),i=r.reduce((e,t)=>e+t.value,0);return(0,V.jsxs)(`div`,{className:`flex flex-col items-center gap-4 sm:flex-row sm:items-center`,children:[(0,V.jsx)(`div`,{className:`size-36 shrink-0`,children:(0,V.jsx)(aM,{width:`100%`,height:`100%`,children:(0,V.jsxs)($de,{children:[(0,V.jsx)(hQ,{data:r,dataKey:`value`,nameKey:`label`,innerRadius:`62%`,outerRadius:`100%`,paddingAngle:+(r.length>1),stroke:`var(--background)`,strokeWidth:2,isAnimationActive:!1,children:r.map(e=>(0,V.jsx)(Qq,{fill:e.color},e.key))}),(0,V.jsx)(Zq,{content:(0,V.jsx)(tfe,{measure:n}),isAnimationActive:!1})]})})}),(0,V.jsx)(`ul`,{className:`flex w-full min-w-0 flex-col gap-0.5`,children:t.map(t=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(ZS,{to:{kind:`list`,resource:e,filter:t.filter},className:`group flex items-center gap-2 rounded-md px-1 py-0.5 hover:bg-muted`,children:[(0,V.jsx)(`span`,{className:`size-2.5 shrink-0 rounded-full`,style:{background:t.color},"aria-hidden":!0}),(0,V.jsx)(`span`,{className:`min-w-0 flex-1 truncate group-hover:text-primary-text`,children:t.label}),(0,V.jsx)(`span`,{className:`font-medium tabular-nums`,children:gE(t.value,n)}),(0,V.jsx)(`span`,{className:`w-9 text-right text-xs text-muted-foreground tabular-nums`,children:efe(t.value??0,i)})]})},t.key))})]})},rfe={hour:{hour:`2-digit`,minute:`2-digit`,hour12:!1},day:{day:`numeric`,month:`short`},week:{day:`numeric`,month:`short`},month:{month:`short`,year:`2-digit`},year:{year:`numeric`}},ife={hour:{day:`numeric`,month:`short`,hour:`2-digit`,minute:`2-digit`,hour12:!1},day:{day:`numeric`,month:`short`,year:`numeric`},week:{day:`numeric`,month:`short`,year:`numeric`},month:{month:`long`,year:`numeric`},year:{year:`numeric`}},a4=e=>{let t=new Intl.DateTimeFormat(`en-GB`,{...e,timeZone:`UTC`});return e=>t.format(e)},o4={fontSize:11,fill:`var(--muted-foreground)`},afe=({active:e,payload:t,measure:n,bucket:r})=>{let i=t?.[0]?.payload;return!e||!i?null:(0,V.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,V.jsx)(`div`,{className:`text-muted-foreground`,children:(r===`week`?`Week of `:``)+a4(ife[r])(i.at)}),(0,V.jsx)(`div`,{className:`font-semibold tabular-nums`,children:gE(i.value,n)})]})},ofe=({points:e,measure:t,bucket:n,type:r})=>{let i=Gl(`(min-width: 640px)`),a=a4(rfe[n]),o=(0,V.jsx)(r0,{vertical:!1,stroke:`var(--border)`}),s=(0,V.jsx)(X0,{dataKey:`at`,tickFormatter:a,tick:o4,axisLine:!1,tickLine:!1,minTickGap:i?24:40,height:18}),c=(0,V.jsx)(t2,{width:i?48:36,tick:o4,axisLine:!1,tickLine:!1,tickCount:3,tickFormatter:e=>e.toLocaleString(`en-IE`,{notation:`compact`})}),l=(0,V.jsx)(Zq,{cursor:r===`bar`?{fill:`var(--muted)`}:{stroke:`var(--border-strong)`},content:(0,V.jsx)(afe,{measure:t,bucket:n}),isAnimationActive:!1});return(0,V.jsx)(`div`,{className:`h-40`,children:(0,V.jsx)(aM,{width:`100%`,height:`100%`,children:r===`line`?(0,V.jsxs)(Lde,{data:e,margin:{top:6,right:6,bottom:0,left:0},children:[o,s,c,l,(0,V.jsx)(T0,{dataKey:`value`,stroke:`var(--chart-1)`,strokeWidth:2,dot:e.length<=31&&{r:3,fill:`var(--chart-1)`,strokeWidth:0},activeDot:{r:4,stroke:`var(--background)`,strokeWidth:2},isAnimationActive:!1})]}):(0,V.jsxs)($2,{data:e,margin:{top:6,right:0,bottom:0,left:0},barCategoryGap:`22%`,children:[o,s,c,l,(0,V.jsx)(H0,{dataKey:`value`,fill:`var(--chart-1)`,radius:[4,4,0,0],isAnimationActive:!1})]})})})},sfe=(e,t,n,r)=>{let i=n??r,a=i===void 0?void 0:e.fields[i];return!a||i===void 0?{kind:`count`}:{kind:n===void 0?`average`:`sum`,field:a,hints:t?.fields[i]}},s4=({model:e,view:t,groupBy:n,type:r=`bar`,sum:i,average:a,filter:o=``,granularity:s=`day`,range:c=`30d`,limit:l=10,empty:u=`Nothing to chart yet.`})=>{let{resources:d,views:f}=J(),p=e.fields[n],m=p?.type===`date`||p?.type===`timestamp`,h=p?.type===`relation`&&p.relation?d[p.relation.resource]:void 0,g=h&&h.primaryKey.length===1?Px(h,f[h.name]):void 0,_=m?{granularity:s,range:c,timeZone:Wd()}:{limit:l,...g&&{label:g}},v=sE(e.name,{groupBy:n,filter:o,...i&&{sum:i},...a&&{average:a},..._},!!p),y=sfe(e,t,i,a);if(!p)return null;if(v.isPending)return(0,V.jsx)(cu,{className:`h-36 w-full`});if(v.error)return(0,V.jsx)(`p`,{className:`text-danger-text`,children:`Could not load the chart.`});let{groups:b}=v.data;if(b.every(e=>e.count===0))return(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:u});if(m)return(0,V.jsx)(ofe,{points:hE(b,y),measure:y,bucket:s,type:r===`line`?`line`:`bar`});let x=mE(b,p,t?.fields[n],y,o);return r===`donut`?(0,V.jsx)(nfe,{resource:e.name,slices:x,measure:y}):(0,V.jsx)(_E,{resource:e.name,slices:x,measure:y})},cfe=({node:e,slots:t})=>{let{resource:n,title:r,description:i,actions:a,span:o,...s}=ZT(e),{resources:c,views:l}=J(),u=c[n];return u?(0,V.jsx)($T,{title:r,description:i,actions:t.actions,className:`h-full`,children:(0,V.jsx)(s4,{model:u,view:l[n],...s})}):null},lfe=co(),c4=async(e,t,n,r,i)=>{let a=n.primaryKey[0],o=[...new Set(r)].sort();if(o.length===0||n.primaryKey.length!==1)return new Map;let s=Px(n,i),c=await e.fetchQuery({queryKey:W.labels(n.name,o.join(`,`)),staleTime:3e5,queryFn:async()=>(await t.list(n.name,{filter:qa(lfe.in(a,o)),fields:[a,s],pageSize:o.length})).items.map(e=>[String(e[a]),String(e[s])])});return new Map(c)},l4=(e,t,n)=>n.flatMap(n=>{let r=t.fields[n],i=r?.type===`relation`&&r.relation?e[r.relation.resource]:void 0;return i?[{name:n,target:i}]:[]}),u4=(e,t,n,r)=>Object.fromEntries(l4(e,n,r).filter(({target:e})=>e.primaryKey.length===1).map(({name:e,target:n})=>[e,Px(n,t[n.name])])),d4=(e,t,n,r,i={})=>{let a=l4(e,t,n);return r.map(e=>{let t={...e};for(let{name:n}of a)e[n]!=null&&(t[n]={id:e[n],name:i[n]?.[String(e[n])]??String(e[n])});return t})},f4=(e,t)=>{let n=String(t);return e&&Object.hasOwn(e,n)?e[n]:void 0},p4=({value:e,hints:t,children:n})=>(0,V.jsx)(Au,{tone:Gx(String(e)),color:f4(t?.valueColors,e),shape:t?.badgeShape,children:n}),ufe=({field:e,value:t,known:n})=>{let{resources:r,views:i}=J(),a=G(),o=Gp(),s=e.relation?r[e.relation.resource]:void 0,c=String(t),l=mh({queryKey:W.relatedLabel(s?.name??``,c),enabled:!!s&&n===void 0,queryFn:async()=>(await c4(o,a,s,[c],i[s.name])).get(c)??c});return s?(0,V.jsx)(ZS,{to:{kind:`record`,resource:s.name,key:c},className:`font-medium text-primary-text hover:underline`,children:n??l.data??c}):(0,V.jsx)(`span`,{children:c})},dfe=({model:e,field:t,value:n,format:r,relationLabel:i})=>{let{views:a}=J(),o={...a[e.name]?.fields[t.name],...r&&{format:r}};if(n==null||n===``)return(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});if(t.type===`relation`)return(0,V.jsx)(ufe,{field:t,value:n,known:i});let s=t.type===`file`?bb(n):void 0;if(s&&`url`in s&&s.url){let e=Ob(n,{width:40,height:40});return(0,V.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[e&&(0,V.jsx)(hC,{image:e,className:`size-10 shrink-0 rounded border border-border object-cover`}),(0,V.jsx)(`a`,{href:s.url,target:`_blank`,rel:`noreferrer`,className:`truncate font-medium text-primary-text hover:underline`,children:s.name})]})}if(Mx(t,o))return(0,V.jsx)(OC,{source:String(n)});let c=eS(t,n,o),l=t.type===`text`?Vx(o):void 0;return l?(0,V.jsx)(PC,{format:l,value:c}):t.type===`enum`||o.format===`badge`?(0,V.jsx)(p4,{value:n,hints:o,children:c}):(0,V.jsx)(`span`,{title:tS(t,n),className:B(o.format===`code`&&`font-mono text-xs`,(t.type===`decimal`||t.type===`integer`)&&`tabular-nums`,o.multiline&&`whitespace-pre-line break-words`),children:c})},m4=e=>{let{views:t}=J(),n=wC(e.field,t[e.model.name]?.fields[e.field.name]),r=(0,V.jsx)(dfe,{...e});return n?(0,V.jsx)(EC,{shown:n,part:`display`,field:e.field,value:e.value,fallback:r}):r},h4=(e,t,n)=>{if(!t)return[];let r=sc(e,t.model.name,n);return r.ok?r.steps:[]},g4=(e,t,n,r,i)=>({queryKey:W.pathValue(n?.model.name??``,n?.key??``,r),enabled:i.length>1,queryFn:async()=>{let r=n.record;for(let n of i.slice(0,-1)){let i=r[n.field.name];if(i==null)return null;let a=n.field.relation.resource;r=(await t.fetchQuery({queryKey:W.record(a,String(i)),queryFn:()=>e.get(a,String(i))})).record}return r[i.at(-1).field.name]??null}}),_4=(e,t,n)=>{let r=t.at(-1);return!e||!r?{state:`missing`}:t.length===1?{state:`ready`,value:e.record[r.field.name],field:r.field,model:r.model}:n.isPending?{state:`loading`}:{state:`ready`,value:n.data??null,field:r.field,model:r.model}},v4=(e,t)=>{let{resources:n}=J(),r=h4(n,e,t);return _4(e,r,mh(g4(G(),Gp(),e,t,r)))},ffe=(e,t)=>{let{resources:n}=J(),r=G(),i=Gp(),a=t.map(t=>h4(n,e,t)),o=fh({queries:t.map((t,n)=>g4(r,i,e,t,a[n]))});return t.map((t,n)=>_4(e,a[n],o[n]))},pfe=(e,t)=>{if(t)return t;let n=e.split(`.`).map(e=>K(e).toLowerCase()).join(` `);return n[0].toUpperCase()+n.slice(1)},mfe=({node:e})=>{let{name:t,label:n,format:r}=ZT(e),{views:i}=J(),a=v4(jT(),t);if(a.state===`missing`)return null;let o=a.state===`loading`?(0,V.jsx)(cu,{className:`h-4 w-24`}):(0,V.jsx)(m4,{model:a.model,field:a.field,value:a.value,format:r});if(n===!1)return(0,V.jsx)(`div`,{children:o});let s=n??pfe(t,a.state===`ready`?i[a.model.name]?.fields[a.field.name]?.label:void 0);return(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:s}),(0,V.jsx)(`div`,{className:`mt-0.5 truncate`,children:o})]})},hfe={1:``,2:`md:grid-cols-2`,3:`md:grid-cols-2 xl:grid-cols-3`,4:`sm:grid-cols-2 xl:grid-cols-4`},gfe={1:``,2:`grid-cols-2`,3:`grid-cols-2 xl:grid-cols-3`,4:`grid-cols-2 xl:grid-cols-4`},_fe={1:``,2:`md:col-span-2`,3:`md:col-span-2 xl:col-span-3`,4:`sm:col-span-2 md:col-span-2 xl:col-span-4`},vfe=e=>typeof e==`object`&&!e.custom&&e.type===`Stat`,yfe=({node:e,children:t})=>{let{columns:n=2}=ZT(e),r=e.children,i=r.length>0&&r.every(vfe);return(0,V.jsx)(`div`,{className:B(`grid grid-cols-1 gap-4`,i?gfe[n]:hfe[n]),children:t.map((e,t)=>{let n=r[t],i=typeof n==`object`?n.props.span:void 0;return(0,V.jsx)(`div`,{className:B(`min-w-0`,i&&_fe[i]),children:e},t)})})},y4=`font-medium text-primary-text hover:underline`,bfe=({node:e})=>{let t=ZT(e),n=jT()?.record,r=e.children.filter(e=>typeof e==`string`).join(``);if(t.to){let e=go(t.to,n);return(0,V.jsx)(ZS,{to:e,className:y4,children:r||ps(e)})}let i=t.href??``;return(0,V.jsx)(`a`,{href:i,className:y4,...i.startsWith(`http`)&&{target:`_blank`,rel:`noreferrer`},children:r||i})},xfe=(e,t,n)=>Object.fromEntries(t.map(t=>{let r=e.fields[t];if(r.type===`file`)return[t,n?.record[t]??null];if(n)return[t,r.type===`boolean`?!!n.record[t]:Mb(n.record[t])];let i=r.default&&`value`in r.default?r.default.value:void 0;return[t,r.type===`boolean`?!!i:Mb(i)]})),Sfe=(e,t,n)=>Object.fromEntries(Object.entries(t).flatMap(([t,r])=>{let i=e.fields[t];return Kb(r)?r.key===Mb(n.record[t])?[]:[[t,i.type===`integer`?Number(r.key):r.key]]:Vb(i,r,n.record[t])?[[t,Rb(i,r)]]:[]})),Cfe=({model:e,record:t,mode:n,label:r,title:i,fields:a,values:s,onClose:c})=>{let{resources:l,views:u}=J(),d=G(),f=Qy(),p=qT(),m=u[e.name],[h,g]=(0,o.useState)(()=>xfe(e,a,t)),[_,v]=(0,o.useState)({}),[y,b]=(0,o.useState)(0),x=KC(y),[S,C]=(0,o.useState)(),[w,T]=(0,o.useState)(!1),E=async()=>{T(!0),C(void 0),await(n===`create`?d.create(e.name,{...Xb(e,l,h),...s}):d.update(e.name,t.key,Sfe(e,h,t),t.etag??`*`)).then(async()=>{await p(e.name),f.show({state:`success`,title:`${i??r}: saved`}),c()},e=>{let t=WC(e);v(t),Object.keys(t).length>0&&b(e=>e+1),C(e)}),T(!1)};return(0,V.jsx)(wf,{title:i??r,onClose:c,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:c,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,loading:w,onClick:()=>void E(),children:n===`create`?`Create`:`Save`})]}),children:(0,V.jsxs)(`form`,{ref:x,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),E()},children:[S!==void 0&&Object.keys(_).length===0&&(0,V.jsx)(ax,{title:`Not saved`,error:S}),a.map(n=>{let r=e.fields[n],i=h[n],a=r.relation?l[r.relation.resource]:void 0,o=m?.fields[n]?.label??K(n),s=_[n];return(0,V.jsx)(eb,{name:n,label:o,help:m?.fields[n]?.help,error:s&&UC(r,o,s),children:(0,V.jsx)(IC,{field:r,hints:m?.fields[n],value:Kb(i)?i.key:i,stored:t?.record[n],relationLabel:Kb(i)?i.label:void 0,relationPicker:a?{target:a,view:u[a.name]}:void 0,invalid:!!_[n],resource:e.name,onChange:e=>{v(({[n]:e,...t})=>t),g(t=>({...t,[n]:e}))}})},n)})]})})},wfe=({model:e,recordKey:t,children:n})=>{let r=GT(e,{key:t});return(0,V.jsx)(V.Fragment,{children:n(r.data??void 0)})},Tfe=({node:e})=>{let t=ZT(e),n=jT(),{resources:r}=J(),i=r[t.resource??n?.model.name??``],a=YS(i?.name??``),[s,c]=(0,o.useState)(!1);if(!i||!(t.mode===`create`?MT(a,`create`):MT(a,`update`)&&n?.permissions?.update!==!1))return null;let l=e=>(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{size:`sm`,variant:t.variant??`secondary`,disabled:t.mode===`edit`&&!e,onClick:()=>c(!0),children:t.label}),s&&(0,V.jsx)(Cfe,{...t,model:i,record:t.mode===`edit`?e:void 0,onClose:()=>c(!1)})]});return t.mode===`edit`&&t.recordKey!==void 0?(0,V.jsx)(wfe,{model:i,recordKey:t.recordKey,children:l}):l(t.mode===`edit`?n:void 0)},Efe=({node:e,children:t,slots:n})=>{let{title:r,description:i}=ZT(e);return(0,V.jsx)(`div`,{className:`flex-1`,children:(0,V.jsxs)(`div`,{className:`mx-auto flex max-w-[1200px] flex-col gap-6 px-4 pb-16 pt-6 md:px-10 md:py-8`,children:[(0,V.jsx)(gd,{title:r,subtitle:i,actions:n.actions}),t]})})},b4=(e,t)=>{let n=jT(),r=v4(typeof e==`string`?n:void 0,typeof e==`string`?e:``);return typeof e==`number`?e:e===void 0?t:r.state===`ready`?Number(r.value):r.state===`loading`?void 0:NaN},Dfe=({node:e})=>{let{value:t,max:n,label:r}=ZT(e),i=b4(t,0),a=b4(n,100);if(i===void 0||a===void 0)return(0,V.jsx)(cu,{className:`h-6 w-full`});if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=a>0?Math.min(1,Math.max(0,i/a)):0;return(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:r}),(0,V.jsxs)(`span`,{className:`tabular-nums`,children:[i.toLocaleString(`en-IE`),` / `,a.toLocaleString(`en-IE`)]})]}),(0,V.jsx)(`div`,{role:`progressbar`,"aria-label":r,"aria-valuenow":i,"aria-valuemin":0,"aria-valuemax":a,className:`mt-1.5 h-2 overflow-hidden rounded-full bg-muted`,children:(0,V.jsx)(`div`,{className:o>=.9?`h-full rounded-full bg-warning`:`h-full rounded-full bg-primary`,style:{width:`${o*100}%`}})})]})},Ofe=({model:e,filter:t,sort:n,recordKey:r,title:i,description:a,empty:o,actions:s,children:c})=>{let l=GT(e,{filter:t,sort:n,key:r}),u=e=>l.data?(0,V.jsx)(AT,{value:l.data,children:e}):void 0,d=l.isPending?(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsx)(cu,{className:`h-4 w-1/2`}),(0,V.jsx)(cu,{className:`h-4 w-1/3`})]}):l.error?(0,V.jsx)(ax,{title:`Could not load`,error:l.error}):l.data?u((0,V.jsx)(`div`,{className:`flex flex-col gap-3`,children:c})):(0,V.jsx)(eE,{children:o??`Nothing here yet.`});return(0,V.jsx)($T,{title:i,description:a,actions:s?u(s):void 0,className:`h-full`,children:d})},kfe=({node:e,children:t,slots:n})=>{let{resource:r,filter:i,sort:a,recordKey:o,title:s,description:c,empty:l}=ZT(e),u=J().resources[r];return u?(0,V.jsx)(Ofe,{model:u,filter:i,sort:a,recordKey:o,title:s,description:c,empty:l,actions:n.actions,children:t}):null};function Afe(e){return jfe(e)||typeof e==`function`||Mfe(e)}function jfe(e){return typeof e==`function`&&(()=>{let t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function Mfe(e){return typeof e==`object`&&typeof e.$$typeof==`symbol`&&[`react.memo`,`react.forward_ref`].includes(e.$$typeof.description)}function x4(e,t){return e==null?null:Afe(e)?o.createElement(e,t):e}function Nfe(e){if(`cell`in e&&e.cell){let t=e.cell,n=t.column.columnDef,r=t,i=n;return r.getIsAggregated?.()?x4(i.aggregatedCell??n.cell,t.getContext()):r.getIsPlaceholder?.()?null:x4(n.cell,t.getContext())}return`header`in e&&e.header?x4(e.header.column.columnDef.header,e.header.getContext()):`footer`in e&&e.footer?x4(e.footer.column.columnDef.footer,e.footer.getContext()):null}function Pfe({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(1)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(1)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function Ffe(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var S4=[],C4=0,{link:w4,unlink:Ife,propagate:Lfe,checkDirty:T4,shallowPropagate:E4}=Pfe({update(e){return e._update()},notify(e){S4[O4++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,j4(e))}}),D4=0,O4=0,k4,A4=0;function Rfe(e){try{++A4,e()}finally{--A4||M4()}}function j4(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=Ife(n,e)}function M4(){if(!(A4>0)){for(;D4<O4;){let e=S4[D4];S4[D4++]=void 0,e.notify()}D4=0,O4=0}}function zfe(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:+!n,get(){return k4!==void 0&&w4(i,k4,C4),i._snapshot},subscribe(e){let t=Ffe(e),n={current:!1},r=Bfe(()=>{i.get(),n.current?(k4=void 0,t.next?.(i._snapshot)):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=k4,o=t?.compare??Object.is;if(n)k4=i,++C4,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{k4=a,n&&(i.flags&=-5),j4(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&T4(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&E4(e)}}else e&32&&(i.flags=e&-33);return k4!==void 0&&w4(i,k4,C4),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Lfe(e),E4(e),M4())}},i}function Bfe(e){let t=()=>{let t=k4;k4=n,++C4,n.depsTail=void 0,n.flags=6;try{return e()}finally{k4=t,n.flags&=-5,j4(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&T4(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,j4(this)}};return t(),n}function N4(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();let n=P4(e);if(n.length!==P4(t).length)return!1;for(let r=0;r<n.length;r++)if(!Object.prototype.hasOwnProperty.call(t,n[r])||!Object.is(e[n[r]],t[n[r]]))return!1;return!0}function P4(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function Vfe(e,t){return e===t}function F4(e,t=e=>e,n){let r=n?.compare??Vfe,i=(0,o.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,o.useCallback)(()=>e.get(),[e]);return(0,tk.useSyncExternalStoreWithSelector)(i,a,a,t,r)}function Hfe(e){let t=F4(e.source,e.selector,{compare:N4});return typeof e.children==`function`?e.children(t):e.children}function Ufe(e){let t=e;return Object.defineProperty(e,"state",{get(){return e.get()}}),`set`in e&&(t.setState=e.set.bind(e)),t}function Wfe(e){let{createAtom:t,batch:n}=e,r=t(0);return{createOptionsStore:!1,wrapExternalAtoms:!1,addSubscription:()=>{throw Error(`Feature not supported in current reactivity implementation`)},unmount:()=>{throw Error(`Feature not supported in current reactivity implementation`)},schedule:e.schedule??(e=>queueMicrotask(e)),batch:n,untrack:e=>e(),createReadonlyAtom:(e,n)=>{let i=n?.compare??Object.is,a=!1,o,s=()=>{let t=e();return(!a||!i(o,t))&&(o=t,a=!0),o},c=t(()=>(r.get(),s()),{compare:i});return{get:s,subscribe:c.subscribe.bind(c)}},createWritableAtom:(e,n)=>t(e,{compare:n?.compare}),commit:()=>{r.set(e=>e+1)}}}function Gfe(e,t=Object.is){let n=!1,r;return{get:e.get,markCommitted:e=>{r=e,n=!0},subscribe:i=>e.subscribe(e=>{(!n||!t(r,e))&&i(e)})}}function Kfe(){return Wfe({createAtom:zfe,batch:Rfe})}function I4(e,t){return typeof e==`function`?e(t):e}function L4(e){if(Array.isArray(e))return e.map(L4);if(e&&typeof e==`object`){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n=t===null?R4():{},r=Object.keys(e);for(let t=0;t<r.length;t++){let i=r[t];Object.defineProperty(n,i,{configurable:!0,enumerable:!0,value:L4(e[i]),writable:!0})}return n}return e}function qfe(e,t){let n=Object.keys(t),r=e;for(let e=0;e<n.length;e++){let i=n[e];!i.startsWith(`_memo_`)&&i!==`_cellsCache`&&(r[i]=t[i])}return e}function R4(){return Object.create(null)}function z4(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function B4(e,t){return n=>{(t.options.atoms?.[e]??t.baseAtoms[e]).set(e=>I4(n,e))}}function V4(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function H4(e){return Reflect.ownKeys(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}var Jfe=3;function Yfe(e,t){return U4(e,t,Jfe)}function U4(e,t,n){if(Object.is(e,t))return!0;if(n<=0||!V4(e)||!V4(t)||(Array.isArray(e)||Array.isArray(t))&&(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length))return!1;let r=H4(e),i=H4(t);if(r.length!==i.length)return!1;let a=e,o=t;for(let e=0;e<r.length;e++){let i=r[e];if(!Object.prototype.propertyIsEnumerable.call(t,i)||!U4(a[i],o[i],n-1))return!1}return!0}function W4(e,t,n,r=Yfe){let i=`on${t.charAt(0).toUpperCase()}${t.slice(1)}Change`,a=e.options[i];a&&a(e=>{let t=I4(n,e);return r(e,t)?e:t})}function Xfe(e){return e instanceof Function}function Zfe(e,t){let n=[],r=e=>{e.forEach(e=>{n.push(e);let i=t(e);i.length&&r(i)})};return r(e),n}var Qfe=({fn:e,memoDeps:t,onAfterCompare:n,onAfterUpdate:r,onBeforeCompare:i,onBeforeUpdate:a})=>{let o=[],s;return c=>{i?.();let l=t?.(c),u=!l||l.length!==o?.length;if(!u&&l){for(let e=0;e<l.length;e++)if(l[e]!==o[e]){u=!0;break}}return n?.(u),u?(o=l,a?.(),s=e(...l??[]),r?.(s),s):s}};function $fe(e){let t=!1;return()=>{if(!t){t=!0;return}e()}}function G4({feature:e,fnName:t,objectId:n,onAfterUpdate:r,table:i,...a}){let o=()=>{if(!r)return;let{schedule:e,untrack:t}=i._reactivity;e(()=>t(()=>r()))},s={onAfterUpdate:()=>{o()}};return Qfe({...a,...s})}function K4(e,t=`_`){let[n,r]=e.split(t);return{fnKey:r,fnName:`${n}.${r}`,parentName:n}}function q4(e,t,n){for(let[r,{fn:i,memoDeps:a}]of Object.entries(n)){let{fnKey:n,fnName:o}=K4(r);t[n]=a?G4({memoDeps:a,fn:i,fnName:o,table:t,feature:e}):i}}function J4(e,t,n,r){for(let[i,{fn:a,memoDeps:o}]of Object.entries(r)){let{fnKey:r,fnName:s}=K4(i);if(o){let i=`_memo_${r}`;t[r]=function(...t){if(!this[i]){let t=this;this[i]=G4({memoDeps:e=>o(t,e),fn:(...e)=>a(t,...e),fnName:s,objectId:t.id,table:n,feature:e})}return this[i](...t)}}else t[r]=function(...e){return a(this,...e)}}}function Y4(e,t,n,...r){return e[t]?.(...r)??n(e,...r)}function epe(e){return e.row.getValue(e.column.id)}function tpe(e){return e.getValue()??e.table.options.renderFallbackValue}function npe(e){return{table:e.table,column:e.column,row:e.row,cell:e,getValue:()=>e.getValue(),renderValue:()=>e.renderValue()}}var rpe={assignCellPrototype:(e,t)=>{J4(`coreCellsFeature`,e,t,{cell_getValue:{fn:e=>epe(e)},cell_renderValue:{fn:e=>tpe(e)},cell_getContext:{fn:e=>npe(e),memoDeps:e=>[e]}})}};function ipe(e){if(!e._headerPrototype){e._headerPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignHeaderPrototype?.(e._headerPrototype,e)}return e._headerPrototype}function X4(e,t,n){let r=ipe(e),i=Object.create(r);i.colSpan=0,i.column=t,i.depth=n.depth,i.headerGroup=null,i.id=n.id??t.id,i.index=n.index,i.isPlaceholder=!!n.isPlaceholder,i.placeholderId=n.placeholderId,i.rowSpan=0,i.subHeaders=[];let a=e._headerInstanceInitFns;for(let e=0;e<a.length;e++)a[e](i);return i}function ape(){return{start:[],end:[]}}function Z4(e){let t=e.table.atoms.columnVisibility?.get();if(!t)return!0;let n=e.columns;return n.length?n.some(e=>Y4(e,`getIsVisible`,Z4)):(z4(t,e.id)?t[e.id]:void 0)??!0}function ope(e){return e.getAllLeafColumns().filter(e=>Y4(e,`getIsVisible`,Z4))}function Q4(e,t=1){let n=t;for(let r=0;r<e.length;r++){let i=e[r];Y4(i,`getIsVisible`,Z4)&&i.columns.length&&(n=Math.max(n,Q4(i.columns,t+1)))}return n}function spe(e,t){return e?`${e}_${t}`:String(t)}function cpe(e,t,n,r){let i=e??``;return t&&(i=i?`${i}_${t}`:String(t)),n&&(i=i?`${i}_${n}`:n),r&&(i=i?`${i}_${r}`:r),i}function lpe(e,t){let n=0;for(let r=0;r<e.length;r++)e[r].column===t&&n++;return n}function $4(e,t,n,r,i,a){let o={depth:t,id:spe(r,t),headers:[]},s=[];for(let i=0;i<e.length;i++){if(!(i in e))continue;let a=e[i],c=s[s.length-1],l=a.column.depth===o.depth,u,d=!1;if(l&&a.column.parent?u=a.column.parent:(u=a.column,d=!0),c&&c.column===u)c.subHeaders.push(a);else{let e=X4(n,u,{id:cpe(r,t,u.id,a.id),isPlaceholder:d,placeholderId:d?String(lpe(s,u)):void 0,depth:t,index:s.length});e.subHeaders.push(a),s.push(e)}o.headers.push(a),a.headerGroup=o}for(let e=0;e<a.length;e++)a[e](o);i.push(o),t>0&&$4(s,t-1,n,r,i,a)}function e3(e){for(let t=0;t<e.length;t++){let n=e[t];if(!Y4(n.column,`getIsVisible`,Z4))continue;let r=0;if(n.subHeaders.length){e3(n.subHeaders);for(let e=0;e<n.subHeaders.length;e++){let t=n.subHeaders[e];Y4(t.column,`getIsVisible`,Z4)&&(r+=t.colSpan)}}else r=1;if(n.colSpan=r,n.isPlaceholder&&n.subHeaders.length===1&&n.subHeaders[0].column===n.column){let e=1,t=n.subHeaders[0];for(;t;)t.rowSpan=0,e++,t=t.subHeaders.length===1&&t.subHeaders[0].column===n.column?t.subHeaders[0]:void 0;n.rowSpan=e}else n.rowSpan=1}}function t3(e,t,n,r){let i=Q4(e),a=[],o=n._headerGroupInstanceInitFns,s=Array(t.length);for(let e=0;e<t.length;e++)e in t&&(s[e]=X4(n,t[e],{depth:i,index:e}));return $4(s,i-1,n,r,a,o),a.reverse(),e3(a[0]?.headers??[]),a}function upe(e){if(!e._columnPrototype){e._columnPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignColumnPrototype?.(e._columnPrototype,e)}return e._columnPrototype}function dpe(e,t,n,r){let i={...e.getDefaultColumnDef(),...t},a=i.accessorKey,o=a===void 0?void 0:String(a),s=i.id??o?.replaceAll(`.`,`_`)??(typeof i.header==`string`?i.header:void 0),c;if(i.accessorFn)c=i.accessorFn;else if(a!==void 0){if(typeof a==`string`&&a.includes(`.`)){let e=a.split(`.`);c=t=>{let n=t;for(let t=0;t<e.length;t++){let r=e[t];n=n?.[r]}return n}}else c=e=>e[i.accessorKey]}if(!s)throw Error();let l=upe(e),u=Object.create(l);u.accessorFn=c,u.columnDef=i,u.columns=[],u.depth=n,u.id=`${String(s)}`,u.parent=r;let d=e._columnInstanceInitFns;for(let e=0;e<d.length;e++)d[e](u);return u}function n3(e){let t=e.atoms.columnOrder?.get();return n=>{let r=[];if(!t?.length)r=n;else{let e=new Map;for(let t=0;t<n.length;t++){let r=n[t];e.set(r.id,r)}for(let n=0;n<t.length;n++){let i=t[n],a=e.get(i);a&&(r.push(a),e.delete(i))}for(let t=0;t<n.length;t++){let i=n[t];e.has(i.id)&&r.push(i)}}return fpe(e,r)}}function fpe(e,t){let n=e.atoms.grouping?.get()??[],{groupedColumnMode:r}=e.options;if(!n.length||!r)return t;let i=t.filter(e=>!n.includes(e.id));if(r===`remove`)return i;let a=new Map;for(let e=0;e<t.length;e++){let n=t[e];a.set(n.id,n)}let o=[];for(let e=0;e<n.length;e++){let t=a.get(n[e]);t&&o.push(t)}return[...o,...i]}function ppe(e){return[e,...e.columns.flatMap(e=>e.getFlatColumns())]}function mpe(e){if(e.columns.length){let t=e.columns.flatMap(e=>e.getLeafColumns());return Y4(e.table,`getOrderColumns`,n3)(t)}return[e]}function hpe(e){return{header:e=>{let t=e.header.column.columnDef;return t.accessorKey?t.accessorKey:t.accessorFn?t.id:null},cell:e=>e.renderValue()?.toString?.()??null,...Object.values(e._features).reduce((e,t)=>Object.assign(e,t.getDefaultColumnDef?.()),{}),...e.options.defaultColumn}}function r3(e,t,n,r=0){let i=Array(t.length);for(let a=0;a<t.length;a++){if(!(a in t))continue;let o=t[a],s=dpe(e,o,r,n),c=o;s.columns=c.columns?r3(e,c.columns,s,r+1):[],i[a]=s}return i}function gpe(e){return r3(e,e.options.columns)}function _pe(e){return e.getAllColumns().flatMap(e=>e.getFlatColumns())}function vpe(e){let t=R4(),n=e.getAllFlatColumns();for(let e=0;e<n.length;e++){let r=n[e];t[r.id]=r}return t}function ype(e){let t=e.getAllColumns().flatMap(e=>e.getLeafColumns());return Y4(e,`getOrderColumns`,n3)(t)}function bpe(e){let t=R4(),n=e.getAllLeafColumns();for(let e=0;e<n.length;e++){let r=n[e];t[r.id]=r}return t}function xpe(e,t){return e.getAllFlatColumnsById()[t]}var Spe={assignColumnPrototype:(e,t)=>{J4(`coreColumnsFeature`,e,t,{column_getFlatColumns:{fn:e=>ppe(e),memoDeps:e=>[e.table.options.columns]},column_getLeafColumns:{fn:e=>mpe(e),memoDeps:e=>[e.table.atoms.columnOrder?.get(),e.table.atoms.grouping?.get(),e.table.options.columns,e.table.options.groupedColumnMode]}})},constructTableAPIs:e=>{q4(`coreColumnsFeature`,e,{table_getDefaultColumnDef:{fn:()=>hpe(e),memoDeps:()=>[e.options.defaultColumn]},table_getAllColumns:{fn:()=>gpe(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumns:{fn:()=>_pe(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumnsById:{fn:()=>vpe(e),memoDeps:()=>[e.options.columns]},table_getAllLeafColumns:{fn:()=>ype(e),memoDeps:()=>[e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.options.columns,e.options.groupedColumnMode]},table_getAllLeafColumnsById:{fn:()=>bpe(e),memoDeps:()=>[e.getAllLeafColumns()]},table_getColumn:{fn:t=>xpe(e,t)}})}};function i3(e,t){for(let n=0;n<e.subHeaders.length;n++)i3(e.subHeaders[n],t);t.push(e)}function Cpe(e){let t=[];return i3(e,t),t}function wpe(e){return{column:e.column,header:e,table:e.column.table}}function Tpe(e){let{start:t,end:n}=e.atoms.columnPinning?.get()??ape(),r=e.getAllColumns(),i=Y4(e,`getVisibleLeafColumns`,ope);if(!t.length&&!n.length)return t3(r,i,e);let a=e.getAllLeafColumnsById(),o=[];for(let e=0;e<t.length;e++){let n=a[t[e]];n&&Y4(n,`getIsVisible`,Z4)&&o.push(n)}let s=[];for(let e=0;e<n.length;e++){let t=a[n[e]];t&&Y4(t,`getIsVisible`,Z4)&&s.push(t)}let c=i.filter(e=>!t.includes(e.id)&&!n.includes(e.id));return t3(r,[...o,...c,...s],e)}function Epe(e){return[...e.getHeaderGroups()].reverse()}function Dpe(e){let t=e.getHeaderGroups(),n=[];for(let e=0;e<t.length;e++){let r=t[e].headers;for(let e=0;e<r.length;e++)n.push(r[e])}return n}function Ope(e){let t=e.getHeaderGroups()[0]?.headers??[],n=[];for(let e=0;e<t.length;e++){let r=t[e].getLeafHeaders();for(let e=0;e<r.length;e++)n.push(r[e])}return n}var kpe={assignHeaderPrototype:(e,t)=>{J4(`coreHeadersFeature`,e,t,{header_getLeafHeaders:{fn:e=>Cpe(e),memoDeps:e=>[e.column.table.options.columns]},header_getContext:{fn:e=>wpe(e),memoDeps:e=>[e.column.table.options.columns]}})},constructTableAPIs:e=>{q4(`coreHeadersFeature`,e,{table_getHeaderGroups:{fn:()=>Tpe(e),memoDeps:()=>[e.options.columns,e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.atoms.columnPinning?.get(),e.atoms.columnVisibility?.get(),e.options.groupedColumnMode]},table_getFooterGroups:{fn:()=>Epe(e),memoDeps:()=>[e.getHeaderGroups()]},table_getFlatHeaders:{fn:()=>Dpe(e),memoDeps:()=>[e.getHeaderGroups()]},table_getLeafHeaders:{fn:()=>Ope(e),memoDeps:()=>[e.getHeaderGroups()]}})}};function Ape(e){if(!e._rowPrototype){e._rowPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignRowPrototype?.(e._rowPrototype,e)}return e._rowPrototype}var jpe=(e,t,n,r,i,a,o)=>{let s=Ape(e),c=Object.create(s);c._displayIndexCache=-1,c._uniqueValuesCache=R4(),c._valuesCache=R4(),c.depth=i,c.id=t,c.index=r,c.original=n,c.parentId=o,c.subRows=a??[];let l=e._rowInstanceInitFns;for(let e=0;e<l.length;e++)l[e](c);return c},Mpe=/([0-9]+)/gm;function a3(e){let t=Object.assign((e,n,r)=>{let i=e.getValue(r),a=n.getValue(r),o=t.resolveDataValue;return o&&(i=o(i),a=o(a)),t.sort(i,a,e,n,r)},e);return t}a3({resolveDataValue:e=>c3(e).toLowerCase(),sort:(e,t)=>l3(e,t)}),a3({resolveDataValue:e=>c3(e),sort:(e,t)=>l3(e,t)}),a3({resolveDataValue:e=>c3(e).toLowerCase(),sort:(e,t)=>s3(e,t)}),a3({resolveDataValue:e=>c3(e),sort:(e,t)=>s3(e,t)}),a3({resolveDataValue:e=>Npe(e),sort:(e,t)=>e>t?1:e<t?-1:0});var o3=a3({sort:(e,t)=>s3(e,t)});function s3(e,t){return e===t?0:e>t?1:-1}function Npe(e){return e instanceof Date?e.getTime():e}function c3(e){return typeof e==`number`?isNaN(e)||e===1/0||e===-1/0?``:String(e):typeof e==`string`?e:``}function l3(e,t){let n=0,r=0,i=e.length,a=t.length;for(;n<i&&r<a;){let i=u3(e.charCodeAt(n)),a=u3(t.charCodeAt(r)),o=d3(e,n,i),s=d3(t,r,a);if(!i&&!a){let i=Ppe(e,n,o,t,r,s);if(i)return i;n=o,r=s;continue}if(i!==a)return i?1:-1;let c=Fpe(e,n,o,t,r,s);if(c)return c;n=o,r=s}return p3(e,n)-p3(t,r)}function u3(e){return e>=48&&e<=57}function d3(e,t,n){let r=t+1;for(;r<e.length&&u3(e.charCodeAt(r))===n;)r++;return r}function Ppe(e,t,n,r,i,a){let o=n-t,s=a-i,c=o<s?o:s;for(let n=0;n<c;n++){let a=e.charCodeAt(t+n),o=r.charCodeAt(i+n);if(a>o)return 1;if(o>a)return-1}return o>s?1:s>o?-1:0}function Fpe(e,t,n,r,i,a){let o=t;for(;o<n&&e.charCodeAt(o)===48;)o++;let s=i;for(;s<a&&r.charCodeAt(s)===48;)s++;let c=n-o,l=a-s;if(c===0&&l===0)return 0;if(c<=15&&l<=15){let t=f3(e,o,n),i=f3(r,s,a);return t>i?1:i>t?-1:0}let u=parseInt(e.slice(t,n),10),d=parseInt(r.slice(i,a),10);return u>d?1:d>u?-1:0}function f3(e,t,n){let r=0;for(let i=t;i<n;i++)r=r*10+e.charCodeAt(i)-48;return r}function p3(e,t){let n=0,r=t;for(;r<e.length;)n++,r=d3(e,r,u3(e.charCodeAt(r)));return n}function m3(){return[]}function Ipe(e,t){W4(e,`cellSelection`,t?m3():L4(e.initialState.cellSelection)??m3())}function Lpe(e){e.atoms.cellSelection&&(e.options.autoResetAll??e.options.autoResetCellSelection??!0)&&e._reactivity.schedule(()=>Ipe(e))}function Rpe(e){e.atoms.expanded&&(e.options.autoResetAll??e.options.autoResetExpanded??!e.options.manualExpanding)&&e._reactivity.schedule(()=>zpe(e))}function zpe(e,t){let n=e.initialState.expanded;W4(e,`expanded`,t?R4():n===!0||Object.assign(R4(),L4(n??{})))}var h3=0;function Bpe(e){if(e.options.autoResetAll??e.options.autoResetPageIndex??!e.options.manualPagination){if((e.atoms.pagination?.get()?.pageIndex??h3)===h3)return;Upe(e,!0)}}function Vpe(e,t){W4(e,`pagination`,t)}function Hpe(e,t){Vpe(e,n=>{let r=I4(t,n.pageIndex),i=e.options.pageCount===void 0||e.options.pageCount===-1?2**53-1:e.options.pageCount-1;return r=Math.max(0,Math.min(r,i)),{...n,pageIndex:r}})}function Upe(e,t){Hpe(e,t?h3:e.initialState.pagination?.pageIndex??h3)}function Wpe(){return[]}function g3(e,t){W4(e,`sorting`,t)}function _3(e,t){g3(e,t?[]:L4(e.initialState.sorting??[]))}function Gpe(e){e.atoms.sorting&&(e.options.autoResetAll??e.options.autoResetSorting??!1)&&_3(e)}function v3(e){let t=e.table._rowModelFns.sortFns,n=e.table.getFilteredRowModel().flatRows.slice(0,10),r,i=!1;for(let t=0;t<n.length;t++){let a=n[t].getValue(e.id);if(Object.prototype.toString.call(a)===`[object Date]`){r=`datetime`;break}if(typeof a==`string`&&(i=!0,a.split(Mpe).length>1)){r=`alphanumeric`;break}}if(!r&&i&&(r=`text`),r){let e=t?.[r];if(e||r===`alphanumeric`&&(e=t?.text),e)return e}return o3}function y3(e){let t=e.table.getFilteredRowModel().flatRows.slice(0,10);for(let n=0;n<t.length;n++){let r=t[n].getValue(e.id);if(r!=null)return typeof r==`string`?`asc`:`desc`}return`desc`}function Kpe(e){let t=e.table._rowModelFns.sortFns;return Xfe(e.columnDef.sortFn)?e.columnDef.sortFn:e.columnDef.sortFn===`auto`?v3(e):t?.[e.columnDef.sortFn]??o3}function b3(e,t,n){let r=S3(e,n&&w3(e)),i=t!==void 0;g3(e.table,a=>{let o=a.findIndex(t=>t.id===e.id),s=o===-1?void 0:a[o],c=[],l,u=i?t:r===`desc`,d=!!(a.length&&w3(e)&&n);return l=d?s?`toggle`:`add`:s?`toggle`:`replace`,l===`toggle`&&(i||r||(l=`remove`)),l===`add`?(c=[...a,{id:e.id,desc:u}],c.splice(0,c.length-(e.table.options.maxMultiSortColCount??2**53-1))):c=l===`toggle`?d?a.map(t=>t.id===e.id?{...t,desc:u}:t):[{id:e.id,desc:u}]:l===`remove`?d?a.filter(t=>t.id!==e.id):[]:[{id:e.id,desc:u}],c})}function x3(e){return e.columnDef.sortDescFirst??e.table.options.sortDescFirst??y3(e)===`desc`?`desc`:`asc`}function S3(e,t){let n=x3(e),r=T3(e);return r?r!==n&&(e.table.options.enableSortingRemoval??!0)&&(!t||(e.table.options.enableMultiRemove??!0))?!1:r===`desc`?`asc`:`desc`:n}function C3(e){return(e.columnDef.enableSorting??!0)&&(e.table.options.enableSorting??!0)&&!!e.accessorFn}function w3(e){return e.columnDef.enableMultiSort??e.table.options.enableMultiSort??!!e.accessorFn}function T3(e){let t=e.table.atoms.sorting?.get()?.find(t=>t.id===e.id);return t?t.desc?`desc`:`asc`:!1}function qpe(e){return e.table.atoms.sorting?.get()?.findIndex(t=>t.id===e.id)??-1}function Jpe(e){g3(e.table,t=>t.length?t.filter(t=>t.id!==e.id):[])}function Ype(e){let t=C3(e);return n=>{t&&b3(e,void 0,w3(e)?e.table.options.isMultiSortEvent?.(n):!1)}}function Xpe(){return e=>G4({feature:`coreRowModelsFeature`,table:e,fnName:`table.getCoreRowModel`,memoDeps:()=>[e.options.data],fn:()=>Zpe(e,e.options.data),onAfterUpdate:$fe(()=>{Rpe(e),Bpe(e),Gpe(e),Lpe(e)})})}function E3(e,t,n,r=0,i){let a=[];for(let o=0;o<n.length;o++){let s=n[o],c=jpe(e,e.getRowId(s,o,i),s,o,r,void 0,i?.id);t.flatRows.push(c),t.rowsById[c.id]=c,a.push(c),e.options.getSubRows&&(c.originalSubRows=e.options.getSubRows(s,o),c.originalSubRows?.length&&(c.subRows=E3(e,t,c.originalSubRows,r+1,c)))}return a}function Zpe(e,t){let n={rows:[],flatRows:[],rowsById:R4()};return n.rows=E3(e,n,t),n}function Qpe(e){return e._rowModels.coreRowModel||(e._rowModels.coreRowModel=e.options.features.coreRowModel?.(e)??Xpe()(e)),e._rowModels.coreRowModel()}function $pe(e){return e.getCoreRowModel()}function eme(e){return e._rowModels.filteredRowModel||(e._rowModels.filteredRowModel=e.options.features.filteredRowModel?.(e)),e.options.manualFiltering||!e._rowModels.filteredRowModel?e.getPreFilteredRowModel():e._rowModels.filteredRowModel()}function tme(e){return e.getFilteredRowModel()}function nme(e){return e._rowModels.groupedRowModel||(e._rowModels.groupedRowModel=e.options.features.groupedRowModel?.(e)),e.options.manualGrouping||!e._rowModels.groupedRowModel?e.getPreGroupedRowModel():e._rowModels.groupedRowModel()}function rme(e){return e.getGroupedRowModel()}function ime(e){return e._rowModels.sortedRowModel||(e._rowModels.sortedRowModel=e.options.features.sortedRowModel?.(e)),e.options.manualSorting||!e._rowModels.sortedRowModel?e.getPreSortedRowModel():e._rowModels.sortedRowModel()}function ame(e){return e.getSortedRowModel()}function ome(e){return e._rowModels.expandedRowModel||(e._rowModels.expandedRowModel=e.options.features.expandedRowModel?.(e)),e.options.manualExpanding||!e._rowModels.expandedRowModel?e.getPreExpandedRowModel():e._rowModels.expandedRowModel()}function sme(e){return e.getExpandedRowModel()}function cme(e){return e._rowModels.paginatedRowModel||(e._rowModels.paginatedRowModel=e.options.features.paginatedRowModel?.(e)),e.options.manualPagination||!e._rowModels.paginatedRowModel?e.getPrePaginatedRowModel():e._rowModels.paginatedRowModel()}function lme(e){return e.getPaginatedRowModel()}var ume={constructTableAPIs:e=>{q4(`coreRowModelsFeature`,e,{table_getCoreRowModel:{fn:()=>Qpe(e)},table_getPreFilteredRowModel:{fn:()=>$pe(e)},table_getFilteredRowModel:{fn:()=>eme(e)},table_getPreGroupedRowModel:{fn:()=>tme(e)},table_getGroupedRowModel:{fn:()=>nme(e)},table_getPreSortedRowModel:{fn:()=>rme(e)},table_getSortedRowModel:{fn:()=>ime(e)},table_getPreExpandedRowModel:{fn:()=>ame(e)},table_getExpandedRowModel:{fn:()=>ome(e)},table_getPrePaginatedRowModel:{fn:()=>sme(e)},table_getPaginatedRowModel:{fn:()=>cme(e)},table_getRowModel:{fn:()=>lme(e)}})}};function dme(e){if(!e._cellPrototype){e._cellPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignCellPrototype?.(e._cellPrototype,e)}return e._cellPrototype}function fme(e,t,n){let r=dme(n),i=Object.create(r);i.column=e,i.id=`${t.id}_${e.id}`,i.row=t;let a=n._cellInstanceInitFns;for(let e=0;e<a.length;e++)a[e](i);return i}function pme(e){let t=e.table.getRowsInDisplayOrder(),n=e._displayIndexCache;return t[n]===e?n:-1}function mme(e){let t=e.getPrePaginatedRowModel().rows;if(e.options.paginateExpandedRows===!1){let e=[],n=t=>{t._displayIndexCache=e.length,e.push(t),t.subRows.length&&t.getIsExpanded?.()&&t.subRows.forEach(n)};return t.forEach(n),e}for(let e=0;e<t.length;e++)t[e]._displayIndexCache=e;return t}function hme(e,t){if(z4(e._valuesCache,t))return e._valuesCache[t];let n=e.table.getColumn(t);if(n?.accessorFn)return e._valuesCache[t]=n.accessorFn(e.original,e.index),e._valuesCache[t]}function gme(e,t){if(z4(e._uniqueValuesCache,t))return e._uniqueValuesCache[t];let n=e.table.getColumn(t);if(n?.accessorFn)return n.columnDef.getUniqueValues?(e._uniqueValuesCache[t]=n.columnDef.getUniqueValues(e.original,e.index),e._uniqueValuesCache[t]):(e._uniqueValuesCache[t]=[e.getValue(t)],e._uniqueValuesCache[t])}function _me(e,t){return e.getValue(t)??e.table.options.renderFallbackValue}function vme(e){return Zfe(e.subRows,e=>e.subRows)}function yme(e){let t=e.getCoreRowModel().flatRows,n=0;for(let e=0;e<t.length;e++)n=Math.max(n,t[e].depth);return n}function bme(e){if(e.parentId)return e.table.getCoreRowModel().rowsById[e.parentId]??e.table.getRow(e.parentId,!0)}function xme(e){let t=[],n=e;for(;;){let e=n.getParentRow();if(!e)break;t.push(e),n=e}return t.reverse()}function Sme(e){let t=e.table.getAllLeafColumns(),n=e._cellsCache;n||=e._cellsCache=new WeakMap;let r=Array(t.length);for(let i=0;i<t.length;i++){let a=t[i],o=n.get(a);o||(o=fme(a,e,e.table),n.set(a,o)),r[i]=o}return r}function Cme(e){let t=R4(),n=e.getAllCells();for(let e=0;e<n.length;e++){let r=n[e];t[r.column.id]=r}return t}function wme(e,t,n,r){return t.options.getRowId?.(e,n,r)??(r?`${r.id}.${n}`:String(n))}function Tme(e,t,n){let r=(n?e.getPrePaginatedRowModel():e.getRowModel()).rowsById[t];if(!r&&(r=e.getCoreRowModel().rowsById[t],!r))throw Error();return r}var Eme={assignRowPrototype:(e,t)=>{J4(`coreRowsFeature`,e,t,{row_getDisplayIndex:{fn:e=>pme(e)},row_getAllCellsByColumnId:{fn:e=>Cme(e),memoDeps:e=>[e.getAllCells()]},row_getAllCells:{fn:e=>Sme(e),memoDeps:e=>[e.table.getAllLeafColumns()]},row_getLeafRows:{fn:e=>vme(e),memoDeps:e=>[e.subRows]},row_getParentRow:{fn:e=>bme(e)},row_getParentRows:{fn:e=>xme(e)},row_getUniqueValues:{fn:(e,t)=>gme(e,t)},row_getValue:{fn:(e,t)=>hme(e,t)},row_renderValue:{fn:(e,t)=>_me(e,t)}})},constructTableAPIs:e=>{q4(`coreRowsFeature`,e,{table_getRowsInDisplayOrder:{fn:()=>mme(e),memoDeps:()=>[e.getPrePaginatedRowModel().rows,e.options.paginateExpandedRows,e.options.paginateExpandedRows===!1?e.atoms.expanded?.get():void 0]},table_getRowId:{fn:(t,n,r)=>wme(t,e,n,r)},table_getRow:{fn:(t,n)=>Tme(e,t,n)},table_getMaxSubRowDepth:{fn:()=>yme(e),memoDeps:()=>[e.getCoreRowModel()]}})}};function D3(e,t,n=(e,t)=>e===t){let r=t===void 0?e.options.state:t;e._reactivity.batch(()=>{if(r)for(let t in r){let i=e.baseAtoms[t];if(!i)continue;let a=r[t],o=a===void 0?e.initialState[t]:a;n(e._reactivity.untrack(()=>i.get()),o)||i.set(()=>o)}})}function O3(e,t,n=(e,t)=>e===t){e._reactivity.batch(()=>{D3(e,t,n),e._reactivity.commit?.()})}function Dme(e){let t=L4(e.initialState);e._reactivity.batch(()=>{let n=Object.keys(t);for(let r=0;r<n.length;r++){let i=n[r];e.baseAtoms[i].set(t[i])}});let n=Object.values(e._features);for(let t=0;t<n.length;t++)n[t].resetTableInstanceData?.(e)}function Ome(e,t){let{features:n,atoms:r,initialState:i}=e.options;if(!e.options.mergeOptions)return{...e.options,...t,features:n,atoms:r,initialState:i};let a=e.options.mergeOptions(e.options,t),o={...Object.getOwnPropertyDescriptors(a)};return Object.defineProperties(Object.create(Object.getPrototypeOf(a)),{...o,features:{value:n,enumerable:!0,configurable:!0,writable:!0},atoms:{value:r,enumerable:!0,configurable:!0,writable:!0},initialState:{value:i,enumerable:!0,configurable:!0,writable:!0}})}function k3(e,t,n){let r=Ome(e,I4(t,e.options));e.optionsStore?e.optionsStore.set(()=>r):e.options=r,n?.syncExternalState!==!1&&O3(e,r.state??null)}var kme={coreCellsFeature:rpe,coreColumnsFeature:Spe,coreHeadersFeature:kpe,coreRowModelsFeature:ume,coreRowsFeature:Eme,coreTablesFeature:{constructTableAPIs:e=>{q4(`coreTablesFeature`,e,{table_reset:{fn:()=>Dme(e)},table_setOptions:{fn:t=>k3(e,t)}})}}};function Ame(){return{accessor:(e,t)=>typeof e==`function`?{...t,accessorFn:e}:{...t,accessorKey:e},columns:e=>e,display:e=>e,group:e=>e}}function jme(e){return e}function Mme(e,t={}){return Object.values(e).forEach(e=>{t=e.getInitialState?.(t)??t}),L4(t)}function Nme(e){let t=e.features.coreReactivityFeature,{aggregationFns:n,columnMeta:r,coreRowModel:i,expandedRowModel:a,facetedMinMaxValues:o,facetedRowModel:s,facetedUniqueValues:c,filterFns:l,filterMeta:u,filteredRowModel:d,groupedRowModel:f,paginatedRowModel:p,sortFns:m,sortedRowModel:h,tableMeta:g,..._}=e.features,v={_cellInstanceInitFns:[],_columnInstanceInitFns:[],_features:{...kme,..._},_headerGroupInstanceInitFns:[],_headerInstanceInitFns:[],_reactivity:t,_rowInstanceInitFns:[],_rowModelFns:{aggregationFns:n,filterFns:l,sortFns:m},_rowModels:{},atoms:{},baseAtoms:{}},y=Object.values(v._features),b={...y.reduce((e,t)=>Object.assign(e,t.getDefaultTableOptions?.(v)),{}),...e};if(t.wrapExternalAtoms&&b.atoms)for(let[e,n]of Object.entries(b.atoms)){let r=n,i=t.createWritableAtom(r.get(),{debugName:`externalAtom/${e}`});b.atoms[e]=i;let a=!1,o=r.subscribe(e=>{a||i.set(e)}),s=i.subscribe(e=>{a=!0,r.set(e),a=!1});t.addSubscription(o),t.addSubscription(s)}t.createOptionsStore?(v.optionsStore=t.createWritableAtom(b,{debugName:`table/optionsStore`}),Object.defineProperty(v,"options",{configurable:!0,enumerable:!0,get(){return v.optionsStore.get()},set(e){v.optionsStore.set(()=>e)}})):v.options=b,v.initialState=Mme(v._features,v.options.initialState);let x=Object.keys(v.initialState);for(let e=0;e<x.length;e++){let n=x[e];v.baseAtoms[n]=t.createWritableAtom(v.initialState[n],{debugName:`table/baseAtoms/${n}`}),v.atoms[n]=t.createReadonlyAtom(()=>{let e=v.options,t=e.atoms?.[n],r=t?t.get():v.baseAtoms[n].get();if(t)return r;let i=e.state;if(i&&z4(i,n)){let e=i[n];return e===void 0?v.initialState[n]:e}return r},{debugName:`table/atoms/${n}`})}D3(v),v.store=Ufe(t.createReadonlyAtom(()=>{let e={};for(let t=0;t<x.length;t++){let n=x[t];e[n]=v.atoms[n].get()}return e},{compare:N4,debugName:`table/store`}));for(let e=0;e<y.length;e++){let t=y[e];t.initTableInstanceData?.(v),t.initCellInstanceData&&v._cellInstanceInitFns.push(t.initCellInstanceData.bind(t)),t.initColumnInstanceData&&v._columnInstanceInitFns.push(t.initColumnInstanceData.bind(t)),t.initHeaderGroupInstanceData&&v._headerGroupInstanceInitFns.push(t.initHeaderGroupInstanceData.bind(t)),t.initHeaderInstanceData&&v._headerInstanceInitFns.push(t.initHeaderInstanceData.bind(t)),t.initRowInstanceData&&v._rowInstanceInitFns.push(t.initRowInstanceData.bind(t)),t.constructTableAPIs?.(v)}return v}function Pme(){return R4()}function A3(e,t){e.options.onRowSelectionChange?.(t)}function Fme(e,t){e._lastSelectedRowId=null,A3(e,t?R4():Object.assign(R4(),L4(e.initialState.rowSelection??{})))}function j3(e,t,n){e._lastSelectedRowId=null,A3(e,r=>{if(t=t===void 0?!Y4(e,`getIsAllRowsSelected`,P3):t,n?.deselectAll&&!t)return R4();let i=Object.assign(R4(),r),a=e.getPreGroupedRowModel().flatRows;if(t){let e=new Map;a.forEach(t=>{W3(t,e)&&(i[t.id]=!0)})}else a.forEach(e=>{B3(e)&&delete i[e.id]});return i})}function M3(e,t,n){e._lastSelectedRowId=null,A3(e,r=>{let i=t===void 0?!Y4(e,`getIsAllPageRowsSelected`,F3):t;if(n?.deselectAll&&!i)return R4();let a=Object.assign(R4(),r);return e.getRowModel().rows.forEach(t=>{U3(a,t.id,i,!0,e,!0)}),a})}function Ime(e){return e.getCoreRowModel()}function Lme(e){let t=e.getCoreRowModel();return Y4(e,`getIsSomeRowsSelected`,I3)?q3(t,e):{rows:[],flatRows:[],rowsById:R4()}}function Rme(e){let t=e.getFilteredRowModel();return Y4(e,`getIsSomeRowsSelected`,I3)?q3(t,e):{rows:[],flatRows:[],rowsById:R4()}}function zme(e){let t=e.getSortedRowModel();return Y4(e,`getIsSomeRowsSelected`,I3)?q3(t,e):{rows:[],flatRows:[],rowsById:R4()}}function N3(e){return Object.keys(e.atoms.rowSelection?.get()??{})}function P3(e){let t=e.getFilteredRowModel().flatRows,n=e.atoms.rowSelection?.get()??{},r=!!(t.length&&Object.keys(n).length);if(r){let e=new Map;t.some(t=>!J3(t,n)&&W3(t,e))&&(r=!1)}return r}function F3(e){let t=e.getPaginatedRowModel().flatRows,n=e.atoms.rowSelection?.get()??{},r=new Map,i=!1;for(let e=0;e<t.length;e++){let a=t[e];if(J3(a,n))!i&&W3(a,r)&&(i=!0);else if(W3(a,r))return!1}return i}function I3(e){return Y4(e,`getSelectedRowIds`,N3).length>0}function Bme(e){return e.getPaginatedRowModel().flatRows.filter(e=>B3(e)).some(e=>R3(e)||Y4(e,`getIsSomeSelected`,z3))}function Vme(e){return t=>{j3(e,t.target.checked)}}function Hme(e){return t=>{M3(e,t.target.checked)}}function L3(e,t,n){let r=R3(e);A3(e.table,i=>{t=t===void 0?!r:t;let a=Object.assign(R4(),i);return U3(a,e.id,t,(n?.selectChildren??!0)&&H3(e),e.table),!t&&n?.deselectParents&&G3(a,e),a})}function R3(e){return J3(e,e.table.atoms.rowSelection?.get()??{})}function z3(e){return Y3(e)===`some`}function Ume(e){return Y3(e)===`all`}function B3(e){let t=e.table.options;return typeof t.enableRowSelection==`function`?t.enableRowSelection(e):t.enableRowSelection??!0}function V3(e){let t=e.table.options;return typeof t.enableSubRowSelection==`function`?t.enableSubRowSelection(e):t.enableSubRowSelection??!0}function H3(e){let t=e.table.options;return typeof t.enableMultiRowSelection==`function`?t.enableMultiRowSelection(e):t.enableMultiRowSelection??!0}function Wme(e,t){let n=B3(e);return r=>{if(!n)return;let i=r,a=e.table,o=i.target.checked,s=a._lastSelectedRowId;(!(a.options.enableRowRangeSelection!==!1&&s!==null&&H3(e)&&(a.options.isRowRangeSelectionEvent?.(r)??!1))||!Gme(e,s,o,t))&&L3(e,o,t),a._lastSelectedRowId=e.id}}function Gme(e,t,n,r){let i=r?.selectChildren??!0,a=e.table,o=a.getRowsInDisplayOrder(),s=a.getPrePaginatedRowModel().rowsById[t]??a.getCoreRowModel().rowsById[t];if(!s)return!1;let c=s.getDisplayIndex(),l=e.getDisplayIndex(),u=o[c],d=o[l];if(c<0||l<0||c>=o.length||l>=o.length||u?.id!==s.id||d?.id!==e.id||!H3(s)||!H3(e))return!1;let f=Math.min(c,l),p=Math.max(c,l);return A3(a,e=>{let t=Object.assign(R4(),e);for(let e=f;e<=p;e++){let s=o[e];B3(s)&&H3(s)&&(U3(t,s.id,n,i,a),!n&&r?.deselectParents&&G3(t,s))}return t}),!0}function U3(e,t,n,r,i,a){let o=i.getRow(t,!0);n?(H3(o)||Object.keys(e).forEach(t=>delete e[t]),B3(o)&&(e[t]=!0)):(!a||B3(o))&&delete e[t],r&&o.subRows.length&&V3(o)&&o.subRows.forEach(t=>U3(e,t.id,n,r,i,a))}function W3(e,t){if(!B3(e))return!1;let n=e.table;if(n.options.enableSubRowSelection===!0)return!0;let r=e.parentId;if(r===void 0)return!0;let i=t.get(r);if(i!==void 0)return i;let a=n.getCoreRowModel().rowsById,o=[],s=!0,c=r;for(;c!==void 0;){let e=t.get(c);if(e!==void 0){s=e;break}o.push(c);let r=a[c]??n.getRow(c,!0);if(!V3(r)){s=!1;break}c=r.parentId}return o.forEach(e=>t.set(e,s)),s}function G3(e,t){let n=t.table.getCoreRowModel().rowsById,r=t.parentId;for(;r!==void 0;)delete e[r],r=(n[r]??t.table.getRow(r,!0)).parentId}function K3(e,t,n,r){let i=[];for(let a=0;a<e.length;a++){let o=e[a],s=J3(o,t);if(s&&(n.push(o),r[o.id]=o),o.subRows.length){let e=K3(o.subRows,t,n,r);if(s){let t=Object.create(Object.getPrototypeOf(o));qfe(t,o),t.subRows=e,i.push(t)}}else s&&i.push(o)}return i}function q3(e,t){let n=[],r=R4(),i=t.atoms.rowSelection?.get()??{};return{rows:K3(e.rows,i,n,r),flatRows:n,rowsById:r}}function J3(e,t){return!!(z4(t,e.id)&&t[e.id])}function Y3(e){if(!e.subRows.length)return!1;let t=e.table.atoms.rowSelection?.get()??{},n=!1,r=!0,i=!1;for(let a=0;a<e.subRows.length;a++){let o=e.subRows[a];if(n&&!r)break;if(B3(o)&&(i=!0,J3(o,t)?n=!0:r=!1),o.subRows.length){let e=Y3(o);e===`all`?(n=!0,i=!0):e===`some`?(n=!0,r=!1,i=!0):r=!1}}return i?r?`all`:n?`some`:!1:!1}var Kme={initTableInstanceData:e=>{e._lastSelectedRowId=null},resetTableInstanceData:e=>{e._lastSelectedRowId=null},getInitialState:e=>({rowSelection:Pme(),...e}),getDefaultTableOptions:e=>({onRowSelectionChange:B4(`rowSelection`,e),enableRowSelection:!0,enableMultiRowSelection:!0,enableRowRangeSelection:!0,enableSubRowSelection:!0,isRowRangeSelectionEvent:e=>{let t=e;return!!(t.shiftKey||t.nativeEvent?.shiftKey)}}),assignRowPrototype:(e,t)=>{J4(`rowSelectionFeature`,e,t,{row_toggleSelected:{fn:(e,t,n)=>L3(e,t,n)},row_getIsSelected:{fn:e=>R3(e)},row_getIsSomeSelected:{fn:e=>z3(e),memoDeps:e=>[e.subRows,e.table.atoms.rowSelection?.get(),e.table.options.enableRowSelection]},row_getIsAllSubRowsSelected:{fn:e=>Ume(e),memoDeps:e=>[e.subRows,e.table.atoms.rowSelection?.get(),e.table.options.enableRowSelection]},row_getCanSelect:{fn:e=>B3(e)},row_getCanSelectSubRows:{fn:e=>V3(e)},row_getCanMultiSelect:{fn:e=>H3(e)},row_getToggleSelectedHandler:{fn:(e,t)=>Wme(e,t)}})},constructTableAPIs:e=>{q4(`rowSelectionFeature`,e,{table_setRowSelection:{fn:t=>A3(e,t)},table_resetRowSelection:{fn:t=>Fme(e,t)},table_toggleAllRowsSelected:{fn:(t,n)=>j3(e,t,n)},table_toggleAllPageRowsSelected:{fn:(t,n)=>M3(e,t,n)},table_getPreSelectedRowModel:{fn:()=>Ime(e)},table_getSelectedRowModel:{fn:()=>Lme(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getCoreRowModel()]},table_getFilteredSelectedRowModel:{fn:()=>Rme(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getFilteredRowModel()]},table_getGroupedSelectedRowModel:{fn:()=>zme(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getSortedRowModel()]},table_getSelectedRowIds:{fn:()=>N3(e),memoDeps:()=>[e.atoms.rowSelection?.get()]},table_getIsAllRowsSelected:{fn:()=>P3(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getFilteredRowModel(),e.options.enableRowSelection,e.options.enableSubRowSelection]},table_getIsAllPageRowsSelected:{fn:()=>F3(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getPaginatedRowModel(),e.options.enableRowSelection,e.options.enableSubRowSelection]},table_getIsSomeRowsSelected:{fn:()=>I3(e),memoDeps:()=>[e.atoms.rowSelection?.get()]},table_getIsSomePageRowsSelected:{fn:()=>Bme(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getPaginatedRowModel(),e.options.enableRowSelection]},table_getToggleAllRowsSelectedHandler:{fn:()=>Vme(e)},table_getToggleAllPageRowsSelectedHandler:{fn:()=>Hme(e)}})}},qme={getInitialState(e){return{sorting:Wpe(),...e}},getDefaultColumnDef(){return{sortFn:`auto`,sortUndefined:1}},getDefaultTableOptions(e){return{autoResetSorting:!1,onSortingChange:B4(`sorting`,e),isMultiSortEvent:e=>e.shiftKey}},assignColumnPrototype(e,t){J4(`rowSortingFeature`,e,t,{column_getAutoSortFn:{fn:e=>v3(e)},column_getAutoSortDir:{fn:e=>y3(e)},column_getSortFn:{fn:e=>Kpe(e)},column_toggleSorting:{fn:(e,t,n)=>b3(e,t,n)},column_getFirstSortDir:{fn:e=>x3(e)},column_getNextSortingOrder:{fn:(e,t)=>S3(e,t)},column_getCanSort:{fn:e=>C3(e)},column_getCanMultiSort:{fn:e=>w3(e)},column_getIsSorted:{fn:e=>T3(e)},column_getSortIndex:{fn:e=>qpe(e)},column_clearSorting:{fn:e=>Jpe(e)},column_getToggleSortingHandler:{fn:e=>Ype(e)}})},constructTableAPIs(e){q4(`rowSortingFeature`,e,{table_setSorting:{fn:t=>g3(e,t)},table_resetSorting:{fn:t=>_3(e,t)}})}},Jme=typeof window>`u`?o.useEffect:o.useLayoutEffect;function Yme(e,t){let[{table:n,rootSource:r}]=(0,o.useState)(()=>{let t=Nme({...e,features:{coreReactivityFeature:Kfe(),...e.features}});return t.Subscribe=(e=>Hfe({...e,source:e.source??t.store})),t.FlexRender=Nfe,{table:t,rootSource:Gfe(t.store,N4)}}),i=n;k3(i,t=>({...t,...e}),{syncExternalState:!1});let a=i.options.state,s=r.get(),c=F4(r,t,{compare:N4});return Jme(()=>{r.markCommitted(s),O3(i,a??null,N4)}),(0,o.useMemo)(()=>({...n,options:e,state:c}),[n,e,c])}var Xme=e=>t=>{let n=t.currentTarget;n.scrollWidth>Math.ceil(n.getBoundingClientRect().width)?n.title=e:n.removeAttribute(`title`)},X3=({text:e,className:t})=>(0,V.jsx)(`span`,{className:B(`truncate`,t),onMouseEnter:Xme(e),children:e}),Z3=e=>(0,V.jsx)(`span`,{className:`text-faint-foreground`,children:e}),Q3=(e,t)=>{if(t==null)return Z3(`—`);let n=ux(e,t)??``;switch(e.kind){case`text`:return e.link?(0,V.jsx)(PC,{format:e.link,value:n,className:`block min-w-0 truncate`}):(0,V.jsx)(X3,{text:n});case`id`:return(0,V.jsx)(X3,{text:n,className:`font-mono text-xs text-muted-foreground`});case`money`:return(0,V.jsx)(`span`,{className:`tabular-nums`,children:n});case`date`:return(0,V.jsx)(`span`,{className:`tabular-nums text-muted-foreground`,children:n});case`datetime`:return(0,V.jsx)(`span`,{className:`tabular-nums text-muted-foreground`,title:`Shown in ${ef(Number(t),Wd())}`,children:n});case`number`:return(0,V.jsx)(`span`,{className:`tabular-nums`,children:n});case`signed`:return(0,V.jsx)(`span`,{className:B(`tabular-nums`,Number(t)<0?`text-danger-text`:`text-success-text`),children:n});case`percent`:return Number(t)===0?Z3(`—`):(0,V.jsx)(`span`,{className:`tabular-nums`,children:n});case`status`:return(0,V.jsx)(Au,{tone:e.tones?.[String(t)]??`neutral`,color:f4(e.colors,t),shape:e.shape,children:n});case`relation`:return(0,V.jsx)(X3,{text:n,className:`font-medium text-primary-text hover:underline`});case`boolean`:return t?(0,V.jsx)(`span`,{className:`inline-flex size-4 items-center justify-center rounded-full bg-success-soft text-success-text`,children:(0,V.jsx)(ge,{className:`size-3`,strokeWidth:3})}):Z3(`No`);case`file`:{let e=bb(t);if(!e)return Z3(`—`);if(`missing`in e)return(0,V.jsx)(X3,{text:e.name,className:`text-danger-text`});let n=Ob(t,{width:20,height:20});return(0,V.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[n?(0,V.jsx)(hC,{image:n,className:`size-5 shrink-0 rounded-sm object-cover`}):(0,V.jsx)(en,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,V.jsx)(X3,{text:e.name})]})}case`user`:{let e=Ey(String(t));return(0,V.jsxs)(`span`,{className:`inline-flex items-center gap-2 truncate`,children:[(0,V.jsx)(xu,{initials:e.initials,hue:e.hue,size:`xs`,className:`ring-0`}),(0,V.jsx)(X3,{text:e.name,className:`text-muted-foreground`})]})}}},Zme=jme({rowSortingFeature:qme,rowSelectionFeature:Kme}),$3=Ame(),Qme=e=>$3.columns(e.map(e=>$3.accessor(t=>e.value?e.value(t):t[e.id],{id:e.id,header:e.header,enableSorting:e.sortable??!1,cell:t=>e.render?e.render(t.row.original):Q3(e,t.getValue())}))),$me=({total:e,selectedCount:t,bulkActions:n=[],className:r})=>(0,V.jsx)(`div`,{className:B(`flex h-9 shrink-0 items-center border-t bg-surface px-3 text-xs text-muted-foreground`,r),children:(0,V.jsxs)(`span`,{className:`flex items-center tabular-nums`,children:[Ud(e),t>0&&(0,V.jsxs)(`span`,{className:`ml-3 font-medium text-primary-text`,children:[Bd(t),` selected`]}),t>0&&n.map(e=>(0,V.jsx)(`button`,{type:`button`,onClick:e.onRun,className:B(`ml-3 rounded border bg-background px-2 py-0.5 font-medium hover:bg-muted`,e.destructive?`border-danger/40 text-danger-text`:`text-foreground`),children:e.label},e.label))]})}),ehe=(e,t)=>e.filter(e=>e.available?.(t)??!0),the=({row:e,actions:t})=>{let{open:n,setOpen:r,place:i,button:a,menu:o}=fb();return(0,V.jsxs)(`div`,{className:`relative flex justify-center bg-inherit`,onClick:e=>e.stopPropagation(),children:[(0,V.jsx)(`button`,{ref:a,type:`button`,"aria-label":`Row actions`,"aria-haspopup":`menu`,"aria-expanded":n,onClick:()=>r(!n),className:`inline-flex items-center justify-center rounded p-1 text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-11`,children:(0,V.jsx)(Xe,{className:`size-4`})}),n&&(0,nr.createPortal)((0,V.jsx)(`ul`,{ref:o,role:`menu`,onClick:e=>e.stopPropagation(),style:i??{visibility:`hidden`},className:`fixed z-50 min-w-36 rounded-md border bg-background py-1 shadow-pop`,children:t.map(t=>(0,V.jsx)(`li`,{role:`none`,children:t.link?(0,V.jsx)(du,{role:`menuitem`,to:t.link(e),onClick:()=>r(!1),className:B(`block w-full px-3 py-1.5 text-left hover:bg-muted`,t.destructive&&`text-danger-text`),children:t.label}):(0,V.jsx)(`button`,{type:`button`,role:`menuitem`,className:B(`block w-full px-3 py-1.5 text-left hover:bg-muted`,t.destructive&&`text-danger-text`),onClick:()=>{r(!1),t.onSelect(e)},children:t.label})},t.label))}),document.body)]})},nhe=e=>52+Math.ceil(String(e).length*1.33)*7,e6=.6,t6=(e,t)=>Math.max(e.minWidth??0,e.width*t),rhe=(e,t)=>e.fixed?`${Math.max(e.minWidth??0,e.width)}px`:`minmax(${t6(e,t)}px, ${e.width}fr)`,n6=(e,t,n=0,r=e6)=>`${t}px ${e.map(e=>rhe(e,r)).join(` `)}${n>0?` ${n}px`:``}`,ihe=(e,t,n=0,r=e6)=>t+n+e.reduce((e,t)=>e+(t.fixed?Math.max(t.minWidth??0,t.width):t6(t,r)),0),ahe=()=>{let e=(0,o.useRef)(null),t=(0,o.useRef)(null),[n,r]=(0,o.useState)({scrolled:!1,more:!1}),i=(0,o.useCallback)(()=>{let t=e.current;if(!t)return;let n={scrolled:t.scrollLeft>1,more:t.scrollLeft+t.clientWidth<t.scrollWidth-1};r(e=>e.scrolled===n.scrolled&&e.more===n.more?e:n)},[]);return{ref:e,attach:(0,o.useCallback)(n=>{if(t.current?.disconnect(),t.current=null,e.current=n,!n)return;let r=new ResizeObserver(i);r.observe(n);for(let e of Array.from(n.children))r.observe(e);t.current=r,i()},[i]),onScroll:i,...n}},ohe=`protobase:pinned:`,she=(e,t)=>`${ohe}${e}:${t}`,che=(e,t)=>zu(()=>{let n=e.getItem(t);if(n===null)return;let r=JSON.parse(n);return Array.isArray(r)&&r.every(e=>typeof e==`string`)?r:void 0},void 0),lhe=(e,t,n)=>zu(()=>e.setItem(t,JSON.stringify(n)),void 0),uhe=(e,t=[])=>{let[n,r]=(0,o.useState)(()=>e?che(localStorage,e):void 0),i=(0,o.useCallback)(t=>{r(t),e&&lhe(localStorage,e,t)},[e]);return[n??t,i]},dhe=e=>{let t=e.findIndex(e=>e.title);return t<0||t>1?[]:e.slice(0,t+1).map(e=>e.id)},fhe=e=>Object.fromEntries(e.map(({id:e,width:t,minWidth:n,fixed:r})=>[e,{width:t,minWidth:n,fixed:r}])),phe=(e,t)=>{let n=e.map(e=>e.id).sort().join(` `),[r,i]=(0,o.useState)(),a=r?.key===n?r:void 0;!a&&t.length>0&&i({key:n,sizes:fhe(Dx(e,t))});let s=a?.sizes;return(0,o.useMemo)(()=>s?e.map(e=>({...e,...s[e.id]})):e,[e,s])},r6=e=>e===`money`||e===`number`||e===`signed`||e===`percent`,mhe=`This column can't be sorted`,hhe=({header:e,pinned:t,sortable:n,onTogglePin:r})=>{let[i,a]=(0,o.useState)(!1),s=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(!i)return;let e=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!s.current?.contains(e.target))&&a(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,e)}},[i]),(0,V.jsxs)(`div`,{ref:s,className:`relative ml-auto shrink-0`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":`${e} column menu`,"aria-haspopup":`menu`,"aria-expanded":i,onClick:()=>a(!i),className:`relative inline-flex size-5 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:opacity-100 after:absolute after:-inset-2 after:content-[''] md:opacity-0 md:group-hover/cell:opacity-100 aria-expanded:opacity-100`,children:(0,V.jsx)(Xe,{className:`size-3.5`})}),i&&(0,V.jsxs)(`ul`,{role:`menu`,className:`absolute right-0 top-full z-30 mt-1 min-w-32 rounded-md border bg-background py-1 text-body font-normal text-foreground shadow-pop`,children:[!n&&(0,V.jsx)(`li`,{role:`none`,children:(0,V.jsx)(`span`,{role:`menuitem`,"aria-disabled":`true`,className:`block min-h-9 whitespace-nowrap px-3 py-1.5 text-muted-foreground`,children:`This column can't be sorted`})}),(0,V.jsx)(`li`,{role:`none`,children:(0,V.jsx)(`button`,{type:`button`,role:`menuitem`,className:`block min-h-9 w-full whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted`,onClick:()=>{a(!1),r()},children:t?`Unpin`:`Pin to left`})})]})]})},ghe=({sorted:e})=>e===`asc`?(0,V.jsx)(A,{className:`size-3 text-foreground`}):e===`desc`?(0,V.jsx)(S,{className:`size-3 text-foreground`}):(0,V.jsx)(we,{className:`size-3 opacity-0 group-hover/head:opacity-100`}),i6=({spec:e})=>(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`span`,{className:`truncate`,children:e.header}),e.highlight&&(0,V.jsx)(`span`,{className:`rounded bg-primary px-1 text-[10px] font-semibold uppercase leading-4 text-primary-foreground`,children:`New`})]}),_he=({cells:e,specs:t,gutter:n,selectedCount:r,selectable:i,trailing:a,minScale:o,pins:s={},lastPinned:c,scrolled:l,onTogglePin:u,onClearSelection:d})=>(0,V.jsxs)(`div`,{className:`grid h-8 shrink-0 items-center border-b bg-surface text-xs font-medium text-muted-foreground`,style:{gridTemplateColumns:n6(t,n,a,o)},role:`row`,children:[(0,V.jsxs)(`div`,{className:B(`sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3`,l&&!c&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:n},children:[i&&(0,V.jsx)(Fh,{checked:!1,indeterminate:r>0,label:r>0?`Clear selection`:`No rows selected`,disabled:r===0,onChange:d,className:B(r===0&&`opacity-60`)}),n>40&&(0,V.jsx)(`span`,{className:`w-6 text-right text-faint-foreground`,children:`#`})]}),e.map(({spec:e,sorted:t,onSort:n})=>{let r=e.id in s;return(0,V.jsxs)(`div`,{"data-col-id":e.id,style:r?{left:s[e.id]}:void 0,className:B(`group/cell flex h-full min-w-0 items-center`,r&&`sticky z-10 bg-inherit`,r&&l&&e.id===c&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`,e.highlight&&`bg-primary-soft text-primary-text`),children:[e.sortable?(0,V.jsxs)(`button`,{type:`button`,onClick:n,className:B(`group/head flex h-full min-w-0 flex-1 items-center gap-1 pl-3 pr-1 text-left`,r6(e.kind)&&`justify-end`,`hover:text-foreground`,t&&`text-foreground`),children:[(0,V.jsx)(i6,{spec:e}),(0,V.jsx)(ghe,{sorted:t})]}):(0,V.jsx)(`div`,{title:mhe,className:B(`flex h-full min-w-0 flex-1 items-center gap-1 pl-3 pr-1 text-left`,r6(e.kind)&&`justify-end`),children:(0,V.jsx)(i6,{spec:e})}),(0,V.jsx)(`div`,{className:`pr-1.5`,children:(0,V.jsx)(hhe,{header:e.header,pinned:r,sortable:!!e.sortable,onTogglePin:()=>u(e.id)})})]},e.id)}),a?(0,V.jsx)(`div`,{className:`sticky right-0 z-10 h-full bg-inherit`}):null]}),a6=e=>({gridTemplateColumns:n6(e.specs,e.gutter,e.trailing,e.minScale),height:e.height,transform:`translateY(${e.offset}px)`}),o6=(e,t)=>B(`flex h-full min-w-0 items-center overflow-hidden whitespace-nowrap px-3`,r6(e.kind)&&`justify-end`,e.highlight&&`bg-primary-soft/60`,t.pins&&e.id in t.pins&&`sticky z-10 bg-inherit`,t.scrolled&&e.id===t.lastPinned&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),s6=(e,t)=>t&&e.id in t?{left:t[e.id]}:void 0,c6=({width:e,index:t,selectable:n,selected:r,onToggle:i,edge:a})=>(0,V.jsxs)(`div`,{onClick:n?e=>{e.stopPropagation(),i?.()}:void 0,className:B(`sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3`,n&&`cursor-default`,a&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:e},children:[n&&(0,V.jsx)(Fh,{checked:!!r,label:`Select row ${t+1}`}),e>40&&(0,V.jsx)(`span`,{className:`min-w-6 text-right text-[11px] tabular-nums text-faint-foreground`,children:Bd(t+1)})]}),vhe=(e,t,n)=>({gridTemplateColumns:n6(e.specs,e.gutter,e.trailing,e.minScale),height:e.height,top:e.offset,transform:t===0?void 0:`translateY(${t}px)`,transition:n}),yhe=e=>t=>{t.target.closest(`a`)||e()},l6=({cells:e,selected:t,onToggle:n,onOpen:r,menu:i,handle:a,rowRef:o,dragY:s,transition:c,dragging:l,...u})=>(0,V.jsxs)(`div`,{ref:o,role:`row`,onClick:r&&yhe(r),className:B(`absolute inset-x-0 top-0 grid items-center border-b`,t?`bg-primary-soft`:`bg-background hover:bg-surface`,r&&`cursor-pointer`,l&&`z-30 bg-surface shadow-pop`),style:s===void 0?a6(u):vhe(u,s,c),children:[a?(0,V.jsx)(`div`,{className:B(`sticky left-0 z-10 flex h-full items-center bg-inherit pl-1.5`,u.scrolled&&!u.lastPinned&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:u.gutter},children:a}):(0,V.jsx)(c6,{width:u.gutter,index:u.index,selectable:u.selectable,selected:t,onToggle:n,edge:u.scrolled&&!u.lastPinned}),e.map(({spec:e,content:t,props:n,chosen:r,editing:i,editable:a})=>(0,V.jsx)(`div`,{role:n?`gridcell`:`cell`,...n,className:B(o6(e,u),n&&`scroll-mb-[calc(var(--pb-sticky-bottom,0px)+3rem)] scroll-mt-[calc(var(--pb-sticky-top,0px)+2rem)] outline-none`,a&&!i&&`cursor-default`,r&&`shadow-[inset_0_0_0_2px_var(--primary)]`,i&&`z-30 overflow-visible bg-background px-1`),style:s6(e,u.pins),children:t},e.id)),i&&(0,V.jsx)(`div`,{className:`sticky right-0 z-10 flex h-full items-center justify-center bg-inherit`,children:i})]}),u6=[`w-3/4`,`w-1/2`,`w-2/3`,`w-5/6`,`w-2/5`],bhe=e=>(0,V.jsxs)(`div`,{role:`row`,"aria-busy":!0,className:`absolute inset-x-0 top-0 grid items-center border-b bg-background`,style:a6(e),children:[(0,V.jsx)(c6,{width:e.gutter,index:e.index,selectable:!1,edge:e.scrolled&&!e.lastPinned}),e.specs.map((t,n)=>(0,V.jsx)(`div`,{className:o6(t,e),style:s6(t,e.pins),children:(0,V.jsx)(cu,{className:B(`h-2.5`,u6[(e.index+n)%u6.length],r6(t.kind)&&`ml-auto`)})},t.id))]}),xhe=(e,t)=>{let n=new Map;return{get:t=>n.get(Math.floor(t/e))?.[t%e],hasPage:e=>n.has(e),setPage:(e,r)=>{if(n.delete(e),n.set(e,r),n.size<=t)return;let i=n.keys().next();i.done||n.delete(i.value)},keepOnly:e=>{for(let t of[...n.keys()])e.includes(t)||n.delete(t)},get size(){return n.size}}},d6=(e,t,n)=>{let r=Math.floor(e/n),i=Math.floor(t/n);return Array.from({length:i-r+1},(e,t)=>r+t)},f6=(e,t)=>Math.max(0,Math.min(40,e-t*40)),p6=({total:e,rowAt:t,loadRows:n,revision:r,latencyMs:i},a,s)=>{let c=(0,o.useMemo)(()=>xhe(40,60),[t,n]),[l,u]=(0,o.useState)(0),d=Math.floor(a/40),f=Math.floor(s/40),p=!n&&i===0;(0,o.useEffect)(()=>{if(p)return;let r=d6(d*40,f*40,40).filter(e=>!c.hasPage(e)),a=t=>f6(e,t),o=(e,t)=>{c.setPage(e,t),u(e=>e+1)};if(n){let e=!1;for(let t of r)n(t*40,a(t)).then(n=>{e||o(t,n)});return()=>{e=!0}}let s=r.map(e=>setTimeout(()=>o(e,Array.from({length:a(e)},(n,r)=>t(e*40+r))),i));return()=>s.forEach(clearTimeout)},[c,d,f,i,e,t,n,p]);let m=(0,o.useRef)(r);return(0,o.useEffect)(()=>{if(!n||r===m.current)return;m.current=r;let t=d6(d*40,f*40,40);c.keepOnly(t);for(let r of t.filter(e=>c.hasPage(e)))n(r*40,f6(e,r)).then(e=>{c.setPage(r,e),u(e=>e+1)})},[c,r,n,d,f,e]),(0,o.useCallback)(e=>p?t(e):c.get(e),[c,p,t,l])},She=1e7,m6=(e,t,n)=>{let r=e*t,i=Math.min(r,She);return{rowHeight:t,trueHeight:r,contentHeight:i,scaled:r>i,maxTop:Math.max(0,r-n),maxScroll:Math.max(0,i-n)}},Che=(e,t)=>!e.scaled||t<=0?t:t>=e.maxScroll?e.maxTop+t-e.maxScroll:t/e.maxScroll*e.maxTop,h6=(e,t)=>!e.scaled||t<=0?t:t>=e.maxTop?e.maxScroll+t-e.maxTop:t/e.maxTop*e.maxScroll,whe=(e,t,n,r)=>{let i=t*e.rowHeight;return e.scaled?i-n+r:i},g6=(e,t,n,r,i)=>{let a=Math.min(e,Math.max(0,Math.floor(t/n)-i)),o=Math.min(e-1,Math.floor((t+r)/n)+i);return{first:a,last:Math.max(a-1,o)}},The=e=>{let t=document.scrollingElement??document.documentElement;for(let n=e.parentElement;n&&n!==t&&n!==document.body;n=n.parentElement)if(/auto|scroll/.test(getComputedStyle(n).overflowY))return n;return t},_6=e=>e===(document.scrollingElement??document.documentElement),Ehe=e=>_6(e)?window:e,v6=e=>Number.parseFloat(e)||0,Dhe=e=>{let t=getComputedStyle(e),n=_6(e)?{top:0,height:e.clientHeight}:{top:e.getBoundingClientRect().top+e.clientTop,height:e.clientHeight},r=v6(t.scrollPaddingTop);return{top:n.top+r,height:Math.max(0,n.height-r-v6(t.scrollPaddingBottom))}},y6=6,b6=(e,t,n)=>{let r=m6(t,n,e.height),i=Che(r,e.position);return{geometry:r,top:i,topIndex:Math.floor(Math.max(0,i)/n),...g6(t,i,n,e.height,y6)}},x6=({total:e,rowHeight:t,initialIndex:n,inset:r=0,settle:i,ready:a=!0})=>{let s=(0,o.useRef)(null),c=(0,o.useRef)(null),[l,u]=(0,o.useState)({position:0,height:0}),d=(0,o.useRef)({total:e,rowHeight:t,initialIndex:n,inset:r,ready:a});d.current={total:e,rowHeight:t,initialIndex:n,inset:r,ready:a};let f=(0,o.useCallback)(()=>{let e=s.current;if(!e||!c.current)return;let t=Dhe(c.current),n=d.current.inset;return{position:t.top+n-e.getBoundingClientRect().top,height:Math.max(0,t.height-n)}},[]),p=(0,o.useRef)(l);p.current=l;let m=(0,o.useCallback)(()=>{let e=f();if(!e)return;let t=p.current,{total:n,rowHeight:r}=d.current,i=b6(t,n,r),a=b6(e,n,r),o=!a.geometry.scaled&&i.first===a.first&&i.last===a.last&&i.topIndex===a.topIndex;(t.height!==e.height||t.position!==e.position&&!o)&&(p.current=e,u(e))},[f]),h=(0,o.useRef)({pending:!0,laidOut:!1}),g=(0,o.useCallback)(()=>{if(!h.current.pending||!h.current.laidOut||!d.current.ready)return;let e=f(),t=c.current;if(!e||!t)return;h.current.pending=!1;let{total:n,rowHeight:r,initialIndex:i}=d.current;i>0?t.scrollTop+=h6(m6(n,r,e.height),i*r)-e.position:e.position>0&&(t.scrollTop=0)},[f]);(0,o.useLayoutEffect)(()=>{let e=s.current;if(!e)return;let t=The(e);c.current=t;let n=Ehe(t);n.addEventListener(`scroll`,m,{passive:!0}),window.addEventListener(`resize`,m,{passive:!0});let r=new ResizeObserver(()=>{h.current.laidOut=!0,g(),m()});return r.observe(t),r.observe(e),m(),()=>{n.removeEventListener(`scroll`,m),window.removeEventListener(`resize`,m),r.disconnect(),c.current=null}},[m,g]),(0,o.useLayoutEffect)(()=>{g(),m()});let _=(0,o.useCallback)(e=>{let t=f();if(!t||!c.current)return;let n=m6(d.current.total,d.current.rowHeight,t.height);c.current.scrollTop+=h6(n,e)-t.position,m()},[f,m]),v=b6(l,e,t),y=i?i(v.top):v.top,{first:b,last:x}=i?g6(e,y,t,l.height,y6):v,S=Array.from({length:x-b+1},(e,t)=>({index:b+t,offset:whe(v.geometry,b+t,y,l.position)}));return{ref:s,height:l.height,top:y,geometry:v.geometry,rows:S,first:b,last:x,scrollTo:_}},Ohe=e=>e===`ArrowUp`||e===`ArrowDown`||e===`ArrowLeft`||e===`ArrowRight`,khe=(e,t,n,r)=>{let i=n.indexOf(e.column);if(t===`ArrowUp`)return e.index>0?{...e,index:e.index-1}:void 0;if(t===`ArrowDown`)return e.index<r-1?{...e,index:e.index+1}:void 0;let a=n[t===`ArrowLeft`?i-1:i+1];return i>=0&&a!==void 0?{...e,column:a}:void 0},Ahe=(e,t,n,r)=>{let i=t.indexOf(e);return(r===1?t.slice(i+1):t.slice(0,Math.max(0,i)).reverse()).find(n)},S6=e=>`${e.index}:${e.column}`,jhe=({editor:e,columns:t,total:n,rowAt:r,onOpenRow:i,container:a})=>{let[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(!1),d=(0,o.useRef)(!1),f=(0,o.useRef)(!1);if((0,o.useEffect)(()=>{if(!s||l||!d.current)return;d.current=!1;let e=a.current?.querySelector(`[data-cell="${S6(s)}"]`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`nearest`,inline:`nearest`}))},[s,l,a]),!e)return;let p=t=>{let n=r(t.index);return n!==void 0&&e.editable(n,t.column)},m=(e,t=!1)=>{d.current=!0,c(e),u(t&&p(e))},h=n=>{if(!s)return;let i=r(s.index),o=n&&i?Ahe(s.column,t,t=>e.editable(i,t),n):void 0,c=!!a.current?.contains(document.activeElement);m(o?{...s,column:o}:s,o!==void 0),d.current=c};return{cell:(n,r,i,a)=>{let o={index:n,column:i},u=s?.index===n&&s.column===i,d=e.editable(r,i),p=u||!s&&n===0&&i===t[0];return{content:u&&l?e.render(r,i,h):a,chosen:u,editing:u&&l,editable:d,props:{"data-cell":S6(o),tabIndex:p?0:-1,"aria-selected":u,onMouseDown:()=>{f.current=u},onFocus:e=>{e.target===e.currentTarget&&!u&&c(o)},onClick:e=>{d&&(e.stopPropagation(),f.current&&!l&&m(o,!0))},onDoubleClick:e=>{d&&(e.stopPropagation(),u&&l||m(o,!0))}}}},onKeyDown:e=>{if(l||!s||!(e.target instanceof HTMLElement)||e.target.dataset.cell!==S6(s))return;let a=e.key===`Tab`?e.shiftKey?`ArrowLeft`:`ArrowRight`:e.key;if(Ohe(a)){let i=khe(s,a,t,n);if(!i&&e.key===`Tab`)return;e.preventDefault(),i&&r(i.index)&&m(i);return}if(e.key===`Enter`||e.key===`F2`){e.preventDefault();let t=r(s.index);p(s)?m(s,!0):e.key===`Enter`&&t&&i?.(t);return}e.key===`Escape`&&c(void 0)}}},Mhe=`To move a row, press Space on its handle, move it with the up and down arrow keys, and press Space again to drop it there. Escape puts it back.`,Nhe=({ids:e,rowAt:t,reorder:n,children:r})=>{let i=Zg(Xg(F_,{activationConstraint:{distance:4}}),Xg(L_,{activationConstraint:{delay:250,tolerance:5}}),Xg(D_,{coordinateGetter:yy})),a=t=>e.indexOf(String(t)),o=e=>{let r=t(a(e));return r?n.label(r):`row`};return(0,V.jsx)(kv,{sensors:i,collisionDetection:i_,onDragEnd:({active:e,over:t})=>{t&&e.id!==t.id&&n.onMove(a(e.id),a(t.id))},accessibility:{announcements:{onDragStart:({active:t})=>`Picked up ${o(t.id)}, row ${a(t.id)+1} of ${e.length}.`,onDragOver:({active:t,over:n})=>n?`${o(t.id)} is over row ${a(n.id)+1} of ${e.length}.`:void 0,onDragEnd:({active:t,over:n})=>n?`${o(t.id)} was dropped at row ${a(n.id)+1} of ${e.length}.`:`${o(t.id)} was put back.`,onDragCancel:({active:e})=>`Moving ${o(e.id)} was cancelled. It is back at row ${a(e.id)+1}.`},screenReaderInstructions:{draggable:Mhe}},children:(0,V.jsx)(sy,{items:e,strategy:ry,children:r})})},Phe=({row:e,label:t,...n})=>{let{attributes:r,listeners:i,setNodeRef:a,setActivatorNodeRef:o,transform:s,transition:c,isDragging:l}=hy({id:e.id}),u=(0,V.jsx)(`button`,{ref:o,type:`button`,"aria-label":`Move ${t}`,...r,...i,onClick:e=>e.stopPropagation(),style:{touchAction:`none`},className:`flex size-7 cursor-grab items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:text-foreground active:cursor-grabbing pointer-coarse:size-9`,children:(0,V.jsx)(ct,{className:`size-4`})});return(0,V.jsx)(l6,{...n,rowRef:a,handle:u,dragY:s?.y??0,transition:c,dragging:l})},C6=32,w6=({columns:e,source:t,naturalSort:n,initialScrollIndex:r=0,onScrollIndex:i,latencyMs:a=150,sort:s,onSortChange:c,onOpenRow:l,rowLink:u,rowActions:d,cellEditor:f,rowPatches:p,bulkActions:m,pinKey:h,defaultPinned:g,rowNumbers:_=!0,compact:v=!1,selectable:y=!0,reorder:b,fit:x=!1,scroll:S=`own`,className:C})=>{let w=y&&!b,T=v?28:36,E=!Kl(),D=(g??(E?[]:dhe(e))).join(` `),[O,k]=uhe(h,(0,o.useMemo)(()=>D?D.split(` `):[],[D])),A=(0,o.useMemo)(()=>[...O.flatMap(t=>e.find(e=>e.id===t)??[]),...e.filter(e=>!O.includes(e.id))],[e,O]),j=A.slice(0,A.filter(e=>O.includes(e.id)).length).map(e=>e.id),{total:M}=t,[N,ee]=(0,o.useState)(n?[{id:n.columnId,desc:n.direction===`desc`}]:[]),P=s?[{id:s.columnId,desc:s.direction===`desc`}]:N,te=e=>{let t=typeof e==`function`?e(P):e,n=t[0];c&&n&&c({columnId:n.id,direction:n.desc?`desc`:`asc`}),s||ee(t)},[F,ne]=(0,o.useState)({}),re=(0,o.useMemo)(()=>Qme(A),[A]),ie=P[0],I=!!(!s&&n&&ie&&ie.id===n.columnId&&(ie.desc?`desc`:`asc`)!==n.direction),ae=t.rowAt,oe=(0,o.useCallback)(e=>ae(I?M-1-e:e),[ae,I,M]),[se]=(0,o.useState)(r),{ref:L,top:ce,geometry:le,rows:ue,first:de,last:fe}=x6({total:M,rowHeight:T,initialIndex:se,inset:C6}),pe=E||!_?40:nhe(M),me=Math.floor(Math.max(0,ce)/T);(0,o.useEffect)(()=>i?.(me),[me,i]);let he=p6({total:M,rowAt:ae?oe:void 0,loadRows:t.loadRows,revision:t.revision,latencyMs:a},de,fe),ge=(0,o.useCallback)(e=>{let t=he(e),n=t&&p?.get(t.id);return n?{...t,...n}:t},[he,p]),_e=ue.map(({index:e,offset:t})=>({index:e,offset:t,row:ge(e)})),ve=(0,o.useMemo)(()=>_e.flatMap(({row:e})=>e?[e]:[]),[ge,de,fe]),ye=phe(A,ve),be=Yme({features:Zme,columns:re,data:ve,state:{sorting:P,rowSelection:F},onSortingChange:te,onRowSelectionChange:ne,manualSorting:!0,enableMultiSort:!1,enableSortingRemoval:!1,getRowId:e=>e.id}),xe=new Map(be.getRowModel().rows.map(e=>[e.id,e])),Se=Object.keys(F).length,Ce=(0,o.useRef)(new Map);for(let e of be.getRowModel().rows)e.getIsSelected()&&Ce.current.set(e.id,e.original);let we=d&&d.length>0?40:0,Te=E?1:e6,Ee=ahe(),De=(0,o.useRef)(null),Oe=()=>{Ee.onScroll(),De.current&&Ee.ref.current&&(De.current.scrollLeft=Ee.ref.current.scrollLeft)},[ke,Ae]=(0,o.useState)({});(0,o.useLayoutEffect)(()=>{let e=De.current?.querySelector(`[role=row]`);if(!e)return;let t=pe,n={};for(let r of j)n[r]=t,t+=e.querySelector(`[data-col-id="${r}"]`)?.offsetWidth??0;JSON.stringify(ke)!==JSON.stringify(n)&&Ae(n)});let je=j.at(-1),Me=e=>k(O.includes(e)?O.filter(t=>t!==e):[...O,e]),Ne=be.getHeaderGroups().flatMap(e=>e.headers.map(e=>({spec:A.find(t=>t.id===e.column.id),sorted:e.column.getIsSorted(),onSort:t=>e.column.getToggleSortingHandler()?.(t)}))),Pe=(0,o.useRef)(null),Fe=jhe({editor:f,columns:(0,o.useMemo)(()=>A.map(e=>e.id),[A]),total:M,rowAt:ge,onOpenRow:l,container:Pe}),Ie=(A.find(e=>e.title)??A[0])?.id,Le=ihe(ye,pe,we,Te),Re=S===`own`,ze=(0,V.jsx)(`div`,{ref:De,className:B(`sticky z-20 shrink-0 overflow-hidden`,Re?`top-0`:`top-[var(--pb-sticky-top,0px)]`),children:(0,V.jsx)(`div`,{style:{minWidth:Le},children:(0,V.jsx)(_he,{cells:Ne,specs:ye,gutter:pe,trailing:we,minScale:Te,pins:ke,lastPinned:je,scrolled:Ee.scrolled,onTogglePin:Me,selectable:w,selectedCount:Se,onClearSelection:()=>ne({})})})}),Be=_e.map(({index:e,offset:t,row:n})=>{let r={specs:ye,gutter:pe,index:e,offset:t,height:T,selectable:w,trailing:we,minScale:Te,scrolled:Ee.scrolled,pins:ke,lastPinned:je},i=n?xe.get(n.id):void 0;if(!i||!n)return(0,V.jsx)(bhe,{...r},`skeleton-${e}`);let a=we?ehe(d,n):[],o={...r,selected:i.getIsSelected(),onToggle:()=>i.toggleSelected(),onOpen:l?()=>l(n):void 0,menu:a.length>0?(0,V.jsx)(the,{row:n,actions:a}):void 0,cells:i.getAllCells().map(t=>{let r=(0,V.jsx)(be.FlexRender,{cell:t}),i=!!f?.editable(n,t.column.id),a=u&&t.column.id===Ie&&!i?(0,V.jsx)(du,{to:u(n),className:`flex min-w-0 items-center hover:underline`,children:r}):r;return{spec:A.find(e=>e.id===t.column.id),...Fe?Fe.cell(e,n,t.column.id,a):{content:a}}})};return b?(0,V.jsx)(Phe,{...o,row:n,label:b.label(n)},n.id):(0,V.jsx)(l6,{...o},n.id)}),Ve=(0,V.jsx)(`div`,{ref:Ee.attach,onScroll:Oe,className:`overflow-x-auto overflow-y-hidden overscroll-x-contain [-webkit-overflow-scrolling:touch]`,children:(0,V.jsx)(`div`,{ref:L,className:`relative`,style:{minWidth:Le,height:le.contentHeight},children:b?(0,V.jsx)(Nhe,{ids:Array.from({length:M},(e,t)=>ge(t)?.id??`missing-${t}`),rowAt:ge,reorder:b,children:Be}):Be})});return(0,V.jsxs)(`div`,{ref:Pe,role:`grid`,"aria-rowcount":M,onKeyDown:Fe?.onKeyDown,className:B(`flex flex-col rounded-lg border bg-background`,Re?`min-h-0 overflow-hidden`:`overflow-clip`,C),style:x&&Re?{height:C6+M*T+2}:void 0,children:[(0,V.jsxs)(`div`,{className:B(`relative`,Re&&`flex min-h-0 flex-1 flex-col`),children:[Re?(0,V.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto overflow-x-hidden`,children:[ze,Ve]}):(0,V.jsxs)(V.Fragment,{children:[ze,Ve]}),Ee.more&&(0,V.jsx)(`div`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-y-0 right-0 z-20 w-8 bg-gradient-to-l from-backdrop/15 to-transparent`})]}),!x&&(0,V.jsx)($me,{total:M,className:Re?void 0:`sticky bottom-[var(--pb-sticky-bottom,0px)] z-20`,selectedCount:Se,bulkActions:m?.map(e=>({label:e.label(Se),destructive:e.destructive,onRun:()=>{e.onRun(Object.keys(F).flatMap(e=>Ce.current.get(e)??[])),ne({}),Ce.current.clear()}}))})]})},Fhe=500,T6=async(e,t,n)=>{let r=[],i={},a;do{let o=await e.search(t,{...n,pageSize:Fhe,...a&&{pageToken:a}});r.push(...o.items);for(let[e,t]of Object.entries(o.labels??{}))i[e]={...i[e],...t};a=o.nextPageToken||void 0}while(a);return{items:r,labels:i}},E6=co(),D6=(...e)=>{let t=e.filter(e=>!!e);return t.length===1?t[0]:t.map(e=>`(${e})`).join(` AND `)},O6=e=>e==null?void 0:String(e),Ihe=(e,t,n)=>{let r=new Map;for(let[t,n]of e)r.set(n,(r.get(n)??new Set).add(t));let i=new Map;for(let e of t){let t=e[n],a=O6(typeof t==`object`&&t&&`id`in t?t.id:t);for(let t of a===void 0?[]:r.get(a)??[])i.set(t,[...i.get(t)??[],e])}return i},Lhe=async(e,t,n,r)=>{let i=n.through;if(!i)return r.map(e=>[e,e]);let a=t[i.resource],o=i.key??a?.primaryKey[0];if(!a||o===void 0)throw Error(`The related column ${n.name} names a join resource the app does not have: ${i.resource}`);return(await T6(e,a.name,{filter:D6(qa(E6.in(i.field,r)),i.filter),fields:[i.field,o]})).items.flatMap(e=>{let t=O6(e[i.field]),n=O6(e[o]);return t===void 0||n===void 0?[]:[[t,n]]})},Rhe=async({client:e,resources:t,views:n,load:r,owners:i})=>{let{column:a,fields:o}=r,s=t[a.resource];if(!s)throw Error(`The related column ${a.name} shows a resource the app does not have: ${a.resource}`);if(i.length===0)return new Map;let c=await Lhe(e,t,a,i),l=[...new Set(c.map(([,e])=>e))];if(l.length===0)return new Map;let u=[...new Set([...s.primaryKey,a.field,a.status,...o])],d=u4(t,n,s,u),f=await T6(e,s.name,{filter:D6(qa(E6.in(a.field,l)),a.filter),...a.sort&&{orderBy:a.sort},fields:u,labels:d});return Ihe(c,d4(t,s,u,f.items,f.labels),a.field)},zhe=5e3,Bhe=({queryClient:e,client:t,resources:n,views:r,model:i,columns:a,filter:o,orderBy:s,related:c=[]})=>{let l=c.map(e=>e.column.name).join(`,`),u=e=>c.length===0?W.page(i.name,o,s,40,e):[...W.page(i.name,o,s,40,e),l],d=u4(n,r,i,a),f=rS(r[i.name]),p=async e=>e.nextPageToken===``?e.items.length:e.totalSizeEstimate>zhe?e.totalSizeEstimate:(await t.list(i.name,{filter:o,orderBy:s,pageSize:1,count:`exact`})).totalSize??e.totalSizeEstimate,m=async t=>{if(t===0)return``;let n=u(t-1),r=e.getQueryData(n);if(r)return r.nextPageToken;if(e.getQueryState(n)?.fetchStatus===`fetching`)return(await g(t-1)).nextPageToken},h=async e=>{let l=await m(e);if(e>0&&l===``)return{rows:[],total:0,nextPageToken:``};let u={filter:o,orderBy:s,pageSize:40,labels:d,photos:f},h=l===void 0?await t.seek(i.name,{...u,position:e*40}):await t.list(i.name,{...u,pageToken:l});if(h.items.length===0&&e>0)return{rows:[],total:0,nextPageToken:``};let g=h.items.map(e=>Rx(i,e)),_=d4(n,i,a,iS(i,h.items,h.photos),h.labels),v=await Promise.all(c.map(e=>Rhe({client:t,resources:n,views:r,load:e,owners:g})));return{rows:_.map((e,t)=>({...e,...Object.fromEntries(c.map((e,n)=>[e.column.name,v[n].get(g[t])??[]])),id:g[t]})),total:e===0?await p(h):h.totalSizeEstimate,nextPageToken:h.nextPageToken}},g=t=>e.fetchQuery({queryKey:u(t),staleTime:6e4,queryFn:()=>h(t)});return{page:g,loadRows:async e=>(await g(Math.floor(e/40))).rows}},k6=({resources:e,views:t,model:n,columns:r,filter:i,orderBy:a,related:s})=>{let c=G(),l=Gp(),u=r.join(`,`),d=JSON.stringify(s??[]),f=(0,o.useMemo)(()=>Bhe({queryClient:l,client:c,resources:e,views:t,model:n,columns:r,filter:i,orderBy:a,...s&&{related:s}}),[l,c,e,t,n,u,i,a,d]),p=mh({queryKey:[...W.first(n.name,i,a),u],queryFn:async()=>(await l.invalidateQueries({queryKey:W.pages(n.name,i,a),refetchType:`none`}),f.page(0))});return{source:(0,o.useMemo)(()=>p.data?{total:p.data.total,loadRows:f.loadRows,revision:p.dataUpdatedAt}:void 0,[p.data,p.dataUpdatedAt,f]),error:p.error,isLoading:p.isLoading,page:f.page,key:[...W.first(n.name,i,a),u]}},Vhe=`protobase:embedded-display:`,Hhe=e=>`${Vhe}${e}`,Uhe=(e,t)=>zu(()=>e.getItem(t)??void 0,void 0),Whe=(e,t,n)=>zu(()=>e.setItem(t,n),void 0),Ghe=(e,t,{picked:n,preferred:r})=>{let i=yS(e).map(e=>e.name);return n!==void 0&&i.includes(n)?n:dS(e,t,r!==void 0&&i.includes(r)?r:void 0)},A6=(e,t,n,{resource:r=e.name,...i})=>LS({kind:`list`,resource:r},i,{...FS(e,t,n),display:dS(t,n)}),j6=`inline-flex h-6 items-center rounded-full border border-primary-border bg-primary-soft px-2.5 text-xs font-medium text-primary-text`,M6=({chips:e,className:t})=>(0,V.jsx)(`ul`,{className:B(`flex flex-wrap gap-1.5`,t),"aria-label":`Filters`,children:e.map(e=>(0,V.jsx)(`li`,{className:j6,children:e.label},e.key))}),N6=({chips:e})=>(0,V.jsx)(`span`,{className:`flex flex-wrap gap-1.5`,children:e.map((e,t)=>(0,V.jsxs)(`span`,{className:j6,children:[t>0&&(0,V.jsx)(`span`,{className:`sr-only`,children:`, `}),e.label]},e.key))}),Khe=e=>e.map(e=>e.label).join(`, `),qhe=`inline-flex h-6 items-center gap-1 rounded-full border border-primary-border bg-primary-soft pl-2.5 pr-1.5 text-xs font-medium text-primary-text`,P6=({chips:e,lockedLabels:t=[],onRemove:n,onClear:r,scroll:i})=>e.length===0&&t.length===0?null:(0,V.jsxs)(`div`,{className:i?`flex flex-nowrap items-center gap-1.5 overflow-x-auto pb-1 [&>*]:shrink-0`:`flex flex-wrap items-center gap-1.5`,children:[t.map(e=>(0,V.jsxs)(`span`,{className:`inline-flex h-6 items-center gap-1.5 rounded-full border border-border-strong bg-muted px-2.5 text-xs font-medium text-foreground`,children:[(0,V.jsx)(Pt,{className:`size-3 text-muted-foreground`}),e]},e)),e.map(e=>(0,V.jsxs)(`span`,{className:qhe,children:[e.label,(0,V.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.label}`,onClick:()=>n(e.key),className:`rounded-full p-0.5 hover:bg-primary-border/60`,children:(0,V.jsx)($n,{className:`size-3`})})]},e.key)),e.length>0&&(0,V.jsx)(`button`,{type:`button`,onClick:r,className:`ml-1 text-xs font-medium text-muted-foreground hover:text-foreground`,children:`Clear all`})]}),Jhe=[`7d`,`30d`,`year`],F6={today:`Today`,yesterday:`Yesterday`,"7d":`Last 7 days`,"30d":`Last 30 days`,"90d":`Last 90 days`,month:`This month`,quarter:`This quarter`,year:`This year`},Yhe=({value:e,presets:t=Jhe,onChange:n})=>(0,V.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(t=>{let r=F6[t];return(0,V.jsx)(`button`,{type:`button`,disabled:!r,title:r?void 0:`The server offers the preset "${t}", which this UI does not know`,onClick:()=>n(e===t?void 0:t),className:B(`h-7 rounded-md border px-2.5 text-xs font-medium transition-colors`,!r&&`border-dashed text-danger-text`,e===t?`border-primary-border bg-primary-soft text-primary-text`:`border-border-strong bg-background text-muted-foreground hover:bg-muted`),children:r??`${t} (unsupported)`},t)})}),I6={facets:{},toggles:[]},L6=(e,t,n)=>{let r=e.facets[t]??[],i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,facets:{...e.facets,[t]:i}}},R6=(e,t)=>({...e,toggles:e.toggles.includes(t)?e.toggles.filter(e=>e!==t):[...e.toggles,t]}),z6=(e,t,n)=>{let{[t]:r,...i}=e.ranges??{};return{...e,ranges:n?{...i,[t]:n}:i}},B6=(e,t)=>e.options.find(e=>e.value===t)?.label??e.labels?.[t]??t,V6=(e,t)=>{let n=e.facets.flatMap(e=>(t.facets[e.id]??[]).map(t=>({key:`facet:${e.id}:${t}`,label:`${e.label}: ${B6(e,t)}`}))),r=(e.ranges??[]).flatMap(e=>{let n=t.ranges?.[e.id];return n?[{key:`range:${e.id}`,label:`${e.label}: ${e.format(n[0])} – ${e.format(n[1])}`}]:[]}),i=t.date?[{key:`date`,label:F6[t.date]??t.date}]:[],a=t.toggles.map(t=>({key:`toggle:${t}`,label:e.toggles?.find(e=>e.id===t)?.label??t}));return[...n,...r,...i,...a]},H6=(e,t)=>{if(t===`date`)return{...e,date:void 0};let[n,r,i]=t.split(`:`);if(n===`range`)return z6(e,r,void 0);if(n===`toggle`)return R6(e,r);if(n===`facet`)return L6(e,r,i);throw Error(`Unknown filter chip key: ${t}`)},U6=(e,t)=>e.toLowerCase().includes(t.trim().toLowerCase()),Xhe=(e,t)=>e.onSearch?e.options:e.options.filter(e=>U6(e.label,t)),Zhe=(e,t,n)=>t===0?-1:n===`ArrowDown`?e<0?0:(e+1)%t:e<0?t-1:(e-1+t)%t,Qhe=({config:e,selected:t,onToggle:n,inline:r=!1})=>{let i=(0,o.useId)(),a=(0,o.useRef)(null),[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)(-1),p=r||l,m=Xhe(e,s),h=(0,o.useRef)(e.onSearch);h.current=e.onSearch,(0,o.useEffect)(()=>()=>h.current?.(``),[]);let g=t=>{c(t),f(-1),e.onSearch?.(t)};return(0,V.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,V.jsxs)(`div`,{className:`flex min-h-8 cursor-text flex-wrap items-center gap-1 rounded-md border border-border-strong bg-background px-2 py-1 shadow-sm focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20`,onClick:()=>a.current?.focus(),children:[(0,V.jsx)(pn,{className:`size-3.5 shrink-0 text-muted-foreground`}),t.map(t=>(0,V.jsxs)(`span`,{className:`inline-flex h-5 max-w-full items-center gap-0.5 rounded bg-primary-soft pl-1.5 pr-0.5 text-xs font-medium text-primary-text`,children:[(0,V.jsx)(`span`,{className:`truncate`,children:B6(e,t)}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Remove ${B6(e,t)}`,className:`rounded p-0.5 hover:bg-primary-border/60`,onMouseDown:e=>e.preventDefault(),onClick:()=>n(t),children:(0,V.jsx)($n,{className:`size-3`})})]},t)),(0,V.jsx)(`input`,{ref:a,autoFocus:r,role:`combobox`,"aria-label":e.label,"aria-expanded":p,"aria-controls":`${i}-options`,"aria-autocomplete":`list`,"aria-activedescendant":m[d]?`${i}-${d}`:void 0,placeholder:t.length>0?``:`Search ${e.label.toLowerCase()}`,className:`h-6 min-w-16 flex-1 bg-transparent text-foreground outline-none placeholder:text-faint-foreground`,value:s,onChange:e=>g(e.target.value),onKeyDown:e=>{if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),f(Zhe(d,m.length,e.key));return}if(e.key===`Enter`&&m[d]){e.preventDefault(),n(m[d].value);return}if(e.key===`Backspace`&&s===``&&t.length>0){n(t[t.length-1]);return}e.key===`Escape`&&s!==``&&(e.stopPropagation(),g(``))},onFocus:()=>u(!0),onBlur:()=>{u(!1),f(-1),!r&&s!==``&&g(``)}})]}),p&&(0,V.jsxs)(`ul`,{id:`${i}-options`,role:`listbox`,"aria-label":e.label,"aria-multiselectable":!0,className:B(`flex max-h-60 flex-col gap-px overflow-y-auto`,!r&&`rounded-md border bg-background p-1 shadow-sm`),children:[m.map((e,r)=>{let a=t.includes(e.value);return(0,V.jsxs)(`li`,{id:`${i}-${r}`,role:`option`,"aria-selected":a,tabIndex:-1,className:B(`flex cursor-pointer items-center gap-2 rounded px-1.5 py-1 hover:bg-muted`,r===d&&`bg-muted`),onMouseDown:e=>e.preventDefault(),onClick:()=>n(e.value),children:[(0,V.jsx)(`span`,{className:B(`inline-flex size-4 shrink-0 items-center justify-center rounded border`,a?`border-primary bg-primary text-primary-foreground`:`border-border-strong bg-background`),children:a&&(0,V.jsx)(ge,{className:`size-3`,strokeWidth:3})}),(0,V.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.count!==void 0&&(0,V.jsx)(`span`,{className:`text-xs tabular-nums text-faint-foreground`,children:Bd(e.count)})]},e.value)}),m.length===0&&(0,V.jsx)(`li`,{className:`px-1.5 py-1 text-xs text-faint-foreground`,children:`No matches`})]})]})},$he=({config:e,selected:t,onToggle:n})=>{let[r,i]=(0,o.useState)(``),a=e.options.filter(e=>U6(e.label,r));return(0,V.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[e.searchable&&(0,V.jsx)(sd,{wrapperClassName:`mb-1 h-7`,leading:(0,V.jsx)(pn,{className:`size-3.5`}),placeholder:`Search ${e.label.toLowerCase()}`,value:r,onChange:e=>i(e.target.value)}),a.map(e=>(0,V.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded px-1 py-1 hover:bg-muted`,children:[(0,V.jsx)(Fh,{checked:t.includes(e.value),onChange:()=>n(e.value),label:e.label}),(0,V.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.count!==void 0&&(0,V.jsx)(`span`,{className:`text-xs tabular-nums text-faint-foreground`,children:Bd(e.count)})]},e.value)),a.length===0&&(0,V.jsx)(`span`,{className:`px-1 py-1 text-xs text-faint-foreground`,children:`No matches`})]})},W6=({label:e,activeCount:t,width:n=240,defaultOpen:r=!1,children:i})=>{let[a,s]=(0,o.useState)(r),[c,l]=(0,o.useState)(!1),u=(0,o.useRef)(null);return(0,o.useLayoutEffect)(()=>{a&&u.current&&l(u.current.getBoundingClientRect().left+n>document.documentElement.clientWidth)},[a,n]),(0,o.useEffect)(()=>{if(!a)return;let e=e=>{e.target instanceof Node&&!u.current?.contains(e.target)&&s(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[a]),(0,V.jsxs)(`div`,{ref:u,className:`relative`,children:[(0,V.jsxs)(`button`,{type:`button`,"aria-expanded":a,onClick:()=>s(!a),className:B(`inline-flex h-8 items-center gap-1.5 rounded-md border bg-background px-2.5 font-medium shadow-sm transition-colors hover:bg-muted`,t>0?`border-primary-border text-primary-text`:`border-border-strong text-foreground`),children:[e,t>0&&(0,V.jsx)(`span`,{className:`rounded-full bg-primary px-1.5 text-[11px] leading-4 text-primary-foreground`,children:t}),(0,V.jsx)(ve,{className:`size-3.5 text-muted-foreground`})]}),a&&(0,V.jsx)(`div`,{className:B(`absolute top-full z-30 mt-1.5 rounded-lg border bg-background p-3 shadow-pop`,c?`right-0`:`left-0`),style:{width:n},children:i})]})},G6=({title:e,children:t})=>(0,V.jsxs)(`section`,{className:`flex flex-col gap-2 border-b py-3 last:border-b-0`,children:[(0,V.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e}),t]}),K6=(e,t)=>{let[n,r]=(0,o.useState)(e);return(0,o.useEffect)(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n},ege=(e,t,n,r,i)=>{let a=n+(r-n)*e/t;return n+(r-n)*(e+1)/t>i[0]&&a<i[1]},q6=(e,t,n)=>n===t?0:(e-t)/(n-t),tge=(e,t,n)=>t===0?[Math.min(n,e[1]),e[1]]:[e[0],Math.max(n,e[0])],nge=1e3,rge=({config:e,value:t,onChange:n})=>{let{min:r,max:i,step:a,histogram:s,format:c}=e,[l,u]=(0,o.useState)(),d=l??t??[r,i],f=Math.max(...s),p=()=>{l&&(u(void 0),n(l[0]===r&&l[1]===i?void 0:l))},m=K6(l,nge);return(0,o.useEffect)(()=>{m&&p()},[m]),(0,V.jsxs)(`div`,{className:`w-full`,children:[(0,V.jsxs)(`div`,{className:`px-[7px]`,children:[s.length>0&&(0,V.jsx)(`div`,{className:`mb-1 flex h-12 items-end gap-0.5`,children:s.map((e,t)=>(0,V.jsx)(`span`,{className:B(`flex-1 rounded-t-sm`,ege(t,s.length,r,i,d)?`bg-primary/70`:`bg-border`),style:{height:`${Math.max(6,e/f*100)}%`}},t))}),(0,V.jsxs)(`div`,{className:`relative h-4`,children:[(0,V.jsx)(`span`,{className:`absolute inset-x-0 top-1/2 h-1 -translate-y-1/2 rounded-full bg-border`}),(0,V.jsx)(`span`,{className:`absolute top-1/2 h-1 -translate-y-1/2 rounded-full bg-primary`,style:{left:`${q6(d[0],r,i)*100}%`,right:`${100-q6(d[1],r,i)*100}%`}})]})]}),(0,V.jsx)(`div`,{className:`relative -mt-4 h-4`,children:[0,1].map(t=>(0,V.jsx)(`input`,{type:`range`,className:`pb-range`,"aria-label":`${e.label} ${t===0?`minimum`:`maximum`}`,min:r,max:i,step:a,value:d[t],onChange:e=>u(tge(d,t,Number(e.target.value))),onPointerUp:p,onTouchEnd:p,onBlur:p},t))}),(0,V.jsxs)(`div`,{className:`mt-2 flex justify-between text-xs tabular-nums text-muted-foreground`,children:[(0,V.jsx)(`span`,{children:c(d[0])}),(0,V.jsx)(`span`,{children:c(d[1])})]})]})},J6=({label:e,checked:t,onChange:n})=>(0,V.jsxs)(`label`,{className:`flex cursor-pointer items-center justify-between gap-3 py-1`,children:[(0,V.jsx)(`span`,{children:e}),(0,V.jsx)(ox,{checked:t,onChange:n,label:e})]}),Y6=(e,t)=>e.some(e=>e.length>0)||!!t,X6=({groups:e,trailing:t})=>{if(!Y6(e,t))return null;let n=e.filter(e=>e.length>0);return(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n.map((e,t)=>(0,V.jsxs)(o.Fragment,{children:[t>0&&(0,V.jsx)(`span`,{className:`mx-1 h-5 w-px bg-border`}),e]},t)),t&&(0,V.jsx)(`div`,{className:`flex min-w-32 flex-1 justify-end`,children:t})]})},ige=(e,t,n)=>{let[r,i]=(0,o.useState)(t??I6);return[e??r,e=>{i(e),n?.(e)}]},Z6=({config:e,layout:t,value:n,defaultValue:r,onChange:i,lockedLabels:a,defaultOpenMenu:s,fullWidth:c,leading:l,trailing:u})=>{let[d,f]=ige(n,r,i),p=V6(e,d),m=(0,V.jsx)(P6,{chips:p,lockedLabels:a,onRemove:e=>f(H6(d,e)),onClear:()=>f(I6)}),h=(e,t=!1)=>{let n=d.facets[e.id]??[],r=t=>f(L6(d,e.id,t));return e.combobox?(0,V.jsx)(Qhe,{config:e,selected:n,onToggle:r,inline:t}):(0,V.jsx)($he,{config:e,selected:n,onToggle:r})},g=e.ranges??[],_=e=>(0,V.jsx)(rge,{config:e,value:d.ranges?.[e.id],onChange:t=>f(z6(d,e.id,t))}),v=e.datePresets&&(0,V.jsx)(Yhe,{value:d.date,presets:Array.isArray(e.datePresets)?e.datePresets:void 0,onChange:e=>f({...d,date:e})}),y=(e.toggles??[]).map(e=>(0,V.jsx)(J6,{label:e.label,checked:d.toggles.includes(e.id),onChange:()=>f(R6(d,e.id))},e.id));if(t===`panel`)return(0,V.jsxs)(`aside`,{className:c?`flex w-full flex-col gap-1`:`flex w-64 shrink-0 flex-col gap-1 overflow-y-auto rounded-lg border bg-background px-4 py-3`,children:[(0,V.jsx)(`div`,{className:`flex items-center justify-between pb-1`,children:(0,V.jsx)(`h2`,{className:`font-semibold`,children:`Filters`})}),(p.length>0||(a?.length??0)>0)&&(0,V.jsx)(`div`,{className:`border-b pb-3`,children:m}),l,e.facets.map(e=>(0,V.jsx)(G6,{title:e.label,children:h(e)},e.id)),g.map(e=>(0,V.jsx)(G6,{title:e.label,children:_(e)},e.id)),v&&(0,V.jsx)(G6,{title:`Date`,children:v}),y.length>0&&(0,V.jsx)(G6,{title:`Show only`,children:y})]});let b=[...e.facets.map(e=>(0,V.jsx)(W6,{label:e.label,activeCount:(d.facets[e.id]??[]).length,width:e.combobox?280:void 0,defaultOpen:s===e.id,children:h(e,!0)},e.id)),...g.map(e=>(0,V.jsx)(W6,{label:e.label,activeCount:+!!d.ranges?.[e.id],width:280,defaultOpen:s===e.id,children:_(e)},`range:${e.id}`)),...v?[(0,V.jsx)(o.Fragment,{children:v},`date`)]:[]],x=(e.toggles??[]).map(e=>(0,V.jsx)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:(0,V.jsx)(J6,{label:e.label,checked:d.toggles.includes(e.id),onChange:()=>f(R6(d,e.id))})},e.id)),S=[l?[(0,V.jsx)(o.Fragment,{children:l},`leading`)]:[],b,x];return!Y6(S,u)&&p.length===0&&!a?.length?null:(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsx)(X6,{groups:S,trailing:u}),m]})},Q6=co(),$6={start:0,end:0},e8={"7d":{amount:7,unit:`d`},"30d":{amount:30,unit:`d`},"90d":{amount:90,unit:`d`}},age=e=>new Date(e).toISOString().replace(`.000Z`,`Z`),t8=(e,t,n)=>{let r=Xd(t.getTime(),n),[i,a]=[Number(r.slice(0,4)),Number(r.slice(5,7))-1],o=e=>new Date(e).toISOString().slice(0,10);return e===`year`?o(Date.UTC(i,0,1)):e===`quarter`?o(Date.UTC(i,Math.floor(a/3)*3,1)):e===`month`?o(Date.UTC(i,a,1)):e===`yesterday`?o(Date.parse(`${r}T00:00:00Z`)-864e5):r},n8=[`year`,`quarter`,`month`,`yesterday`,`today`],r8=(e,t,n)=>t===`date`?e:age(Qd(e,n)),i8=(e,t,n)=>t===`date`?{kind:`string`,value:r8(e,t,n),span:$6}:{kind:`timestamp`,value:r8(e,t,n),span:$6},oge=(e,t,n,r,i)=>{if(t in e8)return[Q6.gte(e,Q6.ago(t))];let a=Q6.gte(e,i8(t8(t,n,i),r,i));return t===`yesterday`?[a,Q6.lt(e,i8(t8(`today`,n,i),r,i))]:[a]},sge=(e,t,n=new Date,r=Wd())=>{let i=e.facets.flatMap(e=>{let n=t.facets[e.id]??[];if(n.length===0)return[];if(e.flags){let t=e.options.filter(e=>n.includes(e.value)).map(e=>Q6.eq(e.value,!0));return t.length===0?[]:[t.length===1?t[0]:Q6.or(...t)]}return[n.length===1?Q6.eq(e.id,n[0]):Q6.in(e.id,n)]}),a=(e.ranges??[]).flatMap(e=>{let n=t.ranges?.[e.id];return n?[Q6.gte(e.id,n[0]),Q6.lte(e.id,n[1])]:[]}),o=e.dateField&&t.date?oge(e.dateField,t.date,n,e.dateKind,r):[],s=(e.toggles??[]).filter(e=>t.toggles.includes(e.id)).map(e=>Q6.eq(e.id,!0));return[...i,...a,...o,...s]},cge=e=>e.length===0?``:qa(Q6.and(...e)),a8=(e,t,n=[],r=new Date,i=Wd())=>cge([...sge(e,t,r,i),...n]),o8=e=>e.kind===`and`?e.args.flatMap(o8):[e],s8=e=>e.field.path.join(`.`),lge=e=>e.kind===`compare`&&e.op===`=`&&e.value.kind===`boolean`&&e.value.value,uge=(e,t)=>{let n=e.kind===`or`?e.args:[e];if(!n.every(lge))return;let r=n.map(s8),i=t.get(r[0]);return i!==void 0&&r.every(e=>t.get(e)===i)?{group:i,fields:r}:void 0},c8=e=>e.kind===`number`?String(e.raw):e.kind===`string`?String(e.value):void 0,l8=(e,t,n)=>{let r=e.value;if(r.kind===`now`&&r.offset?.sign===`-`){let{amount:e,unit:t}=r.offset.duration;return Object.entries(e8).find(([,n])=>n.amount===e&&n.unit===t)?.[0]}if(r.kind===`timestamp`)return n8.find(e=>r8(t8(e,t,n),`timestamp`,n)===r.value);if(r.kind===`string`)return n8.find(e=>t8(e,t,n)===r.value)},u8=(e,t,n=new Date,r=Wd())=>{let i=Sa(t);if(!i.ok)return{ok:!1,errors:i.errors};let a={facets:{},toggles:[]},o=[],s=new Set(e.facets.filter(e=>!e.flags).map(e=>e.id)),c=new Map(e.facets.filter(e=>e.flags).flatMap(e=>e.options.map(t=>[t.value,e.id]))),l=new Set((e.toggles??[]).map(e=>e.id)),u=new Set((e.ranges??[]).map(e=>e.id)),d=new Map,f,p;for(let t of i.ast?o8(i.ast):[]){let i=uge(t,c);if(i&&!a.facets[i.group])a.facets[i.group]=i.fields;else if(t.kind===`compare`&&s.has(s8(t))&&t.op===`=`&&c8(t.value)!==void 0)a.facets[s8(t)]=[...a.facets[s8(t)]??[],c8(t.value)];else if(t.kind===`in`&&s.has(s8(t))&&t.values.every(e=>c8(e)!==void 0))a.facets[s8(t)]=[...a.facets[s8(t)]??[],...t.values.map(e=>c8(e))];else if(t.kind===`compare`&&e.dateField===s8(t)&&t.op===`>=`&&l8(t,n,r)&&!a.date)a.date=l8(t,n,r),f=t;else if(t.kind===`compare`&&e.dateField===s8(t)&&t.op===`<`&&(t.value.kind===`timestamp`||t.value.kind===`string`)&&t.value.value===r8(t8(`today`,n,r),t.value.kind===`string`?`date`:`timestamp`,r))p=t;else if(t.kind===`compare`&&l.has(s8(t))&&t.op===`=`&&t.value.kind===`boolean`&&t.value.value)a.toggles.push(s8(t));else if(t.kind===`compare`&&u.has(s8(t))&&(t.op===`>=`||t.op===`<=`)&&t.value.kind===`number`){let e=d.get(s8(t))??{clauses:[]};t.op===`>=`?e.low=t.value.value:e.high=t.value.value,e.clauses.push(t),d.set(s8(t),e)}else o.push(t)}a.date===`yesterday`&&!p&&(o.push(f),a.date=void 0),p&&a.date!==`yesterday`&&o.push(p);for(let[e,t]of d)t.low!==void 0&&t.high!==void 0?a.ranges={...a.ranges,[e]:[t.low,t.high]}:o.push(...t.clauses);return{ok:!0,state:a,extras:o}},dge=[`integer`,`bigint`,`decimal`],fge=(e,t)=>{let n=e?.fields[t]?.type;return n!==void 0&&dge.includes(n)},d8=(e,t)=>e.kind===`range`||e.kind===`facets`&&fge(t,e.field),pge=e=>({id:e,label:e,min:0,max:0,step:1,histogram:[],format:String}),f8=(e,t)=>{let n=e?.filters??[],r=n.find(e=>e.kind===`dateRange`);return{facets:n.flatMap(e=>e.kind===`facets`&&!d8(e,t)?[{id:e.field,label:e.field,options:[],searchable:e.search,...t?.fields[e.field]?.type===`relation`&&{combobox:!0}}]:e.kind===`flags`?[{id:e.fields.join(`|`),label:e.label,options:e.fields.map(e=>({value:e,label:e,count:0})),flags:!0}]:[]),ranges:n.flatMap(e=>e.kind!==`flags`&&d8(e,t)?[pge(e.field)]:[]),...r&&{dateField:r.field,dateKind:t?.fields[r.field]?.type===`date`?`date`:`timestamp`,...r.presets.length>0&&{datePresets:r.presets}},toggles:n.flatMap(e=>e.kind===`toggle`?[{id:e.field,label:e.field}]:[])}},p8=(e,t)=>(e?.filters??[]).some(e=>e.kind===`range`&&e.field===t&&e.histogram),m8=(e,t)=>{let n=e?.fields[t],r=n?.suffix??``;return e=>`${n?.prefix===`€`?Rd(e*100).replace(`.00`,``):String(e)}${r}`},h8=co(),mge={start:0,end:0},hge=(e,t,n)=>{let r=u8(f8(t,e),n);return r.ok?Object.fromEntries(Object.entries(r.state.facets).filter(([t,n])=>e.fields[t]?.type===`relation`&&n.length>0)):{}},gge=(e,t,n)=>{let r=e=>t?.fields[e]?.label??K(e),i=f8(t,e);return{...i,facets:i.facets.map(i=>{if(i.flags)return{...i,options:i.options.map(e=>({...e,label:r(e.value)}))};let a=e.fields[i.id]?.enumValues??[],o=e.fields[i.id]?.type===`enum`?Object.fromEntries(a.map(e=>[e,rs(e,t?.fields[i.id]?.valueLabels)])):n[i.id]??{};return{...i,label:r(i.id),labels:o}}),ranges:(i.ranges??[]).map(e=>({...e,label:r(e.id),format:m8(t,e.id)})),toggles:i.toggles?.map(e=>({...e,label:r(e.id)}))}},g8=(e,t,n,r={})=>{let i=gge(e,t,r),a=u8(i,n);if(!a.ok)return[{key:`unreadable`,label:`A filter that cannot be read`}];let o=a.extras.map((e,t)=>({key:`extra:${t}`,label:e.kind===`search`?`"${e.text}"`:qa(e)}));return[...V6(i,a.state),...o]},_ge=e=>Object.fromEntries(e.facets.filter(e=>!e.flags).map(e=>[e.id,{...e.labels,...Object.fromEntries(e.options.map(e=>[e.value,e.label]))}])),vge=(e,t,n)=>{if(typeof n!=`string`||n===``)return e;let r=h8.gt(t,{kind:`timestamp`,value:new Date(n).toISOString(),span:mge}),i=Sa(e);if(!i.ok)throw Error(`The saved filter cannot be read: ${i.errors.map(e=>e.message).join(`; `)}`);return qa(i.ast?h8.and(i.ast,r):r)},yge=(e,t)=>typeof t!=`string`||t===``?!0:typeof e!=`string`||e===``?!1:new Date(e).getTime()>new Date(t).getTime(),_8=(e,t)=>{let n=G(),r=Gp(),{resources:i,views:a}=J(),o=a[e.name],s=Object.entries(hge(e,o,t)),c=fh({queries:s.map(([t,o])=>{let s=i[e.fields[t].relation.resource];return{queryKey:W.labels(`chips:${e.name}.${t}`,o.join(`,`)),enabled:s!==void 0,queryFn:async()=>Object.fromEntries(await c4(r,n,s,o,a[s.name]))}})});return g8(e,o,t,Object.fromEntries(s.flatMap(([e],t)=>c[t]?.data?[[e,c[t].data]]:[])))},bge=(e,t)=>({record:Object.fromEntries(Object.entries(t).filter(([t])=>Object.hasOwn(e.fields,t))),etag:typeof t.etag==`string`?t.etag:``,...typeof t.permissions==`object`&&t.permissions!==null&&{permissions:t.permissions}}),v8=e=>{let t=Gp();return(0,o.useCallback)(n=>t.setQueryData(W.recordPreview(e.name,Ao(zx(e,n))),bge(e,n)),[t,e])},y8={wallet:dee,"file-text":ot,send:lee,ruler:see,bed:ee,bath:M,house:nee,"door-open":He,"land-plot":yt,leaf:wt,tag:Fn,key:_t,calendar:fe,heart:ut,bell:te,bookmark:se,"external-link":Qe},b8=e=>e!==void 0&&Object.hasOwn(y8,e)?y8[e]:void 0,x8=({benefits:e})=>e&&e.length>0?(0,V.jsx)(`ul`,{className:`flex flex-col gap-2 text-left`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,V.jsx)(ge,{className:`mt-0.5 size-4 shrink-0 text-primary`,"aria-hidden":!0}),e]},e))}):null,S8=({prompt:e})=>{let{canSignUp:t}=H(),{link:n}=Ih(),r=Cf({variant:`primary`}),i=e.signUp?(0,V.jsx)(`a`,{href:e.signUp.href,target:`_blank`,rel:`noreferrer`,className:r,children:e.signUp.label}):t&&(0,V.jsx)(du,{to:n(`sign-up`),className:r,children:`Create an account`});return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(du,{to:n(),className:i?Cf():r,children:`Sign in`}),i]})},C8=e=>{let{prompt:t}=e,n=(0,o.useId)();if(e.as===`dialog`)return(0,V.jsx)(dT,{title:t.title,description:t.description,open:e.open,onClose:e.onClose,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:e.onClose,children:`Not now`}),(0,V.jsx)(S8,{prompt:t})]}),children:(0,V.jsx)(x8,{benefits:t.benefits})});let r=b8(t.icon)??It;return(0,V.jsxs)(`section`,{"aria-labelledby":n,className:`mx-auto flex w-full max-w-md flex-col items-center gap-4 px-5 py-10 text-center sm:py-16`,children:[(0,V.jsx)(`span`,{className:`flex size-12 items-center justify-center rounded-full bg-primary/10 text-primary`,children:(0,V.jsx)(r,{className:`size-6`,"aria-hidden":!0})}),(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsx)(`h1`,{id:n,className:`text-lg font-semibold`,children:t.title}),(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:t.description})]}),(0,V.jsx)(x8,{benefits:t.benefits}),(0,V.jsx)(`div`,{className:`mt-2 flex w-full flex-col-reverse gap-2 sm:w-auto sm:flex-row sm:justify-center [&>*]:min-h-11 sm:[&>*]:min-h-0`,children:(0,V.jsx)(S8,{prompt:t})})]})},xge=co(),w8=e=>{if(typeof e==`string`||typeof e==`number`)return e;if(e&&typeof e==`object`&&`id`in e)return w8(e.id)},Sge=(e,t,n)=>n.flatMap(n=>{let r=w8(n[t]);return r===void 0?[]:[{key:Ao(zx(e,n)),target:r}]}),Cge=(e,t)=>e.find(e=>Ao(e.target)===t),wge=(e,t)=>[...e,{key:``,target:t}],Tge=(e,t)=>e.filter(e=>Ao(e.target)!==t),T8=(e,t)=>{let[n]=e.primaryKey;if(e.primaryKey.length!==1||n===void 0)throw Error(`${e.name} has a composite key, so its saved records cannot be listed`);let r=[...new Set(t.map(e=>e.target))];return r.length===0?void 0:xge.in(n,r)},E8=(e,t)=>W.list(e,``,``,500,`saved:${t}`),D8=(e,t,n)=>{let r=G(),i=J().resources[e];return mh({queryKey:E8(e,t),enabled:n&&i!==void 0,queryFn:async()=>{let n=[],a;do{let o=await r.list(e,{pageSize:500,fields:[...i.primaryKey,t],...a&&{pageToken:a}});n.push(...o.items),a=o.nextPageToken||void 0}while(a);return Sge(i,t,n)}})},Ege=e=>e instanceof Error?e.message:`Something went wrong`,Dge=(e,t,n)=>{let r=J(),i=G(),a=Gp(),o=Qy(),s=qT(),{resource:c,field:l}=e,u=r.permissions[c],d=r.resources[c]!==void 0&&u!==void 0&&MT(u,`create`)&&MT(u,`delete`),f=r.signIn?.[c]?.signIn,p=D8(c,l,d),m=p.data&&Cge(p.data,t),h=E8(c,l),g=hh({mutationFn:async e=>{e?await i.remove(c,e.key):await i.create(c,{[l]:n})},onMutate:async e=>{await a.cancelQueries({queryKey:h,exact:!0});let r=a.getQueryData(h);return a.setQueryData(h,(r=[])=>e?Tge(r,t):wge(r,n)),{before:r}},onError:(e,t,n)=>{a.setQueryData(h,n?.before),o.show({state:`error`,title:t?`Could not take it off`:`Could not save it`,description:Ege(e)})},onSettled:()=>s(c)});return{mode:d?`save`:f?`sign-in`:void 0,prompt:f,saved:m!==void 0,ready:p.data!==void 0&&!g.isPending,toggle:()=>g.mutate(m)}},Oge=({favorite:e,recordKey:t,target:n,className:r})=>{let i=Dge(e,t,n),[a,s]=(0,o.useState)(!1);if(!i.mode)return null;let c=e.label??`Favorite`,l=B(`absolute right-2 top-2 flex size-8 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,r);return i.mode===`sign-in`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":c,"aria-haspopup":`dialog`,className:l,onClick:()=>s(!0),children:(0,V.jsx)(ut,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsx)(C8,{as:`dialog`,prompt:i.prompt,open:a,onClose:()=>s(!1)})]}):(0,V.jsx)(`button`,{type:`button`,"aria-label":c,"aria-pressed":i.saved,"aria-disabled":!i.ready,className:l,onClick:()=>i.ready&&i.toggle(),children:(0,V.jsx)(ut,{className:B(`size-4`,i.saved&&`fill-current text-danger`),"aria-hidden":!0})})},O8=6,kge=(e,t,n)=>{let r=e.bottom+O8;return{top:r+t.height>n.height-O8?Math.max(O8,e.top-O8-t.height):r,left:Math.max(O8,Math.min(e.left,n.width-O8-t.width))}},k8=(e,t)=>{let n=uS(e).find(e=>e.kind===`cards`);if(!n)return{kind:`cards`,name:`dot`,badge:t};let{photos:r,favorite:i,dots:a,...o}=n;return o},Age=(e,t,n,r)=>(e?.list?.relatedColumns??[]).filter(e=>r.includes(e.name)).flatMap(e=>{let r=t[e.resource];return r?[{column:e,fields:ES(r,n[r.name],k8(n[r.name],e.status))}]:[]}),jge=(e,{values:t,label:n,singular:r,plural:i})=>{if(e.length===0)return`No ${i}`;let a=new Map;for(let t of e)t!=null&&a.set(String(t),(a.get(String(t))??0)+1);let o=[...t,...[...a.keys()].filter(e=>!t.includes(e))].filter(e=>a.has(e)).map(e=>`${a.get(e)} ${n(e)}`),s=`${e.length} ${e.length===1?r:i}`;return o.length===0?s:`${s}: ${o.join(`, `)}`},A8=`flex shrink-0 items-center justify-center rounded-full p-0.5 pointer-coarse:p-1.5`,j8=`size-2.5 rounded-full`,M8=`flex min-w-0 items-center gap-0.5`,Mge=150,N8=288,Nge=({shown:e,row:t,target:n,view:r,column:i,Card:a,onEnter:s,onLeave:c})=>{let l=(0,o.useRef)(null),[u,d]=(0,o.useState)();return(0,o.useLayoutEffect)(()=>{l.current&&d(kge(e.dot,{width:N8,height:l.current.offsetHeight},{width:window.innerWidth,height:window.innerHeight}))},[e]),(0,nr.createPortal)((0,V.jsx)(`div`,{ref:l,"data-dot-card":!0,onMouseEnter:s,onMouseLeave:c,style:{width:N8,...u??{visibility:`hidden`,top:0,left:0}},className:`fixed z-50 rounded-lg shadow-pop`,children:(0,V.jsx)(a,{model:n,view:r,display:k8(r,i.status),row:t})}),document.body)},P8=({column:e,records:t,target:n,view:r,wrap:i=!1,Card:a})=>{let s=(0,o.useMemo)(()=>t.map(e=>AS(n,e)),[t,n]),[c,l]=(0,o.useState)(),u=(0,o.useRef)(void 0),d=(0,o.useRef)(`mouse`),f=(0,o.useRef)(null),p=n.fields[e.status],m=r?.fields[e.status],h=t=>p?eS(p,t.record[e.status],m):``,g=Fx(n,r),_=e=>e.labels[g]??String(e.record[g]??e.key),v=(r?.names?.singular??K(n.name)).toLowerCase(),y=(r?.names?.plural??K(n.name)).toLowerCase(),b=jge(s.map(t=>t.record[e.status]),{values:p?.enumValues??[],label:e=>p?eS(p,e,m):e,singular:v,plural:y}),x=()=>window.clearTimeout(u.current),S=()=>{x(),u.current=window.setTimeout(()=>l(void 0),Mge)},C=(e,t)=>{x(),l({key:e,dot:t.getBoundingClientRect()})};(0,o.useEffect)(()=>x,[]),(0,o.useEffect)(()=>{if(!c)return;let e=()=>l(void 0),t=t=>t.key===`Escape`&&e(),n=t=>{let n=t.target;!f.current?.contains(n)&&!n?.closest?.(`[data-dot-card]`)&&e()};return document.addEventListener(`keydown`,t),document.addEventListener(`pointerdown`,n),document.addEventListener(`scroll`,e,!0),window.addEventListener(`resize`,e),()=>{document.removeEventListener(`keydown`,t),document.removeEventListener(`pointerdown`,n),document.removeEventListener(`scroll`,e,!0),window.removeEventListener(`resize`,e)}},[c]);let w=e=>t=>{d.current===`touch`&&c?.key!==e&&(t.preventDefault(),C(e,t.currentTarget))},T=e=>{e.relatedTarget?.closest?.(`[data-dot-card]`)||S()},E=c&&s.find(e=>e.key===c.key);return(0,V.jsxs)(`div`,{ref:f,className:B(M8,i&&`pointer-events-none flex-wrap`),onClick:e=>e.stopPropagation(),onPointerDown:e=>d.current=e.pointerType,children:[(0,V.jsx)(`span`,{className:`sr-only`,children:b}),s.map(t=>{let r=t.record[e.status],i=f4(m?.valueColors,r);return(0,V.jsx)(ZS,{to:{kind:`record`,resource:n.name,key:t.key},"aria-label":`${_(t)}, ${h(t)}`,onPointerEnter:e=>e.pointerType!==`touch`&&C(t.key,e.currentTarget),onPointerLeave:e=>e.pointerType!==`touch`&&S(),onFocus:e=>e.currentTarget.matches(`:focus-visible`)&&C(t.key,e.currentTarget),onBlur:T,onClick:w(t.key),className:B(A8,`pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40`),children:(0,V.jsx)(`span`,{"aria-hidden":!0,style:i===void 0?void 0:{backgroundColor:i},className:B(j8,i===void 0&&Ou[Gx(String(r))],c?.key===t.key&&`ring-2 ring-foreground/30`)})},t.key)}),c&&E&&(0,V.jsx)(Nge,{shown:c,row:E,target:n,view:r,column:e,Card:a,onEnter:x,onLeave:S})]})},Pge=({count:e})=>(0,V.jsx)(`span`,{"aria-hidden":!0,className:B(M8,`invisible flex-wrap`),children:Array.from({length:e},(e,t)=>(0,V.jsx)(`span`,{className:A8,children:(0,V.jsx)(`span`,{className:j8})},t))}),F8=`flex flex-col gap-1.5`,Fge=({dots:e})=>(0,V.jsx)(`span`,{className:F8,children:e.map(({column:e,records:t})=>(0,V.jsx)(Pge,{count:t.length},e.name))}),Ige=({dots:e,Card:t})=>{let{resources:n,views:r}=J();return(0,V.jsx)(`div`,{className:`pointer-events-none absolute inset-x-[calc(0.75rem+1px)] bottom-[calc(0.75rem+1px)] ${F8}`,children:e.map(({column:e,records:i})=>{let a=n[e.resource];return a&&(0,V.jsx)(P8,{column:e,records:i,target:a,view:r[a.name],Card:t,wrap:!0},e.name)})})},Lge=(e,t,n)=>(t.dots??[]).flatMap(t=>{let r=e?.list?.relatedColumns?.find(e=>e.name===t),i=n.record[t];return r&&Array.isArray(i)&&i.length>0?[{column:r,records:i}]:[]}),I8=({value:e})=>{let t=Ob(e,{width:320,height:240});return t?(0,V.jsx)(hC,{image:t,loading:`lazy`,className:`size-full object-cover`}):null},L8=({children:e})=>(0,V.jsx)(`span`,{className:`-mx-3 -mt-3 mb-1.5 block aspect-[4/3] overflow-hidden rounded-t-lg border-b border-border bg-muted`,children:e}),Rge=({value:e})=>(0,V.jsx)(L8,{children:(0,V.jsx)(I8,{value:e})}),zge=10,Bge=(e,t)=>{let n=vb(e)?e.uri:void 0,r=t.filter(e=>vb(e)&&e.uri!==n);return(n===void 0?r:[e,...r]).slice(0,zge)},Vge=(e,t)=>t===0?0:(e%t+t)%t,Hge=(e,t,n)=>t<=0||n===0?0:Math.min(n-1,Math.max(0,Math.round(e/t))),R8=`pointer-events-auto absolute top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm opacity-0 transition-opacity group-has-[[data-card-photos]:hover]/card:opacity-100 group-hover/arrows:opacity-100 group-has-[:focus-visible]/arrows:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,z8=`[@media(hover:none)]:opacity-100`,Uge=({photos:e,cover:t,swipe:n=!0,children:r})=>{let i=(0,o.useRef)(null),a=(0,o.useRef)(void 0),[s,c]=(0,o.useState)(0),l=Bge(t,e),u=e=>{let t=i.current;t&&t.scrollTo({left:e*t.clientWidth})},d=e=>{a.current=Vge((a.current??s)+e,l.length),u(a.current)},f=()=>{a.current=void 0},p=e=>{c(Hge(e.scrollLeft,e.clientWidth,l.length)),a.current!==void 0&&Math.abs(e.scrollLeft-a.current*e.clientWidth)<1&&(a.current=void 0)},m=(0,V.jsx)(L8,{children:(0,V.jsx)(`span`,{ref:i,tabIndex:-1,"data-card-photos":!0,onPointerDown:f,onScroll:e=>p(e.currentTarget),className:B(`flex size-full snap-x snap-mandatory outline-none [scrollbar-width:none] motion-safe:scroll-smooth [&::-webkit-scrollbar]:hidden`,n?`overflow-x-auto overscroll-x-contain`:`overflow-x-hidden`),children:l.map((e,t)=>(0,V.jsx)(`span`,{className:`block size-full shrink-0 snap-start snap-always`,children:(0,V.jsx)(I8,{value:e})},t))})});return(0,V.jsxs)(V.Fragment,{children:[r(m),l.length>1&&(0,V.jsxs)(`div`,{className:`group/arrows pointer-events-none absolute inset-x-px top-px aspect-[4/3]`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":`Previous photo`,className:B(R8,!n&&z8,`left-2`),onClick:()=>d(-1),children:(0,V.jsx)(be,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Next photo`,className:B(R8,!n&&z8,`right-2`),onClick:()=>d(1),children:(0,V.jsx)(Se,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsxs)(`span`,{className:`absolute inset-x-0 bottom-2 flex justify-center`,"aria-live":`polite`,children:[(0,V.jsx)(`span`,{className:`sr-only`,children:`Photo ${s+1} of ${l.length}`}),(0,V.jsx)(`span`,{className:`flex items-center gap-1 rounded-full bg-background/70 px-1.5 py-1 leading-none`,"aria-hidden":!0,children:l.map((e,t)=>(0,V.jsx)(`span`,{className:B(`size-1.5 rounded-full`,t===s?`bg-foreground`:`bg-foreground/35`)},t))})]})]})]})},Wge=({icon:e,children:t})=>{let n=b8(e);return(0,V.jsxs)(`dd`,{className:`flex items-center gap-1 tabular-nums`,children:[n&&(0,V.jsx)(n,{className:`size-3.5 shrink-0`,"aria-hidden":!0}),t]})},B8=({model:e,view:t,display:n,row:r,swipe:i=!0,mark:a})=>{let{image:o,title:s,subtitle:c,amount:l,badge:u,meta:d,footer:f,flags:p}=xS(e,t,n),m=e=>t?.fields[e]?.label??K(e),h=n=>{let i=e.fields[n];if(!i)return``;let a=r.record[n];return r.labels[n]===void 0&&Mx(i,t?.fields[n])&&typeof a==`string`&&a!==``?jx(a):r.labels[n]??eS(i,a,t?.fields[n])},{fields:g,components:_}=SC(),v=v8(e),y=n.card===void 0?void 0:_?.[n.card],b=n=>{let i=e.fields[n],a=i&&CC(g,i,t?.fields[n]);return a?(0,V.jsx)(EC,{shown:a,part:`display`,field:i,value:r.record[n],fallback:h(n)}):h(n)},x=n=>{let i=e.fields[n],a=r.record[n];return!i||!Mx(i,t?.fields[n])||CC(g,i,t?.fields[n])||typeof a!=`string`||a===``?b(n):(0,V.jsx)(OC,{source:a,inLink:!0})},S=n=>{let i=e.fields[n],a=t?.fields[n],o=r.record[n];return!i||a?.format!==`badge`||CC(g,i,a)||o==null||o===``?b(n):(0,V.jsx)(p4,{value:o,hints:a,children:h(n)})},C=n=>{let i=e.fields[n];if(!i)return;if(r.labels[n]!==void 0||CC(g,i,t?.fields[n]))return(0,V.jsx)(`strong`,{className:`font-semibold text-foreground`,children:b(n)});let a=wS(i,r.record[n],t?.fields[n]);return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`strong`,{className:`font-semibold text-foreground`,children:a.amount}),a.suffix]})},w=y?void 0:n.photos,T=u===void 0?void 0:r.record[u],E=p.filter(e=>r.record[e]===!0),D=o===void 0?void 0:r.record[o],O=CS(r,l),k=SS(r,f),A=o!==void 0||w!==void 0,j=n.favorite,M=y?[]:Lge(t,n,r),N=e=>(0,V.jsxs)(V.Fragment,{children:[A&&e,(0,V.jsxs)(`span`,{className:`flex items-start justify-between gap-2 ${j&&!A?`pr-8`:``}`,children:[(0,V.jsx)(`span`,{className:`min-w-0 truncate font-medium`,children:b(s)}),u!==void 0&&T!=null&&(0,V.jsx)(p4,{value:T,hints:t?.fields[u],children:h(u)})]}),c!==void 0&&(0,V.jsx)(`span`,{className:t?.fields[c]?.markdown?`line-clamp-3 break-words text-muted-foreground`:t?.fields[c]?.multiline?`line-clamp-3 whitespace-pre-line break-words text-muted-foreground`:`truncate text-muted-foreground`,children:x(c)}),O!==void 0&&(0,V.jsx)(`span`,{className:`truncate tabular-nums text-muted-foreground`,children:C(O)}),d.length>0&&(0,V.jsx)(`dl`,{className:`mt-auto flex flex-wrap items-center gap-x-3 gap-y-0.5 pt-1 text-xs text-muted-foreground`,children:SS(r,d).map(e=>(0,V.jsxs)(`div`,{className:`flex gap-1`,children:[(0,V.jsx)(`dt`,{className:`sr-only`,children:m(e)}),(0,V.jsx)(Wge,{icon:t?.fields[e]?.icon,children:S(e)})]},e))}),E.length>0&&(0,V.jsx)(`ul`,{className:`flex flex-wrap gap-1`,"aria-label":`Features`,children:E.map(e=>(0,V.jsx)(`li`,{children:(0,V.jsx)(Au,{dot:!1,children:m(e)})},e))}),k.length>0&&(0,V.jsx)(`span`,{className:`truncate text-xs text-muted-foreground ${d.length>0?``:`mt-auto`}`,children:k.map((e,t)=>(0,V.jsxs)(`span`,{children:[t>0&&(0,V.jsx)(`span`,{"aria-hidden":!0,children:` • `}),b(e)]},e))}),M.length>0&&(0,V.jsx)(Fge,{dots:M})]}),ee=t=>(0,V.jsxs)(ZS,{to:{kind:`record`,resource:e.name,key:r.key},onClick:()=>v(r.record),className:`flex h-full flex-col gap-1.5 rounded-lg border border-border bg-background p-3 hover:border-border-strong hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,children:[a&&!A&&(0,V.jsx)(Au,{tone:`blue`,className:`self-start`,children:a}),y?(0,V.jsx)(Qh,{name:n.card,fallback:N(t),children:(0,V.jsx)(y,{row:r})}):N(t)]});return(0,V.jsxs)(`div`,{className:w?`group/card relative h-full`:j||a||M.length>0?`relative h-full`:`h-full`,children:[w?(0,V.jsx)(Uge,{photos:r.photos??[],cover:D,swipe:i,children:ee},r.key):ee((0,V.jsx)(Rge,{value:D})),a&&A&&(0,V.jsx)(Au,{tone:`blue`,className:`pointer-events-none absolute top-2 left-2 shadow-sm`,children:a}),M.length>0&&(0,V.jsx)(Ige,{dots:M,Card:B8}),j&&(0,V.jsx)(Oge,{favorite:j,recordKey:r.key,target:zx(e,r.record),className:A?void 0:`right-1.5 top-1.5`})]})},V8=268,H8=3,U8=(e,t,n)=>{let r=Math.floor(Math.max(0,e)/V8),i=Math.ceil((Math.max(0,e)+t)/V8);return{start:Math.max(0,r-H8),end:Math.min(n,i+H8)}},W8=e=>e*V8,Gge=e=>{let t=(0,o.useRef)(null),[n,r]=(0,o.useState)({left:0,width:0});(0,o.useLayoutEffect)(()=>{let n=t.current;if(!n)return;let i=()=>r(t=>{let r={left:n.scrollLeft,width:n.clientWidth};return((t,n)=>{let[r,i]=[U8(t.left,t.width,e),U8(n.left,n.width,e)];return r.start===i.start&&r.end===i.end&&t.width===n.width&&t.left>0==n.left>0&&Math.abs(t.left-n.left)<1})(t,r)?t:r});i();let a=new ResizeObserver(i);return a.observe(n),n.addEventListener(`scroll`,i,{passive:!0}),()=>{a.disconnect(),n.removeEventListener(`scroll`,i)}},[e]);let i=Math.max(0,W8(e)-12),a=e=>t.current?.scrollBy({left:e*Math.max(W8(1),n.width-12),behavior:`smooth`});return{ref:t,...U8(n.left,n.width,e),back:n.left>0,on:n.left+n.width<i-1,page:a}},G8=`absolute top-1/2 z-10 hidden size-8 -translate-y-1/2 items-center justify-center rounded-full border border-border-strong bg-background shadow-pop hover:bg-muted sm:flex`,K8=({cards:e})=>e>0?(0,V.jsx)(`li`,{"aria-hidden":!0,className:`shrink-0`,style:{width:W8(e)-12}}):null,Kge=({model:e,view:t,display:n,source:r,label:i,isNew:a})=>{let{total:o}=r,s=Gge(o),c=p6({total:o,rowAt:r.rowAt,loadRows:r.loadRows,revision:r.revision,latencyMs:0},s.start,Math.max(s.start,s.end-1)),l=Array.from({length:s.end-s.start},(e,t)=>s.start+t);return(0,V.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,V.jsxs)(`ul`,{ref:s.ref,"aria-label":i,className:`flex snap-x gap-3 overflow-x-auto overflow-y-hidden pb-1`,style:{scrollbarWidth:`thin`},children:[(0,V.jsx)(K8,{cards:s.start}),l.map(r=>{let i=c(r);if(!i)return(0,V.jsx)(`li`,{"aria-hidden":!0,className:`shrink-0`,style:{width:256},children:(0,V.jsx)(cu,{className:`h-full min-h-24 rounded-lg`})},`skeleton-${r}`);let s=AS(e,i);return(0,V.jsx)(`li`,{"aria-posinset":r+1,"aria-setsize":o,className:`grid shrink-0 snap-start grid-cols-[minmax(0,1fr)]`,style:{width:256},children:(0,V.jsx)(B8,{model:e,view:t,display:n,row:s,swipe:!1,mark:a?.(s)?`New`:void 0})},s.key)}),(0,V.jsx)(K8,{cards:o-s.end})]}),s.back&&(0,V.jsx)(`button`,{type:`button`,"aria-label":`Previous ${i.toLowerCase()}`,onClick:()=>s.page(-1),className:`${G8} -left-3`,children:(0,V.jsx)(be,{className:`size-4`,"aria-hidden":!0})}),s.on&&(0,V.jsx)(`button`,{type:`button`,"aria-label":`Next ${i.toLowerCase()}`,onClick:()=>s.page(1),className:`${G8} -right-3`,children:(0,V.jsx)(Se,{className:`size-4`,"aria-hidden":!0})})]})},qge=co(),Jge=(e,t)=>{if(!t)return e;let n=Sa(e);if(!n.ok)throw Error(`The filter cannot be read: ${n.errors.map(e=>e.message).join(`; `)}`);return qa(n.ast?qge.and(n.ast,t):t)},Yge=(e,t)=>{let n=uS(e).filter(e=>e.kind===`cards`);return n.find(e=>e.name===t)??n[0]??{kind:`cards`,name:`cards`}},Xge=()=>(0,V.jsx)(`div`,{className:`flex gap-3 overflow-hidden`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-24 w-64 shrink-0`},t))}),q8=({model:e,view:t,filter:n,sort:r=``,display:i,limit:a,chips:s=!0,empty:c,note:l,isNew:u,viewAll:d,scope:f,list:p})=>{let{resources:m,views:h}=J(),g=ql(),_=Yge(t,i),v=r||jS(e,t),y=k6({resources:m,views:h,model:e,columns:(0,o.useMemo)(()=>DS(e,t,[]),[e,t]),filter:(0,o.useMemo)(()=>Jge(n,f),[n,f]),orderBy:v}),b=_8(e,n),x=(t?.names?.singular??K(e.name)).toLowerCase(),S=t?.names?.plural??K(e.name),C=y.source?.total,T=(0,o.useMemo)(()=>y.source&&{...y.source,total:Math.min(y.source.total,a??1/0)},[y.source,a]);return(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3`,children:[s&&b.length>0||C!==void 0||l?(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[s&&b.length>0?(0,V.jsx)(M6,{chips:b}):(0,V.jsx)(`span`,{}),(0,V.jsxs)(`p`,{className:`flex flex-wrap gap-x-3 text-muted-foreground`,children:[l&&(0,V.jsx)(`span`,{children:l}),C!==void 0&&(0,V.jsx)(`span`,{className:`tabular-nums`,children:`${C.toLocaleString(`en-GB`)} ${C===1?x:S.toLowerCase()}`})]})]}):null,y.isLoading?(0,V.jsx)(Xge,{}):y.error?(0,V.jsx)(ax,{title:`Could not load`,error:y.error}):!T||T.total===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:c??`No ${S.toLowerCase()} match.`}):(0,V.jsx)(Kge,{model:e,view:t,display:_,source:T,label:S,isNew:u}),(0,V.jsxs)(ZS,{to:A6(e,t,g,{filter:n,orderBy:v,display:_.name,savedSearch:d?.savedSearch,resource:p}),onClick:d?.onOpen,className:`flex items-center gap-1 self-end font-medium text-primary-text hover:underline`,children:[d?.label??(0,V.jsxs)(V.Fragment,{children:[`View all `,(0,V.jsx)(`span`,{className:`sr-only`,children:S.toLowerCase()})]}),(0,V.jsx)(w,{className:`size-3.5`,"aria-hidden":!0})]})]})},Zge=({model:e,view:t,empty:n,...r})=>{let{resources:i,views:a}=J(),o=PS(i,a,e.name),s=D8(e.name,t.listOf,!0),c=(t.names?.plural??K(e.name)).toLowerCase();if(!o.listOf)return null;if(s.error)return(0,V.jsx)(ax,{title:`Could not load your ${c}`,error:s.error});if(!s.data)return(0,V.jsx)(cu,{className:`h-24`});let l=T8(o.model,s.data);return l?(0,V.jsx)(q8,{...r,model:o.model,view:o.view,filter:``,scope:l,list:e.name,empty:n}):(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:n??`No ${c} yet.`})},Qge=e=>W.list(e,``,``,500,`saved-searches`),J8=(e,t)=>{let n=G(),{resources:r,views:i}=J(),a=r[e];return mh({queryKey:Qge(e),enabled:t&&a!==void 0,queryFn:async()=>{let t=[],r;do{let o=await n.list(e,{pageSize:500,orderBy:jS(a,i[e]),...r&&{pageToken:r}});t.push(...o.items),r=o.nextPageToken||void 0}while(r);return t}})},Y8=({model:e,of:t,target:n,targetView:r,row:i,recordKey:a})=>{let o=G(),s=qT(),c=String(i[t.filter]??``),l=_8(n,c),u=t.name===void 0?void 0:i[t.name],d=typeof u==`string`&&u!==``?u:void 0,f=t.unseen,p=hh({mutationFn:t=>o.update(e.name,a,{[f.seenAt]:t},i.etag??`*`),onSettled:()=>s(e.name)}),m=mh({...UT(o,n,f?vge(c,f.field,i[f.seenAt]):``),enabled:f!==void 0}),h=(r?.names?.plural??K(n.name)).toLowerCase(),g={model:n,view:r,filter:c,sort:f?`${f.field} desc`:void 0,limit:t.limit,chips:d!==void 0,empty:`No ${h} match.`,note:f&&m.data===0&&`No new ${h} since you last looked.`,isNew:f&&(e=>yge(e.record[f.field],i[f.seenAt])),viewAll:{label:`View all results`,savedSearch:a,...f&&{onOpen:()=>p.mutate(new Date().toISOString())}}};return{name:d,chips:l,title:d??Khe(l),body:g}},$ge=({model:e,view:t,target:n,targetView:r,row:i})=>{let a=Ao(zx(e,i)),{name:o,chips:s,title:c,body:l}=Y8({model:e,of:t.searchesOf,target:n,targetView:r,row:i,recordKey:a});return(0,V.jsxs)(`section`,{"aria-label":c,className:`flex flex-col gap-3 py-4 first:pt-0 last:pb-0`,children:[(0,V.jsx)(`h3`,{className:`text-[15px] font-semibold`,children:(0,V.jsx)(ZS,{to:{kind:`record`,resource:e.name,key:a},className:`hover:underline`,children:o??(0,V.jsx)(N6,{chips:s})})}),(0,V.jsx)(q8,{...l})]})},e_e=({model:e,view:t,empty:n})=>{let{resources:r,views:i}=J(),a=t.searchesOf,o=r[a.resource],s=J8(e.name,!0),c=(t.names?.plural??K(e.name)).toLowerCase();return o?s.error?(0,V.jsx)(ax,{title:`Could not load your ${c}`,error:s.error}):s.data?s.data.length===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:n??`No ${c} yet.`}):(0,V.jsx)(`div`,{className:`flex flex-col divide-y`,children:s.data.map(n=>(0,V.jsx)($ge,{model:e,view:t,target:o,targetView:i[a.resource],row:n},Ao(zx(e,n))))}):(0,V.jsx)(cu,{className:`h-40`}):null},t_e=({node:e,slots:t})=>{let{resource:n,filter:r=``,sort:i,limit:a,display:o,title:s,description:c,empty:l}=ZT(e),{resources:u,views:d}=J(),f=u[n];if(!f)return null;let p=d[f.name];return(0,V.jsx)($T,{title:s,description:c,actions:t.actions,children:p?.searchesOf?(0,V.jsx)(e_e,{model:f,view:p,empty:l}):p?.listOf===void 0?(0,V.jsx)(q8,{model:f,view:p,filter:r,sort:i,limit:a,display:o,empty:l}):(0,V.jsx)(Zge,{model:f,view:p,limit:a,display:o,empty:l})})},n_e=({node:e,children:t})=>{let{when:n}=ZT(e),{resources:r}=J(),i=G(),a=jT(),s=(0,o.useMemo)(()=>ic(n),[n]),c=s.ok?s.paths:[],l=c.map(e=>oc(e,e=>!!(a&&Object.hasOwn(a.model.fields,e)))),u=c.filter((e,t)=>l[t]===void 0),d=ffe(a,u),f=fh({queries:l.flatMap(e=>{let t=e===void 0?void 0:r[e];return t?[UT(i,t)]:[]})});if(!s.ok||d.some(e=>e.state===`loading`)||f.some(e=>e.isPending))return null;let p={};u.forEach((e,t)=>{let n=d[t];n.state===`ready`&&(p[e]=n.value)});let m=0;return c.forEach((e,t)=>{l[t]!==void 0&&(p[e]=r[l[t]]?f[m++]?.data??0:0)}),ac(s,p)?(0,V.jsx)(V.Fragment,{children:t}):null},X8=`text-2xl font-semibold tracking-tight tabular-nums`,r_e=({model:e,filter:t})=>{let n=WT(e,t);return n.isPending?(0,V.jsx)(cu,{className:`h-8 w-16`}):n.error?(0,V.jsx)(`span`,{className:`text-danger-text`,children:`Could not count`}):(0,V.jsx)(ZS,{to:{kind:`list`,resource:e.name,filter:t},className:`${X8} hover:text-primary-text after:absolute after:inset-0 after:content-['']`,children:n.data.toLocaleString(`en-IE`)})},i_e=({field:e,format:t})=>{let n=v4(jT(),e);return n.state===`loading`?(0,V.jsx)(cu,{className:`h-8 w-16`}):n.state===`missing`?null:(0,V.jsx)(`span`,{className:X8,children:(0,V.jsx)(m4,{model:n.model,field:n.field,value:n.value,format:t})})},a_e=({node:e})=>{let{label:t,value:n,resource:r,filter:i,field:a,format:o,description:s}=ZT(e),{resources:c}=J(),l=r===void 0?void 0:c[r];return(0,V.jsxs)($T,{className:`relative h-full`,bodyClassName:`flex flex-col`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground break-words`,children:t}),(0,V.jsxs)(`div`,{className:`mt-auto pt-1`,children:[n!==void 0&&(0,V.jsx)(`span`,{className:X8,children:n}),l&&(0,V.jsx)(r_e,{model:l,filter:i}),a!==void 0&&(0,V.jsx)(i_e,{field:a,format:o})]}),s&&(0,V.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s})]})},Z8=e=>e===null?`none`:`value:${e}`,Q8=e=>{let t=xie(e);return t.length>0?t:a_(e)},o_e=(e,{context:{collisionRect:t,droppableRects:n,droppableContainers:r,over:i}})=>{let a=e.code===`ArrowRight`?1:e.code===`ArrowLeft`?-1:0;if(a===0||!t)return;e.preventDefault();let o=r.getEnabled().flatMap(e=>{let t=n.get(e.id);return t?[{id:e.id,rect:t}]:[]}).sort((e,t)=>e.rect.left-t.rect.left),s=t.left+t.width/2,c=i?o.findIndex(e=>e.id===i.id):o.findIndex(e=>e.rect.left<=s&&s<=e.rect.right),l=o[c+a];if(c!==-1&&l)return{x:l.rect.left+(l.rect.width-t.width)/2,y:l.rect.top}},$8=(e,t,n,r)=>{let i=gh({queryKey:[...n,`display`],enabled:r,initialPageParam:0,queryFn:({pageParam:e})=>t(e),getNextPageParam:(e,t)=>e.rows.length===40&&t.length*40<(t[0]?.total??0)?t.length:void 0}),a=i.data?.pages??[];return{resource:e.name,rows:a.flatMap(t=>t.rows.map(t=>AS(e,t))),total:a[0]?.total??0,loading:i.isPending,error:i.error,more:i.hasNextPage,loadMore:()=>void i.fetchNextPage()}},s_e=({model:e,by:t,value:n,fields:r,filter:i,orderBy:a})=>{let{resources:o,views:s}=J(),c=k6({resources:o,views:s,model:e,columns:r,filter:sS(i,t,n),orderBy:a});return $8(e,c.page,c.key,!0)},c_e=({model:e,view:t,display:n,column:r,fields:i,filter:a,orderBy:o,limit:s,moves:c,movable:l,dragged:u})=>{let d=s_e({model:e,by:n.by,value:r.value,fields:i,filter:a,orderBy:o}),{setNodeRef:f,isOver:p}=Lv({id:Z8(r.value)}),m=cS(e,t,n),h=new Set(d.rows.map(e=>e.key)),g=new Map(c.map(e=>[e.row.key,e])),_=d.rows.filter(e=>g.has(e.key)&&g.get(e.key).to!==r.value),v=c.filter(e=>e.to===r.value&&!h.has(e.row.key)).map(e=>e.row),y=d.rows.filter(e=>!_.includes(e)).map(e=>g.has(e.key)?g.get(e.key).row:e),b=[...v,...y].slice(0,s),x=d.total-_.length+v.length;if(r.value===null&&!d.loading&&x===0&&!p)return null;let S=(t?.names?.plural??K(e.name)).toLowerCase(),C=t?.fields[n.by];return(0,V.jsxs)(`section`,{ref:f,"aria-label":`${r.label}, ${x}`,className:B(`flex w-72 shrink-0 snap-start flex-col gap-2 rounded-lg bg-surface p-2`,p&&`ring-2 ring-primary/30`),children:[(0,V.jsxs)(`header`,{className:`flex items-center justify-between gap-2 px-1 pt-0.5`,children:[(0,V.jsx)(`h2`,{className:`min-w-0 truncate text-xs font-medium`,children:r.value===null?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:r.label}):(0,V.jsx)(p4,{value:r.value,hints:C,children:r.label})}),!d.loading&&(0,V.jsx)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:x.toLocaleString(`en-IE`)})]}),d.loading?Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-20`},t)):d.error?(0,V.jsx)(ax,{title:`Could not load rows`,error:d.error}):b.length===0?(0,V.jsxs)(`p`,{className:`px-1 py-4 text-center text-xs text-muted-foreground`,children:[`No `,S]}):(0,V.jsx)(`ul`,{className:`flex flex-col gap-2`,children:b.map(n=>(0,V.jsx)(`li`,{children:(0,V.jsx)(l_e,{model:e,view:t,card:m,row:n,movable:l&&NT(n.record,`update`),dragged:u})},n.key))}),s===void 0&&d.more&&(0,V.jsx)(U,{size:`sm`,variant:`ghost`,onClick:d.loadMore,children:`Show more`})]})},l_e=({model:e,view:t,card:n,row:r,movable:i,dragged:a})=>{let{setNodeRef:o,setActivatorNodeRef:s,listeners:c,isDragging:l}=Nv({id:r.key,data:{row:r},disabled:!i});return(0,V.jsx)(`div`,{ref:e=>{o(e),s(e?.querySelector(`a`)??e)},...c,onDragStart:e=>e.preventDefault(),onClickCapture:e=>{a()&&(e.preventDefault(),e.stopPropagation())},className:B(i&&`cursor-grab touch-manipulation`,l&&`opacity-40`),children:(0,V.jsx)(B8,{model:e,view:t,display:n,row:r,swipe:!1})})},u_e=(e,t)=>{let n=G(),r=Qy(),i=qT(),[a,s]=(0,o.useState)([]),c=e=>s(t=>t.filter(t=>t.row.key!==e)),l=hh({mutationFn:({row:r,to:i})=>{let a=typeof r.record.etag==`string`?r.record.etag:`*`;return n.update(e.name,zx(e,r.record),{[t]:i.value},a)},onMutate:({row:e,to:n})=>{let r={...e,record:{...e.record,[t]:n.value}};s(t=>[...t.filter(t=>t.row.key!==e.key),{row:r,to:n.value}])},onError:(e,{row:t,to:n})=>{c(t.key),r.show({state:`error`,title:`Could not move it to ${n.label}`,description:lS(e)})},onSettled:async(t,n,{row:r})=>{await i(e.name),c(r.key)}});return{moves:a,move:(e,t)=>l.mutate({row:e,to:t})}},e5=({model:e,view:t,display:n,fields:r,filter:i,orderBy:a,limit:s})=>{let c=oS(e,t,n),l=cS(e,t,n),u=MT(YS(e.name),`update`)&&!e.fields[n.by]?.readOnly,{moves:d,move:f}=u_e(e,n.by),[p,m]=(0,o.useState)(),h=(0,o.useRef)(!1),g=Zg(Xg(F_,{activationConstraint:{distance:4}}),Xg(L_,{activationConstraint:{delay:250,tolerance:5}}),Xg(D_,{keyboardCodes:{start:[`Space`],cancel:[`Escape`],end:[`Space`,`Enter`]},coordinateGetter:o_e})),_=e=>String(e.labels[l.title]??e.record[l.title]??e.key),v=e=>c.find(t=>Z8(t.value)===e),y=e=>e.record[n.by]??null;return(0,V.jsxs)(kv,{sensors:g,collisionDetection:Q8,onDragStart:({active:e})=>{h.current=!0,m(e.data.current.row)},onDragEnd:({active:e,over:t})=>{m(void 0),setTimeout(()=>h.current=!1);let n=e.data.current.row,r=t?v(t.id):void 0;r&&r.value!==y(n)&&f(n,r)},onDragCancel:()=>{m(void 0),setTimeout(()=>h.current=!1)},accessibility:{announcements:{onDragStart:({active:e})=>`Picked up ${_(e.data.current.row)}.`,onDragOver:({active:e,over:t})=>`${_(e.data.current.row)} is over ${t?v(t.id)?.label:`no column`}.`,onDragEnd:({active:e,over:t})=>t?`${_(e.data.current.row)} was moved to ${v(t.id)?.label}.`:`${_(e.data.current.row)} was put back.`,onDragCancel:({active:e})=>`Moving ${_(e.data.current.row)} was cancelled.`},screenReaderInstructions:{draggable:`To move a card to another column, press Space, move it with the left and right arrow keys, and press Space again to drop it there. Escape puts it back.`}},children:[(0,V.jsx)(`div`,{className:`min-w-0 flex-1 overflow-x-auto`,children:(0,V.jsx)(`div`,{className:`flex snap-x items-start gap-3 pb-2`,children:c.map(o=>(0,V.jsx)(c_e,{model:e,view:t,display:n,column:o,fields:r,filter:i,orderBy:a,limit:s,moves:d,movable:u,dragged:()=>h.current},Z8(o.value)))})}),(0,V.jsx)(Yv,{children:p&&(0,V.jsx)(B8,{model:e,view:t,display:l,row:p,swipe:!1})})]})},t5=864e5,n5=e=>new Date(e).toISOString().slice(0,10),r5=e=>Date.parse(`${e}T00:00:00Z`),i5=(e,t)=>n5(r5(e)+t*t5),a5=e=>i5(e,-((new Date(r5(e)).getUTCDay()+6)%7)),o5=(e,t=0)=>{let n=new Date(r5(e));return n5(Date.UTC(n.getUTCFullYear(),n.getUTCMonth()+t,1))},s5=({scale:e,day:t})=>({scale:e,day:e===`month`?o5(t):a5(t)}),c5=(e,t,n=Wd())=>s5(e??{scale:`month`,day:Xd(t,n)}),l5=(e,t,n=Wd())=>s5({scale:e,day:Xd(t,n)}),u5=(e,t)=>e.scale===`month`?{scale:`month`,day:o5(e.day,t)}:{scale:`week`,day:i5(a5(e.day),7*t)},d5=e=>{let t=a5(e.scale===`month`?o5(e.day):e.day),n=(r5(e.scale===`month`?i5(a5(i5(o5(e.day,1),-1)),6):i5(t,6))-r5(t))/t5+1;return Array.from({length:n},(e,n)=>i5(t,n))},d_e=e=>{let t=d5(e);return{from:t[0],to:i5(t.at(-1),1)}},f5=(e,t)=>t.fields[e.start]?.type===`timestamp`,f_e=(e,t,n,r=Wd())=>{let i=f5(e,t),a=e=>new Date(Qd(e,r)).toISOString().replace(`.000Z`,`Z`),o=e=>i?{kind:`timestamp`,value:a(e),span:{start:0,end:0}}:{kind:`string`,value:e,span:{start:0,end:0}},s=lo.and(lo.gte(e.start,o(n.from)),lo.lt(e.start,o(n.to)));if(e.end===void 0)return qa(s);let c=i?lo.gt(e.end,o(n.from)):lo.gte(e.end,o(n.from));return qa(lo.or(s,lo.and(lo.lt(e.start,o(n.from)),c)))},p_e=(e,t)=>e===``?t:`(${e}) AND (${t})`,p5=e=>{if(typeof e!=`string`)return;let t=Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e);return Number.isNaN(t)?void 0:t},m_e=(e,t,n,r,i=Wd())=>{let a=p5(e[t.start]);if(a===void 0)return[];let o=f5(t,n),s=e=>o?Xd(e,i):n5(e),c=s(a),l=t.end===void 0?void 0:p5(e[t.end]),u=l===void 0?c:s(o?l-1:l),d=u<c?c:u;return r.filter(e=>e>=c&&e<=d)},h_e=(e,t,n,r,i=Wd())=>{let a=new Map(r.map(e=>[e,[]])),o=e.toSorted((e,n)=>(p5(e.record[t.start])??0)-(p5(n.record[t.start])??0));for(let e of o)for(let o of m_e(e.record,t,n,r,i))a.get(o).push(e);return a},g_e=(e,t,n,r,i,a=Wd())=>{let o=(r5(i)-r5(r))/t5,s=f5(t,n),c=e=>{let t=p5(e);if(t!==void 0)return s?new Date(Zd(t+Jd(t,a)+o*t5,a)).toISOString():i5(n5(t),o)},l=c(e[t.start]),u=t.end===void 0?void 0:c(e[t.end]);return{...l!==void 0&&{[t.start]:l},...u!==void 0&&{[t.end]:u}}},__e=e=>{let t=d5(e),n=e=>Date.parse(`${e}T00:00:00Z`);return e.scale===`month`?ff(n(e.day)):hf(n(t[0]),n(t.at(-1)))},v_e=({view:e,now:t,linkTo:n,onView:r})=>{let i=(e,t,i,a,o)=>n?(0,V.jsx)(ZS,{to:n(e),className:t,"aria-label":i,"aria-current":o?`page`:void 0,children:a}):(0,V.jsx)(`button`,{type:`button`,className:t,"aria-label":i,"aria-pressed":o,onClick:()=>r?.(e),children:a}),a=e.scale===`month`&&Xd(t,Wd()).startsWith(e.day.slice(0,7)),o=n=>n===`week`&&a?l5(`week`,t):c5({scale:n,day:e.day},t),s=(t,n)=>i(o(t),Nu.option(e.scale===t),n,n,e.scale===t),c=e.scale===`month`?`month`:`week`,l=Cf({variant:`secondary`,size:`sm`});return(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,V.jsx)(`h2`,{className:`text-sm font-medium`,children:__e(e)}),(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-1`,children:[i(u5(e,-1),l,`Previous ${c}`,(0,V.jsx)(be,{className:`size-3.5`})),i(l5(e.scale,t),l,`Today`,`Today`),i(u5(e,1),l,`Next ${c}`,(0,V.jsx)(Se,{className:`size-3.5`}))]}),(0,V.jsxs)(`span`,{role:`group`,"aria-label":`Calendar scale`,className:Nu.group(),children:[s(`month`,`Month`),s(`week`,`Week`)]})]})]})},y_e=`day:`,m5=e=>`${y_e}${e}`,b_e=(e,t)=>`${e}@${t}`,x_e=(e,{context:{active:t,collisionRect:n,droppableRects:r,over:i}})=>{let a={ArrowLeft:-1,ArrowRight:1,ArrowUp:-7,ArrowDown:7}[e.code],o=i?String(i.id).slice(4):t?.data.current?.day;if(a===void 0||!n||o===void 0)return;e.preventDefault();let s=r.get(m5(i5(o,a)));if(s)return{x:s.left+(s.width-n.width)/2,y:s.top+4}},S_e=({day:e,count:t,children:n,more:r,inMonth:i,today:a,week:o})=>{let{setNodeRef:s,isOver:c}=Lv({id:m5(e)}),l=Date.parse(`${e}T00:00:00Z`);return(0,V.jsxs)(`section`,{ref:s,"aria-label":`${mf(l)}, ${t}`,className:B(`flex min-w-0 flex-col gap-1 bg-background p-1`,o?`min-h-28 sm:min-h-64`:`min-h-24`,!i&&`bg-surface`,c&&`ring-2 ring-inset ring-primary/30`),children:[(0,V.jsxs)(`header`,{className:B(`flex items-center gap-1 px-0.5 text-xs`,i?`text-foreground`:`text-muted-foreground`),children:[o&&(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:pf(l)}),(0,V.jsx)(`span`,{"aria-current":a?`date`:void 0,className:B(`inline-flex size-5 items-center justify-center rounded-full tabular-nums`,a&&`bg-primary font-medium text-primary-foreground`),children:Number(e.slice(8))})]}),n,r]})},h5=(e,t,n,r)=>{let i=n.title??Fx(e,t),a=e.fields[i],o=r.labels[i]??(a?eS(a,r.record[i],t?.fields[i]):``);return o===``?r.key:o},C_e=(e,t,n,r)=>{let i=n.record[t.start];if(e.fields[t.start]?.type!==`timestamp`||typeof i!=`string`)return;let a=Date.parse(i);return Xd(a,Wd())===r?gf(a):void 0},g5=({model:e,view:t,display:n,row:r,day:i})=>{let a=v8(e),o=C_e(e,n,r,i);return(0,V.jsxs)(ZS,{to:{kind:`record`,resource:e.name,key:r.key},onClick:()=>a(r.record),className:`flex min-w-0 items-baseline gap-1 rounded-md border border-border bg-background px-1.5 py-0.5 text-xs hover:border-border-strong hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,children:[o&&(0,V.jsx)(`span`,{className:`shrink-0 tabular-nums text-muted-foreground`,children:o}),(0,V.jsx)(`span`,{className:`min-w-0 truncate`,children:h5(e,t,n,r)})]})},w_e=({movable:e,dragged:t,...n})=>{let{setNodeRef:r,setActivatorNodeRef:i,listeners:a,isDragging:o}=Nv({id:b_e(n.row.key,n.day),data:{row:n.row,day:n.day},disabled:!e});return(0,V.jsx)(`div`,{ref:e=>{r(e),i(e?.querySelector(`a`)??e)},...a,onDragStart:e=>e.preventDefault(),onClickCapture:e=>{t()&&(e.preventDefault(),e.stopPropagation())},className:B(`min-w-0`,e&&`cursor-grab touch-manipulation`,o&&`opacity-40`),children:(0,V.jsx)(g5,{...n})})},T_e=({model:e,display:t,range:n,fields:r,filter:i})=>{let{resources:a,views:s}=J(),c=k6({resources:a,views:s,model:e,columns:r,filter:p_e(i,f_e(t,e,n)),orderBy:`${t.start} asc`}),l=$8(e,c.page,c.key,!0),u=l.more&&!l.loading&&l.rows.length<500;(0,o.useEffect)(()=>{u&&l.loadMore()},[u,l.rows.length]);let d=l.rows.length>500||l.rows.length===500&&l.more;return{rows:l.rows.slice(0,500),capped:d,loading:l.loading,error:l.error}},E_e=(e,t)=>{let n=new Map(t.map(e=>[e.key,e.patch]));return e.map(e=>n.has(e.key)?{...e,record:{...e.record,...n.get(e.key)}}:e)},D_e=(e,t)=>{let n=G(),r=Qy(),i=qT(),[a,s]=(0,o.useState)([]),c=e=>s(t=>t.filter(t=>t.key!==e)),l=hh({mutationFn:({row:t,patch:r})=>{let i=typeof t.record.etag==`string`?t.record.etag:`*`;return n.update(e.name,zx(e,t.record),r,i)},onMutate:({row:e,patch:t})=>s(n=>[...n.filter(t=>t.key!==e.key),{key:e.key,patch:t}]),onError:(e,{row:t,to:n})=>{c(t.key),r.show({state:`error`,title:`Could not move it to ${sf(Date.parse(`${n}T00:00:00Z`))}`,description:lS(e)})},onSettled:async(t,n,{row:r})=>{await i(e.name),c(r.key)}});return{moves:a,move:(n,r,i)=>l.mutate({row:n,patch:g_e(n.record,t,e,r,i),to:i})}},O_e=3,_5=({model:e,view:t,display:n,fields:r,filter:i,at:a,linkTo:s,now:c=Date.now()})=>{let[l,u]=(0,o.useState)(),d=c5(s?a:l,c),f=d5(d),p=T_e({model:e,display:n,range:d_e(d),fields:r,filter:i}),{moves:m,move:h}=D_e(e,n),g=h_e(E_e(p.rows,m),n,e,f),_=MT(YS(e.name),`update`)&&[n.start,n.end].every(t=>t===void 0||!e.fields[t]?.readOnly),[v,y]=(0,o.useState)(),b=(0,o.useRef)(!1),x=Zg(Xg(F_,{activationConstraint:{distance:4}}),Xg(L_,{activationConstraint:{delay:250,tolerance:5}}),Xg(D_,{keyboardCodes:{start:[`Space`],cancel:[`Escape`],end:[`Space`,`Enter`]},coordinateGetter:x_e})),S=Xd(c,Wd()),C=d.scale===`week`,w=e=>sf(Date.parse(`${String(e).slice(m5(``).length)}T00:00:00Z`)),T=r=>h5(e,t,n,r.row),E={onDragStart:({active:e})=>`Picked up ${T(e.data.current)}.`,onDragOver:({active:e,over:t})=>`${T(e.data.current)} is over ${t?w(t.id):`no day`}.`,onDragEnd:({active:e,over:t})=>t?`${T(e.data.current)} was moved to ${w(t.id)}.`:`${T(e.data.current)} was put back.`,onDragCancel:({active:e})=>`Moving ${T(e.data.current)} was cancelled.`},D=()=>{y(void 0),setTimeout(()=>b.current=!1)},O=({active:e})=>{b.current=!0,y(e.data.current)},k=({active:e,over:t})=>{D();let{row:n,day:r}=e.data.current,i=t?String(t.id).slice(m5(``).length):void 0;i&&i!==r&&h(n,r,i)},A=(e,t)=>{let n=c5({scale:`week`,day:e},c),r=`+${t} more`,i=`self-start rounded px-1 text-xs text-muted-foreground hover:text-foreground focus-visible:outline-2 focus-visible:outline-primary`;return s?(0,V.jsx)(ZS,{to:s(n),className:i,children:r}):(0,V.jsx)(`button`,{type:`button`,className:i,onClick:()=>u(n),children:r})};return(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-3`,children:[(0,V.jsx)(v_e,{view:d,now:c,linkTo:s,onView:u}),p.error&&(0,V.jsx)(ax,{title:`Could not load rows`,error:p.error}),p.capped&&(0,V.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Showing the first `,500,` records of this `,d.scale,`. Narrow the filter to see the rest.`]}),(0,V.jsxs)(kv,{sensors:x,collisionDetection:Q8,onDragStart:O,onDragEnd:k,onDragCancel:D,accessibility:{announcements:E,screenReaderInstructions:{draggable:`To move an event to another day, press Space, move it a day with the left and right arrow keys or a week with the up and down arrow keys, and press Space again to drop it there. Escape puts it back.`}},children:[(0,V.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-border`,children:[!C&&(0,V.jsx)(`div`,{"aria-hidden":!0,className:`grid grid-cols-7 gap-px border-b border-border bg-border`,children:f.slice(0,7).map(e=>(0,V.jsx)(`span`,{className:`bg-surface px-1.5 py-1 text-xs font-medium text-muted-foreground`,children:pf(Date.parse(`${e}T00:00:00Z`))},e))}),(0,V.jsx)(`div`,{className:B(`grid gap-px bg-border`,C?`grid-cols-1 sm:grid-cols-7`:`grid-cols-7`),children:f.map(r=>{let i=g.get(r),a=C?i:i.slice(0,O_e);return(0,V.jsx)(S_e,{day:r,count:i.length,inMonth:C||r.startsWith(d.day.slice(0,7)),today:r===S,week:C,more:a.length<i.length&&A(r,i.length-a.length),children:p.loading?(0,V.jsx)(cu,{className:`h-4`}):a.map(i=>(0,V.jsx)(w_e,{model:e,view:t,display:n,row:i,day:r,movable:_&&NT(i.record,`update`),dragged:()=>b.current},i.key))},r)})})]}),(0,V.jsx)(Yv,{children:v&&(0,V.jsx)(g5,{model:e,view:t,display:n,row:v.row,day:v.day})})]})]})},k_e=({list:e,empty:t,loading:n,children:r})=>(0,V.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:e.loading?n:e.error?(0,V.jsx)(ax,{title:`Could not load rows`,error:e.error}):e.rows.length===0?(0,V.jsx)(`p`,{className:`py-8 text-center text-muted-foreground`,children:t}):r}),A_e=({list:e})=>(0,V.jsxs)(`div`,{className:`flex items-center justify-between gap-3 py-3 text-xs text-muted-foreground`,children:[(0,V.jsxs)(`span`,{children:[e.rows.length.toLocaleString(`en-IE`),` of `,e.total.toLocaleString(`en-IE`)]}),e.more&&(0,V.jsx)(U,{size:`sm`,onClick:e.loadMore,children:`Show more`})]}),v5=`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,j_e=`flex snap-x snap-mandatory gap-3 overflow-x-auto pb-1`,M_e=({model:e,view:t,display:n,list:r,row:i=!1,footer:a=!0})=>{let o=(t?.names?.plural??K(e.name)).toLowerCase();return(0,V.jsxs)(k_e,{list:r,empty:`No ${o} match.`,loading:(0,V.jsx)(`div`,{className:v5,children:Array.from({length:6},(e,t)=>(0,V.jsx)(cu,{className:`h-24`},t))}),children:[(0,V.jsx)(`ul`,{className:i?j_e:v5,"aria-label":t?.names?.plural??K(e.name),children:r.rows.map(r=>(0,V.jsx)(`li`,{className:B(i&&`w-64 shrink-0 snap-start`),children:(0,V.jsx)(B8,{model:e,view:t,display:n,row:r,swipe:!i})},r.key))}),a&&(0,V.jsx)(A_e,{list:r})]})},y5=(0,o.createContext)(void 0),N_e=({value:e,children:t})=>(0,V.jsx)(y5.Provider,{value:e,children:t}),P_e=()=>{let e=(0,o.useContext)(y5);if(!e)throw Error(`useListDisplay is used inside a list display, which the list page draws`);return e},F_e=()=>(0,o.useContext)(y5),b5=({display:e,list:t})=>{let{components:n}=SC(),r=n?.[e.component];return r?(0,V.jsx)(N_e,{value:t,children:(0,V.jsx)(`div`,{className:`min-w-0 flex-1 overflow-x-auto`,children:(0,V.jsx)(Qh,{name:e.component,children:(0,V.jsx)(r,{...bo(e.props??{})})})})}):(0,V.jsxs)(Zh,{children:[`No component is registered as `,e.component,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]})},x5=co(),I_e={bounds:{south:-90,west:-180,north:90,east:180},zoom:0},L_e=22,S5=e=>Math.floor(e*1e6)/1e6,C5=e=>Math.ceil(e*1e6)/1e6,w5=e=>((e+180)%360+360)%360-180,R_e=(e,t)=>{let n=[x5.gte(e.latitude,S5(Math.max(t.south,-90))),x5.lte(e.latitude,C5(Math.min(t.north,90)))];if(t.east-t.west>=360)return x5.and(...n);let r=x5.gte(e.longitude,S5(w5(t.west))),i=x5.lte(e.longitude,C5(w5(t.east)));return w5(t.west)<=w5(t.east)?x5.and(...n,r,i):x5.and(...n,x5.or(r,i))},z_e=(e,t,n)=>{let r=qa(R_e(t,n));return e.trim()===``?r:`(${e}) AND ${r}`},B_e=e=>Math.min(Math.max(Math.floor(e),0),L_e),V_e=(e,t)=>{let n=[...e.map(e=>({south:e.latitude,west:e.longitude,north:e.latitude,east:e.longitude})),...t.map(e=>e.bounds)];if(n.length!==0)return{south:Math.min(...n.map(e=>e.south)),west:Math.min(...n.map(e=>e.west)),north:Math.max(...n.map(e=>e.north)),east:Math.max(...n.map(e=>e.east))}},T5=e=>{if(typeof e==`number`)return e;if(typeof e==`string`&&e.trim()!==``)return Number(e)},E5=(e,t)=>{let n=T5(e[t.latitude]),r=T5(e[t.longitude]);if(n!==void 0&&r!==void 0&&Math.abs(n)<=90&&Math.abs(r)<=180)return{latitude:n,longitude:r}},H_e=6371008.8,D5=64,O5=(e,t)=>t.approximate===void 0?t.exact!==void 0&&e[t.exact]===!1:e[t.approximate]===!0,k5=(e,t)=>{let n=t/H_e,r=e.latitude*Math.PI/180,i=e.longitude*Math.PI/180;return{type:`Polygon`,coordinates:[Array.from({length:65},(e,t)=>{let a=t%D5/D5*2*Math.PI,o=Math.asin(Math.sin(r)*Math.cos(n)+Math.cos(r)*Math.sin(n)*Math.cos(a));return[(i+Math.atan2(Math.sin(a)*Math.sin(n)*Math.cos(r),Math.cos(n)-Math.sin(r)*Math.sin(o)))*180/Math.PI,o*180/Math.PI]})]}},U_e=e=>Array.isArray(e)&&e.length>=2&&typeof e[0]==`number`&&typeof e[1]==`number`&&Math.abs(e[0])<=180&&Math.abs(e[1])<=90,A5=(e,t)=>Array.isArray(e)&&e.length>=t&&e.every(U_e),j5=e=>Array.isArray(e)&&e.length>0&&e.every(e=>A5(e,4)),W_e=e=>Array.isArray(e)&&e.length>0&&e.every(e=>A5(e,2)),G_e=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch(e){if(e instanceof SyntaxError)return;throw e}},K_e=e=>{let t=G_e(e);if(typeof t!=`object`||!t)return;let n=t.type===`Feature`?t.geometry:t;if(typeof n!=`object`||!n)return;let{type:r,coordinates:i}=n;if(r===`Polygon`&&j5(i)||r===`MultiPolygon`&&Array.isArray(i)&&i.length>0&&i.every(j5)||r===`LineString`&&A5(i,2)||r===`MultiLineString`&&W_e(i))return{type:r,coordinates:i}},q_e=(e,t,n)=>{if(!O5(e,t))return;let r=t.area===void 0?void 0:K_e(e[t.area]);if(r)return r;let i=t.radius===void 0?void 0:T5(e[t.radius]);return i!==void 0&&Number.isFinite(i)&&i>0?k5(n,i):t.defaultRadius===void 0?void 0:k5(n,t.defaultRadius)},M5=(e,t)=>e.flatMap(e=>{let n=E5(e.record,t);if(!n)return[];if(!O5(e.record,t))return[{key:e.key,...n}];let r=q_e(e.record,t,n);return[{key:e.key,...n,approximate:!0,...r&&{area:r}}]}),J_e=(e,t)=>{let n=[];for(let r of e){let e=n.find(e=>Math.hypot(e.at.x-r.x,e.at.y-r.y)<=t);e?e.keys.push(r.key):n.push({at:r,keys:[r.key]})}return n.map(e=>({keys:e.keys,at:e.at.key}))},Y_e=(e,t)=>{if(!e)return;let n=new Set(t.map(e=>e.key)),r=e.keys.filter(e=>n.has(e));if(r.length===0)return;let i=r.indexOf(e.keys[e.index]);return{keys:r,index:Math.max(i,0)}},N5=(e,t)=>({keys:e.keys,index:((e.index+t)%e.keys.length+e.keys.length)%e.keys.length}),X_e=({model:e,display:t,fields:n,filter:r,orderBy:i,area:a})=>{let o=G(),{resources:s,views:c}=J(),l={latitude:t.latitude,longitude:t.longitude},u=a?z_e(r,l,a.bounds):``,d=a?B_e(a.zoom):0;return mh({queryKey:W.map(e.name,`${l.latitude},${l.longitude}`,d,u,i),enabled:a!==void 0,placeholderData:hm,queryFn:async()=>{let t=await o.map(e.name,{...l,zoom:d,filter:u,orderBy:i,labels:u4(s,c,e,n),photos:rS(c[e.name])});return{rows:d4(s,e,n,iS(e,t.items,t.photos),t.labels).map(t=>AS(e,t)),buckets:t.buckets,total:t.totalSize}}})},Z_e=(0,o.lazy)(()=>qh(()=>import(`./records-map-Ci3qFCDs.js`).then(e=>({default:e.RecordsMap})),__vite__mapDeps([4,1,2,5,6,3,7]))),Q_e=250,P5=`flex size-8 items-center justify-center rounded-full border border-border bg-background hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,F5=({model:e,view:t,display:n,filter:r,orderBy:i,fields:a,at:s,onMove:c,footer:l=!0,flush:u=!1})=>{let d=J().maps,f=d?.style,[p,m]=(0,o.useState)(),[h,g]=(0,o.useState)(),_=K6(h,Q_e),[v,y]=(0,o.useState)(s===void 0),b=X_e({model:e,display:n,fields:a,filter:r,orderBy:i,area:v?I_e:_}),x=b.isPlaceholderData?void 0:b.data,S=b.data?.rows??[],C=b.data?.buckets??[],w=M5(S,n),T=v&&x?V_e(M5(x.rows,n),x.buckets):void 0,E=TS(t,n),D=(t?.names?.plural??K(e.name)).toLowerCase(),O=(t?.names?.singular??K(e.name)).toLowerCase(),k=Y_e(p,S),A=k&&S.find(e=>e.key===k.keys[k.index]),j=new Set(w.filter(e=>e.approximate).map(e=>e.key)),M=e=>{let t=e.filter(e=>j.has(e)).length;return e.length===1?t===1?`Show the ${O}, at an approximate position`:`Show the ${O}`:t===0?`Show ${e.length} ${D}`:t===e.length?`Show ${e.length} ${D}, at approximate positions`:`Show ${e.length} ${D}, ${t} at approximate positions`},N=e=>`Zoom in on ${e.toLocaleString(`en-IE`)} ${e===1?O:D}`,ee=(0,o.useRef)(null),[P,te]=(0,o.useState)(0);if((0,o.useLayoutEffect)(()=>te(ee.current?.offsetHeight??0),[A?.key]),!f)return(0,V.jsx)(Zh,{children:`The map display needs a map style: set PROTOBASE_MAP_STYLE_URL.`});let F=x?.total===0;return(0,V.jsxs)(`div`,{className:B(`flex h-full min-h-[36rem] flex-1 flex-col sm:min-h-[28rem]`,u&&`max-md:-mx-5 max-md:-mb-4 max-md:min-h-0`),children:[(0,V.jsxs)(`div`,{className:B(`relative min-h-0 flex-1 overflow-hidden rounded-lg border border-border bg-muted`,u&&`max-md:rounded-none max-md:border-0`),children:[(0,V.jsx)(o.Suspense,{fallback:null,children:(0,V.jsx)(Z_e,{style:f,layers:d?.layers,initial:s,points:w,buckets:C,fit:T,onFitted:()=>y(!1),onMove:(e,t)=>{g(e),c?.(t)},selected:k?.keys,covered:k?P:0,onSelect:e=>m({keys:e,index:0}),onClear:()=>m(void 0),markerLabel:M,bucketLabel:N})}),b.error&&(0,V.jsx)(`div`,{className:`absolute inset-x-3 top-3 z-10`,children:(0,V.jsx)(ax,{title:`Could not load rows`,error:b.error})}),F&&(0,V.jsx)(`div`,{className:`pointer-events-none absolute inset-x-3 top-3 z-10 flex justify-center`,children:(0,V.jsxs)(`p`,{className:`pointer-events-auto flex items-center gap-3 rounded-full border border-border bg-background px-4 py-1.5 text-muted-foreground shadow`,role:`status`,children:[v?`No ${D} match.`:`No ${D} in this part of the map.`,!v&&(0,V.jsx)(U,{size:`sm`,onClick:()=>y(!0),children:`Show all`})]})}),k&&A&&(0,V.jsx)(`div`,{ref:ee,className:`pointer-events-none absolute inset-x-3 bottom-3 z-10 flex justify-center`,children:(0,V.jsxs)(`div`,{className:`pointer-events-auto flex w-full max-w-[16rem] flex-col gap-2 sm:max-w-xs`,role:`group`,"aria-label":`Chosen ${O}`,children:[(0,V.jsxs)(`div`,{className:`flex items-center justify-end gap-1.5`,children:[j.has(A.key)&&(0,V.jsxs)(`span`,{className:`mr-auto flex items-center gap-1 rounded-full border border-border bg-background px-2 py-1 text-xs`,children:[(0,V.jsx)(Ae,{className:`size-3.5`,"aria-hidden":!0}),`Approximate position`]}),k.keys.length>1&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":`Previous`,className:P5,onClick:()=>m(N5(k,-1)),children:(0,V.jsx)(be,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsxs)(`span`,{className:`rounded-full border border-border bg-background px-2 py-1 text-xs tabular-nums`,"aria-live":`polite`,children:[k.index+1,` / `,k.keys.length]}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Next`,className:P5,onClick:()=>m(N5(k,1)),children:(0,V.jsx)(Se,{className:`size-4`,"aria-hidden":!0})})]}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Close`,className:P5,onClick:()=>m(void 0),children:(0,V.jsx)($n,{className:`size-4`,"aria-hidden":!0})})]}),(0,V.jsx)(`div`,{className:`shadow-lg`,children:(0,V.jsx)(B8,{model:e,view:t,display:E,row:A})})]})})]}),l&&(0,V.jsx)(`p`,{className:`hidden py-3 text-xs text-muted-foreground md:block`,children:$_e(b.data,D)})]})},$_e=(e,t)=>{if(!e)return`\xA0`;let n=e.total.toLocaleString(`en-IE`);return e.buckets.length===0&&e.rows.length<e.total?`${e.rows.length.toLocaleString(`en-IE`)} of ${n} ${t} in view`:`${n} ${t} in view`},I5=(e,t,n)=>{if(n!==0){if(e===`Home`)return 0;if(e===`End`)return n-1;if(e===`ArrowDown`)return t<0?0:(t+1)%n;if(e===`ArrowUp`)return t<0?n-1:(t-1+n)%n}},L5=({value:e,options:t,onChange:n,label:r})=>{let[i,a]=(0,o.useState)(!1),s=(0,o.useRef)(null),c=(0,o.useRef)(null),l=(0,o.useRef)([]),u=t.findIndex(t=>t.value===e),d=t[u];(0,o.useEffect)(()=>{if(!i)return;l.current[Math.max(u,0)]?.focus();let e=e=>{e.target instanceof Node&&!s.current?.contains(e.target)&&a(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[i]);let f=()=>{a(!1),c.current?.focus()};return(0,V.jsxs)(`div`,{ref:s,className:`relative shrink-0`,children:[(0,V.jsxs)(`button`,{ref:c,type:`button`,"aria-label":d?`${r}: ${d.label}`:r,"aria-haspopup":`menu`,"aria-expanded":i,onClick:()=>a(!i),className:`inline-flex h-8 items-center gap-1.5 rounded-md border border-border-strong bg-background px-2.5 text-body font-medium shadow-sm transition-colors hover:bg-muted pointer-coarse:h-11`,children:[d?.icon&&(0,V.jsx)(d.icon,{className:`size-3.5`}),d?.label??r,(0,V.jsx)(ve,{className:`size-3.5 text-muted-foreground`})]}),i&&(0,V.jsx)(`ul`,{role:`menu`,"aria-label":r,onKeyDown:e=>{if(e.key===`Escape`)return f();if(e.key===`Tab`)return a(!1);let n=I5(e.key,l.current.indexOf(document.activeElement),t.length);n!==void 0&&(e.preventDefault(),l.current[n]?.focus())},className:`absolute right-0 top-full z-30 mt-1 min-w-40 rounded-md border bg-background py-1 text-body shadow-pop`,children:t.map((t,r)=>(0,V.jsx)(`li`,{role:`none`,children:(0,V.jsxs)(`button`,{ref:e=>{l.current[r]=e},type:`button`,role:`menuitemradio`,"aria-checked":t.value===e,onClick:()=>{f(),t.value!==e&&n(t.value)},className:B(`flex min-h-9 w-full items-center gap-2 whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted focus:bg-muted focus:outline-none pointer-coarse:min-h-11`,t.value===e&&`font-medium`),children:[t.icon?(0,V.jsx)(t.icon,{className:`size-3.5`}):(0,V.jsx)(`span`,{className:`size-3.5`}),(0,V.jsx)(`span`,{className:`flex-1`,children:t.label}),t.value===e&&(0,V.jsx)(ge,{className:`size-3.5 text-primary-text`})]})},t.value))})]})},eve={table:Nn,cards:ree,kanban:Dn,board:Ie,list:At,calendar:fe,map:iee},R5=({view:e,value:t,onChange:n,menu:r=!1,choices:i=yS(e)})=>{if(i.length<2)return null;let a=i.map(e=>({value:e.name,label:e.label,icon:e.icon===void 0?void 0:eve[e.icon]}));return r?(0,V.jsx)(L5,{label:`Display`,value:t,onChange:n,options:a}):(0,V.jsx)(Pu,{label:`Display`,size:`md`,value:t,onChange:n,options:a})},tve=[[`asc`,`ascending`],[`desc`,`descending`]],z5=({model:e,view:t,display:n,orderBy:r,onChange:i,className:a})=>{let o=MS(r),s=OS(e,t,n),c=s.includes(o.columnId)?s:[o.columnId,...s],l=e=>t?.fields[e]?.label??K(e);return(0,V.jsx)(`select`,{"aria-label":`Sort`,value:`${o.columnId} ${o.direction}`,onChange:e=>i(e.target.value),className:B(`h-8 rounded-md border border-border-strong bg-background px-2.5 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,a),children:c.flatMap(e=>tve.map(([t,n])=>(0,V.jsxs)(`option`,{value:`${e} ${t}`,children:[l(e),`, `,n]},`${e} ${t}`)))})},B5=(e,t,n,r)=>e.map(e=>{let i=t.fields[e.id],a=i&&CC(r,i,n?.fields[e.id]);return a?{...e,render:t=>(0,V.jsx)(EC,{shown:a,part:`cell`,field:i,value:t[e.id],fallback:Q3(e,e.value?e.value(t):t[e.id])})}:e}),V5=e=>e.includes(`.`),nve=({model:e,row:t,column:n})=>{let r=v4(HT(e,AS(e,t).record),n);return r.state===`loading`?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`…`}):r.state===`missing`?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`—`}):(0,V.jsx)(m4,{model:r.model,field:r.field,value:r.value})},rve=(e,t,{resources:n,views:r})=>{let i=sc(n,e.name,t),a=i.ok?i.steps.at(-1):void 0,o=a?.field.name??t;return{id:t,header:r[a?.model.name??e.name]?.fields[o]?.label??K(o),kind:`text`,width:200,render:n=>(0,V.jsx)(nve,{model:e,row:n,column:t})}},H5=(e,t,n,r)=>{let i=new Map(B5(Qx(e,t,[],n.filter(e=>!V5(e))),e,t,r.fieldTypes).map(e=>[e.id,e]));return n.flatMap(t=>V5(t)?[rve(e,t,r)]:i.get(t)??[])},ive=(e,t,n)=>{if(!(e>=t))return`The first ${e} of ${n?`about `:``}${t.toLocaleString(`en-GB`)}.`},U5=(e,t,n)=>{let r=Object.hasOwn(e.fields,t)?e.fields[t]:void 0;return r?.type===`relation`&&r.relation!==void 0&&n[r.relation.resource]?.primaryKey.length===1},ave=(e,t,n)=>{if(e.open!==void 0)return e.open!==e.field&&U5(t,e.open,n)?e.open:void 0;let r=t.primaryKey.filter(r=>r!==e.field&&r!==t.tenant&&U5(t,r,n));return r.length===1?r[0]:void 0},ove=(e,t)=>{let n=e[t],r=typeof n==`object`&&n&&`id`in n?n.id:n;return typeof r==`string`||typeof r==`number`?r:void 0},W5=(e,t)=>(t?.names?.singular??K(e.name)).toLowerCase(),sve=({model:e,view:t,opens:n,resources:r,views:i,canUpdate:a})=>{let o=t=>({kind:`record`,resource:e.name,key:zx(e,t)}),s=n&&e.fields[n]?.relation?.resource,c=s?r[s]:void 0,l=e=>{let t=n&&c?ove(e,n):void 0;return c&&t!==void 0?{kind:`record`,resource:c.name,key:t}:void 0},u=e=>l(e)??o(e),d=W5(e,t);return{address:u,actions:t=>{let n={label:`Open ${d}`,link:e=>t(o(e))};if(!c)return[n];let r=e=>a&&NT(e,`update`);return[{label:`Open ${W5(c,i[c.name])}`,available:e=>l(e)!==void 0,link:e=>t(l(e))},{label:`Edit ${d}`,available:r,link:n=>t({kind:`record`,resource:e.name,key:zx(e,n),edit:!0})},{...n,available:e=>!r(e)}]}}},cve=({model:e,filter:t,orderBy:n,limit:r,fields:i})=>{let a=G(),{resources:o,views:s}=J();return mh({queryKey:[...W.list(e.name,t,n,r,`embedded`),i.join(`,`)],placeholderData:hm,queryFn:async()=>{let c=u4(o,s,e,i),l=rS(s[e.name]),u=await a.search(e.name,{filter:t||void 0,orderBy:n||void 0,pageSize:r,count:`exact`,labels:c,photos:l}),d=d4(o,e,i,iS(e,u.items,u.photos),u.labels).map((t,n)=>({...t,id:Rx(e,u.items[n])}));return u.nextPageToken===``?{rows:d,total:d.length,estimated:!1}:{rows:d,total:u.totalSize??u.totalSizeEstimate,estimated:u.totalSize===void 0}}})},G5=({view:e,value:t,onChange:n})=>(0,V.jsx)(R5,{view:e,value:t,onChange:n,menu:!Kl()}),lve=()=>(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-4 w-full`},t))}),K5=({model:e,view:t,filter:n,sort:r,columns:i,limit:a,display:s,empty:c,row:l=!1,viewAll:u,link:d=!0,opens:f})=>{let{resources:p,views:m}=J(),h=MT(YS(e.name),`update`),{fields:g}=SC(),{go:_,href:v}=XS(),y=ql(),[b,x]=(0,o.useState)(r||jS(e,t)),S=i??Zx(e,t),C=(0,o.useMemo)(()=>H5(e,t,S,{resources:p,views:m,fieldTypes:g}),[e,t,S.join(`,`),p,m,g]),T=(0,o.useMemo)(()=>DS(e,t,C.map(e=>e.id)),[e,t,C]),E=cve({model:e,filter:n,orderBy:b,limit:a,fields:T}),D=E.data?.rows,O=(0,o.useMemo)(()=>D&&{total:D.length,rowAt:e=>D[e]},[D]),k=_S(t,s),A=t?.names?.plural??K(e.name),j=d&&(0,V.jsxs)(ZS,{to:A6(e,t,y,u?{filter:u.filter,orderBy:jS(e,t),display:s,savedSearch:u.savedSearch}:{filter:n,orderBy:b,display:s}),onClick:u?.onOpen,className:`flex items-center gap-1 self-end font-medium text-primary-text hover:underline`,children:[u?u.label:(0,V.jsxs)(V.Fragment,{children:[`View all `,(0,V.jsx)(`span`,{className:`sr-only`,children:A.toLowerCase()})]}),(0,V.jsx)(w,{className:`size-3.5`,"aria-hidden":!0})]});if(E.isPending)return(0,V.jsx)(lve,{});if(E.error)return(0,V.jsx)(ax,{title:`Could not load`,error:E.error});if(!O||O.total===0){let e=(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:c??`Nothing here yet.`});return u&&d?(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[e,j]}):e}let M={resource:e.name,rows:E.data.rows.map(t=>AS(e,t)),total:E.data.total,loading:!1,error:null,more:!1,loadMore:()=>void 0},N=sve({model:e,view:t,opens:f,resources:p,views:m,canUpdate:h}),ee=e=>({href:v(e),onFollow:()=>_(e)}),P=ive(O.total,E.data.total,E.data.estimated);return(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[k?k.kind===`cards`?(0,V.jsx)(M_e,{model:e,view:t,display:k,list:M,row:l||y,footer:!1}):k.kind===`map`?(0,V.jsx)(F5,{model:e,view:t,display:k,filter:n,orderBy:b,fields:T,footer:!1}):k.kind===`board`?(0,V.jsx)(e5,{model:e,view:t,display:k,fields:T,filter:n,orderBy:b,limit:a}):k.kind===`calendar`?(0,V.jsx)(_5,{model:e,view:t,display:k,fields:T,filter:n}):(0,V.jsx)(b5,{display:k,list:M}):(0,V.jsx)(w6,{fit:!0,columns:C,source:O,latencyMs:0,sort:MS(b),onSortChange:e=>x(NS(e)),onOpenRow:e=>_(N.address(e)),rowLink:e=>ee(N.address(e)),rowActions:N.actions(ee),rowNumbers:!1,selectable:!1}),P&&d?(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:P}),j]}):j]})},q5=(e,t,n)=>{let r=ql(),i=Hhe(t),[a,s]=(0,o.useState)(()=>Uhe(localStorage,i)),c=(0,o.useCallback)(e=>{s(e),Whe(localStorage,i,e)},[i]);return[Ghe(e,r,{picked:a,preferred:n}),c]},uve=({model:e,view:t,filter:n=``,sort:r=``,columns:i,limit:a=10,display:o,title:s,description:c,empty:l,actions:u})=>{let[d,f]=q5(t,`page:${e.name}:${s??``}:${n}`,o);return(0,V.jsx)($T,{title:s,description:c,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(G5,{view:t,value:d,onChange:f}),u]}),className:`h-full`,children:(0,V.jsx)(K5,{model:e,view:t,filter:n,sort:r,columns:i,limit:a,display:d,empty:l})})},dve={Page:Efe,Grid:yfe,Card:tE,Stat:a_e,RecordCard:kfe,Field:mfe,Table:({node:e,slots:t})=>{let n=ZT(e),{resources:r,views:i}=J(),a=r[n.resource];return a?(0,V.jsx)(uve,{...n,model:a,view:i[a.name],actions:t.actions}):null},CardRow:rE,RecordRow:t_e,Chart:cfe,Progress:Dfe,ModalForm:Tfe,Action:QT,Show:n_e,Link:bfe},J5=e=>typeof e==`string`||!e.custom&&e.type===`Link`,Y5=e=>{let t=[];for(let n of e){let e=t.at(-1);J5(n)&&e&&J5(e[0])?e.push(n):t.push([n])}return t.map((e,t)=>{let[n]=e;return J5(n)?(0,V.jsx)(`p`,{className:`leading-6`,children:e.map((e,t)=>typeof e==`string`?(0,V.jsx)(o.Fragment,{children:e},t):(0,V.jsx)(X5,{node:e},t))},t):(0,V.jsx)(X5,{node:n},t)})},fve=e=>ec(e)||Array.isArray(e)&&e.length>0&&e.every(ec),pve=e=>Object.fromEntries(Object.entries(e.props).flatMap(([e,t])=>fve(t)?[[e,(0,V.jsx)(V.Fragment,{children:Y5(Array.isArray(t)?t:[t])})]]:[])),X5=({node:e})=>{let{components:t}=SC();if(e.custom){let n=t?.[e.type];return n?(0,V.jsx)(Qh,{name:e.type,children:(0,V.jsx)(n,{...bo(e.props),children:e.children.length>0?Y5(e.children):void 0})}):(0,V.jsxs)(Zh,{children:[`No component is registered as `,e.type,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]})}let n=dve[e.type];return n?(0,V.jsx)(n,{node:e,slots:pve(e),children:Y5(e.children)}):(0,V.jsxs)(Zh,{children:[e.type,` is not a block this version of the app knows.`]})},Z5=({name:e})=>{let t=J().pages[e];return t?(0,V.jsx)(X5,{node:t.tree}):(0,V.jsxs)(KS,{title:`Not found`,children:[`There is no page called `,e,`.`]})},mve=2e3,Q5=(e,t)=>{let n=Qy(),[r,i]=(0,o.useState)(`idle`),[a,s]=(0,o.useState)(),c=(0,o.useRef)(void 0);return(0,o.useEffect)(()=>()=>clearTimeout(c.current),[]),{phase:r,message:a,run:async r=>{let a=e===`toast`?n.show({state:`loading`,title:`Saving ${t}...`}):void 0;s(void 0),e===`button`&&i(`saving`);try{return await r(),a!==void 0&&n.update(a,{state:`success`,title:`${t} saved`}),e===`button`&&(i(`saved`),c.current=setTimeout(()=>i(`idle`),mve)),!0}catch(t){if(!Rs(t))throw t;let r=t.status===412?`Changed by someone else`:`Could not save`,o=GC(t);return a!==void 0&&n.update(a,{state:`error`,title:r,description:o}),e===`button`&&(i(`idle`),s(`${r}: ${o}`)),!1}}}},$5=({title:e,eyebrow:t,submit:n,saving:r,disabled:i,error:a,errorTitle:o=`Not saved`,onSubmit:s,onCancel:c,children:l,ref:u})=>{let d=(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[c&&(0,V.jsx)(U,{className:`max-sm:min-h-11`,onClick:c,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,className:`max-sm:min-h-11 max-sm:flex-1`,loading:r,disabled:i,children:n})]}),f=a!==void 0&&(0,V.jsx)(`div`,{className:`mt-4`,children:(0,V.jsx)(ax,{title:o,error:a})}),p=(0,V.jsx)(`div`,{className:`divide-y divide-border`,children:l}),m=e=>{e.preventDefault(),s()};return e===void 0?(0,V.jsxs)(`form`,{ref:u,className:`max-w-[760px]`,onSubmit:m,children:[f,p,(0,V.jsx)(`footer`,{className:`border-t pt-6 sm:flex sm:justify-end`,children:d})]}):(0,V.jsx)(`form`,{ref:u,className:`flex-1`,onSubmit:m,children:(0,V.jsxs)(`div`,{className:`mx-auto max-w-[760px] px-4 py-6 md:px-10 md:py-8`,children:[(0,V.jsxs)(`header`,{className:`flex flex-col gap-4 border-b pb-6 sm:flex-row sm:items-end sm:justify-between sm:gap-6`,children:[(0,V.jsxs)(`div`,{children:[t&&(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:t}),(0,V.jsx)(`h1`,{className:`mt-1 text-2xl font-semibold tracking-tight`,children:e})]}),d]}),f,p]})})},hve=({noun:e,collection:t,sections:n,saving:r,message:i,onSubmit:a,onCancel:o,ref:s})=>(0,V.jsx)($5,{ref:s,title:`New ${e.toLowerCase()}`,eyebrow:t,submit:`Create ${e.toLowerCase()}`,saving:r,error:i?Error(i):void 0,errorTitle:`Not created`,onSubmit:a,onCancel:o,children:n.map(e=>(0,V.jsx)(tb,{title:e.title,help:e.help,children:(0,V.jsx)(`div`,{className:`grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2`,children:e.fields.map(e=>(0,V.jsx)(eb,{name:e.name,label:e.label,required:e.required,help:e.help,error:e.error,wide:e.wide,children:e.editor},e.name))})},e.title))}),gve=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),_ve=({resource:e,values:t})=>{let n=J(),r=n.resources[e],i=YS(e);return r?MT(i,`create`)?(0,V.jsx)(vve,{resource:e,values:t}):(0,V.jsxs)(KS,{title:`Not allowed`,children:[`You cannot create `,n.views[e]?.names?.plural.toLowerCase()??e,`.`]}):(0,V.jsxs)(KS,{title:`Not found`,children:[`There is no resource called `,e,`.`]})},vve=({resource:e,values:t})=>{let n=J(),r=n.resources[e],i=n.views[e],a=G(),s=Gp(),{go:c}=XS(),l=i?.names?.singular??K(e),u=Q5(i?.saveFeedback??`toast`,`New ${l.toLowerCase()}`),d=Jb(r,i),[f,p]=(0,o.useState)(()=>$b(r,d,t)),[m,h]=(0,o.useState)({}),[g,_]=(0,o.useState)(0),v=KC(g);(0,o.useEffect)(()=>{for(let[e,i]of Object.entries(t??{})){let t=n.resources[r.fields[e]?.relation?.resource??``];t&&c4(s,a,t,[i],n.views[t.name]).then(t=>{let n=t.get(i);n&&p(t=>Kb(t[e])&&t[e].key===i?{...t,[e]:{key:i,label:n}}:t)})}},[t,n,r,a,s]);let y=(e,t)=>{h(t=>gve(t,e)),p(n=>({...n,[e]:t}))},b=()=>u.run(async()=>{let t;try{t=await a.create(e,Xb(r,n.resources,f))}catch(e){let t=WC(e);throw h(t),Object.keys(t).length>0&&_(e=>e+1),e}for(let t of[`page`,`list`,`first-page`,`map`,`facets`,`series`])s.invalidateQueries({queryKey:[t,e]});c({kind:`record`,resource:e,key:zx(r,t.record)},{replace:!0})}),x=d.map(e=>({title:e.title,help:e.help,fields:e.fields.map(e=>{let t=r.fields[e],a=f[e],o=t.relation?n.resources[t.relation.resource]:void 0,s=i?.fields[e]?.label??K(e),c=m[e];return{name:e,label:s,help:i?.fields[e]?.help,required:Zb(t),error:c&&UC(t,s,c),wide:!!(i?.fields[e]?.multiline||i?.fields[e]?.markdown),editor:(0,V.jsx)(IC,{field:t,hints:i?.fields[e],value:Kb(a)?a.key:a??(t.type!==`boolean`&&``),stored:void 0,relationLabel:Kb(a)?a.label:void 0,placeholder:ex(t)?`Set by the database`:void 0,relationPicker:o?{target:o,view:n.views[o.name]}:void 0,invalid:!!m[e],resource:r.name,onChange:t=>y(e,t)})}})}));return(0,V.jsx)(hve,{ref:v,noun:l,collection:i?.names?.plural??K(e),sections:x,saving:u.phase===`saving`,message:u.message,onSubmit:()=>void b(),onCancel:()=>c({kind:`list`,resource:e})})},yve=({resource:e,values:t})=>{let n=J(),r=n.views[e];return r?.create?n.pages[r.create.page]?(0,V.jsx)(Z5,{name:r.create.page}):(0,V.jsxs)(KS,{title:`Not allowed`,children:[`You cannot create `,r.names?.plural.toLowerCase()??K(e),`.`]}):(0,V.jsx)(_ve,{resource:e,values:t},new URLSearchParams(t).toString())},bve=(e,t)=>{let n=new Map(t.map(e=>[e.value,e.count]));return e.map(([e,t])=>({value:e,label:t,...n.get(e)!==void 0&&{count:n.get(e)}}))},xve=(e,t)=>[...new Set(t.filter(t=>!e.includes(t)))],Sve=co(),Cve=(e,t)=>{let n=G(),[r,i]=(0,o.useState)({}),a=e=>!!e?.search?.length&&e.primaryKey.length===1,s=fh({queries:e.map(({id:e,target:i})=>{let o=(r[e]??``).trim();return{queryKey:[`reference-search`,e,i?.name??``,o],enabled:a(i)&&o!==``,placeholderData:hm,queryFn:async()=>{let e=i.primaryKey[0],r=Px(i,t[i.name]);return(await n.list(i.name,{filter:qa(Sve.search(o)),fields:[e,r],pageSize:20})).items.map(t=>[String(t[e]),String(t[r])])}}})});return e.map(({id:e,target:t},n)=>{if(!a(t))return{};let o=t=>i(n=>({...n,[e]:t}));return(r[e]??``).trim()===``?{onSearch:o}:{onSearch:o,matches:s[n]?.data??[]}})},wve=24,Tve=({model:e,resources:t,views:n,view:r,state:i,extras:a})=>{let o=G(),s=Gp(),c=f8(r,e),l=e=>r?.fields[e]?.label??K(e),u=n=>{let r=e.fields[n];return r?.type===`relation`&&r.relation?t[r.relation.resource]:void 0},d=c.facets.flatMap(e=>(e.flags?e.options.map(e=>e.value):[e.id]).map(t=>({group:e.id,field:t}))),f=fh({queries:d.map(({group:t,field:r})=>{let s=a8(c,{...i,facets:{...i.facets,[t]:[]}},a),l=u(r),d=l?.primaryKey.length===1?Px(l,n[l.name]):void 0;return{queryKey:W.facets(e.name,r,s),queryFn:()=>o.facets(e.name,r,{filter:s,limit:50,...d&&{label:d}})}})}),p=(e,t)=>f[d.findIndex(n=>n.group===e&&n.field===t)]?.data,m=fh({queries:c.facets.map(t=>{let r=u(t.id),a=xve((p(t.id,t.id)??[]).flatMap(e=>e.value===null?[]:[String(e.value)]),i.facets[t.id]??[]);return{queryKey:W.labels(`facet:${e.name}.${t.id}`,a.join(`,`)),enabled:!!r&&a.length>0,queryFn:async()=>[...await c4(s,o,r,a,n[r.name])]}})}),h=Cve(c.facets.map(e=>({id:e.id,target:e.combobox?u(e.id):void 0})),n),g=c.ranges??[],_=fh({queries:g.map(t=>{let n=a8(c,z6(i,t.id,void 0),a),s=p8(r,t.id)?wve:1;return{queryKey:W.histogram(e.name,t.id,s,n),queryFn:()=>o.histogram(e.name,t.id,{filter:n,buckets:s})}})});return{facets:c.facets.map((t,n)=>{if(t.flags){let e=t.options.map(({value:e})=>({value:e,label:l(e),count:p(t.id,e)?.find(e=>String(e.value)===`true`)?.count??0}));return{...t,options:e}}let i=e.fields[t.id],a=(p(t.id,t.id)??[]).flatMap(e=>e.label===void 0?[]:[[String(e.value),e.label]]),o=new Map([...a,...m[n]?.data??[]]),s=(p(t.id,t.id)??[]).flatMap(e=>e.value===null?[]:[{value:String(e.value),label:i?.type===`enum`?rs(String(e.value),r?.fields[t.id]?.valueLabels):o.get(String(e.value))??String(e.value),count:e.count}]),c=h[n];return{...t,label:l(t.id),options:c.matches?bve(c.matches,s):s,...o.size>0&&{labels:Object.fromEntries(o)},...c.onSearch&&{onSearch:c.onSearch}}}),ranges:g.flatMap((e,t)=>{let n=_[t]?.data;return!n||n.min===null||n.max===null?[]:[{...e,label:l(e.id),min:Math.floor(n.min),max:Math.ceil(n.max),step:Math.max(1,Math.round((n.max-n.min)/100)),histogram:p8(r,e.id)?n.buckets.map(e=>e.count):[],format:m8(r,e.id)}]}),...c.dateField&&{datePresets:c.datePresets??!0,dateField:c.dateField,dateKind:c.dateKind},toggles:c.toggles?.map(e=>({...e,label:l(e.id)}))}},Eve=co(),Dve=({blockingPlural:e,noun:t})=>`${e} still point at this ${t.toLowerCase()}.`,Ove=({blockedBy:e,resources:t,views:n,noun:r,key:i})=>{let{resource:a,field:o}=e;if(!t[a])return;let s=n[a]?.names?.plural??K(a),c=Dve({blockingPlural:s,noun:r});if(!o||i===void 0)return{text:c};let l={kind:`list`,resource:a,filter:qa(Eve.eq(o,i))};return{text:c,link:{label:`Show ${s.toLowerCase()}`,to:l}}},kve=({title:e,noun:t,busy:n,onConfirm:r,onCancel:i})=>(0,V.jsx)(wf,{title:`Delete ${e}?`,description:`This ${t.toLowerCase()} will be removed. This cannot be undone.`,onClose:i,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:i,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,loading:n,onClick:r,children:`Delete`})]})}),Ave=({title:e,changes:t,busy:n,onReview:r,onDeleteAnyway:i,onCancel:a})=>(0,V.jsx)(wf,{title:`${e} was changed since you opened it`,description:`Someone saved this record in the meantime. Review what changed before you delete it.`,onClose:a,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:r,children:`Review changes`}),(0,V.jsx)(U,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,loading:n,onClick:i,children:`Delete anyway`})]}),children:t.length===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`No visible fields differ; the record was saved again with the same values.`}):(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:t.map(e=>(0,V.jsxs)(`li`,{className:`grid grid-cols-[96px_1fr] gap-3 px-3 py-2`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:e.label}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`span`,{className:`text-muted-foreground line-through`,children:e.before}),` `,(0,V.jsx)(`span`,{className:`font-medium`,children:e.after})]})]},e.field))})}),e7=e=>{if(e.stage===`confirm`)return(0,V.jsx)(wf,{title:`Delete ${e.count} ${e.count===1?e.plural.replace(/s$/,``):e.plural.toLowerCase()}?`,description:`This cannot be undone. Each record is deleted only if it has not changed since the list loaded; anything that changed is reported and kept.`,onClose:e.onCancel,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:e.onCancel,children:`Cancel`}),(0,V.jsxs)(U,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,onClick:e.onConfirm,children:[`Delete `,e.count]})]})});if(e.stage===`running`)return(0,V.jsx)(wf,{title:`Deleting`,description:`${e.done} of ${e.total} done`,onClose:()=>void 0,actions:(0,V.jsx)(U,{loading:!0,disabled:!0,children:`Working`})});let t=e.total-e.failures.length;return(0,V.jsx)(wf,{title:e.failures.length===0?`Deleted ${t}`:`Deleted ${t} of ${e.total}`,description:e.failures.length===0?void 0:`${e.failures.length} could not be deleted and were kept.`,onClose:e.onClose,actions:(0,V.jsx)(U,{variant:`primary`,onClick:e.onClose,children:`Done`}),children:e.failures.length>0&&(0,V.jsx)(`ul`,{className:`max-h-48 divide-y overflow-y-auto rounded-md border`,children:e.failures.map(e=>(0,V.jsxs)(`li`,{className:`px-3 py-2`,children:[(0,V.jsx)(`span`,{className:`font-medium`,children:e.title}),(0,V.jsx)(`span`,{className:`block text-xs text-danger-text`,children:e.message})]},e.title))})})},jve=new Set([`updated_at`,`updatedAt`]),Mve=(e,t,n,r)=>Object.values(e.fields).flatMap(e=>{if(jve.has(e.name)||JSON.stringify(n[e.name]??null)===JSON.stringify(r[e.name]??null))return[];let i=t?.fields[e.name];return[{field:e.name,label:i?.label??K(e.name),before:eS(e,n[e.name],i),after:eS(e,r[e.name],i)}]}),Nve=4,t7=({model:e,view:t,onDeleted:n,onReview:r,restore:i})=>{let a=G(),s=Gp(),c=Qy(),[l,u]=(0,o.useState)(),[d,f]=(0,o.useState)(!1),p=t?.names?.singular??K(e.name),m=t?.names?.plural??K(e.name),{resources:h,views:g}=J(),{href:_,open:v}=XS(),y=(t,n)=>t.blockedBy&&Ove({blockedBy:t.blockedBy,resources:h,views:g,noun:p,...e.primaryKey.length===1&&{key:n.key}}),b=()=>{for(let t of[`page`,`list`,`first-page`,`map`])s.invalidateQueries({queryKey:[t,e.name]});for(let t of[`facets`,`series`,`histogram`])s.invalidateQueries({queryKey:[t,e.name]})},x=async(t,n)=>{let r=n??(await a.get(e.name,t.key)).etag;try{await a.remove(e.name,t.key,{etag:r})}catch(e){if(!(e instanceof Ls))throw e;return e}},S=t=>{b(),u(void 0),n?.(t),c.show({state:`success`,title:`${t.title} deleted`,...e.softDelete&&i&&{action:{label:`Undo`,onClick:()=>{i(t).then(()=>{b(),c.show({state:`success`,title:`${t.title} restored`})},e=>{if(!Rs(e))throw e;b(),c.show({state:e.status===409?`success`:`error`,title:e.status===409?`${t.title} is already back`:`Could not restore ${t.title}`,description:e.status===409?void 0:e.message})})}}}})},C=async(n,r)=>{f(!0);try{if(!await x(n,r))return S(n);let i=(await a.get(e.name,n.key)).record;u({kind:`conflict`,target:n,fresh:i,changes:Mve(e,t,n.snapshot,i)})}catch(e){if(!Rs(e))throw e;u(void 0);let t=y(e,n);c.show({state:`error`,title:`Could not delete ${n.title}`,description:t?.text??e.message,...t?.link&&{action:{label:t.link.label,href:_(t.link.to),onNavigate:v}}})}finally{f(!1)}},w=async e=>{try{return await x(e,e.etag)?{title:e.title,message:`Changed since the list loaded, so it was kept.`}:void 0}catch(t){if(!Rs(t))throw t;return{title:e.title,message:y(t,e)?.text??t.message}}},T=async e=>{let t=[],n=0;u({kind:`bulk-running`,done:n,total:e.length});let r=[...e];await Promise.all(Array.from({length:Math.min(Nve,e.length)},async()=>{for(let i=r.shift();i;i=r.shift()){let r=await w(i);r&&t.push(r),n+=1,u({kind:`bulk-running`,done:n,total:e.length})}})),b(),u({kind:`bulk-done`,total:e.length,failures:t})},E=()=>u(void 0);return{dialogs:l&&(0,V.jsxs)(V.Fragment,{children:[l.kind===`confirm`&&(0,V.jsx)(kve,{title:l.target.title,noun:p,busy:d,onCancel:E,onConfirm:()=>void C(l.target,l.target.etag)}),l.kind===`conflict`&&(0,V.jsx)(Ave,{title:l.target.title,changes:l.changes,busy:d,onCancel:E,onReview:()=>{E(),r?.(l.target,l.fresh)},onDeleteAnyway:()=>void C(l.target,`*`)}),l.kind===`bulk-confirm`&&(0,V.jsx)(e7,{stage:`confirm`,count:l.targets.length,plural:m,onCancel:E,onConfirm:()=>void T(l.targets)}),l.kind===`bulk-running`&&(0,V.jsx)(e7,{stage:`running`,done:l.done,total:l.total}),l.kind===`bulk-done`&&(0,V.jsx)(e7,{stage:`done`,total:l.total,failures:l.failures,onClose:E})]}),start:t=>e.softDelete?C(t,t.etag):u({kind:`confirm`,target:t}),startBulk:e=>u({kind:`bulk-confirm`,targets:e})}},n7=e=>{let t=G();return e.softDelete?async n=>void await t.undelete(e.name,n.key):void 0},r7=(e,t,n)=>e?.create?Object.hasOwn(t,e.create.page):MT(n,`create`),i7=e=>typeof e==`object`&&!!e,a7=e=>e===null||typeof e==`string`&&e.trim()===``,o7=e=>e===null?``:i7(e)?e.date.replace(`T`,` `):typeof e==`boolean`?e?`TRUE`:`FALSE`:String(e),s7=e=>e<26?String.fromCharCode(65+e):s7(Math.floor(e/26)-1)+s7(e%26),c7=(e,t)=>e[t]?.trim()?e[t]:`Column ${s7(t)}`,Pve=e=>/[",\r\n]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e,Fve=(e,t)=>{let n=[...t].sort((e,t)=>e.line-t.line).map(t=>[...e.map((e,n)=>o7(t.cells[n]??null)),String(t.line),t.problems.join(`; `)]);return`${[[...e,`Line`,`Problems`],...n].map(e=>e.map(Pve).join(`,`)).join(`\r
|
|
67
|
+
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function vde(e,t){if(e){if(typeof e==`string`)return q2(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?q2(e,t):void 0}}function q2(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function yde(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function bde(e){if(Array.isArray(e))return e}var xde=()=>(Pq(),null);function J2(e){if(typeof e==`number`)return e;if(typeof e==`string`){var t=parseFloat(e);if(!Number.isNaN(t))return t}return 0}var Sde=(0,o.forwardRef)((e,t)=>{var n=(0,o.useRef)(null),r=K2((0,o.useState)({containerWidth:J2(e.style?.width),containerHeight:J2(e.style?.height)}),2),i=r[0],a=r[1],s=(0,o.useCallback)((e,t)=>{a(n=>{var r=Math.round(e),i=Math.round(t);return n.containerWidth===r&&n.containerHeight===i?n:{containerWidth:r,containerHeight:i}})},[]),c=(0,o.useCallback)(e=>{if(typeof t==`function`&&t(e),n.current!=null&&(n.current.disconnect(),n.current=null),e!=null&&typeof ResizeObserver<`u`){var r=e.getBoundingClientRect(),i=r.width,a=r.height;s(i,a);var o=new ResizeObserver(e=>{var t=e[0];if(t!=null){var n=t.contentRect,r=n.width,i=n.height;s(r,i)}});o.observe(e),n.current=o}},[t,s]);return(0,o.useEffect)(()=>()=>{n.current?.disconnect()},[s]),o.createElement(o.Fragment,null,o.createElement(mM,{width:i.containerWidth,height:i.containerHeight}),o.createElement(`div`,G2({ref:c},e)))}),Cde=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height,i=K2((0,o.useState)({containerWidth:J2(n),containerHeight:J2(r)}),2),a=i[0],s=i[1],c=(0,o.useCallback)((e,t)=>{s(n=>{var r=Math.round(e),i=Math.round(t);return n.containerWidth===r&&n.containerHeight===i?n:{containerWidth:r,containerHeight:i}})},[]),l=(0,o.useCallback)(e=>{if(typeof t==`function`&&t(e),e!=null){var n=e.getBoundingClientRect(),r=n.width,i=n.height;c(r,i)}},[t,c]);return o.createElement(o.Fragment,null,o.createElement(mM,{width:a.containerWidth,height:a.containerHeight}),o.createElement(`div`,G2({ref:l},e)))}),wde=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height;return o.createElement(o.Fragment,null,o.createElement(mM,{width:n,height:r}),o.createElement(`div`,G2({ref:t},e)))}),Tde=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height;return typeof n==`string`||typeof r==`string`?o.createElement(Cde,G2({},e,{ref:t})):typeof n==`number`&&typeof r==`number`?o.createElement(wde,G2({},e,{width:n,height:r,ref:t})):o.createElement(o.Fragment,null,o.createElement(mM,{width:n,height:r}),o.createElement(`div`,G2({ref:t},e)))});function Ede(e){return e?Sde:Tde}var Dde=(0,o.forwardRef)((e,t)=>{var n=e.children,r=e.className,i=e.height,a=e.onClick,s=e.onContextMenu,c=e.onDoubleClick,l=e.onMouseDown,u=e.onMouseEnter,d=e.onMouseLeave,f=e.onMouseMove,p=e.onMouseUp,m=e.onTouchEnd,h=e.onTouchMove,g=e.onTouchStart,_=e.style,v=e.width,y=e.responsive,b=e.dispatchTouchEvents,x=b===void 0||b,S=(0,o.useRef)(null),C=rk(),w=K2((0,o.useState)(null),2),T=w[0],E=w[1],D=K2((0,o.useState)(null),2),O=D[0],k=D[1],A=fde(),j=iM(),M=j?.width>0?j.width:v,N=j?.height>0?j.height:i,ee=(0,o.useCallback)(e=>{A(e),typeof t==`function`&&t(e),E(e),k(e),e!=null&&(S.current=e)},[A,t,E,k]),P=(0,o.useCallback)(e=>{C(i2(e)),C(S2({handler:a,reactEvent:e}))},[C,a]),te=(0,o.useCallback)(e=>{C(o2(e)),C(S2({handler:u,reactEvent:e}))},[C,u]),F=(0,o.useCallback)(e=>{C(UW()),C(S2({handler:d,reactEvent:e}))},[C,d]),ne=(0,o.useCallback)(e=>{C(o2(e)),C(S2({handler:f,reactEvent:e}))},[C,f]),re=(0,o.useCallback)(()=>{C(h2())},[C]),ie=(0,o.useCallback)(()=>{C(g2())},[C]),I=(0,o.useCallback)(e=>{C(m2(e.key))},[C]),ae=(0,o.useCallback)(e=>{C(S2({handler:s,reactEvent:e}))},[C,s]),oe=(0,o.useCallback)(e=>{C(S2({handler:c,reactEvent:e}))},[C,c]),se=(0,o.useCallback)(e=>{C(S2({handler:l,reactEvent:e}))},[C,l]),L=(0,o.useCallback)(e=>{C(S2({handler:p,reactEvent:e}))},[C,p]),ce=(0,o.useCallback)(e=>{C(S2({handler:g,reactEvent:e}))},[C,g]),le=(0,o.useCallback)(e=>{x&&C(D2(e)),C(S2({handler:h,reactEvent:e}))},[C,x,h]),ue=(0,o.useCallback)(e=>{C(S2({handler:m,reactEvent:e}))},[C,m]),de=Ede(y);return o.createElement(cq.Provider,{value:T},o.createElement(xD.Provider,{value:O},o.createElement(de,{width:M??_?.width,height:N??_?.height,className:yE(`recharts-wrapper`,r),style:pde({position:`relative`,cursor:`default`,width:M,height:N},_),onClick:P,onContextMenu:ae,onDoubleClick:oe,onFocus:re,onBlur:ie,onKeyDown:I,onMouseDown:se,onMouseEnter:te,onMouseLeave:F,onMouseMove:ne,onMouseUp:L,onTouchEnd:ue,onTouchMove:le,onTouchStart:ce,ref:ee},o.createElement(xde,null),n)))}),Ode=[`width`,`height`,`responsive`,`children`,`className`,`style`,`compact`,`title`,`desc`];function kde(e,t){if(e==null)return{};var n,r,i=Ade(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Ade(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}var Y2=(0,o.forwardRef)((e,t)=>{var n=e.width,r=e.height,i=e.responsive,a=e.children,s=e.className,c=e.style,l=e.compact,u=e.title,d=e.desc,f=TE(kde(e,Ode));return l?o.createElement(o.Fragment,null,o.createElement(mM,{width:n,height:r}),o.createElement(H2,{otherAttributes:f,title:u,desc:d},a)):o.createElement(Dde,{className:s,style:c,width:n,height:r,responsive:i??!1,onClick:e.onClick,onMouseLeave:e.onMouseLeave,onMouseEnter:e.onMouseEnter,onMouseMove:e.onMouseMove,onMouseDown:e.onMouseDown,onMouseUp:e.onMouseUp,onContextMenu:e.onContextMenu,onDoubleClick:e.onDoubleClick,onTouchStart:e.onTouchStart,onTouchMove:e.onTouchMove,onTouchEnd:e.onTouchEnd},o.createElement(H2,{otherAttributes:f,title:u,desc:d,ref:t},o.createElement(P$,null,a)))});function X2(){return X2=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},X2.apply(null,arguments)}function Z2(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function jde(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Z2(Object(n),!0).forEach(function(t){Mde(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Z2(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Mde(e,t,n){return(t=Nde(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Nde(e){var t=Pde(e,`string`);return typeof t==`symbol`?t:t+``}function Pde(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var Fde=jde({accessibilityLayer:!0,barCategoryGap:`10%`,barGap:4,layout:`horizontal`,margin:{top:5,right:5,bottom:5,left:5},responsive:!1,reverseStackOrder:!1,stackOffset:`none`,syncMethod:`index`},N2),Q2=(0,o.forwardRef)(function(e,t){var n=hO(e.categoricalChartProps,Fde),r=e.chartName,i=e.defaultTooltipEventType,a=e.validateTooltipEventTypes,s=e.tooltipPayloadSearcher,c=e.categoricalChartProps,l={chartName:r,defaultTooltipEventType:i,validateTooltipEventTypes:a,tooltipPayloadSearcher:s,eventEmitter:void 0};return o.createElement(F2,{preloadedState:{options:l},reduxStoreName:c.id??r},o.createElement(v$,{chartData:c.data}),o.createElement(I2,{layout:n.layout,margin:n.margin}),o.createElement(R2,{throttleDelay:n.throttleDelay,throttledEvents:n.throttledEvents}),o.createElement(L2,{baseValue:n.baseValue,accessibilityLayer:n.accessibilityLayer,barCategoryGap:n.barCategoryGap,maxBarSize:n.maxBarSize,stackOffset:n.stackOffset,barGap:n.barGap,barSize:n.barSize,syncId:n.syncId,syncMethod:n.syncMethod,className:n.className,reverseStackOrder:n.reverseStackOrder}),o.createElement(Y2,X2({},n,{ref:t})))}),Ide=[`axis`],Lde=(0,o.forwardRef)((e,t)=>o.createElement(Q2,{chartName:`LineChart`,defaultTooltipEventType:`axis`,validateTooltipEventTypes:Ide,tooltipPayloadSearcher:mq,categoricalChartProps:e,ref:t})),Rde=[`axis`,`item`],$2=(0,o.forwardRef)((e,t)=>o.createElement(Q2,{chartName:`BarChart`,defaultTooltipEventType:`axis`,validateTooltipEventTypes:Rde,tooltipPayloadSearcher:mq,categoricalChartProps:e,ref:t}));function zde(e){var t=rk();return(0,o.useEffect)(()=>{t(que(e))},[t,e]),null}var Bde=[`layout`];function e4(){return e4=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},e4.apply(null,arguments)}function Vde(e,t){if(e==null)return{};var n,r,i=Hde(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function Hde(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function t4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Ude(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?t4(Object(n),!0).forEach(function(t){Wde(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):t4(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Wde(e,t,n){return(t=Gde(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Gde(e){var t=Kde(e,`string`);return typeof t==`symbol`?t:t+``}function Kde(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var n4=Ude({accessibilityLayer:!0,stackOffset:`none`,barCategoryGap:`10%`,barGap:4,margin:{top:5,right:5,bottom:5,left:5},reverseStackOrder:!1,syncMethod:`index`,layout:`radial`,responsive:!1,cx:`50%`,cy:`50%`,innerRadius:0,outerRadius:`80%`},N2),qde=(0,o.forwardRef)(function(e,t){var n=hO(e.categoricalChartProps,n4),r=n.layout,i=Vde(n,Bde),a=e.chartName,s={chartName:a,defaultTooltipEventType:e.defaultTooltipEventType,validateTooltipEventTypes:e.validateTooltipEventTypes,tooltipPayloadSearcher:e.tooltipPayloadSearcher,eventEmitter:void 0};return o.createElement(F2,{preloadedState:{options:s},reduxStoreName:n.id??a},o.createElement(v$,{chartData:n.data}),o.createElement(I2,{layout:r,margin:n.margin}),o.createElement(R2,{throttleDelay:n.throttleDelay,throttledEvents:n.throttledEvents}),o.createElement(L2,{baseValue:void 0,accessibilityLayer:n.accessibilityLayer,barCategoryGap:n.barCategoryGap,maxBarSize:n.maxBarSize,stackOffset:n.stackOffset,barGap:n.barGap,barSize:n.barSize,syncId:n.syncId,syncMethod:n.syncMethod,className:n.className,reverseStackOrder:n.reverseStackOrder}),o.createElement(zde,{cx:n.cx,cy:n.cy,startAngle:n.startAngle,endAngle:n.endAngle,innerRadius:n.innerRadius,outerRadius:n.outerRadius}),o.createElement(Y2,e4({},i,{ref:t})))});function r4(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function i4(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?r4(Object(n),!0).forEach(function(t){Jde(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r4(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function Jde(e,t,n){return(t=Yde(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Yde(e){var t=Xde(e,`string`);return typeof t==`symbol`?t:t+``}function Xde(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}var Zde=[`item`],Qde=i4(i4({},n4),{},{layout:`centric`,startAngle:0,endAngle:360}),$de=(0,o.forwardRef)((e,t)=>{var n=hO(e,Qde);return o.createElement(qde,{chartName:`PieChart`,defaultTooltipEventType:`item`,validateTooltipEventTypes:Zde,tooltipPayloadSearcher:mq,categoricalChartProps:n,ref:t})}),efe=(e,t)=>t>0?`${Math.round(e/t*100)}%`:``,tfe=({active:e,payload:t,measure:n})=>{let r=t?.[0]?.payload;return!e||!r?null:(0,V.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,V.jsx)(`div`,{className:`text-muted-foreground`,children:r.label}),(0,V.jsx)(`div`,{className:`font-semibold tabular-nums`,children:gE(r.value,n)})]})},nfe=({resource:e,slices:t,measure:n})=>{let r=t.filter(e=>e.value!==null&&e.value>0),i=r.reduce((e,t)=>e+t.value,0);return(0,V.jsxs)(`div`,{className:`flex flex-col items-center gap-4 sm:flex-row sm:items-center`,children:[(0,V.jsx)(`div`,{className:`size-36 shrink-0`,children:(0,V.jsx)(aM,{width:`100%`,height:`100%`,children:(0,V.jsxs)($de,{children:[(0,V.jsx)(hQ,{data:r,dataKey:`value`,nameKey:`label`,innerRadius:`62%`,outerRadius:`100%`,paddingAngle:+(r.length>1),stroke:`var(--background)`,strokeWidth:2,isAnimationActive:!1,children:r.map(e=>(0,V.jsx)(Qq,{fill:e.color},e.key))}),(0,V.jsx)(Zq,{content:(0,V.jsx)(tfe,{measure:n}),isAnimationActive:!1})]})})}),(0,V.jsx)(`ul`,{className:`flex w-full min-w-0 flex-col gap-0.5`,children:t.map(t=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(ZS,{to:{kind:`list`,resource:e,filter:t.filter},className:`group flex items-center gap-2 rounded-md px-1 py-0.5 hover:bg-muted`,children:[(0,V.jsx)(`span`,{className:`size-2.5 shrink-0 rounded-full`,style:{background:t.color},"aria-hidden":!0}),(0,V.jsx)(`span`,{className:`min-w-0 flex-1 truncate group-hover:text-primary-text`,children:t.label}),(0,V.jsx)(`span`,{className:`font-medium tabular-nums`,children:gE(t.value,n)}),(0,V.jsx)(`span`,{className:`w-9 text-right text-xs text-muted-foreground tabular-nums`,children:efe(t.value??0,i)})]})},t.key))})]})},rfe={hour:{hour:`2-digit`,minute:`2-digit`,hour12:!1},day:{day:`numeric`,month:`short`},week:{day:`numeric`,month:`short`},month:{month:`short`,year:`2-digit`},year:{year:`numeric`}},ife={hour:{day:`numeric`,month:`short`,hour:`2-digit`,minute:`2-digit`,hour12:!1},day:{day:`numeric`,month:`short`,year:`numeric`},week:{day:`numeric`,month:`short`,year:`numeric`},month:{month:`long`,year:`numeric`},year:{year:`numeric`}},a4=e=>{let t=new Intl.DateTimeFormat(`en-GB`,{...e,timeZone:`UTC`});return e=>t.format(e)},o4={fontSize:11,fill:`var(--muted-foreground)`},afe=({active:e,payload:t,measure:n,bucket:r})=>{let i=t?.[0]?.payload;return!e||!i?null:(0,V.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,V.jsx)(`div`,{className:`text-muted-foreground`,children:(r===`week`?`Week of `:``)+a4(ife[r])(i.at)}),(0,V.jsx)(`div`,{className:`font-semibold tabular-nums`,children:gE(i.value,n)})]})},ofe=({points:e,measure:t,bucket:n,type:r})=>{let i=Gl(`(min-width: 640px)`),a=a4(rfe[n]),o=(0,V.jsx)(r0,{vertical:!1,stroke:`var(--border)`}),s=(0,V.jsx)(X0,{dataKey:`at`,tickFormatter:a,tick:o4,axisLine:!1,tickLine:!1,minTickGap:i?24:40,height:18}),c=(0,V.jsx)(t2,{width:i?48:36,tick:o4,axisLine:!1,tickLine:!1,tickCount:3,tickFormatter:e=>e.toLocaleString(`en-IE`,{notation:`compact`})}),l=(0,V.jsx)(Zq,{cursor:r===`bar`?{fill:`var(--muted)`}:{stroke:`var(--border-strong)`},content:(0,V.jsx)(afe,{measure:t,bucket:n}),isAnimationActive:!1});return(0,V.jsx)(`div`,{className:`h-40`,children:(0,V.jsx)(aM,{width:`100%`,height:`100%`,children:r===`line`?(0,V.jsxs)(Lde,{data:e,margin:{top:6,right:6,bottom:0,left:0},children:[o,s,c,l,(0,V.jsx)(T0,{dataKey:`value`,stroke:`var(--chart-1)`,strokeWidth:2,dot:e.length<=31&&{r:3,fill:`var(--chart-1)`,strokeWidth:0},activeDot:{r:4,stroke:`var(--background)`,strokeWidth:2},isAnimationActive:!1})]}):(0,V.jsxs)($2,{data:e,margin:{top:6,right:0,bottom:0,left:0},barCategoryGap:`22%`,children:[o,s,c,l,(0,V.jsx)(H0,{dataKey:`value`,fill:`var(--chart-1)`,radius:[4,4,0,0],isAnimationActive:!1})]})})})},sfe=(e,t,n,r)=>{let i=n??r,a=i===void 0?void 0:e.fields[i];return!a||i===void 0?{kind:`count`}:{kind:n===void 0?`average`:`sum`,field:a,hints:t?.fields[i]}},s4=({model:e,view:t,groupBy:n,type:r=`bar`,sum:i,average:a,filter:o=``,granularity:s=`day`,range:c=`30d`,limit:l=10,empty:u=`Nothing to chart yet.`})=>{let{resources:d,views:f}=J(),p=e.fields[n],m=p?.type===`date`||p?.type===`timestamp`,h=p?.type===`relation`&&p.relation?d[p.relation.resource]:void 0,g=h&&h.primaryKey.length===1?Px(h,f[h.name]):void 0,_=m?{granularity:s,range:c,timeZone:Wd()}:{limit:l,...g&&{label:g}},v=sE(e.name,{groupBy:n,filter:o,...i&&{sum:i},...a&&{average:a},..._},!!p),y=sfe(e,t,i,a);if(!p)return null;if(v.isPending)return(0,V.jsx)(cu,{className:`h-36 w-full`});if(v.error)return(0,V.jsx)(`p`,{className:`text-danger-text`,children:`Could not load the chart.`});let{groups:b}=v.data;if(b.every(e=>e.count===0))return(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:u});if(m)return(0,V.jsx)(ofe,{points:hE(b,y),measure:y,bucket:s,type:r===`line`?`line`:`bar`});let x=mE(b,p,t?.fields[n],y,o);return r===`donut`?(0,V.jsx)(nfe,{resource:e.name,slices:x,measure:y}):(0,V.jsx)(_E,{resource:e.name,slices:x,measure:y})},cfe=({node:e,slots:t})=>{let{resource:n,title:r,description:i,actions:a,span:o,...s}=ZT(e),{resources:c,views:l}=J(),u=c[n];return u?(0,V.jsx)($T,{title:r,description:i,actions:t.actions,className:`h-full`,children:(0,V.jsx)(s4,{model:u,view:l[n],...s})}):null},lfe=co(),c4=async(e,t,n,r,i)=>{let a=n.primaryKey[0],o=[...new Set(r)].sort();if(o.length===0||n.primaryKey.length!==1)return new Map;let s=Px(n,i),c=await e.fetchQuery({queryKey:W.labels(n.name,o.join(`,`)),staleTime:3e5,queryFn:async()=>(await t.list(n.name,{filter:qa(lfe.in(a,o)),fields:[a,s],pageSize:o.length})).items.map(e=>[String(e[a]),String(e[s])])});return new Map(c)},l4=(e,t,n)=>n.flatMap(n=>{let r=t.fields[n],i=r?.type===`relation`&&r.relation?e[r.relation.resource]:void 0;return i?[{name:n,target:i}]:[]}),u4=(e,t,n,r)=>Object.fromEntries(l4(e,n,r).filter(({target:e})=>e.primaryKey.length===1).map(({name:e,target:n})=>[e,Px(n,t[n.name])])),d4=(e,t,n,r,i={})=>{let a=l4(e,t,n);return r.map(e=>{let t={...e};for(let{name:n}of a)e[n]!=null&&(t[n]={id:e[n],name:i[n]?.[String(e[n])]??String(e[n])});return t})},f4=(e,t)=>{let n=String(t);return e&&Object.hasOwn(e,n)?e[n]:void 0},p4=({value:e,hints:t,children:n})=>(0,V.jsx)(Au,{tone:Gx(String(e)),color:f4(t?.valueColors,e),shape:t?.badgeShape,children:n}),ufe=({field:e,value:t,known:n})=>{let{resources:r,views:i}=J(),a=G(),o=Gp(),s=e.relation?r[e.relation.resource]:void 0,c=String(t),l=mh({queryKey:W.relatedLabel(s?.name??``,c),enabled:!!s&&n===void 0,queryFn:async()=>(await c4(o,a,s,[c],i[s.name])).get(c)??c});return s?(0,V.jsx)(ZS,{to:{kind:`record`,resource:s.name,key:c},className:`font-medium text-primary-text hover:underline`,children:n??l.data??c}):(0,V.jsx)(`span`,{children:c})},dfe=({model:e,field:t,value:n,format:r,relationLabel:i})=>{let{views:a}=J(),o={...a[e.name]?.fields[t.name],...r&&{format:r}};if(n==null||n===``)return(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`—`});if(t.type===`relation`)return(0,V.jsx)(ufe,{field:t,value:n,known:i});let s=t.type===`file`?bb(n):void 0;if(s&&`url`in s&&s.url){let e=Ob(n,{width:40,height:40});return(0,V.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[e&&(0,V.jsx)(hC,{image:e,className:`size-10 shrink-0 rounded border border-border object-cover`}),(0,V.jsx)(`a`,{href:s.url,target:`_blank`,rel:`noreferrer`,className:`truncate font-medium text-primary-text hover:underline`,children:s.name})]})}if(Mx(t,o))return(0,V.jsx)(OC,{source:String(n)});let c=eS(t,n,o),l=t.type===`text`?Vx(o):void 0;return l?(0,V.jsx)(PC,{format:l,value:c}):t.type===`enum`||o.format===`badge`?(0,V.jsx)(p4,{value:n,hints:o,children:c}):(0,V.jsx)(`span`,{title:tS(t,n),className:B(o.format===`code`&&`font-mono text-xs`,(t.type===`decimal`||t.type===`integer`)&&`tabular-nums`,o.multiline&&`whitespace-pre-line break-words`),children:c})},m4=e=>{let{views:t}=J(),n=wC(e.field,t[e.model.name]?.fields[e.field.name]),r=(0,V.jsx)(dfe,{...e});return n?(0,V.jsx)(EC,{shown:n,part:`display`,field:e.field,value:e.value,fallback:r}):r},h4=(e,t,n)=>{if(!t)return[];let r=sc(e,t.model.name,n);return r.ok?r.steps:[]},g4=(e,t,n,r,i)=>({queryKey:W.pathValue(n?.model.name??``,n?.key??``,r),enabled:i.length>1,queryFn:async()=>{let r=n.record;for(let n of i.slice(0,-1)){let i=r[n.field.name];if(i==null)return null;let a=n.field.relation.resource;r=(await t.fetchQuery({queryKey:W.record(a,String(i)),queryFn:()=>e.get(a,String(i))})).record}return r[i.at(-1).field.name]??null}}),_4=(e,t,n)=>{let r=t.at(-1);return!e||!r?{state:`missing`}:t.length===1?{state:`ready`,value:e.record[r.field.name],field:r.field,model:r.model}:n.isPending?{state:`loading`}:{state:`ready`,value:n.data??null,field:r.field,model:r.model}},v4=(e,t)=>{let{resources:n}=J(),r=h4(n,e,t);return _4(e,r,mh(g4(G(),Gp(),e,t,r)))},ffe=(e,t)=>{let{resources:n}=J(),r=G(),i=Gp(),a=t.map(t=>h4(n,e,t)),o=fh({queries:t.map((t,n)=>g4(r,i,e,t,a[n]))});return t.map((t,n)=>_4(e,a[n],o[n]))},pfe=(e,t)=>{if(t)return t;let n=e.split(`.`).map(e=>K(e).toLowerCase()).join(` `);return n[0].toUpperCase()+n.slice(1)},mfe=({node:e})=>{let{name:t,label:n,format:r}=ZT(e),{views:i}=J(),a=v4(jT(),t);if(a.state===`missing`)return null;let o=a.state===`loading`?(0,V.jsx)(cu,{className:`h-4 w-24`}):(0,V.jsx)(m4,{model:a.model,field:a.field,value:a.value,format:r});if(n===!1)return(0,V.jsx)(`div`,{children:o});let s=n??pfe(t,a.state===`ready`?i[a.model.name]?.fields[a.field.name]?.label:void 0);return(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:s}),(0,V.jsx)(`div`,{className:`mt-0.5 truncate`,children:o})]})},hfe={1:``,2:`md:grid-cols-2`,3:`md:grid-cols-2 xl:grid-cols-3`,4:`sm:grid-cols-2 xl:grid-cols-4`},gfe={1:``,2:`grid-cols-2`,3:`grid-cols-2 xl:grid-cols-3`,4:`grid-cols-2 xl:grid-cols-4`},_fe={1:``,2:`md:col-span-2`,3:`md:col-span-2 xl:col-span-3`,4:`sm:col-span-2 md:col-span-2 xl:col-span-4`},vfe=e=>typeof e==`object`&&!e.custom&&e.type===`Stat`,yfe=({node:e,children:t})=>{let{columns:n=2}=ZT(e),r=e.children,i=r.length>0&&r.every(vfe);return(0,V.jsx)(`div`,{className:B(`grid grid-cols-1 gap-4`,i?gfe[n]:hfe[n]),children:t.map((e,t)=>{let n=r[t],i=typeof n==`object`?n.props.span:void 0;return(0,V.jsx)(`div`,{className:B(`min-w-0`,i&&_fe[i]),children:e},t)})})},y4=`font-medium text-primary-text hover:underline`,bfe=({node:e})=>{let t=ZT(e),n=jT()?.record,r=e.children.filter(e=>typeof e==`string`).join(``);if(t.to){let e=go(t.to,n);return(0,V.jsx)(ZS,{to:e,className:y4,children:r||ps(e)})}let i=t.href??``;return(0,V.jsx)(`a`,{href:i,className:y4,...i.startsWith(`http`)&&{target:`_blank`,rel:`noreferrer`},children:r||i})},xfe=(e,t,n)=>Object.fromEntries(t.map(t=>{let r=e.fields[t];if(r.type===`file`)return[t,n?.record[t]??null];if(n)return[t,r.type===`boolean`?!!n.record[t]:Mb(n.record[t])];let i=r.default&&`value`in r.default?r.default.value:void 0;return[t,r.type===`boolean`?!!i:Mb(i)]})),Sfe=(e,t,n)=>Object.fromEntries(Object.entries(t).flatMap(([t,r])=>{let i=e.fields[t];return Kb(r)?r.key===Mb(n.record[t])?[]:[[t,i.type===`integer`?Number(r.key):r.key]]:Vb(i,r,n.record[t])?[[t,Rb(i,r)]]:[]})),Cfe=({model:e,record:t,mode:n,label:r,title:i,fields:a,values:s,onClose:c})=>{let{resources:l,views:u}=J(),d=G(),f=Qy(),p=qT(),m=u[e.name],[h,g]=(0,o.useState)(()=>xfe(e,a,t)),[_,v]=(0,o.useState)({}),[y,b]=(0,o.useState)(0),x=KC(y),[S,C]=(0,o.useState)(),[w,T]=(0,o.useState)(!1),E=async()=>{T(!0),C(void 0),await(n===`create`?d.create(e.name,{...Xb(e,l,h),...s}):d.update(e.name,t.key,Sfe(e,h,t),t.etag??`*`)).then(async()=>{await p(e.name),f.show({state:`success`,title:`${i??r}: saved`}),c()},e=>{let t=WC(e);v(t),Object.keys(t).length>0&&b(e=>e+1),C(e)}),T(!1)};return(0,V.jsx)(wf,{title:i??r,onClose:c,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:c,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,loading:w,onClick:()=>void E(),children:n===`create`?`Create`:`Save`})]}),children:(0,V.jsxs)(`form`,{ref:x,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),E()},children:[S!==void 0&&Object.keys(_).length===0&&(0,V.jsx)(ax,{title:`Not saved`,error:S}),a.map(n=>{let r=e.fields[n],i=h[n],a=r.relation?l[r.relation.resource]:void 0,o=m?.fields[n]?.label??K(n),s=_[n];return(0,V.jsx)(eb,{name:n,label:o,help:m?.fields[n]?.help,error:s&&UC(r,o,s),children:(0,V.jsx)(IC,{field:r,hints:m?.fields[n],value:Kb(i)?i.key:i,stored:t?.record[n],relationLabel:Kb(i)?i.label:void 0,relationPicker:a?{target:a,view:u[a.name]}:void 0,invalid:!!_[n],resource:e.name,onChange:e=>{v(({[n]:e,...t})=>t),g(t=>({...t,[n]:e}))}})},n)})]})})},wfe=({model:e,recordKey:t,children:n})=>{let r=GT(e,{key:t});return(0,V.jsx)(V.Fragment,{children:n(r.data??void 0)})},Tfe=({node:e})=>{let t=ZT(e),n=jT(),{resources:r}=J(),i=r[t.resource??n?.model.name??``],a=YS(i?.name??``),[s,c]=(0,o.useState)(!1);if(!i||!(t.mode===`create`?MT(a,`create`):MT(a,`update`)&&n?.permissions?.update!==!1))return null;let l=e=>(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{size:`sm`,variant:t.variant??`secondary`,disabled:t.mode===`edit`&&!e,onClick:()=>c(!0),children:t.label}),s&&(0,V.jsx)(Cfe,{...t,model:i,record:t.mode===`edit`?e:void 0,onClose:()=>c(!1)})]});return t.mode===`edit`&&t.recordKey!==void 0?(0,V.jsx)(wfe,{model:i,recordKey:t.recordKey,children:l}):l(t.mode===`edit`?n:void 0)},Efe=({node:e,children:t,slots:n})=>{let{title:r,description:i}=ZT(e);return(0,V.jsx)(`div`,{className:`flex-1`,children:(0,V.jsxs)(`div`,{className:`mx-auto flex max-w-[1200px] flex-col gap-6 px-4 pb-16 pt-6 md:px-10 md:py-8`,children:[(0,V.jsx)(gd,{title:r,subtitle:i,actions:n.actions}),t]})})},b4=(e,t)=>{let n=jT(),r=v4(typeof e==`string`?n:void 0,typeof e==`string`?e:``);return typeof e==`number`?e:e===void 0?t:r.state===`ready`?Number(r.value):r.state===`loading`?void 0:NaN},Dfe=({node:e})=>{let{value:t,max:n,label:r}=ZT(e),i=b4(t,0),a=b4(n,100);if(i===void 0||a===void 0)return(0,V.jsx)(cu,{className:`h-6 w-full`});if(!Number.isFinite(i)||!Number.isFinite(a))return null;let o=a>0?Math.min(1,Math.max(0,i/a)):0;return(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:r}),(0,V.jsxs)(`span`,{className:`tabular-nums`,children:[i.toLocaleString(`en-IE`),` / `,a.toLocaleString(`en-IE`)]})]}),(0,V.jsx)(`div`,{role:`progressbar`,"aria-label":r,"aria-valuenow":i,"aria-valuemin":0,"aria-valuemax":a,className:`mt-1.5 h-2 overflow-hidden rounded-full bg-muted`,children:(0,V.jsx)(`div`,{className:o>=.9?`h-full rounded-full bg-warning`:`h-full rounded-full bg-primary`,style:{width:`${o*100}%`}})})]})},Ofe=({model:e,filter:t,sort:n,recordKey:r,title:i,description:a,empty:o,actions:s,children:c})=>{let l=GT(e,{filter:t,sort:n,key:r}),u=e=>l.data?(0,V.jsx)(AT,{value:l.data,children:e}):void 0,d=l.isPending?(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsx)(cu,{className:`h-4 w-1/2`}),(0,V.jsx)(cu,{className:`h-4 w-1/3`})]}):l.error?(0,V.jsx)(ax,{title:`Could not load`,error:l.error}):l.data?u((0,V.jsx)(`div`,{className:`flex flex-col gap-3`,children:c})):(0,V.jsx)(eE,{children:o??`Nothing here yet.`});return(0,V.jsx)($T,{title:i,description:a,actions:s?u(s):void 0,className:`h-full`,children:d})},kfe=({node:e,children:t,slots:n})=>{let{resource:r,filter:i,sort:a,recordKey:o,title:s,description:c,empty:l}=ZT(e),u=J().resources[r];return u?(0,V.jsx)(Ofe,{model:u,filter:i,sort:a,recordKey:o,title:s,description:c,empty:l,actions:n.actions,children:t}):null};function Afe(e){return jfe(e)||typeof e==`function`||Mfe(e)}function jfe(e){return typeof e==`function`&&(()=>{let t=Object.getPrototypeOf(e);return t.prototype&&t.prototype.isReactComponent})()}function Mfe(e){return typeof e==`object`&&typeof e.$$typeof==`symbol`&&[`react.memo`,`react.forward_ref`].includes(e.$$typeof.description)}function x4(e,t){return e==null?null:Afe(e)?o.createElement(e,t):e}function Nfe(e){if(`cell`in e&&e.cell){let t=e.cell,n=t.column.columnDef,r=t,i=n;return r.getIsAggregated?.()?x4(i.aggregatedCell??n.cell,t.getContext()):r.getIsPlaceholder?.()?null:x4(n.cell,t.getContext())}return`header`in e&&e.header?x4(e.header.column.columnDef.header,e.header.getContext()):`footer`in e&&e.footer?x4(e.footer.column.columnDef.footer,e.footer.getContext()):null}function Pfe({update:e,notify:t,unwatched:n}){return{link:r,unlink:i,propagate:a,checkDirty:o,shallowPropagate:s};function r(e,t,n){let r=t.depsTail;if(r!==void 0&&r.dep===e)return;let i=r===void 0?t.deps:r.nextDep;if(i!==void 0&&i.dep===e){i.version=n,t.depsTail=i;return}let a=e.subsTail;if(a!==void 0&&a.version===n&&a.sub===t)return;let o=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:a,nextSub:void 0};i!==void 0&&(i.prevDep=o),r===void 0?t.deps=o:r.nextDep=o,a===void 0?e.subs=o:a.nextSub=o}function i(e,t=e.sub){let r=e.dep,i=e.prevDep,a=e.nextDep,o=e.nextSub,s=e.prevSub;return a===void 0?t.depsTail=i:a.prevDep=i,i===void 0?t.deps=a:i.nextDep=a,o===void 0?r.subsTail=s:o.prevSub=s,s===void 0?(r.subs=o)===void 0&&n(r):s.nextSub=o,a}function a(e){let n=e.nextSub,r;top:do{let i=e.sub,a=i.flags;if(a&60?a&12?a&4?!(a&48)&&c(e,i)?(i.flags=a|40,a&=1):a=0:i.flags=a&-9|32:a=0:i.flags=a|32,a&2&&t(i),a&1){let t=i.subs;if(t!==void 0){let i=(e=t).nextSub;i!==void 0&&(r={value:n,prev:r},n=i);continue}}if((e=n)!==void 0){n=e.nextSub;continue}for(;r!==void 0;)if(e=r.value,r=r.prev,e!==void 0){n=e.nextSub;continue top}break}while(1)}function o(t,n){let r,i=0,a=!1;top:do{let o=t.dep,c=o.flags;if(n.flags&16)a=!0;else if((c&17)==17){if(e(o)){let e=o.subs;e.nextSub!==void 0&&s(e),a=!0}}else if((c&33)==33){(t.nextSub!==void 0||t.prevSub!==void 0)&&(r={value:t,prev:r}),t=o.deps,n=o,++i;continue}if(!a){let e=t.nextDep;if(e!==void 0){t=e;continue}}for(;i--;){let i=n.subs,o=i.nextSub!==void 0;if(o?(t=r.value,r=r.prev):t=i,a){if(e(n)){o&&s(i),n=t.sub;continue}a=!1}else n.flags&=-33;n=t.sub;let c=t.nextDep;if(c!==void 0){t=c;continue top}}return a}while(1)}function s(e){do{let n=e.sub,r=n.flags;(r&48)==32&&(n.flags=r|16,(r&6)==2&&t(n))}while((e=e.nextSub)!==void 0)}function c(e,t){let n=t.depsTail;for(;n!==void 0;){if(n===e)return!0;n=n.prevDep}return!1}}function Ffe(e,t,n){let r=typeof e==`object`,i=r?e:void 0;return{next:(r?e.next:e)?.bind(i),error:(r?e.error:t)?.bind(i),complete:(r?e.complete:n)?.bind(i)}}var S4=[],C4=0,{link:w4,unlink:Ife,propagate:Lfe,checkDirty:T4,shallowPropagate:E4}=Pfe({update(e){return e._update()},notify(e){S4[O4++]=e,e.flags&=-3},unwatched(e){e.depsTail!==void 0&&(e.depsTail=void 0,e.flags=17,j4(e))}}),D4=0,O4=0,k4,A4=0;function Rfe(e){try{++A4,e()}finally{--A4||M4()}}function j4(e){let t=e.depsTail,n=t===void 0?e.deps:t.nextDep;for(;n!==void 0;)n=Ife(n,e)}function M4(){if(!(A4>0)){for(;D4<O4;){let e=S4[D4];S4[D4++]=void 0,e.notify()}D4=0,O4=0}}function zfe(e,t){let n=typeof e==`function`,r=e,i={_snapshot:n?void 0:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:+!n,get(){return k4!==void 0&&w4(i,k4,C4),i._snapshot},subscribe(e){let t=Ffe(e),n={current:!1},r=Bfe(()=>{i.get(),n.current?(k4=void 0,t.next?.(i._snapshot)):n.current=!0});return{unsubscribe:()=>{r.stop()}}},_update(e){let a=k4,o=t?.compare??Object.is;if(n)k4=i,++C4,i.depsTail=void 0;else if(e===void 0)return!1;n&&(i.flags=5);try{let t=i._snapshot,a=typeof e==`function`?e(t):e===void 0&&n?r(t):e;return t===void 0||!o(t,a)?(i._snapshot=a,!0):!1}finally{k4=a,n&&(i.flags&=-5),j4(i)}}};return n?(i.flags=17,i.get=function(){let e=i.flags;if(e&16||e&32&&T4(i.deps,i)){if(i._update()){let e=i.subs;e!==void 0&&E4(e)}}else e&32&&(i.flags=e&-33);return k4!==void 0&&w4(i,k4,C4),i._snapshot}):i.set=function(e){if(i._update(e)){let e=i.subs;e!==void 0&&(Lfe(e),E4(e),M4())}},i}function Bfe(e){let t=()=>{let t=k4;k4=n,++C4,n.depsTail=void 0,n.flags=6;try{return e()}finally{k4=t,n.flags&=-5,j4(n)}},n={deps:void 0,depsTail:void 0,subs:void 0,subsTail:void 0,flags:6,notify(){let e=this.flags;e&16||e&32&&T4(this.deps,this)?t():this.flags=2},stop(){this.flags=0,this.depsTail=void 0,j4(this)}};return t(),n}function N4(e,t){if(Object.is(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||!Object.is(r,t.get(n)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(let n of e)if(!t.has(n))return!1;return!0}if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();let n=P4(e);if(n.length!==P4(t).length)return!1;for(let r=0;r<n.length;r++)if(!Object.prototype.hasOwnProperty.call(t,n[r])||!Object.is(e[n[r]],t[n[r]]))return!1;return!0}function P4(e){return Object.keys(e).concat(Object.getOwnPropertySymbols(e))}function Vfe(e,t){return e===t}function F4(e,t=e=>e,n){let r=n?.compare??Vfe,i=(0,o.useCallback)(t=>{let{unsubscribe:n}=e.subscribe(t);return n},[e]),a=(0,o.useCallback)(()=>e.get(),[e]);return(0,tk.useSyncExternalStoreWithSelector)(i,a,a,t,r)}function Hfe(e){let t=F4(e.source,e.selector,{compare:N4});return typeof e.children==`function`?e.children(t):e.children}function Ufe(e){let t=e;return Object.defineProperty(e,"state",{get(){return e.get()}}),`set`in e&&(t.setState=e.set.bind(e)),t}function Wfe(e){let{createAtom:t,batch:n}=e,r=t(0);return{createOptionsStore:!1,wrapExternalAtoms:!1,addSubscription:()=>{throw Error(`Feature not supported in current reactivity implementation`)},unmount:()=>{throw Error(`Feature not supported in current reactivity implementation`)},schedule:e.schedule??(e=>queueMicrotask(e)),batch:n,untrack:e=>e(),createReadonlyAtom:(e,n)=>{let i=n?.compare??Object.is,a=!1,o,s=()=>{let t=e();return(!a||!i(o,t))&&(o=t,a=!0),o},c=t(()=>(r.get(),s()),{compare:i});return{get:s,subscribe:c.subscribe.bind(c)}},createWritableAtom:(e,n)=>t(e,{compare:n?.compare}),commit:()=>{r.set(e=>e+1)}}}function Gfe(e,t=Object.is){let n=!1,r;return{get:e.get,markCommitted:e=>{r=e,n=!0},subscribe:i=>e.subscribe(e=>{(!n||!t(r,e))&&i(e)})}}function Kfe(){return Wfe({createAtom:zfe,batch:Rfe})}function I4(e,t){return typeof e==`function`?e(t):e}function L4(e){if(Array.isArray(e))return e.map(L4);if(e&&typeof e==`object`){let t=Object.getPrototypeOf(e);if(t!==Object.prototype&&t!==null)return e;let n=t===null?R4():{},r=Object.keys(e);for(let t=0;t<r.length;t++){let i=r[t];Object.defineProperty(n,i,{configurable:!0,enumerable:!0,value:L4(e[i]),writable:!0})}return n}return e}function qfe(e,t){let n=Object.keys(t),r=e;for(let e=0;e<n.length;e++){let i=n[e];!i.startsWith(`_memo_`)&&i!==`_cellsCache`&&(r[i]=t[i])}return e}function R4(){return Object.create(null)}function z4(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function B4(e,t){return n=>{(t.options.atoms?.[e]??t.baseAtoms[e]).set(e=>I4(n,e))}}function V4(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function H4(e){return Reflect.ownKeys(e).filter(t=>Object.prototype.propertyIsEnumerable.call(e,t))}var Jfe=3;function Yfe(e,t){return U4(e,t,Jfe)}function U4(e,t,n){if(Object.is(e,t))return!0;if(n<=0||!V4(e)||!V4(t)||(Array.isArray(e)||Array.isArray(t))&&(!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length))return!1;let r=H4(e),i=H4(t);if(r.length!==i.length)return!1;let a=e,o=t;for(let e=0;e<r.length;e++){let i=r[e];if(!Object.prototype.propertyIsEnumerable.call(t,i)||!U4(a[i],o[i],n-1))return!1}return!0}function W4(e,t,n,r=Yfe){let i=`on${t.charAt(0).toUpperCase()}${t.slice(1)}Change`,a=e.options[i];a&&a(e=>{let t=I4(n,e);return r(e,t)?e:t})}function Xfe(e){return e instanceof Function}function Zfe(e,t){let n=[],r=e=>{e.forEach(e=>{n.push(e);let i=t(e);i.length&&r(i)})};return r(e),n}var Qfe=({fn:e,memoDeps:t,onAfterCompare:n,onAfterUpdate:r,onBeforeCompare:i,onBeforeUpdate:a})=>{let o=[],s;return c=>{i?.();let l=t?.(c),u=!l||l.length!==o?.length;if(!u&&l){for(let e=0;e<l.length;e++)if(l[e]!==o[e]){u=!0;break}}return n?.(u),u?(o=l,a?.(),s=e(...l??[]),r?.(s),s):s}};function $fe(e){let t=!1;return()=>{if(!t){t=!0;return}e()}}function G4({feature:e,fnName:t,objectId:n,onAfterUpdate:r,table:i,...a}){let o=()=>{if(!r)return;let{schedule:e,untrack:t}=i._reactivity;e(()=>t(()=>r()))},s={onAfterUpdate:()=>{o()}};return Qfe({...a,...s})}function K4(e,t=`_`){let[n,r]=e.split(t);return{fnKey:r,fnName:`${n}.${r}`,parentName:n}}function q4(e,t,n){for(let[r,{fn:i,memoDeps:a}]of Object.entries(n)){let{fnKey:n,fnName:o}=K4(r);t[n]=a?G4({memoDeps:a,fn:i,fnName:o,table:t,feature:e}):i}}function J4(e,t,n,r){for(let[i,{fn:a,memoDeps:o}]of Object.entries(r)){let{fnKey:r,fnName:s}=K4(i);if(o){let i=`_memo_${r}`;t[r]=function(...t){if(!this[i]){let t=this;this[i]=G4({memoDeps:e=>o(t,e),fn:(...e)=>a(t,...e),fnName:s,objectId:t.id,table:n,feature:e})}return this[i](...t)}}else t[r]=function(...e){return a(this,...e)}}}function Y4(e,t,n,...r){return e[t]?.(...r)??n(e,...r)}function epe(e){return e.row.getValue(e.column.id)}function tpe(e){return e.getValue()??e.table.options.renderFallbackValue}function npe(e){return{table:e.table,column:e.column,row:e.row,cell:e,getValue:()=>e.getValue(),renderValue:()=>e.renderValue()}}var rpe={assignCellPrototype:(e,t)=>{J4(`coreCellsFeature`,e,t,{cell_getValue:{fn:e=>epe(e)},cell_renderValue:{fn:e=>tpe(e)},cell_getContext:{fn:e=>npe(e),memoDeps:e=>[e]}})}};function ipe(e){if(!e._headerPrototype){e._headerPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignHeaderPrototype?.(e._headerPrototype,e)}return e._headerPrototype}function X4(e,t,n){let r=ipe(e),i=Object.create(r);i.colSpan=0,i.column=t,i.depth=n.depth,i.headerGroup=null,i.id=n.id??t.id,i.index=n.index,i.isPlaceholder=!!n.isPlaceholder,i.placeholderId=n.placeholderId,i.rowSpan=0,i.subHeaders=[];let a=e._headerInstanceInitFns;for(let e=0;e<a.length;e++)a[e](i);return i}function ape(){return{start:[],end:[]}}function Z4(e){let t=e.table.atoms.columnVisibility?.get();if(!t)return!0;let n=e.columns;return n.length?n.some(e=>Y4(e,`getIsVisible`,Z4)):(z4(t,e.id)?t[e.id]:void 0)??!0}function ope(e){return e.getAllLeafColumns().filter(e=>Y4(e,`getIsVisible`,Z4))}function Q4(e,t=1){let n=t;for(let r=0;r<e.length;r++){let i=e[r];Y4(i,`getIsVisible`,Z4)&&i.columns.length&&(n=Math.max(n,Q4(i.columns,t+1)))}return n}function spe(e,t){return e?`${e}_${t}`:String(t)}function cpe(e,t,n,r){let i=e??``;return t&&(i=i?`${i}_${t}`:String(t)),n&&(i=i?`${i}_${n}`:n),r&&(i=i?`${i}_${r}`:r),i}function lpe(e,t){let n=0;for(let r=0;r<e.length;r++)e[r].column===t&&n++;return n}function $4(e,t,n,r,i,a){let o={depth:t,id:spe(r,t),headers:[]},s=[];for(let i=0;i<e.length;i++){if(!(i in e))continue;let a=e[i],c=s[s.length-1],l=a.column.depth===o.depth,u,d=!1;if(l&&a.column.parent?u=a.column.parent:(u=a.column,d=!0),c&&c.column===u)c.subHeaders.push(a);else{let e=X4(n,u,{id:cpe(r,t,u.id,a.id),isPlaceholder:d,placeholderId:d?String(lpe(s,u)):void 0,depth:t,index:s.length});e.subHeaders.push(a),s.push(e)}o.headers.push(a),a.headerGroup=o}for(let e=0;e<a.length;e++)a[e](o);i.push(o),t>0&&$4(s,t-1,n,r,i,a)}function e3(e){for(let t=0;t<e.length;t++){let n=e[t];if(!Y4(n.column,`getIsVisible`,Z4))continue;let r=0;if(n.subHeaders.length){e3(n.subHeaders);for(let e=0;e<n.subHeaders.length;e++){let t=n.subHeaders[e];Y4(t.column,`getIsVisible`,Z4)&&(r+=t.colSpan)}}else r=1;if(n.colSpan=r,n.isPlaceholder&&n.subHeaders.length===1&&n.subHeaders[0].column===n.column){let e=1,t=n.subHeaders[0];for(;t;)t.rowSpan=0,e++,t=t.subHeaders.length===1&&t.subHeaders[0].column===n.column?t.subHeaders[0]:void 0;n.rowSpan=e}else n.rowSpan=1}}function t3(e,t,n,r){let i=Q4(e),a=[],o=n._headerGroupInstanceInitFns,s=Array(t.length);for(let e=0;e<t.length;e++)e in t&&(s[e]=X4(n,t[e],{depth:i,index:e}));return $4(s,i-1,n,r,a,o),a.reverse(),e3(a[0]?.headers??[]),a}function upe(e){if(!e._columnPrototype){e._columnPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignColumnPrototype?.(e._columnPrototype,e)}return e._columnPrototype}function dpe(e,t,n,r){let i={...e.getDefaultColumnDef(),...t},a=i.accessorKey,o=a===void 0?void 0:String(a),s=i.id??o?.replaceAll(`.`,`_`)??(typeof i.header==`string`?i.header:void 0),c;if(i.accessorFn)c=i.accessorFn;else if(a!==void 0){if(typeof a==`string`&&a.includes(`.`)){let e=a.split(`.`);c=t=>{let n=t;for(let t=0;t<e.length;t++){let r=e[t];n=n?.[r]}return n}}else c=e=>e[i.accessorKey]}if(!s)throw Error();let l=upe(e),u=Object.create(l);u.accessorFn=c,u.columnDef=i,u.columns=[],u.depth=n,u.id=`${String(s)}`,u.parent=r;let d=e._columnInstanceInitFns;for(let e=0;e<d.length;e++)d[e](u);return u}function n3(e){let t=e.atoms.columnOrder?.get();return n=>{let r=[];if(!t?.length)r=n;else{let e=new Map;for(let t=0;t<n.length;t++){let r=n[t];e.set(r.id,r)}for(let n=0;n<t.length;n++){let i=t[n],a=e.get(i);a&&(r.push(a),e.delete(i))}for(let t=0;t<n.length;t++){let i=n[t];e.has(i.id)&&r.push(i)}}return fpe(e,r)}}function fpe(e,t){let n=e.atoms.grouping?.get()??[],{groupedColumnMode:r}=e.options;if(!n.length||!r)return t;let i=t.filter(e=>!n.includes(e.id));if(r===`remove`)return i;let a=new Map;for(let e=0;e<t.length;e++){let n=t[e];a.set(n.id,n)}let o=[];for(let e=0;e<n.length;e++){let t=a.get(n[e]);t&&o.push(t)}return[...o,...i]}function ppe(e){return[e,...e.columns.flatMap(e=>e.getFlatColumns())]}function mpe(e){if(e.columns.length){let t=e.columns.flatMap(e=>e.getLeafColumns());return Y4(e.table,`getOrderColumns`,n3)(t)}return[e]}function hpe(e){return{header:e=>{let t=e.header.column.columnDef;return t.accessorKey?t.accessorKey:t.accessorFn?t.id:null},cell:e=>e.renderValue()?.toString?.()??null,...Object.values(e._features).reduce((e,t)=>Object.assign(e,t.getDefaultColumnDef?.()),{}),...e.options.defaultColumn}}function r3(e,t,n,r=0){let i=Array(t.length);for(let a=0;a<t.length;a++){if(!(a in t))continue;let o=t[a],s=dpe(e,o,r,n),c=o;s.columns=c.columns?r3(e,c.columns,s,r+1):[],i[a]=s}return i}function gpe(e){return r3(e,e.options.columns)}function _pe(e){return e.getAllColumns().flatMap(e=>e.getFlatColumns())}function vpe(e){let t=R4(),n=e.getAllFlatColumns();for(let e=0;e<n.length;e++){let r=n[e];t[r.id]=r}return t}function ype(e){let t=e.getAllColumns().flatMap(e=>e.getLeafColumns());return Y4(e,`getOrderColumns`,n3)(t)}function bpe(e){let t=R4(),n=e.getAllLeafColumns();for(let e=0;e<n.length;e++){let r=n[e];t[r.id]=r}return t}function xpe(e,t){return e.getAllFlatColumnsById()[t]}var Spe={assignColumnPrototype:(e,t)=>{J4(`coreColumnsFeature`,e,t,{column_getFlatColumns:{fn:e=>ppe(e),memoDeps:e=>[e.table.options.columns]},column_getLeafColumns:{fn:e=>mpe(e),memoDeps:e=>[e.table.atoms.columnOrder?.get(),e.table.atoms.grouping?.get(),e.table.options.columns,e.table.options.groupedColumnMode]}})},constructTableAPIs:e=>{q4(`coreColumnsFeature`,e,{table_getDefaultColumnDef:{fn:()=>hpe(e),memoDeps:()=>[e.options.defaultColumn]},table_getAllColumns:{fn:()=>gpe(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumns:{fn:()=>_pe(e),memoDeps:()=>[e.options.columns]},table_getAllFlatColumnsById:{fn:()=>vpe(e),memoDeps:()=>[e.options.columns]},table_getAllLeafColumns:{fn:()=>ype(e),memoDeps:()=>[e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.options.columns,e.options.groupedColumnMode]},table_getAllLeafColumnsById:{fn:()=>bpe(e),memoDeps:()=>[e.getAllLeafColumns()]},table_getColumn:{fn:t=>xpe(e,t)}})}};function i3(e,t){for(let n=0;n<e.subHeaders.length;n++)i3(e.subHeaders[n],t);t.push(e)}function Cpe(e){let t=[];return i3(e,t),t}function wpe(e){return{column:e.column,header:e,table:e.column.table}}function Tpe(e){let{start:t,end:n}=e.atoms.columnPinning?.get()??ape(),r=e.getAllColumns(),i=Y4(e,`getVisibleLeafColumns`,ope);if(!t.length&&!n.length)return t3(r,i,e);let a=e.getAllLeafColumnsById(),o=[];for(let e=0;e<t.length;e++){let n=a[t[e]];n&&Y4(n,`getIsVisible`,Z4)&&o.push(n)}let s=[];for(let e=0;e<n.length;e++){let t=a[n[e]];t&&Y4(t,`getIsVisible`,Z4)&&s.push(t)}let c=i.filter(e=>!t.includes(e.id)&&!n.includes(e.id));return t3(r,[...o,...c,...s],e)}function Epe(e){return[...e.getHeaderGroups()].reverse()}function Dpe(e){let t=e.getHeaderGroups(),n=[];for(let e=0;e<t.length;e++){let r=t[e].headers;for(let e=0;e<r.length;e++)n.push(r[e])}return n}function Ope(e){let t=e.getHeaderGroups()[0]?.headers??[],n=[];for(let e=0;e<t.length;e++){let r=t[e].getLeafHeaders();for(let e=0;e<r.length;e++)n.push(r[e])}return n}var kpe={assignHeaderPrototype:(e,t)=>{J4(`coreHeadersFeature`,e,t,{header_getLeafHeaders:{fn:e=>Cpe(e),memoDeps:e=>[e.column.table.options.columns]},header_getContext:{fn:e=>wpe(e),memoDeps:e=>[e.column.table.options.columns]}})},constructTableAPIs:e=>{q4(`coreHeadersFeature`,e,{table_getHeaderGroups:{fn:()=>Tpe(e),memoDeps:()=>[e.options.columns,e.atoms.columnOrder?.get(),e.atoms.grouping?.get(),e.atoms.columnPinning?.get(),e.atoms.columnVisibility?.get(),e.options.groupedColumnMode]},table_getFooterGroups:{fn:()=>Epe(e),memoDeps:()=>[e.getHeaderGroups()]},table_getFlatHeaders:{fn:()=>Dpe(e),memoDeps:()=>[e.getHeaderGroups()]},table_getLeafHeaders:{fn:()=>Ope(e),memoDeps:()=>[e.getHeaderGroups()]}})}};function Ape(e){if(!e._rowPrototype){e._rowPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignRowPrototype?.(e._rowPrototype,e)}return e._rowPrototype}var jpe=(e,t,n,r,i,a,o)=>{let s=Ape(e),c=Object.create(s);c._displayIndexCache=-1,c._uniqueValuesCache=R4(),c._valuesCache=R4(),c.depth=i,c.id=t,c.index=r,c.original=n,c.parentId=o,c.subRows=a??[];let l=e._rowInstanceInitFns;for(let e=0;e<l.length;e++)l[e](c);return c},Mpe=/([0-9]+)/gm;function a3(e){let t=Object.assign((e,n,r)=>{let i=e.getValue(r),a=n.getValue(r),o=t.resolveDataValue;return o&&(i=o(i),a=o(a)),t.sort(i,a,e,n,r)},e);return t}a3({resolveDataValue:e=>c3(e).toLowerCase(),sort:(e,t)=>l3(e,t)}),a3({resolveDataValue:e=>c3(e),sort:(e,t)=>l3(e,t)}),a3({resolveDataValue:e=>c3(e).toLowerCase(),sort:(e,t)=>s3(e,t)}),a3({resolveDataValue:e=>c3(e),sort:(e,t)=>s3(e,t)}),a3({resolveDataValue:e=>Npe(e),sort:(e,t)=>e>t?1:e<t?-1:0});var o3=a3({sort:(e,t)=>s3(e,t)});function s3(e,t){return e===t?0:e>t?1:-1}function Npe(e){return e instanceof Date?e.getTime():e}function c3(e){return typeof e==`number`?isNaN(e)||e===1/0||e===-1/0?``:String(e):typeof e==`string`?e:``}function l3(e,t){let n=0,r=0,i=e.length,a=t.length;for(;n<i&&r<a;){let i=u3(e.charCodeAt(n)),a=u3(t.charCodeAt(r)),o=d3(e,n,i),s=d3(t,r,a);if(!i&&!a){let i=Ppe(e,n,o,t,r,s);if(i)return i;n=o,r=s;continue}if(i!==a)return i?1:-1;let c=Fpe(e,n,o,t,r,s);if(c)return c;n=o,r=s}return p3(e,n)-p3(t,r)}function u3(e){return e>=48&&e<=57}function d3(e,t,n){let r=t+1;for(;r<e.length&&u3(e.charCodeAt(r))===n;)r++;return r}function Ppe(e,t,n,r,i,a){let o=n-t,s=a-i,c=o<s?o:s;for(let n=0;n<c;n++){let a=e.charCodeAt(t+n),o=r.charCodeAt(i+n);if(a>o)return 1;if(o>a)return-1}return o>s?1:s>o?-1:0}function Fpe(e,t,n,r,i,a){let o=t;for(;o<n&&e.charCodeAt(o)===48;)o++;let s=i;for(;s<a&&r.charCodeAt(s)===48;)s++;let c=n-o,l=a-s;if(c===0&&l===0)return 0;if(c<=15&&l<=15){let t=f3(e,o,n),i=f3(r,s,a);return t>i?1:i>t?-1:0}let u=parseInt(e.slice(t,n),10),d=parseInt(r.slice(i,a),10);return u>d?1:d>u?-1:0}function f3(e,t,n){let r=0;for(let i=t;i<n;i++)r=r*10+e.charCodeAt(i)-48;return r}function p3(e,t){let n=0,r=t;for(;r<e.length;)n++,r=d3(e,r,u3(e.charCodeAt(r)));return n}function m3(){return[]}function Ipe(e,t){W4(e,`cellSelection`,t?m3():L4(e.initialState.cellSelection)??m3())}function Lpe(e){e.atoms.cellSelection&&(e.options.autoResetAll??e.options.autoResetCellSelection??!0)&&e._reactivity.schedule(()=>Ipe(e))}function Rpe(e){e.atoms.expanded&&(e.options.autoResetAll??e.options.autoResetExpanded??!e.options.manualExpanding)&&e._reactivity.schedule(()=>zpe(e))}function zpe(e,t){let n=e.initialState.expanded;W4(e,`expanded`,t?R4():n===!0||Object.assign(R4(),L4(n??{})))}var h3=0;function Bpe(e){if(e.options.autoResetAll??e.options.autoResetPageIndex??!e.options.manualPagination){if((e.atoms.pagination?.get()?.pageIndex??h3)===h3)return;Upe(e,!0)}}function Vpe(e,t){W4(e,`pagination`,t)}function Hpe(e,t){Vpe(e,n=>{let r=I4(t,n.pageIndex),i=e.options.pageCount===void 0||e.options.pageCount===-1?2**53-1:e.options.pageCount-1;return r=Math.max(0,Math.min(r,i)),{...n,pageIndex:r}})}function Upe(e,t){Hpe(e,t?h3:e.initialState.pagination?.pageIndex??h3)}function Wpe(){return[]}function g3(e,t){W4(e,`sorting`,t)}function _3(e,t){g3(e,t?[]:L4(e.initialState.sorting??[]))}function Gpe(e){e.atoms.sorting&&(e.options.autoResetAll??e.options.autoResetSorting??!1)&&_3(e)}function v3(e){let t=e.table._rowModelFns.sortFns,n=e.table.getFilteredRowModel().flatRows.slice(0,10),r,i=!1;for(let t=0;t<n.length;t++){let a=n[t].getValue(e.id);if(Object.prototype.toString.call(a)===`[object Date]`){r=`datetime`;break}if(typeof a==`string`&&(i=!0,a.split(Mpe).length>1)){r=`alphanumeric`;break}}if(!r&&i&&(r=`text`),r){let e=t?.[r];if(e||r===`alphanumeric`&&(e=t?.text),e)return e}return o3}function y3(e){let t=e.table.getFilteredRowModel().flatRows.slice(0,10);for(let n=0;n<t.length;n++){let r=t[n].getValue(e.id);if(r!=null)return typeof r==`string`?`asc`:`desc`}return`desc`}function Kpe(e){let t=e.table._rowModelFns.sortFns;return Xfe(e.columnDef.sortFn)?e.columnDef.sortFn:e.columnDef.sortFn===`auto`?v3(e):t?.[e.columnDef.sortFn]??o3}function b3(e,t,n){let r=S3(e,n&&w3(e)),i=t!==void 0;g3(e.table,a=>{let o=a.findIndex(t=>t.id===e.id),s=o===-1?void 0:a[o],c=[],l,u=i?t:r===`desc`,d=!!(a.length&&w3(e)&&n);return l=d?s?`toggle`:`add`:s?`toggle`:`replace`,l===`toggle`&&(i||r||(l=`remove`)),l===`add`?(c=[...a,{id:e.id,desc:u}],c.splice(0,c.length-(e.table.options.maxMultiSortColCount??2**53-1))):c=l===`toggle`?d?a.map(t=>t.id===e.id?{...t,desc:u}:t):[{id:e.id,desc:u}]:l===`remove`?d?a.filter(t=>t.id!==e.id):[]:[{id:e.id,desc:u}],c})}function x3(e){return e.columnDef.sortDescFirst??e.table.options.sortDescFirst??y3(e)===`desc`?`desc`:`asc`}function S3(e,t){let n=x3(e),r=T3(e);return r?r!==n&&(e.table.options.enableSortingRemoval??!0)&&(!t||(e.table.options.enableMultiRemove??!0))?!1:r===`desc`?`asc`:`desc`:n}function C3(e){return(e.columnDef.enableSorting??!0)&&(e.table.options.enableSorting??!0)&&!!e.accessorFn}function w3(e){return e.columnDef.enableMultiSort??e.table.options.enableMultiSort??!!e.accessorFn}function T3(e){let t=e.table.atoms.sorting?.get()?.find(t=>t.id===e.id);return t?t.desc?`desc`:`asc`:!1}function qpe(e){return e.table.atoms.sorting?.get()?.findIndex(t=>t.id===e.id)??-1}function Jpe(e){g3(e.table,t=>t.length?t.filter(t=>t.id!==e.id):[])}function Ype(e){let t=C3(e);return n=>{t&&b3(e,void 0,w3(e)?e.table.options.isMultiSortEvent?.(n):!1)}}function Xpe(){return e=>G4({feature:`coreRowModelsFeature`,table:e,fnName:`table.getCoreRowModel`,memoDeps:()=>[e.options.data],fn:()=>Zpe(e,e.options.data),onAfterUpdate:$fe(()=>{Rpe(e),Bpe(e),Gpe(e),Lpe(e)})})}function E3(e,t,n,r=0,i){let a=[];for(let o=0;o<n.length;o++){let s=n[o],c=jpe(e,e.getRowId(s,o,i),s,o,r,void 0,i?.id);t.flatRows.push(c),t.rowsById[c.id]=c,a.push(c),e.options.getSubRows&&(c.originalSubRows=e.options.getSubRows(s,o),c.originalSubRows?.length&&(c.subRows=E3(e,t,c.originalSubRows,r+1,c)))}return a}function Zpe(e,t){let n={rows:[],flatRows:[],rowsById:R4()};return n.rows=E3(e,n,t),n}function Qpe(e){return e._rowModels.coreRowModel||(e._rowModels.coreRowModel=e.options.features.coreRowModel?.(e)??Xpe()(e)),e._rowModels.coreRowModel()}function $pe(e){return e.getCoreRowModel()}function eme(e){return e._rowModels.filteredRowModel||(e._rowModels.filteredRowModel=e.options.features.filteredRowModel?.(e)),e.options.manualFiltering||!e._rowModels.filteredRowModel?e.getPreFilteredRowModel():e._rowModels.filteredRowModel()}function tme(e){return e.getFilteredRowModel()}function nme(e){return e._rowModels.groupedRowModel||(e._rowModels.groupedRowModel=e.options.features.groupedRowModel?.(e)),e.options.manualGrouping||!e._rowModels.groupedRowModel?e.getPreGroupedRowModel():e._rowModels.groupedRowModel()}function rme(e){return e.getGroupedRowModel()}function ime(e){return e._rowModels.sortedRowModel||(e._rowModels.sortedRowModel=e.options.features.sortedRowModel?.(e)),e.options.manualSorting||!e._rowModels.sortedRowModel?e.getPreSortedRowModel():e._rowModels.sortedRowModel()}function ame(e){return e.getSortedRowModel()}function ome(e){return e._rowModels.expandedRowModel||(e._rowModels.expandedRowModel=e.options.features.expandedRowModel?.(e)),e.options.manualExpanding||!e._rowModels.expandedRowModel?e.getPreExpandedRowModel():e._rowModels.expandedRowModel()}function sme(e){return e.getExpandedRowModel()}function cme(e){return e._rowModels.paginatedRowModel||(e._rowModels.paginatedRowModel=e.options.features.paginatedRowModel?.(e)),e.options.manualPagination||!e._rowModels.paginatedRowModel?e.getPrePaginatedRowModel():e._rowModels.paginatedRowModel()}function lme(e){return e.getPaginatedRowModel()}var ume={constructTableAPIs:e=>{q4(`coreRowModelsFeature`,e,{table_getCoreRowModel:{fn:()=>Qpe(e)},table_getPreFilteredRowModel:{fn:()=>$pe(e)},table_getFilteredRowModel:{fn:()=>eme(e)},table_getPreGroupedRowModel:{fn:()=>tme(e)},table_getGroupedRowModel:{fn:()=>nme(e)},table_getPreSortedRowModel:{fn:()=>rme(e)},table_getSortedRowModel:{fn:()=>ime(e)},table_getPreExpandedRowModel:{fn:()=>ame(e)},table_getExpandedRowModel:{fn:()=>ome(e)},table_getPrePaginatedRowModel:{fn:()=>sme(e)},table_getPaginatedRowModel:{fn:()=>cme(e)},table_getRowModel:{fn:()=>lme(e)}})}};function dme(e){if(!e._cellPrototype){e._cellPrototype={table:e};let t=Object.values(e._features);for(let n=0;n<t.length;n++)t[n].assignCellPrototype?.(e._cellPrototype,e)}return e._cellPrototype}function fme(e,t,n){let r=dme(n),i=Object.create(r);i.column=e,i.id=`${t.id}_${e.id}`,i.row=t;let a=n._cellInstanceInitFns;for(let e=0;e<a.length;e++)a[e](i);return i}function pme(e){let t=e.table.getRowsInDisplayOrder(),n=e._displayIndexCache;return t[n]===e?n:-1}function mme(e){let t=e.getPrePaginatedRowModel().rows;if(e.options.paginateExpandedRows===!1){let e=[],n=t=>{t._displayIndexCache=e.length,e.push(t),t.subRows.length&&t.getIsExpanded?.()&&t.subRows.forEach(n)};return t.forEach(n),e}for(let e=0;e<t.length;e++)t[e]._displayIndexCache=e;return t}function hme(e,t){if(z4(e._valuesCache,t))return e._valuesCache[t];let n=e.table.getColumn(t);if(n?.accessorFn)return e._valuesCache[t]=n.accessorFn(e.original,e.index),e._valuesCache[t]}function gme(e,t){if(z4(e._uniqueValuesCache,t))return e._uniqueValuesCache[t];let n=e.table.getColumn(t);if(n?.accessorFn)return n.columnDef.getUniqueValues?(e._uniqueValuesCache[t]=n.columnDef.getUniqueValues(e.original,e.index),e._uniqueValuesCache[t]):(e._uniqueValuesCache[t]=[e.getValue(t)],e._uniqueValuesCache[t])}function _me(e,t){return e.getValue(t)??e.table.options.renderFallbackValue}function vme(e){return Zfe(e.subRows,e=>e.subRows)}function yme(e){let t=e.getCoreRowModel().flatRows,n=0;for(let e=0;e<t.length;e++)n=Math.max(n,t[e].depth);return n}function bme(e){if(e.parentId)return e.table.getCoreRowModel().rowsById[e.parentId]??e.table.getRow(e.parentId,!0)}function xme(e){let t=[],n=e;for(;;){let e=n.getParentRow();if(!e)break;t.push(e),n=e}return t.reverse()}function Sme(e){let t=e.table.getAllLeafColumns(),n=e._cellsCache;n||=e._cellsCache=new WeakMap;let r=Array(t.length);for(let i=0;i<t.length;i++){let a=t[i],o=n.get(a);o||(o=fme(a,e,e.table),n.set(a,o)),r[i]=o}return r}function Cme(e){let t=R4(),n=e.getAllCells();for(let e=0;e<n.length;e++){let r=n[e];t[r.column.id]=r}return t}function wme(e,t,n,r){return t.options.getRowId?.(e,n,r)??(r?`${r.id}.${n}`:String(n))}function Tme(e,t,n){let r=(n?e.getPrePaginatedRowModel():e.getRowModel()).rowsById[t];if(!r&&(r=e.getCoreRowModel().rowsById[t],!r))throw Error();return r}var Eme={assignRowPrototype:(e,t)=>{J4(`coreRowsFeature`,e,t,{row_getDisplayIndex:{fn:e=>pme(e)},row_getAllCellsByColumnId:{fn:e=>Cme(e),memoDeps:e=>[e.getAllCells()]},row_getAllCells:{fn:e=>Sme(e),memoDeps:e=>[e.table.getAllLeafColumns()]},row_getLeafRows:{fn:e=>vme(e),memoDeps:e=>[e.subRows]},row_getParentRow:{fn:e=>bme(e)},row_getParentRows:{fn:e=>xme(e)},row_getUniqueValues:{fn:(e,t)=>gme(e,t)},row_getValue:{fn:(e,t)=>hme(e,t)},row_renderValue:{fn:(e,t)=>_me(e,t)}})},constructTableAPIs:e=>{q4(`coreRowsFeature`,e,{table_getRowsInDisplayOrder:{fn:()=>mme(e),memoDeps:()=>[e.getPrePaginatedRowModel().rows,e.options.paginateExpandedRows,e.options.paginateExpandedRows===!1?e.atoms.expanded?.get():void 0]},table_getRowId:{fn:(t,n,r)=>wme(t,e,n,r)},table_getRow:{fn:(t,n)=>Tme(e,t,n)},table_getMaxSubRowDepth:{fn:()=>yme(e),memoDeps:()=>[e.getCoreRowModel()]}})}};function D3(e,t,n=(e,t)=>e===t){let r=t===void 0?e.options.state:t;e._reactivity.batch(()=>{if(r)for(let t in r){let i=e.baseAtoms[t];if(!i)continue;let a=r[t],o=a===void 0?e.initialState[t]:a;n(e._reactivity.untrack(()=>i.get()),o)||i.set(()=>o)}})}function O3(e,t,n=(e,t)=>e===t){e._reactivity.batch(()=>{D3(e,t,n),e._reactivity.commit?.()})}function Dme(e){let t=L4(e.initialState);e._reactivity.batch(()=>{let n=Object.keys(t);for(let r=0;r<n.length;r++){let i=n[r];e.baseAtoms[i].set(t[i])}});let n=Object.values(e._features);for(let t=0;t<n.length;t++)n[t].resetTableInstanceData?.(e)}function Ome(e,t){let{features:n,atoms:r,initialState:i}=e.options;if(!e.options.mergeOptions)return{...e.options,...t,features:n,atoms:r,initialState:i};let a=e.options.mergeOptions(e.options,t),o={...Object.getOwnPropertyDescriptors(a)};return Object.defineProperties(Object.create(Object.getPrototypeOf(a)),{...o,features:{value:n,enumerable:!0,configurable:!0,writable:!0},atoms:{value:r,enumerable:!0,configurable:!0,writable:!0},initialState:{value:i,enumerable:!0,configurable:!0,writable:!0}})}function k3(e,t,n){let r=Ome(e,I4(t,e.options));e.optionsStore?e.optionsStore.set(()=>r):e.options=r,n?.syncExternalState!==!1&&O3(e,r.state??null)}var kme={coreCellsFeature:rpe,coreColumnsFeature:Spe,coreHeadersFeature:kpe,coreRowModelsFeature:ume,coreRowsFeature:Eme,coreTablesFeature:{constructTableAPIs:e=>{q4(`coreTablesFeature`,e,{table_reset:{fn:()=>Dme(e)},table_setOptions:{fn:t=>k3(e,t)}})}}};function Ame(){return{accessor:(e,t)=>typeof e==`function`?{...t,accessorFn:e}:{...t,accessorKey:e},columns:e=>e,display:e=>e,group:e=>e}}function jme(e){return e}function Mme(e,t={}){return Object.values(e).forEach(e=>{t=e.getInitialState?.(t)??t}),L4(t)}function Nme(e){let t=e.features.coreReactivityFeature,{aggregationFns:n,columnMeta:r,coreRowModel:i,expandedRowModel:a,facetedMinMaxValues:o,facetedRowModel:s,facetedUniqueValues:c,filterFns:l,filterMeta:u,filteredRowModel:d,groupedRowModel:f,paginatedRowModel:p,sortFns:m,sortedRowModel:h,tableMeta:g,..._}=e.features,v={_cellInstanceInitFns:[],_columnInstanceInitFns:[],_features:{...kme,..._},_headerGroupInstanceInitFns:[],_headerInstanceInitFns:[],_reactivity:t,_rowInstanceInitFns:[],_rowModelFns:{aggregationFns:n,filterFns:l,sortFns:m},_rowModels:{},atoms:{},baseAtoms:{}},y=Object.values(v._features),b={...y.reduce((e,t)=>Object.assign(e,t.getDefaultTableOptions?.(v)),{}),...e};if(t.wrapExternalAtoms&&b.atoms)for(let[e,n]of Object.entries(b.atoms)){let r=n,i=t.createWritableAtom(r.get(),{debugName:`externalAtom/${e}`});b.atoms[e]=i;let a=!1,o=r.subscribe(e=>{a||i.set(e)}),s=i.subscribe(e=>{a=!0,r.set(e),a=!1});t.addSubscription(o),t.addSubscription(s)}t.createOptionsStore?(v.optionsStore=t.createWritableAtom(b,{debugName:`table/optionsStore`}),Object.defineProperty(v,"options",{configurable:!0,enumerable:!0,get(){return v.optionsStore.get()},set(e){v.optionsStore.set(()=>e)}})):v.options=b,v.initialState=Mme(v._features,v.options.initialState);let x=Object.keys(v.initialState);for(let e=0;e<x.length;e++){let n=x[e];v.baseAtoms[n]=t.createWritableAtom(v.initialState[n],{debugName:`table/baseAtoms/${n}`}),v.atoms[n]=t.createReadonlyAtom(()=>{let e=v.options,t=e.atoms?.[n],r=t?t.get():v.baseAtoms[n].get();if(t)return r;let i=e.state;if(i&&z4(i,n)){let e=i[n];return e===void 0?v.initialState[n]:e}return r},{debugName:`table/atoms/${n}`})}D3(v),v.store=Ufe(t.createReadonlyAtom(()=>{let e={};for(let t=0;t<x.length;t++){let n=x[t];e[n]=v.atoms[n].get()}return e},{compare:N4,debugName:`table/store`}));for(let e=0;e<y.length;e++){let t=y[e];t.initTableInstanceData?.(v),t.initCellInstanceData&&v._cellInstanceInitFns.push(t.initCellInstanceData.bind(t)),t.initColumnInstanceData&&v._columnInstanceInitFns.push(t.initColumnInstanceData.bind(t)),t.initHeaderGroupInstanceData&&v._headerGroupInstanceInitFns.push(t.initHeaderGroupInstanceData.bind(t)),t.initHeaderInstanceData&&v._headerInstanceInitFns.push(t.initHeaderInstanceData.bind(t)),t.initRowInstanceData&&v._rowInstanceInitFns.push(t.initRowInstanceData.bind(t)),t.constructTableAPIs?.(v)}return v}function Pme(){return R4()}function A3(e,t){e.options.onRowSelectionChange?.(t)}function Fme(e,t){e._lastSelectedRowId=null,A3(e,t?R4():Object.assign(R4(),L4(e.initialState.rowSelection??{})))}function j3(e,t,n){e._lastSelectedRowId=null,A3(e,r=>{if(t=t===void 0?!Y4(e,`getIsAllRowsSelected`,P3):t,n?.deselectAll&&!t)return R4();let i=Object.assign(R4(),r),a=e.getPreGroupedRowModel().flatRows;if(t){let e=new Map;a.forEach(t=>{W3(t,e)&&(i[t.id]=!0)})}else a.forEach(e=>{B3(e)&&delete i[e.id]});return i})}function M3(e,t,n){e._lastSelectedRowId=null,A3(e,r=>{let i=t===void 0?!Y4(e,`getIsAllPageRowsSelected`,F3):t;if(n?.deselectAll&&!i)return R4();let a=Object.assign(R4(),r);return e.getRowModel().rows.forEach(t=>{U3(a,t.id,i,!0,e,!0)}),a})}function Ime(e){return e.getCoreRowModel()}function Lme(e){let t=e.getCoreRowModel();return Y4(e,`getIsSomeRowsSelected`,I3)?q3(t,e):{rows:[],flatRows:[],rowsById:R4()}}function Rme(e){let t=e.getFilteredRowModel();return Y4(e,`getIsSomeRowsSelected`,I3)?q3(t,e):{rows:[],flatRows:[],rowsById:R4()}}function zme(e){let t=e.getSortedRowModel();return Y4(e,`getIsSomeRowsSelected`,I3)?q3(t,e):{rows:[],flatRows:[],rowsById:R4()}}function N3(e){return Object.keys(e.atoms.rowSelection?.get()??{})}function P3(e){let t=e.getFilteredRowModel().flatRows,n=e.atoms.rowSelection?.get()??{},r=!!(t.length&&Object.keys(n).length);if(r){let e=new Map;t.some(t=>!J3(t,n)&&W3(t,e))&&(r=!1)}return r}function F3(e){let t=e.getPaginatedRowModel().flatRows,n=e.atoms.rowSelection?.get()??{},r=new Map,i=!1;for(let e=0;e<t.length;e++){let a=t[e];if(J3(a,n))!i&&W3(a,r)&&(i=!0);else if(W3(a,r))return!1}return i}function I3(e){return Y4(e,`getSelectedRowIds`,N3).length>0}function Bme(e){return e.getPaginatedRowModel().flatRows.filter(e=>B3(e)).some(e=>R3(e)||Y4(e,`getIsSomeSelected`,z3))}function Vme(e){return t=>{j3(e,t.target.checked)}}function Hme(e){return t=>{M3(e,t.target.checked)}}function L3(e,t,n){let r=R3(e);A3(e.table,i=>{t=t===void 0?!r:t;let a=Object.assign(R4(),i);return U3(a,e.id,t,(n?.selectChildren??!0)&&H3(e),e.table),!t&&n?.deselectParents&&G3(a,e),a})}function R3(e){return J3(e,e.table.atoms.rowSelection?.get()??{})}function z3(e){return Y3(e)===`some`}function Ume(e){return Y3(e)===`all`}function B3(e){let t=e.table.options;return typeof t.enableRowSelection==`function`?t.enableRowSelection(e):t.enableRowSelection??!0}function V3(e){let t=e.table.options;return typeof t.enableSubRowSelection==`function`?t.enableSubRowSelection(e):t.enableSubRowSelection??!0}function H3(e){let t=e.table.options;return typeof t.enableMultiRowSelection==`function`?t.enableMultiRowSelection(e):t.enableMultiRowSelection??!0}function Wme(e,t){let n=B3(e);return r=>{if(!n)return;let i=r,a=e.table,o=i.target.checked,s=a._lastSelectedRowId;(!(a.options.enableRowRangeSelection!==!1&&s!==null&&H3(e)&&(a.options.isRowRangeSelectionEvent?.(r)??!1))||!Gme(e,s,o,t))&&L3(e,o,t),a._lastSelectedRowId=e.id}}function Gme(e,t,n,r){let i=r?.selectChildren??!0,a=e.table,o=a.getRowsInDisplayOrder(),s=a.getPrePaginatedRowModel().rowsById[t]??a.getCoreRowModel().rowsById[t];if(!s)return!1;let c=s.getDisplayIndex(),l=e.getDisplayIndex(),u=o[c],d=o[l];if(c<0||l<0||c>=o.length||l>=o.length||u?.id!==s.id||d?.id!==e.id||!H3(s)||!H3(e))return!1;let f=Math.min(c,l),p=Math.max(c,l);return A3(a,e=>{let t=Object.assign(R4(),e);for(let e=f;e<=p;e++){let s=o[e];B3(s)&&H3(s)&&(U3(t,s.id,n,i,a),!n&&r?.deselectParents&&G3(t,s))}return t}),!0}function U3(e,t,n,r,i,a){let o=i.getRow(t,!0);n?(H3(o)||Object.keys(e).forEach(t=>delete e[t]),B3(o)&&(e[t]=!0)):(!a||B3(o))&&delete e[t],r&&o.subRows.length&&V3(o)&&o.subRows.forEach(t=>U3(e,t.id,n,r,i,a))}function W3(e,t){if(!B3(e))return!1;let n=e.table;if(n.options.enableSubRowSelection===!0)return!0;let r=e.parentId;if(r===void 0)return!0;let i=t.get(r);if(i!==void 0)return i;let a=n.getCoreRowModel().rowsById,o=[],s=!0,c=r;for(;c!==void 0;){let e=t.get(c);if(e!==void 0){s=e;break}o.push(c);let r=a[c]??n.getRow(c,!0);if(!V3(r)){s=!1;break}c=r.parentId}return o.forEach(e=>t.set(e,s)),s}function G3(e,t){let n=t.table.getCoreRowModel().rowsById,r=t.parentId;for(;r!==void 0;)delete e[r],r=(n[r]??t.table.getRow(r,!0)).parentId}function K3(e,t,n,r){let i=[];for(let a=0;a<e.length;a++){let o=e[a],s=J3(o,t);if(s&&(n.push(o),r[o.id]=o),o.subRows.length){let e=K3(o.subRows,t,n,r);if(s){let t=Object.create(Object.getPrototypeOf(o));qfe(t,o),t.subRows=e,i.push(t)}}else s&&i.push(o)}return i}function q3(e,t){let n=[],r=R4(),i=t.atoms.rowSelection?.get()??{};return{rows:K3(e.rows,i,n,r),flatRows:n,rowsById:r}}function J3(e,t){return!!(z4(t,e.id)&&t[e.id])}function Y3(e){if(!e.subRows.length)return!1;let t=e.table.atoms.rowSelection?.get()??{},n=!1,r=!0,i=!1;for(let a=0;a<e.subRows.length;a++){let o=e.subRows[a];if(n&&!r)break;if(B3(o)&&(i=!0,J3(o,t)?n=!0:r=!1),o.subRows.length){let e=Y3(o);e===`all`?(n=!0,i=!0):e===`some`?(n=!0,r=!1,i=!0):r=!1}}return i?r?`all`:n?`some`:!1:!1}var Kme={initTableInstanceData:e=>{e._lastSelectedRowId=null},resetTableInstanceData:e=>{e._lastSelectedRowId=null},getInitialState:e=>({rowSelection:Pme(),...e}),getDefaultTableOptions:e=>({onRowSelectionChange:B4(`rowSelection`,e),enableRowSelection:!0,enableMultiRowSelection:!0,enableRowRangeSelection:!0,enableSubRowSelection:!0,isRowRangeSelectionEvent:e=>{let t=e;return!!(t.shiftKey||t.nativeEvent?.shiftKey)}}),assignRowPrototype:(e,t)=>{J4(`rowSelectionFeature`,e,t,{row_toggleSelected:{fn:(e,t,n)=>L3(e,t,n)},row_getIsSelected:{fn:e=>R3(e)},row_getIsSomeSelected:{fn:e=>z3(e),memoDeps:e=>[e.subRows,e.table.atoms.rowSelection?.get(),e.table.options.enableRowSelection]},row_getIsAllSubRowsSelected:{fn:e=>Ume(e),memoDeps:e=>[e.subRows,e.table.atoms.rowSelection?.get(),e.table.options.enableRowSelection]},row_getCanSelect:{fn:e=>B3(e)},row_getCanSelectSubRows:{fn:e=>V3(e)},row_getCanMultiSelect:{fn:e=>H3(e)},row_getToggleSelectedHandler:{fn:(e,t)=>Wme(e,t)}})},constructTableAPIs:e=>{q4(`rowSelectionFeature`,e,{table_setRowSelection:{fn:t=>A3(e,t)},table_resetRowSelection:{fn:t=>Fme(e,t)},table_toggleAllRowsSelected:{fn:(t,n)=>j3(e,t,n)},table_toggleAllPageRowsSelected:{fn:(t,n)=>M3(e,t,n)},table_getPreSelectedRowModel:{fn:()=>Ime(e)},table_getSelectedRowModel:{fn:()=>Lme(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getCoreRowModel()]},table_getFilteredSelectedRowModel:{fn:()=>Rme(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getFilteredRowModel()]},table_getGroupedSelectedRowModel:{fn:()=>zme(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getSortedRowModel()]},table_getSelectedRowIds:{fn:()=>N3(e),memoDeps:()=>[e.atoms.rowSelection?.get()]},table_getIsAllRowsSelected:{fn:()=>P3(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getFilteredRowModel(),e.options.enableRowSelection,e.options.enableSubRowSelection]},table_getIsAllPageRowsSelected:{fn:()=>F3(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getPaginatedRowModel(),e.options.enableRowSelection,e.options.enableSubRowSelection]},table_getIsSomeRowsSelected:{fn:()=>I3(e),memoDeps:()=>[e.atoms.rowSelection?.get()]},table_getIsSomePageRowsSelected:{fn:()=>Bme(e),memoDeps:()=>[e.atoms.rowSelection?.get(),e.getPaginatedRowModel(),e.options.enableRowSelection]},table_getToggleAllRowsSelectedHandler:{fn:()=>Vme(e)},table_getToggleAllPageRowsSelectedHandler:{fn:()=>Hme(e)}})}},qme={getInitialState(e){return{sorting:Wpe(),...e}},getDefaultColumnDef(){return{sortFn:`auto`,sortUndefined:1}},getDefaultTableOptions(e){return{autoResetSorting:!1,onSortingChange:B4(`sorting`,e),isMultiSortEvent:e=>e.shiftKey}},assignColumnPrototype(e,t){J4(`rowSortingFeature`,e,t,{column_getAutoSortFn:{fn:e=>v3(e)},column_getAutoSortDir:{fn:e=>y3(e)},column_getSortFn:{fn:e=>Kpe(e)},column_toggleSorting:{fn:(e,t,n)=>b3(e,t,n)},column_getFirstSortDir:{fn:e=>x3(e)},column_getNextSortingOrder:{fn:(e,t)=>S3(e,t)},column_getCanSort:{fn:e=>C3(e)},column_getCanMultiSort:{fn:e=>w3(e)},column_getIsSorted:{fn:e=>T3(e)},column_getSortIndex:{fn:e=>qpe(e)},column_clearSorting:{fn:e=>Jpe(e)},column_getToggleSortingHandler:{fn:e=>Ype(e)}})},constructTableAPIs(e){q4(`rowSortingFeature`,e,{table_setSorting:{fn:t=>g3(e,t)},table_resetSorting:{fn:t=>_3(e,t)}})}},Jme=typeof window>`u`?o.useEffect:o.useLayoutEffect;function Yme(e,t){let[{table:n,rootSource:r}]=(0,o.useState)(()=>{let t=Nme({...e,features:{coreReactivityFeature:Kfe(),...e.features}});return t.Subscribe=(e=>Hfe({...e,source:e.source??t.store})),t.FlexRender=Nfe,{table:t,rootSource:Gfe(t.store,N4)}}),i=n;k3(i,t=>({...t,...e}),{syncExternalState:!1});let a=i.options.state,s=r.get(),c=F4(r,t,{compare:N4});return Jme(()=>{r.markCommitted(s),O3(i,a??null,N4)}),(0,o.useMemo)(()=>({...n,options:e,state:c}),[n,e,c])}var Xme=e=>t=>{let n=t.currentTarget;n.scrollWidth>Math.ceil(n.getBoundingClientRect().width)?n.title=e:n.removeAttribute(`title`)},X3=({text:e,className:t})=>(0,V.jsx)(`span`,{className:B(`truncate`,t),onMouseEnter:Xme(e),children:e}),Z3=e=>(0,V.jsx)(`span`,{className:`text-faint-foreground`,children:e}),Q3=(e,t)=>{if(t==null)return Z3(`—`);let n=ux(e,t)??``;switch(e.kind){case`text`:return e.link?(0,V.jsx)(PC,{format:e.link,value:n,className:`block min-w-0 truncate`}):(0,V.jsx)(X3,{text:n});case`id`:return(0,V.jsx)(X3,{text:n,className:`font-mono text-xs text-muted-foreground`});case`money`:return(0,V.jsx)(`span`,{className:`tabular-nums`,children:n});case`date`:return(0,V.jsx)(`span`,{className:`tabular-nums text-muted-foreground`,children:n});case`datetime`:return(0,V.jsx)(`span`,{className:`tabular-nums text-muted-foreground`,title:`Shown in ${ef(Number(t),Wd())}`,children:n});case`number`:return(0,V.jsx)(`span`,{className:`tabular-nums`,children:n});case`signed`:return(0,V.jsx)(`span`,{className:B(`tabular-nums`,Number(t)<0?`text-danger-text`:`text-success-text`),children:n});case`percent`:return Number(t)===0?Z3(`—`):(0,V.jsx)(`span`,{className:`tabular-nums`,children:n});case`status`:return(0,V.jsx)(Au,{tone:e.tones?.[String(t)]??`neutral`,color:f4(e.colors,t),shape:e.shape,children:n});case`relation`:return(0,V.jsx)(X3,{text:n,className:`font-medium text-primary-text hover:underline`});case`boolean`:return t?(0,V.jsx)(`span`,{className:`inline-flex size-4 items-center justify-center rounded-full bg-success-soft text-success-text`,children:(0,V.jsx)(ge,{className:`size-3`,strokeWidth:3})}):Z3(`No`);case`file`:{let e=bb(t);if(!e)return Z3(`—`);if(`missing`in e)return(0,V.jsx)(X3,{text:e.name,className:`text-danger-text`});let n=Ob(t,{width:20,height:20});return(0,V.jsxs)(`span`,{className:`inline-flex min-w-0 items-center gap-2`,children:[n?(0,V.jsx)(hC,{image:n,className:`size-5 shrink-0 rounded-sm object-cover`}):(0,V.jsx)(en,{className:`size-3.5 shrink-0 text-muted-foreground`}),(0,V.jsx)(X3,{text:e.name})]})}case`user`:{let e=Ey(String(t));return(0,V.jsxs)(`span`,{className:`inline-flex items-center gap-2 truncate`,children:[(0,V.jsx)(xu,{initials:e.initials,hue:e.hue,size:`xs`,className:`ring-0`}),(0,V.jsx)(X3,{text:e.name,className:`text-muted-foreground`})]})}}},Zme=jme({rowSortingFeature:qme,rowSelectionFeature:Kme}),$3=Ame(),Qme=e=>$3.columns(e.map(e=>$3.accessor(t=>e.value?e.value(t):t[e.id],{id:e.id,header:e.header,enableSorting:e.sortable??!1,cell:t=>e.render?e.render(t.row.original):Q3(e,t.getValue())}))),$me=({total:e,selectedCount:t,bulkActions:n=[],className:r})=>(0,V.jsx)(`div`,{className:B(`flex h-9 shrink-0 items-center border-t bg-surface px-3 text-xs text-muted-foreground`,r),children:(0,V.jsxs)(`span`,{className:`flex items-center tabular-nums`,children:[Ud(e),t>0&&(0,V.jsxs)(`span`,{className:`ml-3 font-medium text-primary-text`,children:[Bd(t),` selected`]}),t>0&&n.map(e=>(0,V.jsx)(`button`,{type:`button`,onClick:e.onRun,className:B(`ml-3 rounded border bg-background px-2 py-0.5 font-medium hover:bg-muted`,e.destructive?`border-danger/40 text-danger-text`:`text-foreground`),children:e.label},e.label))]})}),ehe=(e,t)=>e.filter(e=>e.available?.(t)??!0),the=({row:e,actions:t})=>{let{open:n,setOpen:r,place:i,button:a,menu:o}=fb();return(0,V.jsxs)(`div`,{className:`relative flex justify-center bg-inherit`,onClick:e=>e.stopPropagation(),children:[(0,V.jsx)(`button`,{ref:a,type:`button`,"aria-label":`Row actions`,"aria-haspopup":`menu`,"aria-expanded":n,onClick:()=>r(!n),className:`inline-flex items-center justify-center rounded p-1 text-faint-foreground hover:bg-muted hover:text-foreground pointer-coarse:size-11`,children:(0,V.jsx)(Xe,{className:`size-4`})}),n&&(0,nr.createPortal)((0,V.jsx)(`ul`,{ref:o,role:`menu`,onClick:e=>e.stopPropagation(),style:i??{visibility:`hidden`},className:`fixed z-50 min-w-36 rounded-md border bg-background py-1 shadow-pop`,children:t.map(t=>(0,V.jsx)(`li`,{role:`none`,children:t.link?(0,V.jsx)(du,{role:`menuitem`,to:t.link(e),onClick:()=>r(!1),className:B(`block w-full px-3 py-1.5 text-left hover:bg-muted`,t.destructive&&`text-danger-text`),children:t.label}):(0,V.jsx)(`button`,{type:`button`,role:`menuitem`,className:B(`block w-full px-3 py-1.5 text-left hover:bg-muted`,t.destructive&&`text-danger-text`),onClick:()=>{r(!1),t.onSelect(e)},children:t.label})},t.label))}),document.body)]})},nhe=e=>52+Math.ceil(String(e).length*1.33)*7,e6=.6,t6=(e,t)=>Math.max(e.minWidth??0,e.width*t),rhe=(e,t)=>e.fixed?`${Math.max(e.minWidth??0,e.width)}px`:`minmax(${t6(e,t)}px, ${e.width}fr)`,n6=(e,t,n=0,r=e6)=>`${t}px ${e.map(e=>rhe(e,r)).join(` `)}${n>0?` ${n}px`:``}`,ihe=(e,t,n=0,r=e6)=>t+n+e.reduce((e,t)=>e+(t.fixed?Math.max(t.minWidth??0,t.width):t6(t,r)),0),ahe=()=>{let e=(0,o.useRef)(null),t=(0,o.useRef)(null),[n,r]=(0,o.useState)({scrolled:!1,more:!1}),i=(0,o.useCallback)(()=>{let t=e.current;if(!t)return;let n={scrolled:t.scrollLeft>1,more:t.scrollLeft+t.clientWidth<t.scrollWidth-1};r(e=>e.scrolled===n.scrolled&&e.more===n.more?e:n)},[]);return{ref:e,attach:(0,o.useCallback)(n=>{if(t.current?.disconnect(),t.current=null,e.current=n,!n)return;let r=new ResizeObserver(i);r.observe(n);for(let e of Array.from(n.children))r.observe(e);t.current=r,i()},[i]),onScroll:i,...n}},ohe=`protobase:pinned:`,she=(e,t)=>`${ohe}${e}:${t}`,che=(e,t)=>zu(()=>{let n=e.getItem(t);if(n===null)return;let r=JSON.parse(n);return Array.isArray(r)&&r.every(e=>typeof e==`string`)?r:void 0},void 0),lhe=(e,t,n)=>zu(()=>e.setItem(t,JSON.stringify(n)),void 0),uhe=(e,t=[])=>{let[n,r]=(0,o.useState)(()=>e?che(localStorage,e):void 0),i=(0,o.useCallback)(t=>{r(t),e&&lhe(localStorage,e,t)},[e]);return[n??t,i]},dhe=e=>{let t=e.findIndex(e=>e.title);return t<0||t>1?[]:e.slice(0,t+1).map(e=>e.id)},fhe=e=>Object.fromEntries(e.map(({id:e,width:t,minWidth:n,fixed:r})=>[e,{width:t,minWidth:n,fixed:r}])),phe=(e,t)=>{let n=e.map(e=>e.id).sort().join(` `),[r,i]=(0,o.useState)(),a=r?.key===n?r:void 0;!a&&t.length>0&&i({key:n,sizes:fhe(Dx(e,t))});let s=a?.sizes;return(0,o.useMemo)(()=>s?e.map(e=>({...e,...s[e.id]})):e,[e,s])},r6=e=>e===`money`||e===`number`||e===`signed`||e===`percent`,mhe=`This column can't be sorted`,hhe=({header:e,pinned:t,sortable:n,onTogglePin:r})=>{let[i,a]=(0,o.useState)(!1),s=(0,o.useRef)(null);return(0,o.useEffect)(()=>{if(!i)return;let e=e=>{(e instanceof KeyboardEvent?e.key===`Escape`:!s.current?.contains(e.target))&&a(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,e),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,e)}},[i]),(0,V.jsxs)(`div`,{ref:s,className:`relative ml-auto shrink-0`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":`${e} column menu`,"aria-haspopup":`menu`,"aria-expanded":i,onClick:()=>a(!i),className:`relative inline-flex size-5 items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:opacity-100 after:absolute after:-inset-2 after:content-[''] md:opacity-0 md:group-hover/cell:opacity-100 aria-expanded:opacity-100`,children:(0,V.jsx)(Xe,{className:`size-3.5`})}),i&&(0,V.jsxs)(`ul`,{role:`menu`,className:`absolute right-0 top-full z-30 mt-1 min-w-32 rounded-md border bg-background py-1 text-body font-normal text-foreground shadow-pop`,children:[!n&&(0,V.jsx)(`li`,{role:`none`,children:(0,V.jsx)(`span`,{role:`menuitem`,"aria-disabled":`true`,className:`block min-h-9 whitespace-nowrap px-3 py-1.5 text-muted-foreground`,children:`This column can't be sorted`})}),(0,V.jsx)(`li`,{role:`none`,children:(0,V.jsx)(`button`,{type:`button`,role:`menuitem`,className:`block min-h-9 w-full whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted`,onClick:()=>{a(!1),r()},children:t?`Unpin`:`Pin to left`})})]})]})},ghe=({sorted:e})=>e===`asc`?(0,V.jsx)(A,{className:`size-3 text-foreground`}):e===`desc`?(0,V.jsx)(S,{className:`size-3 text-foreground`}):(0,V.jsx)(we,{className:`size-3 opacity-0 group-hover/head:opacity-100`}),i6=({spec:e})=>(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`span`,{className:`truncate`,children:e.header}),e.highlight&&(0,V.jsx)(`span`,{className:`rounded bg-primary px-1 text-[10px] font-semibold uppercase leading-4 text-primary-foreground`,children:`New`})]}),_he=({cells:e,specs:t,gutter:n,selectedCount:r,selectable:i,trailing:a,minScale:o,pins:s={},lastPinned:c,scrolled:l,onTogglePin:u,onClearSelection:d})=>(0,V.jsxs)(`div`,{className:`grid h-8 shrink-0 items-center border-b bg-surface text-xs font-medium text-muted-foreground`,style:{gridTemplateColumns:n6(t,n,a,o)},role:`row`,children:[(0,V.jsxs)(`div`,{className:B(`sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3`,l&&!c&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:n},children:[i&&(0,V.jsx)(Fh,{checked:!1,indeterminate:r>0,label:r>0?`Clear selection`:`No rows selected`,disabled:r===0,onChange:d,className:B(r===0&&`opacity-60`)}),n>40&&(0,V.jsx)(`span`,{className:`w-6 text-right text-faint-foreground`,children:`#`})]}),e.map(({spec:e,sorted:t,onSort:n})=>{let r=e.id in s;return(0,V.jsxs)(`div`,{"data-col-id":e.id,style:r?{left:s[e.id]}:void 0,className:B(`group/cell flex h-full min-w-0 items-center`,r&&`sticky z-10 bg-inherit`,r&&l&&e.id===c&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`,e.highlight&&`bg-primary-soft text-primary-text`),children:[e.sortable?(0,V.jsxs)(`button`,{type:`button`,onClick:n,className:B(`group/head flex h-full min-w-0 flex-1 items-center gap-1 pl-3 pr-1 text-left`,r6(e.kind)&&`justify-end`,`hover:text-foreground`,t&&`text-foreground`),children:[(0,V.jsx)(i6,{spec:e}),(0,V.jsx)(ghe,{sorted:t})]}):(0,V.jsx)(`div`,{title:mhe,className:B(`flex h-full min-w-0 flex-1 items-center gap-1 pl-3 pr-1 text-left`,r6(e.kind)&&`justify-end`),children:(0,V.jsx)(i6,{spec:e})}),(0,V.jsx)(`div`,{className:`pr-1.5`,children:(0,V.jsx)(hhe,{header:e.header,pinned:r,sortable:!!e.sortable,onTogglePin:()=>u(e.id)})})]},e.id)}),a?(0,V.jsx)(`div`,{className:`sticky right-0 z-10 h-full bg-inherit`}):null]}),a6=e=>({gridTemplateColumns:n6(e.specs,e.gutter,e.trailing,e.minScale),height:e.height,transform:`translateY(${e.offset}px)`}),o6=(e,t)=>B(`flex h-full min-w-0 items-center overflow-hidden whitespace-nowrap px-3`,r6(e.kind)&&`justify-end`,e.highlight&&`bg-primary-soft/60`,t.pins&&e.id in t.pins&&`sticky z-10 bg-inherit`,t.scrolled&&e.id===t.lastPinned&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),s6=(e,t)=>t&&e.id in t?{left:t[e.id]}:void 0,c6=({width:e,index:t,selectable:n,selected:r,onToggle:i,edge:a})=>(0,V.jsxs)(`div`,{onClick:n?e=>{e.stopPropagation(),i?.()}:void 0,className:B(`sticky left-0 z-10 flex h-full items-center gap-2 bg-inherit pl-3`,n&&`cursor-default`,a&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:e},children:[n&&(0,V.jsx)(Fh,{checked:!!r,label:`Select row ${t+1}`}),e>40&&(0,V.jsx)(`span`,{className:`min-w-6 text-right text-[11px] tabular-nums text-faint-foreground`,children:Bd(t+1)})]}),vhe=(e,t,n)=>({gridTemplateColumns:n6(e.specs,e.gutter,e.trailing,e.minScale),height:e.height,top:e.offset,transform:t===0?void 0:`translateY(${t}px)`,transition:n}),yhe=e=>t=>{t.target.closest(`a`)||e()},l6=({cells:e,selected:t,onToggle:n,onOpen:r,menu:i,handle:a,rowRef:o,dragY:s,transition:c,dragging:l,...u})=>(0,V.jsxs)(`div`,{ref:o,role:`row`,onClick:r&&yhe(r),className:B(`absolute inset-x-0 top-0 grid items-center border-b`,t?`bg-primary-soft`:`bg-background hover:bg-surface`,r&&`cursor-pointer`,l&&`z-30 bg-surface shadow-pop`),style:s===void 0?a6(u):vhe(u,s,c),children:[a?(0,V.jsx)(`div`,{className:B(`sticky left-0 z-10 flex h-full items-center bg-inherit pl-1.5`,u.scrolled&&!u.lastPinned&&`shadow-[1px_0_0_var(--border),4px_0_6px_-2px_rgb(0_0_0/0.12)]`),style:{width:u.gutter},children:a}):(0,V.jsx)(c6,{width:u.gutter,index:u.index,selectable:u.selectable,selected:t,onToggle:n,edge:u.scrolled&&!u.lastPinned}),e.map(({spec:e,content:t,props:n,chosen:r,editing:i,editable:a})=>(0,V.jsx)(`div`,{role:n?`gridcell`:`cell`,...n,className:B(o6(e,u),n&&`scroll-mb-[calc(var(--pb-sticky-bottom,0px)+3rem)] scroll-mt-[calc(var(--pb-sticky-top,0px)+2rem)] outline-none`,a&&!i&&`cursor-default`,r&&`shadow-[inset_0_0_0_2px_var(--primary)]`,i&&`z-30 overflow-visible bg-background px-1`),style:s6(e,u.pins),children:t},e.id)),i&&(0,V.jsx)(`div`,{className:`sticky right-0 z-10 flex h-full items-center justify-center bg-inherit`,children:i})]}),u6=[`w-3/4`,`w-1/2`,`w-2/3`,`w-5/6`,`w-2/5`],bhe=e=>(0,V.jsxs)(`div`,{role:`row`,"aria-busy":!0,className:`absolute inset-x-0 top-0 grid items-center border-b bg-background`,style:a6(e),children:[(0,V.jsx)(c6,{width:e.gutter,index:e.index,selectable:!1,edge:e.scrolled&&!e.lastPinned}),e.specs.map((t,n)=>(0,V.jsx)(`div`,{className:o6(t,e),style:s6(t,e.pins),children:(0,V.jsx)(cu,{className:B(`h-2.5`,u6[(e.index+n)%u6.length],r6(t.kind)&&`ml-auto`)})},t.id))]}),xhe=(e,t)=>{let n=new Map;return{get:t=>n.get(Math.floor(t/e))?.[t%e],hasPage:e=>n.has(e),setPage:(e,r)=>{if(n.delete(e),n.set(e,r),n.size<=t)return;let i=n.keys().next();i.done||n.delete(i.value)},keepOnly:e=>{for(let t of[...n.keys()])e.includes(t)||n.delete(t)},get size(){return n.size}}},d6=(e,t,n)=>{let r=Math.floor(e/n),i=Math.floor(t/n);return Array.from({length:i-r+1},(e,t)=>r+t)},f6=(e,t)=>Math.max(0,Math.min(40,e-t*40)),p6=({total:e,rowAt:t,loadRows:n,revision:r,latencyMs:i},a,s)=>{let c=(0,o.useMemo)(()=>xhe(40,60),[t,n]),[l,u]=(0,o.useState)(0),d=Math.floor(a/40),f=Math.floor(s/40),p=!n&&i===0;(0,o.useEffect)(()=>{if(p)return;let r=d6(d*40,f*40,40).filter(e=>!c.hasPage(e)),a=t=>f6(e,t),o=(e,t)=>{c.setPage(e,t),u(e=>e+1)};if(n){let e=!1;for(let t of r)n(t*40,a(t)).then(n=>{e||o(t,n)});return()=>{e=!0}}let s=r.map(e=>setTimeout(()=>o(e,Array.from({length:a(e)},(n,r)=>t(e*40+r))),i));return()=>s.forEach(clearTimeout)},[c,d,f,i,e,t,n,p]);let m=(0,o.useRef)(r);return(0,o.useEffect)(()=>{if(!n||r===m.current)return;m.current=r;let t=d6(d*40,f*40,40);c.keepOnly(t);for(let r of t.filter(e=>c.hasPage(e)))n(r*40,f6(e,r)).then(e=>{c.setPage(r,e),u(e=>e+1)})},[c,r,n,d,f,e]),(0,o.useCallback)(e=>p?t(e):c.get(e),[c,p,t,l])},She=1e7,m6=(e,t,n)=>{let r=e*t,i=Math.min(r,She);return{rowHeight:t,trueHeight:r,contentHeight:i,scaled:r>i,maxTop:Math.max(0,r-n),maxScroll:Math.max(0,i-n)}},Che=(e,t)=>!e.scaled||t<=0?t:t>=e.maxScroll?e.maxTop+t-e.maxScroll:t/e.maxScroll*e.maxTop,h6=(e,t)=>!e.scaled||t<=0?t:t>=e.maxTop?e.maxScroll+t-e.maxTop:t/e.maxTop*e.maxScroll,whe=(e,t,n,r)=>{let i=t*e.rowHeight;return e.scaled?i-n+r:i},g6=(e,t,n,r,i)=>{let a=Math.min(e,Math.max(0,Math.floor(t/n)-i)),o=Math.min(e-1,Math.floor((t+r)/n)+i);return{first:a,last:Math.max(a-1,o)}},The=e=>{let t=document.scrollingElement??document.documentElement;for(let n=e.parentElement;n&&n!==t&&n!==document.body;n=n.parentElement)if(/auto|scroll/.test(getComputedStyle(n).overflowY))return n;return t},_6=e=>e===(document.scrollingElement??document.documentElement),Ehe=e=>_6(e)?window:e,v6=e=>Number.parseFloat(e)||0,Dhe=e=>{let t=getComputedStyle(e),n=_6(e)?{top:0,height:e.clientHeight}:{top:e.getBoundingClientRect().top+e.clientTop,height:e.clientHeight},r=v6(t.scrollPaddingTop);return{top:n.top+r,height:Math.max(0,n.height-r-v6(t.scrollPaddingBottom))}},y6=6,b6=(e,t,n)=>{let r=m6(t,n,e.height),i=Che(r,e.position);return{geometry:r,top:i,topIndex:Math.floor(Math.max(0,i)/n),...g6(t,i,n,e.height,y6)}},x6=({total:e,rowHeight:t,initialIndex:n,inset:r=0,settle:i,ready:a=!0})=>{let s=(0,o.useRef)(null),c=(0,o.useRef)(null),[l,u]=(0,o.useState)({position:0,height:0}),d=(0,o.useRef)({total:e,rowHeight:t,initialIndex:n,inset:r,ready:a});d.current={total:e,rowHeight:t,initialIndex:n,inset:r,ready:a};let f=(0,o.useCallback)(()=>{let e=s.current;if(!e||!c.current)return;let t=Dhe(c.current),n=d.current.inset;return{position:t.top+n-e.getBoundingClientRect().top,height:Math.max(0,t.height-n)}},[]),p=(0,o.useRef)(l);p.current=l;let m=(0,o.useCallback)(()=>{let e=f();if(!e)return;let t=p.current,{total:n,rowHeight:r}=d.current,i=b6(t,n,r),a=b6(e,n,r),o=!a.geometry.scaled&&i.first===a.first&&i.last===a.last&&i.topIndex===a.topIndex;(t.height!==e.height||t.position!==e.position&&!o)&&(p.current=e,u(e))},[f]),h=(0,o.useRef)({pending:!0,laidOut:!1}),g=(0,o.useCallback)(()=>{if(!h.current.pending||!h.current.laidOut||!d.current.ready)return;let e=f(),t=c.current;if(!e||!t)return;h.current.pending=!1;let{total:n,rowHeight:r,initialIndex:i}=d.current;i>0?t.scrollTop+=h6(m6(n,r,e.height),i*r)-e.position:e.position>0&&(t.scrollTop=0)},[f]);(0,o.useLayoutEffect)(()=>{let e=s.current;if(!e)return;let t=The(e);c.current=t;let n=Ehe(t);n.addEventListener(`scroll`,m,{passive:!0}),window.addEventListener(`resize`,m,{passive:!0});let r=new ResizeObserver(()=>{h.current.laidOut=!0,g(),m()});return r.observe(t),r.observe(e),m(),()=>{n.removeEventListener(`scroll`,m),window.removeEventListener(`resize`,m),r.disconnect(),c.current=null}},[m,g]),(0,o.useLayoutEffect)(()=>{g(),m()});let _=(0,o.useCallback)(e=>{let t=f();if(!t||!c.current)return;let n=m6(d.current.total,d.current.rowHeight,t.height);c.current.scrollTop+=h6(n,e)-t.position,m()},[f,m]),v=b6(l,e,t),y=i?i(v.top):v.top,{first:b,last:x}=i?g6(e,y,t,l.height,y6):v,S=Array.from({length:x-b+1},(e,t)=>({index:b+t,offset:whe(v.geometry,b+t,y,l.position)}));return{ref:s,height:l.height,top:y,geometry:v.geometry,rows:S,first:b,last:x,scrollTo:_}},Ohe=e=>e===`ArrowUp`||e===`ArrowDown`||e===`ArrowLeft`||e===`ArrowRight`,khe=(e,t,n,r)=>{let i=n.indexOf(e.column);if(t===`ArrowUp`)return e.index>0?{...e,index:e.index-1}:void 0;if(t===`ArrowDown`)return e.index<r-1?{...e,index:e.index+1}:void 0;let a=n[t===`ArrowLeft`?i-1:i+1];return i>=0&&a!==void 0?{...e,column:a}:void 0},Ahe=(e,t,n,r)=>{let i=t.indexOf(e);return(r===1?t.slice(i+1):t.slice(0,Math.max(0,i)).reverse()).find(n)},S6=e=>`${e.index}:${e.column}`,jhe=({editor:e,columns:t,total:n,rowAt:r,onOpenRow:i,container:a})=>{let[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(!1),d=(0,o.useRef)(!1),f=(0,o.useRef)(!1);if((0,o.useEffect)(()=>{if(!s||l||!d.current)return;d.current=!1;let e=a.current?.querySelector(`[data-cell="${S6(s)}"]`);e&&(e.focus({preventScroll:!0}),e.scrollIntoView({block:`nearest`,inline:`nearest`}))},[s,l,a]),!e)return;let p=t=>{let n=r(t.index);return n!==void 0&&e.editable(n,t.column)},m=(e,t=!1)=>{d.current=!0,c(e),u(t&&p(e))},h=n=>{if(!s)return;let i=r(s.index),o=n&&i?Ahe(s.column,t,t=>e.editable(i,t),n):void 0,c=!!a.current?.contains(document.activeElement);m(o?{...s,column:o}:s,o!==void 0),d.current=c};return{cell:(n,r,i,a)=>{let o={index:n,column:i},u=s?.index===n&&s.column===i,d=e.editable(r,i),p=u||!s&&n===0&&i===t[0];return{content:u&&l?e.render(r,i,h):a,chosen:u,editing:u&&l,editable:d,props:{"data-cell":S6(o),tabIndex:p?0:-1,"aria-selected":u,onMouseDown:()=>{f.current=u},onFocus:e=>{e.target===e.currentTarget&&!u&&c(o)},onClick:e=>{d&&(e.stopPropagation(),f.current&&!l&&m(o,!0))},onDoubleClick:e=>{d&&(e.stopPropagation(),u&&l||m(o,!0))}}}},onKeyDown:e=>{if(l||!s||!(e.target instanceof HTMLElement)||e.target.dataset.cell!==S6(s))return;let a=e.key===`Tab`?e.shiftKey?`ArrowLeft`:`ArrowRight`:e.key;if(Ohe(a)){let i=khe(s,a,t,n);if(!i&&e.key===`Tab`)return;e.preventDefault(),i&&r(i.index)&&m(i);return}if(e.key===`Enter`||e.key===`F2`){e.preventDefault();let t=r(s.index);p(s)?m(s,!0):e.key===`Enter`&&t&&i?.(t);return}e.key===`Escape`&&c(void 0)}}},Mhe=`To move a row, press Space on its handle, move it with the up and down arrow keys, and press Space again to drop it there. Escape puts it back.`,Nhe=({ids:e,rowAt:t,reorder:n,children:r})=>{let i=Zg(Xg(F_,{activationConstraint:{distance:4}}),Xg(L_,{activationConstraint:{delay:250,tolerance:5}}),Xg(D_,{coordinateGetter:yy})),a=t=>e.indexOf(String(t)),o=e=>{let r=t(a(e));return r?n.label(r):`row`};return(0,V.jsx)(kv,{sensors:i,collisionDetection:i_,onDragEnd:({active:e,over:t})=>{t&&e.id!==t.id&&n.onMove(a(e.id),a(t.id))},accessibility:{announcements:{onDragStart:({active:t})=>`Picked up ${o(t.id)}, row ${a(t.id)+1} of ${e.length}.`,onDragOver:({active:t,over:n})=>n?`${o(t.id)} is over row ${a(n.id)+1} of ${e.length}.`:void 0,onDragEnd:({active:t,over:n})=>n?`${o(t.id)} was dropped at row ${a(n.id)+1} of ${e.length}.`:`${o(t.id)} was put back.`,onDragCancel:({active:e})=>`Moving ${o(e.id)} was cancelled. It is back at row ${a(e.id)+1}.`},screenReaderInstructions:{draggable:Mhe}},children:(0,V.jsx)(sy,{items:e,strategy:ry,children:r})})},Phe=({row:e,label:t,...n})=>{let{attributes:r,listeners:i,setNodeRef:a,setActivatorNodeRef:o,transform:s,transition:c,isDragging:l}=hy({id:e.id}),u=(0,V.jsx)(`button`,{ref:o,type:`button`,"aria-label":`Move ${t}`,...r,...i,onClick:e=>e.stopPropagation(),style:{touchAction:`none`},className:`flex size-7 cursor-grab items-center justify-center rounded text-faint-foreground hover:bg-muted hover:text-foreground focus-visible:text-foreground active:cursor-grabbing pointer-coarse:size-9`,children:(0,V.jsx)(ct,{className:`size-4`})});return(0,V.jsx)(l6,{...n,rowRef:a,handle:u,dragY:s?.y??0,transition:c,dragging:l})},C6=32,w6=({columns:e,source:t,naturalSort:n,initialScrollIndex:r=0,onScrollIndex:i,latencyMs:a=150,sort:s,onSortChange:c,onOpenRow:l,rowLink:u,rowActions:d,cellEditor:f,rowPatches:p,bulkActions:m,pinKey:h,defaultPinned:g,rowNumbers:_=!0,compact:v=!1,selectable:y=!0,reorder:b,fit:x=!1,scroll:S=`own`,className:C})=>{let w=y&&!b,T=v?28:36,E=!Kl(),D=(g??(E?[]:dhe(e))).join(` `),[O,k]=uhe(h,(0,o.useMemo)(()=>D?D.split(` `):[],[D])),A=(0,o.useMemo)(()=>[...O.flatMap(t=>e.find(e=>e.id===t)??[]),...e.filter(e=>!O.includes(e.id))],[e,O]),j=A.slice(0,A.filter(e=>O.includes(e.id)).length).map(e=>e.id),{total:M}=t,[N,ee]=(0,o.useState)(n?[{id:n.columnId,desc:n.direction===`desc`}]:[]),P=s?[{id:s.columnId,desc:s.direction===`desc`}]:N,te=e=>{let t=typeof e==`function`?e(P):e,n=t[0];c&&n&&c({columnId:n.id,direction:n.desc?`desc`:`asc`}),s||ee(t)},[F,ne]=(0,o.useState)({}),re=(0,o.useMemo)(()=>Qme(A),[A]),ie=P[0],I=!!(!s&&n&&ie&&ie.id===n.columnId&&(ie.desc?`desc`:`asc`)!==n.direction),ae=t.rowAt,oe=(0,o.useCallback)(e=>ae(I?M-1-e:e),[ae,I,M]),[se]=(0,o.useState)(r),{ref:L,top:ce,geometry:le,rows:ue,first:de,last:fe}=x6({total:M,rowHeight:T,initialIndex:se,inset:C6}),pe=E||!_?40:nhe(M),me=Math.floor(Math.max(0,ce)/T);(0,o.useEffect)(()=>i?.(me),[me,i]);let he=p6({total:M,rowAt:ae?oe:void 0,loadRows:t.loadRows,revision:t.revision,latencyMs:a},de,fe),ge=(0,o.useCallback)(e=>{let t=he(e),n=t&&p?.get(t.id);return n?{...t,...n}:t},[he,p]),_e=ue.map(({index:e,offset:t})=>({index:e,offset:t,row:ge(e)})),ve=(0,o.useMemo)(()=>_e.flatMap(({row:e})=>e?[e]:[]),[ge,de,fe]),ye=phe(A,ve),be=Yme({features:Zme,columns:re,data:ve,state:{sorting:P,rowSelection:F},onSortingChange:te,onRowSelectionChange:ne,manualSorting:!0,enableMultiSort:!1,enableSortingRemoval:!1,getRowId:e=>e.id}),xe=new Map(be.getRowModel().rows.map(e=>[e.id,e])),Se=Object.keys(F).length,Ce=(0,o.useRef)(new Map);for(let e of be.getRowModel().rows)e.getIsSelected()&&Ce.current.set(e.id,e.original);let we=d&&d.length>0?40:0,Te=E?1:e6,Ee=ahe(),De=(0,o.useRef)(null),Oe=()=>{Ee.onScroll(),De.current&&Ee.ref.current&&(De.current.scrollLeft=Ee.ref.current.scrollLeft)},[ke,Ae]=(0,o.useState)({});(0,o.useLayoutEffect)(()=>{let e=De.current?.querySelector(`[role=row]`);if(!e)return;let t=pe,n={};for(let r of j)n[r]=t,t+=e.querySelector(`[data-col-id="${r}"]`)?.offsetWidth??0;JSON.stringify(ke)!==JSON.stringify(n)&&Ae(n)});let je=j.at(-1),Me=e=>k(O.includes(e)?O.filter(t=>t!==e):[...O,e]),Ne=be.getHeaderGroups().flatMap(e=>e.headers.map(e=>({spec:A.find(t=>t.id===e.column.id),sorted:e.column.getIsSorted(),onSort:t=>e.column.getToggleSortingHandler()?.(t)}))),Pe=(0,o.useRef)(null),Fe=jhe({editor:f,columns:(0,o.useMemo)(()=>A.map(e=>e.id),[A]),total:M,rowAt:ge,onOpenRow:l,container:Pe}),Ie=(A.find(e=>e.title)??A[0])?.id,Le=ihe(ye,pe,we,Te),Re=S===`own`,ze=(0,V.jsx)(`div`,{ref:De,className:B(`sticky z-20 shrink-0 overflow-hidden`,Re?`top-0`:`top-[var(--pb-sticky-top,0px)]`),children:(0,V.jsx)(`div`,{style:{minWidth:Le},children:(0,V.jsx)(_he,{cells:Ne,specs:ye,gutter:pe,trailing:we,minScale:Te,pins:ke,lastPinned:je,scrolled:Ee.scrolled,onTogglePin:Me,selectable:w,selectedCount:Se,onClearSelection:()=>ne({})})})}),Be=_e.map(({index:e,offset:t,row:n})=>{let r={specs:ye,gutter:pe,index:e,offset:t,height:T,selectable:w,trailing:we,minScale:Te,scrolled:Ee.scrolled,pins:ke,lastPinned:je},i=n?xe.get(n.id):void 0;if(!i||!n)return(0,V.jsx)(bhe,{...r},`skeleton-${e}`);let a=we?ehe(d,n):[],o={...r,selected:i.getIsSelected(),onToggle:()=>i.toggleSelected(),onOpen:l?()=>l(n):void 0,menu:a.length>0?(0,V.jsx)(the,{row:n,actions:a}):void 0,cells:i.getAllCells().map(t=>{let r=(0,V.jsx)(be.FlexRender,{cell:t}),i=!!f?.editable(n,t.column.id),a=u&&t.column.id===Ie&&!i?(0,V.jsx)(du,{to:u(n),className:`flex min-w-0 items-center hover:underline`,children:r}):r;return{spec:A.find(e=>e.id===t.column.id),...Fe?Fe.cell(e,n,t.column.id,a):{content:a}}})};return b?(0,V.jsx)(Phe,{...o,row:n,label:b.label(n)},n.id):(0,V.jsx)(l6,{...o},n.id)}),Ve=(0,V.jsx)(`div`,{ref:Ee.attach,onScroll:Oe,className:`overflow-x-auto overflow-y-hidden overscroll-x-contain [-webkit-overflow-scrolling:touch]`,children:(0,V.jsx)(`div`,{ref:L,className:`relative`,style:{minWidth:Le,height:le.contentHeight},children:b?(0,V.jsx)(Nhe,{ids:Array.from({length:M},(e,t)=>ge(t)?.id??`missing-${t}`),rowAt:ge,reorder:b,children:Be}):Be})});return(0,V.jsxs)(`div`,{ref:Pe,role:`grid`,"aria-rowcount":M,onKeyDown:Fe?.onKeyDown,className:B(`flex flex-col rounded-lg border bg-background`,Re?`min-h-0 overflow-hidden`:`overflow-clip`,C),style:x&&Re?{height:C6+M*T+2}:void 0,children:[(0,V.jsxs)(`div`,{className:B(`relative`,Re&&`flex min-h-0 flex-1 flex-col`),children:[Re?(0,V.jsxs)(`div`,{className:`min-h-0 flex-1 overflow-y-auto overflow-x-hidden`,children:[ze,Ve]}):(0,V.jsxs)(V.Fragment,{children:[ze,Ve]}),Ee.more&&(0,V.jsx)(`div`,{"aria-hidden":!0,className:`pointer-events-none absolute inset-y-0 right-0 z-20 w-8 bg-gradient-to-l from-backdrop/15 to-transparent`})]}),!x&&(0,V.jsx)($me,{total:M,className:Re?void 0:`sticky bottom-[var(--pb-sticky-bottom,0px)] z-20`,selectedCount:Se,bulkActions:m?.map(e=>({label:e.label(Se),destructive:e.destructive,onRun:()=>{e.onRun(Object.keys(F).flatMap(e=>Ce.current.get(e)??[])),ne({}),Ce.current.clear()}}))})]})},Fhe=500,T6=async(e,t,n)=>{let r=[],i={},a;do{let o=await e.search(t,{...n,pageSize:Fhe,...a&&{pageToken:a}});r.push(...o.items);for(let[e,t]of Object.entries(o.labels??{}))i[e]={...i[e],...t};a=o.nextPageToken||void 0}while(a);return{items:r,labels:i}},E6=co(),D6=(...e)=>{let t=e.filter(e=>!!e);return t.length===1?t[0]:t.map(e=>`(${e})`).join(` AND `)},O6=e=>e==null?void 0:String(e),Ihe=(e,t,n)=>{let r=new Map;for(let[t,n]of e)r.set(n,(r.get(n)??new Set).add(t));let i=new Map;for(let e of t){let t=e[n],a=O6(typeof t==`object`&&t&&`id`in t?t.id:t);for(let t of a===void 0?[]:r.get(a)??[])i.set(t,[...i.get(t)??[],e])}return i},Lhe=async(e,t,n,r)=>{let i=n.through;if(!i)return r.map(e=>[e,e]);let a=t[i.resource],o=i.key??a?.primaryKey[0];if(!a||o===void 0)throw Error(`The related column ${n.name} names a join resource the app does not have: ${i.resource}`);return(await T6(e,a.name,{filter:D6(qa(E6.in(i.field,r)),i.filter),fields:[i.field,o]})).items.flatMap(e=>{let t=O6(e[i.field]),n=O6(e[o]);return t===void 0||n===void 0?[]:[[t,n]]})},Rhe=async({client:e,resources:t,views:n,load:r,owners:i})=>{let{column:a,fields:o}=r,s=t[a.resource];if(!s)throw Error(`The related column ${a.name} shows a resource the app does not have: ${a.resource}`);if(i.length===0)return new Map;let c=await Lhe(e,t,a,i),l=[...new Set(c.map(([,e])=>e))];if(l.length===0)return new Map;let u=[...new Set([...s.primaryKey,a.field,a.status,...o])],d=u4(t,n,s,u),f=await T6(e,s.name,{filter:D6(qa(E6.in(a.field,l)),a.filter),...a.sort&&{orderBy:a.sort},fields:u,labels:d});return Ihe(c,d4(t,s,u,f.items,f.labels),a.field)},zhe=5e3,Bhe=({queryClient:e,client:t,resources:n,views:r,model:i,columns:a,filter:o,orderBy:s,related:c=[]})=>{let l=c.map(e=>e.column.name).join(`,`),u=e=>c.length===0?W.page(i.name,o,s,40,e):[...W.page(i.name,o,s,40,e),l],d=u4(n,r,i,a),f=rS(r[i.name]),p=async e=>e.nextPageToken===``?e.items.length:e.totalSizeEstimate>zhe?e.totalSizeEstimate:(await t.list(i.name,{filter:o,orderBy:s,pageSize:1,count:`exact`})).totalSize??e.totalSizeEstimate,m=async t=>{if(t===0)return``;let n=u(t-1),r=e.getQueryData(n);if(r)return r.nextPageToken;if(e.getQueryState(n)?.fetchStatus===`fetching`)return(await g(t-1)).nextPageToken},h=async e=>{let l=await m(e);if(e>0&&l===``)return{rows:[],total:0,nextPageToken:``};let u={filter:o,orderBy:s,pageSize:40,labels:d,photos:f},h=l===void 0?await t.seek(i.name,{...u,position:e*40}):await t.list(i.name,{...u,pageToken:l});if(h.items.length===0&&e>0)return{rows:[],total:0,nextPageToken:``};let g=h.items.map(e=>Rx(i,e)),_=d4(n,i,a,iS(i,h.items,h.photos),h.labels),v=await Promise.all(c.map(e=>Rhe({client:t,resources:n,views:r,load:e,owners:g})));return{rows:_.map((e,t)=>({...e,...Object.fromEntries(c.map((e,n)=>[e.column.name,v[n].get(g[t])??[]])),id:g[t]})),total:e===0?await p(h):h.totalSizeEstimate,nextPageToken:h.nextPageToken}},g=t=>e.fetchQuery({queryKey:u(t),staleTime:6e4,queryFn:()=>h(t)});return{page:g,loadRows:async e=>(await g(Math.floor(e/40))).rows}},k6=({resources:e,views:t,model:n,columns:r,filter:i,orderBy:a,related:s})=>{let c=G(),l=Gp(),u=r.join(`,`),d=JSON.stringify(s??[]),f=(0,o.useMemo)(()=>Bhe({queryClient:l,client:c,resources:e,views:t,model:n,columns:r,filter:i,orderBy:a,...s&&{related:s}}),[l,c,e,t,n,u,i,a,d]),p=mh({queryKey:[...W.first(n.name,i,a),u],queryFn:async()=>(await l.invalidateQueries({queryKey:W.pages(n.name,i,a),refetchType:`none`}),f.page(0))});return{source:(0,o.useMemo)(()=>p.data?{total:p.data.total,loadRows:f.loadRows,revision:p.dataUpdatedAt}:void 0,[p.data,p.dataUpdatedAt,f]),error:p.error,isLoading:p.isLoading,page:f.page,key:[...W.first(n.name,i,a),u]}},Vhe=`protobase:embedded-display:`,Hhe=e=>`${Vhe}${e}`,Uhe=(e,t)=>zu(()=>e.getItem(t)??void 0,void 0),Whe=(e,t,n)=>zu(()=>e.setItem(t,n),void 0),Ghe=(e,t,{picked:n,preferred:r})=>{let i=yS(e).map(e=>e.name);return n!==void 0&&i.includes(n)?n:dS(e,t,r!==void 0&&i.includes(r)?r:void 0)},A6=(e,t,n,{resource:r=e.name,...i})=>LS({kind:`list`,resource:r},i,{...FS(e,t,n),display:dS(t,n)}),j6=`inline-flex h-6 items-center rounded-full border border-primary-border bg-primary-soft px-2.5 text-xs font-medium text-primary-text`,M6=({chips:e,className:t})=>(0,V.jsx)(`ul`,{className:B(`flex flex-wrap gap-1.5`,t),"aria-label":`Filters`,children:e.map(e=>(0,V.jsx)(`li`,{className:j6,children:e.label},e.key))}),N6=({chips:e})=>(0,V.jsx)(`span`,{className:`flex flex-wrap gap-1.5`,children:e.map((e,t)=>(0,V.jsxs)(`span`,{className:j6,children:[t>0&&(0,V.jsx)(`span`,{className:`sr-only`,children:`, `}),e.label]},e.key))}),Khe=e=>e.map(e=>e.label).join(`, `),qhe=`inline-flex h-6 items-center gap-1 rounded-full border border-primary-border bg-primary-soft pl-2.5 pr-1.5 text-xs font-medium text-primary-text`,P6=({chips:e,lockedLabels:t=[],onRemove:n,onClear:r,scroll:i})=>e.length===0&&t.length===0?null:(0,V.jsxs)(`div`,{className:i?`flex flex-nowrap items-center gap-1.5 overflow-x-auto pb-1 [&>*]:shrink-0`:`flex flex-wrap items-center gap-1.5`,children:[t.map(e=>(0,V.jsxs)(`span`,{className:`inline-flex h-6 items-center gap-1.5 rounded-full border border-border-strong bg-muted px-2.5 text-xs font-medium text-foreground`,children:[(0,V.jsx)(Pt,{className:`size-3 text-muted-foreground`}),e]},e)),e.map(e=>(0,V.jsxs)(`span`,{className:qhe,children:[e.label,(0,V.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.label}`,onClick:()=>n(e.key),className:`rounded-full p-0.5 hover:bg-primary-border/60`,children:(0,V.jsx)($n,{className:`size-3`})})]},e.key)),e.length>0&&(0,V.jsx)(`button`,{type:`button`,onClick:r,className:`ml-1 text-xs font-medium text-muted-foreground hover:text-foreground`,children:`Clear all`})]}),Jhe=[`7d`,`30d`,`year`],F6={today:`Today`,yesterday:`Yesterday`,"7d":`Last 7 days`,"30d":`Last 30 days`,"90d":`Last 90 days`,month:`This month`,quarter:`This quarter`,year:`This year`},Yhe=({value:e,presets:t=Jhe,onChange:n})=>(0,V.jsx)(`div`,{className:`flex flex-wrap gap-1.5`,children:t.map(t=>{let r=F6[t];return(0,V.jsx)(`button`,{type:`button`,disabled:!r,title:r?void 0:`The server offers the preset "${t}", which this UI does not know`,onClick:()=>n(e===t?void 0:t),className:B(`h-7 rounded-md border px-2.5 text-xs font-medium transition-colors`,!r&&`border-dashed text-danger-text`,e===t?`border-primary-border bg-primary-soft text-primary-text`:`border-border-strong bg-background text-muted-foreground hover:bg-muted`),children:r??`${t} (unsupported)`},t)})}),I6={facets:{},toggles:[]},L6=(e,t,n)=>{let r=e.facets[t]??[],i=r.includes(n)?r.filter(e=>e!==n):[...r,n];return{...e,facets:{...e.facets,[t]:i}}},R6=(e,t)=>({...e,toggles:e.toggles.includes(t)?e.toggles.filter(e=>e!==t):[...e.toggles,t]}),z6=(e,t,n)=>{let{[t]:r,...i}=e.ranges??{};return{...e,ranges:n?{...i,[t]:n}:i}},B6=(e,t)=>e.options.find(e=>e.value===t)?.label??e.labels?.[t]??t,V6=(e,t)=>{let n=e.facets.flatMap(e=>(t.facets[e.id]??[]).map(t=>({key:`facet:${e.id}:${t}`,label:`${e.label}: ${B6(e,t)}`}))),r=(e.ranges??[]).flatMap(e=>{let n=t.ranges?.[e.id];return n?[{key:`range:${e.id}`,label:`${e.label}: ${e.format(n[0])} – ${e.format(n[1])}`}]:[]}),i=t.date?[{key:`date`,label:F6[t.date]??t.date}]:[],a=t.toggles.map(t=>({key:`toggle:${t}`,label:e.toggles?.find(e=>e.id===t)?.label??t}));return[...n,...r,...i,...a]},H6=(e,t)=>{if(t===`date`)return{...e,date:void 0};let[n,r,i]=t.split(`:`);if(n===`range`)return z6(e,r,void 0);if(n===`toggle`)return R6(e,r);if(n===`facet`)return L6(e,r,i);throw Error(`Unknown filter chip key: ${t}`)},U6=(e,t)=>e.toLowerCase().includes(t.trim().toLowerCase()),Xhe=(e,t)=>e.onSearch?e.options:e.options.filter(e=>U6(e.label,t)),Zhe=(e,t,n)=>t===0?-1:n===`ArrowDown`?e<0?0:(e+1)%t:e<0?t-1:(e-1+t)%t,Qhe=({config:e,selected:t,onToggle:n,inline:r=!1})=>{let i=(0,o.useId)(),a=(0,o.useRef)(null),[s,c]=(0,o.useState)(``),[l,u]=(0,o.useState)(!1),[d,f]=(0,o.useState)(-1),p=r||l,m=Xhe(e,s),h=(0,o.useRef)(e.onSearch);h.current=e.onSearch,(0,o.useEffect)(()=>()=>h.current?.(``),[]);let g=t=>{c(t),f(-1),e.onSearch?.(t)};return(0,V.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[(0,V.jsxs)(`div`,{className:`flex min-h-8 cursor-text flex-wrap items-center gap-1 rounded-md border border-border-strong bg-background px-2 py-1 shadow-sm focus-within:border-primary focus-within:ring-2 focus-within:ring-primary/20`,onClick:()=>a.current?.focus(),children:[(0,V.jsx)(pn,{className:`size-3.5 shrink-0 text-muted-foreground`}),t.map(t=>(0,V.jsxs)(`span`,{className:`inline-flex h-5 max-w-full items-center gap-0.5 rounded bg-primary-soft pl-1.5 pr-0.5 text-xs font-medium text-primary-text`,children:[(0,V.jsx)(`span`,{className:`truncate`,children:B6(e,t)}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Remove ${B6(e,t)}`,className:`rounded p-0.5 hover:bg-primary-border/60`,onMouseDown:e=>e.preventDefault(),onClick:()=>n(t),children:(0,V.jsx)($n,{className:`size-3`})})]},t)),(0,V.jsx)(`input`,{ref:a,autoFocus:r,role:`combobox`,"aria-label":e.label,"aria-expanded":p,"aria-controls":`${i}-options`,"aria-autocomplete":`list`,"aria-activedescendant":m[d]?`${i}-${d}`:void 0,placeholder:t.length>0?``:`Search ${e.label.toLowerCase()}`,className:`h-6 min-w-16 flex-1 bg-transparent text-foreground outline-none placeholder:text-faint-foreground`,value:s,onChange:e=>g(e.target.value),onKeyDown:e=>{if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault(),f(Zhe(d,m.length,e.key));return}if(e.key===`Enter`&&m[d]){e.preventDefault(),n(m[d].value);return}if(e.key===`Backspace`&&s===``&&t.length>0){n(t[t.length-1]);return}e.key===`Escape`&&s!==``&&(e.stopPropagation(),g(``))},onFocus:()=>u(!0),onBlur:()=>{u(!1),f(-1),!r&&s!==``&&g(``)}})]}),p&&(0,V.jsxs)(`ul`,{id:`${i}-options`,role:`listbox`,"aria-label":e.label,"aria-multiselectable":!0,className:B(`flex max-h-60 flex-col gap-px overflow-y-auto`,!r&&`rounded-md border bg-background p-1 shadow-sm`),children:[m.map((e,r)=>{let a=t.includes(e.value);return(0,V.jsxs)(`li`,{id:`${i}-${r}`,role:`option`,"aria-selected":a,tabIndex:-1,className:B(`flex cursor-pointer items-center gap-2 rounded px-1.5 py-1 hover:bg-muted`,r===d&&`bg-muted`),onMouseDown:e=>e.preventDefault(),onClick:()=>n(e.value),children:[(0,V.jsx)(`span`,{className:B(`inline-flex size-4 shrink-0 items-center justify-center rounded border`,a?`border-primary bg-primary text-primary-foreground`:`border-border-strong bg-background`),children:a&&(0,V.jsx)(ge,{className:`size-3`,strokeWidth:3})}),(0,V.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.count!==void 0&&(0,V.jsx)(`span`,{className:`text-xs tabular-nums text-faint-foreground`,children:Bd(e.count)})]},e.value)}),m.length===0&&(0,V.jsx)(`li`,{className:`px-1.5 py-1 text-xs text-faint-foreground`,children:`No matches`})]})]})},$he=({config:e,selected:t,onToggle:n})=>{let[r,i]=(0,o.useState)(``),a=e.options.filter(e=>U6(e.label,r));return(0,V.jsxs)(`div`,{className:`flex flex-col gap-1`,children:[e.searchable&&(0,V.jsx)(sd,{wrapperClassName:`mb-1 h-7`,leading:(0,V.jsx)(pn,{className:`size-3.5`}),placeholder:`Search ${e.label.toLowerCase()}`,value:r,onChange:e=>i(e.target.value)}),a.map(e=>(0,V.jsxs)(`label`,{className:`flex cursor-pointer items-center gap-2 rounded px-1 py-1 hover:bg-muted`,children:[(0,V.jsx)(Fh,{checked:t.includes(e.value),onChange:()=>n(e.value),label:e.label}),(0,V.jsx)(`span`,{className:`flex-1 truncate`,children:e.label}),e.count!==void 0&&(0,V.jsx)(`span`,{className:`text-xs tabular-nums text-faint-foreground`,children:Bd(e.count)})]},e.value)),a.length===0&&(0,V.jsx)(`span`,{className:`px-1 py-1 text-xs text-faint-foreground`,children:`No matches`})]})},W6=({label:e,activeCount:t,width:n=240,defaultOpen:r=!1,children:i})=>{let[a,s]=(0,o.useState)(r),[c,l]=(0,o.useState)(!1),u=(0,o.useRef)(null);return(0,o.useLayoutEffect)(()=>{a&&u.current&&l(u.current.getBoundingClientRect().left+n>document.documentElement.clientWidth)},[a,n]),(0,o.useEffect)(()=>{if(!a)return;let e=e=>{e.target instanceof Node&&!u.current?.contains(e.target)&&s(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[a]),(0,V.jsxs)(`div`,{ref:u,className:`relative`,children:[(0,V.jsxs)(`button`,{type:`button`,"aria-expanded":a,onClick:()=>s(!a),className:B(`inline-flex h-8 items-center gap-1.5 rounded-md border bg-background px-2.5 font-medium shadow-sm transition-colors hover:bg-muted`,t>0?`border-primary-border text-primary-text`:`border-border-strong text-foreground`),children:[e,t>0&&(0,V.jsx)(`span`,{className:`rounded-full bg-primary px-1.5 text-[11px] leading-4 text-primary-foreground`,children:t}),(0,V.jsx)(ve,{className:`size-3.5 text-muted-foreground`})]}),a&&(0,V.jsx)(`div`,{className:B(`absolute top-full z-30 mt-1.5 rounded-lg border bg-background p-3 shadow-pop`,c?`right-0`:`left-0`),style:{width:n},children:i})]})},G6=({title:e,children:t})=>(0,V.jsxs)(`section`,{className:`flex flex-col gap-2 border-b py-3 last:border-b-0`,children:[(0,V.jsx)(`h3`,{className:`text-xs font-semibold uppercase tracking-wide text-muted-foreground`,children:e}),t]}),K6=(e,t)=>{let[n,r]=(0,o.useState)(e);return(0,o.useEffect)(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n},ege=(e,t,n,r,i)=>{let a=n+(r-n)*e/t;return n+(r-n)*(e+1)/t>i[0]&&a<i[1]},q6=(e,t,n)=>n===t?0:(e-t)/(n-t),tge=(e,t,n)=>t===0?[Math.min(n,e[1]),e[1]]:[e[0],Math.max(n,e[0])],nge=1e3,rge=({config:e,value:t,onChange:n})=>{let{min:r,max:i,step:a,histogram:s,format:c}=e,[l,u]=(0,o.useState)(),d=l??t??[r,i],f=Math.max(...s),p=()=>{l&&(u(void 0),n(l[0]===r&&l[1]===i?void 0:l))},m=K6(l,nge);return(0,o.useEffect)(()=>{m&&p()},[m]),(0,V.jsxs)(`div`,{className:`w-full`,children:[(0,V.jsxs)(`div`,{className:`px-[7px]`,children:[s.length>0&&(0,V.jsx)(`div`,{className:`mb-1 flex h-12 items-end gap-0.5`,children:s.map((e,t)=>(0,V.jsx)(`span`,{className:B(`flex-1 rounded-t-sm`,ege(t,s.length,r,i,d)?`bg-primary/70`:`bg-border`),style:{height:`${Math.max(6,e/f*100)}%`}},t))}),(0,V.jsxs)(`div`,{className:`relative h-4`,children:[(0,V.jsx)(`span`,{className:`absolute inset-x-0 top-1/2 h-1 -translate-y-1/2 rounded-full bg-border`}),(0,V.jsx)(`span`,{className:`absolute top-1/2 h-1 -translate-y-1/2 rounded-full bg-primary`,style:{left:`${q6(d[0],r,i)*100}%`,right:`${100-q6(d[1],r,i)*100}%`}})]})]}),(0,V.jsx)(`div`,{className:`relative -mt-4 h-4`,children:[0,1].map(t=>(0,V.jsx)(`input`,{type:`range`,className:`pb-range`,"aria-label":`${e.label} ${t===0?`minimum`:`maximum`}`,min:r,max:i,step:a,value:d[t],onChange:e=>u(tge(d,t,Number(e.target.value))),onPointerUp:p,onTouchEnd:p,onBlur:p},t))}),(0,V.jsxs)(`div`,{className:`mt-2 flex justify-between text-xs tabular-nums text-muted-foreground`,children:[(0,V.jsx)(`span`,{children:c(d[0])}),(0,V.jsx)(`span`,{children:c(d[1])})]})]})},J6=({label:e,checked:t,onChange:n})=>(0,V.jsxs)(`label`,{className:`flex cursor-pointer items-center justify-between gap-3 py-1`,children:[(0,V.jsx)(`span`,{children:e}),(0,V.jsx)(ox,{checked:t,onChange:n,label:e})]}),Y6=(e,t)=>e.some(e=>e.length>0)||!!t,X6=({groups:e,trailing:t})=>{if(!Y6(e,t))return null;let n=e.filter(e=>e.length>0);return(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n.map((e,t)=>(0,V.jsxs)(o.Fragment,{children:[t>0&&(0,V.jsx)(`span`,{className:`mx-1 h-5 w-px bg-border`}),e]},t)),t&&(0,V.jsx)(`div`,{className:`flex min-w-32 flex-1 justify-end`,children:t})]})},ige=(e,t,n)=>{let[r,i]=(0,o.useState)(t??I6);return[e??r,e=>{i(e),n?.(e)}]},Z6=({config:e,layout:t,value:n,defaultValue:r,onChange:i,lockedLabels:a,defaultOpenMenu:s,fullWidth:c,leading:l,trailing:u})=>{let[d,f]=ige(n,r,i),p=V6(e,d),m=(0,V.jsx)(P6,{chips:p,lockedLabels:a,onRemove:e=>f(H6(d,e)),onClear:()=>f(I6)}),h=(e,t=!1)=>{let n=d.facets[e.id]??[],r=t=>f(L6(d,e.id,t));return e.combobox?(0,V.jsx)(Qhe,{config:e,selected:n,onToggle:r,inline:t}):(0,V.jsx)($he,{config:e,selected:n,onToggle:r})},g=e.ranges??[],_=e=>(0,V.jsx)(rge,{config:e,value:d.ranges?.[e.id],onChange:t=>f(z6(d,e.id,t))}),v=e.datePresets&&(0,V.jsx)(Yhe,{value:d.date,presets:Array.isArray(e.datePresets)?e.datePresets:void 0,onChange:e=>f({...d,date:e})}),y=(e.toggles??[]).map(e=>(0,V.jsx)(J6,{label:e.label,checked:d.toggles.includes(e.id),onChange:()=>f(R6(d,e.id))},e.id));if(t===`panel`)return(0,V.jsxs)(`aside`,{className:c?`flex w-full flex-col gap-1`:`flex w-64 shrink-0 flex-col gap-1 overflow-y-auto rounded-lg border bg-background px-4 py-3`,children:[(0,V.jsx)(`div`,{className:`flex items-center justify-between pb-1`,children:(0,V.jsx)(`h2`,{className:`font-semibold`,children:`Filters`})}),(p.length>0||(a?.length??0)>0)&&(0,V.jsx)(`div`,{className:`border-b pb-3`,children:m}),l,e.facets.map(e=>(0,V.jsx)(G6,{title:e.label,children:h(e)},e.id)),g.map(e=>(0,V.jsx)(G6,{title:e.label,children:_(e)},e.id)),v&&(0,V.jsx)(G6,{title:`Date`,children:v}),y.length>0&&(0,V.jsx)(G6,{title:`Show only`,children:y})]});let b=[...e.facets.map(e=>(0,V.jsx)(W6,{label:e.label,activeCount:(d.facets[e.id]??[]).length,width:e.combobox?280:void 0,defaultOpen:s===e.id,children:h(e,!0)},e.id)),...g.map(e=>(0,V.jsx)(W6,{label:e.label,activeCount:+!!d.ranges?.[e.id],width:280,defaultOpen:s===e.id,children:_(e)},`range:${e.id}`)),...v?[(0,V.jsx)(o.Fragment,{children:v},`date`)]:[]],x=(e.toggles??[]).map(e=>(0,V.jsx)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:(0,V.jsx)(J6,{label:e.label,checked:d.toggles.includes(e.id),onChange:()=>f(R6(d,e.id))})},e.id)),S=[l?[(0,V.jsx)(o.Fragment,{children:l},`leading`)]:[],b,x];return!Y6(S,u)&&p.length===0&&!a?.length?null:(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsx)(X6,{groups:S,trailing:u}),m]})},Q6=co(),$6={start:0,end:0},e8={"7d":{amount:7,unit:`d`},"30d":{amount:30,unit:`d`},"90d":{amount:90,unit:`d`}},age=e=>new Date(e).toISOString().replace(`.000Z`,`Z`),t8=(e,t,n)=>{let r=Xd(t.getTime(),n),[i,a]=[Number(r.slice(0,4)),Number(r.slice(5,7))-1],o=e=>new Date(e).toISOString().slice(0,10);return e===`year`?o(Date.UTC(i,0,1)):e===`quarter`?o(Date.UTC(i,Math.floor(a/3)*3,1)):e===`month`?o(Date.UTC(i,a,1)):e===`yesterday`?o(Date.parse(`${r}T00:00:00Z`)-864e5):r},n8=[`year`,`quarter`,`month`,`yesterday`,`today`],r8=(e,t,n)=>t===`date`?e:age(Qd(e,n)),i8=(e,t,n)=>t===`date`?{kind:`string`,value:r8(e,t,n),span:$6}:{kind:`timestamp`,value:r8(e,t,n),span:$6},oge=(e,t,n,r,i)=>{if(t in e8)return[Q6.gte(e,Q6.ago(t))];let a=Q6.gte(e,i8(t8(t,n,i),r,i));return t===`yesterday`?[a,Q6.lt(e,i8(t8(`today`,n,i),r,i))]:[a]},sge=(e,t,n=new Date,r=Wd())=>{let i=e.facets.flatMap(e=>{let n=t.facets[e.id]??[];if(n.length===0)return[];if(e.flags){let t=e.options.filter(e=>n.includes(e.value)).map(e=>Q6.eq(e.value,!0));return t.length===0?[]:[t.length===1?t[0]:Q6.or(...t)]}return[n.length===1?Q6.eq(e.id,n[0]):Q6.in(e.id,n)]}),a=(e.ranges??[]).flatMap(e=>{let n=t.ranges?.[e.id];return n?[Q6.gte(e.id,n[0]),Q6.lte(e.id,n[1])]:[]}),o=e.dateField&&t.date?oge(e.dateField,t.date,n,e.dateKind,r):[],s=(e.toggles??[]).filter(e=>t.toggles.includes(e.id)).map(e=>Q6.eq(e.id,!0));return[...i,...a,...o,...s]},cge=e=>e.length===0?``:qa(Q6.and(...e)),a8=(e,t,n=[],r=new Date,i=Wd())=>cge([...sge(e,t,r,i),...n]),o8=e=>e.kind===`and`?e.args.flatMap(o8):[e],s8=e=>e.field.path.join(`.`),lge=e=>e.kind===`compare`&&e.op===`=`&&e.value.kind===`boolean`&&e.value.value,uge=(e,t)=>{let n=e.kind===`or`?e.args:[e];if(!n.every(lge))return;let r=n.map(s8),i=t.get(r[0]);return i!==void 0&&r.every(e=>t.get(e)===i)?{group:i,fields:r}:void 0},c8=e=>e.kind===`number`?String(e.raw):e.kind===`string`?String(e.value):void 0,l8=(e,t,n)=>{let r=e.value;if(r.kind===`now`&&r.offset?.sign===`-`){let{amount:e,unit:t}=r.offset.duration;return Object.entries(e8).find(([,n])=>n.amount===e&&n.unit===t)?.[0]}if(r.kind===`timestamp`)return n8.find(e=>r8(t8(e,t,n),`timestamp`,n)===r.value);if(r.kind===`string`)return n8.find(e=>t8(e,t,n)===r.value)},u8=(e,t,n=new Date,r=Wd())=>{let i=Sa(t);if(!i.ok)return{ok:!1,errors:i.errors};let a={facets:{},toggles:[]},o=[],s=new Set(e.facets.filter(e=>!e.flags).map(e=>e.id)),c=new Map(e.facets.filter(e=>e.flags).flatMap(e=>e.options.map(t=>[t.value,e.id]))),l=new Set((e.toggles??[]).map(e=>e.id)),u=new Set((e.ranges??[]).map(e=>e.id)),d=new Map,f,p;for(let t of i.ast?o8(i.ast):[]){let i=uge(t,c);if(i&&!a.facets[i.group])a.facets[i.group]=i.fields;else if(t.kind===`compare`&&s.has(s8(t))&&t.op===`=`&&c8(t.value)!==void 0)a.facets[s8(t)]=[...a.facets[s8(t)]??[],c8(t.value)];else if(t.kind===`in`&&s.has(s8(t))&&t.values.every(e=>c8(e)!==void 0))a.facets[s8(t)]=[...a.facets[s8(t)]??[],...t.values.map(e=>c8(e))];else if(t.kind===`compare`&&e.dateField===s8(t)&&t.op===`>=`&&l8(t,n,r)&&!a.date)a.date=l8(t,n,r),f=t;else if(t.kind===`compare`&&e.dateField===s8(t)&&t.op===`<`&&(t.value.kind===`timestamp`||t.value.kind===`string`)&&t.value.value===r8(t8(`today`,n,r),t.value.kind===`string`?`date`:`timestamp`,r))p=t;else if(t.kind===`compare`&&l.has(s8(t))&&t.op===`=`&&t.value.kind===`boolean`&&t.value.value)a.toggles.push(s8(t));else if(t.kind===`compare`&&u.has(s8(t))&&(t.op===`>=`||t.op===`<=`)&&t.value.kind===`number`){let e=d.get(s8(t))??{clauses:[]};t.op===`>=`?e.low=t.value.value:e.high=t.value.value,e.clauses.push(t),d.set(s8(t),e)}else o.push(t)}a.date===`yesterday`&&!p&&(o.push(f),a.date=void 0),p&&a.date!==`yesterday`&&o.push(p);for(let[e,t]of d)t.low!==void 0&&t.high!==void 0?a.ranges={...a.ranges,[e]:[t.low,t.high]}:o.push(...t.clauses);return{ok:!0,state:a,extras:o}},dge=[`integer`,`bigint`,`decimal`],fge=(e,t)=>{let n=e?.fields[t]?.type;return n!==void 0&&dge.includes(n)},d8=(e,t)=>e.kind===`range`||e.kind===`facets`&&fge(t,e.field),pge=e=>({id:e,label:e,min:0,max:0,step:1,histogram:[],format:String}),f8=(e,t)=>{let n=e?.filters??[],r=n.find(e=>e.kind===`dateRange`);return{facets:n.flatMap(e=>e.kind===`facets`&&!d8(e,t)?[{id:e.field,label:e.field,options:[],searchable:e.search,...t?.fields[e.field]?.type===`relation`&&{combobox:!0}}]:e.kind===`flags`?[{id:e.fields.join(`|`),label:e.label,options:e.fields.map(e=>({value:e,label:e,count:0})),flags:!0}]:[]),ranges:n.flatMap(e=>e.kind!==`flags`&&d8(e,t)?[pge(e.field)]:[]),...r&&{dateField:r.field,dateKind:t?.fields[r.field]?.type===`date`?`date`:`timestamp`,...r.presets.length>0&&{datePresets:r.presets}},toggles:n.flatMap(e=>e.kind===`toggle`?[{id:e.field,label:e.field}]:[])}},p8=(e,t)=>(e?.filters??[]).some(e=>e.kind===`range`&&e.field===t&&e.histogram),m8=(e,t)=>{let n=e?.fields[t],r=n?.suffix??``;return e=>`${n?.prefix===`€`?Rd(e*100).replace(`.00`,``):String(e)}${r}`},h8=co(),mge={start:0,end:0},hge=(e,t,n)=>{let r=u8(f8(t,e),n);return r.ok?Object.fromEntries(Object.entries(r.state.facets).filter(([t,n])=>e.fields[t]?.type===`relation`&&n.length>0)):{}},gge=(e,t,n)=>{let r=e=>t?.fields[e]?.label??K(e),i=f8(t,e);return{...i,facets:i.facets.map(i=>{if(i.flags)return{...i,options:i.options.map(e=>({...e,label:r(e.value)}))};let a=e.fields[i.id]?.enumValues??[],o=e.fields[i.id]?.type===`enum`?Object.fromEntries(a.map(e=>[e,rs(e,t?.fields[i.id]?.valueLabels)])):n[i.id]??{};return{...i,label:r(i.id),labels:o}}),ranges:(i.ranges??[]).map(e=>({...e,label:r(e.id),format:m8(t,e.id)})),toggles:i.toggles?.map(e=>({...e,label:r(e.id)}))}},g8=(e,t,n,r={})=>{let i=gge(e,t,r),a=u8(i,n);if(!a.ok)return[{key:`unreadable`,label:`A filter that cannot be read`}];let o=a.extras.map((e,t)=>({key:`extra:${t}`,label:e.kind===`search`?`"${e.text}"`:qa(e)}));return[...V6(i,a.state),...o]},_ge=e=>Object.fromEntries(e.facets.filter(e=>!e.flags).map(e=>[e.id,{...e.labels,...Object.fromEntries(e.options.map(e=>[e.value,e.label]))}])),vge=(e,t,n)=>{if(typeof n!=`string`||n===``)return e;let r=h8.gt(t,{kind:`timestamp`,value:new Date(n).toISOString(),span:mge}),i=Sa(e);if(!i.ok)throw Error(`The saved filter cannot be read: ${i.errors.map(e=>e.message).join(`; `)}`);return qa(i.ast?h8.and(i.ast,r):r)},yge=(e,t)=>typeof t!=`string`||t===``?!0:typeof e!=`string`||e===``?!1:new Date(e).getTime()>new Date(t).getTime(),_8=(e,t)=>{let n=G(),r=Gp(),{resources:i,views:a}=J(),o=a[e.name],s=Object.entries(hge(e,o,t)),c=fh({queries:s.map(([t,o])=>{let s=i[e.fields[t].relation.resource];return{queryKey:W.labels(`chips:${e.name}.${t}`,o.join(`,`)),enabled:s!==void 0,queryFn:async()=>Object.fromEntries(await c4(r,n,s,o,a[s.name]))}})});return g8(e,o,t,Object.fromEntries(s.flatMap(([e],t)=>c[t]?.data?[[e,c[t].data]]:[])))},bge=(e,t)=>({record:Object.fromEntries(Object.entries(t).filter(([t])=>Object.hasOwn(e.fields,t))),etag:typeof t.etag==`string`?t.etag:``,...typeof t.permissions==`object`&&t.permissions!==null&&{permissions:t.permissions}}),v8=e=>{let t=Gp();return(0,o.useCallback)(n=>t.setQueryData(W.recordPreview(e.name,Ao(zx(e,n))),bge(e,n)),[t,e])},y8={wallet:dee,"file-text":ot,send:lee,ruler:see,bed:ee,bath:M,house:nee,"door-open":He,"land-plot":yt,leaf:wt,tag:Fn,key:_t,calendar:fe,heart:ut,bell:te,bookmark:se,"external-link":Qe},b8=e=>e!==void 0&&Object.hasOwn(y8,e)?y8[e]:void 0,x8=({benefits:e})=>e&&e.length>0?(0,V.jsx)(`ul`,{className:`flex flex-col gap-2 text-left`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`flex items-start gap-2`,children:[(0,V.jsx)(ge,{className:`mt-0.5 size-4 shrink-0 text-primary`,"aria-hidden":!0}),e]},e))}):null,S8=({prompt:e})=>{let{canSignUp:t}=H(),{link:n}=Ih(),r=Cf({variant:`primary`}),i=e.signUp?(0,V.jsx)(`a`,{href:e.signUp.href,target:`_blank`,rel:`noreferrer`,className:r,children:e.signUp.label}):t&&(0,V.jsx)(du,{to:n(`sign-up`),className:r,children:`Create an account`});return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(du,{to:n(),className:i?Cf():r,children:`Sign in`}),i]})},C8=e=>{let{prompt:t}=e,n=(0,o.useId)();if(e.as===`dialog`)return(0,V.jsx)(dT,{title:t.title,description:t.description,open:e.open,onClose:e.onClose,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:e.onClose,children:`Not now`}),(0,V.jsx)(S8,{prompt:t})]}),children:(0,V.jsx)(x8,{benefits:t.benefits})});let r=b8(t.icon)??It;return(0,V.jsxs)(`section`,{"aria-labelledby":n,className:`mx-auto flex w-full max-w-md flex-col items-center gap-4 px-5 py-10 text-center sm:py-16`,children:[(0,V.jsx)(`span`,{className:`flex size-12 items-center justify-center rounded-full bg-primary/10 text-primary`,children:(0,V.jsx)(r,{className:`size-6`,"aria-hidden":!0})}),(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsx)(`h1`,{id:n,className:`text-lg font-semibold`,children:t.title}),(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:t.description})]}),(0,V.jsx)(x8,{benefits:t.benefits}),(0,V.jsx)(`div`,{className:`mt-2 flex w-full flex-col-reverse gap-2 sm:w-auto sm:flex-row sm:justify-center [&>*]:min-h-11 sm:[&>*]:min-h-0`,children:(0,V.jsx)(S8,{prompt:t})})]})},xge=co(),w8=e=>{if(typeof e==`string`||typeof e==`number`)return e;if(e&&typeof e==`object`&&`id`in e)return w8(e.id)},Sge=(e,t,n)=>n.flatMap(n=>{let r=w8(n[t]);return r===void 0?[]:[{key:Ao(zx(e,n)),target:r}]}),Cge=(e,t)=>e.find(e=>Ao(e.target)===t),wge=(e,t)=>[...e,{key:``,target:t}],Tge=(e,t)=>e.filter(e=>Ao(e.target)!==t),T8=(e,t)=>{let[n]=e.primaryKey;if(e.primaryKey.length!==1||n===void 0)throw Error(`${e.name} has a composite key, so its saved records cannot be listed`);let r=[...new Set(t.map(e=>e.target))];return r.length===0?void 0:xge.in(n,r)},E8=(e,t)=>W.list(e,``,``,500,`saved:${t}`),D8=(e,t,n)=>{let r=G(),i=J().resources[e];return mh({queryKey:E8(e,t),enabled:n&&i!==void 0,queryFn:async()=>{let n=[],a;do{let o=await r.list(e,{pageSize:500,fields:[...i.primaryKey,t],...a&&{pageToken:a}});n.push(...o.items),a=o.nextPageToken||void 0}while(a);return Sge(i,t,n)}})},Ege=e=>e instanceof Error?e.message:`Something went wrong`,Dge=(e,t,n)=>{let r=J(),i=G(),a=Gp(),o=Qy(),s=qT(),{resource:c,field:l}=e,u=r.permissions[c],d=r.resources[c]!==void 0&&u!==void 0&&MT(u,`create`)&&MT(u,`delete`),f=r.signIn?.[c]?.signIn,p=D8(c,l,d),m=p.data&&Cge(p.data,t),h=E8(c,l),g=hh({mutationFn:async e=>{e?await i.remove(c,e.key):await i.create(c,{[l]:n})},onMutate:async e=>{await a.cancelQueries({queryKey:h,exact:!0});let r=a.getQueryData(h);return a.setQueryData(h,(r=[])=>e?Tge(r,t):wge(r,n)),{before:r}},onError:(e,t,n)=>{a.setQueryData(h,n?.before),o.show({state:`error`,title:t?`Could not take it off`:`Could not save it`,description:Ege(e)})},onSettled:()=>s(c)});return{mode:d?`save`:f?`sign-in`:void 0,prompt:f,saved:m!==void 0,ready:p.data!==void 0&&!g.isPending,toggle:()=>g.mutate(m)}},Oge=({favorite:e,recordKey:t,target:n,className:r})=>{let i=Dge(e,t,n),[a,s]=(0,o.useState)(!1);if(!i.mode)return null;let c=e.label??`Favorite`,l=B(`absolute right-2 top-2 flex size-8 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,r);return i.mode===`sign-in`?(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":c,"aria-haspopup":`dialog`,className:l,onClick:()=>s(!0),children:(0,V.jsx)(ut,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsx)(C8,{as:`dialog`,prompt:i.prompt,open:a,onClose:()=>s(!1)})]}):(0,V.jsx)(`button`,{type:`button`,"aria-label":c,"aria-pressed":i.saved,"aria-disabled":!i.ready,className:l,onClick:()=>i.ready&&i.toggle(),children:(0,V.jsx)(ut,{className:B(`size-4`,i.saved&&`fill-current text-danger`),"aria-hidden":!0})})},O8=6,kge=(e,t,n)=>{let r=e.bottom+O8;return{top:r+t.height>n.height-O8?Math.max(O8,e.top-O8-t.height):r,left:Math.max(O8,Math.min(e.left,n.width-O8-t.width))}},k8=(e,t)=>{let n=uS(e).find(e=>e.kind===`cards`);if(!n)return{kind:`cards`,name:`dot`,badge:t};let{photos:r,favorite:i,dots:a,...o}=n;return o},Age=(e,t,n,r)=>(e?.list?.relatedColumns??[]).filter(e=>r.includes(e.name)).flatMap(e=>{let r=t[e.resource];return r?[{column:e,fields:ES(r,n[r.name],k8(n[r.name],e.status))}]:[]}),jge=(e,{values:t,label:n,singular:r,plural:i})=>{if(e.length===0)return`No ${i}`;let a=new Map;for(let t of e)t!=null&&a.set(String(t),(a.get(String(t))??0)+1);let o=[...t,...[...a.keys()].filter(e=>!t.includes(e))].filter(e=>a.has(e)).map(e=>`${a.get(e)} ${n(e)}`),s=`${e.length} ${e.length===1?r:i}`;return o.length===0?s:`${s}: ${o.join(`, `)}`},A8=`flex shrink-0 items-center justify-center rounded-full p-0.5 pointer-coarse:p-1.5`,j8=`size-2.5 rounded-full`,M8=`flex min-w-0 items-center gap-0.5`,Mge=150,N8=288,Nge=({shown:e,row:t,target:n,view:r,column:i,Card:a,onEnter:s,onLeave:c})=>{let l=(0,o.useRef)(null),[u,d]=(0,o.useState)();return(0,o.useLayoutEffect)(()=>{l.current&&d(kge(e.dot,{width:N8,height:l.current.offsetHeight},{width:window.innerWidth,height:window.innerHeight}))},[e]),(0,nr.createPortal)((0,V.jsx)(`div`,{ref:l,"data-dot-card":!0,onMouseEnter:s,onMouseLeave:c,style:{width:N8,...u??{visibility:`hidden`,top:0,left:0}},className:`fixed z-50 rounded-lg shadow-pop`,children:(0,V.jsx)(a,{model:n,view:r,display:k8(r,i.status),row:t})}),document.body)},P8=({column:e,records:t,target:n,view:r,wrap:i=!1,Card:a})=>{let s=(0,o.useMemo)(()=>t.map(e=>AS(n,e)),[t,n]),[c,l]=(0,o.useState)(),u=(0,o.useRef)(void 0),d=(0,o.useRef)(`mouse`),f=(0,o.useRef)(null),p=n.fields[e.status],m=r?.fields[e.status],h=t=>p?eS(p,t.record[e.status],m):``,g=Fx(n,r),_=e=>e.labels[g]??String(e.record[g]??e.key),v=(r?.names?.singular??K(n.name)).toLowerCase(),y=(r?.names?.plural??K(n.name)).toLowerCase(),b=jge(s.map(t=>t.record[e.status]),{values:p?.enumValues??[],label:e=>p?eS(p,e,m):e,singular:v,plural:y}),x=()=>window.clearTimeout(u.current),S=()=>{x(),u.current=window.setTimeout(()=>l(void 0),Mge)},C=(e,t)=>{x(),l({key:e,dot:t.getBoundingClientRect()})};(0,o.useEffect)(()=>x,[]),(0,o.useEffect)(()=>{if(!c)return;let e=()=>l(void 0),t=t=>t.key===`Escape`&&e(),n=t=>{let n=t.target;!f.current?.contains(n)&&!n?.closest?.(`[data-dot-card]`)&&e()};return document.addEventListener(`keydown`,t),document.addEventListener(`pointerdown`,n),document.addEventListener(`scroll`,e,!0),window.addEventListener(`resize`,e),()=>{document.removeEventListener(`keydown`,t),document.removeEventListener(`pointerdown`,n),document.removeEventListener(`scroll`,e,!0),window.removeEventListener(`resize`,e)}},[c]);let w=e=>t=>{d.current===`touch`&&c?.key!==e&&(t.preventDefault(),C(e,t.currentTarget))},T=e=>{e.relatedTarget?.closest?.(`[data-dot-card]`)||S()},E=c&&s.find(e=>e.key===c.key);return(0,V.jsxs)(`div`,{ref:f,className:B(M8,i&&`pointer-events-none flex-wrap`),onClick:e=>e.stopPropagation(),onPointerDown:e=>d.current=e.pointerType,children:[(0,V.jsx)(`span`,{className:`sr-only`,children:b}),s.map(t=>{let r=t.record[e.status],i=f4(m?.valueColors,r);return(0,V.jsx)(ZS,{to:{kind:`record`,resource:n.name,key:t.key},"aria-label":`${_(t)}, ${h(t)}`,onPointerEnter:e=>e.pointerType!==`touch`&&C(t.key,e.currentTarget),onPointerLeave:e=>e.pointerType!==`touch`&&S(),onFocus:e=>e.currentTarget.matches(`:focus-visible`)&&C(t.key,e.currentTarget),onBlur:T,onClick:w(t.key),className:B(A8,`pointer-events-auto focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40`),children:(0,V.jsx)(`span`,{"aria-hidden":!0,style:i===void 0?void 0:{backgroundColor:i},className:B(j8,i===void 0&&Ou[Gx(String(r))],c?.key===t.key&&`ring-2 ring-foreground/30`)})},t.key)}),c&&E&&(0,V.jsx)(Nge,{shown:c,row:E,target:n,view:r,column:e,Card:a,onEnter:x,onLeave:S})]})},Pge=({count:e})=>(0,V.jsx)(`span`,{"aria-hidden":!0,className:B(M8,`invisible flex-wrap`),children:Array.from({length:e},(e,t)=>(0,V.jsx)(`span`,{className:A8,children:(0,V.jsx)(`span`,{className:j8})},t))}),F8=`flex flex-col gap-1.5`,Fge=({dots:e})=>(0,V.jsx)(`span`,{className:F8,children:e.map(({column:e,records:t})=>(0,V.jsx)(Pge,{count:t.length},e.name))}),Ige=({dots:e,Card:t})=>{let{resources:n,views:r}=J();return(0,V.jsx)(`div`,{className:`pointer-events-none absolute inset-x-[calc(0.75rem+1px)] bottom-[calc(0.75rem+1px)] ${F8}`,children:e.map(({column:e,records:i})=>{let a=n[e.resource];return a&&(0,V.jsx)(P8,{column:e,records:i,target:a,view:r[a.name],Card:t,wrap:!0},e.name)})})},Lge=(e,t,n)=>(t.dots??[]).flatMap(t=>{let r=e?.list?.relatedColumns?.find(e=>e.name===t),i=n.record[t];return r&&Array.isArray(i)&&i.length>0?[{column:r,records:i}]:[]}),I8=({value:e})=>{let t=Ob(e,{width:320,height:240});return t?(0,V.jsx)(hC,{image:t,loading:`lazy`,className:`size-full object-cover`}):null},L8=({children:e})=>(0,V.jsx)(`span`,{className:`-mx-3 -mt-3 mb-1.5 block aspect-[4/3] overflow-hidden rounded-t-lg border-b border-border bg-muted`,children:e}),Rge=({value:e})=>(0,V.jsx)(L8,{children:(0,V.jsx)(I8,{value:e})}),zge=10,Bge=(e,t)=>{let n=vb(e)?e.uri:void 0,r=t.filter(e=>vb(e)&&e.uri!==n);return(n===void 0?r:[e,...r]).slice(0,zge)},Vge=(e,t)=>t===0?0:(e%t+t)%t,Hge=(e,t,n)=>t<=0||n===0?0:Math.min(n-1,Math.max(0,Math.round(e/t))),R8=`pointer-events-auto absolute top-1/2 flex size-7 -translate-y-1/2 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm opacity-0 transition-opacity group-has-[[data-card-photos]:hover]/card:opacity-100 group-hover/arrows:opacity-100 group-has-[:focus-visible]/arrows:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,z8=`[@media(hover:none)]:opacity-100`,Uge=({photos:e,cover:t,swipe:n=!0,children:r})=>{let i=(0,o.useRef)(null),a=(0,o.useRef)(void 0),[s,c]=(0,o.useState)(0),l=Bge(t,e),u=e=>{let t=i.current;t&&t.scrollTo({left:e*t.clientWidth})},d=e=>{a.current=Vge((a.current??s)+e,l.length),u(a.current)},f=()=>{a.current=void 0},p=e=>{c(Hge(e.scrollLeft,e.clientWidth,l.length)),a.current!==void 0&&Math.abs(e.scrollLeft-a.current*e.clientWidth)<1&&(a.current=void 0)},m=(0,V.jsx)(L8,{children:(0,V.jsx)(`span`,{ref:i,tabIndex:-1,"data-card-photos":!0,onPointerDown:f,onScroll:e=>p(e.currentTarget),className:B(`flex size-full snap-x snap-mandatory outline-none [scrollbar-width:none] motion-safe:scroll-smooth [&::-webkit-scrollbar]:hidden`,n?`overflow-x-auto overscroll-x-contain`:`overflow-x-hidden`),children:l.map((e,t)=>(0,V.jsx)(`span`,{className:`block size-full shrink-0 snap-start snap-always`,children:(0,V.jsx)(I8,{value:e})},t))})});return(0,V.jsxs)(V.Fragment,{children:[r(m),l.length>1&&(0,V.jsxs)(`div`,{className:`group/arrows pointer-events-none absolute inset-x-px top-px aspect-[4/3]`,children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":`Previous photo`,className:B(R8,!n&&z8,`left-2`),onClick:()=>d(-1),children:(0,V.jsx)(be,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Next photo`,className:B(R8,!n&&z8,`right-2`),onClick:()=>d(1),children:(0,V.jsx)(Se,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsxs)(`span`,{className:`absolute inset-x-0 bottom-2 flex justify-center`,"aria-live":`polite`,children:[(0,V.jsx)(`span`,{className:`sr-only`,children:`Photo ${s+1} of ${l.length}`}),(0,V.jsx)(`span`,{className:`flex items-center gap-1 rounded-full bg-background/70 px-1.5 py-1 leading-none`,"aria-hidden":!0,children:l.map((e,t)=>(0,V.jsx)(`span`,{className:B(`size-1.5 rounded-full`,t===s?`bg-foreground`:`bg-foreground/35`)},t))})]})]})]})},Wge=({icon:e,children:t})=>{let n=b8(e);return(0,V.jsxs)(`dd`,{className:`flex items-center gap-1 tabular-nums`,children:[n&&(0,V.jsx)(n,{className:`size-3.5 shrink-0`,"aria-hidden":!0}),t]})},B8=({model:e,view:t,display:n,row:r,swipe:i=!0,mark:a})=>{let{image:o,title:s,subtitle:c,amount:l,badge:u,meta:d,footer:f,flags:p}=xS(e,t,n),m=e=>t?.fields[e]?.label??K(e),h=n=>{let i=e.fields[n];if(!i)return``;let a=r.record[n];return r.labels[n]===void 0&&Mx(i,t?.fields[n])&&typeof a==`string`&&a!==``?jx(a):r.labels[n]??eS(i,a,t?.fields[n])},{fields:g,components:_}=SC(),v=v8(e),y=n.card===void 0?void 0:_?.[n.card],b=n=>{let i=e.fields[n],a=i&&CC(g,i,t?.fields[n]);return a?(0,V.jsx)(EC,{shown:a,part:`display`,field:i,value:r.record[n],fallback:h(n)}):h(n)},x=n=>{let i=e.fields[n],a=r.record[n];return!i||!Mx(i,t?.fields[n])||CC(g,i,t?.fields[n])||typeof a!=`string`||a===``?b(n):(0,V.jsx)(OC,{source:a,inLink:!0})},S=n=>{let i=e.fields[n],a=t?.fields[n],o=r.record[n];return!i||a?.format!==`badge`||CC(g,i,a)||o==null||o===``?b(n):(0,V.jsx)(p4,{value:o,hints:a,children:h(n)})},C=n=>{let i=e.fields[n];if(!i)return;if(r.labels[n]!==void 0||CC(g,i,t?.fields[n]))return(0,V.jsx)(`strong`,{className:`font-semibold text-foreground`,children:b(n)});let a=wS(i,r.record[n],t?.fields[n]);return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`strong`,{className:`font-semibold text-foreground`,children:a.amount}),a.suffix]})},w=y?void 0:n.photos,T=u===void 0?void 0:r.record[u],E=p.filter(e=>r.record[e]===!0),D=o===void 0?void 0:r.record[o],O=CS(r,l),k=SS(r,f),A=o!==void 0||w!==void 0,j=n.favorite,M=y?[]:Lge(t,n,r),N=e=>(0,V.jsxs)(V.Fragment,{children:[A&&e,(0,V.jsxs)(`span`,{className:`flex items-start justify-between gap-2 ${j&&!A?`pr-8`:``}`,children:[(0,V.jsx)(`span`,{className:`min-w-0 truncate font-medium`,children:b(s)}),u!==void 0&&T!=null&&(0,V.jsx)(p4,{value:T,hints:t?.fields[u],children:h(u)})]}),c!==void 0&&(0,V.jsx)(`span`,{className:t?.fields[c]?.markdown?`line-clamp-3 break-words text-muted-foreground`:t?.fields[c]?.multiline?`line-clamp-3 whitespace-pre-line break-words text-muted-foreground`:`truncate text-muted-foreground`,children:x(c)}),O!==void 0&&(0,V.jsx)(`span`,{className:`truncate tabular-nums text-muted-foreground`,children:C(O)}),d.length>0&&(0,V.jsx)(`dl`,{className:`mt-auto flex flex-wrap items-center gap-x-3 gap-y-0.5 pt-1 text-xs text-muted-foreground`,children:SS(r,d).map(e=>(0,V.jsxs)(`div`,{className:`flex gap-1`,children:[(0,V.jsx)(`dt`,{className:`sr-only`,children:m(e)}),(0,V.jsx)(Wge,{icon:t?.fields[e]?.icon,children:S(e)})]},e))}),E.length>0&&(0,V.jsx)(`ul`,{className:`flex flex-wrap gap-1`,"aria-label":`Features`,children:E.map(e=>(0,V.jsx)(`li`,{children:(0,V.jsx)(Au,{dot:!1,children:m(e)})},e))}),k.length>0&&(0,V.jsx)(`span`,{className:`truncate text-xs text-muted-foreground ${d.length>0?``:`mt-auto`}`,children:k.map((e,t)=>(0,V.jsxs)(`span`,{children:[t>0&&(0,V.jsx)(`span`,{"aria-hidden":!0,children:` • `}),b(e)]},e))}),M.length>0&&(0,V.jsx)(Fge,{dots:M})]}),ee=t=>(0,V.jsxs)(ZS,{to:{kind:`record`,resource:e.name,key:r.key},onClick:()=>v(r.record),className:`flex h-full flex-col gap-1.5 rounded-lg border border-border bg-background p-3 hover:border-border-strong hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,children:[a&&!A&&(0,V.jsx)(Au,{tone:`blue`,className:`self-start`,children:a}),y?(0,V.jsx)(Qh,{name:n.card,fallback:N(t),children:(0,V.jsx)(y,{row:r})}):N(t)]});return(0,V.jsxs)(`div`,{className:w?`group/card relative h-full`:j||a||M.length>0?`relative h-full`:`h-full`,children:[w?(0,V.jsx)(Uge,{photos:r.photos??[],cover:D,swipe:i,children:ee},r.key):ee((0,V.jsx)(Rge,{value:D})),a&&A&&(0,V.jsx)(Au,{tone:`blue`,className:`pointer-events-none absolute top-2 left-2 shadow-sm`,children:a}),M.length>0&&(0,V.jsx)(Ige,{dots:M,Card:B8}),j&&(0,V.jsx)(Oge,{favorite:j,recordKey:r.key,target:zx(e,r.record),className:A?void 0:`right-1.5 top-1.5`})]})},V8=268,H8=3,U8=(e,t,n)=>{let r=Math.floor(Math.max(0,e)/V8),i=Math.ceil((Math.max(0,e)+t)/V8);return{start:Math.max(0,r-H8),end:Math.min(n,i+H8)}},W8=e=>e*V8,Gge=e=>{let t=(0,o.useRef)(null),[n,r]=(0,o.useState)({left:0,width:0});(0,o.useLayoutEffect)(()=>{let n=t.current;if(!n)return;let i=()=>r(t=>{let r={left:n.scrollLeft,width:n.clientWidth};return((t,n)=>{let[r,i]=[U8(t.left,t.width,e),U8(n.left,n.width,e)];return r.start===i.start&&r.end===i.end&&t.width===n.width&&t.left>0==n.left>0&&Math.abs(t.left-n.left)<1})(t,r)?t:r});i();let a=new ResizeObserver(i);return a.observe(n),n.addEventListener(`scroll`,i,{passive:!0}),()=>{a.disconnect(),n.removeEventListener(`scroll`,i)}},[e]);let i=Math.max(0,W8(e)-12),a=e=>t.current?.scrollBy({left:e*Math.max(W8(1),n.width-12),behavior:`smooth`});return{ref:t,...U8(n.left,n.width,e),back:n.left>0,on:n.left+n.width<i-1,page:a}},G8=`absolute top-1/2 z-10 hidden size-8 -translate-y-1/2 items-center justify-center rounded-full border border-border-strong bg-background shadow-pop hover:bg-muted sm:flex`,K8=({cards:e})=>e>0?(0,V.jsx)(`li`,{"aria-hidden":!0,className:`shrink-0`,style:{width:W8(e)-12}}):null,Kge=({model:e,view:t,display:n,source:r,label:i,isNew:a})=>{let{total:o}=r,s=Gge(o),c=p6({total:o,rowAt:r.rowAt,loadRows:r.loadRows,revision:r.revision,latencyMs:0},s.start,Math.max(s.start,s.end-1)),l=Array.from({length:s.end-s.start},(e,t)=>s.start+t);return(0,V.jsxs)(`div`,{className:`relative min-w-0`,children:[(0,V.jsxs)(`ul`,{ref:s.ref,"aria-label":i,className:`flex snap-x gap-3 overflow-x-auto overflow-y-hidden pb-1`,style:{scrollbarWidth:`thin`},children:[(0,V.jsx)(K8,{cards:s.start}),l.map(r=>{let i=c(r);if(!i)return(0,V.jsx)(`li`,{"aria-hidden":!0,className:`shrink-0`,style:{width:256},children:(0,V.jsx)(cu,{className:`h-full min-h-24 rounded-lg`})},`skeleton-${r}`);let s=AS(e,i);return(0,V.jsx)(`li`,{"aria-posinset":r+1,"aria-setsize":o,className:`grid shrink-0 snap-start grid-cols-[minmax(0,1fr)]`,style:{width:256},children:(0,V.jsx)(B8,{model:e,view:t,display:n,row:s,swipe:!1,mark:a?.(s)?`New`:void 0})},s.key)}),(0,V.jsx)(K8,{cards:o-s.end})]}),s.back&&(0,V.jsx)(`button`,{type:`button`,"aria-label":`Previous ${i.toLowerCase()}`,onClick:()=>s.page(-1),className:`${G8} -left-3`,children:(0,V.jsx)(be,{className:`size-4`,"aria-hidden":!0})}),s.on&&(0,V.jsx)(`button`,{type:`button`,"aria-label":`Next ${i.toLowerCase()}`,onClick:()=>s.page(1),className:`${G8} -right-3`,children:(0,V.jsx)(Se,{className:`size-4`,"aria-hidden":!0})})]})},qge=co(),Jge=(e,t)=>{if(!t)return e;let n=Sa(e);if(!n.ok)throw Error(`The filter cannot be read: ${n.errors.map(e=>e.message).join(`; `)}`);return qa(n.ast?qge.and(n.ast,t):t)},Yge=(e,t)=>{let n=uS(e).filter(e=>e.kind===`cards`);return n.find(e=>e.name===t)??n[0]??{kind:`cards`,name:`cards`}},Xge=()=>(0,V.jsx)(`div`,{className:`flex gap-3 overflow-hidden`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-24 w-64 shrink-0`},t))}),q8=({model:e,view:t,filter:n,sort:r=``,display:i,limit:a,chips:s=!0,empty:c,note:l,isNew:u,viewAll:d,scope:f,list:p})=>{let{resources:m,views:h}=J(),g=ql(),_=Yge(t,i),v=r||jS(e,t),y=k6({resources:m,views:h,model:e,columns:(0,o.useMemo)(()=>DS(e,t,[]),[e,t]),filter:(0,o.useMemo)(()=>Jge(n,f),[n,f]),orderBy:v}),b=_8(e,n),x=(t?.names?.singular??K(e.name)).toLowerCase(),S=t?.names?.plural??K(e.name),C=y.source?.total,T=(0,o.useMemo)(()=>y.source&&{...y.source,total:Math.min(y.source.total,a??1/0)},[y.source,a]);return(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-3`,children:[s&&b.length>0||C!==void 0||l?(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[s&&b.length>0?(0,V.jsx)(M6,{chips:b}):(0,V.jsx)(`span`,{}),(0,V.jsxs)(`p`,{className:`flex flex-wrap gap-x-3 text-muted-foreground`,children:[l&&(0,V.jsx)(`span`,{children:l}),C!==void 0&&(0,V.jsx)(`span`,{className:`tabular-nums`,children:`${C.toLocaleString(`en-GB`)} ${C===1?x:S.toLowerCase()}`})]})]}):null,y.isLoading?(0,V.jsx)(Xge,{}):y.error?(0,V.jsx)(ax,{title:`Could not load`,error:y.error}):!T||T.total===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:c??`No ${S.toLowerCase()} match.`}):(0,V.jsx)(Kge,{model:e,view:t,display:_,source:T,label:S,isNew:u}),(0,V.jsxs)(ZS,{to:A6(e,t,g,{filter:n,orderBy:v,display:_.name,savedSearch:d?.savedSearch,resource:p}),onClick:d?.onOpen,className:`flex items-center gap-1 self-end font-medium text-primary-text hover:underline`,children:[d?.label??(0,V.jsxs)(V.Fragment,{children:[`View all `,(0,V.jsx)(`span`,{className:`sr-only`,children:S.toLowerCase()})]}),(0,V.jsx)(w,{className:`size-3.5`,"aria-hidden":!0})]})]})},Zge=({model:e,view:t,empty:n,...r})=>{let{resources:i,views:a}=J(),o=PS(i,a,e.name),s=D8(e.name,t.listOf,!0),c=(t.names?.plural??K(e.name)).toLowerCase();if(!o.listOf)return null;if(s.error)return(0,V.jsx)(ax,{title:`Could not load your ${c}`,error:s.error});if(!s.data)return(0,V.jsx)(cu,{className:`h-24`});let l=T8(o.model,s.data);return l?(0,V.jsx)(q8,{...r,model:o.model,view:o.view,filter:``,scope:l,list:e.name,empty:n}):(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:n??`No ${c} yet.`})},Qge=e=>W.list(e,``,``,500,`saved-searches`),J8=(e,t)=>{let n=G(),{resources:r,views:i}=J(),a=r[e];return mh({queryKey:Qge(e),enabled:t&&a!==void 0,queryFn:async()=>{let t=[],r;do{let o=await n.list(e,{pageSize:500,orderBy:jS(a,i[e]),...r&&{pageToken:r}});t.push(...o.items),r=o.nextPageToken||void 0}while(r);return t}})},Y8=({model:e,of:t,target:n,targetView:r,row:i,recordKey:a})=>{let o=G(),s=qT(),c=String(i[t.filter]??``),l=_8(n,c),u=t.name===void 0?void 0:i[t.name],d=typeof u==`string`&&u!==``?u:void 0,f=t.unseen,p=hh({mutationFn:t=>o.update(e.name,a,{[f.seenAt]:t},i.etag??`*`),onSettled:()=>s(e.name)}),m=mh({...UT(o,n,f?vge(c,f.field,i[f.seenAt]):``),enabled:f!==void 0}),h=(r?.names?.plural??K(n.name)).toLowerCase(),g={model:n,view:r,filter:c,sort:f?`${f.field} desc`:void 0,limit:t.limit,chips:d!==void 0,empty:`No ${h} match.`,note:f&&m.data===0&&`No new ${h} since you last looked.`,isNew:f&&(e=>yge(e.record[f.field],i[f.seenAt])),viewAll:{label:`View all results`,savedSearch:a,...f&&{onOpen:()=>p.mutate(new Date().toISOString())}}};return{name:d,chips:l,title:d??Khe(l),body:g}},$ge=({model:e,view:t,target:n,targetView:r,row:i})=>{let a=Ao(zx(e,i)),{name:o,chips:s,title:c,body:l}=Y8({model:e,of:t.searchesOf,target:n,targetView:r,row:i,recordKey:a});return(0,V.jsxs)(`section`,{"aria-label":c,className:`flex flex-col gap-3 py-4 first:pt-0 last:pb-0`,children:[(0,V.jsx)(`h3`,{className:`text-[15px] font-semibold`,children:(0,V.jsx)(ZS,{to:{kind:`record`,resource:e.name,key:a},className:`hover:underline`,children:o??(0,V.jsx)(N6,{chips:s})})}),(0,V.jsx)(q8,{...l})]})},e_e=({model:e,view:t,empty:n})=>{let{resources:r,views:i}=J(),a=t.searchesOf,o=r[a.resource],s=J8(e.name,!0),c=(t.names?.plural??K(e.name)).toLowerCase();return o?s.error?(0,V.jsx)(ax,{title:`Could not load your ${c}`,error:s.error}):s.data?s.data.length===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:n??`No ${c} yet.`}):(0,V.jsx)(`div`,{className:`flex flex-col divide-y`,children:s.data.map(n=>(0,V.jsx)($ge,{model:e,view:t,target:o,targetView:i[a.resource],row:n},Ao(zx(e,n))))}):(0,V.jsx)(cu,{className:`h-40`}):null},t_e=({node:e,slots:t})=>{let{resource:n,filter:r=``,sort:i,limit:a,display:o,title:s,description:c,empty:l}=ZT(e),{resources:u,views:d}=J(),f=u[n];if(!f)return null;let p=d[f.name];return(0,V.jsx)($T,{title:s,description:c,actions:t.actions,children:p?.searchesOf?(0,V.jsx)(e_e,{model:f,view:p,empty:l}):p?.listOf===void 0?(0,V.jsx)(q8,{model:f,view:p,filter:r,sort:i,limit:a,display:o,empty:l}):(0,V.jsx)(Zge,{model:f,view:p,limit:a,display:o,empty:l})})},n_e=({node:e,children:t})=>{let{when:n}=ZT(e),{resources:r}=J(),i=G(),a=jT(),s=(0,o.useMemo)(()=>ic(n),[n]),c=s.ok?s.paths:[],l=c.map(e=>oc(e,e=>!!(a&&Object.hasOwn(a.model.fields,e)))),u=c.filter((e,t)=>l[t]===void 0),d=ffe(a,u),f=fh({queries:l.flatMap(e=>{let t=e===void 0?void 0:r[e];return t?[UT(i,t)]:[]})});if(!s.ok||d.some(e=>e.state===`loading`)||f.some(e=>e.isPending))return null;let p={};u.forEach((e,t)=>{let n=d[t];n.state===`ready`&&(p[e]=n.value)});let m=0;return c.forEach((e,t)=>{l[t]!==void 0&&(p[e]=r[l[t]]?f[m++]?.data??0:0)}),ac(s,p)?(0,V.jsx)(V.Fragment,{children:t}):null},X8=`text-2xl font-semibold tracking-tight tabular-nums`,r_e=({model:e,filter:t})=>{let n=WT(e,t);return n.isPending?(0,V.jsx)(cu,{className:`h-8 w-16`}):n.error?(0,V.jsx)(`span`,{className:`text-danger-text`,children:`Could not count`}):(0,V.jsx)(ZS,{to:{kind:`list`,resource:e.name,filter:t},className:`${X8} hover:text-primary-text after:absolute after:inset-0 after:content-['']`,children:n.data.toLocaleString(`en-IE`)})},i_e=({field:e,format:t})=>{let n=v4(jT(),e);return n.state===`loading`?(0,V.jsx)(cu,{className:`h-8 w-16`}):n.state===`missing`?null:(0,V.jsx)(`span`,{className:X8,children:(0,V.jsx)(m4,{model:n.model,field:n.field,value:n.value,format:t})})},a_e=({node:e})=>{let{label:t,value:n,resource:r,filter:i,field:a,format:o,description:s}=ZT(e),{resources:c}=J(),l=r===void 0?void 0:c[r];return(0,V.jsxs)($T,{className:`relative h-full`,bodyClassName:`flex flex-col`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground break-words`,children:t}),(0,V.jsxs)(`div`,{className:`mt-auto pt-1`,children:[n!==void 0&&(0,V.jsx)(`span`,{className:X8,children:n}),l&&(0,V.jsx)(r_e,{model:l,filter:i}),a!==void 0&&(0,V.jsx)(i_e,{field:a,format:o})]}),s&&(0,V.jsx)(`p`,{className:`mt-1 text-xs text-muted-foreground`,children:s})]})},Z8=e=>e===null?`none`:`value:${e}`,Q8=e=>{let t=xie(e);return t.length>0?t:a_(e)},o_e=(e,{context:{collisionRect:t,droppableRects:n,droppableContainers:r,over:i}})=>{let a=e.code===`ArrowRight`?1:e.code===`ArrowLeft`?-1:0;if(a===0||!t)return;e.preventDefault();let o=r.getEnabled().flatMap(e=>{let t=n.get(e.id);return t?[{id:e.id,rect:t}]:[]}).sort((e,t)=>e.rect.left-t.rect.left),s=t.left+t.width/2,c=i?o.findIndex(e=>e.id===i.id):o.findIndex(e=>e.rect.left<=s&&s<=e.rect.right),l=o[c+a];if(c!==-1&&l)return{x:l.rect.left+(l.rect.width-t.width)/2,y:l.rect.top}},$8=(e,t,n,r)=>{let i=gh({queryKey:[...n,`display`],enabled:r,initialPageParam:0,queryFn:({pageParam:e})=>t(e),getNextPageParam:(e,t)=>e.rows.length===40&&t.length*40<(t[0]?.total??0)?t.length:void 0}),a=i.data?.pages??[];return{resource:e.name,rows:a.flatMap(t=>t.rows.map(t=>AS(e,t))),total:a[0]?.total??0,loading:i.isPending,error:i.error,more:i.hasNextPage,loadMore:()=>void i.fetchNextPage()}},s_e=({model:e,by:t,value:n,fields:r,filter:i,orderBy:a})=>{let{resources:o,views:s}=J(),c=k6({resources:o,views:s,model:e,columns:r,filter:sS(i,t,n),orderBy:a});return $8(e,c.page,c.key,!0)},c_e=({model:e,view:t,display:n,column:r,fields:i,filter:a,orderBy:o,limit:s,moves:c,movable:l,dragged:u})=>{let d=s_e({model:e,by:n.by,value:r.value,fields:i,filter:a,orderBy:o}),{setNodeRef:f,isOver:p}=Lv({id:Z8(r.value)}),m=cS(e,t,n),h=new Set(d.rows.map(e=>e.key)),g=new Map(c.map(e=>[e.row.key,e])),_=d.rows.filter(e=>g.has(e.key)&&g.get(e.key).to!==r.value),v=c.filter(e=>e.to===r.value&&!h.has(e.row.key)).map(e=>e.row),y=d.rows.filter(e=>!_.includes(e)).map(e=>g.has(e.key)?g.get(e.key).row:e),b=[...v,...y].slice(0,s),x=d.total-_.length+v.length;if(r.value===null&&!d.loading&&x===0&&!p)return null;let S=(t?.names?.plural??K(e.name)).toLowerCase(),C=t?.fields[n.by];return(0,V.jsxs)(`section`,{ref:f,"aria-label":`${r.label}, ${x}`,className:B(`flex w-72 shrink-0 snap-start flex-col gap-2 rounded-lg bg-surface p-2`,p&&`ring-2 ring-primary/30`),children:[(0,V.jsxs)(`header`,{className:`flex items-center justify-between gap-2 px-1 pt-0.5`,children:[(0,V.jsx)(`h2`,{className:`min-w-0 truncate text-xs font-medium`,children:r.value===null?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:r.label}):(0,V.jsx)(p4,{value:r.value,hints:C,children:r.label})}),!d.loading&&(0,V.jsx)(`span`,{className:`text-xs tabular-nums text-muted-foreground`,children:x.toLocaleString(`en-IE`)})]}),d.loading?Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-20`},t)):d.error?(0,V.jsx)(ax,{title:`Could not load rows`,error:d.error}):b.length===0?(0,V.jsxs)(`p`,{className:`px-1 py-4 text-center text-xs text-muted-foreground`,children:[`No `,S]}):(0,V.jsx)(`ul`,{className:`flex flex-col gap-2`,children:b.map(n=>(0,V.jsx)(`li`,{children:(0,V.jsx)(l_e,{model:e,view:t,card:m,row:n,movable:l&&NT(n.record,`update`),dragged:u})},n.key))}),s===void 0&&d.more&&(0,V.jsx)(U,{size:`sm`,variant:`ghost`,onClick:d.loadMore,children:`Show more`})]})},l_e=({model:e,view:t,card:n,row:r,movable:i,dragged:a})=>{let{setNodeRef:o,setActivatorNodeRef:s,listeners:c,isDragging:l}=Nv({id:r.key,data:{row:r},disabled:!i});return(0,V.jsx)(`div`,{ref:e=>{o(e),s(e?.querySelector(`a`)??e)},...c,onDragStart:e=>e.preventDefault(),onClickCapture:e=>{a()&&(e.preventDefault(),e.stopPropagation())},className:B(i&&`cursor-grab touch-manipulation`,l&&`opacity-40`),children:(0,V.jsx)(B8,{model:e,view:t,display:n,row:r,swipe:!1})})},u_e=(e,t)=>{let n=G(),r=Qy(),i=qT(),[a,s]=(0,o.useState)([]),c=e=>s(t=>t.filter(t=>t.row.key!==e)),l=hh({mutationFn:({row:r,to:i})=>{let a=typeof r.record.etag==`string`?r.record.etag:`*`;return n.update(e.name,zx(e,r.record),{[t]:i.value},a)},onMutate:({row:e,to:n})=>{let r={...e,record:{...e.record,[t]:n.value}};s(t=>[...t.filter(t=>t.row.key!==e.key),{row:r,to:n.value}])},onError:(e,{row:t,to:n})=>{c(t.key),r.show({state:`error`,title:`Could not move it to ${n.label}`,description:lS(e)})},onSettled:async(t,n,{row:r})=>{await i(e.name),c(r.key)}});return{moves:a,move:(e,t)=>l.mutate({row:e,to:t})}},e5=({model:e,view:t,display:n,fields:r,filter:i,orderBy:a,limit:s})=>{let c=oS(e,t,n),l=cS(e,t,n),u=MT(YS(e.name),`update`)&&!e.fields[n.by]?.readOnly,{moves:d,move:f}=u_e(e,n.by),[p,m]=(0,o.useState)(),h=(0,o.useRef)(!1),g=Zg(Xg(F_,{activationConstraint:{distance:4}}),Xg(L_,{activationConstraint:{delay:250,tolerance:5}}),Xg(D_,{keyboardCodes:{start:[`Space`],cancel:[`Escape`],end:[`Space`,`Enter`]},coordinateGetter:o_e})),_=e=>String(e.labels[l.title]??e.record[l.title]??e.key),v=e=>c.find(t=>Z8(t.value)===e),y=e=>e.record[n.by]??null;return(0,V.jsxs)(kv,{sensors:g,collisionDetection:Q8,onDragStart:({active:e})=>{h.current=!0,m(e.data.current.row)},onDragEnd:({active:e,over:t})=>{m(void 0),setTimeout(()=>h.current=!1);let n=e.data.current.row,r=t?v(t.id):void 0;r&&r.value!==y(n)&&f(n,r)},onDragCancel:()=>{m(void 0),setTimeout(()=>h.current=!1)},accessibility:{announcements:{onDragStart:({active:e})=>`Picked up ${_(e.data.current.row)}.`,onDragOver:({active:e,over:t})=>`${_(e.data.current.row)} is over ${t?v(t.id)?.label:`no column`}.`,onDragEnd:({active:e,over:t})=>t?`${_(e.data.current.row)} was moved to ${v(t.id)?.label}.`:`${_(e.data.current.row)} was put back.`,onDragCancel:({active:e})=>`Moving ${_(e.data.current.row)} was cancelled.`},screenReaderInstructions:{draggable:`To move a card to another column, press Space, move it with the left and right arrow keys, and press Space again to drop it there. Escape puts it back.`}},children:[(0,V.jsx)(`div`,{className:`min-w-0 flex-1 overflow-x-auto`,children:(0,V.jsx)(`div`,{className:`flex snap-x items-start gap-3 pb-2`,children:c.map(o=>(0,V.jsx)(c_e,{model:e,view:t,display:n,column:o,fields:r,filter:i,orderBy:a,limit:s,moves:d,movable:u,dragged:()=>h.current},Z8(o.value)))})}),(0,V.jsx)(Yv,{children:p&&(0,V.jsx)(B8,{model:e,view:t,display:l,row:p,swipe:!1})})]})},t5=864e5,n5=e=>new Date(e).toISOString().slice(0,10),r5=e=>Date.parse(`${e}T00:00:00Z`),i5=(e,t)=>n5(r5(e)+t*t5),a5=e=>i5(e,-((new Date(r5(e)).getUTCDay()+6)%7)),o5=(e,t=0)=>{let n=new Date(r5(e));return n5(Date.UTC(n.getUTCFullYear(),n.getUTCMonth()+t,1))},s5=({scale:e,day:t})=>({scale:e,day:e===`month`?o5(t):a5(t)}),c5=(e,t,n=Wd())=>s5(e??{scale:`month`,day:Xd(t,n)}),l5=(e,t,n=Wd())=>s5({scale:e,day:Xd(t,n)}),u5=(e,t)=>e.scale===`month`?{scale:`month`,day:o5(e.day,t)}:{scale:`week`,day:i5(a5(e.day),7*t)},d5=e=>{let t=a5(e.scale===`month`?o5(e.day):e.day),n=(r5(e.scale===`month`?i5(a5(i5(o5(e.day,1),-1)),6):i5(t,6))-r5(t))/t5+1;return Array.from({length:n},(e,n)=>i5(t,n))},d_e=e=>{let t=d5(e);return{from:t[0],to:i5(t.at(-1),1)}},f5=(e,t)=>t.fields[e.start]?.type===`timestamp`,f_e=(e,t,n,r=Wd())=>{let i=f5(e,t),a=e=>new Date(Qd(e,r)).toISOString().replace(`.000Z`,`Z`),o=e=>i?{kind:`timestamp`,value:a(e),span:{start:0,end:0}}:{kind:`string`,value:e,span:{start:0,end:0}},s=lo.and(lo.gte(e.start,o(n.from)),lo.lt(e.start,o(n.to)));if(e.end===void 0)return qa(s);let c=i?lo.gt(e.end,o(n.from)):lo.gte(e.end,o(n.from));return qa(lo.or(s,lo.and(lo.lt(e.start,o(n.from)),c)))},p_e=(e,t)=>e===``?t:`(${e}) AND (${t})`,p5=e=>{if(typeof e!=`string`)return;let t=Date.parse(/^\d{4}-\d{2}-\d{2}$/.test(e)?`${e}T00:00:00Z`:e);return Number.isNaN(t)?void 0:t},m_e=(e,t,n,r,i=Wd())=>{let a=p5(e[t.start]);if(a===void 0)return[];let o=f5(t,n),s=e=>o?Xd(e,i):n5(e),c=s(a),l=t.end===void 0?void 0:p5(e[t.end]),u=l===void 0?c:s(o?l-1:l),d=u<c?c:u;return r.filter(e=>e>=c&&e<=d)},h_e=(e,t,n,r,i=Wd())=>{let a=new Map(r.map(e=>[e,[]])),o=e.toSorted((e,n)=>(p5(e.record[t.start])??0)-(p5(n.record[t.start])??0));for(let e of o)for(let o of m_e(e.record,t,n,r,i))a.get(o).push(e);return a},g_e=(e,t,n,r,i,a=Wd())=>{let o=(r5(i)-r5(r))/t5,s=f5(t,n),c=e=>{let t=p5(e);if(t!==void 0)return s?new Date(Zd(t+Jd(t,a)+o*t5,a)).toISOString():i5(n5(t),o)},l=c(e[t.start]),u=t.end===void 0?void 0:c(e[t.end]);return{...l!==void 0&&{[t.start]:l},...u!==void 0&&{[t.end]:u}}},__e=e=>{let t=d5(e),n=e=>Date.parse(`${e}T00:00:00Z`);return e.scale===`month`?ff(n(e.day)):hf(n(t[0]),n(t.at(-1)))},v_e=({view:e,now:t,linkTo:n,onView:r})=>{let i=(e,t,i,a,o)=>n?(0,V.jsx)(ZS,{to:n(e),className:t,"aria-label":i,"aria-current":o?`page`:void 0,children:a}):(0,V.jsx)(`button`,{type:`button`,className:t,"aria-label":i,"aria-pressed":o,onClick:()=>r?.(e),children:a}),a=e.scale===`month`&&Xd(t,Wd()).startsWith(e.day.slice(0,7)),o=n=>n===`week`&&a?l5(`week`,t):c5({scale:n,day:e.day},t),s=(t,n)=>i(o(t),Nu.option(e.scale===t),n,n,e.scale===t),c=e.scale===`month`?`month`:`week`,l=Cf({variant:`secondary`,size:`sm`});return(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,V.jsx)(`h2`,{className:`text-sm font-medium`,children:__e(e)}),(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-1`,children:[i(u5(e,-1),l,`Previous ${c}`,(0,V.jsx)(be,{className:`size-3.5`})),i(l5(e.scale,t),l,`Today`,`Today`),i(u5(e,1),l,`Next ${c}`,(0,V.jsx)(Se,{className:`size-3.5`}))]}),(0,V.jsxs)(`span`,{role:`group`,"aria-label":`Calendar scale`,className:Nu.group(),children:[s(`month`,`Month`),s(`week`,`Week`)]})]})]})},y_e=`day:`,m5=e=>`${y_e}${e}`,b_e=(e,t)=>`${e}@${t}`,x_e=(e,{context:{active:t,collisionRect:n,droppableRects:r,over:i}})=>{let a={ArrowLeft:-1,ArrowRight:1,ArrowUp:-7,ArrowDown:7}[e.code],o=i?String(i.id).slice(4):t?.data.current?.day;if(a===void 0||!n||o===void 0)return;e.preventDefault();let s=r.get(m5(i5(o,a)));if(s)return{x:s.left+(s.width-n.width)/2,y:s.top+4}},S_e=({day:e,count:t,children:n,more:r,inMonth:i,today:a,week:o})=>{let{setNodeRef:s,isOver:c}=Lv({id:m5(e)}),l=Date.parse(`${e}T00:00:00Z`);return(0,V.jsxs)(`section`,{ref:s,"aria-label":`${mf(l)}, ${t}`,className:B(`flex min-w-0 flex-col gap-1 bg-background p-1`,o?`min-h-28 sm:min-h-64`:`min-h-24`,!i&&`bg-surface`,c&&`ring-2 ring-inset ring-primary/30`),children:[(0,V.jsxs)(`header`,{className:B(`flex items-center gap-1 px-0.5 text-xs`,i?`text-foreground`:`text-muted-foreground`),children:[o&&(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:pf(l)}),(0,V.jsx)(`span`,{"aria-current":a?`date`:void 0,className:B(`inline-flex size-5 items-center justify-center rounded-full tabular-nums`,a&&`bg-primary font-medium text-primary-foreground`),children:Number(e.slice(8))})]}),n,r]})},h5=(e,t,n,r)=>{let i=n.title??Fx(e,t),a=e.fields[i],o=r.labels[i]??(a?eS(a,r.record[i],t?.fields[i]):``);return o===``?r.key:o},C_e=(e,t,n,r)=>{let i=n.record[t.start];if(e.fields[t.start]?.type!==`timestamp`||typeof i!=`string`)return;let a=Date.parse(i);return Xd(a,Wd())===r?gf(a):void 0},g5=({model:e,view:t,display:n,row:r,day:i})=>{let a=v8(e),o=C_e(e,n,r,i);return(0,V.jsxs)(ZS,{to:{kind:`record`,resource:e.name,key:r.key},onClick:()=>a(r.record),className:`flex min-w-0 items-baseline gap-1 rounded-md border border-border bg-background px-1.5 py-0.5 text-xs hover:border-border-strong hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,children:[o&&(0,V.jsx)(`span`,{className:`shrink-0 tabular-nums text-muted-foreground`,children:o}),(0,V.jsx)(`span`,{className:`min-w-0 truncate`,children:h5(e,t,n,r)})]})},w_e=({movable:e,dragged:t,...n})=>{let{setNodeRef:r,setActivatorNodeRef:i,listeners:a,isDragging:o}=Nv({id:b_e(n.row.key,n.day),data:{row:n.row,day:n.day},disabled:!e});return(0,V.jsx)(`div`,{ref:e=>{r(e),i(e?.querySelector(`a`)??e)},...a,onDragStart:e=>e.preventDefault(),onClickCapture:e=>{t()&&(e.preventDefault(),e.stopPropagation())},className:B(`min-w-0`,e&&`cursor-grab touch-manipulation`,o&&`opacity-40`),children:(0,V.jsx)(g5,{...n})})},T_e=({model:e,display:t,range:n,fields:r,filter:i})=>{let{resources:a,views:s}=J(),c=k6({resources:a,views:s,model:e,columns:r,filter:p_e(i,f_e(t,e,n)),orderBy:`${t.start} asc`}),l=$8(e,c.page,c.key,!0),u=l.more&&!l.loading&&l.rows.length<500;(0,o.useEffect)(()=>{u&&l.loadMore()},[u,l.rows.length]);let d=l.rows.length>500||l.rows.length===500&&l.more;return{rows:l.rows.slice(0,500),capped:d,loading:l.loading,error:l.error}},E_e=(e,t)=>{let n=new Map(t.map(e=>[e.key,e.patch]));return e.map(e=>n.has(e.key)?{...e,record:{...e.record,...n.get(e.key)}}:e)},D_e=(e,t)=>{let n=G(),r=Qy(),i=qT(),[a,s]=(0,o.useState)([]),c=e=>s(t=>t.filter(t=>t.key!==e)),l=hh({mutationFn:({row:t,patch:r})=>{let i=typeof t.record.etag==`string`?t.record.etag:`*`;return n.update(e.name,zx(e,t.record),r,i)},onMutate:({row:e,patch:t})=>s(n=>[...n.filter(t=>t.key!==e.key),{key:e.key,patch:t}]),onError:(e,{row:t,to:n})=>{c(t.key),r.show({state:`error`,title:`Could not move it to ${sf(Date.parse(`${n}T00:00:00Z`))}`,description:lS(e)})},onSettled:async(t,n,{row:r})=>{await i(e.name),c(r.key)}});return{moves:a,move:(n,r,i)=>l.mutate({row:n,patch:g_e(n.record,t,e,r,i),to:i})}},O_e=3,_5=({model:e,view:t,display:n,fields:r,filter:i,at:a,linkTo:s,now:c=Date.now()})=>{let[l,u]=(0,o.useState)(),d=c5(s?a:l,c),f=d5(d),p=T_e({model:e,display:n,range:d_e(d),fields:r,filter:i}),{moves:m,move:h}=D_e(e,n),g=h_e(E_e(p.rows,m),n,e,f),_=MT(YS(e.name),`update`)&&[n.start,n.end].every(t=>t===void 0||!e.fields[t]?.readOnly),[v,y]=(0,o.useState)(),b=(0,o.useRef)(!1),x=Zg(Xg(F_,{activationConstraint:{distance:4}}),Xg(L_,{activationConstraint:{delay:250,tolerance:5}}),Xg(D_,{keyboardCodes:{start:[`Space`],cancel:[`Escape`],end:[`Space`,`Enter`]},coordinateGetter:x_e})),S=Xd(c,Wd()),C=d.scale===`week`,w=e=>sf(Date.parse(`${String(e).slice(m5(``).length)}T00:00:00Z`)),T=r=>h5(e,t,n,r.row),E={onDragStart:({active:e})=>`Picked up ${T(e.data.current)}.`,onDragOver:({active:e,over:t})=>`${T(e.data.current)} is over ${t?w(t.id):`no day`}.`,onDragEnd:({active:e,over:t})=>t?`${T(e.data.current)} was moved to ${w(t.id)}.`:`${T(e.data.current)} was put back.`,onDragCancel:({active:e})=>`Moving ${T(e.data.current)} was cancelled.`},D=()=>{y(void 0),setTimeout(()=>b.current=!1)},O=({active:e})=>{b.current=!0,y(e.data.current)},k=({active:e,over:t})=>{D();let{row:n,day:r}=e.data.current,i=t?String(t.id).slice(m5(``).length):void 0;i&&i!==r&&h(n,r,i)},A=(e,t)=>{let n=c5({scale:`week`,day:e},c),r=`+${t} more`,i=`self-start rounded px-1 text-xs text-muted-foreground hover:text-foreground focus-visible:outline-2 focus-visible:outline-primary`;return s?(0,V.jsx)(ZS,{to:s(n),className:i,children:r}):(0,V.jsx)(`button`,{type:`button`,className:i,onClick:()=>u(n),children:r})};return(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-3`,children:[(0,V.jsx)(v_e,{view:d,now:c,linkTo:s,onView:u}),p.error&&(0,V.jsx)(ax,{title:`Could not load rows`,error:p.error}),p.capped&&(0,V.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Showing the first `,500,` records of this `,d.scale,`. Narrow the filter to see the rest.`]}),(0,V.jsxs)(kv,{sensors:x,collisionDetection:Q8,onDragStart:O,onDragEnd:k,onDragCancel:D,accessibility:{announcements:E,screenReaderInstructions:{draggable:`To move an event to another day, press Space, move it a day with the left and right arrow keys or a week with the up and down arrow keys, and press Space again to drop it there. Escape puts it back.`}},children:[(0,V.jsxs)(`div`,{className:`overflow-hidden rounded-lg border border-border`,children:[!C&&(0,V.jsx)(`div`,{"aria-hidden":!0,className:`grid grid-cols-7 gap-px border-b border-border bg-border`,children:f.slice(0,7).map(e=>(0,V.jsx)(`span`,{className:`bg-surface px-1.5 py-1 text-xs font-medium text-muted-foreground`,children:pf(Date.parse(`${e}T00:00:00Z`))},e))}),(0,V.jsx)(`div`,{className:B(`grid gap-px bg-border`,C?`grid-cols-1 sm:grid-cols-7`:`grid-cols-7`),children:f.map(r=>{let i=g.get(r),a=C?i:i.slice(0,O_e);return(0,V.jsx)(S_e,{day:r,count:i.length,inMonth:C||r.startsWith(d.day.slice(0,7)),today:r===S,week:C,more:a.length<i.length&&A(r,i.length-a.length),children:p.loading?(0,V.jsx)(cu,{className:`h-4`}):a.map(i=>(0,V.jsx)(w_e,{model:e,view:t,display:n,row:i,day:r,movable:_&&NT(i.record,`update`),dragged:()=>b.current},i.key))},r)})})]}),(0,V.jsx)(Yv,{children:v&&(0,V.jsx)(g5,{model:e,view:t,display:n,row:v.row,day:v.day})})]})]})},k_e=({list:e,empty:t,loading:n,children:r})=>(0,V.jsx)(`div`,{className:`min-h-0 flex-1 overflow-y-auto`,children:e.loading?n:e.error?(0,V.jsx)(ax,{title:`Could not load rows`,error:e.error}):e.rows.length===0?(0,V.jsx)(`p`,{className:`py-8 text-center text-muted-foreground`,children:t}):r}),A_e=({list:e})=>(0,V.jsxs)(`div`,{className:`flex items-center justify-between gap-3 py-3 text-xs text-muted-foreground`,children:[(0,V.jsxs)(`span`,{children:[e.rows.length.toLocaleString(`en-IE`),` of `,e.total.toLocaleString(`en-IE`)]}),e.more&&(0,V.jsx)(U,{size:`sm`,onClick:e.loadMore,children:`Show more`})]}),v5=`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,j_e=`flex snap-x snap-mandatory gap-3 overflow-x-auto pb-1`,M_e=({model:e,view:t,display:n,list:r,row:i=!1,footer:a=!0})=>{let o=(t?.names?.plural??K(e.name)).toLowerCase();return(0,V.jsxs)(k_e,{list:r,empty:`No ${o} match.`,loading:(0,V.jsx)(`div`,{className:v5,children:Array.from({length:6},(e,t)=>(0,V.jsx)(cu,{className:`h-24`},t))}),children:[(0,V.jsx)(`ul`,{className:i?j_e:v5,"aria-label":t?.names?.plural??K(e.name),children:r.rows.map(r=>(0,V.jsx)(`li`,{className:B(i&&`w-64 shrink-0 snap-start`),children:(0,V.jsx)(B8,{model:e,view:t,display:n,row:r,swipe:!i})},r.key))}),a&&(0,V.jsx)(A_e,{list:r})]})},y5=(0,o.createContext)(void 0),N_e=({value:e,children:t})=>(0,V.jsx)(y5.Provider,{value:e,children:t}),P_e=()=>{let e=(0,o.useContext)(y5);if(!e)throw Error(`useListDisplay is used inside a list display, which the list page draws`);return e},F_e=()=>(0,o.useContext)(y5),b5=({display:e,list:t})=>{let{components:n}=SC(),r=n?.[e.component];return r?(0,V.jsx)(N_e,{value:t,children:(0,V.jsx)(`div`,{className:`min-w-0 flex-1 overflow-x-auto`,children:(0,V.jsx)(Qh,{name:e.component,children:(0,V.jsx)(r,{...bo(e.props??{})})})})}):(0,V.jsxs)(Zh,{children:[`No component is registered as `,e.component,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]})},x5=co(),I_e={bounds:{south:-90,west:-180,north:90,east:180},zoom:0},L_e=22,S5=e=>Math.floor(e*1e6)/1e6,C5=e=>Math.ceil(e*1e6)/1e6,w5=e=>((e+180)%360+360)%360-180,R_e=(e,t)=>{let n=[x5.gte(e.latitude,S5(Math.max(t.south,-90))),x5.lte(e.latitude,C5(Math.min(t.north,90)))];if(t.east-t.west>=360)return x5.and(...n);let r=x5.gte(e.longitude,S5(w5(t.west))),i=x5.lte(e.longitude,C5(w5(t.east)));return w5(t.west)<=w5(t.east)?x5.and(...n,r,i):x5.and(...n,x5.or(r,i))},z_e=(e,t,n)=>{let r=qa(R_e(t,n));return e.trim()===``?r:`(${e}) AND ${r}`},B_e=e=>Math.min(Math.max(Math.floor(e),0),L_e),V_e=(e,t)=>{let n=[...e.map(e=>({south:e.latitude,west:e.longitude,north:e.latitude,east:e.longitude})),...t.map(e=>e.bounds)];if(n.length!==0)return{south:Math.min(...n.map(e=>e.south)),west:Math.min(...n.map(e=>e.west)),north:Math.max(...n.map(e=>e.north)),east:Math.max(...n.map(e=>e.east))}},T5=e=>{if(typeof e==`number`)return e;if(typeof e==`string`&&e.trim()!==``)return Number(e)},E5=(e,t)=>{let n=T5(e[t.latitude]),r=T5(e[t.longitude]);if(n!==void 0&&r!==void 0&&Math.abs(n)<=90&&Math.abs(r)<=180)return{latitude:n,longitude:r}},H_e=6371008.8,D5=64,O5=(e,t)=>t.approximate===void 0?t.exact!==void 0&&e[t.exact]===!1:e[t.approximate]===!0,k5=(e,t)=>{let n=t/H_e,r=e.latitude*Math.PI/180,i=e.longitude*Math.PI/180;return{type:`Polygon`,coordinates:[Array.from({length:65},(e,t)=>{let a=t%D5/D5*2*Math.PI,o=Math.asin(Math.sin(r)*Math.cos(n)+Math.cos(r)*Math.sin(n)*Math.cos(a));return[(i+Math.atan2(Math.sin(a)*Math.sin(n)*Math.cos(r),Math.cos(n)-Math.sin(r)*Math.sin(o)))*180/Math.PI,o*180/Math.PI]})]}},U_e=e=>Array.isArray(e)&&e.length>=2&&typeof e[0]==`number`&&typeof e[1]==`number`&&Math.abs(e[0])<=180&&Math.abs(e[1])<=90,A5=(e,t)=>Array.isArray(e)&&e.length>=t&&e.every(U_e),j5=e=>Array.isArray(e)&&e.length>0&&e.every(e=>A5(e,4)),W_e=e=>Array.isArray(e)&&e.length>0&&e.every(e=>A5(e,2)),G_e=e=>{if(typeof e!=`string`)return e;try{return JSON.parse(e)}catch(e){if(e instanceof SyntaxError)return;throw e}},K_e=e=>{let t=G_e(e);if(typeof t!=`object`||!t)return;let n=t.type===`Feature`?t.geometry:t;if(typeof n!=`object`||!n)return;let{type:r,coordinates:i}=n;if(r===`Polygon`&&j5(i)||r===`MultiPolygon`&&Array.isArray(i)&&i.length>0&&i.every(j5)||r===`LineString`&&A5(i,2)||r===`MultiLineString`&&W_e(i))return{type:r,coordinates:i}},q_e=(e,t,n)=>{if(!O5(e,t))return;let r=t.area===void 0?void 0:K_e(e[t.area]);if(r)return r;let i=t.radius===void 0?void 0:T5(e[t.radius]);return i!==void 0&&Number.isFinite(i)&&i>0?k5(n,i):t.defaultRadius===void 0?void 0:k5(n,t.defaultRadius)},M5=(e,t)=>e.flatMap(e=>{let n=E5(e.record,t);if(!n)return[];if(!O5(e.record,t))return[{key:e.key,...n}];let r=q_e(e.record,t,n);return[{key:e.key,...n,approximate:!0,...r&&{area:r}}]}),J_e=(e,t)=>{let n=[];for(let r of e){let e=n.find(e=>Math.hypot(e.at.x-r.x,e.at.y-r.y)<=t);e?e.keys.push(r.key):n.push({at:r,keys:[r.key]})}return n.map(e=>({keys:e.keys,at:e.at.key}))},Y_e=(e,t)=>{if(!e)return;let n=new Set(t.map(e=>e.key)),r=e.keys.filter(e=>n.has(e));if(r.length===0)return;let i=r.indexOf(e.keys[e.index]);return{keys:r,index:Math.max(i,0)}},N5=(e,t)=>({keys:e.keys,index:((e.index+t)%e.keys.length+e.keys.length)%e.keys.length}),X_e=({model:e,display:t,fields:n,filter:r,orderBy:i,area:a})=>{let o=G(),{resources:s,views:c}=J(),l={latitude:t.latitude,longitude:t.longitude},u=a?z_e(r,l,a.bounds):``,d=a?B_e(a.zoom):0;return mh({queryKey:W.map(e.name,`${l.latitude},${l.longitude}`,d,u,i),enabled:a!==void 0,placeholderData:hm,queryFn:async()=>{let t=await o.map(e.name,{...l,zoom:d,filter:u,orderBy:i,labels:u4(s,c,e,n),photos:rS(c[e.name])});return{rows:d4(s,e,n,iS(e,t.items,t.photos),t.labels).map(t=>AS(e,t)),buckets:t.buckets,total:t.totalSize}}})},Z_e=(0,o.lazy)(()=>qh(()=>import(`./records-map-CLj0uHGq.js`).then(e=>({default:e.RecordsMap})),__vite__mapDeps([4,1,2,5,6,3,7]))),Q_e=250,P5=`flex size-8 items-center justify-center rounded-full border border-border bg-background hover:bg-surface focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/30`,F5=({model:e,view:t,display:n,filter:r,orderBy:i,fields:a,at:s,onMove:c,footer:l=!0,flush:u=!1})=>{let d=J().maps,f=d?.style,[p,m]=(0,o.useState)(),[h,g]=(0,o.useState)(),_=K6(h,Q_e),[v,y]=(0,o.useState)(s===void 0),b=X_e({model:e,display:n,fields:a,filter:r,orderBy:i,area:v?I_e:_}),x=b.isPlaceholderData?void 0:b.data,S=b.data?.rows??[],C=b.data?.buckets??[],w=M5(S,n),T=v&&x?V_e(M5(x.rows,n),x.buckets):void 0,E=TS(t,n),D=(t?.names?.plural??K(e.name)).toLowerCase(),O=(t?.names?.singular??K(e.name)).toLowerCase(),k=Y_e(p,S),A=k&&S.find(e=>e.key===k.keys[k.index]),j=new Set(w.filter(e=>e.approximate).map(e=>e.key)),M=e=>{let t=e.filter(e=>j.has(e)).length;return e.length===1?t===1?`Show the ${O}, at an approximate position`:`Show the ${O}`:t===0?`Show ${e.length} ${D}`:t===e.length?`Show ${e.length} ${D}, at approximate positions`:`Show ${e.length} ${D}, ${t} at approximate positions`},N=e=>`Zoom in on ${e.toLocaleString(`en-IE`)} ${e===1?O:D}`,ee=(0,o.useRef)(null),[P,te]=(0,o.useState)(0);if((0,o.useLayoutEffect)(()=>te(ee.current?.offsetHeight??0),[A?.key]),!f)return(0,V.jsx)(Zh,{children:`The map display needs a map style: set PROTOBASE_MAP_STYLE_URL.`});let F=x?.total===0;return(0,V.jsxs)(`div`,{className:B(`flex h-full min-h-[36rem] flex-1 flex-col sm:min-h-[28rem]`,u&&`max-md:-mx-5 max-md:-mb-4 max-md:min-h-0`),children:[(0,V.jsxs)(`div`,{className:B(`relative min-h-0 flex-1 overflow-hidden rounded-lg border border-border bg-muted`,u&&`max-md:rounded-none max-md:border-0`),children:[(0,V.jsx)(o.Suspense,{fallback:null,children:(0,V.jsx)(Z_e,{style:f,layers:d?.layers,initial:s,points:w,buckets:C,fit:T,onFitted:()=>y(!1),onMove:(e,t)=>{g(e),c?.(t)},selected:k?.keys,covered:k?P:0,onSelect:e=>m({keys:e,index:0}),onClear:()=>m(void 0),markerLabel:M,bucketLabel:N})}),b.error&&(0,V.jsx)(`div`,{className:`absolute inset-x-3 top-3 z-10`,children:(0,V.jsx)(ax,{title:`Could not load rows`,error:b.error})}),F&&(0,V.jsx)(`div`,{className:`pointer-events-none absolute inset-x-3 top-3 z-10 flex justify-center`,children:(0,V.jsxs)(`p`,{className:`pointer-events-auto flex items-center gap-3 rounded-full border border-border bg-background px-4 py-1.5 text-muted-foreground shadow`,role:`status`,children:[v?`No ${D} match.`:`No ${D} in this part of the map.`,!v&&(0,V.jsx)(U,{size:`sm`,onClick:()=>y(!0),children:`Show all`})]})}),k&&A&&(0,V.jsx)(`div`,{ref:ee,className:`pointer-events-none absolute inset-x-3 bottom-3 z-10 flex justify-center`,children:(0,V.jsxs)(`div`,{className:`pointer-events-auto flex w-full max-w-[16rem] flex-col gap-2 sm:max-w-xs`,role:`group`,"aria-label":`Chosen ${O}`,children:[(0,V.jsxs)(`div`,{className:`flex items-center justify-end gap-1.5`,children:[j.has(A.key)&&(0,V.jsxs)(`span`,{className:`mr-auto flex items-center gap-1 rounded-full border border-border bg-background px-2 py-1 text-xs`,children:[(0,V.jsx)(Ae,{className:`size-3.5`,"aria-hidden":!0}),`Approximate position`]}),k.keys.length>1&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,"aria-label":`Previous`,className:P5,onClick:()=>m(N5(k,-1)),children:(0,V.jsx)(be,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsxs)(`span`,{className:`rounded-full border border-border bg-background px-2 py-1 text-xs tabular-nums`,"aria-live":`polite`,children:[k.index+1,` / `,k.keys.length]}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Next`,className:P5,onClick:()=>m(N5(k,1)),children:(0,V.jsx)(Se,{className:`size-4`,"aria-hidden":!0})})]}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Close`,className:P5,onClick:()=>m(void 0),children:(0,V.jsx)($n,{className:`size-4`,"aria-hidden":!0})})]}),(0,V.jsx)(`div`,{className:`shadow-lg`,children:(0,V.jsx)(B8,{model:e,view:t,display:E,row:A})})]})})]}),l&&(0,V.jsx)(`p`,{className:`hidden py-3 text-xs text-muted-foreground md:block`,children:$_e(b.data,D)})]})},$_e=(e,t)=>{if(!e)return`\xA0`;let n=e.total.toLocaleString(`en-IE`);return e.buckets.length===0&&e.rows.length<e.total?`${e.rows.length.toLocaleString(`en-IE`)} of ${n} ${t} in view`:`${n} ${t} in view`},I5=(e,t,n)=>{if(n!==0){if(e===`Home`)return 0;if(e===`End`)return n-1;if(e===`ArrowDown`)return t<0?0:(t+1)%n;if(e===`ArrowUp`)return t<0?n-1:(t-1+n)%n}},L5=({value:e,options:t,onChange:n,label:r})=>{let[i,a]=(0,o.useState)(!1),s=(0,o.useRef)(null),c=(0,o.useRef)(null),l=(0,o.useRef)([]),u=t.findIndex(t=>t.value===e),d=t[u];(0,o.useEffect)(()=>{if(!i)return;l.current[Math.max(u,0)]?.focus();let e=e=>{e.target instanceof Node&&!s.current?.contains(e.target)&&a(!1)};return document.addEventListener(`pointerdown`,e),()=>document.removeEventListener(`pointerdown`,e)},[i]);let f=()=>{a(!1),c.current?.focus()};return(0,V.jsxs)(`div`,{ref:s,className:`relative shrink-0`,children:[(0,V.jsxs)(`button`,{ref:c,type:`button`,"aria-label":d?`${r}: ${d.label}`:r,"aria-haspopup":`menu`,"aria-expanded":i,onClick:()=>a(!i),className:`inline-flex h-8 items-center gap-1.5 rounded-md border border-border-strong bg-background px-2.5 text-body font-medium shadow-sm transition-colors hover:bg-muted pointer-coarse:h-11`,children:[d?.icon&&(0,V.jsx)(d.icon,{className:`size-3.5`}),d?.label??r,(0,V.jsx)(ve,{className:`size-3.5 text-muted-foreground`})]}),i&&(0,V.jsx)(`ul`,{role:`menu`,"aria-label":r,onKeyDown:e=>{if(e.key===`Escape`)return f();if(e.key===`Tab`)return a(!1);let n=I5(e.key,l.current.indexOf(document.activeElement),t.length);n!==void 0&&(e.preventDefault(),l.current[n]?.focus())},className:`absolute right-0 top-full z-30 mt-1 min-w-40 rounded-md border bg-background py-1 text-body shadow-pop`,children:t.map((t,r)=>(0,V.jsx)(`li`,{role:`none`,children:(0,V.jsxs)(`button`,{ref:e=>{l.current[r]=e},type:`button`,role:`menuitemradio`,"aria-checked":t.value===e,onClick:()=>{f(),t.value!==e&&n(t.value)},className:B(`flex min-h-9 w-full items-center gap-2 whitespace-nowrap px-3 py-1.5 text-left hover:bg-muted focus:bg-muted focus:outline-none pointer-coarse:min-h-11`,t.value===e&&`font-medium`),children:[t.icon?(0,V.jsx)(t.icon,{className:`size-3.5`}):(0,V.jsx)(`span`,{className:`size-3.5`}),(0,V.jsx)(`span`,{className:`flex-1`,children:t.label}),t.value===e&&(0,V.jsx)(ge,{className:`size-3.5 text-primary-text`})]})},t.value))})]})},eve={table:Nn,cards:ree,kanban:Dn,board:Ie,list:At,calendar:fe,map:iee},R5=({view:e,value:t,onChange:n,menu:r=!1,choices:i=yS(e)})=>{if(i.length<2)return null;let a=i.map(e=>({value:e.name,label:e.label,icon:e.icon===void 0?void 0:eve[e.icon]}));return r?(0,V.jsx)(L5,{label:`Display`,value:t,onChange:n,options:a}):(0,V.jsx)(Pu,{label:`Display`,size:`md`,value:t,onChange:n,options:a})},tve=[[`asc`,`ascending`],[`desc`,`descending`]],z5=({model:e,view:t,display:n,orderBy:r,onChange:i,className:a})=>{let o=MS(r),s=OS(e,t,n),c=s.includes(o.columnId)?s:[o.columnId,...s],l=e=>t?.fields[e]?.label??K(e);return(0,V.jsx)(`select`,{"aria-label":`Sort`,value:`${o.columnId} ${o.direction}`,onChange:e=>i(e.target.value),className:B(`h-8 rounded-md border border-border-strong bg-background px-2.5 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,a),children:c.flatMap(e=>tve.map(([t,n])=>(0,V.jsxs)(`option`,{value:`${e} ${t}`,children:[l(e),`, `,n]},`${e} ${t}`)))})},B5=(e,t,n,r)=>e.map(e=>{let i=t.fields[e.id],a=i&&CC(r,i,n?.fields[e.id]);return a?{...e,render:t=>(0,V.jsx)(EC,{shown:a,part:`cell`,field:i,value:t[e.id],fallback:Q3(e,e.value?e.value(t):t[e.id])})}:e}),V5=e=>e.includes(`.`),nve=({model:e,row:t,column:n})=>{let r=v4(HT(e,AS(e,t).record),n);return r.state===`loading`?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`…`}):r.state===`missing`?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`—`}):(0,V.jsx)(m4,{model:r.model,field:r.field,value:r.value})},rve=(e,t,{resources:n,views:r})=>{let i=sc(n,e.name,t),a=i.ok?i.steps.at(-1):void 0,o=a?.field.name??t;return{id:t,header:r[a?.model.name??e.name]?.fields[o]?.label??K(o),kind:`text`,width:200,render:n=>(0,V.jsx)(nve,{model:e,row:n,column:t})}},H5=(e,t,n,r)=>{let i=new Map(B5(Qx(e,t,[],n.filter(e=>!V5(e))),e,t,r.fieldTypes).map(e=>[e.id,e]));return n.flatMap(t=>V5(t)?[rve(e,t,r)]:i.get(t)??[])},ive=(e,t,n)=>{if(!(e>=t))return`The first ${e} of ${n?`about `:``}${t.toLocaleString(`en-GB`)}.`},U5=(e,t,n)=>{let r=Object.hasOwn(e.fields,t)?e.fields[t]:void 0;return r?.type===`relation`&&r.relation!==void 0&&n[r.relation.resource]?.primaryKey.length===1},ave=(e,t,n)=>{if(e.open!==void 0)return e.open!==e.field&&U5(t,e.open,n)?e.open:void 0;let r=t.primaryKey.filter(r=>r!==e.field&&r!==t.tenant&&U5(t,r,n));return r.length===1?r[0]:void 0},ove=(e,t)=>{let n=e[t],r=typeof n==`object`&&n&&`id`in n?n.id:n;return typeof r==`string`||typeof r==`number`?r:void 0},W5=(e,t)=>(t?.names?.singular??K(e.name)).toLowerCase(),sve=({model:e,view:t,opens:n,resources:r,views:i,canUpdate:a})=>{let o=t=>({kind:`record`,resource:e.name,key:zx(e,t)}),s=n&&e.fields[n]?.relation?.resource,c=s?r[s]:void 0,l=e=>{let t=n&&c?ove(e,n):void 0;return c&&t!==void 0?{kind:`record`,resource:c.name,key:t}:void 0},u=e=>l(e)??o(e),d=W5(e,t);return{address:u,actions:t=>{let n={label:`Open ${d}`,link:e=>t(o(e))};if(!c)return[n];let r=e=>a&&NT(e,`update`);return[{label:`Open ${W5(c,i[c.name])}`,available:e=>l(e)!==void 0,link:e=>t(l(e))},{label:`Edit ${d}`,available:r,link:n=>t({kind:`record`,resource:e.name,key:zx(e,n),edit:!0})},{...n,available:e=>!r(e)}]}}},cve=({model:e,filter:t,orderBy:n,limit:r,fields:i})=>{let a=G(),{resources:o,views:s}=J();return mh({queryKey:[...W.list(e.name,t,n,r,`embedded`),i.join(`,`)],placeholderData:hm,queryFn:async()=>{let c=u4(o,s,e,i),l=rS(s[e.name]),u=await a.search(e.name,{filter:t||void 0,orderBy:n||void 0,pageSize:r,count:`exact`,labels:c,photos:l}),d=d4(o,e,i,iS(e,u.items,u.photos),u.labels).map((t,n)=>({...t,id:Rx(e,u.items[n])}));return u.nextPageToken===``?{rows:d,total:d.length,estimated:!1}:{rows:d,total:u.totalSize??u.totalSizeEstimate,estimated:u.totalSize===void 0}}})},G5=({view:e,value:t,onChange:n})=>(0,V.jsx)(R5,{view:e,value:t,onChange:n,menu:!Kl()}),lve=()=>(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-4 w-full`},t))}),K5=({model:e,view:t,filter:n,sort:r,columns:i,limit:a,display:s,empty:c,row:l=!1,viewAll:u,link:d=!0,opens:f})=>{let{resources:p,views:m}=J(),h=MT(YS(e.name),`update`),{fields:g}=SC(),{go:_,href:v}=XS(),y=ql(),[b,x]=(0,o.useState)(r||jS(e,t)),S=i??Zx(e,t),C=(0,o.useMemo)(()=>H5(e,t,S,{resources:p,views:m,fieldTypes:g}),[e,t,S.join(`,`),p,m,g]),T=(0,o.useMemo)(()=>DS(e,t,C.map(e=>e.id)),[e,t,C]),E=cve({model:e,filter:n,orderBy:b,limit:a,fields:T}),D=E.data?.rows,O=(0,o.useMemo)(()=>D&&{total:D.length,rowAt:e=>D[e]},[D]),k=_S(t,s),A=t?.names?.plural??K(e.name),j=d&&(0,V.jsxs)(ZS,{to:A6(e,t,y,u?{filter:u.filter,orderBy:jS(e,t),display:s,savedSearch:u.savedSearch}:{filter:n,orderBy:b,display:s}),onClick:u?.onOpen,className:`flex items-center gap-1 self-end font-medium text-primary-text hover:underline`,children:[u?u.label:(0,V.jsxs)(V.Fragment,{children:[`View all `,(0,V.jsx)(`span`,{className:`sr-only`,children:A.toLowerCase()})]}),(0,V.jsx)(w,{className:`size-3.5`,"aria-hidden":!0})]});if(E.isPending)return(0,V.jsx)(lve,{});if(E.error)return(0,V.jsx)(ax,{title:`Could not load`,error:E.error});if(!O||O.total===0){let e=(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:c??`Nothing here yet.`});return u&&d?(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[e,j]}):e}let M={resource:e.name,rows:E.data.rows.map(t=>AS(e,t)),total:E.data.total,loading:!1,error:null,more:!1,loadMore:()=>void 0},N=sve({model:e,view:t,opens:f,resources:p,views:m,canUpdate:h}),ee=e=>({href:v(e),onFollow:()=>_(e)}),P=ive(O.total,E.data.total,E.data.estimated);return(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[k?k.kind===`cards`?(0,V.jsx)(M_e,{model:e,view:t,display:k,list:M,row:l||y,footer:!1}):k.kind===`map`?(0,V.jsx)(F5,{model:e,view:t,display:k,filter:n,orderBy:b,fields:T,footer:!1}):k.kind===`board`?(0,V.jsx)(e5,{model:e,view:t,display:k,fields:T,filter:n,orderBy:b,limit:a}):k.kind===`calendar`?(0,V.jsx)(_5,{model:e,view:t,display:k,fields:T,filter:n}):(0,V.jsx)(b5,{display:k,list:M}):(0,V.jsx)(w6,{fit:!0,columns:C,source:O,latencyMs:0,sort:MS(b),onSortChange:e=>x(NS(e)),onOpenRow:e=>_(N.address(e)),rowLink:e=>ee(N.address(e)),rowActions:N.actions(ee),rowNumbers:!1,selectable:!1}),P&&d?(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:P}),j]}):j]})},q5=(e,t,n)=>{let r=ql(),i=Hhe(t),[a,s]=(0,o.useState)(()=>Uhe(localStorage,i)),c=(0,o.useCallback)(e=>{s(e),Whe(localStorage,i,e)},[i]);return[Ghe(e,r,{picked:a,preferred:n}),c]},uve=({model:e,view:t,filter:n=``,sort:r=``,columns:i,limit:a=10,display:o,title:s,description:c,empty:l,actions:u})=>{let[d,f]=q5(t,`page:${e.name}:${s??``}:${n}`,o);return(0,V.jsx)($T,{title:s,description:c,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(G5,{view:t,value:d,onChange:f}),u]}),className:`h-full`,children:(0,V.jsx)(K5,{model:e,view:t,filter:n,sort:r,columns:i,limit:a,display:d,empty:l})})},dve={Page:Efe,Grid:yfe,Card:tE,Stat:a_e,RecordCard:kfe,Field:mfe,Table:({node:e,slots:t})=>{let n=ZT(e),{resources:r,views:i}=J(),a=r[n.resource];return a?(0,V.jsx)(uve,{...n,model:a,view:i[a.name],actions:t.actions}):null},CardRow:rE,RecordRow:t_e,Chart:cfe,Progress:Dfe,ModalForm:Tfe,Action:QT,Show:n_e,Link:bfe},J5=e=>typeof e==`string`||!e.custom&&e.type===`Link`,Y5=e=>{let t=[];for(let n of e){let e=t.at(-1);J5(n)&&e&&J5(e[0])?e.push(n):t.push([n])}return t.map((e,t)=>{let[n]=e;return J5(n)?(0,V.jsx)(`p`,{className:`leading-6`,children:e.map((e,t)=>typeof e==`string`?(0,V.jsx)(o.Fragment,{children:e},t):(0,V.jsx)(X5,{node:e},t))},t):(0,V.jsx)(X5,{node:n},t)})},fve=e=>ec(e)||Array.isArray(e)&&e.length>0&&e.every(ec),pve=e=>Object.fromEntries(Object.entries(e.props).flatMap(([e,t])=>fve(t)?[[e,(0,V.jsx)(V.Fragment,{children:Y5(Array.isArray(t)?t:[t])})]]:[])),X5=({node:e})=>{let{components:t}=SC();if(e.custom){let n=t?.[e.type];return n?(0,V.jsx)(Qh,{name:e.type,children:(0,V.jsx)(n,{...bo(e.props),children:e.children.length>0?Y5(e.children):void 0})}):(0,V.jsxs)(Zh,{children:[`No component is registered as `,e.type,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]})}let n=dve[e.type];return n?(0,V.jsx)(n,{node:e,slots:pve(e),children:Y5(e.children)}):(0,V.jsxs)(Zh,{children:[e.type,` is not a block this version of the app knows.`]})},Z5=({name:e})=>{let t=J().pages[e];return t?(0,V.jsx)(X5,{node:t.tree}):(0,V.jsxs)(KS,{title:`Not found`,children:[`There is no page called `,e,`.`]})},mve=2e3,Q5=(e,t)=>{let n=Qy(),[r,i]=(0,o.useState)(`idle`),[a,s]=(0,o.useState)(),c=(0,o.useRef)(void 0);return(0,o.useEffect)(()=>()=>clearTimeout(c.current),[]),{phase:r,message:a,run:async r=>{let a=e===`toast`?n.show({state:`loading`,title:`Saving ${t}...`}):void 0;s(void 0),e===`button`&&i(`saving`);try{return await r(),a!==void 0&&n.update(a,{state:`success`,title:`${t} saved`}),e===`button`&&(i(`saved`),c.current=setTimeout(()=>i(`idle`),mve)),!0}catch(t){if(!Rs(t))throw t;let r=t.status===412?`Changed by someone else`:`Could not save`,o=GC(t);return a!==void 0&&n.update(a,{state:`error`,title:r,description:o}),e===`button`&&(i(`idle`),s(`${r}: ${o}`)),!1}}}},$5=({title:e,eyebrow:t,submit:n,saving:r,disabled:i,error:a,errorTitle:o=`Not saved`,onSubmit:s,onCancel:c,children:l,ref:u})=>{let d=(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[c&&(0,V.jsx)(U,{className:`max-sm:min-h-11`,onClick:c,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,type:`submit`,className:`max-sm:min-h-11 max-sm:flex-1`,loading:r,disabled:i,children:n})]}),f=a!==void 0&&(0,V.jsx)(`div`,{className:`mt-4`,children:(0,V.jsx)(ax,{title:o,error:a})}),p=(0,V.jsx)(`div`,{className:`divide-y divide-border`,children:l}),m=e=>{e.preventDefault(),s()};return e===void 0?(0,V.jsxs)(`form`,{ref:u,className:`max-w-[760px]`,onSubmit:m,children:[f,p,(0,V.jsx)(`footer`,{className:`border-t pt-6 sm:flex sm:justify-end`,children:d})]}):(0,V.jsx)(`form`,{ref:u,className:`flex-1`,onSubmit:m,children:(0,V.jsxs)(`div`,{className:`mx-auto max-w-[760px] px-4 py-6 md:px-10 md:py-8`,children:[(0,V.jsxs)(`header`,{className:`flex flex-col gap-4 border-b pb-6 sm:flex-row sm:items-end sm:justify-between sm:gap-6`,children:[(0,V.jsxs)(`div`,{children:[t&&(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:t}),(0,V.jsx)(`h1`,{className:`mt-1 text-2xl font-semibold tracking-tight`,children:e})]}),d]}),f,p]})})},hve=({noun:e,collection:t,sections:n,saving:r,message:i,onSubmit:a,onCancel:o,ref:s})=>(0,V.jsx)($5,{ref:s,title:`New ${e.toLowerCase()}`,eyebrow:t,submit:`Create ${e.toLowerCase()}`,saving:r,error:i?Error(i):void 0,errorTitle:`Not created`,onSubmit:a,onCancel:o,children:n.map(e=>(0,V.jsx)(tb,{title:e.title,help:e.help,children:(0,V.jsx)(`div`,{className:`grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2`,children:e.fields.map(e=>(0,V.jsx)(eb,{name:e.name,label:e.label,required:e.required,help:e.help,error:e.error,wide:e.wide,children:e.editor},e.name))})},e.title))}),gve=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),_ve=({resource:e,values:t})=>{let n=J(),r=n.resources[e],i=YS(e);return r?MT(i,`create`)?(0,V.jsx)(vve,{resource:e,values:t}):(0,V.jsxs)(KS,{title:`Not allowed`,children:[`You cannot create `,n.views[e]?.names?.plural.toLowerCase()??e,`.`]}):(0,V.jsxs)(KS,{title:`Not found`,children:[`There is no resource called `,e,`.`]})},vve=({resource:e,values:t})=>{let n=J(),r=n.resources[e],i=n.views[e],a=G(),s=Gp(),{go:c}=XS(),l=i?.names?.singular??K(e),u=Q5(i?.saveFeedback??`toast`,`New ${l.toLowerCase()}`),d=Jb(r,i),[f,p]=(0,o.useState)(()=>$b(r,d,t)),[m,h]=(0,o.useState)({}),[g,_]=(0,o.useState)(0),v=KC(g);(0,o.useEffect)(()=>{for(let[e,i]of Object.entries(t??{})){let t=n.resources[r.fields[e]?.relation?.resource??``];t&&c4(s,a,t,[i],n.views[t.name]).then(t=>{let n=t.get(i);n&&p(t=>Kb(t[e])&&t[e].key===i?{...t,[e]:{key:i,label:n}}:t)})}},[t,n,r,a,s]);let y=(e,t)=>{h(t=>gve(t,e)),p(n=>({...n,[e]:t}))},b=()=>u.run(async()=>{let t;try{t=await a.create(e,Xb(r,n.resources,f))}catch(e){let t=WC(e);throw h(t),Object.keys(t).length>0&&_(e=>e+1),e}for(let t of[`page`,`list`,`first-page`,`map`,`facets`,`series`])s.invalidateQueries({queryKey:[t,e]});c({kind:`record`,resource:e,key:zx(r,t.record)},{replace:!0})}),x=d.map(e=>({title:e.title,help:e.help,fields:e.fields.map(e=>{let t=r.fields[e],a=f[e],o=t.relation?n.resources[t.relation.resource]:void 0,s=i?.fields[e]?.label??K(e),c=m[e];return{name:e,label:s,help:i?.fields[e]?.help,required:Zb(t),error:c&&UC(t,s,c),wide:!!(i?.fields[e]?.multiline||i?.fields[e]?.markdown),editor:(0,V.jsx)(IC,{field:t,hints:i?.fields[e],value:Kb(a)?a.key:a??(t.type!==`boolean`&&``),stored:void 0,relationLabel:Kb(a)?a.label:void 0,placeholder:ex(t)?`Set by the database`:void 0,relationPicker:o?{target:o,view:n.views[o.name]}:void 0,invalid:!!m[e],resource:r.name,onChange:t=>y(e,t)})}})}));return(0,V.jsx)(hve,{ref:v,noun:l,collection:i?.names?.plural??K(e),sections:x,saving:u.phase===`saving`,message:u.message,onSubmit:()=>void b(),onCancel:()=>c({kind:`list`,resource:e})})},yve=({resource:e,values:t})=>{let n=J(),r=n.views[e];return r?.create?n.pages[r.create.page]?(0,V.jsx)(Z5,{name:r.create.page}):(0,V.jsxs)(KS,{title:`Not allowed`,children:[`You cannot create `,r.names?.plural.toLowerCase()??K(e),`.`]}):(0,V.jsx)(_ve,{resource:e,values:t},new URLSearchParams(t).toString())},bve=(e,t)=>{let n=new Map(t.map(e=>[e.value,e.count]));return e.map(([e,t])=>({value:e,label:t,...n.get(e)!==void 0&&{count:n.get(e)}}))},xve=(e,t)=>[...new Set(t.filter(t=>!e.includes(t)))],Sve=co(),Cve=(e,t)=>{let n=G(),[r,i]=(0,o.useState)({}),a=e=>!!e?.search?.length&&e.primaryKey.length===1,s=fh({queries:e.map(({id:e,target:i})=>{let o=(r[e]??``).trim();return{queryKey:[`reference-search`,e,i?.name??``,o],enabled:a(i)&&o!==``,placeholderData:hm,queryFn:async()=>{let e=i.primaryKey[0],r=Px(i,t[i.name]);return(await n.list(i.name,{filter:qa(Sve.search(o)),fields:[e,r],pageSize:20})).items.map(t=>[String(t[e]),String(t[r])])}}})});return e.map(({id:e,target:t},n)=>{if(!a(t))return{};let o=t=>i(n=>({...n,[e]:t}));return(r[e]??``).trim()===``?{onSearch:o}:{onSearch:o,matches:s[n]?.data??[]}})},wve=24,Tve=({model:e,resources:t,views:n,view:r,state:i,extras:a})=>{let o=G(),s=Gp(),c=f8(r,e),l=e=>r?.fields[e]?.label??K(e),u=n=>{let r=e.fields[n];return r?.type===`relation`&&r.relation?t[r.relation.resource]:void 0},d=c.facets.flatMap(e=>(e.flags?e.options.map(e=>e.value):[e.id]).map(t=>({group:e.id,field:t}))),f=fh({queries:d.map(({group:t,field:r})=>{let s=a8(c,{...i,facets:{...i.facets,[t]:[]}},a),l=u(r),d=l?.primaryKey.length===1?Px(l,n[l.name]):void 0;return{queryKey:W.facets(e.name,r,s),queryFn:()=>o.facets(e.name,r,{filter:s,limit:50,...d&&{label:d}})}})}),p=(e,t)=>f[d.findIndex(n=>n.group===e&&n.field===t)]?.data,m=fh({queries:c.facets.map(t=>{let r=u(t.id),a=xve((p(t.id,t.id)??[]).flatMap(e=>e.value===null?[]:[String(e.value)]),i.facets[t.id]??[]);return{queryKey:W.labels(`facet:${e.name}.${t.id}`,a.join(`,`)),enabled:!!r&&a.length>0,queryFn:async()=>[...await c4(s,o,r,a,n[r.name])]}})}),h=Cve(c.facets.map(e=>({id:e.id,target:e.combobox?u(e.id):void 0})),n),g=c.ranges??[],_=fh({queries:g.map(t=>{let n=a8(c,z6(i,t.id,void 0),a),s=p8(r,t.id)?wve:1;return{queryKey:W.histogram(e.name,t.id,s,n),queryFn:()=>o.histogram(e.name,t.id,{filter:n,buckets:s})}})});return{facets:c.facets.map((t,n)=>{if(t.flags){let e=t.options.map(({value:e})=>({value:e,label:l(e),count:p(t.id,e)?.find(e=>String(e.value)===`true`)?.count??0}));return{...t,options:e}}let i=e.fields[t.id],a=(p(t.id,t.id)??[]).flatMap(e=>e.label===void 0?[]:[[String(e.value),e.label]]),o=new Map([...a,...m[n]?.data??[]]),s=(p(t.id,t.id)??[]).flatMap(e=>e.value===null?[]:[{value:String(e.value),label:i?.type===`enum`?rs(String(e.value),r?.fields[t.id]?.valueLabels):o.get(String(e.value))??String(e.value),count:e.count}]),c=h[n];return{...t,label:l(t.id),options:c.matches?bve(c.matches,s):s,...o.size>0&&{labels:Object.fromEntries(o)},...c.onSearch&&{onSearch:c.onSearch}}}),ranges:g.flatMap((e,t)=>{let n=_[t]?.data;return!n||n.min===null||n.max===null?[]:[{...e,label:l(e.id),min:Math.floor(n.min),max:Math.ceil(n.max),step:Math.max(1,Math.round((n.max-n.min)/100)),histogram:p8(r,e.id)?n.buckets.map(e=>e.count):[],format:m8(r,e.id)}]}),...c.dateField&&{datePresets:c.datePresets??!0,dateField:c.dateField,dateKind:c.dateKind},toggles:c.toggles?.map(e=>({...e,label:l(e.id)}))}},Eve=co(),Dve=({blockingPlural:e,noun:t})=>`${e} still point at this ${t.toLowerCase()}.`,Ove=({blockedBy:e,resources:t,views:n,noun:r,key:i})=>{let{resource:a,field:o}=e;if(!t[a])return;let s=n[a]?.names?.plural??K(a),c=Dve({blockingPlural:s,noun:r});if(!o||i===void 0)return{text:c};let l={kind:`list`,resource:a,filter:qa(Eve.eq(o,i))};return{text:c,link:{label:`Show ${s.toLowerCase()}`,to:l}}},kve=({title:e,noun:t,busy:n,onConfirm:r,onCancel:i})=>(0,V.jsx)(wf,{title:`Delete ${e}?`,description:`This ${t.toLowerCase()} will be removed. This cannot be undone.`,onClose:i,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:i,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,loading:n,onClick:r,children:`Delete`})]})}),Ave=({title:e,changes:t,busy:n,onReview:r,onDeleteAnyway:i,onCancel:a})=>(0,V.jsx)(wf,{title:`${e} was changed since you opened it`,description:`Someone saved this record in the meantime. Review what changed before you delete it.`,onClose:a,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:r,children:`Review changes`}),(0,V.jsx)(U,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,loading:n,onClick:i,children:`Delete anyway`})]}),children:t.length===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`No visible fields differ; the record was saved again with the same values.`}):(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:t.map(e=>(0,V.jsxs)(`li`,{className:`grid grid-cols-[96px_1fr] gap-3 px-3 py-2`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:e.label}),(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`span`,{className:`text-muted-foreground line-through`,children:e.before}),` `,(0,V.jsx)(`span`,{className:`font-medium`,children:e.after})]})]},e.field))})}),e7=e=>{if(e.stage===`confirm`)return(0,V.jsx)(wf,{title:`Delete ${e.count} ${e.count===1?e.plural.replace(/s$/,``):e.plural.toLowerCase()}?`,description:`This cannot be undone. Each record is deleted only if it has not changed since the list loaded; anything that changed is reported and kept.`,onClose:e.onCancel,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:e.onCancel,children:`Cancel`}),(0,V.jsxs)(U,{variant:`primary`,className:`bg-danger hover:bg-danger/90`,onClick:e.onConfirm,children:[`Delete `,e.count]})]})});if(e.stage===`running`)return(0,V.jsx)(wf,{title:`Deleting`,description:`${e.done} of ${e.total} done`,onClose:()=>void 0,actions:(0,V.jsx)(U,{loading:!0,disabled:!0,children:`Working`})});let t=e.total-e.failures.length;return(0,V.jsx)(wf,{title:e.failures.length===0?`Deleted ${t}`:`Deleted ${t} of ${e.total}`,description:e.failures.length===0?void 0:`${e.failures.length} could not be deleted and were kept.`,onClose:e.onClose,actions:(0,V.jsx)(U,{variant:`primary`,onClick:e.onClose,children:`Done`}),children:e.failures.length>0&&(0,V.jsx)(`ul`,{className:`max-h-48 divide-y overflow-y-auto rounded-md border`,children:e.failures.map(e=>(0,V.jsxs)(`li`,{className:`px-3 py-2`,children:[(0,V.jsx)(`span`,{className:`font-medium`,children:e.title}),(0,V.jsx)(`span`,{className:`block text-xs text-danger-text`,children:e.message})]},e.title))})})},jve=new Set([`updated_at`,`updatedAt`]),Mve=(e,t,n,r)=>Object.values(e.fields).flatMap(e=>{if(jve.has(e.name)||JSON.stringify(n[e.name]??null)===JSON.stringify(r[e.name]??null))return[];let i=t?.fields[e.name];return[{field:e.name,label:i?.label??K(e.name),before:eS(e,n[e.name],i),after:eS(e,r[e.name],i)}]}),Nve=4,t7=({model:e,view:t,onDeleted:n,onReview:r,restore:i})=>{let a=G(),s=Gp(),c=Qy(),[l,u]=(0,o.useState)(),[d,f]=(0,o.useState)(!1),p=t?.names?.singular??K(e.name),m=t?.names?.plural??K(e.name),{resources:h,views:g}=J(),{href:_,open:v}=XS(),y=(t,n)=>t.blockedBy&&Ove({blockedBy:t.blockedBy,resources:h,views:g,noun:p,...e.primaryKey.length===1&&{key:n.key}}),b=()=>{for(let t of[`page`,`list`,`first-page`,`map`])s.invalidateQueries({queryKey:[t,e.name]});for(let t of[`facets`,`series`,`histogram`])s.invalidateQueries({queryKey:[t,e.name]})},x=async(t,n)=>{let r=n??(await a.get(e.name,t.key)).etag;try{await a.remove(e.name,t.key,{etag:r})}catch(e){if(!(e instanceof Ls))throw e;return e}},S=t=>{b(),u(void 0),n?.(t),c.show({state:`success`,title:`${t.title} deleted`,...e.softDelete&&i&&{action:{label:`Undo`,onClick:()=>{i(t).then(()=>{b(),c.show({state:`success`,title:`${t.title} restored`})},e=>{if(!Rs(e))throw e;b(),c.show({state:e.status===409?`success`:`error`,title:e.status===409?`${t.title} is already back`:`Could not restore ${t.title}`,description:e.status===409?void 0:e.message})})}}}})},C=async(n,r)=>{f(!0);try{if(!await x(n,r))return S(n);let i=(await a.get(e.name,n.key)).record;u({kind:`conflict`,target:n,fresh:i,changes:Mve(e,t,n.snapshot,i)})}catch(e){if(!Rs(e))throw e;u(void 0);let t=y(e,n);c.show({state:`error`,title:`Could not delete ${n.title}`,description:t?.text??e.message,...t?.link&&{action:{label:t.link.label,href:_(t.link.to),onNavigate:v}}})}finally{f(!1)}},w=async e=>{try{return await x(e,e.etag)?{title:e.title,message:`Changed since the list loaded, so it was kept.`}:void 0}catch(t){if(!Rs(t))throw t;return{title:e.title,message:y(t,e)?.text??t.message}}},T=async e=>{let t=[],n=0;u({kind:`bulk-running`,done:n,total:e.length});let r=[...e];await Promise.all(Array.from({length:Math.min(Nve,e.length)},async()=>{for(let i=r.shift();i;i=r.shift()){let r=await w(i);r&&t.push(r),n+=1,u({kind:`bulk-running`,done:n,total:e.length})}})),b(),u({kind:`bulk-done`,total:e.length,failures:t})},E=()=>u(void 0);return{dialogs:l&&(0,V.jsxs)(V.Fragment,{children:[l.kind===`confirm`&&(0,V.jsx)(kve,{title:l.target.title,noun:p,busy:d,onCancel:E,onConfirm:()=>void C(l.target,l.target.etag)}),l.kind===`conflict`&&(0,V.jsx)(Ave,{title:l.target.title,changes:l.changes,busy:d,onCancel:E,onReview:()=>{E(),r?.(l.target,l.fresh)},onDeleteAnyway:()=>void C(l.target,`*`)}),l.kind===`bulk-confirm`&&(0,V.jsx)(e7,{stage:`confirm`,count:l.targets.length,plural:m,onCancel:E,onConfirm:()=>void T(l.targets)}),l.kind===`bulk-running`&&(0,V.jsx)(e7,{stage:`running`,done:l.done,total:l.total}),l.kind===`bulk-done`&&(0,V.jsx)(e7,{stage:`done`,total:l.total,failures:l.failures,onClose:E})]}),start:t=>e.softDelete?C(t,t.etag):u({kind:`confirm`,target:t}),startBulk:e=>u({kind:`bulk-confirm`,targets:e})}},n7=e=>{let t=G();return e.softDelete?async n=>void await t.undelete(e.name,n.key):void 0},r7=(e,t,n)=>e?.create?Object.hasOwn(t,e.create.page):MT(n,`create`),i7=e=>typeof e==`object`&&!!e,a7=e=>e===null||typeof e==`string`&&e.trim()===``,o7=e=>e===null?``:i7(e)?e.date.replace(`T`,` `):typeof e==`boolean`?e?`TRUE`:`FALSE`:String(e),s7=e=>e<26?String.fromCharCode(65+e):s7(Math.floor(e/26)-1)+s7(e%26),c7=(e,t)=>e[t]?.trim()?e[t]:`Column ${s7(t)}`,Pve=e=>/[",\r\n]/.test(e)?`"${e.replace(/"/g,`""`)}"`:e,Fve=(e,t)=>{let n=[...t].sort((e,t)=>e.line-t.line).map(t=>[...e.map((e,n)=>o7(t.cells[n]??null)),String(t.line),t.problems.join(`; `)]);return`${[[...e,`Line`,`Problems`],...n].map(e=>e.map(Pve).join(`,`)).join(`\r
|
|
68
68
|
`)}\r\n`},l7=({label:e,counts:t})=>(0,V.jsx)(`dl`,{"aria-label":e,className:`grid grid-cols-2 gap-3 sm:grid-cols-4`,children:t.map(([e,t])=>(0,V.jsxs)(`div`,{className:`rounded-lg border px-3 py-2`,children:[(0,V.jsx)(`dt`,{className:`text-xs text-muted-foreground`,children:e}),(0,V.jsx)(`dd`,{className:`text-lg font-semibold tabular-nums`,children:t.toLocaleString(`en-IE`)})]},e))}),u7=(e,t)=>e?.fields[t]?.label??K(t),Ive=new Set([`text`,`integer`,`bigint`,`decimal`,`boolean`,`date`,`timestamp`,`uuid`,`enum`,`relation`,`currency`,`country`]),d7=(e,t)=>{let n=e.relation?t[e.relation.resource]:void 0;return n?.primaryKey.length===1?n:void 0},Lve=(e,t)=>Object.values(e.fields).filter(n=>n.readOnly||n.name===e.tenant||!Ive.has(n.type)?!1:n.type!==`relation`||d7(n,t)!==void 0),Rve=new Set([`text`,`integer`,`bigint`,`uuid`,`date`,`currency`,`country`,`enum`]),f7=e=>{let t=e.primaryKey.length===1?[e.fields[e.primaryKey[0]]]:[],n=Object.values(e.fields).filter(t=>t.filterable&&!t.sensitive&&Rve.has(t.type)&&!e.primaryKey.includes(t.name));return[...t,...n]},p7=(e,t)=>d7(e,t),m7=e=>!e.nullable&&!e.default,h7=e=>e.toLowerCase().replace(/[\s_-]+/g,``),g7=(e,t,n)=>{let r=new Set;return e.flatMap((e,i)=>{let a=h7(e);if(a===``)return[];let o=t.find(e=>!r.has(e.name)&&(h7(u7(n,e.name))===a||h7(e.name)===a));return o?(r.add(o.name),[{column:i,field:o.name}]):[]})},_7=(e,t,n)=>{if(e===`update`)return[];let r=new Set(n.map(e=>e.field));return t.filter(e=>m7(e)&&!r.has(e.name))},v7=e=>({ok:!0,value:e}),y7=e=>({ok:!1,problem:e}),b7=e=>`“${o7(e)}”`,x7=(e,t)=>{if(typeof e==`number`)return String(e);if(typeof e==`string`)return _b(e,t.decimal)},zve=(e,t,n)=>{let r=x7(t,n);if(r===void 0)return y7(`${b7(t)} is not a number`);let[i,a=``]=r.split(`.`);if(/[1-9]/.test(a)||/e/i.test(r))return y7(`${b7(t)} is not a whole number`);if(e.type===`bigint`)return v7(String(BigInt(i)));let o=Number(i);return Number.isSafeInteger(o)?v7(o):y7(`${b7(t)} is too large`)},Bve=(e,t)=>{let n=x7(e,t);return n===void 0?y7(`${b7(e)} is not a number`):v7(n)},Vve=new Set([`true`,`yes`,`1`]),Hve=new Set([`false`,`no`,`0`]),Uve=e=>{if(typeof e==`boolean`)return v7(e);let t=typeof e==`string`||typeof e==`number`?String(e).trim().toLowerCase():``;return Vve.has(t)?v7(!0):Hve.has(t)?v7(!1):y7(`${b7(e)} is not true or false (true, false, yes, no, 1 or 0)`)},S7=e=>String(e).padStart(2,`0`),Wve=(e,t,n)=>{let r=new Date(Date.UTC(e,t-1,n));if(r.getUTCFullYear()===e&&r.getUTCMonth()===t-1&&r.getUTCDate()===n)return`${e}-${S7(t)}-${S7(n)}`},C7=`(\\d{1,2}):(\\d{2})(?::(\\d{2})(?:\\.\\d+)?)?`,Gve=(e,t)=>{let n=RegExp(`^(\\d{4})[-/](\\d{1,2})[-/](\\d{1,2})(?:[T ]${C7}(Z|[+-]\\d{2}:?\\d{2})?)?$`).exec(e.trim()),r=RegExp(`^(\\d{1,2})[./-](\\d{1,2})[./-](\\d{4})(?: ${C7})?$`).exec(e.trim());if(!n&&!r)return;let[i,a,o]=n?[n[1],n[2],n[3]].map(Number):t===`dmy`?[r[3],r[2],r[1]].map(Number):[r[3],r[1],r[2]].map(Number),s=Wve(i,a,o);if(!s)return;let[c,l,u=`0`]=n?n.slice(4,7):r.slice(4,7);if(c===void 0)return{date:s};if(!(Number(c)>23||Number(l)>59||Number(u)>59))return{date:s,time:`${S7(Number(c))}:${l}:${S7(Number(u))}`,zone:n?.[7]}},w7=(e,t)=>{if(i7(e)){let[t,n]=e.date.split(`T`);return{date:t,time:n}}return typeof e==`string`?Gve(e,t.dateOrder):void 0},T7=(e,t)=>y7(`${b7(e)} is not a date (2026-04-03 or ${t.dateOrder===`dmy`?`day/month/year`:`month/day/year`})`),Kve=(e,t)=>{let n=w7(e,t);return n?n.time&&n.time!==`00:00:00`?y7(`${b7(e)} has a time of day; the field holds a date`):v7(n.date):T7(e,t)},qve=(e,t)=>{let n=w7(e,t);if(!n)return T7(e,t);if(n.zone)return v7(new Date(`${n.date}T${n.time}${n.zone===`Z`?`Z`:n.zone.replace(/^([+-]\d{2})(\d{2})$/,`$1:$2`)}`).toISOString());let[r,i,a]=n.date.split(`-`).map(Number),[o,s,c]=(n.time??`00:00:00`).split(`:`).map(Number);return v7(new Date(r,i-1,a,o,s,c).toISOString())},E7=e=>e.trim().toLowerCase().replace(/\s+/g,` `),Jve=(e,t,n)=>{let r=e.enumValues??[],i=E7(o7(n)),a=r.filter(e=>E7(e)===i||E7(rs(e,t?.valueLabels))===i);return a.length===1?v7(a[0]):a.length>1?y7(`${b7(n)} matches more than one value: ${a.map(e=>rs(e,t?.valueLabels)).join(`, `)}`):y7(`${b7(n)} is not one of ${r.map(e=>rs(e,t?.valueLabels)).join(`, `)}`)},Yve=e=>typeof e==`boolean`?y7(`${b7(e)} is true or false, not text`):v7(o7(e)),D7=(e,t,n,r)=>{if(a7(n))return e.nullable?v7(null):y7(`is empty, and it is required`);switch(e.type){case`integer`:case`bigint`:return zve(e,n,r);case`decimal`:return Bve(n,r);case`boolean`:return Uve(n);case`date`:return Kve(n,r);case`timestamp`:return qve(n,r);case`enum`:return Jve(e,t,n);case`text`:case`uuid`:case`currency`:case`country`:return Yve(n);default:throw Error(`Not implemented: importing ${e.type} fields, which importableFields leaves out`)}},Xve=(e,t)=>e[t]?.names?.singular??K(t),Zve=(e,t)=>e[t]?.names?.plural??K(t),Qve=(e,t,n)=>{let{model:r,resources:i,views:a}=n,o=a[r.name],s={},c={},l=[],u=[];for(let{column:n,field:d,matchBy:f}of t.columns){let p=r.fields[d],m=e.cells[n]??null,h=u7(o,d),g=p7(p,i);if(g&&!a7(m)){let e=f??g.primaryKey[0],n=D7(g.fields[e],a[g.name]?.fields[e],m,t.options);n.ok?u.push({field:d,finding:{model:g,field:e,value:n.value}}):l.push(`${h}: ${n.problem}`),s[d]=o7(m);continue}let _=D7(p,o?.fields[d],m,t.options);_.ok?c[d]=s[d]=_.value:l.push(`${h}: ${_.problem}`)}let d;if(t.match&&t.mode!==`create`){let n=r.fields[t.match.field],i=D7({...n,nullable:!1},o?.fields[n.name],e.cells[t.match.column]??null,t.options);i.ok?d={model:r,field:n.name,value:i.value}:l.push(`${u7(o,n.name)}: ${i.problem}`)}return{values:s,data:c,problems:l,relations:u,match:d}},O7=(e,t)=>{let n=e.lookups.keysOf(t.model.name,t.field,t.value),r=`${u7(e.views[t.model.name],t.field).toLowerCase()} “${String(t.value)}”`;return n.length===1?{key:n[0]}:n.length===0?{none:`no ${Xve(e.views,t.model.name).toLowerCase()} has ${r}`}:{several:`${n.length} ${Zve(e.views,t.model.name).toLowerCase()} have ${r}`}},$ve=e=>e.cells.every(a7),k7=async(e,t,n)=>{let{model:r,views:i}=n,a=e.filter(e=>!$ve(e)).map(e=>({row:e,...Qve(e,t,n)})),o=new Map;for(let e of a.flatMap(e=>[...e.relations.map(e=>e.finding),...e.match?[e.match]:[]])){let t=`${e.model.name}.${e.field}`;o.has(t)||o.set(t,{model:e.model,field:e.field,values:[]}),o.get(t).values.push(e.value)}for(let{model:e,field:t,values:r}of o.values())await n.lookups.load(e,t,r);return a.map(({row:e,values:a,data:o,problems:s,relations:c,match:l})=>{let u={...o};for(let{field:e,finding:t}of c){let a=O7(n,t);`key`in a?u[e]=a.key:s.push(`${u7(i[r.name],e)}: ${a.none??a.several}`)}let d=l&&O7(n,l);d?.several&&s.push(`Not one record: ${d.several}`),d?.none&&t.mode===`update`&&s.push(`Nothing to update: ${d.none}`);let f={line:e.line,cells:e.cells,values:a,problems:s};return s.length>0?f:d&&`key`in d?{...f,op:{op:`update`,resource:r.name,key:d.key,etag:`*`,data:u}}:{...f,op:{op:`create`,resource:r.name,data:u}}})},eye=5,tye=5,nye=async(e,t)=>{let n=e.rows(t),{value:r=[]}=await n.next();await n.return(void 0);let[i,...a]=r;return{headers:(i?.cells??[]).map(o7),sample:a.slice(0,eye)}};async function*A7(e,t){let n=!0;for await(let r of e.rows(t))yield n?r.slice(1):r,n=!1}var rye=async(e,t,n,r,i,a)=>{let o={rows:0,creates:0,updates:0,problems:[],preview:[]};for await(let s of A7(e,t)){a?.throwIfAborted();for(let e of await k7(s,n,r))o.rows++,o.preview.length<tye&&o.preview.push(e),e.op?.op===`create`?o.creates++:e.op?.op===`update`?o.updates++:o.problems.push({line:e.line,cells:e.cells,problems:e.problems});i(o.rows)}return o},iye=(e,t)=>{if(!Rs(e))return[e.message];let n=e.errors.filter(e=>e.field);return n.length===0?[e.message]:n.map(e=>`${u7(t.views[t.model.name],e.field)}: ${e.message}`)},aye=async(e,t,n,r,{client:i,onProgress:a,cancelled:o})=>{let s={created:0,updated:0,skipped:0,failed:0,notWritten:[]},c=async e=>{let t=[...e];for(;t.length>0;){let e=t.map(e=>e.op);try{let{results:t}=await i.batchWrite(e);for(let e of t)e.op===`create`?s.created++:e.op===`update`&&s.updated++;return}catch(e){let n=Rs(e)?e.operation:void 0;if(n===void 0||!t[n])throw e;let[i]=t.splice(n,1);s.failed++,s.notWritten.push({line:i.line,cells:i.cells,problems:iye(e,r)})}}},l=[],u=async e=>{for(;l.length>=100||e&&l.length>0;){if(o())return!1;await c(l.splice(0,100)),a({...s})}return!0};for await(let i of A7(e,t)){for(let e of await k7(i,n,r))e.op?l.push(e):(s.skipped++,s.notWritten.push({line:e.line,cells:e.cells,problems:e.problems}));if(!await u(!1))return{...s,cancelled:!0}}return await u(!0)?{...s,cancelled:!1}:{...s,cancelled:!0}},j7=50,M7=(e,t,n)=>Af(Fve(t,n),`${(e??`import`).replace(/\.[^.]+$/,``)} - not imported.csv`,`text/csv`),N7=({rows:e})=>(0,V.jsxs)(`ul`,{"aria-label":`Rows not imported`,className:`flex flex-col gap-1 text-xs`,children:[e.slice(0,j7).map(e=>(0,V.jsxs)(`li`,{children:[(0,V.jsxs)(`span`,{className:`font-medium`,children:[`Row `,e.line,`:`]}),` `,e.problems.join(`; `)]},e.line)),e.length>j7&&(0,V.jsxs)(`li`,{className:`text-muted-foreground`,children:[`And `,(e.length-j7).toLocaleString(`en-IE`),` more rows, all in the file.`]})]}),oye=({rows:e})=>(0,V.jsxs)(`p`,{className:`flex items-center gap-2 text-muted-foreground`,role:`status`,children:[(0,V.jsx)(ld,{className:`size-3.5`}),`Checking rows… `,e.toLocaleString(`en-IE`),` read`]}),sye=({check:e,model:t,resources:n,views:r,columns:i,headers:a,fileName:o})=>{let s=r[t.name],c=i.map(e=>t.fields[e.field]);return(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsx)(l7,{label:`Check`,counts:[[`Rows`,e.rows],[`To create`,e.creates],[`To update`,e.updates],[`With problems`,e.problems.length]]}),e.preview.length>0&&(0,V.jsx)(`div`,{className:`overflow-x-auto rounded-lg border`,children:(0,V.jsxs)(`table`,{"aria-label":`First rows`,className:`w-full text-left text-xs`,children:[(0,V.jsx)(`thead`,{className:`bg-muted text-muted-foreground`,children:(0,V.jsxs)(`tr`,{children:[(0,V.jsx)(`th`,{className:`px-2 py-1.5 font-medium`,children:`Row`}),c.map(e=>(0,V.jsx)(`th`,{className:`whitespace-nowrap px-2 py-1.5 font-medium`,children:u7(s,e.name)},e.name))]})}),(0,V.jsx)(`tbody`,{className:`divide-y`,children:e.preview.map(e=>(0,V.jsxs)(`tr`,{className:e.problems.length>0?`bg-danger-soft`:void 0,children:[(0,V.jsx)(`td`,{className:`px-2 py-1.5 tabular-nums text-muted-foreground`,children:e.line}),c.map(t=>(0,V.jsx)(`td`,{className:`max-w-48 truncate px-2 py-1.5`,children:p7(t,n)?String(e.values[t.name]??`—`):t.name in e.values?eS(t,e.values[t.name],s?.fields[t.name]):``},t.name))]},e.line))})]})}),e.problems.length>0&&(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,V.jsx)(`h3`,{className:`font-medium`,children:`Rows with problems, which are skipped`}),(0,V.jsxs)(U,{size:`sm`,onClick:()=>M7(o,a,e.problems),children:[(0,V.jsx)(We,{className:`size-3.5`}),`Download`]})]}),(0,V.jsx)(N7,{rows:e.problems})]}),(0,V.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`Rows are saved in batches of `,100,`. Cancelling, or an error, keeps the batches already saved; a row the server refuses is listed and the others are saved.`]})]})},P7=({label:e,name:t,value:n,options:r,onChange:i,help:a,className:s})=>{let c=(0,o.useId)();return(0,V.jsxs)(`div`,{className:B(`flex min-w-0 flex-col gap-1.5`,s),children:[(0,V.jsx)(`label`,{htmlFor:c,className:`font-medium`,children:e}),(0,V.jsx)(`select`,{id:c,"aria-label":t,value:n,onChange:e=>i(e.target.value),className:`h-8 w-full min-w-0 rounded-md border border-border-strong bg-background px-2 shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20 max-sm:min-h-11`,children:r.map(e=>(0,V.jsx)(`option`,{value:e.value,children:e.label},e.value))}),a&&(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:a})]})},cye=({file:e,sheets:t,sheet:n,reading:r,onChoose:i,onSheet:a})=>{let s=(0,o.useId)();return(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsx)(`label`,{htmlFor:s,className:`font-medium`,children:`File`}),(0,V.jsx)(`input`,{id:s,type:`file`,accept:`.xlsx,.csv,text/csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,disabled:r,onChange:e=>{let t=e.target.files?.[0];t&&i(t)},className:`file:mr-3 file:h-8 file:rounded-md file:border file:border-border-strong file:bg-background file:px-3 file:font-medium file:text-foreground max-sm:file:min-h-11`}),(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`An Excel workbook (.xlsx) or a CSV file saved as UTF-8. Its first row names the columns.`})]}),r&&(0,V.jsxs)(`p`,{className:`flex items-center gap-2 text-muted-foreground`,role:`status`,children:[(0,V.jsx)(ld,{className:`size-3.5`}),`Reading `,e?.name??`the file`,`…`]}),!r&&t.length>1&&(0,V.jsxs)(`div`,{className:`flex items-end gap-3`,children:[(0,V.jsx)(tee,{className:`mb-2 size-4 shrink-0 text-muted-foreground`}),(0,V.jsx)(P7,{className:`flex-1`,label:`Sheet`,value:n??``,options:t.map(e=>({value:e,label:e})),onChange:a})]})]})},lye=[{value:`create`,label:`Create`},{value:`update`,label:`Update`},{value:`upsert`,label:`Create or update`}],uye={create:`Each row creates a record.`,update:`Each row updates the record its value finds; a row that finds none is not imported.`,upsert:`Each row updates the record its value finds, or creates one when it finds none.`},F7=``,dye=({flow:e,model:t,resources:n,views:r,canUpdate:i})=>{let a=r[t.name],o=e.head?.headers??[],s=e.head?.sample??[],c=_7(e.mode,e.fields,e.columns),l=[{value:F7,label:`Do not import`},...e.fields.map(e=>({value:e.name,label:`${u7(a,e.name)}${m7(e)?` *`:``}`}))],u=o.map((e,t)=>({value:String(t),label:c7(o,t)})),d=f7(t);return(0,V.jsxs)(`div`,{className:`flex flex-col gap-5`,children:[i&&(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsx)(`span`,{className:`font-medium`,children:`Rows`}),(0,V.jsx)(`div`,{children:(0,V.jsx)(Pu,{label:`What each row does`,size:`md`,value:e.mode,options:lye,onChange:e.setMode})}),(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:uye[e.mode]})]}),e.mode!==`create`&&(0,V.jsxs)(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[(0,V.jsx)(P7,{label:`Find records by`,value:e.match?.field??F7,options:[{value:F7,label:`Choose a field`},...d.map(e=>({value:e.name,label:u7(a,e.name)}))],onChange:t=>e.setMatch(t?{field:t,column:e.match?.column??0}:void 0),help:`A field no two records share, such as the key or an email.`}),(0,V.jsx)(P7,{label:`Found in column`,value:e.match?String(e.match.column):F7,options:[{value:F7,label:`Choose a column`},...u],onChange:t=>e.setMatch(t&&e.match?{...e.match,column:Number(t)}:e.match)})]}),(0,V.jsxs)(`div`,{className:`grid grid-cols-1 gap-3 sm:grid-cols-2`,children:[(0,V.jsx)(P7,{label:`Numbers`,value:e.options.decimal,options:[{value:`.`,label:`1,234.56`},{value:`,`,label:`1.234,56`}],onChange:t=>e.setOptions({...e.options,decimal:t})}),(0,V.jsx)(P7,{label:`Dates`,value:e.options.dateOrder,options:[{value:`dmy`,label:`Day first (31/12/2026)`},{value:`mdy`,label:`Month first (12/31/2026)`}],onChange:t=>e.setOptions({...e.options,dateOrder:t}),help:`Dates written as 2026-12-31 read the same either way. Times without a zone are your own time.`})]}),e.mode!==`update`&&(0,V.jsx)(`p`,{className:`-mb-3 text-xs text-muted-foreground`,children:`New records need the fields marked *.`}),(0,V.jsx)(`section`,{"aria-label":`Columns`,className:`flex flex-col divide-y divide-border border-y`,children:o.map((i,c)=>{let u=e.columns.find(e=>e.column===c),d=u?t.fields[u.field]:void 0,f=d?p7(d,n):void 0,p=s.map(e=>o7(e.cells[c]??null)).filter(e=>e!==``).slice(0,3),m=c7(o,c);return(0,V.jsxs)(`div`,{className:`grid grid-cols-1 gap-2 py-3 sm:grid-cols-2 sm:gap-4`,children:[(0,V.jsxs)(`div`,{className:`min-w-0`,children:[(0,V.jsx)(`p`,{className:`truncate font-medium`,children:m}),(0,V.jsx)(`p`,{className:`truncate text-xs text-muted-foreground`,children:p.length>0?p.join(`, `):`Empty in the first rows`})]}),(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:[(0,V.jsx)(P7,{label:`Field`,name:`Field for ${m}`,value:u?.field??F7,options:l,onChange:t=>e.mapColumn(c,t||void 0)}),f&&(0,V.jsx)(P7,{label:`Found by`,name:`${r[f.name]?.names?.plural??u7(a,d.name)} found by`,value:u.matchBy??f.primaryKey[0],options:f7(f).map(e=>({value:e.name,label:u7(r[f.name],e.name)})),onChange:t=>e.matchColumnBy(c,t)})]})]},c)})}),c.length>0&&(0,V.jsxs)(`p`,{role:`alert`,className:`flex gap-2 rounded-lg border border-warning/30 bg-warning-soft px-3 py-2 text-warning-text`,children:[(0,V.jsx)(Vn,{className:`mt-0.5 size-4 shrink-0`}),(0,V.jsxs)(`span`,{children:[`No column fills `,c.map(e=>u7(a,e.name)).join(`, `),`, which new records need.`]})]})]})},I7=e=>e.toLocaleString(`en-IE`),fye=({progress:e,total:t,cancelling:n})=>{let r=e.created+e.updated+e.failed;return(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2 text-xs`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:n?`Stopping after this batch…`:`Saving rows…`}),(0,V.jsxs)(`span`,{className:`tabular-nums`,children:[I7(r),` / `,I7(t)]})]}),(0,V.jsx)(`div`,{role:`progressbar`,"aria-label":`Rows saved`,"aria-valuenow":r,"aria-valuemin":0,"aria-valuemax":t,className:`h-2 overflow-hidden rounded-full bg-muted`,children:(0,V.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-[width]`,style:{width:`${t>0?Math.min(100,r/t*100):0}%`}})})]})},pye=({result:e,stopped:t,headers:n,fileName:r})=>(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[t!==void 0&&(0,V.jsx)(ax,{title:`The import stopped. The rows counted below were saved.`,error:t}),e.cancelled&&(0,V.jsx)(`p`,{role:`status`,children:`Cancelled. The rows counted below were saved.`}),(0,V.jsx)(l7,{label:`Import summary`,counts:[[`Created`,e.created],[`Updated`,e.updated],[`Skipped`,e.skipped],[`Failed`,e.failed]]}),e.notWritten.length>0&&(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-center justify-between gap-2`,children:[(0,V.jsx)(`h3`,{className:`font-medium`,children:`Rows not imported`}),(0,V.jsxs)(U,{size:`sm`,onClick:()=>M7(r,n,e.notWritten),children:[(0,V.jsx)(We,{className:`size-3.5`}),`Download`]})]}),(0,V.jsx)(`p`,{className:`text-xs text-muted-foreground`,children:`Skipped rows had problems in the file; the server refused the failed ones. The file holds each with the reason, to fix and import again.`}),(0,V.jsx)(N7,{rows:[...e.notWritten].sort((e,t)=>e.line-t.line)})]})]}),mye=e=>{let t=hb(e),n=new Intl.DateTimeFormat(e).formatToParts(new Date(2026,3,3)).map(e=>e.type);return{decimal:t,dateOrder:n.indexOf(`month`)<n.indexOf(`day`)?`mdy`:`dmy`}},hye=co(),L7=100,R7=e=>String(e),gye=e=>{let t=new Map,n=(e,n)=>{let r=`${e}.${n}`;return t.has(r)||t.set(r,new Map),t.get(r)};return{load:async(t,r,i)=>{let a=n(t.name,r),o=[...new Map(i.filter(e=>!a.has(R7(e))).map(e=>[R7(e),e])).values()],s=t.primaryKey[0];for(let n=0;n<o.length;n+=L7){let i=o.slice(n,n+L7);for(let e of i)a.set(R7(e),[]);let c=qa(hye.in(r,i)),l;do{let n=await e(t.name).list(t.name,{filter:c,fields:[...new Set([s,r])],pageSize:1e3,pageToken:l});for(let e of n.items)a.get(R7(e[r]))?.push(e[s]);l=n.nextPageToken||void 0}while(l)}},keysOf:(e,t,r)=>n(e,t).get(R7(r))??[]}},_ye=500,z7=()=>{let e=new Worker(new URL(`/assets/parse-worker-BtcY0dQw.js`,``+import.meta.url),{type:`module`}),t=[],n;return e.onmessage=e=>{if(n){let t=n;n=void 0,t(e.data)}else t.push(e.data)},e.onerror=e=>{e.preventDefault();let r={type:`error`,message:`The file could not be read`};n?n(r):t.push(r)},{send:t=>e.postMessage(t),receive:()=>t.length>0?Promise.resolve(t.shift()):new Promise(e=>n=e),stop:()=>e.terminate()}},vye=e=>({sheets:async()=>{let t=z7();try{t.send({type:`sheets`,file:e});let n=await t.receive();if(n.type===`error`)throw Error(n.message);if(n.type!==`sheets`)throw Error(`The parse worker answered ${n.type} to a request for sheets`);return n.sheets}finally{t.stop()}},rows:async function*(t){let n=z7();try{for(n.send({type:`read`,file:e,sheet:t,chunk:_ye});;){let e=await n.receive();if(e.type===`error`)throw Error(e.message);if(e.type===`end`)return;if(e.type!==`rows`)throw Error(`The parse worker answered ${e.type} to a read`);yield e.rows,n.send({type:`next`})}}finally{n.stop()}}}),B7={created:0,updated:0,skipped:0,failed:0,notWritten:[]},yye=({model:e,resources:t,views:n,sourceFor:r=vye})=>{let i=Lne(),a=Gp(),s=n[e.name],c=(0,o.useMemo)(()=>Lve(e,t),[e,t]),[l,u]=(0,o.useState)({kind:`file`,reading:!1}),[d,f]=(0,o.useState)(),[p,m]=(0,o.useState)(),[h,g]=(0,o.useState)(),[_,v]=(0,o.useState)(),[y,b]=(0,o.useState)(`create`),[x,S]=(0,o.useState)([]),[C,w]=(0,o.useState)(),[T,E]=(0,o.useState)(()=>mye()),D=(0,o.useRef)(!1),O=(0,o.useRef)(void 0),k=e=>t=>{f(t),u(e)},A=e=>{f(void 0),u({kind:`file`,reading:!0});let t=r(e);t.sheets().then(n=>{if(m({file:e,source:t,sheets:n}),g(n[0]),n.length<=1)return j(t,n[0]);u({kind:`file`,reading:!1})}).catch(k({kind:`file`,reading:!1}))},j=async(t,n)=>{u({kind:`file`,reading:!0});let r=await nye(t,n);v(r),S(g7(r.headers,c,s));let i=f7(e)[0],a=i?g7(r.headers,[i],s)[0]:void 0;w(i&&a?{field:i.name,column:a.column}:void 0),u({kind:`map`})},M=()=>{p&&(f(void 0),j(p.source,h).catch(k({kind:`file`,reading:!1})))},N=(e,t)=>S(n=>{let r=n.filter(n=>n.column!==e&&n.field!==t);return t?[...r,{column:e,field:t}].sort((e,t)=>e.column-t.column):r}),ee=(e,t)=>S(n=>n.map(n=>n.column===e?{...n,matchBy:t}:n)),P=()=>({mode:y,columns:x,match:y===`create`?void 0:C,options:T}),te=()=>({model:e,resources:t,views:n,lookups:gye(i)});return{step:l,error:d,file:p?.file,sheets:p?.sheets??[],sheet:h,setSheet:g,head:_,fields:c,mode:y,setMode:b,columns:x,mapColumn:N,matchColumnBy:ee,match:C,setMatch:w,options:T,setOptions:E,choose:A,openSheet:M,check:()=>{if(!p)return;f(void 0);let e=new AbortController;O.current=e,u({kind:`checking`,rows:0}),rye(p.source,h,P(),te(),e=>u({kind:`checking`,rows:e}),e.signal).then(t=>{e.signal.aborted||u({kind:`checked`,check:t})}).catch(t=>{e.signal.aborted||k({kind:`map`})(t)})},back:()=>{O.current?.abort(),f(void 0),u({kind:`map`})},start:t=>{if(!p)return;f(void 0),D.current=!1,u({kind:`importing`,progress:B7,total:t,cancelling:!1});let n=B7;aye(p.source,h,P(),te(),{client:i(e.name),onProgress:e=>{n=e,u({kind:`importing`,progress:e,total:t,cancelling:D.current})},cancelled:()=>D.current}).then(e=>u({kind:`done`,result:e})).catch(e=>u({kind:`done`,result:{...n,cancelled:!1},stopped:e})).finally(()=>{for(let t of[`page`,`list`,`first-page`,`map`,`facets`,`series`])a.invalidateQueries({queryKey:[t,e.name]})})},cancel:()=>{D.current=!0,u(e=>e.kind===`importing`?{...e,cancelling:!0}:e)},stop:()=>O.current?.abort()}},bye=e=>e.step.kind===`file`?`Could not read the file`:`Could not check the rows`,xye=e=>e.columns.length===0?!1:e.mode===`create`?_7(`create`,e.fields,e.columns).length===0:e.match!==void 0,Sye=({model:e,resources:t,views:n,canUpdate:r,onClose:i,sourceFor:a})=>{let o=yye({model:e,resources:t,views:n,sourceFor:a}),s=n[e.name]?.names?.plural??K(e.name),{step:c}=o,l=o.head?.headers??[],u=()=>{c.kind!==`importing`&&(o.stop(),i())},d=(0,V.jsx)(U,{onClick:u,children:`Cancel`});return(0,V.jsx)(dT,{open:!0,wide:!0,title:`Import ${s.toLowerCase()}`,description:o.file&&c.kind!==`file`?o.file.name:void 0,onClose:u,actions:(()=>{switch(c.kind){case`file`:return(0,V.jsxs)(V.Fragment,{children:[d,o.sheets.length>1&&(0,V.jsx)(U,{variant:`primary`,loading:c.reading,onClick:o.openSheet,children:`Next`})]});case`map`:return(0,V.jsxs)(V.Fragment,{children:[d,(0,V.jsx)(U,{variant:`primary`,disabled:!xye(o),onClick:o.check,children:`Check rows`})]});case`checking`:return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:o.back,children:`Back`}),(0,V.jsx)(U,{variant:`primary`,loading:!0,children:`Checking`})]});case`checked`:{let e=c.check.creates+c.check.updates;return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:o.back,children:`Back`}),(0,V.jsxs)(U,{variant:`primary`,disabled:e===0,onClick:()=>o.start(e),children:[`Import `,e.toLocaleString(`en-IE`),` `,e===1?`row`:`rows`]})]})}case`importing`:return(0,V.jsx)(U,{variant:`danger`,disabled:c.cancelling,onClick:o.cancel,children:`Cancel import`});case`done`:return(0,V.jsx)(U,{variant:`primary`,onClick:i,children:`Done`})}})(),children:(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[o.error!==void 0&&(0,V.jsx)(ax,{title:bye(o),error:o.error}),(()=>{switch(c.kind){case`file`:return(0,V.jsx)(cye,{file:o.file,sheets:o.sheets,sheet:o.sheet,reading:c.reading,onChoose:o.choose,onSheet:o.setSheet});case`map`:return(0,V.jsx)(dye,{flow:o,model:e,resources:t,views:n,canUpdate:r});case`checking`:return(0,V.jsx)(oye,{rows:c.rows});case`checked`:return(0,V.jsx)(sye,{check:c.check,model:e,resources:t,views:n,columns:o.columns,headers:l,fileName:o.file?.name});case`importing`:return(0,V.jsx)(fye,{progress:c.progress,total:c.total,cancelling:c.cancelling});case`done`:return(0,V.jsx)(pye,{result:c.result,stopped:c.stopped,headers:l,fileName:o.file?.name})}})()]})})},Cye=({model:e})=>{let{resources:t,views:n}=J(),r=YS(e.name),[i,a]=(0,o.useState)(!1);return n[e.name]?.import===!1||!MT(r,`create`)?null:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{onClick:()=>a(!0),"aria-haspopup":`dialog`,children:[(0,V.jsx)(Gn,{className:`size-3.5`}),`Import`]}),i&&(0,V.jsx)(Sye,{model:e,resources:t,views:n,canUpdate:MT(r,`update`),onClose:()=>a(!1)})]})},wye=()=>new DOMException(`The export was cancelled`,`AbortError`),Tye=async({client:e,resource:t,filters:n,orderBy:r,plan:i,labels:a,limit:o,port:s,sink:c,signal:l,onProgress:u})=>{let d=i.columns.map(e=>e.name),f=0;try{await c.write(await s.send({kind:`start`,plan:i}));for(let[i,p]of n.entries()){let m=``;do{let h=await e.search(t,{filter:p,orderBy:r,pageSize:500,pageToken:m,fields:d,labels:a});if(l.aborted)throw wye();let g=h.items.slice(0,o-f);if(await c.write(await s.send({kind:`page`,records:g,labels:h.labels??{}})),f+=g.length,u(f),m=h.nextPageToken,f>=o)return await V7(s,c),{rows:f,truncated:g.length<h.items.length||m!==``||i+1<n.length}}while(m!==``)}return await V7(s,c),{rows:f,truncated:!1}}catch(e){throw await c.abort(),e}finally{s.close()}},V7=async(e,t)=>{await t.write(await e.send({kind:`finish`})),await t.close()},Eye=1048575,H7=`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
|
69
|
-
`,U7=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,W7=`http://schemas.openxmlformats.org/package/2006/relationships`;`${H7}`,`${H7}${W7}${U7}`,`${H7}${W7}${U7}${U7}`,new TextEncoder;var Dye=co(),G7=e=>e?.export!==!1,K7=e=>Object.values(e.fields).flatMap(e=>e.sensitive?[]:[e.name]),Oye=(e,t)=>{let n=new Set(K7(e));return Zx(e,t).filter(e=>n.has(e))},q7=(e,t,n)=>Object.fromEntries(Qx(e,t,[],n).map(e=>[e.id,e.header])),kye=(e,t,n)=>{let r=q7(e,t,n);return n.flatMap(n=>{let i=e.fields[n];return i?[{name:n,header:r[n],field:i,hints:t?.fields[n]??{}}]:[]})},J7=(e,t)=>{let n=e?.export?e.export.maxRows??1/0:1/0;return Math.min(n,t===`xlsx`?Eye:1/0)},Y7=e=>e.primaryKey.length===1,Aye=(e,t)=>{let[n]=e.primaryKey;if(!n||e.primaryKey.length!==1)throw Error(`Not implemented: selected rows are exported by a single-field key`);let r=[];for(let e=0;e<t.length;e+=500)r.push(qa(Dye.in(n,t.slice(e,e+500))));return r},jye=()=>{let e=new Worker(new URL(`/assets/export-worker-BoAr3vuF.js`,``+import.meta.url),{type:`module`,name:`protobase-export`}),t=[];return e.onmessage=e=>t.shift()?.resolve(e.data.bytes),e.onerror=e=>{e.preventDefault();let n=Error(`The export could not be built: ${e.message}`);for(let e of t.splice(0))e.reject(n)},{send:n=>new Promise((r,i)=>{t.push({resolve:r,reject:i}),e.postMessage(n)}),close:()=>e.terminate()}},Mye=[{value:`xlsx`,label:`Excel (.xlsx)`},{value:`csv`,label:`CSV`}],Nye=[{value:`shown`,label:`As shown`},{value:`raw`,label:`Raw values`}],Pye={shown:`Labels, dates and numbers as the list shows them.`,raw:`Values as they are stored, such as keys and codes.`},Fye=e=>e.kind===`counting`?`Counting rows…`:e.kind===`exact`||e.rows>1e4?Ud(e.rows):`more than 10,000 rows`,X7=e=>{if(e.kind!==`counting`)return e.kind===`exact`?e.rows:Math.max(e.rows,10001)},Z7=({label:e,help:t,children:n})=>(0,V.jsxs)(`div`,{className:`flex flex-col items-start gap-1.5`,children:[(0,V.jsx)(`span`,{className:`text-[13px] font-medium`,children:e}),n,t&&(0,V.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t})]}),Q7=(e,t,n)=>{let r=e.indexOf(t),i=[...e];return i.splice(r,1),i.splice(r+n,0,t),i},Iye=({fields:e,columns:t,onChange:n})=>{let r=Object.fromEntries(e.map(e=>[e.name,e.label])),i=[...t,...e.map(e=>e.name).filter(e=>!t.includes(e))];return(0,V.jsx)(`ul`,{className:`divide-y self-stretch rounded-md border`,"aria-label":`Columns`,children:i.map(e=>{let i=t.includes(e),a=t.indexOf(e);return(0,V.jsxs)(`li`,{className:`flex min-h-10 items-center gap-2 px-3 py-1`,children:[(0,V.jsxs)(`label`,{className:`flex min-w-0 flex-1 cursor-pointer items-center gap-2.5`,children:[(0,V.jsx)(Fh,{checked:i,label:r[e],onChange:r=>n(r?[...t,e]:t.filter(t=>t!==e))}),(0,V.jsx)(`span`,{className:i?`truncate`:`truncate text-muted-foreground`,children:r[e]})]}),i&&(0,V.jsxs)(`span`,{className:`flex shrink-0 gap-1`,children:[(0,V.jsx)(U,{size:`sm`,variant:`ghost`,className:`min-h-8 px-2`,"aria-label":`Move ${r[e]} up`,disabled:a===0,onClick:()=>n(Q7(t,e,-1)),children:(0,V.jsx)(A,{className:`size-3.5`})}),(0,V.jsx)(U,{size:`sm`,variant:`ghost`,className:`min-h-8 px-2`,"aria-label":`Move ${r[e]} down`,disabled:a===t.length-1,onClick:()=>n(Q7(t,e,1)),children:(0,V.jsx)(S,{className:`size-3.5`})})]})]},e)})})},Lye=({plural:e,view:t,fields:n,initialColumns:r,count:i,selected:a,open:s,onExport:c,onClose:l})=>{let[u,d]=(0,o.useState)(`xlsx`),[f,p]=(0,o.useState)(a?`selected`:`list`),[m,h]=(0,o.useState)(r),[g,_]=(0,o.useState)(`shown`),v=J7(t,u),y=f===`selected`?`${Bd(a??0)} selected ${a===1?`row`:`rows`}`:Fye(i),b=(f===`selected`?a??0:X7(i)??0)>v,x=[{value:`list`,label:`Rows in the list`},{value:`selected`,label:`Selected (${Bd(a??0)})`}];return(0,V.jsx)(dT,{title:`Export ${e.toLowerCase()}`,open:s,onClose:l,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:l,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,disabled:m.length===0,onClick:()=>c({format:u,scope:f,columns:m,mode:g}),children:`Export`})]}),children:(0,V.jsxs)(`div`,{className:`flex flex-col gap-4 text-[13px]`,children:[(0,V.jsx)(Z7,{label:`Format`,children:(0,V.jsx)(Pu,{size:`md`,label:`Format`,value:u,options:Mye,onChange:d})}),a!==void 0&&a>0&&(0,V.jsx)(Z7,{label:`Rows`,help:f===`list`?`With the list’s filters, search and sort.`:void 0,children:(0,V.jsx)(Pu,{size:`md`,label:`Rows`,value:f,options:x,onChange:p})}),(0,V.jsx)(Z7,{label:`Values`,help:Pye[g],children:(0,V.jsx)(Pu,{size:`md`,label:`Values`,value:g,options:Nye,onChange:_})}),(0,V.jsx)(Z7,{label:`Columns`,children:(0,V.jsx)(Iye,{fields:n,columns:m,onChange:h})}),(0,V.jsxs)(`p`,{role:`status`,className:`text-muted-foreground`,children:[`Exports `,y,`.`,b&&` A file holds at most ${Bd(v)} rows; the rest are left out.`]})]})})},Rye=({plural:e,done:t,total:n,onCancel:r})=>{let i=n?Math.min(1,t/n):void 0;return(0,V.jsx)(dT,{title:`Exporting ${e.toLowerCase()}`,open:!0,onClose:r,actions:(0,V.jsx)(U,{onClick:r,children:`Cancel`}),children:(0,V.jsxs)(`div`,{className:`flex flex-col gap-2 text-[13px]`,children:[(0,V.jsx)(`div`,{role:`progressbar`,"aria-label":`Rows exported`,"aria-valuemin":0,"aria-valuemax":n,"aria-valuenow":t,className:`h-1.5 overflow-hidden rounded-full bg-muted`,children:(0,V.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-[width]`,style:{width:`${(i??0)*100}%`}})}),(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:n?`${Bd(t)} of ${Bd(n)} rows`:`${Bd(t)} rows`})]})})},$7={xlsx:{mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,extension:`.xlsx`,description:`Excel workbook`},csv:{mime:`text/csv`,extension:`.csv`,description:`CSV file`}},zye=/[\\/:*?"<>|\u0000-\u001f]/g,Bye=(e,t,n=new Date)=>{let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,`0`),String(n.getDate()).padStart(2,`0`)].join(`-`);return`${e.replace(zye,` `).trim()} ${r}${$7[t].extension}`},Vye=8e6,Hye=(e,t)=>{let n=new Blob([],{type:$7[t].mime}),r=[],i=0,a=()=>{n=new Blob([n,...r],{type:$7[t].mime}),r=[],i=0};return{write:async e=>{e.length!==0&&(r.push(e),i+=e.length,i>=Vye&&a())},close:async()=>{a();let t=URL.createObjectURL(n),r=document.createElement(`a`);r.href=t,r.download=e,r.click(),setTimeout(()=>URL.revokeObjectURL(t),6e4)},abort:async()=>{r=[],n=new Blob([])}}},e9=()=>globalThis.showSaveFilePicker,Uye=()=>typeof e9()==`function`,Wye=async(e,t)=>{let n=e9();if(!n)throw Error(`This browser cannot save a file as it is built`);let r=$7[t],i;try{i=await n({suggestedName:e,types:[{description:r.description,accept:{[r.mime]:[r.extension]}}]})}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}let a=await i.createWritable();return{write:async e=>{e.length>0&&await a.write(e)},close:()=>a.close(),abort:()=>a.abort()}},Gye=(e,t)=>Uye()?Wye(e,t):Promise.resolve(Hye(e,t)),Kye=(e,t)=>{let n=t[e.primaryKey[0]];return typeof n==`object`&&n&&`id`in n?n.id:n},qye=({model:e,view:t,resources:n,views:r,plural:i,filter:a,orderBy:s,createPort:c=jye,createSink:l=Gye})=>{let u=G(),d=Qy(),[f,p]=(0,o.useState)({kind:`closed`}),m=(0,o.useRef)(void 0),h=mh({queryKey:W.exportCount(e.name,a),enabled:f.kind===`settings`,queryFn:async()=>{let t=await u.list(e.name,{filter:a||void 0,pageSize:1,count:`exact`,fields:e.primaryKey});return t.totalSize===void 0?{kind:`estimate`,rows:t.totalSizeEstimate}:{kind:`exact`,rows:t.totalSize}}}).data??{kind:`counting`},g=(t=[])=>p({kind:`settings`,selected:Y7(e)?t.map(t=>Kye(e,t)):[]}),_=async(o,f)=>{let g=Bye(i,o.format),_=await l(g,o.format);if(!_)return;let v=J7(t,o.format),y=o.scope===`selected`?f.length:X7(h),b=y===void 0?void 0:Math.min(y,v),x=new AbortController;m.current=x,p({kind:`running`,done:0,total:b});try{let l=await Tye({client:u,resource:e.name,filters:o.scope===`selected`?Aye(e,f):[a],orderBy:s,plan:{format:o.format,mode:o.mode,name:i,columns:kye(e,t,o.columns)},labels:o.mode===`shown`?u4(n,r,e,o.columns):{},limit:v,port:c(),sink:_,signal:x.signal,onProgress:e=>x.signal.aborted||p({kind:`running`,done:e,total:b})});d.show({state:`success`,title:`Exported ${Bd(l.rows)} ${i.toLowerCase()}`,description:l.truncated?`${g}: the first ${Bd(l.rows)} rows, as many as a file holds.`:g})}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;if(!Rs(e))throw e;d.show({state:`error`,title:`Could not export ${i.toLowerCase()}`,description:e.message})}finally{m.current=void 0,p(e=>e.kind===`running`?{kind:`closed`}:e)}},v=()=>{m.current?.abort(),p({kind:`closed`})},y=K7(e),b=q7(e,t,y);return{open:g,dialogs:f.kind===`settings`?(0,V.jsx)(Lye,{plural:i,view:t,fields:y.map(e=>({name:e,label:b[e]})),initialColumns:Oye(e,t),count:h,selected:f.selected.length>0?f.selected.length:void 0,open:!0,onExport:e=>void _(e,f.selected),onClose:()=>p({kind:`closed`})}):f.kind===`running`?(0,V.jsx)(Rye,{plural:i,done:f.done,total:f.total,onCancel:v}):null}},Jye=({state:e,onClearSearch:t,onClearFilters:n,create:r})=>(0,V.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-8 text-center text-muted-foreground`,children:[(0,V.jsx)(`p`,{children:e.message}),(e.clearSearch||e.clearFilters||e.create&&r)&&(0,V.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[e.clearSearch&&(0,V.jsx)(U,{onClick:t,children:`Clear search`}),e.clearFilters&&(0,V.jsx)(U,{onClick:n,children:`Clear filters`}),e.create&&r]})]}),Yye=({plural:e,search:t,filtered:n,scoped:r,canCreate:i})=>{let a=e.toLowerCase();return t?{message:`No ${a} match “${t}”.`,clearSearch:!0,clearFilters:n,create:!1}:n?{message:`No ${a} match these filters.`,clearSearch:!1,clearFilters:!0,create:!1}:r?{message:`No ${a} match.`,clearSearch:!1,clearFilters:!1,create:!1}:{message:`No ${a} yet.`,clearSearch:!1,clearFilters:!1,create:i}},Xye=(e,t)=>{},Zye=({windowMs:e=1e3,comebacks:t=2,onHold:n=Xye}={})=>{let r,i=[],a;return(o,s)=>{if(a?.among.has(o))return a.value;if(a&&(a=void 0,i=[]),o===r||(r=o,i=i.filter(t=>s-t.at<=e),i.push({value:o,at:s,comeback:i.some(e=>e.value===o)}),i.filter(e=>e.comeback).length<t))return o;let c=new Set(i.slice(-2*t).map(e=>e.value));return a={value:Math.min(...c),among:c},n(a.value,[...c]),a.value}},Qye=e=>Math.max(1,Math.floor((e+12)/252)),$ye=(e,t)=>Math.max(0,(e-(t-1)*12)/t),ebe=(e,t,n,r)=>({start:e*n,end:Math.max(0,Math.min(r,(t+1)*n)-1)}),tbe=(e,t,n)=>{let r=e/t.rowHeight;return t.columns===n.columns?r*n.rowHeight:Math.floor(Math.floor(r)*t.columns/n.columns)*n.rowHeight},nbe=8,rbe=(e,t,n)=>{let r=e.get(t);if(r!==void 0&&r>=n)return e;let i=new Map(e);i.delete(t),i.set(t,n);for(let e of i.keys()){if(i.size<=nbe)break;i.delete(e)}return i},ibe=({source:e,label:t,initialIndex:n,onScrollIndex:r,minHeight:i,children:a})=>{let{total:s}=e,[c]=(0,o.useState)(n),[l,u]=(0,o.useState)(0),d=Qye(l),f=$ye(l,d),[p,m]=(0,o.useState)(()=>new Map),h=Math.ceil(Math.max(i(f),p.get(f)??0)),g=h+12,_={columns:d,rowHeight:g},v=(0,o.useRef)({layout:_,top:0}),y=v.current.top>0&&(v.current.layout.columns!==d||v.current.layout.rowHeight!==g),b=e=>y?tbe(v.current.top,v.current.layout,_):e,x=f>0&&p.has(f),S=x6({total:Math.ceil(s/d),rowHeight:g,initialIndex:Math.floor(c/d),settle:b,ready:x});(0,o.useLayoutEffect)(()=>{y&&S.scrollTo(S.top),v.current={layout:_,top:S.top},y||r(Math.floor(Math.max(0,S.top)/g)*d)});let C=ebe(S.first,S.last,d,s),w=p6({total:s,rowAt:e.rowAt,loadRows:e.loadRows,revision:e.revision,latencyMs:0},C.start,C.end),[T]=(0,o.useState)(()=>Zye());(0,o.useLayoutEffect)(()=>{let e=S.ref.current;if(!e)return;let t=()=>u(T(e.clientWidth,performance.now())),n=new ResizeObserver(t);return n.observe(e),t(),()=>n.disconnect()},[T]);let E=(0,o.useRef)(f);E.current=f;let[D]=(0,o.useState)(()=>new ResizeObserver(e=>{let t=Math.max(...e.map(e=>e.borderBoxSize[0]?.blockSize??e.contentRect.height)),n=E.current;m(e=>rbe(e,n,t))}));(0,o.useLayoutEffect)(()=>()=>D.disconnect(),[D]);let O=(0,o.useCallback)(e=>{if(e)return D.observe(e),()=>D.unobserve(e)},[D]);return(0,V.jsx)(`ul`,{ref:S.ref,className:`relative min-w-0 flex-auto`,"aria-label":t,style:{height:S.geometry.contentHeight},children:S.rows.flatMap(({index:e,offset:t})=>Array.from({length:d},(n,r)=>{let i=e*d+r;if(i>=s)return[];let o=w(i),c={top:t,left:r*(f+12),width:f,minHeight:h};return o?(0,V.jsx)(`li`,{ref:O,"aria-posinset":i+1,"aria-setsize":s,className:`absolute grid grid-cols-[minmax(0,1fr)]`,style:c,children:a(o)},o.id):(0,V.jsx)(`li`,{"aria-hidden":!0,className:`absolute grid grid-cols-[minmax(0,1fr)]`,style:c,children:(0,V.jsx)(cu,{className:`h-full rounded-lg`})},`skeleton-${i}`)}))})},abe=`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,obe=e=>e*.75,sbe=44,cbe=({model:e,view:t,display:n,list:r,empty:i})=>{let a=t?.names?.plural??K(e.name),o=n.card===void 0&&(n.image!==void 0||n.photos!==void 0);return r.isLoading?(0,V.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden ${abe}`,children:Array.from({length:6},(e,t)=>(0,V.jsx)(cu,{className:`h-24`},t))}):r.error?(0,V.jsx)(ax,{title:`Could not load rows`,error:r.error}):!r.source||r.source.total===0?i??(0,V.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,a.toLowerCase(),` match.`]}):(0,V.jsx)(ibe,{source:r.source,label:a,initialIndex:r.initialIndex,onScrollIndex:r.onScrollIndex,minHeight:e=>(o?obe(e):0)+sbe,children:r=>(0,V.jsx)(B8,{model:e,view:t,display:n,row:AS(e,r)})})},t9=new Map,lbe=()=>{let{entry:e,path:t,params:n}=wh(),r=`${t}?${n.toString()}`,i=t9.get(e),a=(0,o.useCallback)(t=>void t9.set(e,{url:r,index:t}),[e,r]);return{initialIndex:i?.url===r?i.index:0,remember:a}},n9=e=>e.reduce((e,t)=>e+t.count,0),ube=e=>{let t=Math.floor(e.length/2),n=n9(e.slice(0,t)),r=n9(e.slice(e.length-t));return n===0?0:(r-n)/n*100},dbe=({active:e,payload:t,noun:n})=>{let r=t?.[0]?.payload;return!e||!r?null:(0,V.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,V.jsx)(`div`,{className:`text-muted-foreground`,children:sf(r.at)}),(0,V.jsxs)(`div`,{className:`font-semibold tabular-nums`,children:[Bd(r.count),` `,n]})]})},r9={fontSize:11,fill:`var(--muted-foreground)`},fbe=({title:e=`Orders created`,noun:t=`orders`,defaultGranularity:n=`day`,data:r,granularity:i,onGranularityChange:a,periodLabel:s,className:c})=>{let[l,u]=(0,o.useState)(n),d=i??l,f=a??u,p=r??Ny(d),m=Gl(`(min-width: 640px)`),h=ube(p);return(0,V.jsxs)(`section`,{className:B(`rounded-lg border bg-background px-4 pb-2 pt-3`,c),children:[(0,V.jsxs)(`header`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,V.jsx)(`h2`,{className:`font-semibold`,children:e}),(0,V.jsx)(`span`,{className:`font-semibold tabular-nums`,children:Bd(n9(p))}),(0,V.jsxs)(`span`,{className:B(`text-xs font-medium tabular-nums`,h>=0?`text-success-text`:`text-danger-text`),children:[h>=0?`+`:`−`,Math.abs(h).toFixed(1),`%`]}),(0,V.jsx)(`span`,{className:`hidden text-xs text-muted-foreground sm:inline`,children:s??`last ${d===`day`?`30 days`:`12 weeks`}`})]}),(0,V.jsx)(Pu,{value:d,onChange:f,options:[{value:`day`,label:`Day`},{value:`week`,label:`Week`}]})]}),(0,V.jsx)(`div`,{className:`mt-2 h-24`,children:(0,V.jsx)(aM,{width:`100%`,height:`100%`,children:(0,V.jsxs)($2,{data:p,margin:{top:4,right:0,bottom:0,left:0},barCategoryGap:d===`day`?`22%`:`30%`,children:[(0,V.jsx)(r0,{vertical:!1,stroke:`var(--border)`}),(0,V.jsx)(X0,{dataKey:`at`,padding:{left:4,right:m?4:18},tickFormatter:cf,tick:r9,axisLine:!1,tickLine:!1,interval:d===`day`?m?4:9:m?1:3,height:18}),(0,V.jsx)(t2,{width:m?36:28,tick:r9,axisLine:!1,tickLine:!1,tickCount:3}),(0,V.jsx)(Zq,{cursor:{fill:`var(--muted)`},content:(0,V.jsx)(dbe,{noun:t}),isAnimationActive:!1}),(0,V.jsx)(H0,{dataKey:`count`,fill:`var(--primary)`,radius:[2,2,0,0],isAnimationActive:!1})]})})})]})},pbe={"7d":`last 7 days`,"30d":`last 30 days`,"90d":`last 90 days`,"1y":`last year`,all:`all time`},mbe=({resource:e,chart:t,title:n,noun:r,filter:i})=>{let[a,s]=(0,o.useState)(t.granularity===`week`?`week`:`day`),c=a===`week`?`90d`:t.range,l=aE(e,{field:t.field,range:c,granularity:a,filter:i,timeZone:Wd()}).data?.points.map(e=>({at:Date.parse(`${e.bucket}Z`),count:e.count}))??[];return(0,V.jsx)(fbe,{title:n,noun:r,data:l,granularity:a,onGranularityChange:s,periodLabel:a===`week`?`last 12 weeks`:pbe[c]})},i9=(e,t,n)=>{let r=e.sum??e.average;if(r===void 0)return n;let i=t?.fields[r]?.label??K(r);return e.sum===void 0?`Average ${i.toLowerCase()}`:`${i}`},hbe=({model:e,view:t,chart:n,plural:r,filter:i})=>{let a=t?.fields[n.groupBy]?.label??K(n.groupBy);return(0,V.jsxs)(`section`,{className:`rounded-lg border bg-background px-4 pb-3 pt-3`,"aria-label":`${i9(n,t,r)} by ${a.toLowerCase()}`,children:[(0,V.jsxs)(`h2`,{className:`mb-2 font-semibold`,children:[i9(n,t,r),` by `,a.toLowerCase()]}),(0,V.jsx)(s4,{model:e,view:t,groupBy:n.groupBy,type:n.type,sum:n.sum,average:n.average,limit:n.limit,filter:i})]})},gbe=({value:e,onCommit:t,placeholder:n,className:r})=>{let[i,a]=(0,o.useState)(e);return(0,o.useEffect)(()=>a(e),[e]),(0,o.useEffect)(()=>{if(i===e)return;let n=setTimeout(()=>t(i),350);return()=>clearTimeout(n)},[i,e,t]),(0,V.jsx)(sd,{wrapperClassName:B(`min-w-0 flex-1 sm:w-72 sm:flex-initial`,r),leading:(0,V.jsx)(pn,{className:`size-4`}),placeholder:n,"aria-label":`Search`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>e.key===`Enter`&&t(i)})},_be=(e,t,n,r,i)=>{let a=n?.list?.relatedColumns??[];if(a.length===0)return e;let o=new Map(e.map(e=>[e.id,e]));return Zx(t,n).flatMap(e=>{let t=o.get(e);if(t)return[t];let n=a.find(t=>t.name===e),s=n&&r[n.resource];if(!n||!s)return[];let c=n.label??K(n.name);return[{id:n.name,header:c,kind:`text`,width:160,minWidth:dx(c,!1),sortable:!1,render:e=>(0,V.jsx)(P8,{column:n,records:e[n.name]??[],target:s,view:i[s.name],Card:B8})}]})},vbe=({model:e,view:t,target:n,children:r})=>{let i=D8(e.name,t.listOf,!0),a=t.names?.plural??K(e.name),o=e=>(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[(0,V.jsx)(gd,{title:a,subtitle:t.help}),e]});if(i.error)return o((0,V.jsx)(ax,{title:`Could not load your ${a.toLowerCase()}`,error:i.error}));if(!i.data)return o((0,V.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-24`},t))}));let s=T8(n,i.data);return s?r(s):o((0,V.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,a.toLowerCase(),` yet.`]}))},a9=({title:e,chips:t,label:n,required:r,initial:i=``,busy:a,onSave:s,onClose:c})=>{let l=(0,o.useId)(),[u,d]=(0,o.useState)(i),f=`${l}-form`;return(0,V.jsx)(dT,{open:!0,title:e,onClose:c,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:c,children:`Cancel`}),(0,V.jsx)(U,{type:`submit`,form:f,variant:`primary`,loading:a,children:`Save`})]}),children:(0,V.jsxs)(`form`,{id:f,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),s(u.trim()===``?null:u.trim())},children:[t.length>0&&(0,V.jsx)(M6,{chips:t}),(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,V.jsx)(`label`,{htmlFor:l,className:`font-medium`,children:n}),!r&&(0,V.jsx)(`span`,{id:`${l}-hint`,className:`text-xs text-muted-foreground`,children:`Optional`})]}),(0,V.jsx)(sd,{id:l,value:u,required:r,pattern:r?`.*\\S.*`:void 0,"aria-describedby":r?void 0:`${l}-hint`,autoFocus:!0,autoComplete:`off`,onChange:e=>d(e.target.value)})]})]})})},o9=co(),ybe={start:0,end:0},s9=(e,t)=>o9.and(t,{kind:`present`,field:e.field,span:ybe}),c9=e=>{switch(e.kind){case`and`:case`or`:return{...e,args:e.args.map(c9)};case`not`:return l9(e.arg);case`search`:case`present`:case`isNull`:return e;default:return s9(e,e)}},l9=e=>{switch(e.kind){case`and`:return o9.or(...e.args.map(l9));case`or`:return o9.and(...e.args.map(l9));case`not`:return c9(e.arg);case`search`:case`present`:case`isNull`:return o9.not(e);default:return s9(e,o9.not(e))}},u9=e=>{let t=Sa(e);if(!t.ok)throw Error(`The filter cannot be read: ${t.errors.map(e=>e.message).join(`; `)}`);return t.ast},d9=(e,t)=>{let n=u9(e);if(!n)return null;let r=u9(t),i=o9.not(c9(n));return qa(r?o9.and(r,i):i)},bbe=(e,t)=>d9(t,e),f9=e=>e.key.startsWith(`extra:`)?`extra:${e.label}`:e.key,xbe=(e,t)=>{let n=new Map(e.map(e=>[f9(e),e])),r=new Map(t.map(e=>[f9(e),e])),i=e.filter(e=>!r.has(f9(e))).map(e=>({kind:`removed`,label:e.label})),a=t.flatMap(e=>{let t=n.get(f9(e));return t&&t.label!==e.label?[{kind:`changed`,label:e.label,before:t.label}]:[]}),o=t.filter(e=>!n.has(f9(e))).map(e=>({kind:`added`,label:e.label}));return[...i,...a,...o]},Sbe=(e,t,n,r)=>{let i=e-t;return i===0?`As many ${r}`:`${Math.abs(i)} ${i>0?`more`:`fewer`} ${Math.abs(i)===1?n:r}`},p9=12,m9={added:{word:`Added`,className:`text-success-text`},removed:{word:`Removed`,className:`text-danger-text`},changed:{word:`Changed`,className:`text-primary-text`}},Cbe=({changes:e})=>(0,V.jsx)(`ul`,{"aria-label":`Filter changes`,className:`divide-y rounded-md border`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`grid grid-cols-[72px_1fr] gap-3 px-3 py-2`,children:[(0,V.jsx)(`span`,{className:`font-medium ${m9[e.kind].className}`,children:m9[e.kind].word}),e.kind===`changed`?(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`span`,{className:`text-muted-foreground line-through`,children:e.before}),` `,(0,V.jsx)(`span`,{className:`font-medium`,children:e.label})]}):(0,V.jsx)(`span`,{className:e.kind===`removed`?`text-muted-foreground line-through`:`font-medium`,children:e.label})]},`${e.kind}:${e.label}`))}),h9=(e,t)=>{let n=mh({...UT(G(),e,t??``),enabled:t!==null});return t===null?0:n.data},wbe=(e,t,n)=>`${e} ${e===1?t:n}`,g9=({model:e,view:t,title:n,filter:r,total:i,plural:a})=>{let o=t?.list?.displays?.find(e=>e.kind===`cards`);return(0,V.jsxs)(`section`,{"aria-label":n,className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`h3`,{className:`font-semibold`,children:[n,` `,(0,V.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`(`,i??`…`,`)`]})]}),i!==void 0&&i>p9&&(0,V.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The first `,p9,` of `,i,`.`]}),r===null||i===0?(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`No `,a,`.`]}):(0,V.jsx)(K5,{model:e,view:t,filter:r,sort:jS(e,t),limit:p9,display:o?.name??`table`,row:!0,link:!1,empty:`No ${a}.`})]})},Tbe=({model:e,view:t,title:n,before:r,after:i,saveNewLabel:a,updating:s,creating:c,onUpdate:l,onSaveNew:u,onCancel:d})=>{let f=xbe(_8(e,r),_8(e,i)),p=(0,o.useMemo)(()=>d9(r,i),[r,i]),m=(0,o.useMemo)(()=>bbe(r,i),[r,i]),h=h9(e,p),g=h9(e,m),_=(t?.names?.singular??K(e.name)).toLowerCase(),v=(t?.names?.plural??K(e.name)).toLowerCase(),y=h!==void 0&&g!==void 0;return(0,V.jsx)(dT,{open:!0,wide:!0,title:n,onClose:d,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:d,children:`Cancel`}),(0,V.jsx)(U,{loading:c,disabled:s,onClick:u,children:a}),(0,V.jsx)(U,{variant:`primary`,loading:s,disabled:c,onClick:l,children:`Update`})]}),children:(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[f.length>0&&(0,V.jsx)(Cbe,{changes:f}),y?(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`span`,{className:`font-semibold`,children:Sbe(h,g,_,v)}),(0,V.jsxs)(`span`,{className:`text-muted-foreground`,children:[`: `,wbe(h,_,v),` added, `,g,` removed`]})]}):(0,V.jsx)(cu,{className:`h-4 w-48`}),(0,V.jsx)(g9,{model:e,view:t,title:`Added`,filter:p,total:h,plural:v}),(0,V.jsx)(g9,{model:e,view:t,title:`Removed`,filter:m,total:g,plural:v})]})})},Ebe=()=>{let{address:e,set:t}=XS();return{key:e?.kind===`list`?e.savedSearch:void 0,open:e=>t({savedSearch:e})}},_9=e=>e instanceof Error?e.message:`Something went wrong`,Dbe=(e,t)=>{let n=J(),r=G(),i=Qy(),a=qT(),{href:o,open:s}=XS(),c=Ebe(),{resource:l}=e,u=n.resources[l],d=n.views[l]?.searchesOf,f=n.permissions[l],p=u!==void 0&&d!==void 0&&f!==void 0&&MT(f,`create`)&&MT(f,`delete`),m=n.signIn?.[l]?.signIn,h=J8(l,p),g=e=>Ao(zx(u,e)),_=d&&h.data?.find(e=>e[d.filter]===t),v=_||c.key===void 0||!f||!MT(f,`update`)?void 0:h.data?.find(e=>g(e)===c.key),y=n.views[l]?.names,b=y?.plural??`saved searches`,x=d?.name===void 0?void 0:u?.fields[d.name],S=hh({mutationFn:e=>r.create(l,{[d.filter]:t,...d.name&&{[d.name]:e}}),onSuccess:e=>{c.open(g(e.record)),i.show({state:`success`,title:`Search saved`,action:{label:`Open ${b.toLowerCase()}`,href:o({kind:`list`,resource:l}),onNavigate:s}})},onError:e=>i.show({state:`error`,title:`Could not save the search`,description:_9(e)}),onSettled:()=>a(l)}),C=hh({mutationFn:e=>r.remove(l,g(e)),onError:e=>i.show({state:`error`,title:`Could not take the search off`,description:_9(e)}),onSettled:()=>a(l)}),w=hh({mutationFn:e=>r.update(l,g(e),{[d.filter]:t},e.etag??`*`),onSuccess:()=>i.show({state:`success`,title:`Search updated`}),onError:e=>i.show({state:`error`,title:`Could not update the search`,description:_9(e)}),onSettled:()=>a(l)}),T=S.isPending||C.isPending||w.isPending;return{mode:p?`save`:m?`sign-in`:void 0,prompt:m,saved:_!==void 0,opened:v&&{filter:String(v[d.filter]??``),name:d.name&&typeof v[d.name]==`string`&&v[d.name]!==``?String(v[d.name]):void 0},noun:(y?.singular??K(l)).toLowerCase(),naming:x&&{label:n.views[l]?.fields[x.name]?.label??K(x.name),required:!x.nullable},ready:h.data!==void 0&&!T,updating:w.isPending,creating:S.isPending,remove:()=>_&&C.mutate(_),saveNew:(e,t)=>S.mutate(e,t),update:e=>v&&w.mutate(v,e)}},Obe=({model:e,view:t,search:n,filter:r,chips:i,className:a})=>{let s=Dbe(n,r),[c,l]=(0,o.useState)(!1),[u,d]=(0,o.useState)(!1),[f,p]=(0,o.useState)();if(!s.mode)return null;let m=n.label??`Save search`;if(s.mode===`sign-in`)return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{className:a,"aria-haspopup":`dialog`,onClick:()=>l(!0),children:[(0,V.jsx)(se,{className:`size-3.5`,"aria-hidden":!0}),m]}),(0,V.jsx)(C8,{as:`dialog`,prompt:s.prompt,open:c,onClose:()=>l(!1)})]});let h=e=>{d(!1),s.naming?p(e):s.saveNew(null)},g=f!==void 0&&s.naming&&(0,V.jsx)(a9,{title:f,chips:i,label:s.naming.label,required:s.naming.required,busy:s.creating,onSave:e=>s.saveNew(e,{onSuccess:()=>p(void 0)}),onClose:()=>p(void 0)}),_=s.opened;if(_){let n=`Save as new ${s.noun}`;return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{className:a,"aria-haspopup":`dialog`,"aria-disabled":!s.ready,onClick:()=>s.ready&&d(!0),children:[(0,V.jsx)(oee,{className:`size-3.5`,"aria-hidden":!0}),(0,V.jsx)(`span`,{className:`max-w-60 truncate`,children:_.name?`Update ${_.name}`:`Update ${s.noun}`})]}),(0,V.jsxs)(U,{className:a,"aria-haspopup":s.naming?`dialog`:void 0,"aria-disabled":!s.ready,onClick:()=>s.ready&&h(n),children:[(0,V.jsx)(ae,{className:`size-3.5`,"aria-hidden":!0}),n]}),u&&(0,V.jsx)(Tbe,{model:e,view:t,title:_.name?`Update ${_.name}?`:`Update this ${s.noun}?`,before:_.filter,after:r,saveNewLabel:n,updating:s.updating,creating:s.creating,onUpdate:()=>s.update({onSuccess:()=>d(!1)}),onSaveNew:()=>h(n),onCancel:()=>d(!1)}),g]})}let v=s.saved?ie:se;return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{className:a,"aria-pressed":s.saved,"aria-haspopup":!s.saved&&s.naming?`dialog`:void 0,"aria-disabled":!s.ready,onClick:()=>s.ready&&(s.saved?s.remove():h(m)),children:[(0,V.jsx)(v,{className:s.saved?`size-3.5 text-primary`:`size-3.5`,"aria-hidden":!0}),m]}),g]})},kbe=e=>e instanceof Error?e.message:`Something went wrong`,Abe=({model:e,view:t,name:n,value:r,onChange:i})=>{let a=(0,o.useId)(),s=e.fields[n],c=t.fields[n],l=c?.label??K(n);if(s?.type===`boolean`)return(0,V.jsx)(ox,{checked:r===!0,onChange:i,label:l});if(s?.type!==`enum`)throw Error(`Not implemented: "${n}" is ${s?.type??`unknown`}, and a saved search's controls are enums or booleans`);return(0,V.jsxs)(`label`,{htmlFor:a,className:`flex items-center gap-2 text-muted-foreground`,children:[l,(0,V.jsx)(`select`,{id:a,value:String(r??``),onChange:e=>i(e.target.value),className:`h-8 rounded-md border border-border-strong bg-background px-2 text-foreground shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,children:(s.enumValues??[]).map(e=>(0,V.jsx)(`option`,{value:e,children:rs(e,c?.valueLabels)},e))})]})},jbe=(e,t,n)=>Object.entries(n).map(([n,r])=>`${t.fields[n]?.label??K(n)}: ${e.fields[n]?.type===`boolean`?r===!0?`On`:`Off`:rs(String(r),t.fields[n]?.valueLabels)}`).join(`, `),Mbe=({model:e,view:t,recordKey:n,title:r,row:i,fields:a})=>{let o=G(),s=Qy(),c=qT(),l=hh({mutationFn:t=>o.update(e.name,n,t,i.etag??`*`),onSuccess:(n,i)=>s.show({state:`success`,title:`${r} saved`,description:jbe(e,t,i)}),onError:e=>s.show({state:`error`,title:`Could not change the search`,description:kbe(e)}),onSettled:()=>c(e.name)});return(0,V.jsx)(`div`,{className:`flex flex-wrap items-center gap-3`,children:a.map(n=>(0,V.jsx)(Abe,{model:e,view:t,name:n,value:l.isPending&&n in(l.variables??{})?l.variables[n]:i[n],onChange:e=>l.mutate({[n]:e})},n))})},Nbe=e=>e instanceof Error?e.message:`Something went wrong`,Pbe=({model:e,view:t,of:n,target:r,targetView:i,row:a,recordKey:s,canRename:c,onDelete:l})=>{let u=G(),d=Qy(),f=qT(),[p,m]=(0,o.useState)(!1),{name:h,chips:g,title:_,body:v}=Y8({model:e,of:n,target:r,targetView:i,row:a,recordKey:s}),y=hh({mutationFn:t=>u.update(e.name,s,{[n.name]:t},a.etag??`*`),onSuccess:()=>m(!1),onError:e=>d.show({state:`error`,title:`Could not rename the search`,description:Nbe(e)}),onSettled:()=>f(e.name)}),b=n.name===void 0?void 0:e.fields[n.name];return(0,V.jsxs)(`section`,{"aria-label":_,className:`flex flex-col gap-3 rounded-lg border bg-surface p-4`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,V.jsx)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:(0,V.jsx)(ZS,{to:{kind:`record`,resource:e.name,key:s},className:`hover:underline`,children:h??(0,V.jsx)(N6,{chips:g})})})}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n.controls&&(0,V.jsx)(Mbe,{model:e,view:t,recordKey:s,title:_,row:a,fields:n.controls}),c&&b&&(0,V.jsx)(U,{variant:`ghost`,"aria-label":`Rename ${_}`,"aria-haspopup":`dialog`,onClick:()=>m(!0),children:(0,V.jsx)(nn,{className:`size-3.5`,"aria-hidden":!0})}),l&&(0,V.jsx)(U,{variant:`ghost`,"aria-label":`Delete ${_}`,onClick:()=>l(_),children:(0,V.jsx)(zn,{className:`size-3.5`,"aria-hidden":!0})})]})]}),p&&b&&(0,V.jsx)(a9,{title:`Rename ${_}`,chips:g,label:t.fields[b.name]?.label??K(b.name),required:!b.nullable,initial:h,busy:y.isPending,onSave:e=>y.mutate(e),onClose:()=>m(!1)}),(0,V.jsx)(q8,{...v})]})},Fbe=({model:e,view:t})=>{let{resources:n,views:r}=J(),i=t.searchesOf,a=n[i.resource],o=r[i.resource],s=J8(e.name,!0),c=YS(e.name),l=t7({model:e,view:t}),u=t.names?.plural??K(e.name),d=e=>(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[l.dialogs,(0,V.jsx)(gd,{title:u,subtitle:t.help}),e]});if(!a)return d((0,V.jsxs)(KS,{title:`Not found`,children:[`There is no resource called `,i.resource,`.`]}));if(s.error)return d((0,V.jsx)(ax,{title:`Could not load your ${u.toLowerCase()}`,error:s.error}));if(!s.data)return d((0,V.jsx)(`div`,{className:`flex flex-col gap-3`,children:Array.from({length:2},(e,t)=>(0,V.jsx)(cu,{className:`h-56`},t))}));if(s.data.length===0){let e=(o?.names?.plural??K(a.name)).toLowerCase();return d((0,V.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,u.toLowerCase(),` yet. Filter the`,` `,(0,V.jsx)(ZS,{to:{kind:`list`,resource:a.name},className:`font-medium text-primary-text hover:underline`,children:e}),` `,`and save the search.`]}))}return d((0,V.jsx)(`div`,{className:`flex flex-col gap-4`,children:s.data.map(n=>{let r=Ao(zx(e,n)),s=MT(c,`delete`)?e=>void l.start({key:r,title:e,etag:n.etag,snapshot:n}):void 0;return(0,V.jsx)(Pbe,{model:e,view:t,of:i,target:a,targetView:o,row:n,recordKey:r,canRename:MT(c,`update`),onDelete:s},r)})}))},Ibe=({field:e,hints:t,resource:n,stored:r,onSave:i,close:a})=>{let[s,c]=(0,o.useState)(()=>Bb(e,r)),l=(0,o.useRef)(null),u=(0,o.useRef)(!1),d=!t?.widget&&(e.type===`boolean`||e.type===`enum`);(0,o.useEffect)(()=>{l.current?.querySelector(`input, select, textarea, button, [tabindex]`)?.focus()},[]);let f=(t,n,o=s)=>{u.current||(u.current=!0,t&&Vb(e,o,r)&&i(Rb(e,o)),a(n))};return(0,V.jsx)(`div`,{ref:l,className:`w-full min-w-0`,onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),f(!0)):e.key===`Tab`?(e.preventDefault(),f(!0,e.shiftKey?-1:1)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),f(!1))},onBlur:e=>{l.current?.contains(e.relatedTarget)||f(!0)},children:(0,V.jsx)(IC,{field:e,hints:t,value:s,stored:r,resource:n,onChange:e=>{c(e),d&&f(!0,void 0,e)}})})},Lbe=e=>{let t=G(),n=Gp(),r=Qy(),[i,a]=(0,o.useState)(new Map),s=(0,o.useRef)(i),c=(0,o.useRef)(new Map),l=(e,t)=>{s.current=new Map(s.current).set(e,{...s.current.get(e),...t}),a(s.current)},u=async(i,a,o)=>{let c=zx(e,i),u=String(s.current.get(i.id)?.etag??i.etag);try{let r=await t.update(e.name,c,{[a]:o},u);l(i.id,{[a]:r.record[a],etag:r.etag}),n.setQueryData(W.record(e.name,Ao(c)),r),n.invalidateQueries({queryKey:[`page`,e.name]}),n.invalidateQueries({queryKey:[`list`,e.name]}),n.invalidateQueries({queryKey:[`map`,e.name]})}catch(n){if(!Rs(n))throw l(i.id,{[a]:i[a]}),n;let o=n.status===412,s=o?await t.get(e.name,c):void 0;l(i.id,s?{[a]:s.record[a],etag:s.etag}:{[a]:i[a]});let u=n.errors.find(e=>e.field===a)?.message??n.message;r.show({state:`error`,title:o?`Changed by someone else`:`Could not save`,description:u})}};return{patches:i,save:(e,t,n)=>{l(e.id,{[t]:n});let r=(c.current.get(e.id)??Promise.resolve()).then(()=>u(e,t,n));return c.current.set(e.id,r.catch(()=>void 0)),r}}},Rbe=(e,t,n)=>{let r=Lbe(e),i=t?.list?.editable??[];return{editor:i.length>0&&MT(n,`update`)?{editable:(t,n)=>i.includes(n)&&e.fields[n]!==void 0&&Pb(e.fields[n])&&NT(t,`update`),render:(n,i,a)=>(0,V.jsx)(Ibe,{field:e.fields[i],hints:t?.fields[i],resource:e.name,stored:n[i],onSave:e=>void r.save(n,i,e),close:a})}:void 0,patches:r.patches}},v9=(e,t)=>{let n=e.position;if(!n||!MT(t,`update`))return;let r=e.fields[n.field];return r&&!r.readOnly?n.field:void 0},zbe=(e,t)=>e.position?.within===void 0?v9(e,t):void 0,Bbe=(e,t,n)=>t.position?.within!==void 0&&e.field===t.position.within&&!e.through&&!e.filter?v9(t,n):void 0,Vbe=({model:e,field:t,filter:n,fields:r})=>{let i=G(),a=Qy(),s=qT(),{resources:c,views:l}=J(),u=`${t} asc`,d=mh({queryKey:[...W.list(e.name,n,u,500,`hand-order`),r.join(`,`)],queryFn:async()=>{let t=u4(c,l,e,r),a=await i.search(e.name,{filter:n||void 0,orderBy:u,pageSize:500,labels:t});return{rows:d4(c,e,r,a.items,a.labels).map((t,n)=>({...t,id:Rx(e,a.items[n])})),more:!!a.nextPageToken}}}),[f,p]=(0,o.useState)(),m=(0,o.useRef)(void 0),h=(0,o.useRef)(Promise.resolve()),g=(0,o.useRef)(0),_=async()=>{let n=m.current;if(!n)return;let r=Object.fromEntries(n.flatMap(t=>typeof t.etag==`string`?[[Ao(zx(e,t)),t.etag]]:[])),a=(await i.batchWrite([{op:`reorder`,resource:e.name,field:t,keys:n.map(t=>zx(e,t)),etags:r}])).results[0];if(a?.op!==`reorder`||!m.current)return;let o=new Map(a.records.map(t=>[Rx(e,t.record),t]));m.current=m.current.map(e=>{let n=o.get(e.id);return n?{...e,[t]:n.record[t],etag:n.etag}:e})},v=e=>{m.current=void 0,p(void 0),a.show({state:`error`,title:`Could not change the order`,description:lS(e)})},y=async()=>{--g.current,!(g.current>0)&&(await s(e.name),!(g.current>0)&&(m.current=void 0,p(void 0)))};return{rows:f??d.data?.rows,more:d.data?.more??!1,loading:d.isPending,error:d.error,move:(e,t)=>{let n=m.current??d.data?.rows;n&&e!==t&&(m.current=Xv(n,e,t),p(m.current),g.current+=1,h.current=h.current.then(_).catch(v).then(y))}}},y9=({model:e,view:t,field:n,filter:r,columns:i})=>{let{resources:a,views:s}=J(),{fields:c}=SC(),{go:l,href:u}=XS(),d=(0,o.useMemo)(()=>H5(e,t,i,{resources:a,views:s,fieldTypes:c}).map(e=>({...e,sortable:!1})),[e,t,i.join(`,`),a,s,c]),f=Vbe({model:e,field:n,filter:r,fields:(0,o.useMemo)(()=>DS(e,t,d.map(e=>e.id)),[e,t,d])}),p=f.rows,m=(0,o.useMemo)(()=>p&&{total:p.length,rowAt:e=>p[e]},[p]),h=(t?.names?.plural??K(e.name)).toLowerCase();if(f.loading)return(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-4 w-full`},t))});if(f.error)return(0,V.jsx)(ax,{title:`Could not load`,error:f.error});if(f.more)return(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`There are more than `,500 .toLocaleString(`en-IE`),` `,h,`, too many to sort by hand.`]});if(!m||m.total===0)return(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Nothing here yet.`});let g=t=>l({kind:`record`,resource:e.name,key:zx(e,t)});return(0,V.jsx)(w6,{fit:!0,scroll:`parent`,columns:d,source:m,latencyMs:0,onOpenRow:g,rowLink:t=>({href:u({kind:`record`,resource:e.name,key:zx(e,t)}),onFollow:()=>g(t)}),rowNumbers:!1,reorder:{label:n=>Ix(e,t,n,n.id),onMove:f.move}})},b9=({sorting:e,onChange:t,size:n,iconOnly:r=!1})=>{let i=e?`Done`:`Sort`;return(0,V.jsxs)(U,{size:n,variant:e?`primary`:`secondary`,onClick:()=>t(!e),...r&&{"aria-label":i,title:i},children:[e?(0,V.jsx)(ge,{className:`size-3.5`}):(0,V.jsx)(E,{className:`size-3.5`}),!r&&i]})},Hbe=co(),Ube=e=>e.find(e=>e.kind===`search`),Wbe=({address:e})=>{let{resources:t,views:n,signIn:r}=J(),i=t[e.resource],a=r?.[e.resource];if(!i)return a?(0,V.jsx)(C8,{as:`page`,prompt:a.signIn}):(0,V.jsxs)(KS,{title:`Not found`,children:[`There is no resource called `,e.resource,`.`]});let o=n[e.resource];if(o?.searchesOf)return(0,V.jsx)(Fbe,{model:i,view:o});let s=PS(t,n,e.resource);if(o&&s.listOf){let t=s.model;return(0,V.jsx)(vbe,{model:i,view:o,target:t,children:n=>(0,V.jsx)(x9,{model:t,address:e,scope:n,heading:{title:o.names?.plural??K(i.name),subtitle:o.help}})})}return(0,V.jsx)(x9,{model:i,address:e})},x9=({model:e,address:t,scope:n,heading:r})=>{let i=J(),{set:a,listTo:s,go:c,href:l}=XS(),u=e.name,d=i.views[u],f=(0,o.useMemo)(()=>f8(d,e),[d,e]),{fields:p}=SC(),m=(0,o.useMemo)(()=>_be(B5(Qx(e,d),e,d,p),e,d,i.resources,i.views),[e,d,p,i.resources,i.views]),h=t.filter,g=(0,o.useMemo)(()=>u8(f,h),[f,h]),_=g.ok?g.state:I6,v=g.ok?g.extras:[],{orderBy:y,filterLayout:b}=t,x=Kl(),S=ql(),[C,w]=(0,o.useState)(!1),T=n?[...v,n]:v,E=Tve({model:e,resources:i.resources,views:i.views,view:d,state:_,extras:T}),D=n?a8(f,_,T):g.ok?h:``,O=(0,o.useMemo)(()=>DS(e,d,m.map(e=>e.id)),[e,d,m]),k=(0,o.useMemo)(()=>Age(d,i.resources,i.views,O),[d,i.resources,i.views,O]),A=k6({resources:i.resources,views:i.views,model:e,columns:O,filter:D,orderBy:y,related:k}),j=gS(e,d,t.display),M=YS(u),N=n?void 0:zbe(e,M),[ee,P]=(0,o.useState)(!1),te=ee&&N!==void 0,F=te||j?.kind!==`map`;iu(F);let ne=$8(e,A.page,A.key,j?.kind===`custom`),re=lbe(),ie=Fx(e,d),I=e=>({key:e.id,title:String(typeof e[ie]==`object`?e[ie].name:e[ie]??e.id),etag:typeof e.etag==`string`?e.etag:void 0,snapshot:e}),ae=d?.names?.singular??K(u),oe=Rbe(e,d,M),{state:se}=H(),L=t7({model:e,view:d,restore:n7(e),onReview:e=>c({kind:`record`,resource:u,key:e.key})}),ce=(e,t=v)=>a({filter:a8(f,e,t)}),le=Ube(v),ue=e=>{let t=v.filter(e=>e.kind!==`search`);ce(_,e?[...t,Hbe.search(e)]:t)},de=d?.names?.plural??K(u),fe=j?.kind===`calendar`?void 0:j,pe=fe&&(0,V.jsx)(z5,{model:e,view:d,display:fe,orderBy:y,onChange:e=>a({orderBy:e})}),me=e.search?.length?(0,V.jsx)(gbe,{value:le?.kind===`search`?le.text:``,onCommit:ue,placeholder:`Search ${de.toLowerCase()}`,className:x?void 0:`min-h-11`}):null,he=(0,V.jsx)(Z6,{layout:b,config:E,value:_,onChange:ce,leading:b===`bar`?pe:void 0,trailing:me}),ge=b===`bar`?he:(0,V.jsx)(X6,{groups:[pe?[pe]:[]],trailing:me}),_e=V6(E,_),ve=(0,V.jsx)(P6,{scroll:!0,chips:_e,onRemove:e=>ce(H6(_,e)),onClear:()=>ce(I6)}),ye=fe&&(0,V.jsx)(G6,{title:`Sort`,children:(0,V.jsx)(z5,{model:e,view:d,display:fe,orderBy:y,onChange:e=>a({orderBy:e}),className:`min-h-11 w-full`})}),be=(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsxs)(U,{className:`min-h-11`,onClick:()=>w(!0),"aria-haspopup":`dialog`,children:[(0,V.jsx)(Cn,{className:`size-3.5`}),`Filters`,_e.length>0&&` (${_e.length})`]}),me??(0,V.jsx)(`div`,{className:`min-w-0 flex-1`,children:ve})]}),me&&ve,(0,V.jsx)(uT,{title:`Filters`,open:C,onClose:()=>w(!1),children:(0,V.jsx)(Z6,{layout:`panel`,fullWidth:!0,config:E,value:_,onChange:ce,leading:ye})})]}),xe=!n&&r7(d,i.pages,M)&&(0,V.jsxs)(ZS,{to:{kind:`create`,resource:u},className:Cf({variant:`primary`}),children:[(0,V.jsx)(an,{className:`size-3.5`}),`New `,ae.toLowerCase()]}),Se=d?.saveSearch&&!n&&g.ok&&h&&(0,V.jsx)(Obe,{model:e,view:d,search:d.saveSearch,filter:h,chips:g8(e,d,h,_ge(E))}),Ce=!n&&(0,V.jsx)(Cye,{model:e}),we=qye({model:e,view:d,resources:i.resources,views:i.views,plural:de,filter:D,orderBy:y}),Te=G7(d)&&(0,V.jsxs)(U,{onClick:()=>we.open(),...!x&&{"aria-label":`Export`,title:`Export`},children:[(0,V.jsx)(We,{className:`size-3.5`}),x&&`Export`]}),Ee=N&&(0,V.jsx)(b9,{sorting:te,onChange:P,iconOnly:!x}),De=t=>!te&&(0,V.jsx)(R5,{view:d,choices:bS(e,d,S),value:j?.name??`table`,onChange:e=>a({display:e}),menu:t}),Oe=v8(e),ke=t=>{Oe(AS(e,t).record),c({kind:`record`,resource:u,key:zx(e,t)})},Ae=A.source?(0,V.jsx)(w6,{columns:m,source:A.source,sort:MS(y),onSortChange:e=>a({orderBy:NS(e)}),onOpenRow:ke,rowLink:t=>({href:l({kind:`record`,resource:u,key:zx(e,t)}),onFollow:()=>ke(t)}),cellEditor:oe.editor,rowPatches:oe.patches,initialScrollIndex:re.initialIndex,onScrollIndex:re.remember,rowActions:[{label:`Open ${ae.toLowerCase()}`,onSelect:ke},...MT(M,`delete`)?[{label:`Delete`,destructive:!0,available:e=>NT(e,`delete`),onSelect:e=>void L.start(I(e))}]:[]],bulkActions:[...G7(d)&&Y7(e)?[{label:e=>`Export ${e}`,onRun:e=>we.open(e)}]:[],...MT(M,`delete`)?[{label:e=>`Delete ${e}`,destructive:!0,onRun:e=>L.startBulk(e.map(I))}]:[]],rowNumbers:!1,pinKey:se.kind===`signed-in`?she(se.user.id,u):void 0,scroll:`parent`,className:`flex-1`}):(0,V.jsx)(`div`,{className:`flex-1 rounded-lg border bg-surface`}),je={...A,initialIndex:re.initialIndex,onScrollIndex:re.remember},Me=Yye({plural:de,search:le?.kind===`search`?le.text:``,filtered:_e.length>0,scoped:!!n||v.some(e=>e.kind!==`search`),canCreate:!!xe}),Ne=(0,V.jsx)(Jye,{state:Me,onClearSearch:()=>ue(``),onClearFilters:()=>ce(I6),create:xe}),Pe=te?(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Drag a row by its handle to move it. Every move is saved as you drop it.`}),(0,V.jsx)(y9,{model:e,view:d,field:N,filter:``,columns:Zx(e,d)})]}):j?j.kind===`cards`?(0,V.jsx)(cbe,{model:e,view:d,display:j,list:je,empty:Ne},A.key.join(` `)):j.kind===`map`?(0,V.jsx)(F5,{model:e,view:d,display:j,filter:D,orderBy:y,fields:O,at:t.map,onMove:e=>a({map:e}),flush:!0}):j.kind===`board`?(0,V.jsx)(e5,{model:e,view:d,display:j,fields:O,filter:D,orderBy:y}):j.kind===`calendar`?(0,V.jsx)(_5,{model:e,view:d,display:j,fields:O,filter:D,at:t.calendar,linkTo:e=>s({calendar:e})}):(0,V.jsx)(b5,{display:j,list:ne}):A.source?.total===0&&!A.error?Ne:Ae;return(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[L.dialogs,we.dialogs,(0,V.jsx)(gd,{title:r?.title??de,subtitle:r?r.subtitle:d?.help,aside:!x&&De(!0),actions:x?(0,V.jsxs)(V.Fragment,{children:[De(!1),Ee,Se,Ce,Te,xe]}):(0,V.jsxs)(V.Fragment,{children:[Ee,Se,Ce,Te,xe]})}),!g.ok&&(0,V.jsx)(ax,{title:`The filter in the address could not be read`,error:Error(g.errors.map(e=>e.message).join(`; `))}),A.error&&!j&&!te&&(0,V.jsx)(ax,{title:`Could not load rows`,error:A.error}),d?.chart&&!te&&(Do(d.chart)?(0,V.jsx)(hbe,{model:e,view:d,chart:d.chart,plural:de,filter:D}):(0,V.jsx)(mbe,{resource:u,chart:d.chart,title:`${de} created`,noun:de.toLowerCase(),filter:D})),!te&&(x?ge:be),x&&b===`panel`&&!te?(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,V.jsx)(`div`,{className:F?`sticky top-[calc(var(--pb-sticky-top,0px)+1rem)] flex max-h-[calc(100dvh-var(--pb-sticky-top,0px)-var(--pb-sticky-bottom,0px)-2rem)] shrink-0 self-start`:`flex shrink-0`,children:he}),Pe]}):Pe]})},S9=({roles:e,selected:t,grantable:n,disabled:r,onChange:i})=>(0,V.jsx)(`div`,{className:`flex flex-wrap gap-x-4 gap-y-2`,children:e.filter(e=>e.membership).map(e=>{let a=t.includes(e.name),o=r||!n.has(e.name);return(0,V.jsxs)(`label`,{title:o&&!r?`You cannot give or take away this role`:void 0,className:B(`inline-flex items-center gap-1.5`,o&&`text-muted-foreground`),children:[(0,V.jsx)(Fh,{checked:a,label:e.label,onChange:o?void 0:n=>i(n?[...t,e.name]:t.filter(t=>t!==e.name)),className:B(o&&`cursor-default opacity-60`)}),e.label]},e.name)})}),C9=e=>e?.role===`owner`?[`owner`,`admin`,`member`]:[`admin`,`member`],Gbe=({member:e,current:t,onChanged:n})=>{let{session:r,organizations:i}=H(),a=t.organization.id,{busy:o,error:s,run:c}=Gh(),l=i?.roles??[],u=e.id===t.memberId,d=C9(t),f=e.role===`owner`&&t.role!==`owner`;return(0,V.jsxs)(`li`,{className:`flex flex-col gap-2 px-3 py-3`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsxs)(`span`,{className:`block truncate font-medium`,children:[e.name,u&&` (you)`]}),(0,V.jsx)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:e.email})]}),(0,V.jsx)(`select`,{"aria-label":`Organization role of ${e.name}`,value:e.role,disabled:o||f,onChange:t=>void c(async()=>{await r.organizations.setRole(a,e.id,t.target.value),n()}),className:`h-7 rounded-md border border-border-strong bg-background px-2 text-xs`,children:(f?[e.role]:d).map(e=>(0,V.jsx)(`option`,{value:e,children:Vh[e]},e))}),!u&&(0,V.jsx)(U,{size:`sm`,variant:`danger`,loading:o,disabled:f,onClick:()=>void c(async()=>{await r.organizations.removeMember(a,e.id),n()}),children:`Remove`})]}),(0,V.jsx)(S9,{roles:l,selected:e.appRoles,grantable:Wh(l,t),disabled:o,onChange:t=>void c(async()=>{await r.organizations.setAppRoles(e.id,t),n()})}),(0,V.jsx)(Ef,{message:s})]})},Kbe=({current:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)(),s=e?.organization?.id,c=(0,o.useCallback)(()=>{s&&t.organizations.members(s).then(r,e=>a(e instanceof pc?xd(e):`Could not read the members`))},[t,s]);return(0,o.useEffect)(c,[c]),e?.organization?(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:`Members`,subtitle:`Who works in ${e.organization.name}, and with which roles.`}),(0,V.jsxs)(Tf,{title:`Members`,description:`Owners and admins manage the organization; app roles decide what each member sees and does in the app.`,children:[(0,V.jsx)(Ef,{message:i}),n?(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(t=>(0,V.jsx)(Gbe,{member:t,current:e,onChanged:c},`${t.id}/${t.role}/${t.appRoles.join()}`))}):!i&&(0,V.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})]})]}):null},w9=({link:e})=>e?(0,V.jsxs)(`p`,{className:`mt-3 break-all rounded-md border bg-muted px-3 py-2 text-xs`,children:[`This app cannot send email, so pass this link on yourself. It works once, until the invitation expires: `,(0,V.jsx)(`span`,{className:`font-mono`,children:e})]}):null,qbe=({current:e,onSent:t})=>{let{session:n,organizations:r}=H(),i=r?.roles??[],[a,s]=(0,o.useState)(``),[c,l]=(0,o.useState)(`member`),[u,d]=(0,o.useState)([]),[f,p]=(0,o.useState)(),{busy:m,error:h,run:g}=Gh(),_=()=>g(async()=>{let r=await n.organizations.invite(e.organization.id,{email:a.trim(),role:c,appRoles:u});p(r.link),s(``),d([]),t()});return(0,V.jsxs)(Tf,{title:`Invite someone`,description:`They get an email with a link to join, or to make an account first. You can give the app roles you hold, and those your roles grant.`,children:[(0,V.jsx)(Ef,{message:h}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-3`,onSubmit:e=>{e.preventDefault(),_()},children:[(0,V.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row`,children:[(0,V.jsx)(sd,{"aria-label":`Email`,type:`email`,placeholder:`name@example.com`,value:a,onChange:e=>s(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(`select`,{"aria-label":`Organization role`,value:c,onChange:e=>l(e.target.value),className:`h-8 rounded-md border border-border-strong bg-background px-2`,children:C9(e).map(e=>(0,V.jsx)(`option`,{value:e,children:Vh[e]},e))}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:m,disabled:!a.trim(),children:`Invite`})]}),(0,V.jsx)(S9,{roles:i,selected:u,grantable:Wh(i,e),onChange:d})]}),(0,V.jsx)(w9,{link:f})]})},Jbe=({invitation:e,organizationId:t,onChanged:n})=>{let{session:r,organizations:i}=H(),[a,s]=(0,o.useState)(),{busy:c,error:l,run:u}=Gh(),d=new Date(e.expiresAt).getTime()<Date.now();return(0,V.jsxs)(`li`,{className:`px-3 py-2.5`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.email}),(0,V.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[Vh[e.role],e.appRoles.length>0&&` · ${e.appRoles.map(e=>Hh(i?.roles??[],e)).join(`, `)}`,` · `,d?`Expired`:`Until ${new Date(e.expiresAt).toLocaleDateString()}`]})]}),(0,V.jsx)(U,{size:`sm`,loading:c,onClick:()=>void u(async()=>{s((await r.organizations.resend(t,e)).link),n()}),children:`Send again`}),(0,V.jsx)(U,{size:`sm`,variant:`danger`,loading:c,onClick:()=>void u(async()=>{await r.organizations.revoke(e.id),n()}),children:`Revoke`})]}),(0,V.jsx)(Ef,{message:l}),(0,V.jsx)(w9,{link:a})]})},Ybe=({current:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)([]),i=e?.organization?.id,a=(0,o.useCallback)(()=>{i&&t.organizations.invitations(i).then(e=>r(e.filter(e=>e.status===`pending`)),()=>r([]))},[t,i]);return(0,o.useEffect)(a,[a]),!e?.organization||!i?null:(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:`Invitations`,subtitle:`People invited to ${e.organization.name}.`}),(0,V.jsx)(qbe,{current:e,onSent:a}),(0,V.jsx)(Tf,{title:`Not accepted yet`,description:n.length>0?`Sending again gives a new link, which replaces the earlier one.`:`Nobody is waiting.`,children:n.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(e=>(0,V.jsx)(Jbe,{invitation:e,organizationId:i,onChanged:a},e.id))})})]})},Xbe=e=>{let{session:t}=H(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)([]),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(0),d=(0,o.useCallback)(()=>u(e=>e+1),[]);return(0,o.useEffect)(()=>{e&&Promise.all([t.organizations.current(),t.organizations.list()]).then(([e,t])=>{r(e),a(t)},e=>c(e instanceof pc?xd(e):`Could not read your organizations`))},[e,t,l]),{current:n,organizations:i,...s&&{error:s},reload:d}},T9=e=>window.location.assign(`${e}/`),Zbe=({organization:e,editable:t,onSaved:n})=>{let{session:r}=H(),[i,a]=(0,o.useState)(e.name),[s,c]=(0,o.useState)(e.slug),{busy:l,error:u,run:d}=Gh(),f=i.trim()!==e.name||s!==e.slug;return(0,V.jsxs)(Tf,{title:`Details`,description:t?`The name people see, and the slug that names it in links.`:`Owners and admins can change these.`,children:[(0,V.jsx)(Ef,{message:u}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-2 sm:flex-row`,onSubmit:t=>{t.preventDefault(),d(async()=>{await r.organizations.rename(e.id,{name:i.trim(),slug:s}),n()})},children:[(0,V.jsx)(sd,{"aria-label":`Name`,value:i,disabled:!t,onChange:e=>a(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(sd,{"aria-label":`Slug`,value:s,disabled:!t,onChange:e=>c(e.target.value),wrapperClassName:`sm:w-48`}),t&&(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:l,disabled:!f||!i.trim(),children:`Save`})]})]})},Qbe=({organization:e,memberId:t})=>{let{session:n}=H(),[r,i]=(0,o.useState)([]),[a,s]=(0,o.useState)(``),{busy:c,error:l,run:u}=Gh();return(0,o.useEffect)(()=>{n.organizations.members(e.id).then(e=>i(e.filter(e=>e.id!==t)),()=>i([]))},[n,e.id,t]),(0,V.jsxs)(Tf,{title:`Hand over`,description:`Make another member the owner. You stay as an admin.`,children:[(0,V.jsx)(Ef,{message:l}),(0,V.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row`,children:[(0,V.jsxs)(`select`,{"aria-label":`New owner`,value:a,onChange:e=>s(e.target.value),className:`h-8 flex-1 rounded-md border border-border-strong bg-background px-2`,children:[(0,V.jsx)(`option`,{value:``,children:`Choose a member`}),r.map(e=>(0,V.jsxs)(`option`,{value:e.id,children:[e.name,` (`,e.email,`)`]},e.id))]}),(0,V.jsx)(U,{loading:c,disabled:!a,onClick:()=>void u(async()=>{await n.organizations.transferOwnership(a),window.location.reload()}),children:`Hand over`})]})]})},$be=({organization:e,basePath:t})=>{let{session:n}=H(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(``),{busy:c,error:l,run:u}=Gh(),d=()=>u(async()=>{await n.organizations.remove(e.id),T9(t)});return(0,V.jsxs)(Tf,{title:`Delete organization`,description:`Takes the organization and its members and invitations away. Its records must be deleted first.`,children:[(0,V.jsx)(Ef,{message:r?void 0:l}),(0,V.jsx)(U,{variant:`danger`,onClick:()=>i(!0),children:`Delete organization`}),r&&(0,V.jsxs)(wf,{title:`Delete ${e.name}?`,description:`Type its name to confirm. This cannot be undone.`,onClose:()=>i(!1),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>i(!1),children:`Cancel`}),(0,V.jsx)(U,{variant:`danger`,loading:c,disabled:a!==e.name,onClick:()=>void d(),children:`Delete`})]}),children:[(0,V.jsx)(Ef,{message:l}),(0,V.jsx)(sd,{"aria-label":`Organization name`,value:a,onChange:e=>s(e.target.value)})]})]})},exe=({organization:e,basePath:t,owner:n})=>{let{session:r}=H(),{busy:i,error:a,run:o}=Gh();return(0,V.jsxs)(Tf,{title:`Leave`,description:n?`An organization keeps an owner: hand it over before you leave, unless it has another owner.`:`You stop being a member, and lose your roles here.`,children:[(0,V.jsx)(Ef,{message:a}),(0,V.jsxs)(U,{loading:i,onClick:()=>void o(async()=>{await r.organizations.leave(e.id),T9(t)}),children:[`Leave `,e.name]})]})},txe=({current:e,basePath:t,onChanged:n})=>{let r=e?.organization;if(!r)return(0,V.jsx)(`div`,{className:`mx-auto w-full max-w-3xl px-4 py-6 md:px-6`,children:(0,V.jsx)(gd,{title:`Organization`,subtitle:`You do not work in an organization now. Choose one under Organizations.`})});let i=e.role===`owner`;return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:r.name,subtitle:e.role?`You are ${Vh[e.role].toLowerCase()} here.`:`You work here through your global roles, without being a member.`}),(0,V.jsx)(Zbe,{organization:r,editable:Uh(e),onSaved:n},`${r.name}/${r.slug}`),i&&e.memberId&&(0,V.jsx)(Qbe,{organization:r,memberId:e.memberId}),e.role&&(0,V.jsx)(exe,{organization:r,basePath:t,owner:i}),i&&(0,V.jsx)($be,{organization:r,basePath:t})]})},E9=e=>e.normalize(`NFKD`).replace(/[̀-ͯ]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,63),D9=({organization:e,current:t,busy:n,onOpen:r})=>(0,V.jsxs)(`li`,{className:`flex items-center gap-3 px-3 py-2.5`,children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.name}),(0,V.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:e.slug})]}),t?(0,V.jsx)(Au,{tone:`green`,children:`Current`}):(0,V.jsx)(U,{size:`sm`,loading:n,onClick:r,children:`Open`})]}),nxe=({basePath:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(``),[i,a]=(0,o.useState)(),{busy:s,error:c,run:l}=Gh(),u=()=>l(async()=>{await t.organizations.create({name:n.trim(),slug:i??E9(n)}),T9(e)});return(0,V.jsxs)(Tf,{title:`New organization`,description:`You become its owner, with every role, and work in it once it is made.`,children:[(0,V.jsx)(Ef,{message:c}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-2 sm:flex-row`,onSubmit:e=>{e.preventDefault(),u()},children:[(0,V.jsx)(sd,{"aria-label":`Name`,placeholder:`Name`,value:n,onChange:e=>r(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(sd,{"aria-label":`Slug`,placeholder:`slug`,value:i??E9(n),onChange:e=>a(e.target.value),wrapperClassName:`sm:w-48`}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:s,disabled:!n.trim(),children:`Create`})]})]})},rxe=({basePath:e,currentId:t})=>{let{session:n}=H(),[r,i]=(0,o.useState)(``),[a,s]=(0,o.useState)([]),{busy:c,error:l,run:u}=Gh();return(0,o.useEffect)(()=>{let e=setTimeout(()=>void n.organizations.search(r).then(s,()=>s([])),200);return()=>clearTimeout(e)},[n,r]),(0,V.jsxs)(Tf,{title:`Find an organization`,description:`Your global roles let you work in any organization, with what those roles allow there. Opening one you are not a member of is written to the audit log.`,children:[(0,V.jsx)(Ef,{message:l}),(0,V.jsx)(sd,{"aria-label":`Find an organization`,placeholder:`Name or slug`,value:r,onChange:e=>i(e.target.value),leading:(0,V.jsx)(pn,{className:`size-3.5`}),wrapperClassName:`mb-3`}),a.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:a.map(r=>(0,V.jsx)(D9,{organization:r,current:r.id===t,busy:c,onOpen:()=>void u(async()=>{await n.organizations.switchTo(r.id),T9(e)})},r.id))})]})},ixe=()=>{let{session:e,organizations:t}=H(),[n,r]=(0,o.useState)([]);if((0,o.useEffect)(()=>{e.organizations.myInvitations().then(r,()=>r([]))},[e]),n.length===0)return null;let i=t?.roles??[];return(0,V.jsx)(Tf,{title:`Invitations for you`,description:`Open the link in the invitation email to accept one.`,children:(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(e=>(0,V.jsxs)(`li`,{className:`px-3 py-2.5`,children:[(0,V.jsx)(`span`,{className:`font-medium`,children:e.organizationName??`An organization`}),`: `,e.appRoles.map(e=>Hh(i,e)).join(`, `)||`no app roles`,(0,V.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Until `,new Date(e.expiresAt).toLocaleDateString()]})]},e.id))})})},axe=({state:e,basePath:t})=>{let{session:n,organizations:r,state:i}=H(),{busy:a,error:o,run:s}=Gh(),c=i.kind===`signed-in`?i.user:void 0,l=r?.create===`everyone`||c!==void 0&&bg(c),u=e.current?.organization?.id;return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:`Organizations`,subtitle:`You work in one organization at a time; what you see follows from your roles there.`}),(0,V.jsxs)(Tf,{title:`Your organizations`,description:e.organizations.length>0?`The organizations you are a member of.`:`You are not a member of an organization yet.`,children:[(0,V.jsx)(Ef,{message:o??e.error}),e.organizations.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.organizations.map(e=>(0,V.jsx)(D9,{organization:e,current:e.id===u,busy:a,onOpen:()=>void s(async()=>{await n.organizations.switchTo(e.id),T9(t)})},e.id))})]}),(0,V.jsx)(ixe,{}),l&&(0,V.jsx)(nxe,{basePath:t}),(e.current?.globalRoles.length??0)>0&&(0,V.jsx)(rxe,{basePath:t,currentId:u})]})},oxe=(e,t)=>t?.active?{...e,role:t.active}:e,O9=(e,t)=>e instanceof pc?xd(e):t,sxe=(e,t=!0)=>{let{session:n}=H(),r=Qy(),[i,a]=(0,o.useState)();(0,o.useEffect)(()=>{t&&n.roles.current().then(a,e=>r.show({state:`error`,title:O9(e,`Could not read your roles`)}))},[n,r,t]);let s=(0,o.useCallback)(t=>void n.roles.switchTo(t).then(e,e=>r.show({state:`error`,title:O9(e,`Could not switch the role`)})),[n,r,e]);return{...i&&{current:i},switchTo:s}},k9=e=>new Set((e.userMenu?.items??[]).flatMap(e=>e.kind===`resource`?[e.resource]:e.kind===`page`?[e.page]:[])),cxe=(e,t,n)=>(e.userMenu?.items??[]).map((r,i)=>{if(r.kind===`link`)return{id:`link-${i}`,label:r.label,icon:oT(r.icon,Qe),href:r.href,external:!0};if(r.kind===`page`){let i=e.pages[r.page];return{id:r.page,label:r.label??i?.title??K(r.page),icon:oT(r.icon??i?.icon,xt),href:ps({kind:`page`,page:r.page},t),active:r.page===n}}return{id:r.resource,label:r.label??e.views[r.resource]?.names?.plural??K(r.resource),icon:oT(r.icon,iT(r.resource)),href:ps({kind:`list`,resource:r.resource},t),active:r.resource===n}}),lxe={sales:`Sales`,crm:`CRM`,catalog:`Catalog`,inventory:`Inventory`,core:`Admin`,hr:`HR`},A9=(e,t=``,n={})=>{let r=new Map,i=new Map,a=k9(e);for(let n of Object.values(e.pages)){if(n.nav?.hidden||a.has(n.name))continue;let e=n.nav?.group??`Pages`,o=r.get(e)??{label:e,items:[]};o.items.push({id:n.name,label:n.title,icon:oT(n.icon,xt),href:ps({kind:`page`,page:n.name},t)}),r.set(e,o),i.set(n.name,n.nav?.order??2**53-1)}for(let o of Object.values(e.resources)){let s=e.views[o.name];if(!s||s.nav?.hidden||a.has(o.name))continue;let c=o.table.schema??`public`,l=s.nav?.group??lxe[c]??K(c),u=r.get(l)??{label:l,items:[]};u.items.push({id:o.name,label:s.names?.plural??K(o.name),icon:iT(o.name),href:ps({kind:`list`,resource:o.name},t),...n[o.name]&&{recent:n[o.name]}}),r.set(l,u),i.set(o.name,s.nav?.order??2**53-1)}for(let n of Object.values(e.signIn??{})){if(n.nav?.hidden||a.has(n.resource))continue;let e=n.nav?.group??`Account`,o=r.get(e)??{label:e,items:[]};o.items.push({id:n.resource,label:n.names?.plural??K(n.resource),icon:iT(n.resource),href:ps({kind:`list`,resource:n.resource},t)}),r.set(e,o),i.set(n.resource,n.nav?.order??2**53-1)}for(let n of e.sources??[]){if(n.state!==`error`)continue;let e=r.get(n.source.label)??{label:n.source.label,items:[]};for(let r of n.source.resources)e.items.push({id:r,label:K(r),icon:iT(r),href:ps({kind:`list`,resource:r},t),problem:`Cannot reach ${n.source.label}`});r.set(n.source.label,e)}return[...r.values()].map(e=>({...e,items:[...e.items].sort((e,t)=>(i.get(e.id)??0)-(i.get(t.id)??0))}))},uxe=e=>{let t=SC().shell?.logo;return t?(0,V.jsx)(Qh,{name:`shell.logo`,fallback:(0,V.jsx)(vu,{...e}),children:(0,V.jsx)(t,{...e})}):(0,V.jsx)(vu,{...e})},j9=(0,o.createContext)([]),dxe=()=>(0,o.useContext)(j9),fxe=({ui:e,children:t})=>{let{plugins:n=[]}=J(),{loads:r,settled:i}=hg(n,pg()),a=(0,o.useMemo)(()=>ag(e,r),[e,r]);return i?(0,V.jsx)(xC.Provider,{value:a.ui,children:(0,V.jsx)(j9.Provider,{value:a.off,children:t})}):(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})},pxe=({off:e})=>{let[t,n]=(0,o.useState)(!1);return t||e.length===0?null:(0,V.jsxs)(`div`,{role:`region`,"aria-label":`Plugins off`,className:`flex items-start gap-3 border-b border-warning/40 bg-warning-soft px-4 py-2 text-warning-text`,children:[(0,V.jsx)(sn,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0`}),(0,V.jsx)(`ul`,{className:`min-w-0 flex-1 space-y-0.5 break-words`,children:e.map(e=>(0,V.jsxs)(`li`,{children:[`The plugin `,(0,V.jsx)(`span`,{className:`font-semibold`,children:e.name??e.url}),` is off: `,e.reason,`.`]},e.url))}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Dismiss`,className:`rounded p-0.5 hover:bg-warning/10`,onClick:()=>n(!0),children:(0,V.jsx)($n,{"aria-hidden":!0,className:`size-4`})})]})},M9=(e,t)=>[`${t}_at`,`${t}At`].find(t=>e.fields[t]),N9=({item:e,scope:t})=>{let{components:n}=SC(),r=n?.[e.component],i=r?(0,V.jsx)(AT,{value:t,children:(0,V.jsx)(Qh,{name:e.component,children:(0,V.jsx)(r,{...bo(e.props??{})})})}):(0,V.jsxs)(Zh,{children:[`No component is registered as `,e.component,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]});return e.sidebar?e.title?(0,V.jsx)(ab,{title:e.title,children:i}):i:e.title?(0,V.jsx)(tb,{title:e.title,children:i}):(0,V.jsx)(`section`,{className:`py-8`,children:i})},mxe=(0,o.lazy)(()=>qh(()=>import(`./record-map-Bmns3gJf.js`).then(e=>({default:e.RecordMap})),__vite__mapDeps([8,1,5,2,6,3,7]))),hxe=15,P9=({item:e,record:t})=>{let n=J().maps,r=n?.style,i=E5(t,e);if(!r||!i)return null;let a=(0,V.jsx)(`div`,{className:`overflow-hidden rounded-lg border border-border bg-muted ${e.sidebar?`h-48`:`h-64 md:h-80`}`,children:(0,V.jsx)(o.Suspense,{fallback:null,children:(0,V.jsx)(mxe,{style:r,layers:n?.layers,position:i,zoom:e.zoom??hxe},`${i.latitude},${i.longitude}`)})});return e.sidebar?(0,V.jsx)(ab,{title:e.title,children:a}):(0,V.jsx)(tb,{title:e.title,children:a})},gxe=e=>b8(e)??tr,_xe=({model:e,stored:t,recordKey:n,edit:r,onDelete:i})=>{let{go:a}=XS(),s=rd(),c={model:e,record:t.record,key:n,etag:t.etag,permissions:t.permissions},l=YT(e.name,c,t=>t.run?.kind===`delete`&&a({kind:`list`,resource:e.name},{replace:!0})),[u,d]=(0,o.useState)(),f=l.actions.map(e=>({name:e.label,icon:gxe(e.icon),blocked:l.blocked(e),running:l.running===e.name,...e.run?.kind===`delete`&&{tone:`danger`},onRun:()=>DT(e)?d(e):void l.run(e)})),p=l.actions.some(e=>e.run?.kind===`delete`),m=[...r?[{name:`Edit`,icon:nn,render:({className:e,children:t,role:n})=>(0,V.jsx)(ZS,{to:r,role:n,className:e,children:t})}]:[],...f,...i&&!p?[{name:`Delete`,icon:zn,tone:`danger`,onRun:i}]:[]];return m.length===0?null:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`div`,{className:s?`max-md:hidden`:void 0,children:(0,V.jsx)(rb,{actions:m})}),s&&(0,nr.createPortal)((0,V.jsx)(mb,{actions:m,label:`Record actions`,className:`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`}),s),u&&(0,V.jsx)(OT,{action:u,label:u.label,danger:u.run?.kind===`delete`,onCancel:()=>d(void 0),onConfirm:()=>{d(void 0),l.run(u)},onSubmit:async e=>{await l.submit(u,e),d(void 0)}})]})},vxe=(e,t)=>Object.values(e).find(e=>e.name!==t.name&&e.fields.position&&e.fields.quantity&&Object.values(e.fields).some(e=>e.type===`relation`&&e.relation?.resource===t.name)),yxe=e=>({id:String(e.id),productId:String(e.productId??``),description:String(e.description??``),quantity:Number(e.quantity),unitPriceCents:Math.round(Number(e.unitPrice)*100)}),bxe=({lines:e,draft:t,vatRate:n,saving:r,locked:i=!1})=>{let a=MT(YS(e.name),`update`);return(0,V.jsx)(tb,{title:`Lines`,help:`What the document bills for. Drag the handle, or use the menu, to change the order; Save applies it.`,children:(0,V.jsx)(`div`,{className:`-mx-4 overflow-x-auto px-4 [-webkit-overflow-scrolling:touch] md:mx-0 md:px-0`,children:(0,V.jsx)(`div`,{className:`min-w-[560px]`,children:(0,V.jsx)(Wy,{lines:t.shown.map(yxe),onChange:()=>void 0,onReorder:e=>t.setOrder(e.map(e=>e.id)),vatRate:n,readOnly:!0,reorderable:a&&!r&&!i})})})})},xxe=(e,t,n)=>`protobase:draft:${e}:${t}:${n}`,Sxe=(e,t,n)=>zu(()=>{let r=e.getItem(t);if(r===null)return;let i=JSON.parse(r);if(i&&i.etag===n&&typeof i.fields==`object`&&i.fields!==null)return{etag:n,fields:i.fields,...Array.isArray(i.order)&&{order:i.order.map(String)}}},void 0),Cxe=(e,t,n)=>zu(()=>n?e.setItem(t,JSON.stringify(n)):e.removeItem(t),void 0),wxe=(e,t)=>Number(e.position)-Number(t.position),Txe=(e,t,n)=>{let r=e&&Object.values(e.fields).find(e=>e.type===`relation`&&e.relation?.resource===t.name),i=QS(e?.name??``,{enabled:!!(e&&r),filter:r?`${r.name} = "${n}"`:void 0,pageSize:200,...e?.fields.position?.sortable&&{orderBy:`position asc`}});return{items:[...i.items].sort(wxe),loading:i.isPending&&!!e}},Exe=(e,t)=>{let[n,r]=(0,o.useState)(),i=t.map(e=>String(e.id)),a=(0,o.useMemo)(()=>{if(!n)return t;let e=n.flatMap(e=>t.filter(t=>String(t.id)===e)),r=t.filter(e=>!n.includes(String(e.id)));return[...e,...r]},[n,t]),s=a.map(e=>String(e.id)),c=n!==void 0&&s.some((e,t)=>e!==i[t]),l=(0,o.useCallback)(()=>!e||!c?[]:[{op:`reorder`,resource:e.name,field:`position`,keys:a.map(t=>zx(e,t)),etags:Object.fromEntries(a.flatMap(t=>typeof t.etag==`string`?[[Ao(zx(e,t)),t.etag]]:[]))}],[e,c,a]);return{shown:a,dirty:c,order:c?s:void 0,setOrder:e=>r(e),reset:()=>r(void 0),op:l}},Dxe=e=>{let t=e>=5?5:e===4?3:e;return{shown:t,more:e-t}},Oxe=(e,t)=>Math.abs(e)<40||Math.abs(e)<=Math.abs(t)?0:e<0?1:-1,kxe=e=>e===`ArrowRight`?1:e===`ArrowLeft`?-1:0,Axe=(e,t,n)=>Math.min(Math.max(e+t,0),Math.max(n-1,0)),jxe=e=>e.key===`i`&&!e.ctrlKey&&!e.metaKey&&!e.altKey,F9=`protobase:lightbox-details`,Mxe=e=>zu(()=>e.getItem(F9)===`true`,!1),Nxe=(e,t)=>zu(()=>t?e.setItem(F9,`true`):e.removeItem(F9),void 0),I9=`flex size-10 shrink-0 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40`,Pxe=({title:e,photos:t,index:n,onIndex:r,onClose:i,details:a,detailsTitle:s=`Details`})=>{let c=(0,o.useRef)(null),l=(0,o.useRef)(void 0),u=(0,o.useId)(),d=Kl(),[f,p]=(0,o.useState)(()=>Mxe(localStorage)),[m,h]=(0,o.useState)(!1);tu(c,!0,i),(0,o.useEffect)(()=>h(!0),[]);let g=t.length,_=e=>{let t=Axe(n,e,g);t!==n&&r(t)},v=Ob(t[n],{width:1600,height:1200}),y=a?.(n),b=y!==void 0,x=e=>{p(e),Nxe(localStorage,e)};return(0,V.jsxs)(`div`,{ref:c,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":e,onKeyDown:e=>{if(b&&jxe(e))return e.preventDefault(),x(!f);let t=kxe(e.key);t!==0&&(e.preventDefault(),_(t))},className:`fixed inset-0 z-[90] flex flex-col overflow-y-auto overscroll-contain bg-backdrop outline-none md:flex-row`,children:[(0,V.jsxs)(`div`,{className:`flex h-dvh shrink-0 flex-col md:sticky md:top-0 md:min-w-0 md:flex-1`,children:[(0,V.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 p-3`,children:[(0,V.jsx)(`span`,{className:`rounded-full bg-background/85 px-3 py-1 font-medium tabular-nums text-foreground`,"aria-live":`polite`,children:`${n+1} / ${g}`}),(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[b&&(0,V.jsx)(`button`,{type:`button`,className:B(I9,`aria-expanded:bg-foreground aria-expanded:text-background`),"aria-label":s,"aria-expanded":f,"aria-controls":d?u:void 0,"aria-keyshortcuts":`i`,onClick:()=>x(!f),children:(0,V.jsx)(ht,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsx)(`button`,{type:`button`,className:I9,"aria-label":`Close`,onClick:i,children:(0,V.jsx)($n,{className:`size-4`,"aria-hidden":!0})})]})]}),(0,V.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 touch-pan-y items-center justify-center px-3 pb-3 md:px-16`,onPointerDown:e=>{e.pointerType===`touch`&&(l.current={x:e.clientX,y:e.clientY})},onPointerUp:e=>{l.current&&=(_(Oxe(e.clientX-l.current.x,e.clientY-l.current.y)),void 0)},onPointerCancel:()=>l.current=void 0,children:[v&&(0,V.jsx)(hC,{image:v,className:`max-h-full max-w-full select-none object-contain`},v.url),g>1&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,className:B(I9,`absolute left-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40`),"aria-label":`Previous photo`,"aria-disabled":n===0,onClick:()=>_(-1),children:(0,V.jsx)(be,{className:`size-5`,"aria-hidden":!0})}),(0,V.jsx)(`button`,{type:`button`,className:B(I9,`absolute right-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40`),"aria-label":`Next photo`,"aria-disabled":n===g-1,onClick:()=>_(1),children:(0,V.jsx)(Se,{className:`size-5`,"aria-hidden":!0})})]})]})]}),b&&f&&d&&(0,V.jsxs)(`aside`,{id:u,"aria-label":s,className:`min-h-dvh w-[360px] shrink-0 border-l border-border bg-background p-5 text-foreground`,children:[(0,V.jsx)(`h2`,{className:`mb-3 text-[16px] font-semibold`,children:s}),y]}),(0,V.jsx)(uT,{title:s,open:b&&f&&!d&&m,onClose:()=>x(!1),children:(0,V.jsx)(`div`,{className:`pt-3`,children:y})})]})},Fxe=(e,t,n)=>{let r=(t?.layout??[]).flatMap(e=>e.kind===`section`&&Gb(e.when,!1)?e.fields:[]);return(r.length>0?[...new Set(r)]:Object.keys(e.fields).filter(t=>t!==e.tenant&&!e.primaryKey.includes(t))).filter(r=>e.fields[r]&&!e.fields[r].sensitive&&!n.includes(r)&&Gb(t?.fields[r]?.when,!1))},Ixe=({model:e,view:t,photoKey:n,fields:r})=>{let i=Sg(e.name,n),a=(t?.names?.singular??K(e.name)).toLowerCase();if(i.isPending)return(0,V.jsx)(cu,{className:`h-4 w-48`});if(i.error)return(0,V.jsx)(ax,{title:`Could not load the ${a}`,error:i.error});let o=r.filter(e=>PT(i.data.permissions,e)!==`hidden`);return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(cb,{rows:o.map(n=>({label:t?.fields[n]?.label??K(n),value:(0,V.jsx)(m4,{model:e,field:e.fields[n],value:i.data.record[n]})}))}),(0,V.jsx)(ZS,{to:{kind:`record`,resource:e.name,key:n},className:`mt-3 inline-block font-medium text-primary-text hover:underline`,children:`Open ${a}`})]})},L9=e=>Ob(e,{width:0,height:0})!==void 0,Lxe=(e,t)=>{let n=e.primaryKey.map(e=>t[e]);if(!n.some(e=>e==null))return Ao(n)},Rxe=(e,t,n,r)=>{let i=n===void 0?[]:t.flatMap(e=>{let t=e[n];if(!vb(t)||!L9(t))return[];let i=r&&Lxe(r,e);return[{file:t,...i!==void 0&&{key:i}}]});if(!vb(e)||!L9(e))return i;let a=t=>vb(t.file)&&t.file.uri===e.uri,o=i.find(a)?.key;return[{file:e,...o!==void 0&&{key:o}},...i.filter(e=>!a(e))]},zxe=co(),Bxe=(e,t,n)=>{let r=G(),{resources:i}=J(),a=e.photos?i[e.photos.resource]:void 0,o=e.photos?qa(zxe.eq(e.photos.field,n)):``,s=e.photos?.sort??``,c=mh({queryKey:W.list(a?.name??``,o,s,500,`gallery`),enabled:a!==void 0,queryFn:async()=>(await r.list(a.name,{filter:o,...s&&{orderBy:s},pageSize:500})).items});return{holder:a,items:Rxe(e.image===void 0?void 0:t[e.image],c.data??[],e.photos?.image,a),isPending:a!==void 0&&c.isPending,error:c.error}},Vxe={1:[`md:col-span-4 md:row-span-2`],2:[`md:col-span-2 md:row-span-2`,`md:col-span-2 md:row-span-2`],3:[`md:col-span-2 md:row-span-2`,`md:col-span-2`,`md:col-span-2`],5:[`md:col-span-2 md:row-span-2`,``,``,``,``]},Hxe=({photo:e,large:t})=>{let n=Ob(e,t?{width:960,height:720}:{width:480,height:360});return n?(0,V.jsx)(hC,{image:n,loading:`lazy`,className:`size-full object-cover transition-transform duration-300 group-hover/tile:scale-[1.02]`}):null},Uxe=({item:e,record:t,recordKey:n})=>{let{views:r}=J(),i=Bxe(e,t,n),a=YS(i.holder?.name??``),[s,c]=(0,o.useState)();if(i.isPending)return(0,V.jsx)(tb,{title:e.title,children:(0,V.jsx)(cu,{className:`aspect-[4/3] w-full rounded-lg md:aspect-[2/1]`})});if(i.error)return(0,V.jsx)(tb,{title:e.title,children:(0,V.jsx)(ax,{title:`Could not load the photos`,error:i.error})});let l=i.items.length;if(l===0)return null;let{shown:u,more:d}=Dxe(l),f=i.holder,p=f&&r[f.name],m=f?Fxe(f,p,[e.photos?.image,e.photos?.field].filter(e=>e!==void 0)):[],h=f!==void 0&&a.read!==!1&&m.length>0;return(0,V.jsxs)(tb,{title:e.title,children:[(0,V.jsx)(`div`,{className:`grid aspect-[4/3] grid-cols-4 grid-rows-2 gap-1.5 overflow-hidden rounded-lg md:aspect-[2/1]`,children:i.items.slice(0,u).map((e,t)=>{let n=t===u-1&&d>0;return(0,V.jsxs)(`button`,{type:`button`,"aria-label":n?`Show all ${l} photos`:`Show photo ${t+1} of ${l}`,onClick:()=>c(t),className:B(`group/tile relative overflow-hidden bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary`,t===0?`col-span-4 row-span-2`:`max-md:hidden`,Vxe[u][t]),children:[(0,V.jsx)(Hxe,{photo:e.file,large:t===0}),n&&(0,V.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-backdrop/55 text-lg font-semibold text-white`,"aria-hidden":!0,children:`+${d}`}),t===0&&l>1&&(0,V.jsxs)(`span`,{className:`absolute bottom-2 right-2 flex items-center gap-1.5 rounded-full bg-background/85 px-2.5 py-1 text-xs font-medium tabular-nums text-foreground md:hidden`,"aria-hidden":!0,children:[(0,V.jsx)(pt,{className:`size-3.5`}),l]})]},t)})}),s!==void 0&&(0,V.jsx)(Pxe,{title:e.title,photos:i.items.map(e=>e.file),index:s,onIndex:c,onClose:()=>c(void 0),details:e=>{let t=i.items[e]?.key;return h&&t!==void 0?(0,V.jsx)(Ixe,{model:f,view:p,photoKey:t,fields:m},t):void 0},detailsTitle:f&&`${p?.names?.singular??K(f.name)} details`})]})},Wxe={create:`created this`,update:`changed`,delete:`deleted this`,undelete:`restored this`},Gxe=e=>e.actor?e.actor.name??e.actor.id:e.databaseRole?`Database (${e.databaseRole})`:`Database`,Kxe=(e,t,n)=>{let r=(e.operation===`create`?[]:e.changed).flatMap(r=>{let i=t.fields[r];if(!i||r===t.softDelete)return[];let a=n?.fields[r],o=a?.label??K(r);return i.sensitive||!e.before||!e.after?[{name:r,label:o}]:[{name:r,label:o,before:eS(i,e.before[r],a),after:eS(i,e.after[r],a)}]}),i=e.operation===`update`&&r.length===0?`changed this`:Wxe[e.operation];return{who:Gxe(e),verb:i,fields:r}},qxe=1500,Jxe=(e,t,n,r)=>{let i=G(),a=gh({queryKey:W.history(e,t,n),initialPageParam:``,queryFn:({pageParam:r})=>i.history(e,t,{pageSize:n,pageToken:r}),getNextPageParam:e=>e.nextPageToken||void 0}),{refetch:s}=a;return(0,o.useEffect)(()=>{let e=setTimeout(()=>void s(),qxe);return()=>clearTimeout(e)},[r,s]),{...a,items:a.data?.pages.flatMap(e=>e.items)??[]}},Yxe=()=>(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-4 w-full`},t))}),Xxe=({change:e,model:t,view:n})=>{let{who:r,verb:i,fields:a}=Kxe(e,t,n),o=Date.parse(e.at);return(0,V.jsxs)(`li`,{className:`flex flex-col gap-1.5 py-3 first:pt-0 last:pb-0`,children:[(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:r}),` `,(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:i}),` `,(0,V.jsxs)(`time`,{dateTime:e.at,title:df(o),className:`text-muted-foreground`,children:[`· `,bf(Math.max(0,Math.round((Date.now()-o)/1e3)))]})]}),a.length>0&&(0,V.jsx)(`dl`,{className:`grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-4 gap-y-1`,children:a.map(e=>(0,V.jsxs)(`div`,{className:`contents`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:e.label}),(0,V.jsx)(`dd`,{className:`min-w-0 break-words`,children:e.before===void 0?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`changed`}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`del`,{className:`text-muted-foreground`,children:e.before}),` → `,(0,V.jsx)(`ins`,{className:`no-underline`,children:e.after})]})})]},e.name))})]})},Zxe=({item:e,model:t,view:n,recordKey:r,etag:i})=>{let a=Jxe(t.name,r,e.limit??10,i);return(0,V.jsx)(tb,{title:e.title,children:a.isPending?(0,V.jsx)(Yxe,{}):a.error?(0,V.jsx)(ax,{title:`Could not load the history`,error:a.error}):a.items.length===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`No changes kept yet.`}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`ol`,{className:`divide-y divide-border`,children:a.items.map(e=>(0,V.jsx)(Xxe,{change:e,model:t,view:n},e.id))}),a.hasNextPage&&(0,V.jsx)(U,{size:`sm`,className:`mt-4`,disabled:a.isFetchingNextPage,onClick:()=>void a.fetchNextPage(),children:`Show more`})]})})},Qxe=(e,t)=>{let n=/(?:^|\s)@([^\s@]*)$/.exec(e.slice(0,t));return n?{start:t-n[1].length-1,query:n[1]}:void 0},$xe=(e,t,n)=>{let r=e.slice(t.start+1+t.query.length),i=`@${n}${r.startsWith(` `)?``:` `}`;return{text:`${e.slice(0,t.start)}${i}${r}`,caret:t.start+i.length+ +!!r.startsWith(` `)}},eSe=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),R9=e=>{let t=[...new Set(e)].filter(Boolean).sort((e,t)=>t.length-e.length);return t.length===0?void 0:RegExp(`(?<![\\p{L}\\p{N}_@])@(${t.map(eSe).join(`|`)})(?![\\p{L}\\p{N}_])`,`gu`)},tSe=(e,t)=>{let n=R9(t.map(e=>e.name)),r=new Set(n?[...e.matchAll(n)].map(e=>e[1]):[]);return[...new Set(t.filter(e=>r.has(e.name)).map(e=>e.id))]},nSe=(e,t)=>{let n=R9(t.flatMap(e=>e.name?[e.name]:[]));if(!n)return[{text:e}];let r=[],i=0;for(let t of e.matchAll(n))t.index>i&&r.push({text:e.slice(i,t.index)}),r.push({mention:t[1]}),i=t.index+t[0].length;return i<e.length&&r.push({text:e.slice(i)}),r},rSe=({comment:e})=>(0,V.jsx)(`p`,{className:`whitespace-pre-wrap break-words`,children:nSe(e.body,e.mentions).map((e,t)=>`mention`in e?(0,V.jsxs)(`span`,{className:`font-medium text-primary`,children:[`@`,e.mention]},t):e.text)}),iSe=(e,t,n)=>{let r=G(),i=K6(n,150);return mh({queryKey:W.mentionable(e,t,i??``),queryFn:()=>r.mentionable(e,t,i??``),enabled:i!==void 0,placeholderData:hm})},aSe=(e,t)=>{let n=G(),r=Gp();return hh({mutationFn:r=>n.comment(e,t,r),onSuccess:()=>r.invalidateQueries({queryKey:W.comments(e,t)})})},oSe=8,sSe=({resource:e,recordKey:t})=>{let[n,r]=(0,o.useState)(``),[i,a]=(0,o.useState)(0),[s,c]=(0,o.useState)(!1),[l,u]=(0,o.useState)([]),[d,f]=(0,o.useState)(0),[p,m]=(0,o.useState)(),h=(0,o.useRef)(null),g=(0,o.useRef)(void 0),_=(0,o.useId)(),v=Qy(),y=aSe(e,t),b=Qxe(n,i),x=s&&b!==void 0&&b.start!==p,S=iSe(e,t,x?b.query:void 0),C=x?(S.data??[]).slice(0,oSe):[],w=x&&S.data!==void 0,T=e=>`${_}-${e}`;(0,o.useEffect)(()=>f(0),[b?.query]);let E=b?.start;(0,o.useEffect)(()=>{E===void 0&&m(void 0)},[E]),(0,o.useLayoutEffect)(()=>{g.current!==void 0&&h.current&&(h.current.setSelectionRange(g.current,g.current),a(g.current),g.current=void 0)},[n]);let D=e=>{if(!b)return;let t=$xe(n,b,e.name);g.current=t.caret,r(t.text),u(t=>[...t,e])},O=()=>{n.trim()===``||y.isPending||y.mutate({body:n,mentions:tSe(n,l)},{onSuccess:()=>{r(``),u([])},onError:e=>v.show({state:`error`,title:`Could not post the comment`,description:lS(e)})})};return(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`div`,{className:`relative`,children:[(0,V.jsx)(cx,{ref:h,role:`combobox`,"aria-label":`Comment`,"aria-multiline":!0,"aria-autocomplete":`list`,"aria-expanded":w,"aria-controls":_,"aria-activedescendant":w&&C[d]?T(d):void 0,placeholder:`Write a comment, @ to mention someone`,value:n,onChange:e=>{r(e.target.value),a(e.target.selectionStart)},onSelect:e=>a(e.currentTarget.selectionStart),onFocus:()=>c(!0),onBlur:()=>c(!1),onKeyDown:e=>{if(e.key===`Enter`&&(e.metaKey||e.ctrlKey)){e.preventDefault(),O();return}if(!x)return;let t=I5(e.key,d,C.length);if(t!==void 0&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),f(t);return}if((e.key===`Enter`||e.key===`Tab`)&&C[d]){e.preventDefault(),D(C[d]);return}e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),m(b.start))}}),w&&(0,V.jsxs)(`ul`,{id:_,role:`listbox`,"aria-label":`People to mention`,className:`absolute z-30 mt-1 w-full max-w-sm rounded-md border bg-background py-1 shadow-pop`,onMouseDown:e=>e.preventDefault(),children:[C.map((e,t)=>(0,V.jsx)(`li`,{id:T(t),role:`option`,"aria-selected":t===d,className:B(`cursor-pointer truncate px-3 py-1.5`,t===d&&`bg-muted`),onMouseMove:()=>t!==d&&f(t),onClick:()=>D(e),children:e.name},e.id)),C.length===0&&(0,V.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`No one found`})]})]}),(0,V.jsx)(`div`,{children:(0,V.jsx)(U,{variant:`primary`,size:`sm`,disabled:n.trim()===``,loading:y.isPending,onClick:O,children:`Comment`})})]})},cSe=20,lSe=(e,t)=>{let n=G(),r=gh({queryKey:W.comments(e,t),initialPageParam:``,queryFn:({pageParam:r})=>n.comments(e,t,{pageSize:cSe,pageToken:r}),getNextPageParam:e=>e.nextPageToken||void 0});return{...r,items:r.data?.pages.flatMap(e=>e.items).reverse()??[]}},uSe=()=>(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-4 w-full`},t))}),dSe=({comment:e})=>{let t=e.author.name??e.author.id,n=Date.parse(e.createdAt);return(0,V.jsxs)(`li`,{className:`flex gap-3 py-3 first:pt-0 last:pb-0`,children:[(0,V.jsx)(xu,{initials:vg(t)||`?`,hue:_g(e.author.id),size:`md`,className:`ring-0`}),(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:t}),` `,(0,V.jsxs)(`time`,{dateTime:e.createdAt,title:df(n),className:`text-muted-foreground`,children:[`· `,bf(Math.max(0,Math.round((Date.now()-n)/1e3)))]})]}),(0,V.jsx)(rSe,{comment:e})]})]})},fSe=({item:e,resource:t,recordKey:n,canWrite:r})=>{let i=lSe(t,n);return(0,V.jsxs)(tb,{title:e.title,children:[i.isPending?(0,V.jsx)(uSe,{}):i.error?(0,V.jsx)(ax,{title:`Could not load the comments`,error:i.error}):(0,V.jsxs)(V.Fragment,{children:[i.hasNextPage&&(0,V.jsx)(U,{size:`sm`,className:`mb-4`,disabled:i.isFetchingNextPage,onClick:()=>void i.fetchNextPage(),children:`Show earlier comments`}),i.items.length===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`No comments yet.`}):(0,V.jsx)(`ol`,{className:`divide-y divide-border`,children:i.items.map(e=>(0,V.jsx)(dSe,{comment:e},e.id))})]}),r&&(0,V.jsx)(`div`,{className:`mt-4`,children:(0,V.jsx)(sSe,{resource:t,recordKey:n})})]})},z9=(e,t)=>{let n=G(),r=Gp(),i=Ao(t);return hh({mutationFn:({patch:r,etag:i})=>n.update(e,t,r,i),onSuccess:t=>{r.setQueryData(W.record(e,i),t),r.invalidateQueries({queryKey:[`page`,e]}),r.invalidateQueries({queryKey:[`list`,e]}),r.invalidateQueries({queryKey:[`map`,e]})}})},B9=e=>e instanceof Ls,pSe=e=>{let t=typeof e.resource==`string`?e.resource:e.resource.toModel().name;return e.op===`reorder`?`reorder ${t} by ${e.field}`:`${e.op} ${t}`},mSe=(e,t)=>{let n=e.operation,r=n===void 0?void 0:t[n];return r?`Operation ${n+1} (${pSe(r)}) failed: ${e.message} Nothing was saved.`:`${e.message} Nothing was saved.`},hSe=(e,t)=>new e.constructor({...e.problem,detail:mSe(e,t)}),V9=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),gSe=({model:e,stored:t,recordKey:n,mode:r,subject:i,draftKey:a,lines:s})=>{let c=G(),l=Gp(),u=z9(e.name,n),d=Q5(r,i),[f]=(0,o.useState)(()=>a?Sxe(localStorage,a,t.etag):void 0),[p,m]=(0,o.useState)(f?.fields??{}),[h,g]=(0,o.useState)(!!f),[_,v]=(0,o.useState)(!1),[y,b]=(0,o.useState)({}),[x,S]=(0,o.useState)({}),[C,w]=(0,o.useState)(0),T=Object.entries(p).filter(([n,r])=>Vb(e.fields[n],r,t.record[n])),E=T.length>0,D=E||!!s?.dirty;(0,o.useEffect)(()=>{f?.order&&s?.setOrder(f.order)},[]),(0,o.useEffect)(()=>{if(!a)return;let n=Object.fromEntries(Object.entries(p).filter(([t])=>!e.fields[t]?.sensitive)),r=Object.keys(n).length>0||!!s?.dirty;Cxe(localStorage,a,r?{etag:t.etag,fields:n,...s?.order&&{order:s.order}}:void 0)},[a,e,p,s?.dirty,s?.order,t.etag]);let O=n=>n in p?p[n]:[`boolean`,`file`].includes(e.fields[n].type)?t.record[n]:Mb(t.record[n]),k=(n,r)=>{S(e=>V9(e,n));let i=typeof r==`string`?r!==Mb(t.record[n]):Vb(e.fields[n],r,t.record[n]);m(e=>i?{...e,[n]:r}:V9(e,n))},A=async()=>{let r=await c.get(e.name,n);l.setQueryData(W.record(e.name,n),r);let i={},a={};for(let[n,o]of Object.entries(p)){let s=e.fields[n];Vb(s,o,r.record[n])&&(a[n]=o,Mb(r.record[n])!==Mb(t.record[n])&&(i[n]=s.type===`file`?eS(s,r.record[n]):Mb(r.record[n])))}m(a),b(i)},j=()=>Object.fromEntries(T.map(([t,n])=>[t,Rb(e.fields[t],n)])),M=e=>{let t=WC(e);S(t),Object.keys(t).length>0&&w(e=>e+1)},N=async()=>{try{await u.mutateAsync({patch:j(),etag:t.etag})}catch(e){throw B9(e)?await A():Rs(e)&&M(e),e}},ee=async r=>{let i=[...E?[{op:`update`,resource:e.name,key:n,data:j(),etag:t.etag}]:[],...r];try{await c.batchWrite(i)}catch(e){throw B9(e)?(await A(),await l.invalidateQueries({queryKey:[`list`]}),v(!0)):Rs(e)&&M(e),Rs(e)?hSe(e,i):e}await Promise.all([l.invalidateQueries({queryKey:W.record(e.name,n)}),l.invalidateQueries({queryKey:[`list`]}),l.invalidateQueries({queryKey:[`page`]}),l.invalidateQueries({queryKey:[`map`]})]),s?.reset()};return{value:O,change:k,save:()=>d.run(async()=>{let e=s?.op()??[];e.length>0?await ee(e):await N(),m({}),b({}),S({}),v(!1),g(!1)}),dirty:D,discard:()=>{m({}),b({}),S({}),v(!1),g(!1),s?.reset()},restored:h&&D,dismissRestored:()=>g(!1),linesConflict:_,saving:d.phase===`saving`,phase:d.phase,message:d.message,conflicts:y,errors:x,rejections:C,keepMine:e=>b(t=>V9(t,e)),useTheirs:e=>{b(t=>V9(t,e)),m(t=>V9(t,e))}}},H9=(e,t,n,r)=>{let i=G(),a=Gp(),o=Object.values(e.fields).filter(n=>n.type===`relation`&&n.relation&&n.name!==e.tenant&&r[n.name]!=null&&t[n.relation.resource]?.primaryKey.length===1),s=fh({queries:o.map(e=>{let o=t[e.relation.resource],s=String(r[e.name]);return{queryKey:W.relatedLabel(o.name,s),queryFn:async()=>(await c4(a,i,o,[s],n[o.name])).get(s)??s}})}),c=o.map(e=>({kind:`record`,resource:e.relation.resource,key:String(r[e.name])}));return{addresses:Object.fromEntries(o.map((e,t)=>[e.name,c[t]])),labels:Object.fromEntries(o.map((e,t)=>[e.name,s[t]?.data]))}},_Se=co(),vSe=(e,t,n,r,i)=>{if(e.primaryKey.length!==1)return[];let a=new Set(r.flatMap(e=>e.kind===`related`&&!e.through?[`${e.resource}.${e.field}`]:[])),o=Object.values(t).flatMap(t=>Object.values(t.fields).filter(t=>t.type===`relation`&&t.relation?.resource===e.name&&t.relation.columns.length===1&&t.filterable).filter(e=>e.name!==t.tenant&&t.name!==i?.name&&!a.has(`${t.name}.${e.name}`)).map(e=>({source:t,field:e.name})));return o.map(({source:e,field:t})=>{let r=n[e.name],i=r?.names?.plural??K(e.name),a=o.filter(t=>t.source.name===e.name).length>1;return{resource:e.name,field:t,label:a?`${i} (${r?.fields[t]?.label??K(t)})`:i}})},ySe=(e,t)=>({kind:`list`,resource:e.resource,filter:qa(_Se.eq(e.field,t))}),bSe=co(),xSe=(e,t,n)=>{let r=G(),i=fh({queries:e.map(e=>{let i=qa(bSe.eq(e.field,n));return{queryKey:W.list(e.resource,i,``,1,`incoming`),queryFn:async()=>{let n=await r.list(e.resource,{filter:i,pageSize:1,count:`exact`,fields:t[e.resource].primaryKey});return{count:n.totalSize??n.totalSizeEstimate,exact:n.totalSize!==void 0}}}})});return e.flatMap((e,t)=>{let n=i[t];return n.error?[]:[{relation:e,count:n.data}]})},SSe=({model:e,recordKey:t,layout:n,lines:r})=>{let{resources:i,views:a}=J(),o=xSe(vSe(e,i,a,n,r),i,t);return o.length===0?null:(0,V.jsx)(ab,{title:`Related records`,children:(0,V.jsx)(`ul`,{className:`-mx-2`,children:o.map(({relation:e,count:n})=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(ZS,{to:ySe(e,t),className:`group flex items-center justify-between gap-3 rounded-md px-2 py-2 hover:bg-muted`,children:[(0,V.jsx)(`span`,{className:`min-w-0 truncate font-medium text-primary-text`,children:e.label}),(0,V.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 tabular-nums text-muted-foreground`,children:[n===void 0?(0,V.jsx)(cu,{className:`h-4 w-6`}):`${Bd(n.count)}${n.exact?``:`+`}`,(0,V.jsx)(Se,{className:`size-4 text-faint-foreground group-hover:text-foreground`})]})]})},`${e.resource}.${e.field}`))})})},U9=co(),W9=(...e)=>{let t=e.filter(e=>!!e);return t.length===1?t[0]:t.map(e=>`(${e})`).join(` AND `)},CSe=(e,t)=>{let n=G(),{resources:r}=J(),i=e.through,a=i?r[i.resource]:void 0,o=i?.key??a?.primaryKey[0],s=i?W9(qa(U9.eq(i.field,t)),i.filter):``,c=mh({queryKey:W.list(a?.name??``,s,``,0,`related:${o}`),enabled:!!(a&&o),queryFn:async()=>{let e=await T6(n,a.name,{filter:s,fields:[o]});return[...new Set(e.items.flatMap(e=>e[o]===null||e[o]===void 0?[]:[String(e[o])]))]}});return i?c.data?{filter:c.data.length===0?null:W9(qa(U9.in(e.field,c.data)),e.filter),isPending:!1,error:null}:{filter:void 0,isPending:c.isPending,error:c.error}:{filter:W9(qa(U9.eq(e.field,t)),e.filter),isPending:!1,error:null}},wSe=()=>(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-4 w-full`},t))}),TSe=({text:e})=>(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:e??`Nothing here yet.`}),ESe=({item:e,recordKey:t,owner:n})=>{let{resources:r,views:i}=J(),a=r[e.resource],s=a&&i[a.name],c=CSe(e,t),[l,u]=q5(s,`related:${n}:${e.title}`,e.display),d=YS(e.resource),[f,p]=(0,o.useState)(!1);if(!a)return null;let m=ave(e,a,r),h=e.columns??Zx(a,s).filter(t=>t!==e.field),g=Bbe(e,a,d),_=(0,V.jsx)(G5,{view:s,value:l,onChange:u}),v=g?(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[!f&&_,(0,V.jsx)(b9,{size:`sm`,sorting:f,onChange:p})]}):_;return f&&g?(0,V.jsx)(tb,{title:e.title,help:e.help,actions:v,children:(0,V.jsx)(y9,{model:a,view:s,field:g,filter:qa(U9.eq(e.field,t)),columns:h})}):(0,V.jsx)(tb,{title:e.title,help:e.help,actions:v,children:c.isPending?(0,V.jsx)(wSe,{}):c.error?(0,V.jsx)(ax,{title:`Could not load`,error:c.error}):c.filter===null||c.filter===void 0?(0,V.jsx)(TSe,{text:e.empty}):(0,V.jsx)(K5,{model:a,view:s,filter:c.filter,sort:e.sort??``,columns:h,limit:e.limit??10,display:l,empty:e.empty,opens:m},c.filter)})},DSe=(e,t)=>t===e.tenant||e.primaryKey.includes(t),OSe=(e,t,n)=>{if(t&&t.layout.length>0)return t.layout;let r=Object.values(e.fields).filter(t=>!DSe(e,t.name)),i=r.filter(e=>!e.readOnly);return[{kind:`section`,title:`Details`,fields:(i.length>0&&!n?i:r).map(e=>e.name)},...e.history?[{kind:`history`,title:`History`}]:[],...e.comments?[{kind:`comments`,title:`Comments`}]:[]]},kSe=({resource:e,recordKey:t})=>{let{resources:n}=J(),r=n[e],i=Cg(e,t);return r?i.isPending?(0,V.jsx)(KS,{title:`Loading`,children:`Fetching the record.`}):i.error?(0,V.jsx)(`div`,{className:`p-8`,children:Rs(i.error)&&i.error.status===404?(0,V.jsx)(KS,{title:`Not found`,children:`This record does not exist, or you cannot see it.`}):(0,V.jsx)(ax,{title:`Could not load the record`,error:i.error})}):(0,V.jsx)(ASe,{model:r,recordKey:t,stored:i.data,preview:i.isPlaceholderData},i.isPlaceholderData?`preview`:`loaded`):(0,V.jsxs)(KS,{title:`Not found`,children:[`There is no resource called `,e,`.`]})},ASe=({model:e,recordKey:t,stored:n,preview:r})=>{let i=J(),{address:a,go:s}=XS(),c=i.views[e.name],l=Ix(e,c,n.record,t),{state:u}=H(),d=(0,o.useMemo)(()=>vxe(i.resources,e),[i.resources,e]),f=Exe(d,Txe(d,e,t).items),p=gSe({model:e,stored:n,recordKey:t,mode:c?.saveFeedback??`toast`,subject:l,draftKey:!r&&u.kind===`signed-in`?xxe(u.user.id,e.name,t):void 0,lines:f}),m=Gp(),h=G(),g=KC(p.rejections),_=YS(e.name),v=n7(e),y=MT(_,`update`)&&n.permissions?.update!==!1,{shown:b,offersEdit:x,editing:S}=Hb(c?.recordMode,y,a?.kind===`record`&&a.edit===!0);Hne(p.dirty&&b===`form`),Fne(p.dirty);let C={kind:`record`,resource:e.name,key:t},w={...C,edit:!0},T=b===`form`&&c?.recordMode!==void 0&&c.recordMode!==`edit`,E=MT(_,`delete`)&&n.permissions?.delete!==!1,D=t7({model:e,view:c,restore:v,onDeleted:()=>s({kind:`list`,resource:e.name},{replace:!0}),onReview:()=>void m.invalidateQueries({queryKey:W.record(e.name,t)})}),O=H9(e,i.resources,i.views,n.record),k=t=>{let n=e.fields[t],r=n?.relation?i.resources[n.relation.resource]:void 0;if(r&&r.primaryKey.length===1&&t!==e.tenant&&!e.primaryKey.includes(t))return r},A=Object.values(e.fields).filter(e=>k(e.name)),j={...n.record,...Object.fromEntries(A.map(e=>[e.name,zb(e,p.value(e.name))]))},M=H9(e,i.resources,i.views,j),N=(e,t)=>{let n=k(e);if(!n||!Kb(t))return p.change(e,t);m.setQueryData(W.relatedLabel(n.name,t.key),t.label),p.change(e,Yb(n,t.key))},{fields:ee}=SC(),P=OSe(e,c,b===`read`).filter(e=>Gb(e.when,S)),te=P.flatMap(e=>e.kind===`sidebar`?e.fields:[]),F=e.fields.status?.type===`enum`,ne=n.record.status,re=F&&!te.includes(`status`)&&ne!=null&&ne!==``?String(ne):void 0,ie=M9(e,`updated`),I=e=>c?.fields[e],ae=e=>PT(n.permissions,e)!==`hidden`&&Gb(I(e)?.when,S),oe=e=>!r||Object.hasOwn(n.record,e),se=r=>{let a=e.fields[r],o=PT(n.permissions,r);if(!a||o===`hidden`)return null;let s=p.conflicts[r],l=k(r),u=I(r)?.label??K(r),d=p.errors[r];return(0,V.jsx)(eb,{name:r,label:u,required:b===`form`&&o!==`read`&&Fb(a),help:Wb(I(r),c,S),error:d&&UC(a,u,d),wide:!!(I(r)?.multiline||I(r)?.markdown),conflict:s===void 0?void 0:{user:{name:`Someone else`,initials:`?`,hue:40},ago:`just now`,theirValue:s||`—`,onKeepMine:()=>p.keepMine(r),onUseTheirs:()=>p.useTheirs(r)},children:oe(r)?(0,V.jsx)(IC,{field:a,hints:I(r),value:p.value(r),stored:n.record[r],relationLabel:M.labels[r],relationTo:M.addresses[r],relationPicker:l&&{target:l,view:i.views[l.name]},locked:b!==`form`||o===`read`,invalid:!!p.errors[r],reveal:a.sensitive?()=>h.reveal(e.name,t,r):void 0,resource:e.name,onChange:e=>N(r,e)}):(0,V.jsx)(cu,{className:`h-9`})},a.sensitive?`${r}:${n.etag}`:r)},L=r=>{let i=e.fields[r],a=oe(r)?i.sensitive?(0,V.jsx)(IC,{field:i,hints:I(r),value:``,stored:n.record[r],locked:!0,reveal:()=>h.reveal(e.name,t,r),resource:e.name,onChange:e=>p.change(r,e)}):(0,V.jsx)(m4,{model:e,field:i,value:n.record[r],relationLabel:O.labels[r]}):(0,V.jsx)(cu,{className:`h-4 w-32`});return{label:I(r)?.label??K(r),help:Wb(I(r),c,S),wide:!!(I(r)?.multiline||I(r)?.markdown),value:a}},ce=P.findIndex(e=>e.kind===`sidebar`),le=(0,V.jsx)(ob,{title:`Summary`,rows:te.flatMap(t=>{let r=e.fields[t];if(!r||!ae(t))return[];if(!oe(t))return[{label:I(t)?.label??K(t),value:(0,V.jsx)(cu,{className:`h-4 w-24`})}];let i=eS(r,n.record[t],I(t)),a=n.record[t],o=Mx(r,I(t))&&typeof a==`string`&&a!==``,s=r.type===`text`&&typeof a==`string`&&a!==``?Vx(I(t)):void 0,c=r.type===`enum`?(0,V.jsx)(p4,{value:a,hints:I(t),children:i}):o?(0,V.jsx)(OC,{source:a}):s?(0,V.jsx)(PC,{format:s,value:i}):(0,V.jsx)(`strong`,{title:tS(r,a),className:I(t)?.multiline?`whitespace-pre-line break-words`:void 0,children:i}),l=CC(ee,r,I(t));return[{label:I(t)?.label??K(t),value:l?(0,V.jsx)(EC,{shown:l,part:`display`,field:r,value:n.record[t],fallback:c}):c}]})}),ue={model:e,record:n.record,key:t,etag:n.etag,permissions:n.permissions},de=async()=>{await p.save()&&T&&s(C,{replace:!0})},fe=E?()=>void D.start({key:t,title:l,etag:n.etag,snapshot:n.record}):void 0,pe=b===`form`&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{variant:`primary`,className:`max-md:min-h-11 max-md:flex-1 md:w-full`,loading:p.saving,disabled:!p.dirty&&p.phase!==`saved`,onClick:()=>void de(),children:[p.phase===`saved`&&(0,V.jsx)(ge,{className:`size-4`}),p.phase===`saved`?`Saved`:`Save`]}),T&&(0,V.jsx)(ZS,{to:C,className:B(Cf(),`max-md:min-h-11 md:w-full`),onClick:e=>lu(e)&&p.discard(),children:`Cancel`}),p.dirty&&(0,V.jsx)(`span`,{className:`text-xs text-muted-foreground max-md:order-first`,children:`Unsaved changes`})]});return(0,V.jsxs)(`div`,{ref:g,className:`flex flex-1 flex-col`,inert:r,children:[D.dialogs,(0,V.jsx)(`div`,{className:`flex-1`,children:(0,V.jsxs)(`div`,{className:`mx-auto max-w-[1100px] px-4 pb-8 pt-6 md:px-10 md:py-8`,children:[(0,V.jsx)(sb,{title:l,status:re?{label:rs(re,I(`status`)?.valueLabels),tone:Gx(re)}:void 0}),p.message&&(0,V.jsx)(`div`,{className:`mt-4`,children:(0,V.jsx)(ax,{title:`Not saved`,error:Error(p.message)})}),p.linesConflict&&(0,V.jsx)(`div`,{className:`mt-4`,children:(0,V.jsx)(ax,{title:`The lines were changed by someone else`,error:Error(`The lines were reloaded. Your new order is kept: Save again to apply it.`)})}),b!==`form`&&x&&p.dirty&&(0,V.jsxs)(`div`,{className:`mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2`,role:`status`,children:[(0,V.jsx)(`span`,{children:`You have unsaved changes to this record.`}),(0,V.jsxs)(`span`,{className:`flex gap-2`,children:[(0,V.jsx)(ZS,{to:w,className:Cf({size:`sm`}),children:`Continue editing`}),(0,V.jsx)(U,{size:`sm`,onClick:p.discard,children:`Discard`})]})]}),b===`form`&&p.restored&&(0,V.jsxs)(`div`,{className:`mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2`,role:`status`,children:[(0,V.jsx)(`span`,{children:`Your unsaved changes were restored.`}),(0,V.jsxs)(`span`,{className:`flex gap-2`,children:[(0,V.jsx)(U,{size:`sm`,onClick:p.dismissRestored,children:`Keep`}),(0,V.jsx)(U,{size:`sm`,onClick:p.discard,children:`Discard`})]})]}),(0,V.jsxs)(`div`,{className:`grid grid-cols-1 gap-8 md:grid-cols-[minmax(0,1fr)_300px] md:gap-12`,children:[(0,V.jsxs)(`main`,{className:`divide-y divide-border`,children:[P.flatMap((i,a)=>{if(i.kind===`related`)return[(0,V.jsx)(ESe,{item:i,recordKey:t,owner:e.name},`related:${i.title}`)];if(r&&(i.kind===`custom`||i.kind===`map`||i.kind===`gallery`))return[];if(i.kind===`custom`)return i.sidebar?[]:[(0,V.jsx)(N9,{item:i,scope:ue},`custom:${a}`)];if(i.kind===`map`)return i.sidebar?[]:[(0,V.jsx)(P9,{item:i,record:n.record},`map:${a}`)];if(i.kind===`gallery`)return[(0,V.jsx)(Uxe,{item:i,record:n.record,recordKey:t},`gallery:${a}`)];if(i.kind===`history`)return[(0,V.jsx)(Zxe,{item:i,model:e,view:c,recordKey:t,etag:n.etag},`history:${a}`)];if(i.kind===`comments`)return[(0,V.jsx)(fSe,{item:i,resource:e.name,recordKey:t,canWrite:u.kind!==`visitor`},`comments:${a}`)];if(i.kind!==`section`)return[];let o=i.fields.filter(t=>e.fields[t]&&ae(t)),s=b===`read`&&i.presentation===`facts`,l=s?aS(n.record,o):o;return l.length===0?[]:[(0,V.jsx)(tb,{title:i.title,help:Ub(i.helpWhen,c,S)?i.help:void 0,children:s?(0,V.jsx)(lb,{facts:l.map(e=>({label:L(e).label,value:L(e).value,icon:b8(I(e)?.icon)}))}):b===`read`?(0,V.jsx)(cb,{rows:l.map(L)}):(0,V.jsx)(`div`,{className:`grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2`,children:l.map(se)})},i.title)]}),d&&!r&&(0,V.jsx)(bxe,{lines:d,draft:f,vatRate:Number(n.record.vatRate??21)/100,saving:p.saving,locked:b!==`form`})]}),(0,V.jsxs)(`aside`,{className:`space-y-4 md:pt-8`,children:[pe&&(0,V.jsx)(`div`,{className:`hidden flex-col items-center gap-2 md:flex`,children:pe}),!r&&(0,V.jsx)(_xe,{model:e,stored:n,recordKey:t,edit:x?w:void 0,onDelete:fe}),ce===-1&&le,P.map((e,t)=>e.kind===`custom`&&e.sidebar&&!r?(0,V.jsx)(N9,{item:e,scope:ue},`custom:${t}`):e.kind===`map`&&e.sidebar&&!r?(0,V.jsx)(P9,{item:e,record:n.record},`map:${t}`):t===ce?(0,V.jsx)(o.Fragment,{children:le},`summary`):null),(0,V.jsx)(ob,{title:`Details`,rows:[M9(e,`created`),ie].flatMap(t=>{let r=t?e.fields[t]:void 0;return!t||!r||!ae(t)?[]:[{label:I(t)?.label??K(t),value:oe(t)?(0,V.jsx)(`span`,{title:tS(r,n.record[t]),children:eS(r,n.record[t],I(t))}):(0,V.jsx)(cu,{className:`h-4 w-24`})}]})}),!r&&(0,V.jsx)(SSe,{model:e,recordKey:t,layout:P,lines:d})]})]})]})}),pe&&(0,V.jsx)(`div`,{className:`sticky bottom-[var(--pb-sticky-bottom,0px)] z-20 flex shrink-0 items-center gap-2 border-t bg-background p-3 md:hidden`,children:pe})]})},jSe=e=>Rs(e)?e.status===401||e.status===403?`It did not accept your sign-in: ${e.message}`:e.message:`It did not answer.`,MSe=({status:e})=>{let t=Gp();return e.state===`error`?(0,V.jsx)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center p-8`,children:(0,V.jsxs)(`div`,{className:`max-w-md text-center`,children:[(0,V.jsxs)(`h1`,{className:`text-[16px] font-semibold`,children:[`Cannot reach `,e.source.label]}),(0,V.jsxs)(`p`,{className:`mt-1 text-muted-foreground`,children:[jSe(e.error),` The rest of the app works as before.`]}),(0,V.jsx)(U,{className:`mt-3`,onClick:()=>void t.refetchQueries({queryKey:W.sourceMetas(e.source.url)}),children:`Try again`})]})}):(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading from `,e.source.label]})},G9=(e,t)=>e.toLowerCase().includes(t.trim().toLowerCase()),NSe=(e,t,n=``)=>{let r=A9(e,n).flatMap(e=>e.items.filter(e=>e.href!==void 0&&!e.problem)).filter(e=>G9(e.label,t)).slice(0,5),i=t.trim().replace(/^new\s+/i,``),a=Object.values(e.resources).flatMap(r=>{let a=e.views[r.name];if(!a||a.nav?.hidden||!r7(a,e.pages,e.permissions[r.name]??zS))return[];let o=a.names?.singular??K(r.name),s=`New ${o.toLowerCase()}`;return!G9(s,t)&&!G9(o,i)&&!G9(a.names?.plural??K(r.name),i)?[]:[{id:`new:${r.name}`,title:s,href:ps({kind:`create`,resource:r.name},n)}]});return[...r.length>0?[{id:`go-to`,label:`Go to`,hits:r.map(e=>({id:`go-to:${e.id}`,title:e.label,href:e.href}))}]:[],...a.length>0?[{id:`create`,label:`Create`,hits:a.slice(0,5)}]:[]]},PSe=co(),FSe=e=>Object.values(e.resources).flatMap(t=>{let n=e.views[t.name];return!t.search?.length||!n||n.nav?.hidden||e.permissions[t.name]?.read===!1?[]:[{model:t,view:n,label:n.names?.plural??K(t.name)}]}),ISe=e=>{let t=e.map(e=>e.label.toLowerCase());return t.length===0?`Search`:t.length===1?`Search ${t[0]}`:t.length===2?`Search ${t[0]} and ${t[1]}`:`Search ${t[0]}, ${t[1]} and more`},LSe=e=>qa(PSe.search(e.trim())),K9=e=>{let t=e.view?.searchResult?.title;return t?.length?t:[Fx(e.model,e.view)]},q9=e=>{let t=K9(e);return e.view?.searchResult?.subtitle??e.model.search?.find(e=>!t.includes(e))},RSe=e=>{let t=q9(e),n=[...K9(e),...t?[t]:[],...e.model.search??[]];return[...new Set([...e.model.primaryKey,...n.filter(t=>Object.hasOwn(e.model.fields,t))])]},J9=(e,t,n)=>{let r=t[n];return r==null?``:e.model.fields[n]?.type===`enum`?rs(String(r),e.view?.fields[n]?.valueLabels):String(r)},zSe=(e,t,n,r=``)=>{let i=Ao(zx(e.model,t)),a=K9(e),o=q9(e),s=Ua(e.model,t,n,[...a,...o?[o]:[]])??o,c=s?J9(e,t,s):``;return{id:i,title:a.map(n=>J9(e,t,n)).filter(Boolean).join(` `)||i,...c&&{subtitle:c},href:ps({kind:`record`,resource:e.model.name,key:i},r)}},BSe=()=>{let e=J(),t=G(),{basePath:n}=wh(),r=(0,o.useMemo)(()=>FSe(e),[e]),[i,a]=(0,o.useState)(``),s=i.trim(),c=K6(s,200),l=s.length>=2,u=l&&c.length>=2,d=fh({queries:r.map(e=>({queryKey:[`global-search`,e.model.name,c],enabled:u,staleTime:1/0,gcTime:0,queryFn:()=>t.list(e.model.name,{filter:LSe(c),pageSize:5,fields:RSe(e)})}))}),f=(0,o.useMemo)(()=>u?NSe(e,c,n):[],[u,e,c,n]),p=r.flatMap((e,t)=>{let r=d[t];if(!u||!r)return[];if(r.error)return[{id:e.model.name,label:e.label,hits:[],failed:!0}];let i=(r.data?.items??[]).map(t=>zSe(e,t,c,n));return i.length>0?[{id:e.model.name,label:e.label,hits:i}]:[]}),m=[...f,...p];return{available:Object.keys(e.pages).length>0||Object.keys(e.resources).length>0,placeholder:ISe(r),text:i,setText:a,query:u?c:``,loading:l&&(s!==c||d.some(e=>e.isFetching)),groups:m}},VSe=e=>!!(e?.updateAvailable&&e.indicator),HSe=e=>e?5e3:18e5,Y9={immediate:`Updates as soon as a release is out`,weekly:`Updates at a set time every week`,scheduled:`Updates at the time set for this release`,manual:`Updates only when asked to`},USe={job:`Preparing the update`,build:`Building`},WSe=(e,t)=>{if(!e.updateStage)return`Updating now`;let n=USe[e.updateStage];return e.updateStartedAt?`${n}, started ${_f(Math.max(0,Math.floor((t-Date.parse(e.updateStartedAt))/1e3)))}`:n},X9=(e,t=Date.now(),n=Wd())=>e.updating?WSe(e,t):e.nextUpdateAt?`${Y9[e.policy]}: next on ${df(Date.parse(e.nextUpdateAt),n)}`:Y9[e.policy],GSe=(e,t=Wd())=>{let n=df(Date.parse(e.finishedAt),t),r={succeeded:`Updated to ${e.toVersion} on ${n}`,unchanged:`The update to ${e.toVersion} on ${n} changed nothing`,failed:`The update to ${e.toVersion} failed on ${n}`}[e.outcome];return e.message?`${r}: ${e.message}`:`${r}.`},KSe=e=>Rs(e)&&e.status<500&&e.problem.detail?e.problem.detail:Rs(e)&&e.status===409?`Already on the latest version, or an update is running.`:Rs(e)&&e.status===403?`Only an admin can update the runtime.`:`The update could not be started. Try again later.`,Z9=({label:e,value:t})=>(0,V.jsxs)(`div`,{className:`flex justify-between gap-4 py-1`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:e}),(0,V.jsx)(`span`,{className:`font-medium tabular-nums`,children:t})]}),qSe=({status:e,requesting:t,error:n,checkError:r,onUpdate:i,onClose:a})=>{let o=e.updating?void 0:e.lastUpdate;return(0,V.jsxs)(wf,{title:`Runtime update`,description:e.updating?(0,V.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,V.jsx)(ld,{className:`size-3.5`}),X9(e)]}):X9(e),onClose:a,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:a,children:`Close`}),(0,V.jsx)(U,{variant:`primary`,loading:t,disabled:e.updating||!e.updateAvailable,onClick:i,children:e.updating?`Updating…`:`Update now`})]}),children:[(0,V.jsx)(Z9,{label:`Current version`,value:e.version}),(0,V.jsx)(Z9,{label:`Latest version`,value:e.latest}),o&&(0,V.jsx)(`p`,{className:o.outcome===`failed`?`mt-3 text-danger-text`:`mt-3 text-muted-foreground`,children:GSe(o)}),n!==void 0&&(0,V.jsx)(`p`,{role:`alert`,className:`mt-3 text-danger-text`,children:KSe(n)}),r!==void 0&&(0,V.jsx)(`p`,{className:`mt-3 text-muted-foreground`,children:`The status could not be checked again; this is the last one read.`})]})},JSe=e=>{let t=xg(),n=(0,o.useRef)(t);n.current=t;let r=t!==void 0;return(0,o.useMemo)(()=>r?Wl({url:e,token:()=>n.current}):void 0,[e,r])},YSe=e=>{let[t,n]=(0,o.useState)(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(),[c,l]=(0,o.useState)(),u=t?.updating??!1;return(0,o.useEffect)(()=>{if(!e)return;let t=!0,r=()=>e.status().then(e=>{t&&(n(e),l(void 0))},e=>t&&l(e));r();let i=setInterval(()=>void r(),HSe(u));return()=>{t=!1,clearInterval(i)}},[e,u]),{status:t,update:(0,o.useCallback)(async()=>{e&&(i(!0),s(void 0),await e.update().then(n,s),i(!1))},[e]),requesting:r,error:a,checkError:c}},Q9=({client:e})=>{let{status:t,update:n,requesting:r,error:i,checkError:a}=YSe(e),[s,c]=(0,o.useState)(!1);return!t||!s&&!VSe(t)?null:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{size:`sm`,variant:`ghost`,"aria-label":`Update available`,title:`Update available`,onClick:()=>c(!0),className:`max-md:size-9 max-md:p-0`,children:[(0,V.jsx)(Ee,{className:`size-3.5 text-primary`}),(0,V.jsx)(`span`,{className:`max-md:sr-only`,children:`Update`})]}),s&&(0,V.jsx)(qSe,{status:t,requesting:r,error:i,checkError:a,onUpdate:()=>void n(),onClose:()=>c(!1)})]})},XSe=({url:e})=>(0,V.jsx)(Q9,{client:JSe(e)}),ZSe=({url:e,client:t})=>t?(0,V.jsx)(Q9,{client:t}):(0,V.jsx)(XSe,{url:e}),QSe=({signIn:e,onStop:t})=>{let[n,r]=(0,o.useState)(!1),[i,a]=(0,o.useState)(),s=async()=>{r(!0),a(void 0);try{await t()}catch(e){if(!(e instanceof pc))throw e;a(xd(e)),r(!1)}};return(0,V.jsxs)(`div`,{role:`region`,"aria-label":`Staff session`,className:`flex flex-wrap items-center gap-x-3 gap-y-2 border-b border-warning/40 bg-warning-soft px-4 py-2 text-warning-text`,children:[(0,V.jsx)(uee,{"aria-hidden":!0,className:`size-4 shrink-0`}),(0,V.jsxs)(`p`,{className:`min-w-64 flex-1 break-words`,children:[(0,V.jsx)(`span`,{className:`font-semibold`,children:e.staffName??e.staff}),` is signed in as `,(0,V.jsx)(`span`,{className:`font-semibold`,children:e.user}),` until`,` `,df(Date.parse(e.expiresAt)),`. Reason: `,e.reason]}),i&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,V.jsx)(U,{size:`sm`,loading:n,onClick:()=>void s(),children:`Stop staff session`})]})},$Se=(e,t,n)=>({filter:n.filter??``,orderBy:n.orderBy??jS(e,t),pageSize:n.limit??3,fields:[...new Set([...e.primaryKey,Fx(e,t),n.status])]}),eCe=(e,t,n,r,i,a)=>r.map(r=>{let o=Ao(zx(e,r)),s=String(r[n.status]??``);return{id:o,label:Ix(e,t,r,o),href:ps({kind:`record`,resource:e.name,key:o},i),status:e.fields[n.status]?.type===`enum`&&s?rs(s,t.fields[n.status]?.valueLabels):s,tone:n.tones[s]??`neutral`,pulse:n.pulse?.includes(s)??!1,active:o===a}}),tCe=(e,t,n,r,i)=>{let a=n.find(t=>Ao(zx(e,t))===r);return a!==void 0&&t.some(e=>!Object.is(a[e],i[e]))},$9=({model:e,request:t})=>W.navRecent(e.name,t.filter,t.orderBy,t.pageSize),nCe=e=>{let t=Gp();(0,o.useEffect)(()=>t.getQueryCache().subscribe(n=>{if(n.type!==`updated`||n.action.type!==`success`)return;let[r,i,a]=n.query.queryKey,o=n.action.data?.record;if(r===`record`&&typeof a==`string`&&o)for(let n of e){if(n.model.name!==i)continue;let e=t.getQueryData($9(n));e&&tCe(n.model,n.request.fields,e.items,a,o)&&t.invalidateQueries({queryKey:$9(n),exact:!0})}}),[t,e])},rCe=(e,t,n)=>{let r=G(),i=(0,o.useMemo)(()=>{let t=k9(e);return Object.values(e.views).flatMap(n=>{let r=e.resources[n.resource],i=n.nav?.recent;return r&&i&&!n.nav?.hidden&&!t.has(r.name)?[{model:r,view:n,recent:i,request:$Se(r,n,i)}]:[]})},[e]);nCe(i);let a=fh({queries:i.map(e=>({queryKey:$9(e),queryFn:()=>r.list(e.model.name,e.request)}))});return Object.fromEntries(i.map(({model:e,view:r,recent:i},o)=>{let s=a[o];if(s.isPending)return[e.name,{state:`loading`}];if(s.isError)return[e.name,{state:`error`}];let c=n.resource===e.name?n.key:void 0;return[e.name,{state:`ready`,records:eCe(e,r,i,s.data.items,t,c)}]}))},iCe=e=>e?.kind===`page`?e.page:e?.resource,aCe=e=>e?.kind===`record`?e:void 0,oCe=({workspace:e,sidebarMode:t,assistant:n,runtime:r})=>{let i=J(),{state:a,session:s,signOut:c,stopStaffSession:l,organizations:u}=H(),d=Ih();if(a.kind!==`signed-in`&&a.kind!==`visitor`)throw Error(`The shell is only rendered for a signed-in user or a visitor`);let f=a.kind===`signed-in`?a.user:void 0,p=a.kind===`signed-in`?a.staff:void 0,{path:m,params:h,basePath:g}=wh(),{address:_,go:v,open:y}=XS(),b=iCe(_),x=aCe(_),S=BSe(),C=xw(),w=A9(i,g,rCe(i,g,{resource:b,key:x?.key})),T=Object.keys(i.pages)[0],E=Object.keys(i.resources)[0],D=_?.kind===`page`?i.pages[_.page]:void 0;(0,o.useEffect)(()=>{m===`/`&&(T?v({kind:`page`,page:T},{replace:!0}):E&&v({kind:`list`,resource:E},{replace:!0}))},[m,T,E,v]);let O=_?.kind===`page`?void 0:_?.resource,k=O?GS(i,O):void 0,A=O?i.views[O]:void 0,j=w.find(e=>e.items.some(e=>e.id===b)),M=O?i.resources[O]:void 0,N=Cg(x?.resource??``,x?.key??``,!!(M&&x)),ee=M&&x&&N.data?Ix(M,A,N.data.record,x.key):void 0,P=!!x&&(N.isLoading||k?.state===`loading`),{shell:te}=SC(),F=te?.actions,ne=te?.rightPanel,[re,ie]=(0,o.useState)(!1),I=i.assistant?.url,ae=I&&(0,V.jsx)($w,{open:re,onToggle:()=>ie(!re)}),oe=I&&re&&(0,V.jsx)(nT,{url:I,client:n,page:h.size>0?`${m}?${h}`:m,onClose:()=>ie(!1)}),se=i.errorReporting;(0,o.useEffect)(()=>{se&&jre(se)},[se]);let L=i.runtime?.url,ce=L&&(0,V.jsx)(ZSe,{url:L,client:r}),le=sxe((0,o.useCallback)(()=>T9(g),[g]),!!f),ue=f&&oxe(f,le.current),de=ue?bg(ue):!1,fe=dxe(),pe=Xbe(!!(u&&f)),me=pe.current,he=!!u&&me!==void 0&&!me.organization,ge=u&&f?wre[m]:void 0,_e=f?m===`/-/account`?`Sign-in & security`:m===`/-/sign-in-policy`?`Sign-in policy`:ge:void 0,ve=A?.names?.plural??(O&&K(O)),ye=_e?[_e]:cT({basePath:g,address:_,group:j?.label,page:D,resourceLabel:ve,recordTitle:ee,recordLoading:P});rx(nx(tx({address:_,page:D,accountPage:_e,resourceLabel:ve,singular:A?.names?.singular??(O&&K(O)),recordTitle:ee,recordLoading:P}),i.appName));let be=f&&m===`/-/account`?(0,V.jsx)(jp,{email:f.email}):f&&m===`/-/sign-in-policy`?de?(0,V.jsx)(Up,{}):(0,V.jsx)(KS,{title:`Admins only`,children:`Only an admin can change how people sign in.`}):ge&&m===`/-/organization`?(0,V.jsx)(txe,{current:me,basePath:g,onChanged:pe.reload}):ge&&(m===`/-/organization/members`||m===`/-/organization/invitations`)?Uh(me)?m===`/-/organization/members`?(0,V.jsx)(Kbe,{current:me}):(0,V.jsx)(Ybe,{current:me}):(0,V.jsx)(KS,{title:`Owners and admins only`,children:`Only the organization's owners and admins manage its members.`}):ge&&m===`/-/organizations`||he?(0,V.jsx)(axe,{state:pe,basePath:g}):_?_.kind===`page`?D?(0,V.jsx)(Z5,{name:D.name},D.name):(0,V.jsxs)(KS,{title:`Not found`,children:[`There is no page called `,_.page,`.`]}):k&&k.state!==`ready`?(0,V.jsx)(MSe,{status:k}):_.kind===`create`?(0,V.jsx)(yve,{resource:_.resource,values:_.values},_.resource):_.kind===`record`?(0,V.jsx)(kSe,{resource:_.resource,recordKey:_.key},`${_.resource}/${_.key}`):(0,V.jsx)(Wbe,{address:_},_.resource):m===`/`?(0,V.jsx)(KS,{title:`Choose a resource`,children:`Pick one from the sidebar.`}):(0,V.jsx)(KS,{title:`Not found`,children:`There is nothing at this address.`}),xe=(0,V.jsx)(hd,{pageScroll:!0,sidebarMode:t??`text-small`,activeItem:b??``,breadcrumb:ye,user:ue&&Qre(ue),onSignOut:f&&(()=>void c()),signIn:f?void 0:d.link(),workspace:me?.organization?.name??e,appName:i.appName,logo:uxe,navGroups:w,bottomBar:sT(i,g,b),userMenu:[...cxe(i,g,b),...u&&f?Tre(g,m,me):[],...f?ar(g,m,de):[]],organizations:u&&{...me?.organization&&{current:{id:me.organization.id,name:me.organization.name}},others:pe.organizations.filter(e=>e.id!==me?.organization?.id),onSwitch:e=>void s.organizations.switchTo(e).then(()=>T9(g))},theme:{preference:C.preference,onChange:C.choose},roles:le.current?.active?{active:le.current.active,roles:le.current.roles,onSwitch:le.switchTo}:void 0,onNavigate:y,search:S.available?{placeholder:S.placeholder,text:S.text,onTextChange:S.setText,query:S.query,loading:S.loading,groups:S.groups,onSelect:y}:void 0,actions:(F||ce||ae)&&(0,V.jsxs)(V.Fragment,{children:[F&&(0,V.jsx)(Qh,{name:`shell.actions`,fallback:null,children:(0,V.jsx)(F,{})}),ce,ae]}),rightPanel:(ne||oe)&&(0,V.jsxs)(V.Fragment,{children:[ne&&(0,V.jsx)(Qh,{name:`shell.rightPanel`,fallback:null,children:(0,V.jsx)(ne,{})}),oe]}),children:be}),Se=de&&fe.length>0;return!p&&!Se?xe:(0,V.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[p&&(0,V.jsx)(QSe,{signIn:p,onStop:l}),Se&&(0,V.jsx)(pxe,{off:fe}),(0,V.jsx)(`div`,{className:`min-h-0 flex-1`,children:xe})]})},sCe=({baseUrl:e,client:t,sources:n,workspace:r,sidebarMode:i,ui:a,assistant:o,runtime:s})=>{let{state:c,session:l,markSignedOut:u}=H();return(0,V.jsx)(Sh,{baseUrl:e,client:t,sources:n,token:c.kind===`visitor`?void 0:l.token,onUnauthenticated:u,children:(0,V.jsx)(JS,{children:(0,V.jsx)($y,{children:(0,V.jsx)(fxe,{ui:a,children:(0,V.jsx)(oCe,{workspace:r,sidebarMode:i,assistant:o,runtime:s})})})})})},cCe=({baseUrl:e,client:t,ui:n,children:r})=>{let i=dw();return i?(0,V.jsx)(Sh,{baseUrl:e,client:t,children:(0,V.jsx)(xC.Provider,{value:n??{},children:(0,V.jsx)(lw,{name:i.name},i.name)})}):r},lCe=({auth:e,workspace:t,basePath:n,initialUrl:r,pluginLoader:i,...a})=>(0,V.jsx)(bw,{children:(0,V.jsx)(Fd,{session:e,children:(0,V.jsx)(Bne,{basePath:n,initialUrl:r,children:(0,V.jsx)(Kre,{...i&&{loader:i},children:(0,V.jsx)(cCe,{baseUrl:a.baseUrl,client:a.client,ui:a.ui,children:(0,V.jsx)(Xre,{workspace:t,children:(0,V.jsx)(sCe,{workspace:t,...a})})})})})})});export{G as $,Cw as A,eb as B,Nw as C,Ow as D,kw as E,ZS as F,Rre as G,xg as H,XS as I,qh as J,ig as K,BS as L,bC as M,yC as N,Ew as O,QS as P,Sh as Q,cx as R,Iw as S,jw as T,ug as U,Sg as V,dg as W,kh as X,Ah as Y,Oh as Z,Zw as _,L5 as a,ld as at,Uw as b,F_e as c,zu as ct,oE as d,B as dt,xh as et,aE as f,b as ft,Qw as g,dT as h,$5 as i,Cf as it,Sw as j,ww as k,C8 as l,Pu as lt,ST as m,B9 as n,wf as nt,J_e as o,sd as ot,jT as p,$h as q,z9 as r,U as rt,P_e as s,od as st,lCe as t,If as tt,iE as u,hu as ut,Yw as v,Mw as w,zw as x,qw as y,tb as z};
|
|
69
|
+
`,U7=`http://schemas.openxmlformats.org/officeDocument/2006/relationships`,W7=`http://schemas.openxmlformats.org/package/2006/relationships`;`${H7}`,`${H7}${W7}${U7}`,`${H7}${W7}${U7}${U7}`,new TextEncoder;var Dye=co(),G7=e=>e?.export!==!1,K7=e=>Object.values(e.fields).flatMap(e=>e.sensitive?[]:[e.name]),Oye=(e,t)=>{let n=new Set(K7(e));return Zx(e,t).filter(e=>n.has(e))},q7=(e,t,n)=>Object.fromEntries(Qx(e,t,[],n).map(e=>[e.id,e.header])),kye=(e,t,n)=>{let r=q7(e,t,n);return n.flatMap(n=>{let i=e.fields[n];return i?[{name:n,header:r[n],field:i,hints:t?.fields[n]??{}}]:[]})},J7=(e,t)=>{let n=e?.export?e.export.maxRows??1/0:1/0;return Math.min(n,t===`xlsx`?Eye:1/0)},Y7=e=>e.primaryKey.length===1,Aye=(e,t)=>{let[n]=e.primaryKey;if(!n||e.primaryKey.length!==1)throw Error(`Not implemented: selected rows are exported by a single-field key`);let r=[];for(let e=0;e<t.length;e+=500)r.push(qa(Dye.in(n,t.slice(e,e+500))));return r},jye=()=>{let e=new Worker(new URL(`/assets/export-worker-BoAr3vuF.js`,``+import.meta.url),{type:`module`,name:`protobase-export`}),t=[];return e.onmessage=e=>t.shift()?.resolve(e.data.bytes),e.onerror=e=>{e.preventDefault();let n=Error(`The export could not be built: ${e.message}`);for(let e of t.splice(0))e.reject(n)},{send:n=>new Promise((r,i)=>{t.push({resolve:r,reject:i}),e.postMessage(n)}),close:()=>e.terminate()}},Mye=[{value:`xlsx`,label:`Excel (.xlsx)`},{value:`csv`,label:`CSV`}],Nye=[{value:`shown`,label:`As shown`},{value:`raw`,label:`Raw values`}],Pye={shown:`Labels, dates and numbers as the list shows them.`,raw:`Values as they are stored, such as keys and codes.`},Fye=e=>e.kind===`counting`?`Counting rows…`:e.kind===`exact`||e.rows>1e4?Ud(e.rows):`more than 10,000 rows`,X7=e=>{if(e.kind!==`counting`)return e.kind===`exact`?e.rows:Math.max(e.rows,10001)},Z7=({label:e,help:t,children:n})=>(0,V.jsxs)(`div`,{className:`flex flex-col items-start gap-1.5`,children:[(0,V.jsx)(`span`,{className:`text-[13px] font-medium`,children:e}),n,t&&(0,V.jsx)(`span`,{className:`text-xs text-muted-foreground`,children:t})]}),Q7=(e,t,n)=>{let r=e.indexOf(t),i=[...e];return i.splice(r,1),i.splice(r+n,0,t),i},Iye=({fields:e,columns:t,onChange:n})=>{let r=Object.fromEntries(e.map(e=>[e.name,e.label])),i=[...t,...e.map(e=>e.name).filter(e=>!t.includes(e))];return(0,V.jsx)(`ul`,{className:`divide-y self-stretch rounded-md border`,"aria-label":`Columns`,children:i.map(e=>{let i=t.includes(e),a=t.indexOf(e);return(0,V.jsxs)(`li`,{className:`flex min-h-10 items-center gap-2 px-3 py-1`,children:[(0,V.jsxs)(`label`,{className:`flex min-w-0 flex-1 cursor-pointer items-center gap-2.5`,children:[(0,V.jsx)(Fh,{checked:i,label:r[e],onChange:r=>n(r?[...t,e]:t.filter(t=>t!==e))}),(0,V.jsx)(`span`,{className:i?`truncate`:`truncate text-muted-foreground`,children:r[e]})]}),i&&(0,V.jsxs)(`span`,{className:`flex shrink-0 gap-1`,children:[(0,V.jsx)(U,{size:`sm`,variant:`ghost`,className:`min-h-8 px-2`,"aria-label":`Move ${r[e]} up`,disabled:a===0,onClick:()=>n(Q7(t,e,-1)),children:(0,V.jsx)(A,{className:`size-3.5`})}),(0,V.jsx)(U,{size:`sm`,variant:`ghost`,className:`min-h-8 px-2`,"aria-label":`Move ${r[e]} down`,disabled:a===t.length-1,onClick:()=>n(Q7(t,e,1)),children:(0,V.jsx)(S,{className:`size-3.5`})})]})]},e)})})},Lye=({plural:e,view:t,fields:n,initialColumns:r,count:i,selected:a,open:s,onExport:c,onClose:l})=>{let[u,d]=(0,o.useState)(`xlsx`),[f,p]=(0,o.useState)(a?`selected`:`list`),[m,h]=(0,o.useState)(r),[g,_]=(0,o.useState)(`shown`),v=J7(t,u),y=f===`selected`?`${Bd(a??0)} selected ${a===1?`row`:`rows`}`:Fye(i),b=(f===`selected`?a??0:X7(i)??0)>v,x=[{value:`list`,label:`Rows in the list`},{value:`selected`,label:`Selected (${Bd(a??0)})`}];return(0,V.jsx)(dT,{title:`Export ${e.toLowerCase()}`,open:s,onClose:l,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:l,children:`Cancel`}),(0,V.jsx)(U,{variant:`primary`,disabled:m.length===0,onClick:()=>c({format:u,scope:f,columns:m,mode:g}),children:`Export`})]}),children:(0,V.jsxs)(`div`,{className:`flex flex-col gap-4 text-[13px]`,children:[(0,V.jsx)(Z7,{label:`Format`,children:(0,V.jsx)(Pu,{size:`md`,label:`Format`,value:u,options:Mye,onChange:d})}),a!==void 0&&a>0&&(0,V.jsx)(Z7,{label:`Rows`,help:f===`list`?`With the list’s filters, search and sort.`:void 0,children:(0,V.jsx)(Pu,{size:`md`,label:`Rows`,value:f,options:x,onChange:p})}),(0,V.jsx)(Z7,{label:`Values`,help:Pye[g],children:(0,V.jsx)(Pu,{size:`md`,label:`Values`,value:g,options:Nye,onChange:_})}),(0,V.jsx)(Z7,{label:`Columns`,children:(0,V.jsx)(Iye,{fields:n,columns:m,onChange:h})}),(0,V.jsxs)(`p`,{role:`status`,className:`text-muted-foreground`,children:[`Exports `,y,`.`,b&&` A file holds at most ${Bd(v)} rows; the rest are left out.`]})]})})},Rye=({plural:e,done:t,total:n,onCancel:r})=>{let i=n?Math.min(1,t/n):void 0;return(0,V.jsx)(dT,{title:`Exporting ${e.toLowerCase()}`,open:!0,onClose:r,actions:(0,V.jsx)(U,{onClick:r,children:`Cancel`}),children:(0,V.jsxs)(`div`,{className:`flex flex-col gap-2 text-[13px]`,children:[(0,V.jsx)(`div`,{role:`progressbar`,"aria-label":`Rows exported`,"aria-valuemin":0,"aria-valuemax":n,"aria-valuenow":t,className:`h-1.5 overflow-hidden rounded-full bg-muted`,children:(0,V.jsx)(`div`,{className:`h-full rounded-full bg-primary transition-[width]`,style:{width:`${(i??0)*100}%`}})}),(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:n?`${Bd(t)} of ${Bd(n)} rows`:`${Bd(t)} rows`})]})})},$7={xlsx:{mime:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,extension:`.xlsx`,description:`Excel workbook`},csv:{mime:`text/csv`,extension:`.csv`,description:`CSV file`}},zye=/[\\/:*?"<>|\u0000-\u001f]/g,Bye=(e,t,n=new Date)=>{let r=[n.getFullYear(),String(n.getMonth()+1).padStart(2,`0`),String(n.getDate()).padStart(2,`0`)].join(`-`);return`${e.replace(zye,` `).trim()} ${r}${$7[t].extension}`},Vye=8e6,Hye=(e,t)=>{let n=new Blob([],{type:$7[t].mime}),r=[],i=0,a=()=>{n=new Blob([n,...r],{type:$7[t].mime}),r=[],i=0};return{write:async e=>{e.length!==0&&(r.push(e),i+=e.length,i>=Vye&&a())},close:async()=>{a();let t=URL.createObjectURL(n),r=document.createElement(`a`);r.href=t,r.download=e,r.click(),setTimeout(()=>URL.revokeObjectURL(t),6e4)},abort:async()=>{r=[],n=new Blob([])}}},e9=()=>globalThis.showSaveFilePicker,Uye=()=>typeof e9()==`function`,Wye=async(e,t)=>{let n=e9();if(!n)throw Error(`This browser cannot save a file as it is built`);let r=$7[t],i;try{i=await n({suggestedName:e,types:[{description:r.description,accept:{[r.mime]:[r.extension]}}]})}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;throw e}let a=await i.createWritable();return{write:async e=>{e.length>0&&await a.write(e)},close:()=>a.close(),abort:()=>a.abort()}},Gye=(e,t)=>Uye()?Wye(e,t):Promise.resolve(Hye(e,t)),Kye=(e,t)=>{let n=t[e.primaryKey[0]];return typeof n==`object`&&n&&`id`in n?n.id:n},qye=({model:e,view:t,resources:n,views:r,plural:i,filter:a,orderBy:s,createPort:c=jye,createSink:l=Gye})=>{let u=G(),d=Qy(),[f,p]=(0,o.useState)({kind:`closed`}),m=(0,o.useRef)(void 0),h=mh({queryKey:W.exportCount(e.name,a),enabled:f.kind===`settings`,queryFn:async()=>{let t=await u.list(e.name,{filter:a||void 0,pageSize:1,count:`exact`,fields:e.primaryKey});return t.totalSize===void 0?{kind:`estimate`,rows:t.totalSizeEstimate}:{kind:`exact`,rows:t.totalSize}}}).data??{kind:`counting`},g=(t=[])=>p({kind:`settings`,selected:Y7(e)?t.map(t=>Kye(e,t)):[]}),_=async(o,f)=>{let g=Bye(i,o.format),_=await l(g,o.format);if(!_)return;let v=J7(t,o.format),y=o.scope===`selected`?f.length:X7(h),b=y===void 0?void 0:Math.min(y,v),x=new AbortController;m.current=x,p({kind:`running`,done:0,total:b});try{let l=await Tye({client:u,resource:e.name,filters:o.scope===`selected`?Aye(e,f):[a],orderBy:s,plan:{format:o.format,mode:o.mode,name:i,columns:kye(e,t,o.columns)},labels:o.mode===`shown`?u4(n,r,e,o.columns):{},limit:v,port:c(),sink:_,signal:x.signal,onProgress:e=>x.signal.aborted||p({kind:`running`,done:e,total:b})});d.show({state:`success`,title:`Exported ${Bd(l.rows)} ${i.toLowerCase()}`,description:l.truncated?`${g}: the first ${Bd(l.rows)} rows, as many as a file holds.`:g})}catch(e){if(e instanceof DOMException&&e.name===`AbortError`)return;if(!Rs(e))throw e;d.show({state:`error`,title:`Could not export ${i.toLowerCase()}`,description:e.message})}finally{m.current=void 0,p(e=>e.kind===`running`?{kind:`closed`}:e)}},v=()=>{m.current?.abort(),p({kind:`closed`})},y=K7(e),b=q7(e,t,y);return{open:g,dialogs:f.kind===`settings`?(0,V.jsx)(Lye,{plural:i,view:t,fields:y.map(e=>({name:e,label:b[e]})),initialColumns:Oye(e,t),count:h,selected:f.selected.length>0?f.selected.length:void 0,open:!0,onExport:e=>void _(e,f.selected),onClose:()=>p({kind:`closed`})}):f.kind===`running`?(0,V.jsx)(Rye,{plural:i,done:f.done,total:f.total,onCancel:v}):null}},Jye=({state:e,onClearSearch:t,onClearFilters:n,create:r})=>(0,V.jsxs)(`div`,{className:`flex flex-col items-center gap-3 py-8 text-center text-muted-foreground`,children:[(0,V.jsx)(`p`,{children:e.message}),(e.clearSearch||e.clearFilters||e.create&&r)&&(0,V.jsxs)(`div`,{className:`flex flex-wrap justify-center gap-2`,children:[e.clearSearch&&(0,V.jsx)(U,{onClick:t,children:`Clear search`}),e.clearFilters&&(0,V.jsx)(U,{onClick:n,children:`Clear filters`}),e.create&&r]})]}),Yye=({plural:e,search:t,filtered:n,scoped:r,canCreate:i})=>{let a=e.toLowerCase();return t?{message:`No ${a} match “${t}”.`,clearSearch:!0,clearFilters:n,create:!1}:n?{message:`No ${a} match these filters.`,clearSearch:!1,clearFilters:!0,create:!1}:r?{message:`No ${a} match.`,clearSearch:!1,clearFilters:!1,create:!1}:{message:`No ${a} yet.`,clearSearch:!1,clearFilters:!1,create:i}},Xye=(e,t)=>{},Zye=({windowMs:e=1e3,comebacks:t=2,onHold:n=Xye}={})=>{let r,i=[],a;return(o,s)=>{if(a?.among.has(o))return a.value;if(a&&(a=void 0,i=[]),o===r||(r=o,i=i.filter(t=>s-t.at<=e),i.push({value:o,at:s,comeback:i.some(e=>e.value===o)}),i.filter(e=>e.comeback).length<t))return o;let c=new Set(i.slice(-2*t).map(e=>e.value));return a={value:Math.min(...c),among:c},n(a.value,[...c]),a.value}},Qye=e=>Math.max(1,Math.floor((e+12)/252)),$ye=(e,t)=>Math.max(0,(e-(t-1)*12)/t),ebe=(e,t,n,r)=>({start:e*n,end:Math.max(0,Math.min(r,(t+1)*n)-1)}),tbe=(e,t,n)=>{let r=e/t.rowHeight;return t.columns===n.columns?r*n.rowHeight:Math.floor(Math.floor(r)*t.columns/n.columns)*n.rowHeight},nbe=8,rbe=(e,t,n)=>{let r=e.get(t);if(r!==void 0&&r>=n)return e;let i=new Map(e);i.delete(t),i.set(t,n);for(let e of i.keys()){if(i.size<=nbe)break;i.delete(e)}return i},ibe=({source:e,label:t,initialIndex:n,onScrollIndex:r,minHeight:i,children:a})=>{let{total:s}=e,[c]=(0,o.useState)(n),[l,u]=(0,o.useState)(0),d=Qye(l),f=$ye(l,d),[p,m]=(0,o.useState)(()=>new Map),h=Math.ceil(Math.max(i(f),p.get(f)??0)),g=h+12,_={columns:d,rowHeight:g},v=(0,o.useRef)({layout:_,top:0}),y=v.current.top>0&&(v.current.layout.columns!==d||v.current.layout.rowHeight!==g),b=e=>y?tbe(v.current.top,v.current.layout,_):e,x=f>0&&p.has(f),S=x6({total:Math.ceil(s/d),rowHeight:g,initialIndex:Math.floor(c/d),settle:b,ready:x});(0,o.useLayoutEffect)(()=>{y&&S.scrollTo(S.top),v.current={layout:_,top:S.top},y||r(Math.floor(Math.max(0,S.top)/g)*d)});let C=ebe(S.first,S.last,d,s),w=p6({total:s,rowAt:e.rowAt,loadRows:e.loadRows,revision:e.revision,latencyMs:0},C.start,C.end),[T]=(0,o.useState)(()=>Zye());(0,o.useLayoutEffect)(()=>{let e=S.ref.current;if(!e)return;let t=()=>u(T(e.clientWidth,performance.now())),n=new ResizeObserver(t);return n.observe(e),t(),()=>n.disconnect()},[T]);let E=(0,o.useRef)(f);E.current=f;let[D]=(0,o.useState)(()=>new ResizeObserver(e=>{let t=Math.max(...e.map(e=>e.borderBoxSize[0]?.blockSize??e.contentRect.height)),n=E.current;m(e=>rbe(e,n,t))}));(0,o.useLayoutEffect)(()=>()=>D.disconnect(),[D]);let O=(0,o.useCallback)(e=>{if(e)return D.observe(e),()=>D.unobserve(e)},[D]);return(0,V.jsx)(`ul`,{ref:S.ref,className:`relative min-w-0 flex-auto`,"aria-label":t,style:{height:S.geometry.contentHeight},children:S.rows.flatMap(({index:e,offset:t})=>Array.from({length:d},(n,r)=>{let i=e*d+r;if(i>=s)return[];let o=w(i),c={top:t,left:r*(f+12),width:f,minHeight:h};return o?(0,V.jsx)(`li`,{ref:O,"aria-posinset":i+1,"aria-setsize":s,className:`absolute grid grid-cols-[minmax(0,1fr)]`,style:c,children:a(o)},o.id):(0,V.jsx)(`li`,{"aria-hidden":!0,className:`absolute grid grid-cols-[minmax(0,1fr)]`,style:c,children:(0,V.jsx)(cu,{className:`h-full rounded-lg`})},`skeleton-${i}`)}))})},abe=`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,obe=e=>e*.75,sbe=44,cbe=({model:e,view:t,display:n,list:r,empty:i})=>{let a=t?.names?.plural??K(e.name),o=n.card===void 0&&(n.image!==void 0||n.photos!==void 0);return r.isLoading?(0,V.jsx)(`div`,{className:`min-h-0 flex-1 overflow-hidden ${abe}`,children:Array.from({length:6},(e,t)=>(0,V.jsx)(cu,{className:`h-24`},t))}):r.error?(0,V.jsx)(ax,{title:`Could not load rows`,error:r.error}):!r.source||r.source.total===0?i??(0,V.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,a.toLowerCase(),` match.`]}):(0,V.jsx)(ibe,{source:r.source,label:a,initialIndex:r.initialIndex,onScrollIndex:r.onScrollIndex,minHeight:e=>(o?obe(e):0)+sbe,children:r=>(0,V.jsx)(B8,{model:e,view:t,display:n,row:AS(e,r)})})},t9=new Map,lbe=()=>{let{entry:e,path:t,params:n}=wh(),r=`${t}?${n.toString()}`,i=t9.get(e),a=(0,o.useCallback)(t=>void t9.set(e,{url:r,index:t}),[e,r]);return{initialIndex:i?.url===r?i.index:0,remember:a}},n9=e=>e.reduce((e,t)=>e+t.count,0),ube=e=>{let t=Math.floor(e.length/2),n=n9(e.slice(0,t)),r=n9(e.slice(e.length-t));return n===0?0:(r-n)/n*100},dbe=({active:e,payload:t,noun:n})=>{let r=t?.[0]?.payload;return!e||!r?null:(0,V.jsxs)(`div`,{className:`rounded-md border bg-background px-2.5 py-1.5 text-xs shadow-pop`,children:[(0,V.jsx)(`div`,{className:`text-muted-foreground`,children:sf(r.at)}),(0,V.jsxs)(`div`,{className:`font-semibold tabular-nums`,children:[Bd(r.count),` `,n]})]})},r9={fontSize:11,fill:`var(--muted-foreground)`},fbe=({title:e=`Orders created`,noun:t=`orders`,defaultGranularity:n=`day`,data:r,granularity:i,onGranularityChange:a,periodLabel:s,className:c})=>{let[l,u]=(0,o.useState)(n),d=i??l,f=a??u,p=r??Ny(d),m=Gl(`(min-width: 640px)`),h=ube(p);return(0,V.jsxs)(`section`,{className:B(`rounded-lg border bg-background px-4 pb-2 pt-3`,c),children:[(0,V.jsxs)(`header`,{className:`flex flex-wrap items-center justify-between gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-baseline gap-2`,children:[(0,V.jsx)(`h2`,{className:`font-semibold`,children:e}),(0,V.jsx)(`span`,{className:`font-semibold tabular-nums`,children:Bd(n9(p))}),(0,V.jsxs)(`span`,{className:B(`text-xs font-medium tabular-nums`,h>=0?`text-success-text`:`text-danger-text`),children:[h>=0?`+`:`−`,Math.abs(h).toFixed(1),`%`]}),(0,V.jsx)(`span`,{className:`hidden text-xs text-muted-foreground sm:inline`,children:s??`last ${d===`day`?`30 days`:`12 weeks`}`})]}),(0,V.jsx)(Pu,{value:d,onChange:f,options:[{value:`day`,label:`Day`},{value:`week`,label:`Week`}]})]}),(0,V.jsx)(`div`,{className:`mt-2 h-24`,children:(0,V.jsx)(aM,{width:`100%`,height:`100%`,children:(0,V.jsxs)($2,{data:p,margin:{top:4,right:0,bottom:0,left:0},barCategoryGap:d===`day`?`22%`:`30%`,children:[(0,V.jsx)(r0,{vertical:!1,stroke:`var(--border)`}),(0,V.jsx)(X0,{dataKey:`at`,padding:{left:4,right:m?4:18},tickFormatter:cf,tick:r9,axisLine:!1,tickLine:!1,interval:d===`day`?m?4:9:m?1:3,height:18}),(0,V.jsx)(t2,{width:m?36:28,tick:r9,axisLine:!1,tickLine:!1,tickCount:3}),(0,V.jsx)(Zq,{cursor:{fill:`var(--muted)`},content:(0,V.jsx)(dbe,{noun:t}),isAnimationActive:!1}),(0,V.jsx)(H0,{dataKey:`count`,fill:`var(--primary)`,radius:[2,2,0,0],isAnimationActive:!1})]})})})]})},pbe={"7d":`last 7 days`,"30d":`last 30 days`,"90d":`last 90 days`,"1y":`last year`,all:`all time`},mbe=({resource:e,chart:t,title:n,noun:r,filter:i})=>{let[a,s]=(0,o.useState)(t.granularity===`week`?`week`:`day`),c=a===`week`?`90d`:t.range,l=aE(e,{field:t.field,range:c,granularity:a,filter:i,timeZone:Wd()}).data?.points.map(e=>({at:Date.parse(`${e.bucket}Z`),count:e.count}))??[];return(0,V.jsx)(fbe,{title:n,noun:r,data:l,granularity:a,onGranularityChange:s,periodLabel:a===`week`?`last 12 weeks`:pbe[c]})},i9=(e,t,n)=>{let r=e.sum??e.average;if(r===void 0)return n;let i=t?.fields[r]?.label??K(r);return e.sum===void 0?`Average ${i.toLowerCase()}`:`${i}`},hbe=({model:e,view:t,chart:n,plural:r,filter:i})=>{let a=t?.fields[n.groupBy]?.label??K(n.groupBy);return(0,V.jsxs)(`section`,{className:`rounded-lg border bg-background px-4 pb-3 pt-3`,"aria-label":`${i9(n,t,r)} by ${a.toLowerCase()}`,children:[(0,V.jsxs)(`h2`,{className:`mb-2 font-semibold`,children:[i9(n,t,r),` by `,a.toLowerCase()]}),(0,V.jsx)(s4,{model:e,view:t,groupBy:n.groupBy,type:n.type,sum:n.sum,average:n.average,limit:n.limit,filter:i})]})},gbe=({value:e,onCommit:t,placeholder:n,className:r})=>{let[i,a]=(0,o.useState)(e);return(0,o.useEffect)(()=>a(e),[e]),(0,o.useEffect)(()=>{if(i===e)return;let n=setTimeout(()=>t(i),350);return()=>clearTimeout(n)},[i,e,t]),(0,V.jsx)(sd,{wrapperClassName:B(`min-w-0 flex-1 sm:w-72 sm:flex-initial`,r),leading:(0,V.jsx)(pn,{className:`size-4`}),placeholder:n,"aria-label":`Search`,value:i,onChange:e=>a(e.target.value),onKeyDown:e=>e.key===`Enter`&&t(i)})},_be=(e,t,n,r,i)=>{let a=n?.list?.relatedColumns??[];if(a.length===0)return e;let o=new Map(e.map(e=>[e.id,e]));return Zx(t,n).flatMap(e=>{let t=o.get(e);if(t)return[t];let n=a.find(t=>t.name===e),s=n&&r[n.resource];if(!n||!s)return[];let c=n.label??K(n.name);return[{id:n.name,header:c,kind:`text`,width:160,minWidth:dx(c,!1),sortable:!1,render:e=>(0,V.jsx)(P8,{column:n,records:e[n.name]??[],target:s,view:i[s.name],Card:B8})}]})},vbe=({model:e,view:t,target:n,children:r})=>{let i=D8(e.name,t.listOf,!0),a=t.names?.plural??K(e.name),o=e=>(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[(0,V.jsx)(gd,{title:a,subtitle:t.help}),e]});if(i.error)return o((0,V.jsx)(ax,{title:`Could not load your ${a.toLowerCase()}`,error:i.error}));if(!i.data)return o((0,V.jsx)(`div`,{className:`grid grid-cols-[repeat(auto-fill,minmax(15rem,1fr))] gap-3`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-24`},t))}));let s=T8(n,i.data);return s?r(s):o((0,V.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,a.toLowerCase(),` yet.`]}))},a9=({title:e,chips:t,label:n,required:r,initial:i=``,busy:a,onSave:s,onClose:c})=>{let l=(0,o.useId)(),[u,d]=(0,o.useState)(i),f=`${l}-form`;return(0,V.jsx)(dT,{open:!0,title:e,onClose:c,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:c,children:`Cancel`}),(0,V.jsx)(U,{type:`submit`,form:f,variant:`primary`,loading:a,children:`Save`})]}),children:(0,V.jsxs)(`form`,{id:f,className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),s(u.trim()===``?null:u.trim())},children:[t.length>0&&(0,V.jsx)(M6,{chips:t}),(0,V.jsxs)(`div`,{className:`flex flex-col gap-1.5`,children:[(0,V.jsxs)(`div`,{className:`flex items-baseline justify-between gap-2`,children:[(0,V.jsx)(`label`,{htmlFor:l,className:`font-medium`,children:n}),!r&&(0,V.jsx)(`span`,{id:`${l}-hint`,className:`text-xs text-muted-foreground`,children:`Optional`})]}),(0,V.jsx)(sd,{id:l,value:u,required:r,pattern:r?`.*\\S.*`:void 0,"aria-describedby":r?void 0:`${l}-hint`,autoFocus:!0,autoComplete:`off`,onChange:e=>d(e.target.value)})]})]})})},o9=co(),ybe={start:0,end:0},s9=(e,t)=>o9.and(t,{kind:`present`,field:e.field,span:ybe}),c9=e=>{switch(e.kind){case`and`:case`or`:return{...e,args:e.args.map(c9)};case`not`:return l9(e.arg);case`search`:case`present`:case`isNull`:return e;default:return s9(e,e)}},l9=e=>{switch(e.kind){case`and`:return o9.or(...e.args.map(l9));case`or`:return o9.and(...e.args.map(l9));case`not`:return c9(e.arg);case`search`:case`present`:case`isNull`:return o9.not(e);default:return s9(e,o9.not(e))}},u9=e=>{let t=Sa(e);if(!t.ok)throw Error(`The filter cannot be read: ${t.errors.map(e=>e.message).join(`; `)}`);return t.ast},d9=(e,t)=>{let n=u9(e);if(!n)return null;let r=u9(t),i=o9.not(c9(n));return qa(r?o9.and(r,i):i)},bbe=(e,t)=>d9(t,e),f9=e=>e.key.startsWith(`extra:`)?`extra:${e.label}`:e.key,xbe=(e,t)=>{let n=new Map(e.map(e=>[f9(e),e])),r=new Map(t.map(e=>[f9(e),e])),i=e.filter(e=>!r.has(f9(e))).map(e=>({kind:`removed`,label:e.label})),a=t.flatMap(e=>{let t=n.get(f9(e));return t&&t.label!==e.label?[{kind:`changed`,label:e.label,before:t.label}]:[]}),o=t.filter(e=>!n.has(f9(e))).map(e=>({kind:`added`,label:e.label}));return[...i,...a,...o]},Sbe=(e,t,n,r)=>{let i=e-t;return i===0?`As many ${r}`:`${Math.abs(i)} ${i>0?`more`:`fewer`} ${Math.abs(i)===1?n:r}`},p9=12,m9={added:{word:`Added`,className:`text-success-text`},removed:{word:`Removed`,className:`text-danger-text`},changed:{word:`Changed`,className:`text-primary-text`}},Cbe=({changes:e})=>(0,V.jsx)(`ul`,{"aria-label":`Filter changes`,className:`divide-y rounded-md border`,children:e.map(e=>(0,V.jsxs)(`li`,{className:`grid grid-cols-[72px_1fr] gap-3 px-3 py-2`,children:[(0,V.jsx)(`span`,{className:`font-medium ${m9[e.kind].className}`,children:m9[e.kind].word}),e.kind===`changed`?(0,V.jsxs)(`span`,{children:[(0,V.jsx)(`span`,{className:`text-muted-foreground line-through`,children:e.before}),` `,(0,V.jsx)(`span`,{className:`font-medium`,children:e.label})]}):(0,V.jsx)(`span`,{className:e.kind===`removed`?`text-muted-foreground line-through`:`font-medium`,children:e.label})]},`${e.kind}:${e.label}`))}),h9=(e,t)=>{let n=mh({...UT(G(),e,t??``),enabled:t!==null});return t===null?0:n.data},wbe=(e,t,n)=>`${e} ${e===1?t:n}`,g9=({model:e,view:t,title:n,filter:r,total:i,plural:a})=>{let o=t?.list?.displays?.find(e=>e.kind===`cards`);return(0,V.jsxs)(`section`,{"aria-label":n,className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`h3`,{className:`font-semibold`,children:[n,` `,(0,V.jsxs)(`span`,{className:`font-normal text-muted-foreground`,children:[`(`,i??`…`,`)`]})]}),i!==void 0&&i>p9&&(0,V.jsxs)(`p`,{className:`text-xs text-muted-foreground`,children:[`The first `,p9,` of `,i,`.`]}),r===null||i===0?(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`No `,a,`.`]}):(0,V.jsx)(K5,{model:e,view:t,filter:r,sort:jS(e,t),limit:p9,display:o?.name??`table`,row:!0,link:!1,empty:`No ${a}.`})]})},Tbe=({model:e,view:t,title:n,before:r,after:i,saveNewLabel:a,updating:s,creating:c,onUpdate:l,onSaveNew:u,onCancel:d})=>{let f=xbe(_8(e,r),_8(e,i)),p=(0,o.useMemo)(()=>d9(r,i),[r,i]),m=(0,o.useMemo)(()=>bbe(r,i),[r,i]),h=h9(e,p),g=h9(e,m),_=(t?.names?.singular??K(e.name)).toLowerCase(),v=(t?.names?.plural??K(e.name)).toLowerCase(),y=h!==void 0&&g!==void 0;return(0,V.jsx)(dT,{open:!0,wide:!0,title:n,onClose:d,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:d,children:`Cancel`}),(0,V.jsx)(U,{loading:c,disabled:s,onClick:u,children:a}),(0,V.jsx)(U,{variant:`primary`,loading:s,disabled:c,onClick:l,children:`Update`})]}),children:(0,V.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[f.length>0&&(0,V.jsx)(Cbe,{changes:f}),y?(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`span`,{className:`font-semibold`,children:Sbe(h,g,_,v)}),(0,V.jsxs)(`span`,{className:`text-muted-foreground`,children:[`: `,wbe(h,_,v),` added, `,g,` removed`]})]}):(0,V.jsx)(cu,{className:`h-4 w-48`}),(0,V.jsx)(g9,{model:e,view:t,title:`Added`,filter:p,total:h,plural:v}),(0,V.jsx)(g9,{model:e,view:t,title:`Removed`,filter:m,total:g,plural:v})]})})},Ebe=()=>{let{address:e,set:t}=XS();return{key:e?.kind===`list`?e.savedSearch:void 0,open:e=>t({savedSearch:e})}},_9=e=>e instanceof Error?e.message:`Something went wrong`,Dbe=(e,t)=>{let n=J(),r=G(),i=Qy(),a=qT(),{href:o,open:s}=XS(),c=Ebe(),{resource:l}=e,u=n.resources[l],d=n.views[l]?.searchesOf,f=n.permissions[l],p=u!==void 0&&d!==void 0&&f!==void 0&&MT(f,`create`)&&MT(f,`delete`),m=n.signIn?.[l]?.signIn,h=J8(l,p),g=e=>Ao(zx(u,e)),_=d&&h.data?.find(e=>e[d.filter]===t),v=_||c.key===void 0||!f||!MT(f,`update`)?void 0:h.data?.find(e=>g(e)===c.key),y=n.views[l]?.names,b=y?.plural??`saved searches`,x=d?.name===void 0?void 0:u?.fields[d.name],S=hh({mutationFn:e=>r.create(l,{[d.filter]:t,...d.name&&{[d.name]:e}}),onSuccess:e=>{c.open(g(e.record)),i.show({state:`success`,title:`Search saved`,action:{label:`Open ${b.toLowerCase()}`,href:o({kind:`list`,resource:l}),onNavigate:s}})},onError:e=>i.show({state:`error`,title:`Could not save the search`,description:_9(e)}),onSettled:()=>a(l)}),C=hh({mutationFn:e=>r.remove(l,g(e)),onError:e=>i.show({state:`error`,title:`Could not take the search off`,description:_9(e)}),onSettled:()=>a(l)}),w=hh({mutationFn:e=>r.update(l,g(e),{[d.filter]:t},e.etag??`*`),onSuccess:()=>i.show({state:`success`,title:`Search updated`}),onError:e=>i.show({state:`error`,title:`Could not update the search`,description:_9(e)}),onSettled:()=>a(l)}),T=S.isPending||C.isPending||w.isPending;return{mode:p?`save`:m?`sign-in`:void 0,prompt:m,saved:_!==void 0,opened:v&&{filter:String(v[d.filter]??``),name:d.name&&typeof v[d.name]==`string`&&v[d.name]!==``?String(v[d.name]):void 0},noun:(y?.singular??K(l)).toLowerCase(),naming:x&&{label:n.views[l]?.fields[x.name]?.label??K(x.name),required:!x.nullable},ready:h.data!==void 0&&!T,updating:w.isPending,creating:S.isPending,remove:()=>_&&C.mutate(_),saveNew:(e,t)=>S.mutate(e,t),update:e=>v&&w.mutate(v,e)}},Obe=({model:e,view:t,search:n,filter:r,chips:i,className:a})=>{let s=Dbe(n,r),[c,l]=(0,o.useState)(!1),[u,d]=(0,o.useState)(!1),[f,p]=(0,o.useState)();if(!s.mode)return null;let m=n.label??`Save search`;if(s.mode===`sign-in`)return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{className:a,"aria-haspopup":`dialog`,onClick:()=>l(!0),children:[(0,V.jsx)(se,{className:`size-3.5`,"aria-hidden":!0}),m]}),(0,V.jsx)(C8,{as:`dialog`,prompt:s.prompt,open:c,onClose:()=>l(!1)})]});let h=e=>{d(!1),s.naming?p(e):s.saveNew(null)},g=f!==void 0&&s.naming&&(0,V.jsx)(a9,{title:f,chips:i,label:s.naming.label,required:s.naming.required,busy:s.creating,onSave:e=>s.saveNew(e,{onSuccess:()=>p(void 0)}),onClose:()=>p(void 0)}),_=s.opened;if(_){let n=`Save as new ${s.noun}`;return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{className:a,"aria-haspopup":`dialog`,"aria-disabled":!s.ready,onClick:()=>s.ready&&d(!0),children:[(0,V.jsx)(oee,{className:`size-3.5`,"aria-hidden":!0}),(0,V.jsx)(`span`,{className:`max-w-60 truncate`,children:_.name?`Update ${_.name}`:`Update ${s.noun}`})]}),(0,V.jsxs)(U,{className:a,"aria-haspopup":s.naming?`dialog`:void 0,"aria-disabled":!s.ready,onClick:()=>s.ready&&h(n),children:[(0,V.jsx)(ae,{className:`size-3.5`,"aria-hidden":!0}),n]}),u&&(0,V.jsx)(Tbe,{model:e,view:t,title:_.name?`Update ${_.name}?`:`Update this ${s.noun}?`,before:_.filter,after:r,saveNewLabel:n,updating:s.updating,creating:s.creating,onUpdate:()=>s.update({onSuccess:()=>d(!1)}),onSaveNew:()=>h(n),onCancel:()=>d(!1)}),g]})}let v=s.saved?ie:se;return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{className:a,"aria-pressed":s.saved,"aria-haspopup":!s.saved&&s.naming?`dialog`:void 0,"aria-disabled":!s.ready,onClick:()=>s.ready&&(s.saved?s.remove():h(m)),children:[(0,V.jsx)(v,{className:s.saved?`size-3.5 text-primary`:`size-3.5`,"aria-hidden":!0}),m]}),g]})},kbe=e=>e instanceof Error?e.message:`Something went wrong`,Abe=({model:e,view:t,name:n,value:r,onChange:i})=>{let a=(0,o.useId)(),s=e.fields[n],c=t.fields[n],l=c?.label??K(n);if(s?.type===`boolean`)return(0,V.jsx)(ox,{checked:r===!0,onChange:i,label:l});if(s?.type!==`enum`)throw Error(`Not implemented: "${n}" is ${s?.type??`unknown`}, and a saved search's controls are enums or booleans`);return(0,V.jsxs)(`label`,{htmlFor:a,className:`flex items-center gap-2 text-muted-foreground`,children:[l,(0,V.jsx)(`select`,{id:a,value:String(r??``),onChange:e=>i(e.target.value),className:`h-8 rounded-md border border-border-strong bg-background px-2 text-foreground shadow-sm focus:border-primary focus:outline-none focus:ring-2 focus:ring-primary/20`,children:(s.enumValues??[]).map(e=>(0,V.jsx)(`option`,{value:e,children:rs(e,c?.valueLabels)},e))})]})},jbe=(e,t,n)=>Object.entries(n).map(([n,r])=>`${t.fields[n]?.label??K(n)}: ${e.fields[n]?.type===`boolean`?r===!0?`On`:`Off`:rs(String(r),t.fields[n]?.valueLabels)}`).join(`, `),Mbe=({model:e,view:t,recordKey:n,title:r,row:i,fields:a})=>{let o=G(),s=Qy(),c=qT(),l=hh({mutationFn:t=>o.update(e.name,n,t,i.etag??`*`),onSuccess:(n,i)=>s.show({state:`success`,title:`${r} saved`,description:jbe(e,t,i)}),onError:e=>s.show({state:`error`,title:`Could not change the search`,description:kbe(e)}),onSettled:()=>c(e.name)});return(0,V.jsx)(`div`,{className:`flex flex-wrap items-center gap-3`,children:a.map(n=>(0,V.jsx)(Abe,{model:e,view:t,name:n,value:l.isPending&&n in(l.variables??{})?l.variables[n]:i[n],onChange:e=>l.mutate({[n]:e})},n))})},Nbe=e=>e instanceof Error?e.message:`Something went wrong`,Pbe=({model:e,view:t,of:n,target:r,targetView:i,row:a,recordKey:s,canRename:c,onDelete:l})=>{let u=G(),d=Qy(),f=qT(),[p,m]=(0,o.useState)(!1),{name:h,chips:g,title:_,body:v}=Y8({model:e,of:n,target:r,targetView:i,row:a,recordKey:s}),y=hh({mutationFn:t=>u.update(e.name,s,{[n.name]:t},a.etag??`*`),onSuccess:()=>m(!1),onError:e=>d.show({state:`error`,title:`Could not rename the search`,description:Nbe(e)}),onSettled:()=>f(e.name)}),b=n.name===void 0?void 0:e.fields[n.name];return(0,V.jsxs)(`section`,{"aria-label":_,className:`flex flex-col gap-3 rounded-lg border bg-surface p-4`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-start justify-between gap-3`,children:[(0,V.jsx)(`div`,{className:`flex min-w-0 flex-col gap-2`,children:(0,V.jsx)(`h2`,{className:`text-[16px] font-semibold`,children:(0,V.jsx)(ZS,{to:{kind:`record`,resource:e.name,key:s},className:`hover:underline`,children:h??(0,V.jsx)(N6,{chips:g})})})}),(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[n.controls&&(0,V.jsx)(Mbe,{model:e,view:t,recordKey:s,title:_,row:a,fields:n.controls}),c&&b&&(0,V.jsx)(U,{variant:`ghost`,"aria-label":`Rename ${_}`,"aria-haspopup":`dialog`,onClick:()=>m(!0),children:(0,V.jsx)(nn,{className:`size-3.5`,"aria-hidden":!0})}),l&&(0,V.jsx)(U,{variant:`ghost`,"aria-label":`Delete ${_}`,onClick:()=>l(_),children:(0,V.jsx)(zn,{className:`size-3.5`,"aria-hidden":!0})})]})]}),p&&b&&(0,V.jsx)(a9,{title:`Rename ${_}`,chips:g,label:t.fields[b.name]?.label??K(b.name),required:!b.nullable,initial:h,busy:y.isPending,onSave:e=>y.mutate(e),onClose:()=>m(!1)}),(0,V.jsx)(q8,{...v})]})},Fbe=({model:e,view:t})=>{let{resources:n,views:r}=J(),i=t.searchesOf,a=n[i.resource],o=r[i.resource],s=J8(e.name,!0),c=YS(e.name),l=t7({model:e,view:t}),u=t.names?.plural??K(e.name),d=e=>(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[l.dialogs,(0,V.jsx)(gd,{title:u,subtitle:t.help}),e]});if(!a)return d((0,V.jsxs)(KS,{title:`Not found`,children:[`There is no resource called `,i.resource,`.`]}));if(s.error)return d((0,V.jsx)(ax,{title:`Could not load your ${u.toLowerCase()}`,error:s.error}));if(!s.data)return d((0,V.jsx)(`div`,{className:`flex flex-col gap-3`,children:Array.from({length:2},(e,t)=>(0,V.jsx)(cu,{className:`h-56`},t))}));if(s.data.length===0){let e=(o?.names?.plural??K(a.name)).toLowerCase();return d((0,V.jsxs)(`p`,{className:`py-8 text-center text-muted-foreground`,children:[`No `,u.toLowerCase(),` yet. Filter the`,` `,(0,V.jsx)(ZS,{to:{kind:`list`,resource:a.name},className:`font-medium text-primary-text hover:underline`,children:e}),` `,`and save the search.`]}))}return d((0,V.jsx)(`div`,{className:`flex flex-col gap-4`,children:s.data.map(n=>{let r=Ao(zx(e,n)),s=MT(c,`delete`)?e=>void l.start({key:r,title:e,etag:n.etag,snapshot:n}):void 0;return(0,V.jsx)(Pbe,{model:e,view:t,of:i,target:a,targetView:o,row:n,recordKey:r,canRename:MT(c,`update`),onDelete:s},r)})}))},Ibe=({field:e,hints:t,resource:n,stored:r,onSave:i,close:a})=>{let[s,c]=(0,o.useState)(()=>Bb(e,r)),l=(0,o.useRef)(null),u=(0,o.useRef)(!1),d=!t?.widget&&(e.type===`boolean`||e.type===`enum`);(0,o.useEffect)(()=>{l.current?.querySelector(`input, select, textarea, button, [tabindex]`)?.focus()},[]);let f=(t,n,o=s)=>{u.current||(u.current=!0,t&&Vb(e,o,r)&&i(Rb(e,o)),a(n))};return(0,V.jsx)(`div`,{ref:l,className:`w-full min-w-0`,onKeyDown:e=>{e.key===`Enter`?(e.preventDefault(),f(!0)):e.key===`Tab`?(e.preventDefault(),f(!0,e.shiftKey?-1:1)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),f(!1))},onBlur:e=>{l.current?.contains(e.relatedTarget)||f(!0)},children:(0,V.jsx)(IC,{field:e,hints:t,value:s,stored:r,resource:n,onChange:e=>{c(e),d&&f(!0,void 0,e)}})})},Lbe=e=>{let t=G(),n=Gp(),r=Qy(),[i,a]=(0,o.useState)(new Map),s=(0,o.useRef)(i),c=(0,o.useRef)(new Map),l=(e,t)=>{s.current=new Map(s.current).set(e,{...s.current.get(e),...t}),a(s.current)},u=async(i,a,o)=>{let c=zx(e,i),u=String(s.current.get(i.id)?.etag??i.etag);try{let r=await t.update(e.name,c,{[a]:o},u);l(i.id,{[a]:r.record[a],etag:r.etag}),n.setQueryData(W.record(e.name,Ao(c)),r),n.invalidateQueries({queryKey:[`page`,e.name]}),n.invalidateQueries({queryKey:[`list`,e.name]}),n.invalidateQueries({queryKey:[`map`,e.name]})}catch(n){if(!Rs(n))throw l(i.id,{[a]:i[a]}),n;let o=n.status===412,s=o?await t.get(e.name,c):void 0;l(i.id,s?{[a]:s.record[a],etag:s.etag}:{[a]:i[a]});let u=n.errors.find(e=>e.field===a)?.message??n.message;r.show({state:`error`,title:o?`Changed by someone else`:`Could not save`,description:u})}};return{patches:i,save:(e,t,n)=>{l(e.id,{[t]:n});let r=(c.current.get(e.id)??Promise.resolve()).then(()=>u(e,t,n));return c.current.set(e.id,r.catch(()=>void 0)),r}}},Rbe=(e,t,n)=>{let r=Lbe(e),i=t?.list?.editable??[];return{editor:i.length>0&&MT(n,`update`)?{editable:(t,n)=>i.includes(n)&&e.fields[n]!==void 0&&Pb(e.fields[n])&&NT(t,`update`),render:(n,i,a)=>(0,V.jsx)(Ibe,{field:e.fields[i],hints:t?.fields[i],resource:e.name,stored:n[i],onSave:e=>void r.save(n,i,e),close:a})}:void 0,patches:r.patches}},v9=(e,t)=>{let n=e.position;if(!n||!MT(t,`update`))return;let r=e.fields[n.field];return r&&!r.readOnly?n.field:void 0},zbe=(e,t)=>e.position?.within===void 0?v9(e,t):void 0,Bbe=(e,t,n)=>t.position?.within!==void 0&&e.field===t.position.within&&!e.through&&!e.filter?v9(t,n):void 0,Vbe=({model:e,field:t,filter:n,fields:r})=>{let i=G(),a=Qy(),s=qT(),{resources:c,views:l}=J(),u=`${t} asc`,d=mh({queryKey:[...W.list(e.name,n,u,500,`hand-order`),r.join(`,`)],queryFn:async()=>{let t=u4(c,l,e,r),a=await i.search(e.name,{filter:n||void 0,orderBy:u,pageSize:500,labels:t});return{rows:d4(c,e,r,a.items,a.labels).map((t,n)=>({...t,id:Rx(e,a.items[n])})),more:!!a.nextPageToken}}}),[f,p]=(0,o.useState)(),m=(0,o.useRef)(void 0),h=(0,o.useRef)(Promise.resolve()),g=(0,o.useRef)(0),_=async()=>{let n=m.current;if(!n)return;let r=Object.fromEntries(n.flatMap(t=>typeof t.etag==`string`?[[Ao(zx(e,t)),t.etag]]:[])),a=(await i.batchWrite([{op:`reorder`,resource:e.name,field:t,keys:n.map(t=>zx(e,t)),etags:r}])).results[0];if(a?.op!==`reorder`||!m.current)return;let o=new Map(a.records.map(t=>[Rx(e,t.record),t]));m.current=m.current.map(e=>{let n=o.get(e.id);return n?{...e,[t]:n.record[t],etag:n.etag}:e})},v=e=>{m.current=void 0,p(void 0),a.show({state:`error`,title:`Could not change the order`,description:lS(e)})},y=async()=>{--g.current,!(g.current>0)&&(await s(e.name),!(g.current>0)&&(m.current=void 0,p(void 0)))};return{rows:f??d.data?.rows,more:d.data?.more??!1,loading:d.isPending,error:d.error,move:(e,t)=>{let n=m.current??d.data?.rows;n&&e!==t&&(m.current=Xv(n,e,t),p(m.current),g.current+=1,h.current=h.current.then(_).catch(v).then(y))}}},y9=({model:e,view:t,field:n,filter:r,columns:i})=>{let{resources:a,views:s}=J(),{fields:c}=SC(),{go:l,href:u}=XS(),d=(0,o.useMemo)(()=>H5(e,t,i,{resources:a,views:s,fieldTypes:c}).map(e=>({...e,sortable:!1})),[e,t,i.join(`,`),a,s,c]),f=Vbe({model:e,field:n,filter:r,fields:(0,o.useMemo)(()=>DS(e,t,d.map(e=>e.id)),[e,t,d])}),p=f.rows,m=(0,o.useMemo)(()=>p&&{total:p.length,rowAt:e=>p[e]},[p]),h=(t?.names?.plural??K(e.name)).toLowerCase();if(f.loading)return(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-4 w-full`},t))});if(f.error)return(0,V.jsx)(ax,{title:`Could not load`,error:f.error});if(f.more)return(0,V.jsxs)(`p`,{className:`text-muted-foreground`,children:[`There are more than `,500 .toLocaleString(`en-IE`),` `,h,`, too many to sort by hand.`]});if(!m||m.total===0)return(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Nothing here yet.`});let g=t=>l({kind:`record`,resource:e.name,key:zx(e,t)});return(0,V.jsx)(w6,{fit:!0,scroll:`parent`,columns:d,source:m,latencyMs:0,onOpenRow:g,rowLink:t=>({href:u({kind:`record`,resource:e.name,key:zx(e,t)}),onFollow:()=>g(t)}),rowNumbers:!1,reorder:{label:n=>Ix(e,t,n,n.id),onMove:f.move}})},b9=({sorting:e,onChange:t,size:n,iconOnly:r=!1})=>{let i=e?`Done`:`Sort`;return(0,V.jsxs)(U,{size:n,variant:e?`primary`:`secondary`,onClick:()=>t(!e),...r&&{"aria-label":i,title:i},children:[e?(0,V.jsx)(ge,{className:`size-3.5`}):(0,V.jsx)(E,{className:`size-3.5`}),!r&&i]})},Hbe=co(),Ube=e=>e.find(e=>e.kind===`search`),Wbe=({address:e})=>{let{resources:t,views:n,signIn:r}=J(),i=t[e.resource],a=r?.[e.resource];if(!i)return a?(0,V.jsx)(C8,{as:`page`,prompt:a.signIn}):(0,V.jsxs)(KS,{title:`Not found`,children:[`There is no resource called `,e.resource,`.`]});let o=n[e.resource];if(o?.searchesOf)return(0,V.jsx)(Fbe,{model:i,view:o});let s=PS(t,n,e.resource);if(o&&s.listOf){let t=s.model;return(0,V.jsx)(vbe,{model:i,view:o,target:t,children:n=>(0,V.jsx)(x9,{model:t,address:e,scope:n,heading:{title:o.names?.plural??K(i.name),subtitle:o.help}})})}return(0,V.jsx)(x9,{model:i,address:e})},x9=({model:e,address:t,scope:n,heading:r})=>{let i=J(),{set:a,listTo:s,go:c,href:l}=XS(),u=e.name,d=i.views[u],f=(0,o.useMemo)(()=>f8(d,e),[d,e]),{fields:p}=SC(),m=(0,o.useMemo)(()=>_be(B5(Qx(e,d),e,d,p),e,d,i.resources,i.views),[e,d,p,i.resources,i.views]),h=t.filter,g=(0,o.useMemo)(()=>u8(f,h),[f,h]),_=g.ok?g.state:I6,v=g.ok?g.extras:[],{orderBy:y,filterLayout:b}=t,x=Kl(),S=ql(),[C,w]=(0,o.useState)(!1),T=n?[...v,n]:v,E=Tve({model:e,resources:i.resources,views:i.views,view:d,state:_,extras:T}),D=n?a8(f,_,T):g.ok?h:``,O=(0,o.useMemo)(()=>DS(e,d,m.map(e=>e.id)),[e,d,m]),k=(0,o.useMemo)(()=>Age(d,i.resources,i.views,O),[d,i.resources,i.views,O]),A=k6({resources:i.resources,views:i.views,model:e,columns:O,filter:D,orderBy:y,related:k}),j=gS(e,d,t.display),M=YS(u),N=n?void 0:zbe(e,M),[ee,P]=(0,o.useState)(!1),te=ee&&N!==void 0,F=te||j?.kind!==`map`;iu(F);let ne=$8(e,A.page,A.key,j?.kind===`custom`),re=lbe(),ie=Fx(e,d),I=e=>({key:e.id,title:String(typeof e[ie]==`object`?e[ie].name:e[ie]??e.id),etag:typeof e.etag==`string`?e.etag:void 0,snapshot:e}),ae=d?.names?.singular??K(u),oe=Rbe(e,d,M),{state:se}=H(),L=t7({model:e,view:d,restore:n7(e),onReview:e=>c({kind:`record`,resource:u,key:e.key})}),ce=(e,t=v)=>a({filter:a8(f,e,t)}),le=Ube(v),ue=e=>{let t=v.filter(e=>e.kind!==`search`);ce(_,e?[...t,Hbe.search(e)]:t)},de=d?.names?.plural??K(u),fe=j?.kind===`calendar`?void 0:j,pe=fe&&(0,V.jsx)(z5,{model:e,view:d,display:fe,orderBy:y,onChange:e=>a({orderBy:e})}),me=e.search?.length?(0,V.jsx)(gbe,{value:le?.kind===`search`?le.text:``,onCommit:ue,placeholder:`Search ${de.toLowerCase()}`,className:x?void 0:`min-h-11`}):null,he=(0,V.jsx)(Z6,{layout:b,config:E,value:_,onChange:ce,leading:b===`bar`?pe:void 0,trailing:me}),ge=b===`bar`?he:(0,V.jsx)(X6,{groups:[pe?[pe]:[]],trailing:me}),_e=V6(E,_),ve=(0,V.jsx)(P6,{scroll:!0,chips:_e,onRemove:e=>ce(H6(_,e)),onClear:()=>ce(I6)}),ye=fe&&(0,V.jsx)(G6,{title:`Sort`,children:(0,V.jsx)(z5,{model:e,view:d,display:fe,orderBy:y,onChange:e=>a({orderBy:e}),className:`min-h-11 w-full`})}),be=(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,V.jsxs)(U,{className:`min-h-11`,onClick:()=>w(!0),"aria-haspopup":`dialog`,children:[(0,V.jsx)(Cn,{className:`size-3.5`}),`Filters`,_e.length>0&&` (${_e.length})`]}),me??(0,V.jsx)(`div`,{className:`min-w-0 flex-1`,children:ve})]}),me&&ve,(0,V.jsx)(uT,{title:`Filters`,open:C,onClose:()=>w(!1),children:(0,V.jsx)(Z6,{layout:`panel`,fullWidth:!0,config:E,value:_,onChange:ce,leading:ye})})]}),xe=!n&&r7(d,i.pages,M)&&(0,V.jsxs)(ZS,{to:{kind:`create`,resource:u},className:Cf({variant:`primary`}),children:[(0,V.jsx)(an,{className:`size-3.5`}),`New `,ae.toLowerCase()]}),Se=d?.saveSearch&&!n&&g.ok&&h&&(0,V.jsx)(Obe,{model:e,view:d,search:d.saveSearch,filter:h,chips:g8(e,d,h,_ge(E))}),Ce=!n&&(0,V.jsx)(Cye,{model:e}),we=qye({model:e,view:d,resources:i.resources,views:i.views,plural:de,filter:D,orderBy:y}),Te=G7(d)&&(0,V.jsxs)(U,{onClick:()=>we.open(),...!x&&{"aria-label":`Export`,title:`Export`},children:[(0,V.jsx)(We,{className:`size-3.5`}),x&&`Export`]}),Ee=N&&(0,V.jsx)(b9,{sorting:te,onChange:P,iconOnly:!x}),De=t=>!te&&(0,V.jsx)(R5,{view:d,choices:bS(e,d,S),value:j?.name??`table`,onChange:e=>a({display:e}),menu:t}),Oe=v8(e),ke=t=>{Oe(AS(e,t).record),c({kind:`record`,resource:u,key:zx(e,t)})},Ae=A.source?(0,V.jsx)(w6,{columns:m,source:A.source,sort:MS(y),onSortChange:e=>a({orderBy:NS(e)}),onOpenRow:ke,rowLink:t=>({href:l({kind:`record`,resource:u,key:zx(e,t)}),onFollow:()=>ke(t)}),cellEditor:oe.editor,rowPatches:oe.patches,initialScrollIndex:re.initialIndex,onScrollIndex:re.remember,rowActions:[{label:`Open ${ae.toLowerCase()}`,onSelect:ke},...MT(M,`delete`)?[{label:`Delete`,destructive:!0,available:e=>NT(e,`delete`),onSelect:e=>void L.start(I(e))}]:[]],bulkActions:[...G7(d)&&Y7(e)?[{label:e=>`Export ${e}`,onRun:e=>we.open(e)}]:[],...MT(M,`delete`)?[{label:e=>`Delete ${e}`,destructive:!0,onRun:e=>L.startBulk(e.map(I))}]:[]],rowNumbers:!1,pinKey:se.kind===`signed-in`?she(se.user.id,u):void 0,scroll:`parent`,className:`flex-1`}):(0,V.jsx)(`div`,{className:`flex-1 rounded-lg border bg-surface`}),je={...A,initialIndex:re.initialIndex,onScrollIndex:re.remember},Me=Yye({plural:de,search:le?.kind===`search`?le.text:``,filtered:_e.length>0,scoped:!!n||v.some(e=>e.kind!==`search`),canCreate:!!xe}),Ne=(0,V.jsx)(Jye,{state:Me,onClearSearch:()=>ue(``),onClearFilters:()=>ce(I6),create:xe}),Pe=te?(0,V.jsxs)(`div`,{className:`flex flex-col gap-3`,children:[(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`Drag a row by its handle to move it. Every move is saved as you drop it.`}),(0,V.jsx)(y9,{model:e,view:d,field:N,filter:``,columns:Zx(e,d)})]}):j?j.kind===`cards`?(0,V.jsx)(cbe,{model:e,view:d,display:j,list:je,empty:Ne},A.key.join(` `)):j.kind===`map`?(0,V.jsx)(F5,{model:e,view:d,display:j,filter:D,orderBy:y,fields:O,at:t.map,onMove:e=>a({map:e}),flush:!0}):j.kind===`board`?(0,V.jsx)(e5,{model:e,view:d,display:j,fields:O,filter:D,orderBy:y}):j.kind===`calendar`?(0,V.jsx)(_5,{model:e,view:d,display:j,fields:O,filter:D,at:t.calendar,linkTo:e=>s({calendar:e})}):(0,V.jsx)(b5,{display:j,list:ne}):A.source?.total===0&&!A.error?Ne:Ae;return(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 flex-col gap-3 px-5 py-4`,children:[L.dialogs,we.dialogs,(0,V.jsx)(gd,{title:r?.title??de,subtitle:r?r.subtitle:d?.help,aside:!x&&De(!0),actions:x?(0,V.jsxs)(V.Fragment,{children:[De(!1),Ee,Se,Ce,Te,xe]}):(0,V.jsxs)(V.Fragment,{children:[Ee,Se,Ce,Te,xe]})}),!g.ok&&(0,V.jsx)(ax,{title:`The filter in the address could not be read`,error:Error(g.errors.map(e=>e.message).join(`; `))}),A.error&&!j&&!te&&(0,V.jsx)(ax,{title:`Could not load rows`,error:A.error}),d?.chart&&!te&&(Do(d.chart)?(0,V.jsx)(hbe,{model:e,view:d,chart:d.chart,plural:de,filter:D}):(0,V.jsx)(mbe,{resource:u,chart:d.chart,title:`${de} created`,noun:de.toLowerCase(),filter:D})),!te&&(x?ge:be),x&&b===`panel`&&!te?(0,V.jsxs)(`div`,{className:`flex min-h-0 flex-1 gap-4`,children:[(0,V.jsx)(`div`,{className:F?`sticky top-[calc(var(--pb-sticky-top,0px)+1rem)] flex max-h-[calc(100dvh-var(--pb-sticky-top,0px)-var(--pb-sticky-bottom,0px)-2rem)] shrink-0 self-start`:`flex shrink-0`,children:he}),Pe]}):Pe]})},S9=({roles:e,selected:t,grantable:n,disabled:r,onChange:i})=>(0,V.jsx)(`div`,{className:`flex flex-wrap gap-x-4 gap-y-2`,children:e.filter(e=>e.membership).map(e=>{let a=t.includes(e.name),o=r||!n.has(e.name);return(0,V.jsxs)(`label`,{title:o&&!r?`You cannot give or take away this role`:void 0,className:B(`inline-flex items-center gap-1.5`,o&&`text-muted-foreground`),children:[(0,V.jsx)(Fh,{checked:a,label:e.label,onChange:o?void 0:n=>i(n?[...t,e.name]:t.filter(t=>t!==e.name)),className:B(o&&`cursor-default opacity-60`)}),e.label]},e.name)})}),C9=e=>e?.role===`owner`?[`owner`,`admin`,`member`]:[`admin`,`member`],Gbe=({member:e,current:t,onChanged:n})=>{let{session:r,organizations:i}=H(),a=t.organization.id,{busy:o,error:s,run:c}=Gh(),l=i?.roles??[],u=e.id===t.memberId,d=C9(t),f=e.role===`owner`&&t.role!==`owner`;return(0,V.jsxs)(`li`,{className:`flex flex-col gap-2 px-3 py-3`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsxs)(`span`,{className:`block truncate font-medium`,children:[e.name,u&&` (you)`]}),(0,V.jsx)(`span`,{className:`block truncate text-xs text-muted-foreground`,children:e.email})]}),(0,V.jsx)(`select`,{"aria-label":`Organization role of ${e.name}`,value:e.role,disabled:o||f,onChange:t=>void c(async()=>{await r.organizations.setRole(a,e.id,t.target.value),n()}),className:`h-7 rounded-md border border-border-strong bg-background px-2 text-xs`,children:(f?[e.role]:d).map(e=>(0,V.jsx)(`option`,{value:e,children:Vh[e]},e))}),!u&&(0,V.jsx)(U,{size:`sm`,variant:`danger`,loading:o,disabled:f,onClick:()=>void c(async()=>{await r.organizations.removeMember(a,e.id),n()}),children:`Remove`})]}),(0,V.jsx)(S9,{roles:l,selected:e.appRoles,grantable:Wh(l,t),disabled:o,onChange:t=>void c(async()=>{await r.organizations.setAppRoles(e.id,t),n()})}),(0,V.jsx)(Ef,{message:s})]})},Kbe=({current:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)(),s=e?.organization?.id,c=(0,o.useCallback)(()=>{s&&t.organizations.members(s).then(r,e=>a(e instanceof pc?xd(e):`Could not read the members`))},[t,s]);return(0,o.useEffect)(c,[c]),e?.organization?(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:`Members`,subtitle:`Who works in ${e.organization.name}, and with which roles.`}),(0,V.jsxs)(Tf,{title:`Members`,description:`Owners and admins manage the organization; app roles decide what each member sees and does in the app.`,children:[(0,V.jsx)(Ef,{message:i}),n?(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(t=>(0,V.jsx)(Gbe,{member:t,current:e,onChanged:c},`${t.id}/${t.role}/${t.appRoles.join()}`))}):!i&&(0,V.jsxs)(`div`,{className:`flex items-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})]})]}):null},w9=({link:e})=>e?(0,V.jsxs)(`p`,{className:`mt-3 break-all rounded-md border bg-muted px-3 py-2 text-xs`,children:[`This app cannot send email, so pass this link on yourself. It works once, until the invitation expires: `,(0,V.jsx)(`span`,{className:`font-mono`,children:e})]}):null,qbe=({current:e,onSent:t})=>{let{session:n,organizations:r}=H(),i=r?.roles??[],[a,s]=(0,o.useState)(``),[c,l]=(0,o.useState)(`member`),[u,d]=(0,o.useState)([]),[f,p]=(0,o.useState)(),{busy:m,error:h,run:g}=Gh(),_=()=>g(async()=>{let r=await n.organizations.invite(e.organization.id,{email:a.trim(),role:c,appRoles:u});p(r.link),s(``),d([]),t()});return(0,V.jsxs)(Tf,{title:`Invite someone`,description:`They get an email with a link to join, or to make an account first. You can give the app roles you hold, and those your roles grant.`,children:[(0,V.jsx)(Ef,{message:h}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-3`,onSubmit:e=>{e.preventDefault(),_()},children:[(0,V.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row`,children:[(0,V.jsx)(sd,{"aria-label":`Email`,type:`email`,placeholder:`name@example.com`,value:a,onChange:e=>s(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(`select`,{"aria-label":`Organization role`,value:c,onChange:e=>l(e.target.value),className:`h-8 rounded-md border border-border-strong bg-background px-2`,children:C9(e).map(e=>(0,V.jsx)(`option`,{value:e,children:Vh[e]},e))}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:m,disabled:!a.trim(),children:`Invite`})]}),(0,V.jsx)(S9,{roles:i,selected:u,grantable:Wh(i,e),onChange:d})]}),(0,V.jsx)(w9,{link:f})]})},Jbe=({invitation:e,organizationId:t,onChanged:n})=>{let{session:r,organizations:i}=H(),[a,s]=(0,o.useState)(),{busy:c,error:l,run:u}=Gh(),d=new Date(e.expiresAt).getTime()<Date.now();return(0,V.jsxs)(`li`,{className:`px-3 py-2.5`,children:[(0,V.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2`,children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.email}),(0,V.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[Vh[e.role],e.appRoles.length>0&&` · ${e.appRoles.map(e=>Hh(i?.roles??[],e)).join(`, `)}`,` · `,d?`Expired`:`Until ${new Date(e.expiresAt).toLocaleDateString()}`]})]}),(0,V.jsx)(U,{size:`sm`,loading:c,onClick:()=>void u(async()=>{s((await r.organizations.resend(t,e)).link),n()}),children:`Send again`}),(0,V.jsx)(U,{size:`sm`,variant:`danger`,loading:c,onClick:()=>void u(async()=>{await r.organizations.revoke(e.id),n()}),children:`Revoke`})]}),(0,V.jsx)(Ef,{message:l}),(0,V.jsx)(w9,{link:a})]})},Ybe=({current:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)([]),i=e?.organization?.id,a=(0,o.useCallback)(()=>{i&&t.organizations.invitations(i).then(e=>r(e.filter(e=>e.status===`pending`)),()=>r([]))},[t,i]);return(0,o.useEffect)(a,[a]),!e?.organization||!i?null:(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:`Invitations`,subtitle:`People invited to ${e.organization.name}.`}),(0,V.jsx)(qbe,{current:e,onSent:a}),(0,V.jsx)(Tf,{title:`Not accepted yet`,description:n.length>0?`Sending again gives a new link, which replaces the earlier one.`:`Nobody is waiting.`,children:n.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(e=>(0,V.jsx)(Jbe,{invitation:e,organizationId:i,onChanged:a},e.id))})})]})},Xbe=e=>{let{session:t}=H(),[n,r]=(0,o.useState)(),[i,a]=(0,o.useState)([]),[s,c]=(0,o.useState)(),[l,u]=(0,o.useState)(0),d=(0,o.useCallback)(()=>u(e=>e+1),[]);return(0,o.useEffect)(()=>{e&&Promise.all([t.organizations.current(),t.organizations.list()]).then(([e,t])=>{r(e),a(t)},e=>c(e instanceof pc?xd(e):`Could not read your organizations`))},[e,t,l]),{current:n,organizations:i,...s&&{error:s},reload:d}},T9=e=>window.location.assign(`${e}/`),Zbe=({organization:e,editable:t,onSaved:n})=>{let{session:r}=H(),[i,a]=(0,o.useState)(e.name),[s,c]=(0,o.useState)(e.slug),{busy:l,error:u,run:d}=Gh(),f=i.trim()!==e.name||s!==e.slug;return(0,V.jsxs)(Tf,{title:`Details`,description:t?`The name people see, and the slug that names it in links.`:`Owners and admins can change these.`,children:[(0,V.jsx)(Ef,{message:u}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-2 sm:flex-row`,onSubmit:t=>{t.preventDefault(),d(async()=>{await r.organizations.rename(e.id,{name:i.trim(),slug:s}),n()})},children:[(0,V.jsx)(sd,{"aria-label":`Name`,value:i,disabled:!t,onChange:e=>a(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(sd,{"aria-label":`Slug`,value:s,disabled:!t,onChange:e=>c(e.target.value),wrapperClassName:`sm:w-48`}),t&&(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:l,disabled:!f||!i.trim(),children:`Save`})]})]})},Qbe=({organization:e,memberId:t})=>{let{session:n}=H(),[r,i]=(0,o.useState)([]),[a,s]=(0,o.useState)(``),{busy:c,error:l,run:u}=Gh();return(0,o.useEffect)(()=>{n.organizations.members(e.id).then(e=>i(e.filter(e=>e.id!==t)),()=>i([]))},[n,e.id,t]),(0,V.jsxs)(Tf,{title:`Hand over`,description:`Make another member the owner. You stay as an admin.`,children:[(0,V.jsx)(Ef,{message:l}),(0,V.jsxs)(`div`,{className:`flex flex-col gap-2 sm:flex-row`,children:[(0,V.jsxs)(`select`,{"aria-label":`New owner`,value:a,onChange:e=>s(e.target.value),className:`h-8 flex-1 rounded-md border border-border-strong bg-background px-2`,children:[(0,V.jsx)(`option`,{value:``,children:`Choose a member`}),r.map(e=>(0,V.jsxs)(`option`,{value:e.id,children:[e.name,` (`,e.email,`)`]},e.id))]}),(0,V.jsx)(U,{loading:c,disabled:!a,onClick:()=>void u(async()=>{await n.organizations.transferOwnership(a),window.location.reload()}),children:`Hand over`})]})]})},$be=({organization:e,basePath:t})=>{let{session:n}=H(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(``),{busy:c,error:l,run:u}=Gh(),d=()=>u(async()=>{await n.organizations.remove(e.id),T9(t)});return(0,V.jsxs)(Tf,{title:`Delete organization`,description:`Takes the organization and its members and invitations away. Its records must be deleted first.`,children:[(0,V.jsx)(Ef,{message:r?void 0:l}),(0,V.jsx)(U,{variant:`danger`,onClick:()=>i(!0),children:`Delete organization`}),r&&(0,V.jsxs)(wf,{title:`Delete ${e.name}?`,description:`Type its name to confirm. This cannot be undone.`,onClose:()=>i(!1),actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:()=>i(!1),children:`Cancel`}),(0,V.jsx)(U,{variant:`danger`,loading:c,disabled:a!==e.name,onClick:()=>void d(),children:`Delete`})]}),children:[(0,V.jsx)(Ef,{message:l}),(0,V.jsx)(sd,{"aria-label":`Organization name`,value:a,onChange:e=>s(e.target.value)})]})]})},exe=({organization:e,basePath:t,owner:n})=>{let{session:r}=H(),{busy:i,error:a,run:o}=Gh();return(0,V.jsxs)(Tf,{title:`Leave`,description:n?`An organization keeps an owner: hand it over before you leave, unless it has another owner.`:`You stop being a member, and lose your roles here.`,children:[(0,V.jsx)(Ef,{message:a}),(0,V.jsxs)(U,{loading:i,onClick:()=>void o(async()=>{await r.organizations.leave(e.id),T9(t)}),children:[`Leave `,e.name]})]})},txe=({current:e,basePath:t,onChanged:n})=>{let r=e?.organization;if(!r)return(0,V.jsx)(`div`,{className:`mx-auto w-full max-w-3xl px-4 py-6 md:px-6`,children:(0,V.jsx)(gd,{title:`Organization`,subtitle:`You do not work in an organization now. Choose one under Organizations.`})});let i=e.role===`owner`;return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:r.name,subtitle:e.role?`You are ${Vh[e.role].toLowerCase()} here.`:`You work here through your global roles, without being a member.`}),(0,V.jsx)(Zbe,{organization:r,editable:Uh(e),onSaved:n},`${r.name}/${r.slug}`),i&&e.memberId&&(0,V.jsx)(Qbe,{organization:r,memberId:e.memberId}),e.role&&(0,V.jsx)(exe,{organization:r,basePath:t,owner:i}),i&&(0,V.jsx)($be,{organization:r,basePath:t})]})},E9=e=>e.normalize(`NFKD`).replace(/[̀-ͯ]/g,``).toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,63),D9=({organization:e,current:t,busy:n,onOpen:r})=>(0,V.jsxs)(`li`,{className:`flex items-center gap-3 px-3 py-2.5`,children:[(0,V.jsxs)(`span`,{className:`min-w-0 flex-1`,children:[(0,V.jsx)(`span`,{className:`block truncate font-medium`,children:e.name}),(0,V.jsx)(`span`,{className:`block text-xs text-muted-foreground`,children:e.slug})]}),t?(0,V.jsx)(Au,{tone:`green`,children:`Current`}):(0,V.jsx)(U,{size:`sm`,loading:n,onClick:r,children:`Open`})]}),nxe=({basePath:e})=>{let{session:t}=H(),[n,r]=(0,o.useState)(``),[i,a]=(0,o.useState)(),{busy:s,error:c,run:l}=Gh(),u=()=>l(async()=>{await t.organizations.create({name:n.trim(),slug:i??E9(n)}),T9(e)});return(0,V.jsxs)(Tf,{title:`New organization`,description:`You become its owner, with every role, and work in it once it is made.`,children:[(0,V.jsx)(Ef,{message:c}),(0,V.jsxs)(`form`,{className:`flex flex-col gap-2 sm:flex-row`,onSubmit:e=>{e.preventDefault(),u()},children:[(0,V.jsx)(sd,{"aria-label":`Name`,placeholder:`Name`,value:n,onChange:e=>r(e.target.value),wrapperClassName:`flex-1`}),(0,V.jsx)(sd,{"aria-label":`Slug`,placeholder:`slug`,value:i??E9(n),onChange:e=>a(e.target.value),wrapperClassName:`sm:w-48`}),(0,V.jsx)(U,{type:`submit`,variant:`primary`,loading:s,disabled:!n.trim(),children:`Create`})]})]})},rxe=({basePath:e,currentId:t})=>{let{session:n}=H(),[r,i]=(0,o.useState)(``),[a,s]=(0,o.useState)([]),{busy:c,error:l,run:u}=Gh();return(0,o.useEffect)(()=>{let e=setTimeout(()=>void n.organizations.search(r).then(s,()=>s([])),200);return()=>clearTimeout(e)},[n,r]),(0,V.jsxs)(Tf,{title:`Find an organization`,description:`Your global roles let you work in any organization, with what those roles allow there. Opening one you are not a member of is written to the audit log.`,children:[(0,V.jsx)(Ef,{message:l}),(0,V.jsx)(sd,{"aria-label":`Find an organization`,placeholder:`Name or slug`,value:r,onChange:e=>i(e.target.value),leading:(0,V.jsx)(pn,{className:`size-3.5`}),wrapperClassName:`mb-3`}),a.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:a.map(r=>(0,V.jsx)(D9,{organization:r,current:r.id===t,busy:c,onOpen:()=>void u(async()=>{await n.organizations.switchTo(r.id),T9(e)})},r.id))})]})},ixe=()=>{let{session:e,organizations:t}=H(),[n,r]=(0,o.useState)([]);if((0,o.useEffect)(()=>{e.organizations.myInvitations().then(r,()=>r([]))},[e]),n.length===0)return null;let i=t?.roles??[];return(0,V.jsx)(Tf,{title:`Invitations for you`,description:`Open the link in the invitation email to accept one.`,children:(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:n.map(e=>(0,V.jsxs)(`li`,{className:`px-3 py-2.5`,children:[(0,V.jsx)(`span`,{className:`font-medium`,children:e.organizationName??`An organization`}),`: `,e.appRoles.map(e=>Hh(i,e)).join(`, `)||`no app roles`,(0,V.jsxs)(`span`,{className:`block text-xs text-muted-foreground`,children:[`Until `,new Date(e.expiresAt).toLocaleDateString()]})]},e.id))})})},axe=({state:e,basePath:t})=>{let{session:n,organizations:r,state:i}=H(),{busy:a,error:o,run:s}=Gh(),c=i.kind===`signed-in`?i.user:void 0,l=r?.create===`everyone`||c!==void 0&&bg(c),u=e.current?.organization?.id;return(0,V.jsxs)(`div`,{className:`mx-auto flex w-full max-w-3xl flex-col gap-4 px-4 py-6 md:px-6`,children:[(0,V.jsx)(gd,{title:`Organizations`,subtitle:`You work in one organization at a time; what you see follows from your roles there.`}),(0,V.jsxs)(Tf,{title:`Your organizations`,description:e.organizations.length>0?`The organizations you are a member of.`:`You are not a member of an organization yet.`,children:[(0,V.jsx)(Ef,{message:o??e.error}),e.organizations.length>0&&(0,V.jsx)(`ul`,{className:`divide-y rounded-md border`,children:e.organizations.map(e=>(0,V.jsx)(D9,{organization:e,current:e.id===u,busy:a,onOpen:()=>void s(async()=>{await n.organizations.switchTo(e.id),T9(t)})},e.id))})]}),(0,V.jsx)(ixe,{}),l&&(0,V.jsx)(nxe,{basePath:t}),(e.current?.globalRoles.length??0)>0&&(0,V.jsx)(rxe,{basePath:t,currentId:u})]})},oxe=(e,t)=>t?.active?{...e,role:t.active}:e,O9=(e,t)=>e instanceof pc?xd(e):t,sxe=(e,t=!0)=>{let{session:n}=H(),r=Qy(),[i,a]=(0,o.useState)();(0,o.useEffect)(()=>{t&&n.roles.current().then(a,e=>r.show({state:`error`,title:O9(e,`Could not read your roles`)}))},[n,r,t]);let s=(0,o.useCallback)(t=>void n.roles.switchTo(t).then(e,e=>r.show({state:`error`,title:O9(e,`Could not switch the role`)})),[n,r,e]);return{...i&&{current:i},switchTo:s}},k9=e=>new Set((e.userMenu?.items??[]).flatMap(e=>e.kind===`resource`?[e.resource]:e.kind===`page`?[e.page]:[])),cxe=(e,t,n)=>(e.userMenu?.items??[]).map((r,i)=>{if(r.kind===`link`)return{id:`link-${i}`,label:r.label,icon:oT(r.icon,Qe),href:r.href,external:!0};if(r.kind===`page`){let i=e.pages[r.page];return{id:r.page,label:r.label??i?.title??K(r.page),icon:oT(r.icon??i?.icon,xt),href:ps({kind:`page`,page:r.page},t),active:r.page===n}}return{id:r.resource,label:r.label??e.views[r.resource]?.names?.plural??K(r.resource),icon:oT(r.icon,iT(r.resource)),href:ps({kind:`list`,resource:r.resource},t),active:r.resource===n}}),lxe={sales:`Sales`,crm:`CRM`,catalog:`Catalog`,inventory:`Inventory`,core:`Admin`,hr:`HR`},A9=(e,t=``,n={})=>{let r=new Map,i=new Map,a=k9(e);for(let n of Object.values(e.pages)){if(n.nav?.hidden||a.has(n.name))continue;let e=n.nav?.group??`Pages`,o=r.get(e)??{label:e,items:[]};o.items.push({id:n.name,label:n.title,icon:oT(n.icon,xt),href:ps({kind:`page`,page:n.name},t)}),r.set(e,o),i.set(n.name,n.nav?.order??2**53-1)}for(let o of Object.values(e.resources)){let s=e.views[o.name];if(!s||s.nav?.hidden||a.has(o.name))continue;let c=o.table.schema??`public`,l=s.nav?.group??lxe[c]??K(c),u=r.get(l)??{label:l,items:[]};u.items.push({id:o.name,label:s.names?.plural??K(o.name),icon:iT(o.name),href:ps({kind:`list`,resource:o.name},t),...n[o.name]&&{recent:n[o.name]}}),r.set(l,u),i.set(o.name,s.nav?.order??2**53-1)}for(let n of Object.values(e.signIn??{})){if(n.nav?.hidden||a.has(n.resource))continue;let e=n.nav?.group??`Account`,o=r.get(e)??{label:e,items:[]};o.items.push({id:n.resource,label:n.names?.plural??K(n.resource),icon:iT(n.resource),href:ps({kind:`list`,resource:n.resource},t)}),r.set(e,o),i.set(n.resource,n.nav?.order??2**53-1)}for(let n of e.sources??[]){if(n.state!==`error`)continue;let e=r.get(n.source.label)??{label:n.source.label,items:[]};for(let r of n.source.resources)e.items.push({id:r,label:K(r),icon:iT(r),href:ps({kind:`list`,resource:r},t),problem:`Cannot reach ${n.source.label}`});r.set(n.source.label,e)}return[...r.values()].map(e=>({...e,items:[...e.items].sort((e,t)=>(i.get(e.id)??0)-(i.get(t.id)??0))}))},uxe=e=>{let t=SC().shell?.logo;return t?(0,V.jsx)(Qh,{name:`shell.logo`,fallback:(0,V.jsx)(vu,{...e}),children:(0,V.jsx)(t,{...e})}):(0,V.jsx)(vu,{...e})},j9=(0,o.createContext)([]),dxe=()=>(0,o.useContext)(j9),fxe=({ui:e,children:t})=>{let{plugins:n=[]}=J(),{loads:r,settled:i}=hg(n,pg()),a=(0,o.useMemo)(()=>ag(e,r),[e,r]);return i?(0,V.jsx)(xC.Provider,{value:a.ui,children:(0,V.jsx)(j9.Provider,{value:a.off,children:t})}):(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading`]})},pxe=({off:e})=>{let[t,n]=(0,o.useState)(!1);return t||e.length===0?null:(0,V.jsxs)(`div`,{role:`region`,"aria-label":`Plugins off`,className:`flex items-start gap-3 border-b border-warning/40 bg-warning-soft px-4 py-2 text-warning-text`,children:[(0,V.jsx)(sn,{"aria-hidden":!0,className:`mt-0.5 size-4 shrink-0`}),(0,V.jsx)(`ul`,{className:`min-w-0 flex-1 space-y-0.5 break-words`,children:e.map(e=>(0,V.jsxs)(`li`,{children:[`The plugin `,(0,V.jsx)(`span`,{className:`font-semibold`,children:e.name??e.url}),` is off: `,e.reason,`.`]},e.url))}),(0,V.jsx)(`button`,{type:`button`,"aria-label":`Dismiss`,className:`rounded p-0.5 hover:bg-warning/10`,onClick:()=>n(!0),children:(0,V.jsx)($n,{"aria-hidden":!0,className:`size-4`})})]})},M9=(e,t)=>[`${t}_at`,`${t}At`].find(t=>e.fields[t]),N9=({item:e,scope:t})=>{let{components:n}=SC(),r=n?.[e.component],i=r?(0,V.jsx)(AT,{value:t,children:(0,V.jsx)(Qh,{name:e.component,children:(0,V.jsx)(r,{...bo(e.props??{})})})}):(0,V.jsxs)(Zh,{children:[`No component is registered as `,e.component,`. Export it from protobase.ui.tsx, or load the plugin that provides it.`]});return e.sidebar?e.title?(0,V.jsx)(ab,{title:e.title,children:i}):i:e.title?(0,V.jsx)(tb,{title:e.title,children:i}):(0,V.jsx)(`section`,{className:`py-8`,children:i})},mxe=(0,o.lazy)(()=>qh(()=>import(`./record-map-DvgWFyLn.js`).then(e=>({default:e.RecordMap})),__vite__mapDeps([8,1,5,2,6,3,7]))),hxe=15,P9=({item:e,record:t})=>{let n=J().maps,r=n?.style,i=E5(t,e);if(!r||!i)return null;let a=(0,V.jsx)(`div`,{className:`overflow-hidden rounded-lg border border-border bg-muted ${e.sidebar?`h-48`:`h-64 md:h-80`}`,children:(0,V.jsx)(o.Suspense,{fallback:null,children:(0,V.jsx)(mxe,{style:r,layers:n?.layers,position:i,zoom:e.zoom??hxe},`${i.latitude},${i.longitude}`)})});return e.sidebar?(0,V.jsx)(ab,{title:e.title,children:a}):(0,V.jsx)(tb,{title:e.title,children:a})},gxe=e=>b8(e)??tr,_xe=({model:e,stored:t,recordKey:n,edit:r,onDelete:i})=>{let{go:a}=XS(),s=rd(),c={model:e,record:t.record,key:n,etag:t.etag,permissions:t.permissions},l=YT(e.name,c,t=>t.run?.kind===`delete`&&a({kind:`list`,resource:e.name},{replace:!0})),[u,d]=(0,o.useState)(),f=l.actions.map(e=>({name:e.label,icon:gxe(e.icon),blocked:l.blocked(e),running:l.running===e.name,...e.run?.kind===`delete`&&{tone:`danger`},onRun:()=>DT(e)?d(e):void l.run(e)})),p=l.actions.some(e=>e.run?.kind===`delete`),m=[...r?[{name:`Edit`,icon:nn,render:({className:e,children:t,role:n})=>(0,V.jsx)(ZS,{to:r,role:n,className:e,children:t})}]:[],...f,...i&&!p?[{name:`Delete`,icon:zn,tone:`danger`,onRun:i}]:[]];return m.length===0?null:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`div`,{className:s?`max-md:hidden`:void 0,children:(0,V.jsx)(rb,{actions:m})}),s&&(0,nr.createPortal)((0,V.jsx)(mb,{actions:m,label:`Record actions`,className:`inline-flex size-11 shrink-0 items-center justify-center rounded-md text-muted-foreground hover:bg-muted md:hidden`}),s),u&&(0,V.jsx)(OT,{action:u,label:u.label,danger:u.run?.kind===`delete`,onCancel:()=>d(void 0),onConfirm:()=>{d(void 0),l.run(u)},onSubmit:async e=>{await l.submit(u,e),d(void 0)}})]})},vxe=(e,t)=>Object.values(e).find(e=>e.name!==t.name&&e.fields.position&&e.fields.quantity&&Object.values(e.fields).some(e=>e.type===`relation`&&e.relation?.resource===t.name)),yxe=e=>({id:String(e.id),productId:String(e.productId??``),description:String(e.description??``),quantity:Number(e.quantity),unitPriceCents:Math.round(Number(e.unitPrice)*100)}),bxe=({lines:e,draft:t,vatRate:n,saving:r,locked:i=!1})=>{let a=MT(YS(e.name),`update`);return(0,V.jsx)(tb,{title:`Lines`,help:`What the document bills for. Drag the handle, or use the menu, to change the order; Save applies it.`,children:(0,V.jsx)(`div`,{className:`-mx-4 overflow-x-auto px-4 [-webkit-overflow-scrolling:touch] md:mx-0 md:px-0`,children:(0,V.jsx)(`div`,{className:`min-w-[560px]`,children:(0,V.jsx)(Wy,{lines:t.shown.map(yxe),onChange:()=>void 0,onReorder:e=>t.setOrder(e.map(e=>e.id)),vatRate:n,readOnly:!0,reorderable:a&&!r&&!i})})})})},xxe=(e,t,n)=>`protobase:draft:${e}:${t}:${n}`,Sxe=(e,t,n)=>zu(()=>{let r=e.getItem(t);if(r===null)return;let i=JSON.parse(r);if(i&&i.etag===n&&typeof i.fields==`object`&&i.fields!==null)return{etag:n,fields:i.fields,...Array.isArray(i.order)&&{order:i.order.map(String)}}},void 0),Cxe=(e,t,n)=>zu(()=>n?e.setItem(t,JSON.stringify(n)):e.removeItem(t),void 0),wxe=(e,t)=>Number(e.position)-Number(t.position),Txe=(e,t,n)=>{let r=e&&Object.values(e.fields).find(e=>e.type===`relation`&&e.relation?.resource===t.name),i=QS(e?.name??``,{enabled:!!(e&&r),filter:r?`${r.name} = "${n}"`:void 0,pageSize:200,...e?.fields.position?.sortable&&{orderBy:`position asc`}});return{items:[...i.items].sort(wxe),loading:i.isPending&&!!e}},Exe=(e,t)=>{let[n,r]=(0,o.useState)(),i=t.map(e=>String(e.id)),a=(0,o.useMemo)(()=>{if(!n)return t;let e=n.flatMap(e=>t.filter(t=>String(t.id)===e)),r=t.filter(e=>!n.includes(String(e.id)));return[...e,...r]},[n,t]),s=a.map(e=>String(e.id)),c=n!==void 0&&s.some((e,t)=>e!==i[t]),l=(0,o.useCallback)(()=>!e||!c?[]:[{op:`reorder`,resource:e.name,field:`position`,keys:a.map(t=>zx(e,t)),etags:Object.fromEntries(a.flatMap(t=>typeof t.etag==`string`?[[Ao(zx(e,t)),t.etag]]:[]))}],[e,c,a]);return{shown:a,dirty:c,order:c?s:void 0,setOrder:e=>r(e),reset:()=>r(void 0),op:l}},Dxe=e=>{let t=e>=5?5:e===4?3:e;return{shown:t,more:e-t}},Oxe=(e,t)=>Math.abs(e)<40||Math.abs(e)<=Math.abs(t)?0:e<0?1:-1,kxe=e=>e===`ArrowRight`?1:e===`ArrowLeft`?-1:0,Axe=(e,t,n)=>Math.min(Math.max(e+t,0),Math.max(n-1,0)),jxe=e=>e.key===`i`&&!e.ctrlKey&&!e.metaKey&&!e.altKey,F9=`protobase:lightbox-details`,Mxe=e=>zu(()=>e.getItem(F9)===`true`,!1),Nxe=(e,t)=>zu(()=>t?e.setItem(F9,`true`):e.removeItem(F9),void 0),I9=`flex size-10 shrink-0 items-center justify-center rounded-full bg-background/85 text-foreground shadow-sm transition-colors hover:bg-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary/40`,Pxe=({title:e,photos:t,index:n,onIndex:r,onClose:i,details:a,detailsTitle:s=`Details`})=>{let c=(0,o.useRef)(null),l=(0,o.useRef)(void 0),u=(0,o.useId)(),d=Kl(),[f,p]=(0,o.useState)(()=>Mxe(localStorage)),[m,h]=(0,o.useState)(!1);tu(c,!0,i),(0,o.useEffect)(()=>h(!0),[]);let g=t.length,_=e=>{let t=Axe(n,e,g);t!==n&&r(t)},v=Ob(t[n],{width:1600,height:1200}),y=a?.(n),b=y!==void 0,x=e=>{p(e),Nxe(localStorage,e)};return(0,V.jsxs)(`div`,{ref:c,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":e,onKeyDown:e=>{if(b&&jxe(e))return e.preventDefault(),x(!f);let t=kxe(e.key);t!==0&&(e.preventDefault(),_(t))},className:`fixed inset-0 z-[90] flex flex-col overflow-y-auto overscroll-contain bg-backdrop outline-none md:flex-row`,children:[(0,V.jsxs)(`div`,{className:`flex h-dvh shrink-0 flex-col md:sticky md:top-0 md:min-w-0 md:flex-1`,children:[(0,V.jsxs)(`div`,{className:`flex shrink-0 items-center justify-between gap-2 p-3`,children:[(0,V.jsx)(`span`,{className:`rounded-full bg-background/85 px-3 py-1 font-medium tabular-nums text-foreground`,"aria-live":`polite`,children:`${n+1} / ${g}`}),(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[b&&(0,V.jsx)(`button`,{type:`button`,className:B(I9,`aria-expanded:bg-foreground aria-expanded:text-background`),"aria-label":s,"aria-expanded":f,"aria-controls":d?u:void 0,"aria-keyshortcuts":`i`,onClick:()=>x(!f),children:(0,V.jsx)(ht,{className:`size-4`,"aria-hidden":!0})}),(0,V.jsx)(`button`,{type:`button`,className:I9,"aria-label":`Close`,onClick:i,children:(0,V.jsx)($n,{className:`size-4`,"aria-hidden":!0})})]})]}),(0,V.jsxs)(`div`,{className:`relative flex min-h-0 flex-1 touch-pan-y items-center justify-center px-3 pb-3 md:px-16`,onPointerDown:e=>{e.pointerType===`touch`&&(l.current={x:e.clientX,y:e.clientY})},onPointerUp:e=>{l.current&&=(_(Oxe(e.clientX-l.current.x,e.clientY-l.current.y)),void 0)},onPointerCancel:()=>l.current=void 0,children:[v&&(0,V.jsx)(hC,{image:v,className:`max-h-full max-w-full select-none object-contain`},v.url),g>1&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`button`,{type:`button`,className:B(I9,`absolute left-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40`),"aria-label":`Previous photo`,"aria-disabled":n===0,onClick:()=>_(-1),children:(0,V.jsx)(be,{className:`size-5`,"aria-hidden":!0})}),(0,V.jsx)(`button`,{type:`button`,className:B(I9,`absolute right-3 top-1/2 -translate-y-1/2 aria-disabled:cursor-default aria-disabled:opacity-40`),"aria-label":`Next photo`,"aria-disabled":n===g-1,onClick:()=>_(1),children:(0,V.jsx)(Se,{className:`size-5`,"aria-hidden":!0})})]})]})]}),b&&f&&d&&(0,V.jsxs)(`aside`,{id:u,"aria-label":s,className:`min-h-dvh w-[360px] shrink-0 border-l border-border bg-background p-5 text-foreground`,children:[(0,V.jsx)(`h2`,{className:`mb-3 text-[16px] font-semibold`,children:s}),y]}),(0,V.jsx)(uT,{title:s,open:b&&f&&!d&&m,onClose:()=>x(!1),children:(0,V.jsx)(`div`,{className:`pt-3`,children:y})})]})},Fxe=(e,t,n)=>{let r=(t?.layout??[]).flatMap(e=>e.kind===`section`&&Gb(e.when,!1)?e.fields:[]);return(r.length>0?[...new Set(r)]:Object.keys(e.fields).filter(t=>t!==e.tenant&&!e.primaryKey.includes(t))).filter(r=>e.fields[r]&&!e.fields[r].sensitive&&!n.includes(r)&&Gb(t?.fields[r]?.when,!1))},Ixe=({model:e,view:t,photoKey:n,fields:r})=>{let i=Sg(e.name,n),a=(t?.names?.singular??K(e.name)).toLowerCase();if(i.isPending)return(0,V.jsx)(cu,{className:`h-4 w-48`});if(i.error)return(0,V.jsx)(ax,{title:`Could not load the ${a}`,error:i.error});let o=r.filter(e=>PT(i.data.permissions,e)!==`hidden`);return(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(cb,{rows:o.map(n=>({label:t?.fields[n]?.label??K(n),value:(0,V.jsx)(m4,{model:e,field:e.fields[n],value:i.data.record[n]})}))}),(0,V.jsx)(ZS,{to:{kind:`record`,resource:e.name,key:n},className:`mt-3 inline-block font-medium text-primary-text hover:underline`,children:`Open ${a}`})]})},L9=e=>Ob(e,{width:0,height:0})!==void 0,Lxe=(e,t)=>{let n=e.primaryKey.map(e=>t[e]);if(!n.some(e=>e==null))return Ao(n)},Rxe=(e,t,n,r)=>{let i=n===void 0?[]:t.flatMap(e=>{let t=e[n];if(!vb(t)||!L9(t))return[];let i=r&&Lxe(r,e);return[{file:t,...i!==void 0&&{key:i}}]});if(!vb(e)||!L9(e))return i;let a=t=>vb(t.file)&&t.file.uri===e.uri,o=i.find(a)?.key;return[{file:e,...o!==void 0&&{key:o}},...i.filter(e=>!a(e))]},zxe=co(),Bxe=(e,t,n)=>{let r=G(),{resources:i}=J(),a=e.photos?i[e.photos.resource]:void 0,o=e.photos?qa(zxe.eq(e.photos.field,n)):``,s=e.photos?.sort??``,c=mh({queryKey:W.list(a?.name??``,o,s,500,`gallery`),enabled:a!==void 0,queryFn:async()=>(await r.list(a.name,{filter:o,...s&&{orderBy:s},pageSize:500})).items});return{holder:a,items:Rxe(e.image===void 0?void 0:t[e.image],c.data??[],e.photos?.image,a),isPending:a!==void 0&&c.isPending,error:c.error}},Vxe={1:[`md:col-span-4 md:row-span-2`],2:[`md:col-span-2 md:row-span-2`,`md:col-span-2 md:row-span-2`],3:[`md:col-span-2 md:row-span-2`,`md:col-span-2`,`md:col-span-2`],5:[`md:col-span-2 md:row-span-2`,``,``,``,``]},Hxe=({photo:e,large:t})=>{let n=Ob(e,t?{width:960,height:720}:{width:480,height:360});return n?(0,V.jsx)(hC,{image:n,loading:`lazy`,className:`size-full object-cover transition-transform duration-300 group-hover/tile:scale-[1.02]`}):null},Uxe=({item:e,record:t,recordKey:n})=>{let{views:r}=J(),i=Bxe(e,t,n),a=YS(i.holder?.name??``),[s,c]=(0,o.useState)();if(i.isPending)return(0,V.jsx)(tb,{title:e.title,children:(0,V.jsx)(cu,{className:`aspect-[4/3] w-full rounded-lg md:aspect-[2/1]`})});if(i.error)return(0,V.jsx)(tb,{title:e.title,children:(0,V.jsx)(ax,{title:`Could not load the photos`,error:i.error})});let l=i.items.length;if(l===0)return null;let{shown:u,more:d}=Dxe(l),f=i.holder,p=f&&r[f.name],m=f?Fxe(f,p,[e.photos?.image,e.photos?.field].filter(e=>e!==void 0)):[],h=f!==void 0&&a.read!==!1&&m.length>0;return(0,V.jsxs)(tb,{title:e.title,children:[(0,V.jsx)(`div`,{className:`grid aspect-[4/3] grid-cols-4 grid-rows-2 gap-1.5 overflow-hidden rounded-lg md:aspect-[2/1]`,children:i.items.slice(0,u).map((e,t)=>{let n=t===u-1&&d>0;return(0,V.jsxs)(`button`,{type:`button`,"aria-label":n?`Show all ${l} photos`:`Show photo ${t+1} of ${l}`,onClick:()=>c(t),className:B(`group/tile relative overflow-hidden bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-primary`,t===0?`col-span-4 row-span-2`:`max-md:hidden`,Vxe[u][t]),children:[(0,V.jsx)(Hxe,{photo:e.file,large:t===0}),n&&(0,V.jsx)(`span`,{className:`absolute inset-0 flex items-center justify-center bg-backdrop/55 text-lg font-semibold text-white`,"aria-hidden":!0,children:`+${d}`}),t===0&&l>1&&(0,V.jsxs)(`span`,{className:`absolute bottom-2 right-2 flex items-center gap-1.5 rounded-full bg-background/85 px-2.5 py-1 text-xs font-medium tabular-nums text-foreground md:hidden`,"aria-hidden":!0,children:[(0,V.jsx)(pt,{className:`size-3.5`}),l]})]},t)})}),s!==void 0&&(0,V.jsx)(Pxe,{title:e.title,photos:i.items.map(e=>e.file),index:s,onIndex:c,onClose:()=>c(void 0),details:e=>{let t=i.items[e]?.key;return h&&t!==void 0?(0,V.jsx)(Ixe,{model:f,view:p,photoKey:t,fields:m},t):void 0},detailsTitle:f&&`${p?.names?.singular??K(f.name)} details`})]})},Wxe={create:`created this`,update:`changed`,delete:`deleted this`,undelete:`restored this`},Gxe=e=>e.actor?e.actor.name??e.actor.id:e.databaseRole?`Database (${e.databaseRole})`:`Database`,Kxe=(e,t,n)=>{let r=(e.operation===`create`?[]:e.changed).flatMap(r=>{let i=t.fields[r];if(!i||r===t.softDelete)return[];let a=n?.fields[r],o=a?.label??K(r);return i.sensitive||!e.before||!e.after?[{name:r,label:o}]:[{name:r,label:o,before:eS(i,e.before[r],a),after:eS(i,e.after[r],a)}]}),i=e.operation===`update`&&r.length===0?`changed this`:Wxe[e.operation];return{who:Gxe(e),verb:i,fields:r}},qxe=1500,Jxe=(e,t,n,r)=>{let i=G(),a=gh({queryKey:W.history(e,t,n),initialPageParam:``,queryFn:({pageParam:r})=>i.history(e,t,{pageSize:n,pageToken:r}),getNextPageParam:e=>e.nextPageToken||void 0}),{refetch:s}=a;return(0,o.useEffect)(()=>{let e=setTimeout(()=>void s(),qxe);return()=>clearTimeout(e)},[r,s]),{...a,items:a.data?.pages.flatMap(e=>e.items)??[]}},Yxe=()=>(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-4 w-full`},t))}),Xxe=({change:e,model:t,view:n})=>{let{who:r,verb:i,fields:a}=Kxe(e,t,n),o=Date.parse(e.at);return(0,V.jsxs)(`li`,{className:`flex flex-col gap-1.5 py-3 first:pt-0 last:pb-0`,children:[(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:r}),` `,(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:i}),` `,(0,V.jsxs)(`time`,{dateTime:e.at,title:df(o),className:`text-muted-foreground`,children:[`· `,bf(Math.max(0,Math.round((Date.now()-o)/1e3)))]})]}),a.length>0&&(0,V.jsx)(`dl`,{className:`grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-4 gap-y-1`,children:a.map(e=>(0,V.jsxs)(`div`,{className:`contents`,children:[(0,V.jsx)(`dt`,{className:`text-muted-foreground`,children:e.label}),(0,V.jsx)(`dd`,{className:`min-w-0 break-words`,children:e.before===void 0?(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:`changed`}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`del`,{className:`text-muted-foreground`,children:e.before}),` → `,(0,V.jsx)(`ins`,{className:`no-underline`,children:e.after})]})})]},e.name))})]})},Zxe=({item:e,model:t,view:n,recordKey:r,etag:i})=>{let a=Jxe(t.name,r,e.limit??10,i);return(0,V.jsx)(tb,{title:e.title,children:a.isPending?(0,V.jsx)(Yxe,{}):a.error?(0,V.jsx)(ax,{title:`Could not load the history`,error:a.error}):a.items.length===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`No changes kept yet.`}):(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(`ol`,{className:`divide-y divide-border`,children:a.items.map(e=>(0,V.jsx)(Xxe,{change:e,model:t,view:n},e.id))}),a.hasNextPage&&(0,V.jsx)(U,{size:`sm`,className:`mt-4`,disabled:a.isFetchingNextPage,onClick:()=>void a.fetchNextPage(),children:`Show more`})]})})},Qxe=(e,t)=>{let n=/(?:^|\s)@([^\s@]*)$/.exec(e.slice(0,t));return n?{start:t-n[1].length-1,query:n[1]}:void 0},$xe=(e,t,n)=>{let r=e.slice(t.start+1+t.query.length),i=`@${n}${r.startsWith(` `)?``:` `}`;return{text:`${e.slice(0,t.start)}${i}${r}`,caret:t.start+i.length+ +!!r.startsWith(` `)}},eSe=e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`),R9=e=>{let t=[...new Set(e)].filter(Boolean).sort((e,t)=>t.length-e.length);return t.length===0?void 0:RegExp(`(?<![\\p{L}\\p{N}_@])@(${t.map(eSe).join(`|`)})(?![\\p{L}\\p{N}_])`,`gu`)},tSe=(e,t)=>{let n=R9(t.map(e=>e.name)),r=new Set(n?[...e.matchAll(n)].map(e=>e[1]):[]);return[...new Set(t.filter(e=>r.has(e.name)).map(e=>e.id))]},nSe=(e,t)=>{let n=R9(t.flatMap(e=>e.name?[e.name]:[]));if(!n)return[{text:e}];let r=[],i=0;for(let t of e.matchAll(n))t.index>i&&r.push({text:e.slice(i,t.index)}),r.push({mention:t[1]}),i=t.index+t[0].length;return i<e.length&&r.push({text:e.slice(i)}),r},rSe=({comment:e})=>(0,V.jsx)(`p`,{className:`whitespace-pre-wrap break-words`,children:nSe(e.body,e.mentions).map((e,t)=>`mention`in e?(0,V.jsxs)(`span`,{className:`font-medium text-primary`,children:[`@`,e.mention]},t):e.text)}),iSe=(e,t,n)=>{let r=G(),i=K6(n,150);return mh({queryKey:W.mentionable(e,t,i??``),queryFn:()=>r.mentionable(e,t,i??``),enabled:i!==void 0,placeholderData:hm})},aSe=(e,t)=>{let n=G(),r=Gp();return hh({mutationFn:r=>n.comment(e,t,r),onSuccess:()=>r.invalidateQueries({queryKey:W.comments(e,t)})})},oSe=8,sSe=({resource:e,recordKey:t})=>{let[n,r]=(0,o.useState)(``),[i,a]=(0,o.useState)(0),[s,c]=(0,o.useState)(!1),[l,u]=(0,o.useState)([]),[d,f]=(0,o.useState)(0),[p,m]=(0,o.useState)(),h=(0,o.useRef)(null),g=(0,o.useRef)(void 0),_=(0,o.useId)(),v=Qy(),y=aSe(e,t),b=Qxe(n,i),x=s&&b!==void 0&&b.start!==p,S=iSe(e,t,x?b.query:void 0),C=x?(S.data??[]).slice(0,oSe):[],w=x&&S.data!==void 0,T=e=>`${_}-${e}`;(0,o.useEffect)(()=>f(0),[b?.query]);let E=b?.start;(0,o.useEffect)(()=>{E===void 0&&m(void 0)},[E]),(0,o.useLayoutEffect)(()=>{g.current!==void 0&&h.current&&(h.current.setSelectionRange(g.current,g.current),a(g.current),g.current=void 0)},[n]);let D=e=>{if(!b)return;let t=$xe(n,b,e.name);g.current=t.caret,r(t.text),u(t=>[...t,e])},O=()=>{n.trim()===``||y.isPending||y.mutate({body:n,mentions:tSe(n,l)},{onSuccess:()=>{r(``),u([])},onError:e=>v.show({state:`error`,title:`Could not post the comment`,description:lS(e)})})};return(0,V.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[(0,V.jsxs)(`div`,{className:`relative`,children:[(0,V.jsx)(cx,{ref:h,role:`combobox`,"aria-label":`Comment`,"aria-multiline":!0,"aria-autocomplete":`list`,"aria-expanded":w,"aria-controls":_,"aria-activedescendant":w&&C[d]?T(d):void 0,placeholder:`Write a comment, @ to mention someone`,value:n,onChange:e=>{r(e.target.value),a(e.target.selectionStart)},onSelect:e=>a(e.currentTarget.selectionStart),onFocus:()=>c(!0),onBlur:()=>c(!1),onKeyDown:e=>{if(e.key===`Enter`&&(e.metaKey||e.ctrlKey)){e.preventDefault(),O();return}if(!x)return;let t=I5(e.key,d,C.length);if(t!==void 0&&(e.key===`ArrowDown`||e.key===`ArrowUp`)){e.preventDefault(),f(t);return}if((e.key===`Enter`||e.key===`Tab`)&&C[d]){e.preventDefault(),D(C[d]);return}e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),m(b.start))}}),w&&(0,V.jsxs)(`ul`,{id:_,role:`listbox`,"aria-label":`People to mention`,className:`absolute z-30 mt-1 w-full max-w-sm rounded-md border bg-background py-1 shadow-pop`,onMouseDown:e=>e.preventDefault(),children:[C.map((e,t)=>(0,V.jsx)(`li`,{id:T(t),role:`option`,"aria-selected":t===d,className:B(`cursor-pointer truncate px-3 py-1.5`,t===d&&`bg-muted`),onMouseMove:()=>t!==d&&f(t),onClick:()=>D(e),children:e.name},e.id)),C.length===0&&(0,V.jsx)(`li`,{className:`px-3 py-1.5 text-muted-foreground`,children:`No one found`})]})]}),(0,V.jsx)(`div`,{children:(0,V.jsx)(U,{variant:`primary`,size:`sm`,disabled:n.trim()===``,loading:y.isPending,onClick:O,children:`Comment`})})]})},cSe=20,lSe=(e,t)=>{let n=G(),r=gh({queryKey:W.comments(e,t),initialPageParam:``,queryFn:({pageParam:r})=>n.comments(e,t,{pageSize:cSe,pageToken:r}),getNextPageParam:e=>e.nextPageToken||void 0});return{...r,items:r.data?.pages.flatMap(e=>e.items).reverse()??[]}},uSe=()=>(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-4 w-full`},t))}),dSe=({comment:e})=>{let t=e.author.name??e.author.id,n=Date.parse(e.createdAt);return(0,V.jsxs)(`li`,{className:`flex gap-3 py-3 first:pt-0 last:pb-0`,children:[(0,V.jsx)(xu,{initials:vg(t)||`?`,hue:_g(e.author.id),size:`md`,className:`ring-0`}),(0,V.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col gap-0.5`,children:[(0,V.jsxs)(`p`,{children:[(0,V.jsx)(`span`,{className:`font-medium text-foreground`,children:t}),` `,(0,V.jsxs)(`time`,{dateTime:e.createdAt,title:df(n),className:`text-muted-foreground`,children:[`· `,bf(Math.max(0,Math.round((Date.now()-n)/1e3)))]})]}),(0,V.jsx)(rSe,{comment:e})]})]})},fSe=({item:e,resource:t,recordKey:n,canWrite:r})=>{let i=lSe(t,n);return(0,V.jsxs)(tb,{title:e.title,children:[i.isPending?(0,V.jsx)(uSe,{}):i.error?(0,V.jsx)(ax,{title:`Could not load the comments`,error:i.error}):(0,V.jsxs)(V.Fragment,{children:[i.hasNextPage&&(0,V.jsx)(U,{size:`sm`,className:`mb-4`,disabled:i.isFetchingNextPage,onClick:()=>void i.fetchNextPage(),children:`Show earlier comments`}),i.items.length===0?(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:`No comments yet.`}):(0,V.jsx)(`ol`,{className:`divide-y divide-border`,children:i.items.map(e=>(0,V.jsx)(dSe,{comment:e},e.id))})]}),r&&(0,V.jsx)(`div`,{className:`mt-4`,children:(0,V.jsx)(sSe,{resource:t,recordKey:n})})]})},z9=(e,t)=>{let n=G(),r=Gp(),i=Ao(t);return hh({mutationFn:({patch:r,etag:i})=>n.update(e,t,r,i),onSuccess:t=>{r.setQueryData(W.record(e,i),t),r.invalidateQueries({queryKey:[`page`,e]}),r.invalidateQueries({queryKey:[`list`,e]}),r.invalidateQueries({queryKey:[`map`,e]})}})},B9=e=>e instanceof Ls,pSe=e=>{let t=typeof e.resource==`string`?e.resource:e.resource.toModel().name;return e.op===`reorder`?`reorder ${t} by ${e.field}`:`${e.op} ${t}`},mSe=(e,t)=>{let n=e.operation,r=n===void 0?void 0:t[n];return r?`Operation ${n+1} (${pSe(r)}) failed: ${e.message} Nothing was saved.`:`${e.message} Nothing was saved.`},hSe=(e,t)=>new e.constructor({...e.problem,detail:mSe(e,t)}),V9=(e,t)=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==t)),gSe=({model:e,stored:t,recordKey:n,mode:r,subject:i,draftKey:a,lines:s})=>{let c=G(),l=Gp(),u=z9(e.name,n),d=Q5(r,i),[f]=(0,o.useState)(()=>a?Sxe(localStorage,a,t.etag):void 0),[p,m]=(0,o.useState)(f?.fields??{}),[h,g]=(0,o.useState)(!!f),[_,v]=(0,o.useState)(!1),[y,b]=(0,o.useState)({}),[x,S]=(0,o.useState)({}),[C,w]=(0,o.useState)(0),T=Object.entries(p).filter(([n,r])=>Vb(e.fields[n],r,t.record[n])),E=T.length>0,D=E||!!s?.dirty;(0,o.useEffect)(()=>{f?.order&&s?.setOrder(f.order)},[]),(0,o.useEffect)(()=>{if(!a)return;let n=Object.fromEntries(Object.entries(p).filter(([t])=>!e.fields[t]?.sensitive)),r=Object.keys(n).length>0||!!s?.dirty;Cxe(localStorage,a,r?{etag:t.etag,fields:n,...s?.order&&{order:s.order}}:void 0)},[a,e,p,s?.dirty,s?.order,t.etag]);let O=n=>n in p?p[n]:[`boolean`,`file`].includes(e.fields[n].type)?t.record[n]:Mb(t.record[n]),k=(n,r)=>{S(e=>V9(e,n));let i=typeof r==`string`?r!==Mb(t.record[n]):Vb(e.fields[n],r,t.record[n]);m(e=>i?{...e,[n]:r}:V9(e,n))},A=async()=>{let r=await c.get(e.name,n);l.setQueryData(W.record(e.name,n),r);let i={},a={};for(let[n,o]of Object.entries(p)){let s=e.fields[n];Vb(s,o,r.record[n])&&(a[n]=o,Mb(r.record[n])!==Mb(t.record[n])&&(i[n]=s.type===`file`?eS(s,r.record[n]):Mb(r.record[n])))}m(a),b(i)},j=()=>Object.fromEntries(T.map(([t,n])=>[t,Rb(e.fields[t],n)])),M=e=>{let t=WC(e);S(t),Object.keys(t).length>0&&w(e=>e+1)},N=async()=>{try{await u.mutateAsync({patch:j(),etag:t.etag})}catch(e){throw B9(e)?await A():Rs(e)&&M(e),e}},ee=async r=>{let i=[...E?[{op:`update`,resource:e.name,key:n,data:j(),etag:t.etag}]:[],...r];try{await c.batchWrite(i)}catch(e){throw B9(e)?(await A(),await l.invalidateQueries({queryKey:[`list`]}),v(!0)):Rs(e)&&M(e),Rs(e)?hSe(e,i):e}await Promise.all([l.invalidateQueries({queryKey:W.record(e.name,n)}),l.invalidateQueries({queryKey:[`list`]}),l.invalidateQueries({queryKey:[`page`]}),l.invalidateQueries({queryKey:[`map`]})]),s?.reset()};return{value:O,change:k,save:()=>d.run(async()=>{let e=s?.op()??[];e.length>0?await ee(e):await N(),m({}),b({}),S({}),v(!1),g(!1)}),dirty:D,discard:()=>{m({}),b({}),S({}),v(!1),g(!1),s?.reset()},restored:h&&D,dismissRestored:()=>g(!1),linesConflict:_,saving:d.phase===`saving`,phase:d.phase,message:d.message,conflicts:y,errors:x,rejections:C,keepMine:e=>b(t=>V9(t,e)),useTheirs:e=>{b(t=>V9(t,e)),m(t=>V9(t,e))}}},H9=(e,t,n,r)=>{let i=G(),a=Gp(),o=Object.values(e.fields).filter(n=>n.type===`relation`&&n.relation&&n.name!==e.tenant&&r[n.name]!=null&&t[n.relation.resource]?.primaryKey.length===1),s=fh({queries:o.map(e=>{let o=t[e.relation.resource],s=String(r[e.name]);return{queryKey:W.relatedLabel(o.name,s),queryFn:async()=>(await c4(a,i,o,[s],n[o.name])).get(s)??s}})}),c=o.map(e=>({kind:`record`,resource:e.relation.resource,key:String(r[e.name])}));return{addresses:Object.fromEntries(o.map((e,t)=>[e.name,c[t]])),labels:Object.fromEntries(o.map((e,t)=>[e.name,s[t]?.data]))}},_Se=co(),vSe=(e,t,n,r,i)=>{if(e.primaryKey.length!==1)return[];let a=new Set(r.flatMap(e=>e.kind===`related`&&!e.through?[`${e.resource}.${e.field}`]:[])),o=Object.values(t).flatMap(t=>Object.values(t.fields).filter(t=>t.type===`relation`&&t.relation?.resource===e.name&&t.relation.columns.length===1&&t.filterable).filter(e=>e.name!==t.tenant&&t.name!==i?.name&&!a.has(`${t.name}.${e.name}`)).map(e=>({source:t,field:e.name})));return o.map(({source:e,field:t})=>{let r=n[e.name],i=r?.names?.plural??K(e.name),a=o.filter(t=>t.source.name===e.name).length>1;return{resource:e.name,field:t,label:a?`${i} (${r?.fields[t]?.label??K(t)})`:i}})},ySe=(e,t)=>({kind:`list`,resource:e.resource,filter:qa(_Se.eq(e.field,t))}),bSe=co(),xSe=(e,t,n)=>{let r=G(),i=fh({queries:e.map(e=>{let i=qa(bSe.eq(e.field,n));return{queryKey:W.list(e.resource,i,``,1,`incoming`),queryFn:async()=>{let n=await r.list(e.resource,{filter:i,pageSize:1,count:`exact`,fields:t[e.resource].primaryKey});return{count:n.totalSize??n.totalSizeEstimate,exact:n.totalSize!==void 0}}}})});return e.flatMap((e,t)=>{let n=i[t];return n.error?[]:[{relation:e,count:n.data}]})},SSe=({model:e,recordKey:t,layout:n,lines:r})=>{let{resources:i,views:a}=J(),o=xSe(vSe(e,i,a,n,r),i,t);return o.length===0?null:(0,V.jsx)(ab,{title:`Related records`,children:(0,V.jsx)(`ul`,{className:`-mx-2`,children:o.map(({relation:e,count:n})=>(0,V.jsx)(`li`,{children:(0,V.jsxs)(ZS,{to:ySe(e,t),className:`group flex items-center justify-between gap-3 rounded-md px-2 py-2 hover:bg-muted`,children:[(0,V.jsx)(`span`,{className:`min-w-0 truncate font-medium text-primary-text`,children:e.label}),(0,V.jsxs)(`span`,{className:`flex shrink-0 items-center gap-1 tabular-nums text-muted-foreground`,children:[n===void 0?(0,V.jsx)(cu,{className:`h-4 w-6`}):`${Bd(n.count)}${n.exact?``:`+`}`,(0,V.jsx)(Se,{className:`size-4 text-faint-foreground group-hover:text-foreground`})]})]})},`${e.resource}.${e.field}`))})})},U9=co(),W9=(...e)=>{let t=e.filter(e=>!!e);return t.length===1?t[0]:t.map(e=>`(${e})`).join(` AND `)},CSe=(e,t)=>{let n=G(),{resources:r}=J(),i=e.through,a=i?r[i.resource]:void 0,o=i?.key??a?.primaryKey[0],s=i?W9(qa(U9.eq(i.field,t)),i.filter):``,c=mh({queryKey:W.list(a?.name??``,s,``,0,`related:${o}`),enabled:!!(a&&o),queryFn:async()=>{let e=await T6(n,a.name,{filter:s,fields:[o]});return[...new Set(e.items.flatMap(e=>e[o]===null||e[o]===void 0?[]:[String(e[o])]))]}});return i?c.data?{filter:c.data.length===0?null:W9(qa(U9.in(e.field,c.data)),e.filter),isPending:!1,error:null}:{filter:void 0,isPending:c.isPending,error:c.error}:{filter:W9(qa(U9.eq(e.field,t)),e.filter),isPending:!1,error:null}},wSe=()=>(0,V.jsx)(`div`,{className:`flex flex-col gap-2`,children:Array.from({length:3},(e,t)=>(0,V.jsx)(cu,{className:`h-4 w-full`},t))}),TSe=({text:e})=>(0,V.jsx)(`p`,{className:`text-muted-foreground`,children:e??`Nothing here yet.`}),ESe=({item:e,recordKey:t,owner:n})=>{let{resources:r,views:i}=J(),a=r[e.resource],s=a&&i[a.name],c=CSe(e,t),[l,u]=q5(s,`related:${n}:${e.title}`,e.display),d=YS(e.resource),[f,p]=(0,o.useState)(!1);if(!a)return null;let m=ave(e,a,r),h=e.columns??Zx(a,s).filter(t=>t!==e.field),g=Bbe(e,a,d),_=(0,V.jsx)(G5,{view:s,value:l,onChange:u}),v=g?(0,V.jsxs)(`div`,{className:`flex items-center gap-2`,children:[!f&&_,(0,V.jsx)(b9,{size:`sm`,sorting:f,onChange:p})]}):_;return f&&g?(0,V.jsx)(tb,{title:e.title,help:e.help,actions:v,children:(0,V.jsx)(y9,{model:a,view:s,field:g,filter:qa(U9.eq(e.field,t)),columns:h})}):(0,V.jsx)(tb,{title:e.title,help:e.help,actions:v,children:c.isPending?(0,V.jsx)(wSe,{}):c.error?(0,V.jsx)(ax,{title:`Could not load`,error:c.error}):c.filter===null||c.filter===void 0?(0,V.jsx)(TSe,{text:e.empty}):(0,V.jsx)(K5,{model:a,view:s,filter:c.filter,sort:e.sort??``,columns:h,limit:e.limit??10,display:l,empty:e.empty,opens:m},c.filter)})},DSe=(e,t)=>t===e.tenant||e.primaryKey.includes(t),OSe=(e,t,n)=>{if(t&&t.layout.length>0)return t.layout;let r=Object.values(e.fields).filter(t=>!DSe(e,t.name)),i=r.filter(e=>!e.readOnly);return[{kind:`section`,title:`Details`,fields:(i.length>0&&!n?i:r).map(e=>e.name)},...e.history?[{kind:`history`,title:`History`}]:[],...e.comments?[{kind:`comments`,title:`Comments`}]:[]]},kSe=({resource:e,recordKey:t})=>{let{resources:n}=J(),r=n[e],i=Cg(e,t);return r?i.isPending?(0,V.jsx)(KS,{title:`Loading`,children:`Fetching the record.`}):i.error?(0,V.jsx)(`div`,{className:`p-8`,children:Rs(i.error)&&i.error.status===404?(0,V.jsx)(KS,{title:`Not found`,children:`This record does not exist, or you cannot see it.`}):(0,V.jsx)(ax,{title:`Could not load the record`,error:i.error})}):(0,V.jsx)(ASe,{model:r,recordKey:t,stored:i.data,preview:i.isPlaceholderData},i.isPlaceholderData?`preview`:`loaded`):(0,V.jsxs)(KS,{title:`Not found`,children:[`There is no resource called `,e,`.`]})},ASe=({model:e,recordKey:t,stored:n,preview:r})=>{let i=J(),{address:a,go:s}=XS(),c=i.views[e.name],l=Ix(e,c,n.record,t),{state:u}=H(),d=(0,o.useMemo)(()=>vxe(i.resources,e),[i.resources,e]),f=Exe(d,Txe(d,e,t).items),p=gSe({model:e,stored:n,recordKey:t,mode:c?.saveFeedback??`toast`,subject:l,draftKey:!r&&u.kind===`signed-in`?xxe(u.user.id,e.name,t):void 0,lines:f}),m=Gp(),h=G(),g=KC(p.rejections),_=YS(e.name),v=n7(e),y=MT(_,`update`)&&n.permissions?.update!==!1,{shown:b,offersEdit:x,editing:S}=Hb(c?.recordMode,y,a?.kind===`record`&&a.edit===!0);Hne(p.dirty&&b===`form`),Fne(p.dirty);let C={kind:`record`,resource:e.name,key:t},w={...C,edit:!0},T=b===`form`&&c?.recordMode!==void 0&&c.recordMode!==`edit`,E=MT(_,`delete`)&&n.permissions?.delete!==!1,D=t7({model:e,view:c,restore:v,onDeleted:()=>s({kind:`list`,resource:e.name},{replace:!0}),onReview:()=>void m.invalidateQueries({queryKey:W.record(e.name,t)})}),O=H9(e,i.resources,i.views,n.record),k=t=>{let n=e.fields[t],r=n?.relation?i.resources[n.relation.resource]:void 0;if(r&&r.primaryKey.length===1&&t!==e.tenant&&!e.primaryKey.includes(t))return r},A=Object.values(e.fields).filter(e=>k(e.name)),j={...n.record,...Object.fromEntries(A.map(e=>[e.name,zb(e,p.value(e.name))]))},M=H9(e,i.resources,i.views,j),N=(e,t)=>{let n=k(e);if(!n||!Kb(t))return p.change(e,t);m.setQueryData(W.relatedLabel(n.name,t.key),t.label),p.change(e,Yb(n,t.key))},{fields:ee}=SC(),P=OSe(e,c,b===`read`).filter(e=>Gb(e.when,S)),te=P.flatMap(e=>e.kind===`sidebar`?e.fields:[]),F=e.fields.status?.type===`enum`,ne=n.record.status,re=F&&!te.includes(`status`)&&ne!=null&&ne!==``?String(ne):void 0,ie=M9(e,`updated`),I=e=>c?.fields[e],ae=e=>PT(n.permissions,e)!==`hidden`&&Gb(I(e)?.when,S),oe=e=>!r||Object.hasOwn(n.record,e),se=r=>{let a=e.fields[r],o=PT(n.permissions,r);if(!a||o===`hidden`)return null;let s=p.conflicts[r],l=k(r),u=I(r)?.label??K(r),d=p.errors[r];return(0,V.jsx)(eb,{name:r,label:u,required:b===`form`&&o!==`read`&&Fb(a),help:Wb(I(r),c,S),error:d&&UC(a,u,d),wide:!!(I(r)?.multiline||I(r)?.markdown),conflict:s===void 0?void 0:{user:{name:`Someone else`,initials:`?`,hue:40},ago:`just now`,theirValue:s||`—`,onKeepMine:()=>p.keepMine(r),onUseTheirs:()=>p.useTheirs(r)},children:oe(r)?(0,V.jsx)(IC,{field:a,hints:I(r),value:p.value(r),stored:n.record[r],relationLabel:M.labels[r],relationTo:M.addresses[r],relationPicker:l&&{target:l,view:i.views[l.name]},locked:b!==`form`||o===`read`,invalid:!!p.errors[r],reveal:a.sensitive?()=>h.reveal(e.name,t,r):void 0,resource:e.name,onChange:e=>N(r,e)}):(0,V.jsx)(cu,{className:`h-9`})},a.sensitive?`${r}:${n.etag}`:r)},L=r=>{let i=e.fields[r],a=oe(r)?i.sensitive?(0,V.jsx)(IC,{field:i,hints:I(r),value:``,stored:n.record[r],locked:!0,reveal:()=>h.reveal(e.name,t,r),resource:e.name,onChange:e=>p.change(r,e)}):(0,V.jsx)(m4,{model:e,field:i,value:n.record[r],relationLabel:O.labels[r]}):(0,V.jsx)(cu,{className:`h-4 w-32`});return{label:I(r)?.label??K(r),help:Wb(I(r),c,S),wide:!!(I(r)?.multiline||I(r)?.markdown),value:a}},ce=P.findIndex(e=>e.kind===`sidebar`),le=(0,V.jsx)(ob,{title:`Summary`,rows:te.flatMap(t=>{let r=e.fields[t];if(!r||!ae(t))return[];if(!oe(t))return[{label:I(t)?.label??K(t),value:(0,V.jsx)(cu,{className:`h-4 w-24`})}];let i=eS(r,n.record[t],I(t)),a=n.record[t],o=Mx(r,I(t))&&typeof a==`string`&&a!==``,s=r.type===`text`&&typeof a==`string`&&a!==``?Vx(I(t)):void 0,c=r.type===`enum`?(0,V.jsx)(p4,{value:a,hints:I(t),children:i}):o?(0,V.jsx)(OC,{source:a}):s?(0,V.jsx)(PC,{format:s,value:i}):(0,V.jsx)(`strong`,{title:tS(r,a),className:I(t)?.multiline?`whitespace-pre-line break-words`:void 0,children:i}),l=CC(ee,r,I(t));return[{label:I(t)?.label??K(t),value:l?(0,V.jsx)(EC,{shown:l,part:`display`,field:r,value:n.record[t],fallback:c}):c}]})}),ue={model:e,record:n.record,key:t,etag:n.etag,permissions:n.permissions},de=async()=>{await p.save()&&T&&s(C,{replace:!0})},fe=E?()=>void D.start({key:t,title:l,etag:n.etag,snapshot:n.record}):void 0,pe=b===`form`&&(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{variant:`primary`,className:`max-md:min-h-11 max-md:flex-1 md:w-full`,loading:p.saving,disabled:!p.dirty&&p.phase!==`saved`,onClick:()=>void de(),children:[p.phase===`saved`&&(0,V.jsx)(ge,{className:`size-4`}),p.phase===`saved`?`Saved`:`Save`]}),T&&(0,V.jsx)(ZS,{to:C,className:B(Cf(),`max-md:min-h-11 md:w-full`),onClick:e=>lu(e)&&p.discard(),children:`Cancel`}),p.dirty&&(0,V.jsx)(`span`,{className:`text-xs text-muted-foreground max-md:order-first`,children:`Unsaved changes`})]});return(0,V.jsxs)(`div`,{ref:g,className:`flex flex-1 flex-col`,inert:r,children:[D.dialogs,(0,V.jsx)(`div`,{className:`flex-1`,children:(0,V.jsxs)(`div`,{className:`mx-auto max-w-[1100px] px-4 pb-8 pt-6 md:px-10 md:py-8`,children:[(0,V.jsx)(sb,{title:l,status:re?{label:rs(re,I(`status`)?.valueLabels),tone:Gx(re)}:void 0}),p.message&&(0,V.jsx)(`div`,{className:`mt-4`,children:(0,V.jsx)(ax,{title:`Not saved`,error:Error(p.message)})}),p.linesConflict&&(0,V.jsx)(`div`,{className:`mt-4`,children:(0,V.jsx)(ax,{title:`The lines were changed by someone else`,error:Error(`The lines were reloaded. Your new order is kept: Save again to apply it.`)})}),b!==`form`&&x&&p.dirty&&(0,V.jsxs)(`div`,{className:`mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2`,role:`status`,children:[(0,V.jsx)(`span`,{children:`You have unsaved changes to this record.`}),(0,V.jsxs)(`span`,{className:`flex gap-2`,children:[(0,V.jsx)(ZS,{to:w,className:Cf({size:`sm`}),children:`Continue editing`}),(0,V.jsx)(U,{size:`sm`,onClick:p.discard,children:`Discard`})]})]}),b===`form`&&p.restored&&(0,V.jsxs)(`div`,{className:`mt-4 flex items-center justify-between gap-3 rounded-lg border bg-surface px-3 py-2`,role:`status`,children:[(0,V.jsx)(`span`,{children:`Your unsaved changes were restored.`}),(0,V.jsxs)(`span`,{className:`flex gap-2`,children:[(0,V.jsx)(U,{size:`sm`,onClick:p.dismissRestored,children:`Keep`}),(0,V.jsx)(U,{size:`sm`,onClick:p.discard,children:`Discard`})]})]}),(0,V.jsxs)(`div`,{className:`grid grid-cols-1 gap-8 md:grid-cols-[minmax(0,1fr)_300px] md:gap-12`,children:[(0,V.jsxs)(`main`,{className:`divide-y divide-border`,children:[P.flatMap((i,a)=>{if(i.kind===`related`)return[(0,V.jsx)(ESe,{item:i,recordKey:t,owner:e.name},`related:${i.title}`)];if(r&&(i.kind===`custom`||i.kind===`map`||i.kind===`gallery`))return[];if(i.kind===`custom`)return i.sidebar?[]:[(0,V.jsx)(N9,{item:i,scope:ue},`custom:${a}`)];if(i.kind===`map`)return i.sidebar?[]:[(0,V.jsx)(P9,{item:i,record:n.record},`map:${a}`)];if(i.kind===`gallery`)return[(0,V.jsx)(Uxe,{item:i,record:n.record,recordKey:t},`gallery:${a}`)];if(i.kind===`history`)return[(0,V.jsx)(Zxe,{item:i,model:e,view:c,recordKey:t,etag:n.etag},`history:${a}`)];if(i.kind===`comments`)return[(0,V.jsx)(fSe,{item:i,resource:e.name,recordKey:t,canWrite:u.kind!==`visitor`},`comments:${a}`)];if(i.kind!==`section`)return[];let o=i.fields.filter(t=>e.fields[t]&&ae(t)),s=b===`read`&&i.presentation===`facts`,l=s?aS(n.record,o):o;return l.length===0?[]:[(0,V.jsx)(tb,{title:i.title,help:Ub(i.helpWhen,c,S)?i.help:void 0,children:s?(0,V.jsx)(lb,{facts:l.map(e=>({label:L(e).label,value:L(e).value,icon:b8(I(e)?.icon)}))}):b===`read`?(0,V.jsx)(cb,{rows:l.map(L)}):(0,V.jsx)(`div`,{className:`grid grid-cols-1 gap-x-6 gap-y-5 sm:grid-cols-2`,children:l.map(se)})},i.title)]}),d&&!r&&(0,V.jsx)(bxe,{lines:d,draft:f,vatRate:Number(n.record.vatRate??21)/100,saving:p.saving,locked:b!==`form`})]}),(0,V.jsxs)(`aside`,{className:`space-y-4 md:pt-8`,children:[pe&&(0,V.jsx)(`div`,{className:`hidden flex-col items-center gap-2 md:flex`,children:pe}),!r&&(0,V.jsx)(_xe,{model:e,stored:n,recordKey:t,edit:x?w:void 0,onDelete:fe}),ce===-1&&le,P.map((e,t)=>e.kind===`custom`&&e.sidebar&&!r?(0,V.jsx)(N9,{item:e,scope:ue},`custom:${t}`):e.kind===`map`&&e.sidebar&&!r?(0,V.jsx)(P9,{item:e,record:n.record},`map:${t}`):t===ce?(0,V.jsx)(o.Fragment,{children:le},`summary`):null),(0,V.jsx)(ob,{title:`Details`,rows:[M9(e,`created`),ie].flatMap(t=>{let r=t?e.fields[t]:void 0;return!t||!r||!ae(t)?[]:[{label:I(t)?.label??K(t),value:oe(t)?(0,V.jsx)(`span`,{title:tS(r,n.record[t]),children:eS(r,n.record[t],I(t))}):(0,V.jsx)(cu,{className:`h-4 w-24`})}]})}),!r&&(0,V.jsx)(SSe,{model:e,recordKey:t,layout:P,lines:d})]})]})]})}),pe&&(0,V.jsx)(`div`,{className:`sticky bottom-[var(--pb-sticky-bottom,0px)] z-20 flex shrink-0 items-center gap-2 border-t bg-background p-3 md:hidden`,children:pe})]})},jSe=e=>Rs(e)?e.status===401||e.status===403?`It did not accept your sign-in: ${e.message}`:e.message:`It did not answer.`,MSe=({status:e})=>{let t=Gp();return e.state===`error`?(0,V.jsx)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center p-8`,children:(0,V.jsxs)(`div`,{className:`max-w-md text-center`,children:[(0,V.jsxs)(`h1`,{className:`text-[16px] font-semibold`,children:[`Cannot reach `,e.source.label]}),(0,V.jsxs)(`p`,{className:`mt-1 text-muted-foreground`,children:[jSe(e.error),` The rest of the app works as before.`]}),(0,V.jsx)(U,{className:`mt-3`,onClick:()=>void t.refetchQueries({queryKey:W.sourceMetas(e.source.url)}),children:`Try again`})]})}):(0,V.jsxs)(`div`,{className:`flex h-full min-h-48 flex-1 items-center justify-center gap-2 text-muted-foreground`,children:[(0,V.jsx)(ld,{}),` Loading from `,e.source.label]})},G9=(e,t)=>e.toLowerCase().includes(t.trim().toLowerCase()),NSe=(e,t,n=``)=>{let r=A9(e,n).flatMap(e=>e.items.filter(e=>e.href!==void 0&&!e.problem)).filter(e=>G9(e.label,t)).slice(0,5),i=t.trim().replace(/^new\s+/i,``),a=Object.values(e.resources).flatMap(r=>{let a=e.views[r.name];if(!a||a.nav?.hidden||!r7(a,e.pages,e.permissions[r.name]??zS))return[];let o=a.names?.singular??K(r.name),s=`New ${o.toLowerCase()}`;return!G9(s,t)&&!G9(o,i)&&!G9(a.names?.plural??K(r.name),i)?[]:[{id:`new:${r.name}`,title:s,href:ps({kind:`create`,resource:r.name},n)}]});return[...r.length>0?[{id:`go-to`,label:`Go to`,hits:r.map(e=>({id:`go-to:${e.id}`,title:e.label,href:e.href}))}]:[],...a.length>0?[{id:`create`,label:`Create`,hits:a.slice(0,5)}]:[]]},PSe=co(),FSe=e=>Object.values(e.resources).flatMap(t=>{let n=e.views[t.name];return!t.search?.length||!n||n.nav?.hidden||e.permissions[t.name]?.read===!1?[]:[{model:t,view:n,label:n.names?.plural??K(t.name)}]}),ISe=e=>{let t=e.map(e=>e.label.toLowerCase());return t.length===0?`Search`:t.length===1?`Search ${t[0]}`:t.length===2?`Search ${t[0]} and ${t[1]}`:`Search ${t[0]}, ${t[1]} and more`},LSe=e=>qa(PSe.search(e.trim())),K9=e=>{let t=e.view?.searchResult?.title;return t?.length?t:[Fx(e.model,e.view)]},q9=e=>{let t=K9(e);return e.view?.searchResult?.subtitle??e.model.search?.find(e=>!t.includes(e))},RSe=e=>{let t=q9(e),n=[...K9(e),...t?[t]:[],...e.model.search??[]];return[...new Set([...e.model.primaryKey,...n.filter(t=>Object.hasOwn(e.model.fields,t))])]},J9=(e,t,n)=>{let r=t[n];return r==null?``:e.model.fields[n]?.type===`enum`?rs(String(r),e.view?.fields[n]?.valueLabels):String(r)},zSe=(e,t,n,r=``)=>{let i=Ao(zx(e.model,t)),a=K9(e),o=q9(e),s=Ua(e.model,t,n,[...a,...o?[o]:[]])??o,c=s?J9(e,t,s):``;return{id:i,title:a.map(n=>J9(e,t,n)).filter(Boolean).join(` `)||i,...c&&{subtitle:c},href:ps({kind:`record`,resource:e.model.name,key:i},r)}},BSe=()=>{let e=J(),t=G(),{basePath:n}=wh(),r=(0,o.useMemo)(()=>FSe(e),[e]),[i,a]=(0,o.useState)(``),s=i.trim(),c=K6(s,200),l=s.length>=2,u=l&&c.length>=2,d=fh({queries:r.map(e=>({queryKey:[`global-search`,e.model.name,c],enabled:u,staleTime:1/0,gcTime:0,queryFn:()=>t.list(e.model.name,{filter:LSe(c),pageSize:5,fields:RSe(e)})}))}),f=(0,o.useMemo)(()=>u?NSe(e,c,n):[],[u,e,c,n]),p=r.flatMap((e,t)=>{let r=d[t];if(!u||!r)return[];if(r.error)return[{id:e.model.name,label:e.label,hits:[],failed:!0}];let i=(r.data?.items??[]).map(t=>zSe(e,t,c,n));return i.length>0?[{id:e.model.name,label:e.label,hits:i}]:[]}),m=[...f,...p];return{available:Object.keys(e.pages).length>0||Object.keys(e.resources).length>0,placeholder:ISe(r),text:i,setText:a,query:u?c:``,loading:l&&(s!==c||d.some(e=>e.isFetching)),groups:m}},VSe=e=>!!(e?.updateAvailable&&e.indicator),HSe=e=>e?5e3:18e5,Y9={immediate:`Updates as soon as a release is out`,weekly:`Updates at a set time every week`,scheduled:`Updates at the time set for this release`,manual:`Updates only when asked to`},USe={job:`Preparing the update`,build:`Building`},WSe=(e,t)=>{if(!e.updateStage)return`Updating now`;let n=USe[e.updateStage];return e.updateStartedAt?`${n}, started ${_f(Math.max(0,Math.floor((t-Date.parse(e.updateStartedAt))/1e3)))}`:n},X9=(e,t=Date.now(),n=Wd())=>e.updating?WSe(e,t):e.nextUpdateAt?`${Y9[e.policy]}: next on ${df(Date.parse(e.nextUpdateAt),n)}`:Y9[e.policy],GSe=(e,t=Wd())=>{let n=df(Date.parse(e.finishedAt),t),r={succeeded:`Updated to ${e.toVersion} on ${n}`,unchanged:`The update to ${e.toVersion} on ${n} changed nothing`,failed:`The update to ${e.toVersion} failed on ${n}`}[e.outcome];return e.message?`${r}: ${e.message}`:`${r}.`},KSe=e=>Rs(e)&&e.status<500&&e.problem.detail?e.problem.detail:Rs(e)&&e.status===409?`Already on the latest version, or an update is running.`:Rs(e)&&e.status===403?`Only an admin can update the runtime.`:`The update could not be started. Try again later.`,Z9=({label:e,value:t})=>(0,V.jsxs)(`div`,{className:`flex justify-between gap-4 py-1`,children:[(0,V.jsx)(`span`,{className:`text-muted-foreground`,children:e}),(0,V.jsx)(`span`,{className:`font-medium tabular-nums`,children:t})]}),qSe=({status:e,requesting:t,error:n,checkError:r,onUpdate:i,onClose:a})=>{let o=e.updating?void 0:e.lastUpdate;return(0,V.jsxs)(wf,{title:`Runtime update`,description:e.updating?(0,V.jsxs)(`span`,{className:`inline-flex items-center gap-1.5`,children:[(0,V.jsx)(ld,{className:`size-3.5`}),X9(e)]}):X9(e),onClose:a,actions:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsx)(U,{onClick:a,children:`Close`}),(0,V.jsx)(U,{variant:`primary`,loading:t,disabled:e.updating||!e.updateAvailable,onClick:i,children:e.updating?`Updating…`:`Update now`})]}),children:[(0,V.jsx)(Z9,{label:`Current version`,value:e.version}),(0,V.jsx)(Z9,{label:`Latest version`,value:e.latest}),o&&(0,V.jsx)(`p`,{className:o.outcome===`failed`?`mt-3 text-danger-text`:`mt-3 text-muted-foreground`,children:GSe(o)}),n!==void 0&&(0,V.jsx)(`p`,{role:`alert`,className:`mt-3 text-danger-text`,children:KSe(n)}),r!==void 0&&(0,V.jsx)(`p`,{className:`mt-3 text-muted-foreground`,children:`The status could not be checked again; this is the last one read.`})]})},JSe=e=>{let t=xg(),n=(0,o.useRef)(t);n.current=t;let r=t!==void 0;return(0,o.useMemo)(()=>r?Wl({url:e,token:()=>n.current}):void 0,[e,r])},YSe=e=>{let[t,n]=(0,o.useState)(),[r,i]=(0,o.useState)(!1),[a,s]=(0,o.useState)(),[c,l]=(0,o.useState)(),u=t?.updating??!1;return(0,o.useEffect)(()=>{if(!e)return;let t=!0,r=()=>e.status().then(e=>{t&&(n(e),l(void 0))},e=>t&&l(e));r();let i=setInterval(()=>void r(),HSe(u));return()=>{t=!1,clearInterval(i)}},[e,u]),{status:t,update:(0,o.useCallback)(async()=>{e&&(i(!0),s(void 0),await e.update().then(n,s),i(!1))},[e]),requesting:r,error:a,checkError:c}},Q9=({client:e})=>{let{status:t,update:n,requesting:r,error:i,checkError:a}=YSe(e),[s,c]=(0,o.useState)(!1);return!t||!s&&!VSe(t)?null:(0,V.jsxs)(V.Fragment,{children:[(0,V.jsxs)(U,{size:`sm`,variant:`ghost`,"aria-label":`Update available`,title:`Update available`,onClick:()=>c(!0),className:`max-md:size-9 max-md:p-0`,children:[(0,V.jsx)(Ee,{className:`size-3.5 text-primary`}),(0,V.jsx)(`span`,{className:`max-md:sr-only`,children:`Update`})]}),s&&(0,V.jsx)(qSe,{status:t,requesting:r,error:i,checkError:a,onUpdate:()=>void n(),onClose:()=>c(!1)})]})},XSe=({url:e})=>(0,V.jsx)(Q9,{client:JSe(e)}),ZSe=({url:e,client:t})=>t?(0,V.jsx)(Q9,{client:t}):(0,V.jsx)(XSe,{url:e}),QSe=({signIn:e,onStop:t})=>{let[n,r]=(0,o.useState)(!1),[i,a]=(0,o.useState)(),s=async()=>{r(!0),a(void 0);try{await t()}catch(e){if(!(e instanceof pc))throw e;a(xd(e)),r(!1)}};return(0,V.jsxs)(`div`,{role:`region`,"aria-label":`Staff session`,className:`flex flex-wrap items-center gap-x-3 gap-y-2 border-b border-warning/40 bg-warning-soft px-4 py-2 text-warning-text`,children:[(0,V.jsx)(uee,{"aria-hidden":!0,className:`size-4 shrink-0`}),(0,V.jsxs)(`p`,{className:`min-w-64 flex-1 break-words`,children:[(0,V.jsx)(`span`,{className:`font-semibold`,children:e.staffName??e.staff}),` is signed in as `,(0,V.jsx)(`span`,{className:`font-semibold`,children:e.user}),` until`,` `,df(Date.parse(e.expiresAt)),`. Reason: `,e.reason]}),i&&(0,V.jsx)(`p`,{role:`alert`,className:`text-xs font-medium text-danger-text`,children:i}),(0,V.jsx)(U,{size:`sm`,loading:n,onClick:()=>void s(),children:`Stop staff session`})]})},$Se=(e,t,n)=>({filter:n.filter??``,orderBy:n.orderBy??jS(e,t),pageSize:n.limit??3,fields:[...new Set([...e.primaryKey,Fx(e,t),n.status])]}),eCe=(e,t,n,r,i,a)=>r.map(r=>{let o=Ao(zx(e,r)),s=String(r[n.status]??``);return{id:o,label:Ix(e,t,r,o),href:ps({kind:`record`,resource:e.name,key:o},i),status:e.fields[n.status]?.type===`enum`&&s?rs(s,t.fields[n.status]?.valueLabels):s,tone:n.tones[s]??`neutral`,pulse:n.pulse?.includes(s)??!1,active:o===a}}),tCe=(e,t,n,r,i)=>{let a=n.find(t=>Ao(zx(e,t))===r);return a!==void 0&&t.some(e=>!Object.is(a[e],i[e]))},$9=({model:e,request:t})=>W.navRecent(e.name,t.filter,t.orderBy,t.pageSize),nCe=e=>{let t=Gp();(0,o.useEffect)(()=>t.getQueryCache().subscribe(n=>{if(n.type!==`updated`||n.action.type!==`success`)return;let[r,i,a]=n.query.queryKey,o=n.action.data?.record;if(r===`record`&&typeof a==`string`&&o)for(let n of e){if(n.model.name!==i)continue;let e=t.getQueryData($9(n));e&&tCe(n.model,n.request.fields,e.items,a,o)&&t.invalidateQueries({queryKey:$9(n),exact:!0})}}),[t,e])},rCe=(e,t,n)=>{let r=G(),i=(0,o.useMemo)(()=>{let t=k9(e);return Object.values(e.views).flatMap(n=>{let r=e.resources[n.resource],i=n.nav?.recent;return r&&i&&!n.nav?.hidden&&!t.has(r.name)?[{model:r,view:n,recent:i,request:$Se(r,n,i)}]:[]})},[e]);nCe(i);let a=fh({queries:i.map(e=>({queryKey:$9(e),queryFn:()=>r.list(e.model.name,e.request)}))});return Object.fromEntries(i.map(({model:e,view:r,recent:i},o)=>{let s=a[o];if(s.isPending)return[e.name,{state:`loading`}];if(s.isError)return[e.name,{state:`error`}];let c=n.resource===e.name?n.key:void 0;return[e.name,{state:`ready`,records:eCe(e,r,i,s.data.items,t,c)}]}))},iCe=e=>e?.kind===`page`?e.page:e?.resource,aCe=e=>e?.kind===`record`?e:void 0,oCe=({workspace:e,sidebarMode:t,assistant:n,runtime:r})=>{let i=J(),{state:a,session:s,signOut:c,stopStaffSession:l,organizations:u}=H(),d=Ih();if(a.kind!==`signed-in`&&a.kind!==`visitor`)throw Error(`The shell is only rendered for a signed-in user or a visitor`);let f=a.kind===`signed-in`?a.user:void 0,p=a.kind===`signed-in`?a.staff:void 0,{path:m,params:h,basePath:g}=wh(),{address:_,go:v,open:y}=XS(),b=iCe(_),x=aCe(_),S=BSe(),C=xw(),w=A9(i,g,rCe(i,g,{resource:b,key:x?.key})),T=Object.keys(i.pages)[0],E=Object.keys(i.resources)[0],D=_?.kind===`page`?i.pages[_.page]:void 0;(0,o.useEffect)(()=>{m===`/`&&(T?v({kind:`page`,page:T},{replace:!0}):E&&v({kind:`list`,resource:E},{replace:!0}))},[m,T,E,v]);let O=_?.kind===`page`?void 0:_?.resource,k=O?GS(i,O):void 0,A=O?i.views[O]:void 0,j=w.find(e=>e.items.some(e=>e.id===b)),M=O?i.resources[O]:void 0,N=Cg(x?.resource??``,x?.key??``,!!(M&&x)),ee=M&&x&&N.data?Ix(M,A,N.data.record,x.key):void 0,P=!!x&&(N.isLoading||k?.state===`loading`),{shell:te}=SC(),F=te?.actions,ne=te?.rightPanel,[re,ie]=(0,o.useState)(!1),I=i.assistant?.url,ae=I&&(0,V.jsx)($w,{open:re,onToggle:()=>ie(!re)}),oe=I&&re&&(0,V.jsx)(nT,{url:I,client:n,page:h.size>0?`${m}?${h}`:m,onClose:()=>ie(!1)}),se=i.errorReporting;(0,o.useEffect)(()=>{se&&jre(se)},[se]);let L=i.runtime?.url,ce=L&&(0,V.jsx)(ZSe,{url:L,client:r}),le=sxe((0,o.useCallback)(()=>T9(g),[g]),!!f),ue=f&&oxe(f,le.current),de=ue?bg(ue):!1,fe=dxe(),pe=Xbe(!!(u&&f)),me=pe.current,he=!!u&&me!==void 0&&!me.organization,ge=u&&f?wre[m]:void 0,_e=f?m===`/-/account`?`Sign-in & security`:m===`/-/sign-in-policy`?`Sign-in policy`:ge:void 0,ve=A?.names?.plural??(O&&K(O)),ye=_e?[_e]:cT({basePath:g,address:_,group:j?.label,page:D,resourceLabel:ve,recordTitle:ee,recordLoading:P});rx(nx(tx({address:_,page:D,accountPage:_e,resourceLabel:ve,singular:A?.names?.singular??(O&&K(O)),recordTitle:ee,recordLoading:P}),i.appName));let be=f&&m===`/-/account`?(0,V.jsx)(jp,{email:f.email}):f&&m===`/-/sign-in-policy`?de?(0,V.jsx)(Up,{}):(0,V.jsx)(KS,{title:`Admins only`,children:`Only an admin can change how people sign in.`}):ge&&m===`/-/organization`?(0,V.jsx)(txe,{current:me,basePath:g,onChanged:pe.reload}):ge&&(m===`/-/organization/members`||m===`/-/organization/invitations`)?Uh(me)?m===`/-/organization/members`?(0,V.jsx)(Kbe,{current:me}):(0,V.jsx)(Ybe,{current:me}):(0,V.jsx)(KS,{title:`Owners and admins only`,children:`Only the organization's owners and admins manage its members.`}):ge&&m===`/-/organizations`||he?(0,V.jsx)(axe,{state:pe,basePath:g}):_?_.kind===`page`?D?(0,V.jsx)(Z5,{name:D.name},D.name):(0,V.jsxs)(KS,{title:`Not found`,children:[`There is no page called `,_.page,`.`]}):k&&k.state!==`ready`?(0,V.jsx)(MSe,{status:k}):_.kind===`create`?(0,V.jsx)(yve,{resource:_.resource,values:_.values},_.resource):_.kind===`record`?(0,V.jsx)(kSe,{resource:_.resource,recordKey:_.key},`${_.resource}/${_.key}`):(0,V.jsx)(Wbe,{address:_},_.resource):m===`/`?(0,V.jsx)(KS,{title:`Choose a resource`,children:`Pick one from the sidebar.`}):(0,V.jsx)(KS,{title:`Not found`,children:`There is nothing at this address.`}),xe=(0,V.jsx)(hd,{pageScroll:!0,sidebarMode:t??`text-small`,activeItem:b??``,breadcrumb:ye,user:ue&&Qre(ue),onSignOut:f&&(()=>void c()),signIn:f?void 0:d.link(),workspace:me?.organization?.name??e,appName:i.appName,logo:uxe,navGroups:w,bottomBar:sT(i,g,b),userMenu:[...cxe(i,g,b),...u&&f?Tre(g,m,me):[],...f?ar(g,m,de):[]],organizations:u&&{...me?.organization&&{current:{id:me.organization.id,name:me.organization.name}},others:pe.organizations.filter(e=>e.id!==me?.organization?.id),onSwitch:e=>void s.organizations.switchTo(e).then(()=>T9(g))},theme:{preference:C.preference,onChange:C.choose},roles:le.current?.active?{active:le.current.active,roles:le.current.roles,onSwitch:le.switchTo}:void 0,onNavigate:y,search:S.available?{placeholder:S.placeholder,text:S.text,onTextChange:S.setText,query:S.query,loading:S.loading,groups:S.groups,onSelect:y}:void 0,actions:(F||ce||ae)&&(0,V.jsxs)(V.Fragment,{children:[F&&(0,V.jsx)(Qh,{name:`shell.actions`,fallback:null,children:(0,V.jsx)(F,{})}),ce,ae]}),rightPanel:(ne||oe)&&(0,V.jsxs)(V.Fragment,{children:[ne&&(0,V.jsx)(Qh,{name:`shell.rightPanel`,fallback:null,children:(0,V.jsx)(ne,{})}),oe]}),children:be}),Se=de&&fe.length>0;return!p&&!Se?xe:(0,V.jsxs)(`div`,{className:`flex h-full min-h-0 flex-col`,children:[p&&(0,V.jsx)(QSe,{signIn:p,onStop:l}),Se&&(0,V.jsx)(pxe,{off:fe}),(0,V.jsx)(`div`,{className:`min-h-0 flex-1`,children:xe})]})},sCe=({baseUrl:e,client:t,sources:n,workspace:r,sidebarMode:i,ui:a,assistant:o,runtime:s})=>{let{state:c,session:l,markSignedOut:u}=H();return(0,V.jsx)(Sh,{baseUrl:e,client:t,sources:n,token:c.kind===`visitor`?void 0:l.token,onUnauthenticated:u,children:(0,V.jsx)(JS,{children:(0,V.jsx)($y,{children:(0,V.jsx)(fxe,{ui:a,children:(0,V.jsx)(oCe,{workspace:r,sidebarMode:i,assistant:o,runtime:s})})})})})},cCe=({baseUrl:e,client:t,ui:n,children:r})=>{let i=dw();return i?(0,V.jsx)(Sh,{baseUrl:e,client:t,children:(0,V.jsx)(xC.Provider,{value:n??{},children:(0,V.jsx)(lw,{name:i.name},i.name)})}):r},lCe=({auth:e,workspace:t,basePath:n,initialUrl:r,pluginLoader:i,...a})=>(0,V.jsx)(bw,{children:(0,V.jsx)(Fd,{session:e,children:(0,V.jsx)(Bne,{basePath:n,initialUrl:r,children:(0,V.jsx)(Kre,{...i&&{loader:i},children:(0,V.jsx)(cCe,{baseUrl:a.baseUrl,client:a.client,ui:a.ui,children:(0,V.jsx)(Xre,{workspace:t,children:(0,V.jsx)(sCe,{workspace:t,...a})})})})})})});export{G as $,Cw as A,eb as B,Nw as C,Ow as D,kw as E,ZS as F,Rre as G,xg as H,XS as I,qh as J,ig as K,BS as L,bC as M,yC as N,Ew as O,QS as P,Sh as Q,cx as R,Iw as S,jw as T,ug as U,Sg as V,dg as W,kh as X,Ah as Y,Oh as Z,Zw as _,L5 as a,ld as at,Uw as b,F_e as c,zu as ct,oE as d,B as dt,xh as et,aE as f,b as ft,Qw as g,dT as h,$5 as i,Cf as it,Sw as j,ww as k,C8 as l,Pu as lt,ST as m,B9 as n,wf as nt,J_e as o,sd as ot,jT as p,$h as q,z9 as r,U as rt,P_e as s,od as st,lCe as t,If as tt,iE as u,hu as ut,Yw as v,Mw as w,zw as x,qw as y,tb as z};
|