@malloy-publisher/sdk 0.8.4 → 0.9.0
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/{Dashboard-FD3-Af-_.cjs.js → Dashboard-ChyylkTD.cjs.js} +2 -2
- package/dist/{Dashboard-DnqWRijB.es.js → Dashboard-H1kJlDFo.es.js} +2 -2
- package/dist/{RenderedResult-CetSzFgW.cjs.js → RenderedResult-AJPMUkAD.cjs.js} +1 -1
- package/dist/{RenderedResult-6UKAHaAj.es.js → RenderedResult-BRgIgxWh.es.js} +2 -2
- package/dist/{ServerProvider-DgRFJ43L.es.js → ServerProvider-Boxrv6Ym.es.js} +1093 -1151
- package/dist/ServerProvider-CXrOKD6g.cjs.js +1 -0
- package/dist/builder/index.cjs.js +1 -1
- package/dist/builder/index.es.js +2 -2
- package/dist/client/api.d.ts +79 -1796
- package/dist/client/base.d.ts +0 -24
- package/dist/client/common.d.ts +4 -35
- package/dist/client/configuration.d.ts +24 -17
- package/dist/client/index.cjs.js +1 -1
- package/dist/client/index.es.js +1 -1
- package/dist/hooks/useQueryResult.d.ts +1 -1
- package/dist/index.cjs.js +1 -1
- package/dist/index.es.js +5 -5
- package/openapitools.json +1 -1
- package/package.json +13 -13
- package/src/components/Notebook/Notebook.served.spec.tsx +5 -1
- package/dist/ServerProvider-BsjJvkML.cjs.js +0 -1
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),v=require("@mui/material"),$=require("react"),u=require("./Dashboard-FD3-Af-_.cjs.js"),V=require("./ServerProvider-BsjJvkML.cjs.js"),Mn=require("@tanstack/react-query"),ua=require("@mui/system"),He=require("@mui/icons-material"),ht=require("./RenderedResult-CetSzFgW.cjs.js"),vn=require("react-router-dom");function Do(t){const i=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const h in t)if(h!=="default"){const a=Object.getOwnPropertyDescriptor(t,h);Object.defineProperty(i,h,a.get?a:{enumerable:!0,get:()=>t[h]})}}return i.default=t,Object.freeze(i)}const fe=Do($),Oo=u.createSvgIcon(n.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function mr({label:t,href:i,onClick:h}){const a=p=>{const c=p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||p.button!==0;i!==void 0&&c||(p.preventDefault(),h(p))};return n.jsxs(v.Link,{...i===void 0?{component:"button",type:"button"}:{href:i},onClick:a,underline:"none","aria-label":`Back to ${t}`,sx:{display:"inline-flex",alignItems:"center",gap:.5,cursor:"pointer",color:"text.secondary",fontSize:"0.875rem",mb:2,border:0,p:0,background:"none",font:"inherit","&:hover":{color:"primary.main"}},children:[n.jsx(Oo,{sx:{fontSize:18}}),"Back to ",t]})}function Eo(){const t=vn.useNavigate();return(i,h)=>{if(!h||!h.metaKey&&!h.ctrlKey&&!h.shiftKey&&h.button!==1){t(i);return}const a=new URL(i,window.location.href).href;(h.metaKey||h.ctrlKey||h.button===1||h.shiftKey)&&window.open(a,"_blank")}}const da=u.createSvgIcon(n.jsx("path",{d:"M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3z"})),Io="publisher:resize";function Fo(t){return typeof t=="object"&&t!==null&&t.type===Io&&typeof t.height=="number"}function ha(t){return t.replace(/\/api\/v0\/?$/,"")}function fa({server:t,environmentName:i,packageName:h,path:a}){const p=a.startsWith("public/")?a.slice(7):a;return`${ha(t)}/environments/${encodeURIComponent(i)}/packages/${encodeURIComponent(h)}/`+p}function No(t){try{const{environmentName:i,packageName:h,modelPath:a}=u.parseResourceUri(t);return!i||!h||!a?null:{environmentName:i,packageName:h,dataAppPath:a}}catch{return null}}function Ao({resourceUri:t}){const{server:i,apiClients:h}=V.useServer(),a=No(t),p=a?.environmentName??"",c=a?.packageName??"",l=a?.dataAppPath??"",f=$.useMemo(()=>fa({server:i,environmentName:p,packageName:c,path:l}),[i,p,c,l]),m=u.useQueryWithApiError({queryKey:["data-apps",p,c],queryFn:()=>h.dataApps.listDataApps(p,c),enabled:!!a}).data?.data?.find(w=>w.path===l),x=m?.title??l,S=m?.fit==="viewport",b=$.useRef(null),[g,k]=$.useState(120);return $.useEffect(()=>{if(S)return;function w(T){Fo(T.data)&&T.source===b.current?.contentWindow&&T.data.height>0&&k(Math.ceil(T.data.height))}return window.addEventListener("message",w),()=>window.removeEventListener("message",w)},[S]),a?n.jsxs(v.Box,{sx:{p:3,...S?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1200,mx:"auto"}},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[n.jsx(v.Typography,{variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em"},children:x}),n.jsx(v.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:V.MONO_FONT_FAMILY},children:l}),n.jsx(v.Box,{sx:{flex:1}}),n.jsx(v.Tooltip,{title:"Open standalone in new tab",children:n.jsx(v.IconButton,{size:"small",href:f,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:n.jsx(da,{fontSize:"small"})})})]}),n.jsx(v.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...S?{flex:1,minHeight:0}:{}},children:n.jsx("iframe",{ref:b,src:f,title:x,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:S?"100%":g,border:0}})})]}):n.jsxs(v.Box,{sx:{p:3,maxWidth:1200,mx:"auto"},children:[n.jsx(v.Typography,{variant:"h6",sx:{fontWeight:600},children:"Can't open data app"}),n.jsxs(v.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",n.jsx(v.Box,{component:"span",sx:{fontFamily:V.MONO_FONT_FAMILY,ml:1},children:t})]})]})}function ze({title:t,count:i,description:h,action:a,children:p}){const c=$.useId();return n.jsxs(v.Box,{component:"section","aria-labelledby":c,sx:{mb:4},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:h?0:1,minHeight:40},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[n.jsx(v.Typography,{id:c,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:t}),i!==void 0&&n.jsxs(v.Typography,{variant:"caption",color:"text.secondary",children:["(",i,")"]})]}),a]}),h&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:h}),n.jsx(v.Box,{children:p})]})}function $o({resourceUri:t}){const{environmentName:i}=u.parseResourceUri(t),{apiClients:h}=V.useServer(),[a,p]=$.useState(!1),c=90,{data:l,isSuccess:f,isError:d,error:m}=u.useQueryWithApiError({queryKey:["about",i],queryFn:()=>h.environments.getEnvironment(i,!1)}),x=l?.data?.readme||"",S=x.split(/\s+/),b=S.length>c,g=S.slice(0,c).join(" ");return n.jsxs(n.Fragment,{children:[!f&&!d&&n.jsx(u.Loading,{text:"Fetching About..."}),f&&x&&n.jsxs(ze,{title:"Readme",children:[n.jsx(u.Prose,{variant:"caption",children:a||!b?x:g}),b&&n.jsx(v.Box,{sx:{mt:1},children:n.jsx(u.SecondaryButton,{label:a?"Read less":"Read more",onClick:()=>p(!a)})})]}),d&&n.jsx(u.ApiErrorDisplay,{error:m,context:`${i} > About`})]})}function Ro(t={}){const{autoHideDuration:i=null,disableWindowBlurListener:h=!1,onClose:a,open:p,resumeHideDuration:c}=t,l=u.useTimeout();fe.useEffect(()=>{if(!p)return;function M(j){j.defaultPrevented||j.key==="Escape"&&a?.(j,"escapeKeyDown")}return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[p,a]);const f=u.useEventCallback((M,j)=>{a?.(M,j)}),d=u.useEventCallback(M=>{!a||M==null||l.start(M,()=>{f(null,"timeout")})});fe.useEffect(()=>(p&&d(i),l.clear),[p,i,d,l]);const m=M=>{a?.(M,"clickaway")},x=l.clear,S=fe.useCallback(()=>{i!=null&&d(c??i*.5)},[i,c,d]),b=M=>j=>{const I=M.onBlur;I?.(j),S()},g=M=>j=>{const I=M.onFocus;I?.(j),x()},k=M=>j=>{const I=M.onMouseEnter;I?.(j),x()},w=M=>j=>{const I=M.onMouseLeave;I?.(j),S()};return fe.useEffect(()=>{if(!h&&p)return window.addEventListener("focus",S),window.addEventListener("blur",x),()=>{window.removeEventListener("focus",S),window.removeEventListener("blur",x)}},[h,p,S,x]),{getRootProps:(M={})=>{const j={...u.extractEventHandlers(t),...u.extractEventHandlers(M)};return{role:"presentation",...M,...j,onBlur:b(j),onFocus:g(j),onMouseEnter:k(j),onMouseLeave:w(j)}},onClickAway:m}}function As(t){return t.substring(2).toLowerCase()}function Lo(t,i){return i.documentElement.clientWidth<t.clientX||i.documentElement.clientHeight<t.clientY}function _o(t){const{children:i,disableReactTree:h=!1,mouseEvent:a="onClick",onClickAway:p,touchEvent:c="onTouchEnd"}=t,l=fe.useRef(!1),f=fe.useRef(null),d=fe.useRef(!1),m=fe.useRef(!1);fe.useEffect(()=>(setTimeout(()=>{d.current=!0},0),()=>{d.current=!1}),[]);const x=u.useForkRef(u.getReactElementRef(i),f),S=u.useEventCallback(k=>{const w=m.current;m.current=!1;const T=u.ownerDocument(f.current);if(!d.current||!f.current||"clientX"in k&&Lo(k,T))return;if(l.current){l.current=!1;return}let M;k.composedPath?M=k.composedPath().includes(f.current):M=!T.documentElement.contains(k.target)||f.current.contains(k.target),!M&&(h||!w)&&p(k)}),b=k=>w=>{m.current=!0;const T=i.props[k];T&&T(w)},g={ref:x};return c!==!1&&(g[c]=b(c)),fe.useEffect(()=>{if(c!==!1){const k=As(c),w=u.ownerDocument(f.current),T=()=>{l.current=!0};return w.addEventListener(k,S),w.addEventListener("touchmove",T),()=>{w.removeEventListener(k,S),w.removeEventListener("touchmove",T)}}},[S,c]),a!==!1&&(g[a]=b(a)),fe.useEffect(()=>{if(a!==!1){const k=As(a),w=u.ownerDocument(f.current);return w.addEventListener(k,S),()=>{w.removeEventListener(k,S)}}},[S,a]),fe.cloneElement(i,g)}function Po(t){return u.generateUtilityClass("MuiSnackbarContent",t)}u.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const qo=t=>{const{classes:i}=t,h={root:["root"],action:["action"],message:["message"]};return u.composeClasses(h,Po,i)},Wo=u.styled(u.Paper,{name:"MuiSnackbarContent",slot:"Root"})(u.memoTheme(({theme:t})=>{const i=t.palette.mode==="light"?.8:.98;return{...t.typography.body2,color:t.vars?t.vars.palette.SnackbarContent.color:t.palette.getContrastText(u.emphasize(t.palette.background.default,i)),backgroundColor:t.vars?t.vars.palette.SnackbarContent.bg:u.emphasize(t.palette.background.default,i),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[t.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),zo=u.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),Ho=u.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),Vo=fe.forwardRef(function(i,h){const a=u.useDefaultProps({props:i,name:"MuiSnackbarContent"}),{action:p,className:c,message:l,role:f="alert",...d}=a,m=a,x=qo(m);return n.jsxs(Wo,{role:f,elevation:6,className:u.clsx(x.root,c),ownerState:m,ref:h,...d,children:[n.jsx(zo,{className:x.message,ownerState:m,children:l}),p?n.jsx(Ho,{className:x.action,ownerState:m,children:p}):null]})});function Uo(t){return u.generateUtilityClass("MuiSnackbar",t)}u.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Bo=t=>{const{classes:i,anchorOrigin:h}=t,a={root:["root",`anchorOrigin${u.capitalize(h.vertical)}${u.capitalize(h.horizontal)}`]};return u.composeClasses(a,Uo,i)},Go=u.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(t,i)=>{const{ownerState:h}=t;return[i.root,i[`anchorOrigin${u.capitalize(h.anchorOrigin.vertical)}${u.capitalize(h.anchorOrigin.horizontal)}`]]}})(u.memoTheme(({theme:t})=>({zIndex:(t.vars||t).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:i})=>i.anchorOrigin.vertical==="top",style:{top:8,[t.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:i})=>i.anchorOrigin.vertical!=="top",style:{bottom:8,[t.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:i})=>i.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[t.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:i})=>i.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[t.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:i})=>i.anchorOrigin.horizontal==="center",style:{[t.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Yo=fe.forwardRef(function(i,h){const a=u.useDefaultProps({props:i,name:"MuiSnackbar"}),p=u.useTheme(),c={enter:p.transitions.duration.enteringScreen,exit:p.transitions.duration.leavingScreen},{action:l,anchorOrigin:{vertical:f,horizontal:d}={vertical:"bottom",horizontal:"left"},autoHideDuration:m=null,children:x,className:S,ClickAwayListenerProps:b,ContentProps:g,disableWindowBlurListener:k=!1,message:w,onBlur:T,onClose:M,onFocus:j,onMouseEnter:I,onMouseLeave:E,open:L,resumeHideDuration:H,slots:_={},slotProps:Y={},TransitionComponent:N,transitionDuration:q=c,TransitionProps:{onEnter:B,onExited:A,...P}={},...G}=a,K={...a,anchorOrigin:{vertical:f,horizontal:d},autoHideDuration:m,disableWindowBlurListener:k,TransitionComponent:N,transitionDuration:q},X=Bo(K),{getRootProps:J,onClickAway:U}=Ro({...K}),[te,W]=fe.useState(!0),Q=be=>{W(!0),A&&A(be)},R=(be,he)=>{W(!1),B&&B(be,he)},Z={slots:{transition:N,..._},slotProps:{content:g,clickAwayListener:b,transition:P,...Y}},[de,ae]=u.useSlot("root",{ref:h,className:[X.root,S],elementType:Go,getSlotProps:J,externalForwardedProps:{...Z,...G},ownerState:K}),[ce,{ownerState:xe,...we}]=u.useSlot("clickAwayListener",{elementType:_o,externalForwardedProps:Z,getSlotProps:be=>({onClickAway:(...he)=>{const ye=he[0];be.onClickAway?.(...he),!ye?.defaultMuiPrevented&&U(...he)}}),ownerState:K}),[Me,Ne]=u.useSlot("content",{elementType:Vo,shouldForwardComponentProp:!0,externalForwardedProps:Z,additionalProps:{message:w,action:l},ownerState:K}),[Oe,me]=u.useSlot("transition",{elementType:u.Grow,externalForwardedProps:Z,getSlotProps:be=>({onEnter:(...he)=>{be.onEnter?.(...he),R(...he)},onExited:(...he)=>{be.onExited?.(...he),Q(...he)}}),additionalProps:{appear:!0,in:L,timeout:q,direction:f==="top"?"down":"up"},ownerState:K});return!L&&te?null:n.jsx(ce,{...we,..._.clickAwayListener&&{ownerState:xe},children:n.jsx(de,{...ae,children:n.jsx(Oe,{...me,children:x||n.jsx(Me,{...Ne})})})})});let ir;function Zo(t){ir=t}function $s(t){if(ir)try{ir(t)}catch{}}function Ke(t,i,h){return(async a=>{const p=Date.now();try{const c=await h(a);return $s({type:"console.mutation",resource:t,action:i,ok:!0,durationMs:Date.now()-p}),c}catch(c){throw $s({type:"console.mutation",resource:t,action:i,ok:!1,durationMs:Date.now()-p,reason:c instanceof Error?c.message:"An unknown error occurred"}),c}})}function Dt({mutationFn:t,success:i,invalidates:h,closeDialog:a,resource:p,action:c}){const l=Mn.useQueryClient(),[f,d]=$.useState(""),m=u.useMutationWithApiError({mutationFn:Ke(p,c,t),onSuccess(){a();for(const x of h)l.invalidateQueries({queryKey:x});d(i)},onError(x){d(x instanceof Error?x.message:"An unknown error occurred")}});return{mutate:m.mutate,isPending:m.isPending,notice:n.jsx(Yo,{open:f!=="",autoHideDuration:6e3,onClose:()=>d(""),message:f})}}const ma="https://docs.malloydata.dev/documentation",Zn=`${ma}/user_guides/publishing`,Tt="https://github.com/malloydata/publisher/blob/main/docs",Xe={docsHome:`${ma}/`,publishing:`${Zn}/publishing`,explorer:`${Zn}/explorer`,mcpAgents:`${Zn}/mcp_agents`,surfaces:`${Tt}/choosing-a-surface.md`,dashboards:`${Tt}/dashboards.md`,dataApps:`${Tt}/html-data-apps.md`,givens:`${Tt}/givens.md`,materialization:`${Tt}/materialization.md`,connections:`${Tt}/connections.md`};function Xo({resourceUri:t}){const[i,h]=$.useState(!1),{apiClients:a}=V.useServer(),{environmentName:p}=u.parseResourceUri(t),c=Dt({mutationFn(f){return a.packages.createPackage(p,{name:f.name,description:f.description,location:f.location})},success:"Package created",invalidates:[["packages",p]],closeDialog:()=>h(!1),resource:"package",action:"create"}),l=f=>{f.preventDefault();const d=new FormData(f.currentTarget),m=d.get("name")?.toString(),x=d.get("description")?.toString(),S=d.get("location")?.toString();c.mutate({name:m,description:x,location:S})};return n.jsxs(n.Fragment,{children:[n.jsx(u.AddButton,{label:"Package",onClick:()=>h(!0)}),n.jsx(u.AppDialog,{open:i,onClose:()=>h(!1),title:"New package",description:n.jsxs(n.Fragment,{children:["A package is a directory of Malloy models and their data. Give its location as a GitHub, S3 or GCS URL, or an absolute path the server can read; see the"," ",n.jsx(v.Box,{component:"a",href:Xe.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:n.jsxs(n.Fragment,{children:[n.jsx(v.Button,{disabled:c.isPending,onClick:()=>h(!1),children:"Cancel"}),n.jsx(v.Button,{type:"submit",form:"package-form",variant:"contained",loading:c.isPending,children:"Create package"})]}),children:n.jsx("form",{onSubmit:l,id:"package-form",children:n.jsxs(v.Stack,{sx:{gap:2},children:[n.jsx(v.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(v.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(v.TextField,{id:"location",name:"location",label:"Location",type:"text",placeholder:"e.g. s3://my-bucket/my-package.zip",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),c.notice]})}const Ko=u.createSvgIcon(n.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function jn({icon:t,tint:i,label:h,mono:a,description:p,rightLabel:c,trailingAction:l,onClick:f,ariaLabel:d}){const m=!!f,x=S=>{f&&(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),f(S))};return n.jsxs(v.Box,{onClick:f,onKeyDown:m?x:void 0,role:m?"button":void 0,tabIndex:m?0:void 0,"aria-label":d,sx:S=>({display:"flex",alignItems:"center",gap:1.5,py:1,px:1,mx:-1,cursor:m?"pointer":"default",borderRadius:1.5,transition:"background-color 0.1s","&:hover":m?{backgroundColor:S.palette.mode==="dark"?"rgba(255, 255, 255, 0.08)":"grey.100"}:void 0,"&:focus-visible":m?{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}:void 0}),children:[n.jsx(v.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:i,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t}),n.jsxs(v.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[n.jsx(v.Typography,{variant:"body2",sx:{...a?{fontFamily:V.MONO_FONT_FAMILY}:{},flexShrink:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:h}),p&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p})]}),c&&n.jsx(v.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:c}),l&&n.jsx(v.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:l})]})}const pa=u.createSvgIcon(n.jsx("path",{d:"M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM19 4h-3.5l-1-1h-5l-1 1H5v2h14z"})),Qo=u.generateUtilityClasses("MuiBox",["root"]),Jo=u.createTheme(),ge=ua.createBox({themeId:u.THEME_ID,defaultTheme:Jo,defaultClassName:Qo.root,generateClassName:u.ClassNameGenerator.generate}),Dn=ua.createStack({createStyledComponent:u.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:t=>u.useDefaultProps({props:t,name:"MuiStack"})}),Rs=u.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function el(t){return u.generateUtilityClass("MuiListItemIcon",t)}const Ls=u.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),tl=t=>{const{alignItems:i,classes:h}=t,a={root:["root",i==="flex-start"&&"alignItemsFlexStart"]};return u.composeClasses(a,el,h)},nl=u.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(t,i)=>{const{ownerState:h}=t;return[i.root,h.alignItems==="flex-start"&&i.alignItemsFlexStart]}})(u.memoTheme(({theme:t})=>({minWidth:56,color:(t.vars||t).palette.action.active,flexShrink:0,display:"inline-flex",variants:[{props:{alignItems:"flex-start"},style:{marginTop:8}}]}))),pr=fe.forwardRef(function(i,h){const a=u.useDefaultProps({props:i,name:"MuiListItemIcon"}),{className:p,...c}=a,l=fe.useContext(u.ListContext),f={...a,alignItems:l.alignItems},d=tl(f);return n.jsx(nl,{className:u.clsx(d.root,p),ownerState:f,ref:h,...c})});function rl(t){return u.generateUtilityClass("MuiListItemText",t)}const jt=u.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),sl=t=>{const{classes:i,inset:h,primary:a,secondary:p,dense:c}=t,l={root:["root",h&&"inset",c&&"dense",a&&p&&"multiline"],primary:["primary"],secondary:["secondary"]};return u.composeClasses(l,rl,i)},al=u.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(t,i)=>{const{ownerState:h}=t;return[{[`& .${jt.primary}`]:i.primary},{[`& .${jt.secondary}`]:i.secondary},i.root,h.inset&&i.inset,h.primary&&h.secondary&&i.multiline,h.dense&&i.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${u.typographyClasses.root}:where(& .${jt.primary})`]:{display:"block"},[`.${u.typographyClasses.root}:where(& .${jt.secondary})`]:{display:"block"},variants:[{props:({ownerState:t})=>t.primary&&t.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:t})=>t.inset,style:{paddingLeft:56}}]}),yr=fe.forwardRef(function(i,h){const a=u.useDefaultProps({props:i,name:"MuiListItemText"}),{children:p,className:c,disableTypography:l=!1,inset:f=!1,primary:d,primaryTypographyProps:m,secondary:x,secondaryTypographyProps:S,slots:b={},slotProps:g={},...k}=a,{dense:w}=fe.useContext(u.ListContext);let T=d??p,M=x;const j={...a,disableTypography:l,inset:f,primary:!!T,secondary:!!M,dense:w},I=sl(j),E={slots:b,slotProps:{primary:m,secondary:S,...g}},[L,H]=u.useSlot("root",{className:u.clsx(I.root,c),elementType:al,externalForwardedProps:{...E,...k},ownerState:j,ref:h}),[_,Y]=u.useSlot("primary",{className:I.primary,elementType:u.Typography,externalForwardedProps:E,ownerState:j}),[N,q]=u.useSlot("secondary",{className:I.secondary,elementType:u.Typography,externalForwardedProps:E,ownerState:j});return T!=null&&T.type!==u.Typography&&!l&&(T=n.jsx(_,{variant:w?"body2":"body1",component:Y?.variant?void 0:"span",...Y,children:T})),M!=null&&M.type!==u.Typography&&!l&&(M=n.jsx(N,{variant:"body2",color:"textSecondary",...q,children:M})),n.jsxs(L,{...H,children:[T,M]})});function il(t){return u.generateUtilityClass("MuiMenuItem",t)}const zt=u.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),ol=(t,i)=>{const{ownerState:h}=t;return[i.root,h.dense&&i.dense,h.divider&&i.divider,!h.disableGutters&&i.gutters]},ll=t=>{const{disabled:i,dense:h,divider:a,disableGutters:p,selected:c,classes:l}=t,f={root:["root",h&&"dense",i&&"disabled",!p&&"gutters",a&&"divider",c&&"selected"]},d=u.composeClasses(f,il,l);return{...l,...d}},cl=u.styled(u.ButtonBase,{shouldForwardProp:t=>u.rootShouldForwardProp(t)||t==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:ol})(u.memoTheme(({theme:t})=>({...t.typography.body1,display:"flex",justifyContent:"flex-start",alignItems:"center",position:"relative",textDecoration:"none",minHeight:48,paddingTop:6,paddingBottom:6,boxSizing:"border-box",whiteSpace:"nowrap","&:hover":{textDecoration:"none",backgroundColor:(t.vars||t).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${zt.selected}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,(t.vars||t).palette.action.selectedOpacity),[`&.${zt.focusVisible}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,`${(t.vars||t).palette.action.selectedOpacity} + ${(t.vars||t).palette.action.focusOpacity}`)}},[`&.${zt.selected}:hover`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,`${(t.vars||t).palette.action.selectedOpacity} + ${(t.vars||t).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:t.alpha((t.vars||t).palette.primary.main,(t.vars||t).palette.action.selectedOpacity)}},[`&.${zt.focusVisible}`]:{backgroundColor:(t.vars||t).palette.action.focus},[`&.${zt.disabled}`]:{opacity:(t.vars||t).palette.action.disabledOpacity},[`& + .${Rs.root}`]:{marginTop:t.spacing(1),marginBottom:t.spacing(1)},[`& + .${Rs.inset}`]:{marginLeft:52},[`& .${jt.root}`]:{marginTop:0,marginBottom:0},[`& .${jt.inset}`]:{paddingLeft:36},[`& .${Ls.root}`]:{minWidth:36},variants:[{props:({ownerState:i})=>!i.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:i})=>i.divider,style:{borderBottom:`1px solid ${(t.vars||t).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:i})=>!i.dense,style:{[t.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:i})=>i.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...t.typography.body2,[`& .${Ls.root} svg`]:{fontSize:"1.25rem"}}}]}))),ke=fe.forwardRef(function(i,h){const a=u.useDefaultProps({props:i,name:"MuiMenuItem"}),{autoFocus:p=!1,component:c="li",dense:l=!1,divider:f=!1,disableGutters:d=!1,focusVisibleClassName:m,role:x="menuitem",tabIndex:S,className:b,...g}=a,k=fe.useContext(u.ListContext),w=fe.useMemo(()=>({dense:l||k.dense||!1,disableGutters:d}),[k.dense,l,d]),T=fe.useRef(null);u.useEnhancedEffect(()=>{p&&T.current&&T.current.focus()},[p]);const M={...a,dense:w.dense,divider:f,disableGutters:d},j=ll(a),I=u.useForkRef(T,h);let E;return a.disabled||(E=S!==void 0?S:-1),n.jsx(u.ListContext.Provider,{value:w,children:n.jsx(cl,{ref:I,role:x,tabIndex:E,component:c,focusVisibleClassName:u.clsx(j.focusVisible,m),className:u.clsx(j.root,b),...g,ownerState:M,classes:j})})}),Qe={postgres:[{label:"Host",name:"host",type:"text",required:!1},{label:"Port",name:"port",type:"number",required:!1},{label:"Database Name",name:"databaseName",type:"text",required:!1},{label:"User Name",name:"userName",type:"text",required:!1},{label:"Password",name:"password",type:"password",required:!1},{label:"Connection String",name:"connectionString",type:"text",required:!1}],bigquery:[{label:"Project ID",name:"defaultProjectId",type:"text",required:!1},{label:"Billing Project ID",name:"billingProjectId",type:"text",required:!1},{label:"Location",name:"location",type:"text",required:!1},{label:"Service Account Key JSON",name:"serviceAccountKeyJson",type:"text",required:!0},{label:"Maximum Bytes Billed",name:"maximumBytesBilled",type:"text",required:!1},{label:"Query Timeout Milliseconds",name:"queryTimeoutMilliseconds",type:"text",required:!1}],snowflake:[{label:"Account",name:"account",type:"text",required:!0},{label:"Username",name:"username",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Role",name:"role",type:"text",required:!1},{label:"Warehouse",name:"warehouse",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"Response Timeout Milliseconds",name:"responseTimeoutMilliseconds",type:"text",required:!1},{label:"Private Key",name:"privateKey",type:"password",required:!1},{label:"Private Key Passphrase",name:"privateKeyPass",type:"password",required:!1}],trino:[{label:"Server",name:"server",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!1},{label:"Catalog",name:"catalog",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Peaka Key",name:"peakaKey",type:"password",required:!1}],databricks:[{label:"Host",name:"host",type:"text",required:!0},{label:"HTTP Path",name:"path",type:"text",required:!0},{label:"Access Token",name:"token",type:"password",required:!1},{label:"OAuth Client ID",name:"oauthClientId",type:"text",required:!1},{label:"OAuth Client Secret",name:"oauthClientSecret",type:"password",required:!1},{label:"Default Catalog",name:"defaultCatalog",type:"text",required:!1},{label:"Default Schema",name:"defaultSchema",type:"text",required:!1}],mysql:[{label:"Host",name:"host",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!0},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!0},{label:"Database",name:"database",type:"text",required:!0}],duckdb:[],motherduck:[{label:"Access Token",name:"accessToken",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1}],ducklake:[],publisher:[]},Jt={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},ya=Object.values(V.ConnectionTypeEnum).filter(t=>t!==V.ConnectionTypeEnum.Publisher),or={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},nn=[{label:"Credential Provider",name:"provider",type:"text",required:!1,selectOptions:[{label:"Access key pair",value:"config"},{label:"Host credential chain",value:"credential_chain"}]},{label:"Access Key ID",name:"accessKeyId",type:"text",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Secret Access Key",name:"secretAccessKey",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Credential Chain",name:"chain",type:"text",required:!1,visibleWhen:{field:"provider",value:"credential_chain"}},{label:"Region",name:"region",type:"text",required:!1},{label:"Endpoint",name:"endpoint",type:"text",required:!1},{label:"Session Token",name:"sessionToken",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}}],rn=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],ul=[{label:"Auth Type",name:"authType",type:"text",required:!0,selectOptions:[{label:"SAS Token",value:"sas_token"},{label:"Service Principal (SPN)",value:"service_principal"}]},{label:"SAS URL (e.g. https://account.blob.core.windows.net/container/file.parquet?sp=r&st=...)",name:"sasUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"sas_token"}},{label:"Tenant ID",name:"tenantId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client ID",name:"clientId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client Secret",name:"clientSecret",type:"password",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Account Name",name:"accountName",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"File URL (e.g. abfss://container/path/file.parquet)",name:"fileUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}}];function kn(t){return t==="postgres"||t==="bigquery"||t==="snowflake"?Qe[t]||[]:t==="s3"?nn:t==="gcs"?rn:t==="azure"?ul:[]}function dl({onSubmit:t,isSubmitting:i}){const[h,a]=$.useState(!1),[p,c]=$.useState("postgres"),[l,f]=$.useState([]),[d,m]=$.useState("postgres"),[x,S]=$.useState("s3"),[b,g]=$.useState("config"),k=()=>{a(!0)},w=()=>{a(!1),f([]),c("postgres"),m("postgres"),S("s3"),g("config")},T=async E=>{E.preventDefault();const L=new FormData(E.currentTarget),H=L.get("name")?.toString(),_=L.get("type")?.toString(),Y=Qe[_];if(!H)throw new Error("Name is required");if(!_)throw new Error("Type is required");let N;if(_==="ducklake"){const q={};if(d==="postgres"){const P=Qe.postgres,G={};if(P.forEach(K=>{const X=L.get(`ducklake_pg_${K.name}`)?.toString();X&&(G[K.name]=X)}),Object.keys(G).length===0)throw new Error("DuckLake requires catalog connection");q.postgresConnection=G}const B=L.get("ducklake_bucketUrl")?.toString();if(!B)throw new Error("DuckLake requires a bucket URL");const A={bucketUrl:B};if(x==="s3"){const P={};if(nn.forEach(G=>{const K=L.get(`ducklake_s3_${G.name}`)?.toString();K&&(P[G.name]=K)}),P.provider==="credential_chain")delete P.accessKeyId,delete P.secretAccessKey,delete P.sessionToken;else{if(delete P.chain,!P.accessKeyId)throw new Error("S3 Access Key ID is required");if(!P.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(P).length>0&&(A.s3Connection=P)}else if(x==="gcs"){const P={};if(rn.forEach(G=>{const K=L.get(`ducklake_gcs_${G.name}`)?.toString();K&&(P[G.name]=K)}),!P.keyId)throw new Error("GCS Key ID is required");if(!P.secret)throw new Error("GCS Secret is required");Object.keys(P).length>0&&(A.gcsConnection=P)}N={name:H,type:_,ducklakeConnection:{catalog:q,storage:A}}}else if(_==="duckdb"){if(l.length===0)throw new Error("DuckDB connection must have at least one attached database");const q=l.map((B,A)=>{const P=B.dbType,G=L.get(`attachedDb_${A}_name`)?.toString();if(!G)throw new Error(`Attached database at index ${A} must have a name`);const K={name:G,type:P},X=kn(P);if(X&&X.length>0){const J={};if(X.forEach(te=>{const W=L.get(`attachedDb_${A}_${te.name}`)?.toString();W&&(J[te.name]=W)}),P==="s3"){if(J.provider==="credential_chain")delete J.accessKeyId,delete J.secretAccessKey,delete J.sessionToken;else if(delete J.chain,!J.accessKeyId||!J.secretAccessKey)throw new Error(`Attached database "${G}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const U=or[P];U&&(K[U]=J)}return K});N={name:H,type:_,duckdbConnection:{attachedDatabases:q}}}else{const q={};if(Y.forEach(B=>{const A=L.get(B.name)?.toString();A&&(q[B.name]=A)}),_==="postgres"){if(!!!q.connectionString?.trim()){const A=["host","port","databaseName","userName","password"];for(const P of A)if(!q[P])throw new Error(`${Y.find(G=>G.name===P)?.label||P} is required`)}}else if(_==="bigquery"){if(!q.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if(_==="snowflake"){if(!q.account)throw new Error("Account is required");if(!q.username)throw new Error("Username is required");if(!q.warehouse)throw new Error("Warehouse is required");if(!q.password&&!q.privateKey)throw new Error("Either password or private key is required")}else if(_==="trino"){if(!q.server)throw new Error("Server is required");if(!q.user)throw new Error("User is required");if(q.server.trim().startsWith("https://")&&!q.password&&!q.peakaKey)throw new Error("Password is required for HTTPS connections (or use Peaka Key)")}else if(_==="mysql"){const B=["host","port","database","user","password"];for(const A of B)if(!q[A])throw new Error(`${Y.find(P=>P.name===A)?.label||A} is required`)}else if(_==="motherduck"){if(!q.accessToken)throw new Error("Access Token is required")}else if(_==="databricks"){if(!q.host)throw new Error("Host is required");if(!q.path)throw new Error("HTTP Path is required");const B=q.oauthClientId&&q.oauthClientSecret;if(!q.token&&!B)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}N={name:H,type:_,[Jt[_]]:q}}await t(N),w()},M=()=>{f([...l,{name:"",dbType:"postgres"}])},j=E=>{f(l.filter((L,H)=>H!==E))},I=(E,L)=>{const H=[...l];H[E]={...H[E],dbType:L},f(H)};return n.jsxs($.Fragment,{children:[n.jsx(u.AddButton,{label:"Connection",onClick:k}),n.jsx(u.AppDialog,{open:h,onClose:w,title:"New connection",description:"Add a connection so packages in this environment can query your database with Malloy.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:i,onClick:w,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"connection-form",variant:"contained",loading:i,children:"Create connection"})]}),children:n.jsx("form",{onSubmit:T,id:"connection-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),n.jsx(u.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:p,select:!0,onChange:E=>c(E.target.value),children:ya.map(E=>n.jsx(ke,{value:E,children:E},E))}),p==="ducklake"?n.jsxs(ge,{sx:{mt:2},children:[n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(u.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:d,select:!0,onChange:E=>m(E.target.value),children:n.jsx(ke,{value:"postgres",children:"PostgreSQL"})}),d==="postgres"&&n.jsx(n.Fragment,{children:Qe.postgres.map(E=>n.jsx(u.TextField,{id:`ducklake_pg_${E.name}`,name:`ducklake_pg_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small"},`pg_${E.name}`))})]}),n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(u.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:x,select:!0,onChange:E=>S(E.target.value),children:[n.jsx(ke,{value:"s3",children:"S3"}),n.jsx(ke,{value:"gcs",children:"GCS"})]}),n.jsx(u.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:x==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small"}),x==="s3"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),nn.filter(E=>E.visibleWhen?b===E.visibleWhen.value:!0).map(E=>n.jsx(u.TextField,{id:`ducklake_s3_${E.name}`,name:`ducklake_s3_${E.name}`,label:E.label,type:E.selectOptions?void 0:E.type,fullWidth:!0,size:"small",required:E.required,select:!!E.selectOptions,defaultValue:E.selectOptions?b:void 0,onChange:E.name==="provider"?L=>g(L.target.value):void 0,placeholder:E.name==="region"?"us-east-1":void 0,children:E.selectOptions?.map(L=>n.jsx(ke,{value:L.value,children:L.label},L.value))},`s3_${E.name}`))]}),x==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),rn.map(E=>n.jsx(u.TextField,{id:`ducklake_gcs_${E.name}`,name:`ducklake_gcs_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},`gcs_${E.name}`))]})]})]}):p==="duckdb"?n.jsxs(ge,{sx:{mt:2},children:[n.jsxs(ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(u.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(u.SecondaryButton,{label:"Database",icon:n.jsx(u.AddIcon,{}),onClick:M,ariaLabel:"Add database"})]}),l.length===0&&n.jsx(u.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),l.map((E,L)=>{const H=kn(E.dbType);return n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(u.Typography,{variant:"subtitle2",children:["Database ",L+1]}),n.jsx(u.IconButton,{onClick:()=>j(L),size:"small",color:"error",children:n.jsx(pa,{fontSize:"small"})})]}),n.jsx(u.TextField,{required:!0,id:`attachedDb_${L}_name`,name:`attachedDb_${L}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:E.name}),n.jsx(u.TextField,{id:`attachedDb_${L}_type`,name:`attachedDb_${L}_type`,label:"Database Type",fullWidth:!0,size:"small",value:E.dbType,select:!0,onChange:_=>I(L,_.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(_=>n.jsx(ke,{value:_,children:_},_))}),H.filter(_=>_.visibleWhen?(E[_.visibleWhen.field]||H.find(N=>N.name===_.visibleWhen?.field)?.selectOptions?.[0]?.value)===_.visibleWhen.value:!0).map(_=>n.jsx(u.TextField,{id:`attachedDb_${L}_${_.name}`,name:`attachedDb_${L}_${_.name}`,label:_.label,type:_.selectOptions?void 0:_.type,fullWidth:!0,size:"small",required:_.required,select:!!_.selectOptions,defaultValue:_.selectOptions?.[0]?.value,onChange:_.selectOptions?Y=>{const N=[...l];N[L]={...N[L],[_.name]:Y.target.value},f(N)}:void 0,children:_.selectOptions?.map(Y=>n.jsx(ke,{value:Y.value,children:Y.label},Y.value))},_.name))]},L)})]}):Qe[p].map(E=>n.jsx(u.TextField,{id:E.name,name:E.name,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},E.name))]})})})]})}function hl({connection:t,onCloseDialog:i,isMutating:h,onDelete:a}){const[p,c]=$.useState(!1),l=()=>{c(!0)},f=()=>{c(!1),i()};return n.jsxs($.Fragment,{children:[n.jsxs(ke,{"aria-label":`Delete connection ${t?.name??""}`.trim(),onClick:d=>{d.stopPropagation(),l()},sx:{color:"error.main"},children:[n.jsx(pr,{sx:{color:"inherit"},children:n.jsx(He.Delete,{fontSize:"small"})}),n.jsx(yr,{children:"Delete"})]}),n.jsx(u.AppDialog,{open:p,onClose:f,title:"Delete connection",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{onClick:f,children:"Cancel"}),n.jsx(u.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>a(),loading:h,children:"Delete connection"})]}),children:n.jsxs(u.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:t.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const _s=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function Ps(t){const i=t.duckdbConnection?.attachedDatabases;return!i||i.length===0?[]:i.map(h=>({name:h.name||"",dbType:h.type||"postgres"}))}function qs(t){const i=t.ducklakeConnection;return i&&i.storage?.gcsConnection?"gcs":"s3"}function fl({connection:t,onSubmit:i,isSubmitting:h,onCloseDialog:a}){const[p,c]=$.useState(!1),[l,f]=$.useState(t.type),d=$.useMemo(()=>new Set(t.withheldFields??[]),[t.withheldFields]),[m,x]=$.useState(()=>Ps(t)),[S,b]=$.useState("postgres"),[g,k]=$.useState(()=>qs(t)),[w,T]=$.useState(()=>t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),M=()=>{x(Ps(t)),f(t.type),T(t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),b("postgres"),k(qs(t)),c(!0)},j=()=>{c(!1),a?.()},I=async N=>{N.preventDefault();const q=new FormData(N.currentTarget),B=q.get("name")?.toString(),A=q.get("type")?.toString(),P=Qe[A];if(!B)throw new Error("Name is required");if(!A)throw new Error("Type is required");let G;if(A==="ducklake"){const K={};if(S==="postgres"){const U=Qe.postgres,te={};if(U.forEach(W=>{const Q=q.get(`ducklake_pg_${W.name}`)?.toString();Q&&(te[W.name]=Q)}),Object.keys(te).length===0)throw new Error("DuckLake requires catalog connection");K.postgresConnection=te}const X=q.get("ducklake_bucketUrl")?.toString();if(!X)throw new Error("DuckLake requires a bucket URL");const J={bucketUrl:X};if(g==="s3"){const U={};nn.forEach(W=>{const Q=q.get(`ducklake_s3_${W.name}`)?.toString();Q&&(U[W.name]=Q)});const te=t.ducklakeConnection?.storage?.s3Connection;if(te&&(!U.provider&&te.provider&&(U.provider=te.provider),!U.chain&&te.chain&&(U.chain=te.chain),!U.accessKeyId&&te.accessKeyId&&(U.accessKeyId=te.accessKeyId)),U.provider==="credential_chain")delete U.accessKeyId,delete U.secretAccessKey,delete U.sessionToken;else if(delete U.chain,!U.accessKeyId)throw new Error("S3 Access Key ID is required");Object.keys(U).length>0&&(J.s3Connection=U)}else if(g==="gcs"){const U={};rn.forEach(W=>{const Q=q.get(`ducklake_gcs_${W.name}`)?.toString();Q&&(U[W.name]=Q)});const te=t.ducklakeConnection?.storage?.gcsConnection;if(te&&!U.keyId&&te.keyId&&(U.keyId=te.keyId),!U.keyId)throw new Error("GCS Key ID is required");Object.keys(U).length>0&&(J.gcsConnection=U)}G={name:B,type:A,ducklakeConnection:{catalog:K,storage:J}}}else if(A==="duckdb"){if(m.length===0)throw new Error("DuckDB connection must have at least one attached database");const K=m.map((X,J)=>{const U=X.dbType,te=q.get(`attachedDb_${J}_name`)?.toString();if(!te)throw new Error(`Attached database at index ${J} must have a name`);const W={name:te,type:U},Q=kn(U);if(Q&&Q.length>0){const R={};if(Q.forEach(de=>{const ae=q.get(`attachedDb_${J}_${de.name}`)?.toString();ae&&(R[de.name]=ae)}),U==="s3"){if(R.provider==="credential_chain")delete R.accessKeyId,delete R.secretAccessKey,delete R.sessionToken;else if(delete R.chain,!R.accessKeyId||!R.secretAccessKey)throw new Error(`Attached database "${te}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const Z=or[U];Z&&(W[Z]=R)}return W});G={name:B,type:A,duckdbConnection:{attachedDatabases:K}}}else{const K=t[Jt[A]]||{},X={};if(P.forEach(J=>{const U=q.get(J.name)?.toString(),te=K[J.name];U?X[J.name]=U:_s.has(J.name)||(U!==void 0?X[J.name]=U:te&&(X[J.name]=te))}),A==="postgres"){const J=["host","port","databaseName","userName"],U=d.has("postgresConnection.connectionString");if(!(!!X.connectionString?.trim()||U)){const W=J;for(const Q of W)if(!X[Q])throw new Error(`${P.find(R=>R.name===Q)?.label||Q} is required`)}}else if(A==="snowflake"){if(!X.account)throw new Error("Account is required");if(!X.username)throw new Error("Username is required");if(!X.warehouse)throw new Error("Warehouse is required")}else if(A==="trino"){if(!X.server)throw new Error("Server is required");if(!X.user)throw new Error("User is required")}else if(A==="mysql"){const J=["host","port","database","user"];for(const U of J)if(!X[U])throw new Error(`${P.find(te=>te.name===U)?.label||U} is required`)}else if(A==="databricks"){if(!X.host)throw new Error("Host is required");if(!X.path)throw new Error("HTTP Path is required")}G={name:B,type:A,[Jt[A]]:X}}await i(G),j()},E=()=>{x([...m,{name:"",dbType:"postgres"}])},L=N=>{x(m.filter((q,B)=>B!==N))},H=(N,q)=>{const B=[...m];B[N]={...B[N],dbType:q},x(B)},_=(N,q)=>{const B=t.duckdbConnection?.attachedDatabases;if(!B||!B[N])return"";const A=B[N],P=or[A.type||""];return P&&A[P]?A[P][q]??"":""},Y=N=>{const q=t.ducklakeConnection;if(!q)return"";if(N.startsWith("pg_")){const B=N.replace("pg_","");return q.catalog?.postgresConnection?.[B]??""}if(N==="bucketUrl")return q.storage?.bucketUrl??"";if(N.startsWith("s3_")){const B=N.replace("s3_","");return q.storage?.s3Connection?.[B]??""}if(N.startsWith("gcs_")){const B=N.replace("gcs_","");return q.storage?.gcsConnection?.[B]??""}return""};return n.jsxs($.Fragment,{children:[n.jsxs(ke,{"aria-label":`Edit connection ${t?.name??""}`.trim(),onClick:N=>{N.preventDefault(),N.stopPropagation(),M()},children:[n.jsx(pr,{children:n.jsx(He.Edit,{fontSize:"small"})}),n.jsx(yr,{children:"Edit"})]}),n.jsx(u.AppDialog,{open:p,onClose:j,title:"Edit connection",description:"Change how packages in this environment reach your database.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:h,onClick:j,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"connection-form",variant:"contained",loading:h,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:I,id:"connection-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:t.name}),n.jsx(u.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:l,select:!0,onChange:N=>f(N.target.value),children:ya.map(N=>n.jsx(ke,{value:N,children:N},N))}),l==="ducklake"?n.jsxs(ge,{sx:{mt:2},children:[n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(u.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:S,select:!0,onChange:N=>b(N.target.value),children:n.jsx(ke,{value:"postgres",children:"PostgreSQL"})}),S==="postgres"&&n.jsx(n.Fragment,{children:Qe.postgres.map(N=>n.jsx(u.TextField,{id:`ducklake_pg_${N.name}`,name:`ducklake_pg_${N.name}`,label:N.label,type:N.type,fullWidth:!0,size:"small",defaultValue:Y(`pg_${N.name}`)},`pg_${N.name}`))})]}),n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(u.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:g,select:!0,onChange:N=>k(N.target.value),children:[n.jsx(ke,{value:"s3",children:"S3"}),n.jsx(ke,{value:"gcs",children:"GCS"})]}),n.jsx(u.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:g==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small",defaultValue:Y("bucketUrl")}),g==="s3"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),nn.filter(N=>N.visibleWhen?w===N.visibleWhen.value:!0).map(N=>n.jsx(u.TextField,{id:`ducklake_s3_${N.name}`,name:`ducklake_s3_${N.name}`,label:N.label,type:N.selectOptions?void 0:N.type,fullWidth:!0,size:"small",required:N.required&&N.name!=="secretAccessKey",select:!!N.selectOptions,defaultValue:N.selectOptions?w:Y(`s3_${N.name}`),onChange:N.name==="provider"?q=>T(q.target.value):void 0,placeholder:N.name==="region"?"us-east-1":N.name==="secretAccessKey"&&d.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:N.selectOptions?.map(q=>n.jsx(ke,{value:q.value,children:q.label},q.value))},`s3_${N.name}`))]}),g==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),rn.map(N=>n.jsx(u.TextField,{id:`ducklake_gcs_${N.name}`,name:`ducklake_gcs_${N.name}`,label:N.label,type:N.type,fullWidth:!0,size:"small",required:N.required&&N.name!=="secret",defaultValue:Y(`gcs_${N.name}`),placeholder:N.name==="secret"&&d.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${N.name}`))]})]})]}):l==="duckdb"?n.jsxs(ge,{sx:{mt:2},children:[n.jsxs(ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(u.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(u.SecondaryButton,{label:"Database",icon:n.jsx(u.AddIcon,{}),onClick:E,ariaLabel:"Add database"})]}),m.length===0&&n.jsx(u.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),m.map((N,q)=>{const B=kn(N.dbType);return n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(u.Typography,{variant:"subtitle2",children:["Database ",q+1]}),n.jsx(u.IconButton,{"aria-label":`Remove attached database ${q+1}`,onClick:()=>L(q),size:"small",color:"error",children:n.jsx(pa,{fontSize:"small"})})]}),n.jsx(u.TextField,{required:!0,id:`attachedDb_${q}_name`,name:`attachedDb_${q}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:N.name}),n.jsx(u.TextField,{id:`attachedDb_${q}_type`,name:`attachedDb_${q}_type`,label:"Database Type",fullWidth:!0,size:"small",value:N.dbType,select:!0,onChange:A=>H(q,A.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(A=>n.jsx(ke,{value:A,children:A},A))}),B.filter(A=>A.visibleWhen?(N[A.visibleWhen.field]||_(q,A.visibleWhen.field)||B.find(G=>G.name===A.visibleWhen?.field)?.selectOptions?.[0]?.value)===A.visibleWhen.value:!0).map(A=>n.jsx(u.TextField,{id:`attachedDb_${q}_${A.name}`,name:`attachedDb_${q}_${A.name}`,label:A.label,type:A.selectOptions?void 0:A.type,fullWidth:!0,size:"small",required:A.required,select:!!A.selectOptions,defaultValue:_(q,A.name)||A.selectOptions?.[0]?.value,onChange:A.selectOptions?P=>{const G=[...m];G[q]={...G[q],[A.name]:P.target.value},x(G)}:void 0,children:A.selectOptions?.map(P=>n.jsx(ke,{value:P.value,children:P.label},P.value))},A.name))]},q)})]}):Qe[l].map(N=>{const q=t?.[Jt[l]??""]?.[N.name??""]??"",B=N.type==="password"||_s.has(N.name),A=d.has(`${Jt[l]??""}.${N.name}`);return n.jsx(u.TextField,{id:N.name,name:N.name,label:N.label,type:N.type,fullWidth:!0,size:"small",required:N.required&&!B&&!q,defaultValue:q,placeholder:A?"Leave empty to keep existing":void 0,helperText:B?A?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0},N.name)})]})})})]})}function Ws(t,i){return!t||t.type!=="duckdb"?!1:(t.duckdbConnection?.attachedDatabases||[]).some(a=>a.type==="azure"&&a.name===i)}function ml(t){return t.startsWith("gs://")||t.startsWith("s3://")||t.startsWith("https://")||t.startsWith("abfss://")||t.startsWith("az://")}function ga({connectionName:t,resourceUri:i,schema:h,connection:a}){const{apiClients:p}=V.useServer(),{environmentName:c}=u.parseResourceUri(i),[l,f]=$.useState(null),[d,m]=$.useState(h||null),[x,S]=$.useState(!1),{data:b,isError:g,isLoading:k,error:w}=u.useQueryWithApiError({queryKey:["schemas",c,t],queryFn:()=>p.connections.listSchemas(c,t)}),T=b?.data||[];return n.jsxs(v.Grid,{container:!0,spacing:1,children:[!h&&n.jsx(v.Grid,{size:{xs:12,md:4},children:n.jsxs(v.Paper,{sx:{p:1,m:0},children:[n.jsxs(v.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[n.jsx(v.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),n.jsx(v.FormControlLabel,{control:n.jsx(v.Switch,{checked:x,onChange:M=>S(M.target.checked)}),label:"Hidden Schemas"})]}),n.jsx(v.Divider,{sx:{mt:"2px"}}),n.jsxs(v.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[k&&n.jsx(u.Loading,{text:"Loading schemas..."}),g&&n.jsx(u.ApiErrorDisplay,{error:w,context:`${c} > ${t} > Schemas`}),!k&&!g&&T.length===0&&n.jsx(v.Typography,{variant:"body2",children:"No Schemas"}),!k&&!g&&T.length>0&&n.jsx(v.List,{dense:!0,disablePadding:!0,children:T.map(M=>{const j=M.name;if(M.isHidden&&!x)return null;const E=d===j;return n.jsx(v.ListItemButton,{selected:E,onClick:()=>{m(j),f(null)},children:n.jsx(v.ListItemText,{primary:j})},j)})})]})]})}),n.jsx(v.Grid,{size:{xs:12,md:h?6:4},children:d&&n.jsx(v.Paper,{sx:{p:1,m:0},children:n.jsx(gl,{connectionName:t,schemaName:d,onTableSelect:M=>{f(M)},resourceUri:i,connection:a})})}),n.jsx(v.Grid,{size:{xs:12,md:h?6:4},children:d&&l&&n.jsx(pl,{environmentName:c,connectionName:t,schemaName:d,tableResource:l})})]})}function pl({environmentName:t,connectionName:i,schemaName:h,tableResource:a}){const{apiClients:p}=V.useServer(),{data:c,isLoading:l,isError:f,error:d}=u.useQueryWithApiError({queryKey:["connectionTableDetail",t,i,h,a],queryFn:()=>p.connections.getTable(t,i,h,a),enabled:!!h&&!!a}),m={resource:c?.data?.resource??a,columns:c?.data?.columns??[]};return n.jsxs(v.Paper,{sx:{p:1,m:0},children:[f&&n.jsx(u.ApiErrorDisplay,{error:d,context:`${t} > ${i} > ${h} > ${a}`}),!f&&n.jsx(yl,{table:m,loading:l})]})}function yl({table:t,loading:i}){return i?n.jsx(u.Loading,{text:"Loading columns..."}):n.jsxs(n.Fragment,{children:[n.jsxs(v.Typography,{variant:"overline",fontWeight:"bold",sx:{display:"block",wordBreak:"break-all"},children:[t.resource.includes("://")||/\.(parquet|csv|json|tsv|ndjson)$/i.test(t.resource)?"File":"Table",": ",t.resource]}),n.jsx(v.Divider,{}),n.jsx(v.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:n.jsx(v.TableContainer,{children:n.jsxs(v.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[n.jsx(v.TableHead,{children:n.jsxs(v.TableRow,{children:[n.jsx(v.TableCell,{children:"NAME"}),n.jsx(v.TableCell,{children:"TYPE"})]})}),n.jsx(v.TableBody,{children:t.columns?.sort((h,a)=>h.name.localeCompare(a.name))?.map(h=>n.jsxs(v.TableRow,{children:[n.jsx(v.TableCell,{children:h.name}),n.jsx(v.TableCell,{children:h.type})]},h.name))})]})})})]})}function gl({connectionName:t,schemaName:i,onTableSelect:h,resourceUri:a,connection:p}){const{environmentName:c}=u.parseResourceUri(a),{apiClients:l}=V.useServer(),[f,d]=$.useState(""),{data:m,isSuccess:x,isError:S,error:b,isLoading:g}=u.useQueryWithApiError({queryKey:["tablesInSchema",c,t,i],queryFn:()=>l.connections.listTables(c,t,i)}),k=Ws(p,i),w=M=>k?M:M.split(".").pop()||M,T=x&&m?.data?m.data.filter(M=>w(M.resource).toLowerCase().includes(f.toLowerCase())).sort((M,j)=>w(M.resource).localeCompare(w(j.resource))):[];return n.jsxs(n.Fragment,{children:[n.jsx(v.Typography,{variant:"overline",fontWeight:"bold",children:ml(i)||Ws(p,i)?`Files in ${i}`:`Tables in ${i}`}),n.jsx(v.Divider,{}),n.jsx(v.Box,{sx:{mt:1,mb:1},children:n.jsx(v.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:f,onChange:M=>d(M.target.value),variant:"outlined"})}),n.jsx(v.Divider,{}),n.jsxs(v.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[g&&n.jsx(u.Loading,{text:"Fetching Tables..."}),S&&n.jsx(u.ApiErrorDisplay,{error:b,context:`${c} > ${t} > ${i}`}),x&&T.length===0&&n.jsx(v.Typography,{variant:"body2",children:"No Tables"}),x&&m?.data&&m.data.length>0&&n.jsx(v.List,{dense:!0,disablePadding:!0,children:T.map(M=>{let j=w(M.resource);return!k&&M.resource.includes("://")&&(j=M.resource.split("/").pop()||M.resource),n.jsx(v.ListItemButton,{onClick:()=>h(M.resource),children:n.jsx(v.ListItemText,{primary:j,secondary:M.columns.length>0?`${M.columns.length} columns`:void 0})},M.resource)})})]})]})}const xl={bigquery:"BigQuery",snowflake:"Snowflake",postgres:"PostgreSQL",mysql:"MySQL",trino:"Trino",databricks:"Databricks",duckdb:"DuckDB",ducklake:"DuckLake",s3:"S3",gcs:"GCS",azure:"Azure"};function bl(t){return t?xl[t]??t:""}function vl({resourceUri:t}){const{apiClients:i,mutable:h}=V.useServer(),a=Mn.useQueryClient(),{environmentName:p}=u.parseResourceUri(t),[c,l]=$.useState(""),[f,d]=$.useState(null),m=u.encodeResourceUri({environmentName:p,connectionName:f}),{data:x,isSuccess:S,isError:b,error:g}=u.useQueryWithApiError({queryKey:["connections",p],queryFn:()=>i.connections.listConnections(p)}),k=u.useMutationWithApiError({mutationFn:Ke("connection","create",I=>i.environments.updateEnvironment(p,{name:p,connections:[...x.data,I]})),onSuccess(){l("Connection added successfully"),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),w=u.useMutationWithApiError({mutationFn:Ke("connection","update",I=>i.environments.updateEnvironment(p,{name:p,connections:x.data.map(E=>E.name===I.name?I:E)})),onSuccess(I,E){l(`Connection ${E.name} updated successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),T=u.useMutationWithApiError({mutationFn:Ke("connection","delete",I=>{if(!I.name)throw new Error("Cannot delete a connection with no name");return i.connections.deleteConnection(p,I.name)}),onSuccess(I,E){l(`Connection ${E.name} deleted successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),M=S?[...x.data].sort((I,E)=>(I.name??"").localeCompare(E.name??"")):[],j=k.isPending||w.isPending||T.isPending;return n.jsxs(ze,{title:"Connections",...S?{count:M.length}:{},description:"Database connections available to packages in this environment",...h&&S?{action:n.jsx(dl,{onSubmit:I=>k.mutateAsync(I),isSubmitting:k.isPending})}:{},children:[!S&&!b&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),b&&n.jsx(u.ApiErrorDisplay,{error:g,context:`${p} > Connections`}),S&&M.length===0&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),S&&M.length>0&&n.jsx(v.Stack,{children:M.map(I=>n.jsx(Sl,{connection:I,mutable:h,isMutating:j,onOpenExplorer:()=>d(I.name??null),onEdit:E=>w.mutateAsync(E),onDelete:E=>T.mutateAsync(E)},I.name))}),n.jsx(v.Snackbar,{open:c!=="",autoHideDuration:6e3,onClose:()=>l(""),message:c}),n.jsx(u.AppDialog,{open:f!==null,onClose:()=>d(null),maxWidth:"lg",title:`Connection explorer: ${f??""}`,showClose:!0,children:f&&n.jsx(ga,{resourceUri:m,connectionName:f,connection:x?.data?.find(I=>I.name===f)})})]})}function Sl({connection:t,mutable:i,isMutating:h,onOpenExplorer:a,onEdit:p,onDelete:c}){const[l,f]=$.useState(null),d=!!l,m=S=>{S.stopPropagation(),f(S.currentTarget)},x=()=>f(null);return n.jsx(jn,{icon:n.jsx(Ko,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.connection,label:t.name??"",ariaLabel:t.name??"",description:bl(t.type),onClick:a,...i?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(v.IconButton,{size:"small",onClick:m,"aria-label":`Connection actions for ${t.name??""}`.trim(),children:n.jsx(He.MoreVert,{fontSize:"small"})}),n.jsxs(v.Menu,{anchorEl:l,open:d,onClose:x,onClick:S=>S.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(fl,{connection:t,onSubmit:p,isSubmitting:h,onCloseDialog:x}),n.jsx(hl,{connection:t,onCloseDialog:x,isMutating:h,onDelete:()=>c(t)})]})]})}:{}})}const wl=u.createSvgIcon([n.jsx("path",{d:"M20 2H4c-1 0-2 .9-2 2v3.01c0 .72.43 1.34 1 1.69V20c0 1.1 1.1 2 2 2h14c.9 0 2-.9 2-2V8.7c.57-.35 1-.97 1-1.69V4c0-1.1-1-2-2-2m-1 18H5V9h14zm1-13H4V4h16z"},"0"),n.jsx("path",{d:"M9 12h6v2H9z"},"1")]);function kl({resourceUri:t,onCloseDialog:i}){const[h,a]=$.useState(!1),{apiClients:p}=V.useServer(),c=()=>{a(!0)},l=()=>{a(!1),i()},{environmentName:f,packageName:d}=u.parseResourceUri(t),m=Dt({mutationFn:()=>p.packages.deletePackage(f,d),success:"Package deleted",invalidates:[["packages",f]],closeDialog:l,resource:"package",action:"delete"});return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:c,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Delete,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Delete"})]}),n.jsx(u.AppDialog,{open:h,onClose:l,title:"Delete package",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{onClick:l,children:"Cancel"}),n.jsx(u.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>m.mutate(),loading:m.isPending,children:"Delete package"})]}),children:n.jsxs(u.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:d}),"? The package stops being served and this cannot be undone."]})}),m.notice]})}function Cl({package:t,resourceUri:i,onCloseDialog:h}){const[a,p]=$.useState(!1),{apiClients:c}=V.useServer(),l=()=>{p(!0)},f=()=>{p(!1),h()},{packageName:d,environmentName:m}=u.parseResourceUri(i),x=Dt({mutationFn(b){return c.packages.updatePackage(m,d,{name:d,description:b.description})},success:"Package updated",invalidates:[["packages",m]],closeDialog:f,resource:"package",action:"update"}),S=b=>{b.preventDefault();const k=new FormData(b.currentTarget).get("description")?.toString();x.mutate({description:k})};return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:l,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Edit,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Edit"})]}),n.jsx(u.AppDialog,{open:a,onClose:f,title:"Edit package",description:`What ${t.name} is, for the people who open it.`,actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:x.isPending,onClick:f,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"package-form",variant:"contained",loading:x.isPending,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:S,id:"package-form",children:n.jsxs(v.Stack,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:t.name,InputLabelProps:{shrink:!0}}),n.jsx(u.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:t.description,InputLabelProps:{shrink:!0}})]})})}),x.notice]})}function xa({onSelectPackage:t,resourceUri:i}){const{apiClients:h}=V.useServer(),{environmentName:a}=u.parseResourceUri(i),{data:p,isSuccess:c,isError:l,error:f}=u.useQueryWithApiError({queryKey:["packages",a],queryFn:()=>h.packages.listPackages(a)});if(l)return n.jsx(u.ApiErrorDisplay,{error:f,context:`${a} > Packages`});if(!c)return n.jsx(u.Loading,{text:"Fetching Packages..."});const d=[...p.data].sort((m,x)=>m.name.localeCompare(x.name));return n.jsx(v.Stack,{children:d.map(m=>{const x=u.encodeResourceUri({environmentName:a,packageName:m.name});return n.jsx(Tl,{pkg:m,packageResourceUri:x,onSelectPackage:t},m.name)})})}function Tl({pkg:t,packageResourceUri:i,onSelectPackage:h}){const{mutable:a}=V.useServer(),[p,c]=$.useState(null),l=!!p,f=m=>{m.stopPropagation(),c(m.currentTarget)},d=()=>c(null);return n.jsx(jn,{icon:n.jsx(wl,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.package,label:t.name,ariaLabel:t.name,...t.description?{description:t.description}:{},onClick:m=>h(t.name,m),...a?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(v.IconButton,{size:"small",onClick:f,"aria-label":`Package actions for ${t.name}`,children:n.jsx(He.MoreVert,{fontSize:"small"})}),n.jsxs(v.Menu,{anchorEl:p,open:l,onClose:d,onClick:m=>m.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(Cl,{package:t,resourceUri:i,onCloseDialog:d}),n.jsx(kl,{resourceUri:i,onCloseDialog:d})]})]})}:{}})}function Ml({onSelectPackage:t,resourceUri:i}){const{apiClients:h,mutable:a}=V.useServer(),{environmentName:p}=u.parseResourceUri(i),c=u.useQueryWithApiError({queryKey:["packages",p],queryFn:()=>h.packages.listPackages(p)});return $.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),n.jsxs(v.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[n.jsxs(v.Box,{sx:{mb:4},children:[n.jsx(v.Box,{children:n.jsx(mr,{label:"Publisher",onClick:l=>t("/",l)})}),n.jsx(v.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:p}),n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"Manage packages and database connections in this environment. Open a package to explore its models and notebooks."})]}),n.jsx(ze,{title:"Packages",...c.isSuccess?{count:c.data.data.length}:{},description:"Published packages available for use in this environment",...a?{action:n.jsx(Xo,{resourceUri:i})}:{},children:n.jsx(xa,{onSelectPackage:t,resourceUri:i})}),n.jsx(vl,{resourceUri:i}),n.jsx($o,{resourceUri:i})]})}u.dayjs.extend(u.utc);function Xn(t){switch(t){case"Star":return["Equals","Contains"];case"MinMax":return["Equals","Less Than","Greater Than","Between"];case"DateMinMax":return["Equals","Before","After","Between"];case"Retrieval":return["Semantic Search"];case"Boolean":return["Equals"];case"NONE":default:return[]}}function jl(t){return t==="DateMinMax"}function Kn(t){return t==="Between"}function Dl({spec:t,values:i,selection:h,onChange:a,retrievalFn:p}){const c=()=>h?.matchType?h.matchType:t.defaultMatchType?t.defaultMatchType:t.filterType==="DateMinMax"?"Between":Xn(t.filterType)[0]||"Equals",[l,f]=$.useState(c()),[d,m]=$.useState(h?.value??""),[x,S]=$.useState(h?.value2??""),[b,g]=$.useState([]),[k,w]=$.useState(!1),[T,M]=$.useState(""),[j,I]=$.useState(!1),[E,L]=$.useState(!1),H=$.useRef(null),_=$.useRef(0),[Y,N]=$.useState(!1);$.useEffect(()=>{if(t.filterType!=="Retrieval"||!p)return;const W=T.trim();if(W.length<=2){g([]),I(!1);return}return H.current&&clearTimeout(H.current),H.current=setTimeout(async()=>{_.current+=1;const Q=_.current;w(!0);try{const R=await p(W,t);Q===_.current&&g(R)}catch(R){Q===_.current&&(console.error("Retrieval failed",R),g([]))}finally{Q===_.current&&(w(!1),I(!0))}},500),()=>{H.current&&clearTimeout(H.current)}},[T,t,p]),$.useEffect(()=>{h===null?(m(""),S(""),f(t.defaultMatchType??(t.filterType==="DateMinMax"?"Between":Xn(t.filterType)[0]||"Equals"))):h&&(f(h.matchType),m(h.value??""),S(h.value2??""))},[h,t.filterType,t.defaultMatchType]);const q=Xn(t.filterType),B=jl(t.filterType),A=Kn(l),P=B&&i.length>=2&&i[0].value instanceof Date?u.dayjs.utc(i[0].value):void 0,G=B&&i.length>=2&&i[1].value instanceof Date?u.dayjs.utc(i[1].value):void 0,K=t.filterType==="MinMax"&&i.length>=2&&typeof i[0].value=="number"?i[0].value:void 0,X=t.filterType==="MinMax"&&i.length>=2&&typeof i[1].value=="number"?i[1].value:void 0;if(q.length===0)return null;const J=W=>{const Q=W.target.value;f(Q),Kn(Q)||S(""),d&&a({dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:Q,value:d,...Kn(Q)&&x&&{value2:x}})},U=(W,Q)=>{m(W??""),Q!==void 0&&S(Q??"");const R=Array.isArray(W)&&W.length===0;a(!R&&W!==""&&W!==null&&W!==void 0?{dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:l,value:W,...A&&Q&&{value2:Q}}:null)},te=()=>{m(""),S(""),a(null)};return n.jsxs(ge,{sx:{display:"flex",flexDirection:"column",gap:1.5,fontSize:"0.75rem","& .MuiInputBase-root":{fontSize:"0.75rem"},"& .MuiInputBase-input":{padding:"6px 10px"},"& .MuiSelect-select":{padding:"6px 10px !important"},"& .MuiAutocomplete-input":{padding:"0 !important"},"& .MuiAutocomplete-root .MuiInputBase-root":{padding:"5px 10px",minHeight:"29.5px",boxSizing:"border-box",flexWrap:"wrap"},"& .MuiChip-root":{height:"16px",margin:"0 2px 0 0"},"& .MuiChip-label":{fontSize:"0.7rem",padding:"0 6px"},"& .MuiChip-deleteIcon":{fontSize:"14px",margin:"0 2px 0 -4px"},"& .MuiInputLabel-root":{fontSize:"0.75rem",transform:"translate(10px, 6px) scale(1)"},"& .MuiInputLabel-shrink":{fontSize:"0.85rem",transform:"translate(14px, -9px) scale(0.75)"},"& .MuiOutlinedInput-notchedOutline legend":{fontSize:"0.65rem"},"& .MuiFormHelperText-root":{fontSize:"0.65rem",marginTop:"2px"},"& .MuiSvgIcon-root":{fontSize:"1.25rem"}},children:[n.jsxs(ge,{sx:{fontWeight:600,color:t.required&&!h?"error.main":"text.primary"},children:[t.label??t.dimensionName,t.required&&n.jsx(ge,{component:"span",sx:{color:h?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),t.filterType!=="Boolean"&&!t.defaultMatchType&&q.length>1&&n.jsxs(u.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(u.InputLabel,{children:"Match Type"}),n.jsx(u.Select,{value:l,label:"Match Type",onChange:J,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:q.map(W=>n.jsx(ke,{value:W,children:W},W))})]}),t.filterType==="Star"&&l==="Equals"&&n.jsx(u.Autocomplete,{multiple:!0,size:"small",options:i,getOptionLabel:W=>typeof W=="string"?W:typeof W=="object"&&W!==null&&"value"in W?String(W.value):String(W),value:Array.isArray(d)?d.map(W=>i.find(Q=>Q.value===W)||W):d?[i.find(W=>W.value===d)||d]:[],onChange:(W,Q)=>{const R=Q.map(Z=>typeof Z=="string"?Z:Z&&typeof Z=="object"&&"value"in Z?Z.value:Z);U(R)},noOptionsText:"No matches found",renderInput:W=>n.jsx(u.TextField,{...W,size:"small",label:"Values",placeholder:"Select values..."}),freeSolo:!t.values||t.values.length===0,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),t.filterType==="Star"&&l==="Contains"&&n.jsx(u.TextField,{size:"small",label:"Search Text",value:d,onChange:W=>m(W.target.value),onBlur:()=>U(d),onKeyDown:W=>{W.key==="Enter"&&U(d)},placeholder:"Enter text to search...",fullWidth:!0}),t.filterType==="Boolean"&&n.jsxs(u.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(u.InputLabel,{children:"Value"}),n.jsxs(u.Select,{value:d===!0?"true":d===!1?"false":"",label:"Value",onChange:W=>{const Q=W.target.value;Q==="true"?U(!0):Q==="false"?U(!1):te()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[n.jsx(ke,{value:"",children:n.jsx("em",{children:"Blank"})}),n.jsx(ke,{value:"true",children:"True"}),n.jsx(ke,{value:"false",children:"False"})]})]}),t.filterType==="Retrieval"&&l==="Semantic Search"&&n.jsx(u.Autocomplete,{multiple:!0,size:"small",options:b,loading:k,getOptionLabel:W=>typeof W=="string"?W:typeof W=="object"&&W!==null&&"value"in W?String(W.value):String(W),value:Array.isArray(d)?d.map(W=>b.find(R=>R.value===W)||{value:W}):d?[{value:d}]:[],onInputChange:(W,Q)=>{M(Q)},onChange:(W,Q)=>{const R=Q.map(Z=>typeof Z=="string"?Z:Z&&typeof Z=="object"&&"value"in Z?Z.value:Z);U(R)},noOptionsText:T.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:W=>n.jsx(u.TextField,{...W,size:"small",label:"Search Values",placeholder:"Type to search...",onFocus:()=>L(!0),onBlur:()=>L(!1),helperText:E&&!k&&j&&b.length===0?"No matches found":void 0,InputProps:{...W.InputProps,endAdornment:n.jsxs(n.Fragment,{children:[k?n.jsx(u.CircularProgress,{color:"inherit",size:20}):null,W.InputProps.endAdornment]})}}),freeSolo:!0,filterOptions:W=>W,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),t.filterType==="MinMax"&&!A&&n.jsx(u.TextField,{size:"small",type:"number",label:"Value",value:d,onChange:W=>U(parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:K,max:X},helperText:Y&&K!==void 0&&X!==void 0?`Valid range: [${K} - ${X}]`:void 0}),t.filterType==="MinMax"&&A&&n.jsxs(ge,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(ge,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(u.TextField,{size:"small",type:"number",label:"From",value:d,onChange:W=>U(parseFloat(W.target.value)||"",x),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:K,max:x||X}}),n.jsx(ge,{children:"to"}),n.jsx(u.TextField,{size:"small",type:"number",label:"To",value:x,onChange:W=>U(d,parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:d||K,max:X}})]}),Y&&K!==void 0&&X!==void 0&&n.jsxs(u.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",K," - ",X,"]"]})]}),B&&!A&&n.jsx(u.LocalizationProvider,{dateAdapter:u.AdapterDayjs,children:n.jsx(u.DatePicker,{label:"Date",value:d instanceof Date?u.dayjs.utc(d):null,onChange:W=>{W===null?U(null):W.isValid()&&U(W.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?void 0:P,maxDate:d instanceof Date?void 0:G,referenceDate:l==="After"&&P?P:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>N(!0),onBlur:()=>N(!1),helperText:Y&&P&&G?`Valid range: [${P.format("YYYY-MM-DD")} - ${G.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),B&&A&&n.jsx(u.LocalizationProvider,{dateAdapter:u.AdapterDayjs,children:n.jsxs(ge,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(ge,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(ge,{sx:{flex:1,minWidth:0},children:n.jsx(u.DatePicker,{label:"From",value:d instanceof Date?u.dayjs.utc(d):null,onChange:W=>{W===null?U(null,x):W.isValid()&&U(W.utc().toDate(),x)},timezone:"UTC",minDate:d instanceof Date?void 0:P,maxDate:x instanceof Date?u.dayjs.utc(x):d instanceof Date?void 0:G,referenceDate:P,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),n.jsx(ge,{children:"to"}),n.jsx(ge,{sx:{flex:1,minWidth:0},children:n.jsx(u.DatePicker,{label:"To",value:x instanceof Date?u.dayjs.utc(x):null,onChange:W=>{W===null?U(d,null):W.isValid()&&U(d,W.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?u.dayjs.utc(d):x instanceof Date?void 0:P,maxDate:x instanceof Date?void 0:G,referenceDate:d instanceof Date?u.dayjs.utc(d):P,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),Y&&P&&G&&n.jsxs(u.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",P.format("YYYY-MM-DD")," -"," ",G.format("YYYY-MM-DD"),"]"]})]})})]})}function Ol(t){const i=new Set,h=t.schema?.fields;if(!h)return i;for(const a of h)"kind"in a&&a.kind==="join"&&a.name&&i.add(a.name);return i}function El(t){if(!t)return null;for(const i of t)if(i.startsWith("##(filters)")){const h=i.slice(11).trim();try{const a=JSON.parse(h);if(Array.isArray(a)){const p=[];for(const c of a)if(typeof c=="string"){const l=c.indexOf(".");l>0&&l<c.length-1&&p.push({source:c.substring(0,l),dimension:c.substring(l+1)})}if(p.length>0)return{filters:p}}}catch(a){console.error(`Failed to parse "${i}" annotation:`,a)}}return null}function ba(t){if(t.startsWith("#(filter)")){const i=t.slice(9).trim();try{const h=JSON.parse(i);if(h.type)return h}catch(h){console.error(`Failed to parse "${t}" annotation:`,h)}}return null}function Il(t){const i=t.match(/^#\s*label\s*=\s*"([^"]+)"/);return i?i[1]:null}function Fl(t){const i=new Map;let h="";for(const a of t)if(a.type==="code"){if(!h&&a.text){const c=a.text.split(`
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const n=require("react/jsx-runtime"),v=require("@mui/material"),$=require("react"),u=require("./Dashboard-ChyylkTD.cjs.js"),V=require("./ServerProvider-CXrOKD6g.cjs.js"),Mn=require("@tanstack/react-query"),ua=require("@mui/system"),He=require("@mui/icons-material"),ht=require("./RenderedResult-AJPMUkAD.cjs.js"),vn=require("react-router-dom");function Do(t){const i=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t){for(const h in t)if(h!=="default"){const a=Object.getOwnPropertyDescriptor(t,h);Object.defineProperty(i,h,a.get?a:{enumerable:!0,get:()=>t[h]})}}return i.default=t,Object.freeze(i)}const fe=Do($),Oo=u.createSvgIcon(n.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function mr({label:t,href:i,onClick:h}){const a=p=>{const c=p.metaKey||p.ctrlKey||p.shiftKey||p.altKey||p.button!==0;i!==void 0&&c||(p.preventDefault(),h(p))};return n.jsxs(v.Link,{...i===void 0?{component:"button",type:"button"}:{href:i},onClick:a,underline:"none","aria-label":`Back to ${t}`,sx:{display:"inline-flex",alignItems:"center",gap:.5,cursor:"pointer",color:"text.secondary",fontSize:"0.875rem",mb:2,border:0,p:0,background:"none",font:"inherit","&:hover":{color:"primary.main"}},children:[n.jsx(Oo,{sx:{fontSize:18}}),"Back to ",t]})}function Eo(){const t=vn.useNavigate();return(i,h)=>{if(!h||!h.metaKey&&!h.ctrlKey&&!h.shiftKey&&h.button!==1){t(i);return}const a=new URL(i,window.location.href).href;(h.metaKey||h.ctrlKey||h.button===1||h.shiftKey)&&window.open(a,"_blank")}}const da=u.createSvgIcon(n.jsx("path",{d:"M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3z"})),Io="publisher:resize";function Fo(t){return typeof t=="object"&&t!==null&&t.type===Io&&typeof t.height=="number"}function ha(t){return t.replace(/\/api\/v0\/?$/,"")}function fa({server:t,environmentName:i,packageName:h,path:a}){const p=a.startsWith("public/")?a.slice(7):a;return`${ha(t)}/environments/${encodeURIComponent(i)}/packages/${encodeURIComponent(h)}/`+p}function No(t){try{const{environmentName:i,packageName:h,modelPath:a}=u.parseResourceUri(t);return!i||!h||!a?null:{environmentName:i,packageName:h,dataAppPath:a}}catch{return null}}function Ao({resourceUri:t}){const{server:i,apiClients:h}=V.useServer(),a=No(t),p=a?.environmentName??"",c=a?.packageName??"",l=a?.dataAppPath??"",f=$.useMemo(()=>fa({server:i,environmentName:p,packageName:c,path:l}),[i,p,c,l]),m=u.useQueryWithApiError({queryKey:["data-apps",p,c],queryFn:()=>h.dataApps.listDataApps(p,c),enabled:!!a}).data?.data?.find(w=>w.path===l),x=m?.title??l,S=m?.fit==="viewport",b=$.useRef(null),[g,k]=$.useState(120);return $.useEffect(()=>{if(S)return;function w(T){Fo(T.data)&&T.source===b.current?.contentWindow&&T.data.height>0&&k(Math.ceil(T.data.height))}return window.addEventListener("message",w),()=>window.removeEventListener("message",w)},[S]),a?n.jsxs(v.Box,{sx:{p:3,...S?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1200,mx:"auto"}},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[n.jsx(v.Typography,{variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em"},children:x}),n.jsx(v.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:V.MONO_FONT_FAMILY},children:l}),n.jsx(v.Box,{sx:{flex:1}}),n.jsx(v.Tooltip,{title:"Open standalone in new tab",children:n.jsx(v.IconButton,{size:"small",href:f,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:n.jsx(da,{fontSize:"small"})})})]}),n.jsx(v.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...S?{flex:1,minHeight:0}:{}},children:n.jsx("iframe",{ref:b,src:f,title:x,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:S?"100%":g,border:0}})})]}):n.jsxs(v.Box,{sx:{p:3,maxWidth:1200,mx:"auto"},children:[n.jsx(v.Typography,{variant:"h6",sx:{fontWeight:600},children:"Can't open data app"}),n.jsxs(v.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",n.jsx(v.Box,{component:"span",sx:{fontFamily:V.MONO_FONT_FAMILY,ml:1},children:t})]})]})}function ze({title:t,count:i,description:h,action:a,children:p}){const c=$.useId();return n.jsxs(v.Box,{component:"section","aria-labelledby":c,sx:{mb:4},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:h?0:1,minHeight:40},children:[n.jsxs(v.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[n.jsx(v.Typography,{id:c,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:t}),i!==void 0&&n.jsxs(v.Typography,{variant:"caption",color:"text.secondary",children:["(",i,")"]})]}),a]}),h&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:h}),n.jsx(v.Box,{children:p})]})}function $o({resourceUri:t}){const{environmentName:i}=u.parseResourceUri(t),{apiClients:h}=V.useServer(),[a,p]=$.useState(!1),c=90,{data:l,isSuccess:f,isError:d,error:m}=u.useQueryWithApiError({queryKey:["about",i],queryFn:()=>h.environments.getEnvironment(i,!1)}),x=l?.data?.readme||"",S=x.split(/\s+/),b=S.length>c,g=S.slice(0,c).join(" ");return n.jsxs(n.Fragment,{children:[!f&&!d&&n.jsx(u.Loading,{text:"Fetching About..."}),f&&x&&n.jsxs(ze,{title:"Readme",children:[n.jsx(u.Prose,{variant:"caption",children:a||!b?x:g}),b&&n.jsx(v.Box,{sx:{mt:1},children:n.jsx(u.SecondaryButton,{label:a?"Read less":"Read more",onClick:()=>p(!a)})})]}),d&&n.jsx(u.ApiErrorDisplay,{error:m,context:`${i} > About`})]})}function Ro(t={}){const{autoHideDuration:i=null,disableWindowBlurListener:h=!1,onClose:a,open:p,resumeHideDuration:c}=t,l=u.useTimeout();fe.useEffect(()=>{if(!p)return;function M(j){j.defaultPrevented||j.key==="Escape"&&a?.(j,"escapeKeyDown")}return document.addEventListener("keydown",M),()=>{document.removeEventListener("keydown",M)}},[p,a]);const f=u.useEventCallback((M,j)=>{a?.(M,j)}),d=u.useEventCallback(M=>{!a||M==null||l.start(M,()=>{f(null,"timeout")})});fe.useEffect(()=>(p&&d(i),l.clear),[p,i,d,l]);const m=M=>{a?.(M,"clickaway")},x=l.clear,S=fe.useCallback(()=>{i!=null&&d(c??i*.5)},[i,c,d]),b=M=>j=>{const I=M.onBlur;I?.(j),S()},g=M=>j=>{const I=M.onFocus;I?.(j),x()},k=M=>j=>{const I=M.onMouseEnter;I?.(j),x()},w=M=>j=>{const I=M.onMouseLeave;I?.(j),S()};return fe.useEffect(()=>{if(!h&&p)return window.addEventListener("focus",S),window.addEventListener("blur",x),()=>{window.removeEventListener("focus",S),window.removeEventListener("blur",x)}},[h,p,S,x]),{getRootProps:(M={})=>{const j={...u.extractEventHandlers(t),...u.extractEventHandlers(M)};return{role:"presentation",...M,...j,onBlur:b(j),onFocus:g(j),onMouseEnter:k(j),onMouseLeave:w(j)}},onClickAway:m}}function As(t){return t.substring(2).toLowerCase()}function Lo(t,i){return i.documentElement.clientWidth<t.clientX||i.documentElement.clientHeight<t.clientY}function _o(t){const{children:i,disableReactTree:h=!1,mouseEvent:a="onClick",onClickAway:p,touchEvent:c="onTouchEnd"}=t,l=fe.useRef(!1),f=fe.useRef(null),d=fe.useRef(!1),m=fe.useRef(!1);fe.useEffect(()=>(setTimeout(()=>{d.current=!0},0),()=>{d.current=!1}),[]);const x=u.useForkRef(u.getReactElementRef(i),f),S=u.useEventCallback(k=>{const w=m.current;m.current=!1;const T=u.ownerDocument(f.current);if(!d.current||!f.current||"clientX"in k&&Lo(k,T))return;if(l.current){l.current=!1;return}let M;k.composedPath?M=k.composedPath().includes(f.current):M=!T.documentElement.contains(k.target)||f.current.contains(k.target),!M&&(h||!w)&&p(k)}),b=k=>w=>{m.current=!0;const T=i.props[k];T&&T(w)},g={ref:x};return c!==!1&&(g[c]=b(c)),fe.useEffect(()=>{if(c!==!1){const k=As(c),w=u.ownerDocument(f.current),T=()=>{l.current=!0};return w.addEventListener(k,S),w.addEventListener("touchmove",T),()=>{w.removeEventListener(k,S),w.removeEventListener("touchmove",T)}}},[S,c]),a!==!1&&(g[a]=b(a)),fe.useEffect(()=>{if(a!==!1){const k=As(a),w=u.ownerDocument(f.current);return w.addEventListener(k,S),()=>{w.removeEventListener(k,S)}}},[S,a]),fe.cloneElement(i,g)}function Po(t){return u.generateUtilityClass("MuiSnackbarContent",t)}u.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const qo=t=>{const{classes:i}=t,h={root:["root"],action:["action"],message:["message"]};return u.composeClasses(h,Po,i)},Wo=u.styled(u.Paper,{name:"MuiSnackbarContent",slot:"Root"})(u.memoTheme(({theme:t})=>{const i=t.palette.mode==="light"?.8:.98;return{...t.typography.body2,color:t.vars?t.vars.palette.SnackbarContent.color:t.palette.getContrastText(u.emphasize(t.palette.background.default,i)),backgroundColor:t.vars?t.vars.palette.SnackbarContent.bg:u.emphasize(t.palette.background.default,i),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[t.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),zo=u.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),Ho=u.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),Vo=fe.forwardRef(function(i,h){const a=u.useDefaultProps({props:i,name:"MuiSnackbarContent"}),{action:p,className:c,message:l,role:f="alert",...d}=a,m=a,x=qo(m);return n.jsxs(Wo,{role:f,elevation:6,className:u.clsx(x.root,c),ownerState:m,ref:h,...d,children:[n.jsx(zo,{className:x.message,ownerState:m,children:l}),p?n.jsx(Ho,{className:x.action,ownerState:m,children:p}):null]})});function Uo(t){return u.generateUtilityClass("MuiSnackbar",t)}u.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Bo=t=>{const{classes:i,anchorOrigin:h}=t,a={root:["root",`anchorOrigin${u.capitalize(h.vertical)}${u.capitalize(h.horizontal)}`]};return u.composeClasses(a,Uo,i)},Go=u.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(t,i)=>{const{ownerState:h}=t;return[i.root,i[`anchorOrigin${u.capitalize(h.anchorOrigin.vertical)}${u.capitalize(h.anchorOrigin.horizontal)}`]]}})(u.memoTheme(({theme:t})=>({zIndex:(t.vars||t).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:i})=>i.anchorOrigin.vertical==="top",style:{top:8,[t.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:i})=>i.anchorOrigin.vertical!=="top",style:{bottom:8,[t.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:i})=>i.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[t.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:i})=>i.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[t.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:i})=>i.anchorOrigin.horizontal==="center",style:{[t.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Yo=fe.forwardRef(function(i,h){const a=u.useDefaultProps({props:i,name:"MuiSnackbar"}),p=u.useTheme(),c={enter:p.transitions.duration.enteringScreen,exit:p.transitions.duration.leavingScreen},{action:l,anchorOrigin:{vertical:f,horizontal:d}={vertical:"bottom",horizontal:"left"},autoHideDuration:m=null,children:x,className:S,ClickAwayListenerProps:b,ContentProps:g,disableWindowBlurListener:k=!1,message:w,onBlur:T,onClose:M,onFocus:j,onMouseEnter:I,onMouseLeave:E,open:L,resumeHideDuration:H,slots:_={},slotProps:Y={},TransitionComponent:N,transitionDuration:q=c,TransitionProps:{onEnter:B,onExited:A,...P}={},...G}=a,K={...a,anchorOrigin:{vertical:f,horizontal:d},autoHideDuration:m,disableWindowBlurListener:k,TransitionComponent:N,transitionDuration:q},X=Bo(K),{getRootProps:J,onClickAway:U}=Ro({...K}),[te,W]=fe.useState(!0),Q=be=>{W(!0),A&&A(be)},R=(be,he)=>{W(!1),B&&B(be,he)},Z={slots:{transition:N,..._},slotProps:{content:g,clickAwayListener:b,transition:P,...Y}},[de,ae]=u.useSlot("root",{ref:h,className:[X.root,S],elementType:Go,getSlotProps:J,externalForwardedProps:{...Z,...G},ownerState:K}),[ce,{ownerState:xe,...we}]=u.useSlot("clickAwayListener",{elementType:_o,externalForwardedProps:Z,getSlotProps:be=>({onClickAway:(...he)=>{const ye=he[0];be.onClickAway?.(...he),!ye?.defaultMuiPrevented&&U(...he)}}),ownerState:K}),[Me,Ne]=u.useSlot("content",{elementType:Vo,shouldForwardComponentProp:!0,externalForwardedProps:Z,additionalProps:{message:w,action:l},ownerState:K}),[Oe,me]=u.useSlot("transition",{elementType:u.Grow,externalForwardedProps:Z,getSlotProps:be=>({onEnter:(...he)=>{be.onEnter?.(...he),R(...he)},onExited:(...he)=>{be.onExited?.(...he),Q(...he)}}),additionalProps:{appear:!0,in:L,timeout:q,direction:f==="top"?"down":"up"},ownerState:K});return!L&&te?null:n.jsx(ce,{...we,..._.clickAwayListener&&{ownerState:xe},children:n.jsx(de,{...ae,children:n.jsx(Oe,{...me,children:x||n.jsx(Me,{...Ne})})})})});let ir;function Zo(t){ir=t}function $s(t){if(ir)try{ir(t)}catch{}}function Ke(t,i,h){return(async a=>{const p=Date.now();try{const c=await h(a);return $s({type:"console.mutation",resource:t,action:i,ok:!0,durationMs:Date.now()-p}),c}catch(c){throw $s({type:"console.mutation",resource:t,action:i,ok:!1,durationMs:Date.now()-p,reason:c instanceof Error?c.message:"An unknown error occurred"}),c}})}function Dt({mutationFn:t,success:i,invalidates:h,closeDialog:a,resource:p,action:c}){const l=Mn.useQueryClient(),[f,d]=$.useState(""),m=u.useMutationWithApiError({mutationFn:Ke(p,c,t),onSuccess(){a();for(const x of h)l.invalidateQueries({queryKey:x});d(i)},onError(x){d(x instanceof Error?x.message:"An unknown error occurred")}});return{mutate:m.mutate,isPending:m.isPending,notice:n.jsx(Yo,{open:f!=="",autoHideDuration:6e3,onClose:()=>d(""),message:f})}}const ma="https://docs.malloydata.dev/documentation",Zn=`${ma}/user_guides/publishing`,Tt="https://github.com/malloydata/publisher/blob/main/docs",Xe={docsHome:`${ma}/`,publishing:`${Zn}/publishing`,explorer:`${Zn}/explorer`,mcpAgents:`${Zn}/mcp_agents`,surfaces:`${Tt}/choosing-a-surface.md`,dashboards:`${Tt}/dashboards.md`,dataApps:`${Tt}/html-data-apps.md`,givens:`${Tt}/givens.md`,materialization:`${Tt}/materialization.md`,connections:`${Tt}/connections.md`};function Xo({resourceUri:t}){const[i,h]=$.useState(!1),{apiClients:a}=V.useServer(),{environmentName:p}=u.parseResourceUri(t),c=Dt({mutationFn(f){return a.packages.createPackage(p,{name:f.name,description:f.description,location:f.location})},success:"Package created",invalidates:[["packages",p]],closeDialog:()=>h(!1),resource:"package",action:"create"}),l=f=>{f.preventDefault();const d=new FormData(f.currentTarget),m=d.get("name")?.toString(),x=d.get("description")?.toString(),S=d.get("location")?.toString();c.mutate({name:m,description:x,location:S})};return n.jsxs(n.Fragment,{children:[n.jsx(u.AddButton,{label:"Package",onClick:()=>h(!0)}),n.jsx(u.AppDialog,{open:i,onClose:()=>h(!1),title:"New package",description:n.jsxs(n.Fragment,{children:["A package is a directory of Malloy models and their data. Give its location as a GitHub, S3 or GCS URL, or an absolute path the server can read; see the"," ",n.jsx(v.Box,{component:"a",href:Xe.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:n.jsxs(n.Fragment,{children:[n.jsx(v.Button,{disabled:c.isPending,onClick:()=>h(!1),children:"Cancel"}),n.jsx(v.Button,{type:"submit",form:"package-form",variant:"contained",loading:c.isPending,children:"Create package"})]}),children:n.jsx("form",{onSubmit:l,id:"package-form",children:n.jsxs(v.Stack,{sx:{gap:2},children:[n.jsx(v.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(v.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(v.TextField,{id:"location",name:"location",label:"Location",type:"text",placeholder:"e.g. s3://my-bucket/my-package.zip",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),c.notice]})}const Ko=u.createSvgIcon(n.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function jn({icon:t,tint:i,label:h,mono:a,description:p,rightLabel:c,trailingAction:l,onClick:f,ariaLabel:d}){const m=!!f,x=S=>{f&&(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),f(S))};return n.jsxs(v.Box,{onClick:f,onKeyDown:m?x:void 0,role:m?"button":void 0,tabIndex:m?0:void 0,"aria-label":d,sx:S=>({display:"flex",alignItems:"center",gap:1.5,py:1,px:1,mx:-1,cursor:m?"pointer":"default",borderRadius:1.5,transition:"background-color 0.1s","&:hover":m?{backgroundColor:S.palette.mode==="dark"?"rgba(255, 255, 255, 0.08)":"grey.100"}:void 0,"&:focus-visible":m?{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}:void 0}),children:[n.jsx(v.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:i,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:t}),n.jsxs(v.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[n.jsx(v.Typography,{variant:"body2",sx:{...a?{fontFamily:V.MONO_FONT_FAMILY}:{},flexShrink:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:h}),p&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:p})]}),c&&n.jsx(v.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:c}),l&&n.jsx(v.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:l})]})}const pa=u.createSvgIcon(n.jsx("path",{d:"M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6zM19 4h-3.5l-1-1h-5l-1 1H5v2h14z"})),Qo=u.generateUtilityClasses("MuiBox",["root"]),Jo=u.createTheme(),ge=ua.createBox({themeId:u.THEME_ID,defaultTheme:Jo,defaultClassName:Qo.root,generateClassName:u.ClassNameGenerator.generate}),Dn=ua.createStack({createStyledComponent:u.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:t=>u.useDefaultProps({props:t,name:"MuiStack"})}),Rs=u.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function el(t){return u.generateUtilityClass("MuiListItemIcon",t)}const Ls=u.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),tl=t=>{const{alignItems:i,classes:h}=t,a={root:["root",i==="flex-start"&&"alignItemsFlexStart"]};return u.composeClasses(a,el,h)},nl=u.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(t,i)=>{const{ownerState:h}=t;return[i.root,h.alignItems==="flex-start"&&i.alignItemsFlexStart]}})(u.memoTheme(({theme:t})=>({minWidth:56,color:(t.vars||t).palette.action.active,flexShrink:0,display:"inline-flex",variants:[{props:{alignItems:"flex-start"},style:{marginTop:8}}]}))),pr=fe.forwardRef(function(i,h){const a=u.useDefaultProps({props:i,name:"MuiListItemIcon"}),{className:p,...c}=a,l=fe.useContext(u.ListContext),f={...a,alignItems:l.alignItems},d=tl(f);return n.jsx(nl,{className:u.clsx(d.root,p),ownerState:f,ref:h,...c})});function rl(t){return u.generateUtilityClass("MuiListItemText",t)}const jt=u.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),sl=t=>{const{classes:i,inset:h,primary:a,secondary:p,dense:c}=t,l={root:["root",h&&"inset",c&&"dense",a&&p&&"multiline"],primary:["primary"],secondary:["secondary"]};return u.composeClasses(l,rl,i)},al=u.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(t,i)=>{const{ownerState:h}=t;return[{[`& .${jt.primary}`]:i.primary},{[`& .${jt.secondary}`]:i.secondary},i.root,h.inset&&i.inset,h.primary&&h.secondary&&i.multiline,h.dense&&i.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${u.typographyClasses.root}:where(& .${jt.primary})`]:{display:"block"},[`.${u.typographyClasses.root}:where(& .${jt.secondary})`]:{display:"block"},variants:[{props:({ownerState:t})=>t.primary&&t.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:t})=>t.inset,style:{paddingLeft:56}}]}),yr=fe.forwardRef(function(i,h){const a=u.useDefaultProps({props:i,name:"MuiListItemText"}),{children:p,className:c,disableTypography:l=!1,inset:f=!1,primary:d,primaryTypographyProps:m,secondary:x,secondaryTypographyProps:S,slots:b={},slotProps:g={},...k}=a,{dense:w}=fe.useContext(u.ListContext);let T=d??p,M=x;const j={...a,disableTypography:l,inset:f,primary:!!T,secondary:!!M,dense:w},I=sl(j),E={slots:b,slotProps:{primary:m,secondary:S,...g}},[L,H]=u.useSlot("root",{className:u.clsx(I.root,c),elementType:al,externalForwardedProps:{...E,...k},ownerState:j,ref:h}),[_,Y]=u.useSlot("primary",{className:I.primary,elementType:u.Typography,externalForwardedProps:E,ownerState:j}),[N,q]=u.useSlot("secondary",{className:I.secondary,elementType:u.Typography,externalForwardedProps:E,ownerState:j});return T!=null&&T.type!==u.Typography&&!l&&(T=n.jsx(_,{variant:w?"body2":"body1",component:Y?.variant?void 0:"span",...Y,children:T})),M!=null&&M.type!==u.Typography&&!l&&(M=n.jsx(N,{variant:"body2",color:"textSecondary",...q,children:M})),n.jsxs(L,{...H,children:[T,M]})});function il(t){return u.generateUtilityClass("MuiMenuItem",t)}const zt=u.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),ol=(t,i)=>{const{ownerState:h}=t;return[i.root,h.dense&&i.dense,h.divider&&i.divider,!h.disableGutters&&i.gutters]},ll=t=>{const{disabled:i,dense:h,divider:a,disableGutters:p,selected:c,classes:l}=t,f={root:["root",h&&"dense",i&&"disabled",!p&&"gutters",a&&"divider",c&&"selected"]},d=u.composeClasses(f,il,l);return{...l,...d}},cl=u.styled(u.ButtonBase,{shouldForwardProp:t=>u.rootShouldForwardProp(t)||t==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:ol})(u.memoTheme(({theme:t})=>({...t.typography.body1,display:"flex",justifyContent:"flex-start",alignItems:"center",position:"relative",textDecoration:"none",minHeight:48,paddingTop:6,paddingBottom:6,boxSizing:"border-box",whiteSpace:"nowrap","&:hover":{textDecoration:"none",backgroundColor:(t.vars||t).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${zt.selected}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,(t.vars||t).palette.action.selectedOpacity),[`&.${zt.focusVisible}`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,`${(t.vars||t).palette.action.selectedOpacity} + ${(t.vars||t).palette.action.focusOpacity}`)}},[`&.${zt.selected}:hover`]:{backgroundColor:t.alpha((t.vars||t).palette.primary.main,`${(t.vars||t).palette.action.selectedOpacity} + ${(t.vars||t).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:t.alpha((t.vars||t).palette.primary.main,(t.vars||t).palette.action.selectedOpacity)}},[`&.${zt.focusVisible}`]:{backgroundColor:(t.vars||t).palette.action.focus},[`&.${zt.disabled}`]:{opacity:(t.vars||t).palette.action.disabledOpacity},[`& + .${Rs.root}`]:{marginTop:t.spacing(1),marginBottom:t.spacing(1)},[`& + .${Rs.inset}`]:{marginLeft:52},[`& .${jt.root}`]:{marginTop:0,marginBottom:0},[`& .${jt.inset}`]:{paddingLeft:36},[`& .${Ls.root}`]:{minWidth:36},variants:[{props:({ownerState:i})=>!i.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:i})=>i.divider,style:{borderBottom:`1px solid ${(t.vars||t).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:i})=>!i.dense,style:{[t.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:i})=>i.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...t.typography.body2,[`& .${Ls.root} svg`]:{fontSize:"1.25rem"}}}]}))),ke=fe.forwardRef(function(i,h){const a=u.useDefaultProps({props:i,name:"MuiMenuItem"}),{autoFocus:p=!1,component:c="li",dense:l=!1,divider:f=!1,disableGutters:d=!1,focusVisibleClassName:m,role:x="menuitem",tabIndex:S,className:b,...g}=a,k=fe.useContext(u.ListContext),w=fe.useMemo(()=>({dense:l||k.dense||!1,disableGutters:d}),[k.dense,l,d]),T=fe.useRef(null);u.useEnhancedEffect(()=>{p&&T.current&&T.current.focus()},[p]);const M={...a,dense:w.dense,divider:f,disableGutters:d},j=ll(a),I=u.useForkRef(T,h);let E;return a.disabled||(E=S!==void 0?S:-1),n.jsx(u.ListContext.Provider,{value:w,children:n.jsx(cl,{ref:I,role:x,tabIndex:E,component:c,focusVisibleClassName:u.clsx(j.focusVisible,m),className:u.clsx(j.root,b),...g,ownerState:M,classes:j})})}),Qe={postgres:[{label:"Host",name:"host",type:"text",required:!1},{label:"Port",name:"port",type:"number",required:!1},{label:"Database Name",name:"databaseName",type:"text",required:!1},{label:"User Name",name:"userName",type:"text",required:!1},{label:"Password",name:"password",type:"password",required:!1},{label:"Connection String",name:"connectionString",type:"text",required:!1}],bigquery:[{label:"Project ID",name:"defaultProjectId",type:"text",required:!1},{label:"Billing Project ID",name:"billingProjectId",type:"text",required:!1},{label:"Location",name:"location",type:"text",required:!1},{label:"Service Account Key JSON",name:"serviceAccountKeyJson",type:"text",required:!0},{label:"Maximum Bytes Billed",name:"maximumBytesBilled",type:"text",required:!1},{label:"Query Timeout Milliseconds",name:"queryTimeoutMilliseconds",type:"text",required:!1}],snowflake:[{label:"Account",name:"account",type:"text",required:!0},{label:"Username",name:"username",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Role",name:"role",type:"text",required:!1},{label:"Warehouse",name:"warehouse",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"Response Timeout Milliseconds",name:"responseTimeoutMilliseconds",type:"text",required:!1},{label:"Private Key",name:"privateKey",type:"password",required:!1},{label:"Private Key Passphrase",name:"privateKeyPass",type:"password",required:!1}],trino:[{label:"Server",name:"server",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!1},{label:"Catalog",name:"catalog",type:"text",required:!1},{label:"Schema",name:"schema",type:"text",required:!1},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!1},{label:"Peaka Key",name:"peakaKey",type:"password",required:!1}],databricks:[{label:"Host",name:"host",type:"text",required:!0},{label:"HTTP Path",name:"path",type:"text",required:!0},{label:"Access Token",name:"token",type:"password",required:!1},{label:"OAuth Client ID",name:"oauthClientId",type:"text",required:!1},{label:"OAuth Client Secret",name:"oauthClientSecret",type:"password",required:!1},{label:"Default Catalog",name:"defaultCatalog",type:"text",required:!1},{label:"Default Schema",name:"defaultSchema",type:"text",required:!1}],mysql:[{label:"Host",name:"host",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!0},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!0},{label:"Database",name:"database",type:"text",required:!0}],duckdb:[],motherduck:[{label:"Access Token",name:"accessToken",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1}],ducklake:[],publisher:[]},Jt={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},ya=Object.values(V.ConnectionTypeEnum).filter(t=>t!==V.ConnectionTypeEnum.Publisher),or={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},nn=[{label:"Credential Provider",name:"provider",type:"text",required:!1,selectOptions:[{label:"Access key pair",value:"config"},{label:"Host credential chain",value:"credential_chain"}]},{label:"Access Key ID",name:"accessKeyId",type:"text",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Secret Access Key",name:"secretAccessKey",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}},{label:"Credential Chain",name:"chain",type:"text",required:!1,visibleWhen:{field:"provider",value:"credential_chain"}},{label:"Region",name:"region",type:"text",required:!1},{label:"Endpoint",name:"endpoint",type:"text",required:!1},{label:"Session Token",name:"sessionToken",type:"password",required:!1,visibleWhen:{field:"provider",value:"config"}}],rn=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],ul=[{label:"Auth Type",name:"authType",type:"text",required:!0,selectOptions:[{label:"SAS Token",value:"sas_token"},{label:"Service Principal (SPN)",value:"service_principal"}]},{label:"SAS URL (e.g. https://account.blob.core.windows.net/container/file.parquet?sp=r&st=...)",name:"sasUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"sas_token"}},{label:"Tenant ID",name:"tenantId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client ID",name:"clientId",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Client Secret",name:"clientSecret",type:"password",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"Account Name",name:"accountName",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}},{label:"File URL (e.g. abfss://container/path/file.parquet)",name:"fileUrl",type:"text",required:!1,visibleWhen:{field:"authType",value:"service_principal"}}];function kn(t){return t==="postgres"||t==="bigquery"||t==="snowflake"?Qe[t]||[]:t==="s3"?nn:t==="gcs"?rn:t==="azure"?ul:[]}function dl({onSubmit:t,isSubmitting:i}){const[h,a]=$.useState(!1),[p,c]=$.useState("postgres"),[l,f]=$.useState([]),[d,m]=$.useState("postgres"),[x,S]=$.useState("s3"),[b,g]=$.useState("config"),k=()=>{a(!0)},w=()=>{a(!1),f([]),c("postgres"),m("postgres"),S("s3"),g("config")},T=async E=>{E.preventDefault();const L=new FormData(E.currentTarget),H=L.get("name")?.toString(),_=L.get("type")?.toString(),Y=Qe[_];if(!H)throw new Error("Name is required");if(!_)throw new Error("Type is required");let N;if(_==="ducklake"){const q={};if(d==="postgres"){const P=Qe.postgres,G={};if(P.forEach(K=>{const X=L.get(`ducklake_pg_${K.name}`)?.toString();X&&(G[K.name]=X)}),Object.keys(G).length===0)throw new Error("DuckLake requires catalog connection");q.postgresConnection=G}const B=L.get("ducklake_bucketUrl")?.toString();if(!B)throw new Error("DuckLake requires a bucket URL");const A={bucketUrl:B};if(x==="s3"){const P={};if(nn.forEach(G=>{const K=L.get(`ducklake_s3_${G.name}`)?.toString();K&&(P[G.name]=K)}),P.provider==="credential_chain")delete P.accessKeyId,delete P.secretAccessKey,delete P.sessionToken;else{if(delete P.chain,!P.accessKeyId)throw new Error("S3 Access Key ID is required");if(!P.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(P).length>0&&(A.s3Connection=P)}else if(x==="gcs"){const P={};if(rn.forEach(G=>{const K=L.get(`ducklake_gcs_${G.name}`)?.toString();K&&(P[G.name]=K)}),!P.keyId)throw new Error("GCS Key ID is required");if(!P.secret)throw new Error("GCS Secret is required");Object.keys(P).length>0&&(A.gcsConnection=P)}N={name:H,type:_,ducklakeConnection:{catalog:q,storage:A}}}else if(_==="duckdb"){if(l.length===0)throw new Error("DuckDB connection must have at least one attached database");const q=l.map((B,A)=>{const P=B.dbType,G=L.get(`attachedDb_${A}_name`)?.toString();if(!G)throw new Error(`Attached database at index ${A} must have a name`);const K={name:G,type:P},X=kn(P);if(X&&X.length>0){const J={};if(X.forEach(te=>{const W=L.get(`attachedDb_${A}_${te.name}`)?.toString();W&&(J[te.name]=W)}),P==="s3"){if(J.provider==="credential_chain")delete J.accessKeyId,delete J.secretAccessKey,delete J.sessionToken;else if(delete J.chain,!J.accessKeyId||!J.secretAccessKey)throw new Error(`Attached database "${G}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const U=or[P];U&&(K[U]=J)}return K});N={name:H,type:_,duckdbConnection:{attachedDatabases:q}}}else{const q={};if(Y.forEach(B=>{const A=L.get(B.name)?.toString();A&&(q[B.name]=A)}),_==="postgres"){if(!!!q.connectionString?.trim()){const A=["host","port","databaseName","userName","password"];for(const P of A)if(!q[P])throw new Error(`${Y.find(G=>G.name===P)?.label||P} is required`)}}else if(_==="bigquery"){if(!q.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if(_==="snowflake"){if(!q.account)throw new Error("Account is required");if(!q.username)throw new Error("Username is required");if(!q.warehouse)throw new Error("Warehouse is required");if(!q.password&&!q.privateKey)throw new Error("Either password or private key is required")}else if(_==="trino"){if(!q.server)throw new Error("Server is required");if(!q.user)throw new Error("User is required");if(q.server.trim().startsWith("https://")&&!q.password&&!q.peakaKey)throw new Error("Password is required for HTTPS connections (or use Peaka Key)")}else if(_==="mysql"){const B=["host","port","database","user","password"];for(const A of B)if(!q[A])throw new Error(`${Y.find(P=>P.name===A)?.label||A} is required`)}else if(_==="motherduck"){if(!q.accessToken)throw new Error("Access Token is required")}else if(_==="databricks"){if(!q.host)throw new Error("Host is required");if(!q.path)throw new Error("HTTP Path is required");const B=q.oauthClientId&&q.oauthClientSecret;if(!q.token&&!B)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}N={name:H,type:_,[Jt[_]]:q}}await t(N),w()},M=()=>{f([...l,{name:"",dbType:"postgres"}])},j=E=>{f(l.filter((L,H)=>H!==E))},I=(E,L)=>{const H=[...l];H[E]={...H[E],dbType:L},f(H)};return n.jsxs($.Fragment,{children:[n.jsx(u.AddButton,{label:"Connection",onClick:k}),n.jsx(u.AppDialog,{open:h,onClose:w,title:"New connection",description:"Add a connection so packages in this environment can query your database with Malloy.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:i,onClick:w,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"connection-form",variant:"contained",loading:i,children:"Create connection"})]}),children:n.jsx("form",{onSubmit:T,id:"connection-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),n.jsx(u.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:p,select:!0,onChange:E=>c(E.target.value),children:ya.map(E=>n.jsx(ke,{value:E,children:E},E))}),p==="ducklake"?n.jsxs(ge,{sx:{mt:2},children:[n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(u.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:d,select:!0,onChange:E=>m(E.target.value),children:n.jsx(ke,{value:"postgres",children:"PostgreSQL"})}),d==="postgres"&&n.jsx(n.Fragment,{children:Qe.postgres.map(E=>n.jsx(u.TextField,{id:`ducklake_pg_${E.name}`,name:`ducklake_pg_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small"},`pg_${E.name}`))})]}),n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(u.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:x,select:!0,onChange:E=>S(E.target.value),children:[n.jsx(ke,{value:"s3",children:"S3"}),n.jsx(ke,{value:"gcs",children:"GCS"})]}),n.jsx(u.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:x==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small"}),x==="s3"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),nn.filter(E=>E.visibleWhen?b===E.visibleWhen.value:!0).map(E=>n.jsx(u.TextField,{id:`ducklake_s3_${E.name}`,name:`ducklake_s3_${E.name}`,label:E.label,type:E.selectOptions?void 0:E.type,fullWidth:!0,size:"small",required:E.required,select:!!E.selectOptions,defaultValue:E.selectOptions?b:void 0,onChange:E.name==="provider"?L=>g(L.target.value):void 0,placeholder:E.name==="region"?"us-east-1":void 0,children:E.selectOptions?.map(L=>n.jsx(ke,{value:L.value,children:L.label},L.value))},`s3_${E.name}`))]}),x==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),rn.map(E=>n.jsx(u.TextField,{id:`ducklake_gcs_${E.name}`,name:`ducklake_gcs_${E.name}`,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},`gcs_${E.name}`))]})]})]}):p==="duckdb"?n.jsxs(ge,{sx:{mt:2},children:[n.jsxs(ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(u.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(u.SecondaryButton,{label:"Database",icon:n.jsx(u.AddIcon,{}),onClick:M,ariaLabel:"Add database"})]}),l.length===0&&n.jsx(u.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),l.map((E,L)=>{const H=kn(E.dbType);return n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(u.Typography,{variant:"subtitle2",children:["Database ",L+1]}),n.jsx(u.IconButton,{onClick:()=>j(L),size:"small",color:"error",children:n.jsx(pa,{fontSize:"small"})})]}),n.jsx(u.TextField,{required:!0,id:`attachedDb_${L}_name`,name:`attachedDb_${L}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:E.name}),n.jsx(u.TextField,{id:`attachedDb_${L}_type`,name:`attachedDb_${L}_type`,label:"Database Type",fullWidth:!0,size:"small",value:E.dbType,select:!0,onChange:_=>I(L,_.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(_=>n.jsx(ke,{value:_,children:_},_))}),H.filter(_=>_.visibleWhen?(E[_.visibleWhen.field]||H.find(N=>N.name===_.visibleWhen?.field)?.selectOptions?.[0]?.value)===_.visibleWhen.value:!0).map(_=>n.jsx(u.TextField,{id:`attachedDb_${L}_${_.name}`,name:`attachedDb_${L}_${_.name}`,label:_.label,type:_.selectOptions?void 0:_.type,fullWidth:!0,size:"small",required:_.required,select:!!_.selectOptions,defaultValue:_.selectOptions?.[0]?.value,onChange:_.selectOptions?Y=>{const N=[...l];N[L]={...N[L],[_.name]:Y.target.value},f(N)}:void 0,children:_.selectOptions?.map(Y=>n.jsx(ke,{value:Y.value,children:Y.label},Y.value))},_.name))]},L)})]}):Qe[p].map(E=>n.jsx(u.TextField,{id:E.name,name:E.name,label:E.label,type:E.type,fullWidth:!0,size:"small",required:E.required},E.name))]})})})]})}function hl({connection:t,onCloseDialog:i,isMutating:h,onDelete:a}){const[p,c]=$.useState(!1),l=()=>{c(!0)},f=()=>{c(!1),i()};return n.jsxs($.Fragment,{children:[n.jsxs(ke,{"aria-label":`Delete connection ${t?.name??""}`.trim(),onClick:d=>{d.stopPropagation(),l()},sx:{color:"error.main"},children:[n.jsx(pr,{sx:{color:"inherit"},children:n.jsx(He.Delete,{fontSize:"small"})}),n.jsx(yr,{children:"Delete"})]}),n.jsx(u.AppDialog,{open:p,onClose:f,title:"Delete connection",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{onClick:f,children:"Cancel"}),n.jsx(u.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>a(),loading:h,children:"Delete connection"})]}),children:n.jsxs(u.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:t.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const _s=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function Ps(t){const i=t.duckdbConnection?.attachedDatabases;return!i||i.length===0?[]:i.map(h=>({name:h.name||"",dbType:h.type||"postgres"}))}function qs(t){const i=t.ducklakeConnection;return i&&i.storage?.gcsConnection?"gcs":"s3"}function fl({connection:t,onSubmit:i,isSubmitting:h,onCloseDialog:a}){const[p,c]=$.useState(!1),[l,f]=$.useState(t.type),d=$.useMemo(()=>new Set(t.withheldFields??[]),[t.withheldFields]),[m,x]=$.useState(()=>Ps(t)),[S,b]=$.useState("postgres"),[g,k]=$.useState(()=>qs(t)),[w,T]=$.useState(()=>t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),M=()=>{x(Ps(t)),f(t.type),T(t.ducklakeConnection?.storage?.s3Connection?.provider??"config"),b("postgres"),k(qs(t)),c(!0)},j=()=>{c(!1),a?.()},I=async N=>{N.preventDefault();const q=new FormData(N.currentTarget),B=q.get("name")?.toString(),A=q.get("type")?.toString(),P=Qe[A];if(!B)throw new Error("Name is required");if(!A)throw new Error("Type is required");let G;if(A==="ducklake"){const K={};if(S==="postgres"){const U=Qe.postgres,te={};if(U.forEach(W=>{const Q=q.get(`ducklake_pg_${W.name}`)?.toString();Q&&(te[W.name]=Q)}),Object.keys(te).length===0)throw new Error("DuckLake requires catalog connection");K.postgresConnection=te}const X=q.get("ducklake_bucketUrl")?.toString();if(!X)throw new Error("DuckLake requires a bucket URL");const J={bucketUrl:X};if(g==="s3"){const U={};nn.forEach(W=>{const Q=q.get(`ducklake_s3_${W.name}`)?.toString();Q&&(U[W.name]=Q)});const te=t.ducklakeConnection?.storage?.s3Connection;if(te&&(!U.provider&&te.provider&&(U.provider=te.provider),!U.chain&&te.chain&&(U.chain=te.chain),!U.accessKeyId&&te.accessKeyId&&(U.accessKeyId=te.accessKeyId)),U.provider==="credential_chain")delete U.accessKeyId,delete U.secretAccessKey,delete U.sessionToken;else if(delete U.chain,!U.accessKeyId)throw new Error("S3 Access Key ID is required");Object.keys(U).length>0&&(J.s3Connection=U)}else if(g==="gcs"){const U={};rn.forEach(W=>{const Q=q.get(`ducklake_gcs_${W.name}`)?.toString();Q&&(U[W.name]=Q)});const te=t.ducklakeConnection?.storage?.gcsConnection;if(te&&!U.keyId&&te.keyId&&(U.keyId=te.keyId),!U.keyId)throw new Error("GCS Key ID is required");Object.keys(U).length>0&&(J.gcsConnection=U)}G={name:B,type:A,ducklakeConnection:{catalog:K,storage:J}}}else if(A==="duckdb"){if(m.length===0)throw new Error("DuckDB connection must have at least one attached database");const K=m.map((X,J)=>{const U=X.dbType,te=q.get(`attachedDb_${J}_name`)?.toString();if(!te)throw new Error(`Attached database at index ${J} must have a name`);const W={name:te,type:U},Q=kn(U);if(Q&&Q.length>0){const R={};if(Q.forEach(de=>{const ae=q.get(`attachedDb_${J}_${de.name}`)?.toString();ae&&(R[de.name]=ae)}),U==="s3"){if(R.provider==="credential_chain")delete R.accessKeyId,delete R.secretAccessKey,delete R.sessionToken;else if(delete R.chain,!R.accessKeyId||!R.secretAccessKey)throw new Error(`Attached database "${te}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const Z=or[U];Z&&(W[Z]=R)}return W});G={name:B,type:A,duckdbConnection:{attachedDatabases:K}}}else{const K=t[Jt[A]]||{},X={};if(P.forEach(J=>{const U=q.get(J.name)?.toString(),te=K[J.name];U?X[J.name]=U:_s.has(J.name)||(U!==void 0?X[J.name]=U:te&&(X[J.name]=te))}),A==="postgres"){const J=["host","port","databaseName","userName"],U=d.has("postgresConnection.connectionString");if(!(!!X.connectionString?.trim()||U)){const W=J;for(const Q of W)if(!X[Q])throw new Error(`${P.find(R=>R.name===Q)?.label||Q} is required`)}}else if(A==="snowflake"){if(!X.account)throw new Error("Account is required");if(!X.username)throw new Error("Username is required");if(!X.warehouse)throw new Error("Warehouse is required")}else if(A==="trino"){if(!X.server)throw new Error("Server is required");if(!X.user)throw new Error("User is required")}else if(A==="mysql"){const J=["host","port","database","user"];for(const U of J)if(!X[U])throw new Error(`${P.find(te=>te.name===U)?.label||U} is required`)}else if(A==="databricks"){if(!X.host)throw new Error("Host is required");if(!X.path)throw new Error("HTTP Path is required")}G={name:B,type:A,[Jt[A]]:X}}await i(G),j()},E=()=>{x([...m,{name:"",dbType:"postgres"}])},L=N=>{x(m.filter((q,B)=>B!==N))},H=(N,q)=>{const B=[...m];B[N]={...B[N],dbType:q},x(B)},_=(N,q)=>{const B=t.duckdbConnection?.attachedDatabases;if(!B||!B[N])return"";const A=B[N],P=or[A.type||""];return P&&A[P]?A[P][q]??"":""},Y=N=>{const q=t.ducklakeConnection;if(!q)return"";if(N.startsWith("pg_")){const B=N.replace("pg_","");return q.catalog?.postgresConnection?.[B]??""}if(N==="bucketUrl")return q.storage?.bucketUrl??"";if(N.startsWith("s3_")){const B=N.replace("s3_","");return q.storage?.s3Connection?.[B]??""}if(N.startsWith("gcs_")){const B=N.replace("gcs_","");return q.storage?.gcsConnection?.[B]??""}return""};return n.jsxs($.Fragment,{children:[n.jsxs(ke,{"aria-label":`Edit connection ${t?.name??""}`.trim(),onClick:N=>{N.preventDefault(),N.stopPropagation(),M()},children:[n.jsx(pr,{children:n.jsx(He.Edit,{fontSize:"small"})}),n.jsx(yr,{children:"Edit"})]}),n.jsx(u.AppDialog,{open:p,onClose:j,title:"Edit connection",description:"Change how packages in this environment reach your database.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:h,onClick:j,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"connection-form",variant:"contained",loading:h,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:I,id:"connection-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:t.name}),n.jsx(u.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:l,select:!0,onChange:N=>f(N.target.value),children:ya.map(N=>n.jsx(ke,{value:N,children:N},N))}),l==="ducklake"?n.jsxs(ge,{sx:{mt:2},children:[n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),n.jsx(u.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:S,select:!0,onChange:N=>b(N.target.value),children:n.jsx(ke,{value:"postgres",children:"PostgreSQL"})}),S==="postgres"&&n.jsx(n.Fragment,{children:Qe.postgres.map(N=>n.jsx(u.TextField,{id:`ducklake_pg_${N.name}`,name:`ducklake_pg_${N.name}`,label:N.label,type:N.type,fullWidth:!0,size:"small",defaultValue:Y(`pg_${N.name}`)},`pg_${N.name}`))})]}),n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsx(u.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),n.jsxs(u.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:g,select:!0,onChange:N=>k(N.target.value),children:[n.jsx(ke,{value:"s3",children:"S3"}),n.jsx(ke,{value:"gcs",children:"GCS"})]}),n.jsx(u.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:g==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small",defaultValue:Y("bucketUrl")}),g==="s3"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),nn.filter(N=>N.visibleWhen?w===N.visibleWhen.value:!0).map(N=>n.jsx(u.TextField,{id:`ducklake_s3_${N.name}`,name:`ducklake_s3_${N.name}`,label:N.label,type:N.selectOptions?void 0:N.type,fullWidth:!0,size:"small",required:N.required&&N.name!=="secretAccessKey",select:!!N.selectOptions,defaultValue:N.selectOptions?w:Y(`s3_${N.name}`),onChange:N.name==="provider"?q=>T(q.target.value):void 0,placeholder:N.name==="region"?"us-east-1":N.name==="secretAccessKey"&&d.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:N.selectOptions?.map(q=>n.jsx(ke,{value:q.value,children:q.label},q.value))},`s3_${N.name}`))]}),g==="gcs"&&n.jsxs(n.Fragment,{children:[n.jsx(u.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),rn.map(N=>n.jsx(u.TextField,{id:`ducklake_gcs_${N.name}`,name:`ducklake_gcs_${N.name}`,label:N.label,type:N.type,fullWidth:!0,size:"small",required:N.required&&N.name!=="secret",defaultValue:Y(`gcs_${N.name}`),placeholder:N.name==="secret"&&d.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${N.name}`))]})]})]}):l==="duckdb"?n.jsxs(ge,{sx:{mt:2},children:[n.jsxs(ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsx(u.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),n.jsx(u.SecondaryButton,{label:"Database",icon:n.jsx(u.AddIcon,{}),onClick:E,ariaLabel:"Add database"})]}),m.length===0&&n.jsx(u.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),m.map((N,q)=>{const B=kn(N.dbType);return n.jsxs(ge,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[n.jsxs(ge,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[n.jsxs(u.Typography,{variant:"subtitle2",children:["Database ",q+1]}),n.jsx(u.IconButton,{"aria-label":`Remove attached database ${q+1}`,onClick:()=>L(q),size:"small",color:"error",children:n.jsx(pa,{fontSize:"small"})})]}),n.jsx(u.TextField,{required:!0,id:`attachedDb_${q}_name`,name:`attachedDb_${q}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:N.name}),n.jsx(u.TextField,{id:`attachedDb_${q}_type`,name:`attachedDb_${q}_type`,label:"Database Type",fullWidth:!0,size:"small",value:N.dbType,select:!0,onChange:A=>H(q,A.target.value),children:Object.values(V.AttachedDatabaseTypeEnum).map(A=>n.jsx(ke,{value:A,children:A},A))}),B.filter(A=>A.visibleWhen?(N[A.visibleWhen.field]||_(q,A.visibleWhen.field)||B.find(G=>G.name===A.visibleWhen?.field)?.selectOptions?.[0]?.value)===A.visibleWhen.value:!0).map(A=>n.jsx(u.TextField,{id:`attachedDb_${q}_${A.name}`,name:`attachedDb_${q}_${A.name}`,label:A.label,type:A.selectOptions?void 0:A.type,fullWidth:!0,size:"small",required:A.required,select:!!A.selectOptions,defaultValue:_(q,A.name)||A.selectOptions?.[0]?.value,onChange:A.selectOptions?P=>{const G=[...m];G[q]={...G[q],[A.name]:P.target.value},x(G)}:void 0,children:A.selectOptions?.map(P=>n.jsx(ke,{value:P.value,children:P.label},P.value))},A.name))]},q)})]}):Qe[l].map(N=>{const q=t?.[Jt[l]??""]?.[N.name??""]??"",B=N.type==="password"||_s.has(N.name),A=d.has(`${Jt[l]??""}.${N.name}`);return n.jsx(u.TextField,{id:N.name,name:N.name,label:N.label,type:N.type,fullWidth:!0,size:"small",required:N.required&&!B&&!q,defaultValue:q,placeholder:A?"Leave empty to keep existing":void 0,helperText:B?A?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0},N.name)})]})})})]})}function Ws(t,i){return!t||t.type!=="duckdb"?!1:(t.duckdbConnection?.attachedDatabases||[]).some(a=>a.type==="azure"&&a.name===i)}function ml(t){return t.startsWith("gs://")||t.startsWith("s3://")||t.startsWith("https://")||t.startsWith("abfss://")||t.startsWith("az://")}function ga({connectionName:t,resourceUri:i,schema:h,connection:a}){const{apiClients:p}=V.useServer(),{environmentName:c}=u.parseResourceUri(i),[l,f]=$.useState(null),[d,m]=$.useState(h||null),[x,S]=$.useState(!1),{data:b,isError:g,isLoading:k,error:w}=u.useQueryWithApiError({queryKey:["schemas",c,t],queryFn:()=>p.connections.listSchemas(c,t)}),T=b?.data||[];return n.jsxs(v.Grid,{container:!0,spacing:1,children:[!h&&n.jsx(v.Grid,{size:{xs:12,md:4},children:n.jsxs(v.Paper,{sx:{p:1,m:0},children:[n.jsxs(v.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[n.jsx(v.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),n.jsx(v.FormControlLabel,{control:n.jsx(v.Switch,{checked:x,onChange:M=>S(M.target.checked)}),label:"Hidden Schemas"})]}),n.jsx(v.Divider,{sx:{mt:"2px"}}),n.jsxs(v.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[k&&n.jsx(u.Loading,{text:"Loading schemas..."}),g&&n.jsx(u.ApiErrorDisplay,{error:w,context:`${c} > ${t} > Schemas`}),!k&&!g&&T.length===0&&n.jsx(v.Typography,{variant:"body2",children:"No Schemas"}),!k&&!g&&T.length>0&&n.jsx(v.List,{dense:!0,disablePadding:!0,children:T.map(M=>{const j=M.name;if(M.isHidden&&!x)return null;const E=d===j;return n.jsx(v.ListItemButton,{selected:E,onClick:()=>{m(j),f(null)},children:n.jsx(v.ListItemText,{primary:j})},j)})})]})]})}),n.jsx(v.Grid,{size:{xs:12,md:h?6:4},children:d&&n.jsx(v.Paper,{sx:{p:1,m:0},children:n.jsx(gl,{connectionName:t,schemaName:d,onTableSelect:M=>{f(M)},resourceUri:i,connection:a})})}),n.jsx(v.Grid,{size:{xs:12,md:h?6:4},children:d&&l&&n.jsx(pl,{environmentName:c,connectionName:t,schemaName:d,tableResource:l})})]})}function pl({environmentName:t,connectionName:i,schemaName:h,tableResource:a}){const{apiClients:p}=V.useServer(),{data:c,isLoading:l,isError:f,error:d}=u.useQueryWithApiError({queryKey:["connectionTableDetail",t,i,h,a],queryFn:()=>p.connections.getTable(t,i,h,a),enabled:!!h&&!!a}),m={resource:c?.data?.resource??a,columns:c?.data?.columns??[]};return n.jsxs(v.Paper,{sx:{p:1,m:0},children:[f&&n.jsx(u.ApiErrorDisplay,{error:d,context:`${t} > ${i} > ${h} > ${a}`}),!f&&n.jsx(yl,{table:m,loading:l})]})}function yl({table:t,loading:i}){return i?n.jsx(u.Loading,{text:"Loading columns..."}):n.jsxs(n.Fragment,{children:[n.jsxs(v.Typography,{variant:"overline",fontWeight:"bold",sx:{display:"block",wordBreak:"break-all"},children:[t.resource.includes("://")||/\.(parquet|csv|json|tsv|ndjson)$/i.test(t.resource)?"File":"Table",": ",t.resource]}),n.jsx(v.Divider,{}),n.jsx(v.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:n.jsx(v.TableContainer,{children:n.jsxs(v.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[n.jsx(v.TableHead,{children:n.jsxs(v.TableRow,{children:[n.jsx(v.TableCell,{children:"NAME"}),n.jsx(v.TableCell,{children:"TYPE"})]})}),n.jsx(v.TableBody,{children:t.columns?.sort((h,a)=>h.name.localeCompare(a.name))?.map(h=>n.jsxs(v.TableRow,{children:[n.jsx(v.TableCell,{children:h.name}),n.jsx(v.TableCell,{children:h.type})]},h.name))})]})})})]})}function gl({connectionName:t,schemaName:i,onTableSelect:h,resourceUri:a,connection:p}){const{environmentName:c}=u.parseResourceUri(a),{apiClients:l}=V.useServer(),[f,d]=$.useState(""),{data:m,isSuccess:x,isError:S,error:b,isLoading:g}=u.useQueryWithApiError({queryKey:["tablesInSchema",c,t,i],queryFn:()=>l.connections.listTables(c,t,i)}),k=Ws(p,i),w=M=>k?M:M.split(".").pop()||M,T=x&&m?.data?m.data.filter(M=>w(M.resource).toLowerCase().includes(f.toLowerCase())).sort((M,j)=>w(M.resource).localeCompare(w(j.resource))):[];return n.jsxs(n.Fragment,{children:[n.jsx(v.Typography,{variant:"overline",fontWeight:"bold",children:ml(i)||Ws(p,i)?`Files in ${i}`:`Tables in ${i}`}),n.jsx(v.Divider,{}),n.jsx(v.Box,{sx:{mt:1,mb:1},children:n.jsx(v.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:f,onChange:M=>d(M.target.value),variant:"outlined"})}),n.jsx(v.Divider,{}),n.jsxs(v.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[g&&n.jsx(u.Loading,{text:"Fetching Tables..."}),S&&n.jsx(u.ApiErrorDisplay,{error:b,context:`${c} > ${t} > ${i}`}),x&&T.length===0&&n.jsx(v.Typography,{variant:"body2",children:"No Tables"}),x&&m?.data&&m.data.length>0&&n.jsx(v.List,{dense:!0,disablePadding:!0,children:T.map(M=>{let j=w(M.resource);return!k&&M.resource.includes("://")&&(j=M.resource.split("/").pop()||M.resource),n.jsx(v.ListItemButton,{onClick:()=>h(M.resource),children:n.jsx(v.ListItemText,{primary:j,secondary:M.columns.length>0?`${M.columns.length} columns`:void 0})},M.resource)})})]})]})}const xl={bigquery:"BigQuery",snowflake:"Snowflake",postgres:"PostgreSQL",mysql:"MySQL",trino:"Trino",databricks:"Databricks",duckdb:"DuckDB",ducklake:"DuckLake",s3:"S3",gcs:"GCS",azure:"Azure"};function bl(t){return t?xl[t]??t:""}function vl({resourceUri:t}){const{apiClients:i,mutable:h}=V.useServer(),a=Mn.useQueryClient(),{environmentName:p}=u.parseResourceUri(t),[c,l]=$.useState(""),[f,d]=$.useState(null),m=u.encodeResourceUri({environmentName:p,connectionName:f}),{data:x,isSuccess:S,isError:b,error:g}=u.useQueryWithApiError({queryKey:["connections",p],queryFn:()=>i.connections.listConnections(p)}),k=u.useMutationWithApiError({mutationFn:Ke("connection","create",I=>i.environments.updateEnvironment(p,{name:p,connections:[...x.data,I]})),onSuccess(){l("Connection added successfully"),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),w=u.useMutationWithApiError({mutationFn:Ke("connection","update",I=>i.environments.updateEnvironment(p,{name:p,connections:x.data.map(E=>E.name===I.name?I:E)})),onSuccess(I,E){l(`Connection ${E.name} updated successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),T=u.useMutationWithApiError({mutationFn:Ke("connection","delete",I=>{if(!I.name)throw new Error("Cannot delete a connection with no name");return i.connections.deleteConnection(p,I.name)}),onSuccess(I,E){l(`Connection ${E.name} deleted successfully`),a.invalidateQueries({queryKey:["connections",p]})},onError(I){l(I.message)}}),M=S?[...x.data].sort((I,E)=>(I.name??"").localeCompare(E.name??"")):[],j=k.isPending||w.isPending||T.isPending;return n.jsxs(ze,{title:"Connections",...S?{count:M.length}:{},description:"Database connections available to packages in this environment",...h&&S?{action:n.jsx(dl,{onSubmit:I=>k.mutateAsync(I),isSubmitting:k.isPending})}:{},children:[!S&&!b&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),b&&n.jsx(u.ApiErrorDisplay,{error:g,context:`${p} > Connections`}),S&&M.length===0&&n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),S&&M.length>0&&n.jsx(v.Stack,{children:M.map(I=>n.jsx(Sl,{connection:I,mutable:h,isMutating:j,onOpenExplorer:()=>d(I.name??null),onEdit:E=>w.mutateAsync(E),onDelete:E=>T.mutateAsync(E)},I.name))}),n.jsx(v.Snackbar,{open:c!=="",autoHideDuration:6e3,onClose:()=>l(""),message:c}),n.jsx(u.AppDialog,{open:f!==null,onClose:()=>d(null),maxWidth:"lg",title:`Connection explorer: ${f??""}`,showClose:!0,children:f&&n.jsx(ga,{resourceUri:m,connectionName:f,connection:x?.data?.find(I=>I.name===f)})})]})}function Sl({connection:t,mutable:i,isMutating:h,onOpenExplorer:a,onEdit:p,onDelete:c}){const[l,f]=$.useState(null),d=!!l,m=S=>{S.stopPropagation(),f(S.currentTarget)},x=()=>f(null);return n.jsx(jn,{icon:n.jsx(Ko,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.connection,label:t.name??"",ariaLabel:t.name??"",description:bl(t.type),onClick:a,...i?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(v.IconButton,{size:"small",onClick:m,"aria-label":`Connection actions for ${t.name??""}`.trim(),children:n.jsx(He.MoreVert,{fontSize:"small"})}),n.jsxs(v.Menu,{anchorEl:l,open:d,onClose:x,onClick:S=>S.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(fl,{connection:t,onSubmit:p,isSubmitting:h,onCloseDialog:x}),n.jsx(hl,{connection:t,onCloseDialog:x,isMutating:h,onDelete:()=>c(t)})]})]})}:{}})}const wl=u.createSvgIcon([n.jsx("path",{d:"M20 2H4c-1 0-2 .9-2 2v3.01c0 .72.43 1.34 1 1.69V20c0 1.1 1.1 2 2 2h14c.9 0 2-.9 2-2V8.7c.57-.35 1-.97 1-1.69V4c0-1.1-1-2-2-2m-1 18H5V9h14zm1-13H4V4h16z"},"0"),n.jsx("path",{d:"M9 12h6v2H9z"},"1")]);function kl({resourceUri:t,onCloseDialog:i}){const[h,a]=$.useState(!1),{apiClients:p}=V.useServer(),c=()=>{a(!0)},l=()=>{a(!1),i()},{environmentName:f,packageName:d}=u.parseResourceUri(t),m=Dt({mutationFn:()=>p.packages.deletePackage(f,d),success:"Package deleted",invalidates:[["packages",f]],closeDialog:l,resource:"package",action:"delete"});return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:c,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Delete,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Delete"})]}),n.jsx(u.AppDialog,{open:h,onClose:l,title:"Delete package",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{onClick:l,children:"Cancel"}),n.jsx(u.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>m.mutate(),loading:m.isPending,children:"Delete package"})]}),children:n.jsxs(u.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:d}),"? The package stops being served and this cannot be undone."]})}),m.notice]})}function Cl({package:t,resourceUri:i,onCloseDialog:h}){const[a,p]=$.useState(!1),{apiClients:c}=V.useServer(),l=()=>{p(!0)},f=()=>{p(!1),h()},{packageName:d,environmentName:m}=u.parseResourceUri(i),x=Dt({mutationFn(b){return c.packages.updatePackage(m,d,{name:d,description:b.description})},success:"Package updated",invalidates:[["packages",m]],closeDialog:f,resource:"package",action:"update"}),S=b=>{b.preventDefault();const k=new FormData(b.currentTarget).get("description")?.toString();x.mutate({description:k})};return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:l,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Edit,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Edit"})]}),n.jsx(u.AppDialog,{open:a,onClose:f,title:"Edit package",description:`What ${t.name} is, for the people who open it.`,actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:x.isPending,onClick:f,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"package-form",variant:"contained",loading:x.isPending,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:S,id:"package-form",children:n.jsxs(v.Stack,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:t.name,InputLabelProps:{shrink:!0}}),n.jsx(u.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:t.description,InputLabelProps:{shrink:!0}})]})})}),x.notice]})}function xa({onSelectPackage:t,resourceUri:i}){const{apiClients:h}=V.useServer(),{environmentName:a}=u.parseResourceUri(i),{data:p,isSuccess:c,isError:l,error:f}=u.useQueryWithApiError({queryKey:["packages",a],queryFn:()=>h.packages.listPackages(a)});if(l)return n.jsx(u.ApiErrorDisplay,{error:f,context:`${a} > Packages`});if(!c)return n.jsx(u.Loading,{text:"Fetching Packages..."});const d=[...p.data].sort((m,x)=>m.name.localeCompare(x.name));return n.jsx(v.Stack,{children:d.map(m=>{const x=u.encodeResourceUri({environmentName:a,packageName:m.name});return n.jsx(Tl,{pkg:m,packageResourceUri:x,onSelectPackage:t},m.name)})})}function Tl({pkg:t,packageResourceUri:i,onSelectPackage:h}){const{mutable:a}=V.useServer(),[p,c]=$.useState(null),l=!!p,f=m=>{m.stopPropagation(),c(m.currentTarget)},d=()=>c(null);return n.jsx(jn,{icon:n.jsx(wl,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.package,label:t.name,ariaLabel:t.name,...t.description?{description:t.description}:{},onClick:m=>h(t.name,m),...a?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(v.IconButton,{size:"small",onClick:f,"aria-label":`Package actions for ${t.name}`,children:n.jsx(He.MoreVert,{fontSize:"small"})}),n.jsxs(v.Menu,{anchorEl:p,open:l,onClose:d,onClick:m=>m.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(Cl,{package:t,resourceUri:i,onCloseDialog:d}),n.jsx(kl,{resourceUri:i,onCloseDialog:d})]})]})}:{}})}function Ml({onSelectPackage:t,resourceUri:i}){const{apiClients:h,mutable:a}=V.useServer(),{environmentName:p}=u.parseResourceUri(i),c=u.useQueryWithApiError({queryKey:["packages",p],queryFn:()=>h.packages.listPackages(p)});return $.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),n.jsxs(v.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[n.jsxs(v.Box,{sx:{mb:4},children:[n.jsx(v.Box,{children:n.jsx(mr,{label:"Publisher",onClick:l=>t("/",l)})}),n.jsx(v.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:p}),n.jsx(v.Typography,{variant:"body2",color:"text.secondary",children:"Manage packages and database connections in this environment. Open a package to explore its models and notebooks."})]}),n.jsx(ze,{title:"Packages",...c.isSuccess?{count:c.data.data.length}:{},description:"Published packages available for use in this environment",...a?{action:n.jsx(Xo,{resourceUri:i})}:{},children:n.jsx(xa,{onSelectPackage:t,resourceUri:i})}),n.jsx(vl,{resourceUri:i}),n.jsx($o,{resourceUri:i})]})}u.dayjs.extend(u.utc);function Xn(t){switch(t){case"Star":return["Equals","Contains"];case"MinMax":return["Equals","Less Than","Greater Than","Between"];case"DateMinMax":return["Equals","Before","After","Between"];case"Retrieval":return["Semantic Search"];case"Boolean":return["Equals"];case"NONE":default:return[]}}function jl(t){return t==="DateMinMax"}function Kn(t){return t==="Between"}function Dl({spec:t,values:i,selection:h,onChange:a,retrievalFn:p}){const c=()=>h?.matchType?h.matchType:t.defaultMatchType?t.defaultMatchType:t.filterType==="DateMinMax"?"Between":Xn(t.filterType)[0]||"Equals",[l,f]=$.useState(c()),[d,m]=$.useState(h?.value??""),[x,S]=$.useState(h?.value2??""),[b,g]=$.useState([]),[k,w]=$.useState(!1),[T,M]=$.useState(""),[j,I]=$.useState(!1),[E,L]=$.useState(!1),H=$.useRef(null),_=$.useRef(0),[Y,N]=$.useState(!1);$.useEffect(()=>{if(t.filterType!=="Retrieval"||!p)return;const W=T.trim();if(W.length<=2){g([]),I(!1);return}return H.current&&clearTimeout(H.current),H.current=setTimeout(async()=>{_.current+=1;const Q=_.current;w(!0);try{const R=await p(W,t);Q===_.current&&g(R)}catch(R){Q===_.current&&(console.error("Retrieval failed",R),g([]))}finally{Q===_.current&&(w(!1),I(!0))}},500),()=>{H.current&&clearTimeout(H.current)}},[T,t,p]),$.useEffect(()=>{h===null?(m(""),S(""),f(t.defaultMatchType??(t.filterType==="DateMinMax"?"Between":Xn(t.filterType)[0]||"Equals"))):h&&(f(h.matchType),m(h.value??""),S(h.value2??""))},[h,t.filterType,t.defaultMatchType]);const q=Xn(t.filterType),B=jl(t.filterType),A=Kn(l),P=B&&i.length>=2&&i[0].value instanceof Date?u.dayjs.utc(i[0].value):void 0,G=B&&i.length>=2&&i[1].value instanceof Date?u.dayjs.utc(i[1].value):void 0,K=t.filterType==="MinMax"&&i.length>=2&&typeof i[0].value=="number"?i[0].value:void 0,X=t.filterType==="MinMax"&&i.length>=2&&typeof i[1].value=="number"?i[1].value:void 0;if(q.length===0)return null;const J=W=>{const Q=W.target.value;f(Q),Kn(Q)||S(""),d&&a({dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:Q,value:d,...Kn(Q)&&x&&{value2:x}})},U=(W,Q)=>{m(W??""),Q!==void 0&&S(Q??"");const R=Array.isArray(W)&&W.length===0;a(!R&&W!==""&&W!==null&&W!==void 0?{dimensionName:t.dimensionName,source:t.source,filterName:t.filterName,matchType:l,value:W,...A&&Q&&{value2:Q}}:null)},te=()=>{m(""),S(""),a(null)};return n.jsxs(ge,{sx:{display:"flex",flexDirection:"column",gap:1.5,fontSize:"0.75rem","& .MuiInputBase-root":{fontSize:"0.75rem"},"& .MuiInputBase-input":{padding:"6px 10px"},"& .MuiSelect-select":{padding:"6px 10px !important"},"& .MuiAutocomplete-input":{padding:"0 !important"},"& .MuiAutocomplete-root .MuiInputBase-root":{padding:"5px 10px",minHeight:"29.5px",boxSizing:"border-box",flexWrap:"wrap"},"& .MuiChip-root":{height:"16px",margin:"0 2px 0 0"},"& .MuiChip-label":{fontSize:"0.7rem",padding:"0 6px"},"& .MuiChip-deleteIcon":{fontSize:"14px",margin:"0 2px 0 -4px"},"& .MuiInputLabel-root":{fontSize:"0.75rem",transform:"translate(10px, 6px) scale(1)"},"& .MuiInputLabel-shrink":{fontSize:"0.85rem",transform:"translate(14px, -9px) scale(0.75)"},"& .MuiOutlinedInput-notchedOutline legend":{fontSize:"0.65rem"},"& .MuiFormHelperText-root":{fontSize:"0.65rem",marginTop:"2px"},"& .MuiSvgIcon-root":{fontSize:"1.25rem"}},children:[n.jsxs(ge,{sx:{fontWeight:600,color:t.required&&!h?"error.main":"text.primary"},children:[t.label??t.dimensionName,t.required&&n.jsx(ge,{component:"span",sx:{color:h?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),t.filterType!=="Boolean"&&!t.defaultMatchType&&q.length>1&&n.jsxs(u.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(u.InputLabel,{children:"Match Type"}),n.jsx(u.Select,{value:l,label:"Match Type",onChange:J,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:q.map(W=>n.jsx(ke,{value:W,children:W},W))})]}),t.filterType==="Star"&&l==="Equals"&&n.jsx(u.Autocomplete,{multiple:!0,size:"small",options:i,getOptionLabel:W=>typeof W=="string"?W:typeof W=="object"&&W!==null&&"value"in W?String(W.value):String(W),value:Array.isArray(d)?d.map(W=>i.find(Q=>Q.value===W)||W):d?[i.find(W=>W.value===d)||d]:[],onChange:(W,Q)=>{const R=Q.map(Z=>typeof Z=="string"?Z:Z&&typeof Z=="object"&&"value"in Z?Z.value:Z);U(R)},noOptionsText:"No matches found",renderInput:W=>n.jsx(u.TextField,{...W,size:"small",label:"Values",placeholder:"Select values..."}),freeSolo:!t.values||t.values.length===0,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),t.filterType==="Star"&&l==="Contains"&&n.jsx(u.TextField,{size:"small",label:"Search Text",value:d,onChange:W=>m(W.target.value),onBlur:()=>U(d),onKeyDown:W=>{W.key==="Enter"&&U(d)},placeholder:"Enter text to search...",fullWidth:!0}),t.filterType==="Boolean"&&n.jsxs(u.FormControl,{size:"small",fullWidth:!0,children:[n.jsx(u.InputLabel,{children:"Value"}),n.jsxs(u.Select,{value:d===!0?"true":d===!1?"false":"",label:"Value",onChange:W=>{const Q=W.target.value;Q==="true"?U(!0):Q==="false"?U(!1):te()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[n.jsx(ke,{value:"",children:n.jsx("em",{children:"Blank"})}),n.jsx(ke,{value:"true",children:"True"}),n.jsx(ke,{value:"false",children:"False"})]})]}),t.filterType==="Retrieval"&&l==="Semantic Search"&&n.jsx(u.Autocomplete,{multiple:!0,size:"small",options:b,loading:k,getOptionLabel:W=>typeof W=="string"?W:typeof W=="object"&&W!==null&&"value"in W?String(W.value):String(W),value:Array.isArray(d)?d.map(W=>b.find(R=>R.value===W)||{value:W}):d?[{value:d}]:[],onInputChange:(W,Q)=>{M(Q)},onChange:(W,Q)=>{const R=Q.map(Z=>typeof Z=="string"?Z:Z&&typeof Z=="object"&&"value"in Z?Z.value:Z);U(R)},noOptionsText:T.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:W=>n.jsx(u.TextField,{...W,size:"small",label:"Search Values",placeholder:"Type to search...",onFocus:()=>L(!0),onBlur:()=>L(!1),helperText:E&&!k&&j&&b.length===0?"No matches found":void 0,InputProps:{...W.InputProps,endAdornment:n.jsxs(n.Fragment,{children:[k?n.jsx(u.CircularProgress,{color:"inherit",size:20}):null,W.InputProps.endAdornment]})}}),freeSolo:!0,filterOptions:W=>W,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),t.filterType==="MinMax"&&!A&&n.jsx(u.TextField,{size:"small",type:"number",label:"Value",value:d,onChange:W=>U(parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:K,max:X},helperText:Y&&K!==void 0&&X!==void 0?`Valid range: [${K} - ${X}]`:void 0}),t.filterType==="MinMax"&&A&&n.jsxs(ge,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(ge,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(u.TextField,{size:"small",type:"number",label:"From",value:d,onChange:W=>U(parseFloat(W.target.value)||"",x),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:K,max:x||X}}),n.jsx(ge,{children:"to"}),n.jsx(u.TextField,{size:"small",type:"number",label:"To",value:x,onChange:W=>U(d,parseFloat(W.target.value)||""),onFocus:()=>N(!0),onBlur:()=>N(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:d||K,max:X}})]}),Y&&K!==void 0&&X!==void 0&&n.jsxs(u.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",K," - ",X,"]"]})]}),B&&!A&&n.jsx(u.LocalizationProvider,{dateAdapter:u.AdapterDayjs,children:n.jsx(u.DatePicker,{label:"Date",value:d instanceof Date?u.dayjs.utc(d):null,onChange:W=>{W===null?U(null):W.isValid()&&U(W.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?void 0:P,maxDate:d instanceof Date?void 0:G,referenceDate:l==="After"&&P?P:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>N(!0),onBlur:()=>N(!1),helperText:Y&&P&&G?`Valid range: [${P.format("YYYY-MM-DD")} - ${G.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),B&&A&&n.jsx(u.LocalizationProvider,{dateAdapter:u.AdapterDayjs,children:n.jsxs(ge,{sx:{display:"flex",flexDirection:"column",gap:1},children:[n.jsxs(ge,{sx:{display:"flex",gap:1,alignItems:"center"},children:[n.jsx(ge,{sx:{flex:1,minWidth:0},children:n.jsx(u.DatePicker,{label:"From",value:d instanceof Date?u.dayjs.utc(d):null,onChange:W=>{W===null?U(null,x):W.isValid()&&U(W.utc().toDate(),x)},timezone:"UTC",minDate:d instanceof Date?void 0:P,maxDate:x instanceof Date?u.dayjs.utc(x):d instanceof Date?void 0:G,referenceDate:P,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),n.jsx(ge,{children:"to"}),n.jsx(ge,{sx:{flex:1,minWidth:0},children:n.jsx(u.DatePicker,{label:"To",value:x instanceof Date?u.dayjs.utc(x):null,onChange:W=>{W===null?U(d,null):W.isValid()&&U(d,W.utc().toDate())},timezone:"UTC",minDate:d instanceof Date?u.dayjs.utc(d):x instanceof Date?void 0:P,maxDate:x instanceof Date?void 0:G,referenceDate:d instanceof Date?u.dayjs.utc(d):P,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>N(!0),onBlur:()=>N(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),Y&&P&&G&&n.jsxs(u.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",P.format("YYYY-MM-DD")," -"," ",G.format("YYYY-MM-DD"),"]"]})]})})]})}function Ol(t){const i=new Set,h=t.schema?.fields;if(!h)return i;for(const a of h)"kind"in a&&a.kind==="join"&&a.name&&i.add(a.name);return i}function El(t){if(!t)return null;for(const i of t)if(i.startsWith("##(filters)")){const h=i.slice(11).trim();try{const a=JSON.parse(h);if(Array.isArray(a)){const p=[];for(const c of a)if(typeof c=="string"){const l=c.indexOf(".");l>0&&l<c.length-1&&p.push({source:c.substring(0,l),dimension:c.substring(l+1)})}if(p.length>0)return{filters:p}}}catch(a){console.error(`Failed to parse "${i}" annotation:`,a)}}return null}function ba(t){if(t.startsWith("#(filter)")){const i=t.slice(9).trim();try{const h=JSON.parse(i);if(h.type)return h}catch(h){console.error(`Failed to parse "${t}" annotation:`,h)}}return null}function Il(t){const i=t.match(/^#\s*label\s*=\s*"([^"]+)"/);return i?i[1]:null}function Fl(t){const i=new Map;let h="";for(const a of t)if(a.type==="code"){if(!h&&a.text){const c=a.text.split(`
|
|
2
2
|
`).map(l=>l.trim()).find(l=>l.startsWith("import "))?.match(/['"]([^'"\n]+)['"]/);c&&(h=c[1])}if(a.newSources&&a.newSources.length>0)for(const p of a.newSources)try{const c=JSON.parse(p);c.name&&i.set(c.name,c)}catch(c){console.error("Failed to parse SourceInfo:",c)}}return{sourceInfoMap:i,modelPath:h}}function Nl(t,i,h){const a=[];for(const{source:p,dimension:c}of i){const l=t.get(p);if(!l){console.warn(`Source "${p}" not found in notebook sources`),a.push({source:p,model:h,dimensionName:c,filterType:"Star"});continue}const f=l.schema?.fields;if(!f){a.push({source:p,model:h,dimensionName:c,filterType:"Star"});continue}const d=f.find(S=>S.name===c);if(!d){console.warn(`Dimension "${c}" not found in source "${p}"`),a.push({source:p,model:h,dimensionName:c,filterType:"Star"});continue}let m="Star",x;if("annotations"in d&&d.annotations){for(const S of d.annotations)if(S.value){const b=ba(S.value);b&&(m=b.type);const g=Il(S.value);g&&(x=g)}}a.push({source:p,model:h,dimensionName:c,filterType:m,label:x})}return a}function Al(t,i,h){return t.length===0?"":t.map(p=>{const{dimensionName:c,source:l,matchType:f,value:d,value2:m}=p,S=l&&l!==h?`\`${l}\`.\`${c}\``:`\`${c}\``,b=d instanceof Date,g=(k,w=!1)=>k==null?"null":w&&k instanceof Date?`@${k.getFullYear()}-${String(k.getMonth()+1).padStart(2,"0")}-${String(k.getDate()).padStart(2,"0")}`:typeof k=="string"?`'${u.escapeMalloyString(k)}'`:typeof k=="boolean"?k?"true":"false":String(k);switch(f){case"Equals":case"Semantic Search":return Array.isArray(d)&&d.length>0?`(${d.map(w=>`${S} = ${g(w,b)}`).join(" or ")})`:`${S} = ${g(d,b)}`;case"Contains":return typeof d=="string"?`${S} ~ f'%${u.escapeMalloyString(d)}%'`:`${S} = ${g(d)}`;case"After":case"Greater Than":return`${S} > ${g(d,b)}`;case"Before":case"Less Than":return`${S} < ${g(d,b)}`;case"Between":return m!==void 0?`${S} >= ${g(d,b)} and ${S} <= ${g(m,b)}`:`${S} >= ${g(d,b)}`;default:return""}}).filter(p=>p.length>0).join(" and ")}function $l(t){const i=t.match(/run\s*:\s*(\w+)\s*->/);if(i)return i[1];const h=t.match(/^\s*(\w+)\s*->/m);return h?h[1]:null}function Rl(t,i){return`${t.trimEnd()} + {where: ${i}}`}function Ll(){const[t]=vn.useSearchParams(),i=vn.useNavigate(),h=vn.useLocation(),a=$.useMemo(()=>Object.fromEntries(t.entries()),[t]),p=$.useRef(new Set),c=$.useCallback((l,f)=>{const d=new Set([...f,...p.current]);p.current=new Set([...p.current,...Object.keys(l),...f]);const m=new URLSearchParams(h.search);for(const x of d)Object.prototype.hasOwnProperty.call(l,x)||m.delete(x);for(const[x,S]of Object.entries(l))m.set(x,S);i({search:m.toString(),hash:h.hash},{replace:!0})},[i,h]);return{params:a,onGivensChange:c}}const _l=u.createSvgIcon(n.jsx("path",{d:"m9.17 6 2 2H20v10H4V6zM10 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2h-8z"})),va=t=>{if(!t)return"Explore semantic models, run queries, and build dashboards";const i=t.replace(/^#+\s+/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/`([^`]+)`/g,"$1").trim(),a=i.split(/\n\s*\n/)[1]||i;if(a.length<=120)return a;const p=a.substring(0,120).split(" ");return p.pop(),p.join(" ")+"..."},Sa=(t,i)=>{const h=(t.readme||void 0)?.split(`
|
|
3
3
|
`)??[];return h.length===0&&(h.push(`# ${t.name}`),h.push("")),(t.readme?.length??0)>0&&i?h.splice(2,1,i):i&&h.push(i),h.join(`
|
|
4
4
|
`)};function zs(){const[t,i]=$.useState(!1),{apiClients:h}=V.useServer(),a=()=>{i(!0)},p=()=>{i(!1)},c=Dt({mutationFn(f){return h.environments.createEnvironment({name:f.name,readme:Sa({name:f.name,readme:""},f.description)})},success:"Environment created",invalidates:[["environments"]],closeDialog:p,resource:"environment",action:"create"}),l=async f=>{f.preventDefault();const d=new FormData(f.currentTarget),m=d.get("name")?.toString(),x=d.get("description")?.toString();if(!m)throw new Error("Name is required");c.mutate({name:m,description:x})};return n.jsxs($.Fragment,{children:[n.jsx(u.AddButton,{label:"Environment",onClick:a}),n.jsx(u.AppDialog,{open:t,onClose:p,title:"New environment",description:"An environment holds packages and the connections they query through.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:c.isPending,onClick:p,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"environment-form",variant:"contained",loading:c.isPending,children:"Create environment"})]}),children:n.jsx("form",{onSubmit:l,id:"environment-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),n.jsx(u.TextField,{id:"description",name:"description",label:"Description",placeholder:"Explore semantic models, run queries, and build dashboards",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}})]})})}),c.notice]})}function Pl({environment:t,onCloseDialog:i}){const[h,a]=$.useState(!1),{apiClients:p}=V.useServer(),c=()=>{a(!0)},l=()=>{a(!1),i()},f=Dt({mutationFn:()=>p.environments.deleteEnvironment(t.name),success:"Environment deleted",invalidates:[["environments"]],closeDialog:l,resource:"environment",action:"delete"});return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:c,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Delete,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Delete"})]}),n.jsx(u.AppDialog,{open:h,onClose:l,title:"Delete environment",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{onClick:l,children:"Cancel"}),n.jsx(u.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>f.mutate(),loading:f.isPending,children:"Delete environment"})]}),children:n.jsxs(u.Typography,{variant:"body2",children:["Delete ",n.jsx("strong",{children:t.name}),"? Its packages stop being served and this cannot be undone."]})}),f.notice]})}function ql({environment:t,onCloseDialog:i}){const[h,a]=$.useState(!1),{apiClients:p}=V.useServer(),c=()=>{a(!0)},l=()=>{a(!1),i()},f=Dt({mutationFn(m){return p.environments.updateEnvironment(t.name,{name:t.name,readme:Sa({name:t.name,readme:t.readme},m.description)})},success:"Environment updated",invalidates:[["environments"]],closeDialog:l,resource:"environment",action:"update"}),d=m=>{m.preventDefault();const S=new FormData(m.currentTarget).get("description")?.toString();f.mutate({description:S})};return n.jsxs($.Fragment,{children:[n.jsxs(v.MenuItem,{onClick:c,children:[n.jsx(v.ListItemIcon,{children:n.jsx(He.Edit,{fontSize:"small"})}),n.jsx(v.ListItemText,{children:"Edit"})]}),n.jsx(u.AppDialog,{open:h,onClose:l,title:"Edit environment",description:"What this environment is, for the people who open it.",actions:n.jsxs(n.Fragment,{children:[n.jsx(u.Button,{disabled:f.isPending,onClick:l,children:"Cancel"}),n.jsx(u.Button,{type:"submit",form:"environment-form",variant:"contained",loading:f.isPending,children:"Save changes"})]}),children:n.jsx("form",{onSubmit:d,id:"environment-form",children:n.jsxs(Dn,{sx:{gap:2},children:[n.jsx(u.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:t.name,InputLabelProps:{shrink:!0}}),n.jsx(u.TextField,{id:"description",name:"description",label:"Description",type:"text",fullWidth:!0,size:"small",defaultValue:va(t.readme),InputLabelProps:{shrink:!0}})]})})}),f.notice]})}const Wl=[{title:"Model",body:"An agent writes what the data means in Malloy — sources, joins, measures — from a warehouse or a file, and validates each edit without a restart.",href:Xe.publishing},{title:"Analyze",body:"Claude, Cursor, Codex or an agent you build asks over MCP; applications and BI tools use REST. Every question runs against the model, never the raw tables.",href:Xe.mcpAgents},{title:"Surface",body:"Dashboards declared in Malloy, notebooks, and no-build HTML data apps, all shipped inside the package, plus this Console for browsing them.",href:Xe.surfaces},{title:"Govern",body:"Runtime parameters, row-level filters and per-source gates are declared in the model, so every surface reads the same rules rather than writing its own.",href:Xe.givens},{title:"Optimize",body:"One annotation materializes an expensive source into a table, and another rolls a measure up to a coarser grain, rebuilt on demand or on a schedule.",href:Xe.materialization},{title:"Run anywhere",body:"DuckDB is built in for CSV, Parquet, JSON and Excel; BigQuery, Snowflake, Postgres, Databricks, MotherDuck and more connect by configuration.",href:Xe.connections}];function zl({href:t,children:i}){return n.jsx(v.Box,{component:"a",href:t,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary",textDecoration:"underline"},children:i})}function Hl({onClickEnvironment:t}){const{apiClients:i,mutable:h}=V.useServer(),{data:a,isSuccess:p,isError:c,error:l}=u.useQueryWithApiError({queryKey:["environments"],queryFn:()=>i.environments.listEnvironments()});if(c)return n.jsx(u.ApiErrorDisplay,{error:l,context:"Environments List"});if(!p)return n.jsx(u.Loading,{text:"Loading environments..."});const f=a.data??[];return n.jsxs(v.Container,{maxWidth:"md",sx:{py:6},children:[n.jsxs(v.Box,{sx:{mb:5},children:[n.jsx(v.Typography,{variant:"h3",component:"h1",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Publisher"}),n.jsx(v.Typography,{variant:"body1",color:"text.secondary",sx:{mb:3},children:"The analytics engine for Malloy."}),n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{maxWidth:720,lineHeight:1.6},children:"One data model, served over MCP and REST to AI agents, applications and BI tools. Write down what your data means — the sources, the joins, the measures, who may see what — and every surface asks the same model, so the same question returns the same numbers tomorrow."})]}),n.jsx(v.Grid,{container:!0,spacing:4,sx:{mb:5},children:Wl.map(d=>n.jsx(v.Grid,{size:{xs:12,sm:6},children:n.jsxs(v.Stack,{spacing:1,children:[n.jsx(v.Typography,{variant:"body2",component:"a",href:d.href,target:"_blank",rel:"noopener noreferrer",sx:{fontWeight:500,color:"text.primary",textDecoration:"none","&:hover":{textDecoration:"underline"}},children:d.title}),n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{lineHeight:1.6},children:d.body})]})},d.title))}),n.jsx(v.Divider,{sx:{my:4}}),f.length>0?n.jsx(ze,{title:"Environments",count:f.length,description:"Published environments available on this server",...h?{action:n.jsx(zs,{})}:{},children:n.jsx(v.Stack,{children:f.map(d=>n.jsx(Vl,{environment:d,...t?{onClickEnvironment:t}:{}},d.name))})}):n.jsxs(v.Box,{sx:{mb:4},children:[n.jsx(v.Typography,{variant:"h5",sx:{fontWeight:500,letterSpacing:"-0.025em",mb:1},children:"Get started"}),n.jsx(v.Typography,{variant:"body2",color:"text.secondary",sx:{mb:3,maxWidth:600},children:"Create your first Malloy environment to start exploring semantic models and building data experiences."}),h?n.jsx(zs,{}):n.jsx(v.Button,{variant:"contained",color:"primary",href:Xe.publishing,target:"_blank",rel:"noopener noreferrer",children:"Learn how to create models"})]}),n.jsx(v.Divider,{sx:{my:4}}),n.jsxs(v.Typography,{variant:"body2",color:"text.secondary",sx:{maxWidth:720,lineHeight:1.6,mt:2},children:["Join the"," ",n.jsx(zl,{href:"https://join.slack.com/t/malloy-community/shared_invite/zt-1kgfwgi5g-CrsdaRqs81QY67QW0~t_uw",children:"Malloy Slack community"})," ","to ask questions, share ideas, and contribute."]})]})}function Vl({environment:t,onClickEnvironment:i}){const{mutable:h}=V.useServer(),[a,p]=$.useState(null),c=!!a,l=va(t.readme),f=m=>{m.stopPropagation(),p(m.currentTarget)},d=()=>p(null);return n.jsx(jn,{icon:n.jsx(_l,{sx:{fontSize:18}}),tint:V.SURFACE_TINT.environment,label:t.name??"",ariaLabel:t.name??"",...l?{description:l}:{},...t.name&&i?{onClick:m=>i(`/${t.name}/`,m)}:{},...h?{trailingAction:n.jsxs(n.Fragment,{children:[n.jsx(v.IconButton,{size:"small",onClick:f,"aria-label":`Environment actions for ${t.name}`,children:n.jsx(He.MoreVert,{fontSize:"small"})}),n.jsxs(v.Menu,{anchorEl:a,open:c,onClose:d,onClick:m=>m.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[n.jsx(ql,{environment:t,onCloseDialog:d}),n.jsx(Pl,{environment:t,onCloseDialog:d})]})]})}:{}})}var ct={},Ie={},Ht={},ut={},Qn={},Hs;function Ul(){return Hs||(Hs=1,Object.defineProperty(Qn,"__esModule",{value:!0})),Qn}var Vt={},Ut={},Vs;function ft(){if(Vs)return Ut;Vs=1,Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.CronField=void 0;let t=class wa{#e=!1;#n=!1;#a=!1;#s=[];options={rawValue:""};static get min(){throw new Error("min must be overridden")}static get max(){throw new Error("max must be overridden")}static get chars(){return Object.freeze([])}static get validChars(){return/^[?,*\dH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}static get constraints(){return{min:this.min,max:this.max,chars:this.chars,validChars:this.validChars}}constructor(h,a={rawValue:""}){if(!Array.isArray(h))throw new Error(`${this.constructor.name} Validation error, values is not an array`);if(!(h.length>0))throw new Error(`${this.constructor.name} Validation error, values contains no values`);this.options={...a,rawValue:a.rawValue??""},this.#s=h.sort(wa.sorter),this.#a=this.options.wildcard!==void 0?this.options.wildcard:this.#r(),this.#e=this.options.rawValue.includes("L")||h.includes("L"),this.#n=this.options.rawValue.includes("?")||h.includes("?")}get min(){return this.constructor.min}get max(){return this.constructor.max}get chars(){return this.constructor.chars}get hasLastChar(){return this.#e}get hasQuestionMarkChar(){return this.#n}get isWildcard(){return this.#a}get values(){return this.#s}static sorter(h,a){const p=typeof h=="number",c=typeof a=="number";return p&&c?h-a:!p&&!c?h.localeCompare(a):p?-1:1}static findNearestValueInList(h,a,p){if(p){for(let c=h.length-1;c>=0;c--)if(h[c]<a)return h[c];return null}for(let c=0;c<h.length;c++)if(h[c]>a)return h[c];return null}findNearestValue(h,a){return this.constructor.findNearestValueInList(this.values,h,a)}serialize(){return{wildcard:this.#a,values:this.#s}}validate(){let h;const a=this.chars.length>0?` or chars ${this.chars.join("")}`:"",p=d=>m=>new RegExp(`^\\d{0,2}${m}$`).test(d),c=d=>(h=d,typeof d=="number"?d>=this.min&&d<=this.max:this.chars.some(p(d)));if(!this.#s.every(c))throw new Error(`${this.constructor.name} Validation error, got value ${h} expected range ${this.min}-${this.max}${a}`);const f=this.#s.find((d,m)=>this.#s.indexOf(d)!==m);if(f)throw new Error(`${this.constructor.name} Validation error, duplicate values found: ${f}`)}#r(){return this.options.rawValue.length>0?["*","?"].includes(this.options.rawValue):Array.from({length:this.max-this.min+1},(h,a)=>a+this.min).every(h=>this.#s.includes(h))}};return Ut.CronField=t,Ut}var Us;function Bl(){if(Us)return Vt;Us=1,Object.defineProperty(Vt,"__esModule",{value:!0}),Vt.CronDayOfMonth=void 0;const t=ft(),i=1,h=31,a=Object.freeze(["L"]);let p=class extends t.CronField{static get min(){return i}static get max(){return h}static get chars(){return a}static get validChars(){return/^[?,*\dLH/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(l,f){super(l,f),this.validate()}get values(){return super.values}};return Vt.CronDayOfMonth=p,Vt}var Bt={},Bs;function Gl(){if(Bs)return Bt;Bs=1,Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.CronDayOfWeek=void 0;const t=ft(),i=0,h=7,a=Object.freeze(["L"]);let p=class extends t.CronField{static get min(){return i}static get max(){return h}static get chars(){return a}static get validChars(){return/^[?,*\dLH#/-]+$|^.*H\(\d+-\d+\)\/\d+.*$|^.*H\(\d+-\d+\).*$|^.*H\/\d+.*$/}constructor(l,f){super(l,f),this.validate()}get values(){return super.values}get nthDay(){return this.options.nthDayOfWeek??0}};return Bt.CronDayOfWeek=p,Bt}var Gt={},Gs;function Yl(){if(Gs)return Gt;Gs=1,Object.defineProperty(Gt,"__esModule",{value:!0}),Gt.CronHour=void 0;const t=ft(),i=0,h=23,a=Object.freeze([]);let p=class extends t.CronField{static get min(){return i}static get max(){return h}static get chars(){return a}constructor(l,f){super(l,f),this.validate()}get values(){return super.values}};return Gt.CronHour=p,Gt}var Yt={},Ys;function Zl(){if(Ys)return Yt;Ys=1,Object.defineProperty(Yt,"__esModule",{value:!0}),Yt.CronMinute=void 0;const t=ft(),i=0,h=59,a=Object.freeze([]);let p=class extends t.CronField{static get min(){return i}static get max(){return h}static get chars(){return a}constructor(l,f){super(l,f),this.validate()}get values(){return super.values}};return Yt.CronMinute=p,Yt}var Zt={},Jn={},Ee={},Zs;function Xl(){if(Zs)return Ee;Zs=1,Object.defineProperty(Ee,"__esModule",{value:!0});class t extends Error{}class i extends t{constructor(e){super(`Invalid DateTime: ${e.toMessage()}`)}}class h extends t{constructor(e){super(`Invalid Interval: ${e.toMessage()}`)}}class a extends t{constructor(e){super(`Invalid Duration: ${e.toMessage()}`)}}class p extends t{}class c extends t{constructor(e){super(`Invalid unit ${e}`)}}class l extends t{}class f extends t{constructor(){super("Zone is an abstract class")}}const d="numeric",m="short",x="long",S={year:d,month:d,day:d},b={year:d,month:m,day:d},g={year:d,month:m,day:d,weekday:m},k={year:d,month:x,day:d},w={year:d,month:x,day:d,weekday:x},T={hour:d,minute:d},M={hour:d,minute:d,second:d},j={hour:d,minute:d,second:d,timeZoneName:m},I={hour:d,minute:d,second:d,timeZoneName:x},E={hour:d,minute:d,hourCycle:"h23"},L={hour:d,minute:d,second:d,hourCycle:"h23"},H={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:m},_={hour:d,minute:d,second:d,hourCycle:"h23",timeZoneName:x},Y={year:d,month:d,day:d,hour:d,minute:d},N={year:d,month:d,day:d,hour:d,minute:d,second:d},q={year:d,month:m,day:d,hour:d,minute:d},B={year:d,month:m,day:d,hour:d,minute:d,second:d},A={year:d,month:m,day:d,weekday:m,hour:d,minute:d},P={year:d,month:x,day:d,hour:d,minute:d,timeZoneName:m},G={year:d,month:x,day:d,hour:d,minute:d,second:d,timeZoneName:m},K={year:d,month:x,day:d,weekday:x,hour:d,minute:d,timeZoneName:x},X={year:d,month:x,day:d,weekday:x,hour:d,minute:d,second:d,timeZoneName:x};class J{get type(){throw new f}get name(){throw new f}get ianaName(){return this.name}get isUniversal(){throw new f}offsetName(e,r){throw new f}formatOffset(e,r){throw new f}offset(e){throw new f}equals(e){throw new f}get isValid(){throw new f}}let U=null;class te extends J{static get instance(){return U===null&&(U=new te),U}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(e,{format:r,locale:o}){return Br(e,r,o)}formatOffset(e,r){return Ft(this.offset(e),r)}offset(e){return-new Date(e).getTimezoneOffset()}equals(e){return e.type==="system"}get isValid(){return!0}}const W=new Map;function Q(s){let e=W.get(s);return e===void 0&&(e=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:s,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),W.set(s,e)),e}const R={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function Z(s,e){const r=s.format(e).replace(/\u200E/g,""),o=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec(r),[,y,C,D,O,F,z,ee]=o;return[D,y,C,O,F,z,ee]}function de(s,e){const r=s.formatToParts(e),o=[];for(let y=0;y<r.length;y++){const{type:C,value:D}=r[y],O=R[C];C==="era"?o[O]=D:re(O)||(o[O]=parseInt(D,10))}return o}const ae=new Map;class ce extends J{static create(e){let r=ae.get(e);return r===void 0&&ae.set(e,r=new ce(e)),r}static resetCache(){ae.clear(),W.clear()}static isValidSpecifier(e){return this.isValidZone(e)}static isValidZone(e){if(!e)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:e}).format(),!0}catch{return!1}}constructor(e){super(),this.zoneName=e,this.valid=ce.isValidZone(e)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(e,{format:r,locale:o}){return Br(e,r,o,this.name)}formatOffset(e,r){return Ft(this.offset(e),r)}offset(e){if(!this.valid)return NaN;const r=new Date(e);if(isNaN(r))return NaN;const o=Q(this.name);let[y,C,D,O,F,z,ee]=o.formatToParts?de(o,r):Z(o,r);O==="BC"&&(y=-Math.abs(y)+1);const pe=cn({year:y,month:C,day:D,hour:F===24?0:F,minute:z,second:ee,millisecond:0});let ne=+r;const Te=ne%1e3;return ne-=Te>=0?Te:1e3+Te,(pe-ne)/(60*1e3)}equals(e){return e.type==="iana"&&e.name===this.name}get isValid(){return this.valid}}let xe={};function we(s,e={}){const r=JSON.stringify([s,e]);let o=xe[r];return o||(o=new Intl.ListFormat(s,e),xe[r]=o),o}const Me=new Map;function Ne(s,e={}){const r=JSON.stringify([s,e]);let o=Me.get(r);return o===void 0&&(o=new Intl.DateTimeFormat(s,e),Me.set(r,o)),o}const Oe=new Map;function me(s,e={}){const r=JSON.stringify([s,e]);let o=Oe.get(r);return o===void 0&&(o=new Intl.NumberFormat(s,e),Oe.set(r,o)),o}const be=new Map;function he(s,e={}){const{base:r,...o}=e,y=JSON.stringify([s,o]);let C=be.get(y);return C===void 0&&(C=new Intl.RelativeTimeFormat(s,e),be.set(y,C)),C}let ye=null;function Ot(){return ye||(ye=new Intl.DateTimeFormat().resolvedOptions().locale,ye)}const Je=new Map;function rt(s){let e=Je.get(s);return e===void 0&&(e=new Intl.DateTimeFormat(s).resolvedOptions(),Je.set(s,e)),e}const st=new Map;function Ye(s){let e=st.get(s);if(!e){const r=new Intl.Locale(s);e="getWeekInfo"in r?r.getWeekInfo():r.weekInfo,"minimalDays"in e||(e={...wr,...e}),st.set(s,e)}return e}function On(s){const e=s.indexOf("-x-");e!==-1&&(s=s.substring(0,e));const r=s.indexOf("-u-");if(r===-1)return[s];{let o,y;try{o=Ne(s).resolvedOptions(),y=s}catch{const F=s.substring(0,r);o=Ne(F).resolvedOptions(),y=F}const{numberingSystem:C,calendar:D}=o;return[y,C,D]}}function at(s,e,r){return(r||e)&&(s.includes("-u-")||(s+="-u"),r&&(s+=`-ca-${r}`),e&&(s+=`-nu-${e}`)),s}function Wa(s){const e=[];for(let r=1;r<=12;r++){const o=se.utc(2009,r,1);e.push(s(o))}return e}function za(s){const e=[];for(let r=1;r<=7;r++){const o=se.utc(2016,11,13+r);e.push(s(o))}return e}function sn(s,e,r,o){const y=s.listingMode();return y==="error"?null:y==="en"?r(e):o(e)}function Ha(s){return s.numberingSystem&&s.numberingSystem!=="latn"?!1:s.numberingSystem==="latn"||!s.locale||s.locale.startsWith("en")||rt(s.locale).numberingSystem==="latn"}class Va{constructor(e,r,o){this.padTo=o.padTo||0,this.floor=o.floor||!1;const{padTo:y,floor:C,...D}=o;if(!r||Object.keys(D).length>0){const O={useGrouping:!1,...o};o.padTo>0&&(O.minimumIntegerDigits=o.padTo),this.inf=me(e,O)}}format(e){if(this.inf){const r=this.floor?Math.floor(e):e;return this.inf.format(r)}else{const r=this.floor?Math.floor(e):_n(e,3);return Ce(r,this.padTo)}}}class Ua{constructor(e,r,o){this.opts=o,this.originalZone=void 0;let y;if(this.opts.timeZone)this.dt=e;else if(e.zone.type==="fixed"){const D=-1*(e.offset/60),O=D>=0?`Etc/GMT+${D}`:`Etc/GMT${D}`;e.offset!==0&&ce.create(O).valid?(y=O,this.dt=e):(y="UTC",this.dt=e.offset===0?e:e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone)}else e.zone.type==="system"?this.dt=e:e.zone.type==="iana"?(this.dt=e,y=e.zone.name):(y="UTC",this.dt=e.setZone("UTC").plus({minutes:e.offset}),this.originalZone=e.zone);const C={...this.opts};C.timeZone=C.timeZone||y,this.dtf=Ne(r,C)}format(){return this.originalZone?this.formatToParts().map(({value:e})=>e).join(""):this.dtf.format(this.dt.toJSDate())}formatToParts(){const e=this.dtf.formatToParts(this.dt.toJSDate());return this.originalZone?e.map(r=>{if(r.type==="timeZoneName"){const o=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{...r,value:o}}else return r}):e}resolvedOptions(){return this.dtf.resolvedOptions()}}class Ba{constructor(e,r,o){this.opts={style:"long",...o},!r&&zr()&&(this.rtf=he(e,o))}format(e,r){return this.rtf?this.rtf.format(e,r):fi(r,e,this.opts.numeric,this.opts.style!=="long")}formatToParts(e,r){return this.rtf?this.rtf.formatToParts(e,r):[]}}const wr={firstDay:1,minimalDays:4,weekend:[6,7]};class ue{static fromOpts(e){return ue.create(e.locale,e.numberingSystem,e.outputCalendar,e.weekSettings,e.defaultToEN)}static create(e,r,o,y,C=!1){const D=e||ve.defaultLocale,O=D||(C?"en-US":Ot()),F=r||ve.defaultNumberingSystem,z=o||ve.defaultOutputCalendar,ee=Rn(y)||ve.defaultWeekSettings;return new ue(O,F,z,ee,D)}static resetCache(){ye=null,Me.clear(),Oe.clear(),be.clear(),Je.clear(),st.clear()}static fromObject({locale:e,numberingSystem:r,outputCalendar:o,weekSettings:y}={}){return ue.create(e,r,o,y)}constructor(e,r,o,y,C){const[D,O,F]=On(e);this.locale=D,this.numberingSystem=r||O||null,this.outputCalendar=o||F||null,this.weekSettings=y,this.intl=at(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=C,this.fastNumbersCached=null}get fastNumbers(){return this.fastNumbersCached==null&&(this.fastNumbersCached=Ha(this)),this.fastNumbersCached}listingMode(){const e=this.isEnglish(),r=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return e&&r?"en":"intl"}clone(e){return!e||Object.getOwnPropertyNames(e).length===0?this:ue.create(e.locale||this.specifiedLocale,e.numberingSystem||this.numberingSystem,e.outputCalendar||this.outputCalendar,Rn(e.weekSettings)||this.weekSettings,e.defaultToEN||!1)}redefaultToEN(e={}){return this.clone({...e,defaultToEN:!0})}redefaultToSystem(e={}){return this.clone({...e,defaultToEN:!1})}months(e,r=!1){return sn(this,e,Zr,()=>{const o=this.intl==="ja"||this.intl.startsWith("ja-");r&=!o;const y=r?{month:e,day:"numeric"}:{month:e},C=r?"format":"standalone";if(!this.monthsCache[C][e]){const D=o?O=>this.dtFormatter(O,y).format():O=>this.extract(O,y,"month");this.monthsCache[C][e]=Wa(D)}return this.monthsCache[C][e]})}weekdays(e,r=!1){return sn(this,e,Qr,()=>{const o=r?{weekday:e,year:"numeric",month:"long",day:"numeric"}:{weekday:e},y=r?"format":"standalone";return this.weekdaysCache[y][e]||(this.weekdaysCache[y][e]=za(C=>this.extract(C,o,"weekday"))),this.weekdaysCache[y][e]})}meridiems(){return sn(this,void 0,()=>Jr,()=>{if(!this.meridiemCache){const e={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[se.utc(2016,11,13,9),se.utc(2016,11,13,19)].map(r=>this.extract(r,e,"dayperiod"))}return this.meridiemCache})}eras(e){return sn(this,e,es,()=>{const r={era:e};return this.eraCache[e]||(this.eraCache[e]=[se.utc(-40,1,1),se.utc(2017,1,1)].map(o=>this.extract(o,r,"era"))),this.eraCache[e]})}extract(e,r,o){const y=this.dtFormatter(e,r),C=y.formatToParts(),D=C.find(O=>O.type.toLowerCase()===o);return D?D.value:null}numberFormatter(e={}){return new Va(this.intl,e.forceSimple||this.fastNumbers,e)}dtFormatter(e,r={}){return new Ua(e,this.intl,r)}relFormatter(e={}){return new Ba(this.intl,this.isEnglish(),e)}listFormatter(e={}){return we(this.intl,e)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||rt(this.intl).locale.startsWith("en-us")}getWeekSettings(){return this.weekSettings?this.weekSettings:Hr()?Ye(this.locale):wr}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(e){return this.locale===e.locale&&this.numberingSystem===e.numberingSystem&&this.outputCalendar===e.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}let En=null;class je extends J{static get utcInstance(){return En===null&&(En=new je(0)),En}static instance(e){return e===0?je.utcInstance:new je(e)}static parseSpecifier(e){if(e){const r=e.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(r)return new je(un(r[1],r[2]))}return null}constructor(e){super(),this.fixed=e}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${Ft(this.fixed,"narrow")}`}get ianaName(){return this.fixed===0?"Etc/UTC":`Etc/GMT${Ft(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(e,r){return Ft(this.fixed,r)}get isUniversal(){return!0}offset(){return this.fixed}equals(e){return e.type==="fixed"&&e.fixed===this.fixed}get isValid(){return!0}}class kr extends J{constructor(e){super(),this.zoneName=e}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function et(s,e){if(re(s)||s===null)return e;if(s instanceof J)return s;if(Qa(s)){const r=s.toLowerCase();return r==="default"?e:r==="local"||r==="system"?te.instance:r==="utc"||r==="gmt"?je.utcInstance:je.parseSpecifier(r)||ce.create(s)}else return tt(s)?je.instance(s):typeof s=="object"&&"offset"in s&&typeof s.offset=="function"?s:new kr(s)}const In={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},Cr={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},Ga=In.hanidec.replace(/[\[|\]]/g,"").split("");function Ya(s){let e=parseInt(s,10);if(isNaN(e)){e="";for(let r=0;r<s.length;r++){const o=s.charCodeAt(r);if(s[r].search(In.hanidec)!==-1)e+=Ga.indexOf(s[r]);else for(const y in Cr){const[C,D]=Cr[y];o>=C&&o<=D&&(e+=o-C)}}return parseInt(e,10)}else return e}const Fn=new Map;function Za(){Fn.clear()}function Le({numberingSystem:s},e=""){const r=s||"latn";let o=Fn.get(r);o===void 0&&(o=new Map,Fn.set(r,o));let y=o.get(e);return y===void 0&&(y=new RegExp(`${In[r]}${e}`),o.set(e,y)),y}let Tr=()=>Date.now(),Mr="system",jr=null,Dr=null,Or=null,Er=60,Ir,Fr=null;class ve{static get now(){return Tr}static set now(e){Tr=e}static set defaultZone(e){Mr=e}static get defaultZone(){return et(Mr,te.instance)}static get defaultLocale(){return jr}static set defaultLocale(e){jr=e}static get defaultNumberingSystem(){return Dr}static set defaultNumberingSystem(e){Dr=e}static get defaultOutputCalendar(){return Or}static set defaultOutputCalendar(e){Or=e}static get defaultWeekSettings(){return Fr}static set defaultWeekSettings(e){Fr=Rn(e)}static get twoDigitCutoffYear(){return Er}static set twoDigitCutoffYear(e){Er=e%100}static get throwOnInvalid(){return Ir}static set throwOnInvalid(e){Ir=e}static resetCaches(){ue.resetCache(),ce.resetCache(),se.resetCache(),Za()}}class _e{constructor(e,r){this.reason=e,this.explanation=r}toMessage(){return this.explanation?`${this.reason}: ${this.explanation}`:this.reason}}const Nr=[0,31,59,90,120,151,181,212,243,273,304,334],Ar=[0,31,60,91,121,152,182,213,244,274,305,335];function Ae(s,e){return new _e("unit out of range",`you specified ${e} (of type ${typeof e}) as a ${s}, which is invalid`)}function Nn(s,e,r){const o=new Date(Date.UTC(s,e-1,r));s<100&&s>=0&&o.setUTCFullYear(o.getUTCFullYear()-1900);const y=o.getUTCDay();return y===0?7:y}function $r(s,e,r){return r+(Et(s)?Ar:Nr)[e-1]}function Rr(s,e){const r=Et(s)?Ar:Nr,o=r.findIndex(C=>C<e),y=e-r[o];return{month:o+1,day:y}}function An(s,e){return(s-e+7)%7+1}function an(s,e=4,r=1){const{year:o,month:y,day:C}=s,D=$r(o,y,C),O=An(Nn(o,y,C),r);let F=Math.floor((D-O+14-e)/7),z;return F<1?(z=o-1,F=It(z,e,r)):F>It(o,e,r)?(z=o+1,F=1):z=o,{weekYear:z,weekNumber:F,weekday:O,...hn(s)}}function Lr(s,e=4,r=1){const{weekYear:o,weekNumber:y,weekday:C}=s,D=An(Nn(o,1,e),r),O=pt(o);let F=y*7+C-D-7+e,z;F<1?(z=o-1,F+=pt(z)):F>O?(z=o+1,F-=pt(o)):z=o;const{month:ee,day:ie}=Rr(z,F);return{year:z,month:ee,day:ie,...hn(s)}}function $n(s){const{year:e,month:r,day:o}=s,y=$r(e,r,o);return{year:e,ordinal:y,...hn(s)}}function _r(s){const{year:e,ordinal:r}=s,{month:o,day:y}=Rr(e,r);return{year:e,month:o,day:y,...hn(s)}}function Pr(s,e){if(!re(s.localWeekday)||!re(s.localWeekNumber)||!re(s.localWeekYear)){if(!re(s.weekday)||!re(s.weekNumber)||!re(s.weekYear))throw new p("Cannot mix locale-based week fields with ISO-based week fields");return re(s.localWeekday)||(s.weekday=s.localWeekday),re(s.localWeekNumber)||(s.weekNumber=s.localWeekNumber),re(s.localWeekYear)||(s.weekYear=s.localWeekYear),delete s.localWeekday,delete s.localWeekNumber,delete s.localWeekYear,{minDaysInFirstWeek:e.getMinDaysInFirstWeek(),startOfWeek:e.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function Xa(s,e=4,r=1){const o=on(s.weekYear),y=$e(s.weekNumber,1,It(s.weekYear,e,r)),C=$e(s.weekday,1,7);return o?y?C?!1:Ae("weekday",s.weekday):Ae("week",s.weekNumber):Ae("weekYear",s.weekYear)}function Ka(s){const e=on(s.year),r=$e(s.ordinal,1,pt(s.year));return e?r?!1:Ae("ordinal",s.ordinal):Ae("year",s.year)}function qr(s){const e=on(s.year),r=$e(s.month,1,12),o=$e(s.day,1,ln(s.year,s.month));return e?r?o?!1:Ae("day",s.day):Ae("month",s.month):Ae("year",s.year)}function Wr(s){const{hour:e,minute:r,second:o,millisecond:y}=s,C=$e(e,0,23)||e===24&&r===0&&o===0&&y===0,D=$e(r,0,59),O=$e(o,0,59),F=$e(y,0,999);return C?D?O?F?!1:Ae("millisecond",y):Ae("second",o):Ae("minute",r):Ae("hour",e)}function re(s){return typeof s>"u"}function tt(s){return typeof s=="number"}function on(s){return typeof s=="number"&&s%1===0}function Qa(s){return typeof s=="string"}function Ja(s){return Object.prototype.toString.call(s)==="[object Date]"}function zr(){try{return typeof Intl<"u"&&!!Intl.RelativeTimeFormat}catch{return!1}}function Hr(){try{return typeof Intl<"u"&&!!Intl.Locale&&("weekInfo"in Intl.Locale.prototype||"getWeekInfo"in Intl.Locale.prototype)}catch{return!1}}function ei(s){return Array.isArray(s)?s:[s]}function Vr(s,e,r){if(s.length!==0)return s.reduce((o,y)=>{const C=[e(y),y];return o&&r(o[0],C[0])===o[0]?o:C},null)[1]}function ti(s,e){return e.reduce((r,o)=>(r[o]=s[o],r),{})}function mt(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Rn(s){if(s==null)return null;if(typeof s!="object")throw new l("Week settings must be an object");if(!$e(s.firstDay,1,7)||!$e(s.minimalDays,1,7)||!Array.isArray(s.weekend)||s.weekend.some(e=>!$e(e,1,7)))throw new l("Invalid week settings");return{firstDay:s.firstDay,minimalDays:s.minimalDays,weekend:Array.from(s.weekend)}}function $e(s,e,r){return on(s)&&s>=e&&s<=r}function ni(s,e){return s-e*Math.floor(s/e)}function Ce(s,e=2){const r=s<0;let o;return r?o="-"+(""+-s).padStart(e,"0"):o=(""+s).padStart(e,"0"),o}function nt(s){if(!(re(s)||s===null||s===""))return parseInt(s,10)}function it(s){if(!(re(s)||s===null||s===""))return parseFloat(s)}function Ln(s){if(!(re(s)||s===null||s==="")){const e=parseFloat("0."+s)*1e3;return Math.floor(e)}}function _n(s,e,r="round"){const o=10**e;switch(r){case"expand":return s>0?Math.ceil(s*o)/o:Math.floor(s*o)/o;case"trunc":return Math.trunc(s*o)/o;case"round":return Math.round(s*o)/o;case"floor":return Math.floor(s*o)/o;case"ceil":return Math.ceil(s*o)/o;default:throw new RangeError(`Value rounding ${r} is out of range`)}}function Et(s){return s%4===0&&(s%100!==0||s%400===0)}function pt(s){return Et(s)?366:365}function ln(s,e){const r=ni(e-1,12)+1,o=s+(e-r)/12;return r===2?Et(o)?29:28:[31,null,31,30,31,30,31,31,30,31,30,31][r-1]}function cn(s){let e=Date.UTC(s.year,s.month-1,s.day,s.hour,s.minute,s.second,s.millisecond);return s.year<100&&s.year>=0&&(e=new Date(e),e.setUTCFullYear(s.year,s.month-1,s.day)),+e}function Ur(s,e,r){return-An(Nn(s,1,e),r)+e-1}function It(s,e=4,r=1){const o=Ur(s,e,r),y=Ur(s+1,e,r);return(pt(s)-o+y)/7}function Pn(s){return s>99?s:s>ve.twoDigitCutoffYear?1900+s:2e3+s}function Br(s,e,r,o=null){const y=new Date(s),C={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};o&&(C.timeZone=o);const D={timeZoneName:e,...C},O=new Intl.DateTimeFormat(r,D).formatToParts(y).find(F=>F.type.toLowerCase()==="timezonename");return O?O.value:null}function un(s,e){let r=parseInt(s,10);Number.isNaN(r)&&(r=0);const o=parseInt(e,10)||0,y=r<0||Object.is(r,-0)?-o:o;return r*60+y}function Gr(s){const e=Number(s);if(typeof s=="boolean"||s===""||!Number.isFinite(e))throw new l(`Invalid unit value ${s}`);return e}function dn(s,e){const r={};for(const o in s)if(mt(s,o)){const y=s[o];if(y==null)continue;r[e(o)]=Gr(y)}return r}function Ft(s,e){const r=Math.trunc(Math.abs(s/60)),o=Math.trunc(Math.abs(s%60)),y=s>=0?"+":"-";switch(e){case"short":return`${y}${Ce(r,2)}:${Ce(o,2)}`;case"narrow":return`${y}${r}${o>0?`:${o}`:""}`;case"techie":return`${y}${Ce(r,2)}${Ce(o,2)}`;default:throw new RangeError(`Value format ${e} is out of range for property format`)}}function hn(s){return ti(s,["hour","minute","second","millisecond"])}const ri=["January","February","March","April","May","June","July","August","September","October","November","December"],Yr=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],si=["J","F","M","A","M","J","J","A","S","O","N","D"];function Zr(s){switch(s){case"narrow":return[...si];case"short":return[...Yr];case"long":return[...ri];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}const Xr=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Kr=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],ai=["M","T","W","T","F","S","S"];function Qr(s){switch(s){case"narrow":return[...ai];case"short":return[...Kr];case"long":return[...Xr];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}const Jr=["AM","PM"],ii=["Before Christ","Anno Domini"],oi=["BC","AD"],li=["B","A"];function es(s){switch(s){case"narrow":return[...li];case"short":return[...oi];case"long":return[...ii];default:return null}}function ci(s){return Jr[s.hour<12?0:1]}function ui(s,e){return Qr(e)[s.weekday-1]}function di(s,e){return Zr(e)[s.month-1]}function hi(s,e){return es(e)[s.year<0?0:1]}function fi(s,e,r="always",o=!1){const y={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},C=["hours","minutes","seconds"].indexOf(s)===-1;if(r==="auto"&&C){const ie=s==="days";switch(e){case 1:return ie?"tomorrow":`next ${y[s][0]}`;case-1:return ie?"yesterday":`last ${y[s][0]}`;case 0:return ie?"today":`this ${y[s][0]}`}}const D=Object.is(e,-0)||e<0,O=Math.abs(e),F=O===1,z=y[s],ee=o?F?z[1]:z[2]||z[1]:F?y[s][0]:s;return D?`${O} ${ee} ago`:`in ${O} ${ee}`}function ts(s,e){let r="";for(const o of s)o.literal?r+=o.val:r+=e(o.val);return r}const mi={D:S,DD:b,DDD:k,DDDD:w,t:T,tt:M,ttt:j,tttt:I,T:E,TT:L,TTT:H,TTTT:_,f:Y,ff:q,fff:P,ffff:K,F:N,FF:B,FFF:G,FFFF:X};class De{static create(e,r={}){return new De(e,r)}static parseFormat(e){let r=null,o="",y=!1;const C=[];for(let D=0;D<e.length;D++){const O=e.charAt(D);O==="'"?((o.length>0||y)&&C.push({literal:y||/^\s+$/.test(o),val:o===""?"'":o}),r=null,o="",y=!y):y||O===r?o+=O:(o.length>0&&C.push({literal:/^\s+$/.test(o),val:o}),o=O,r=O)}return o.length>0&&C.push({literal:y||/^\s+$/.test(o),val:o}),C}static macroTokenToFormatOpts(e){return mi[e]}constructor(e,r){this.opts=r,this.loc=e,this.systemLoc=null}formatWithSystemDefault(e,r){return this.systemLoc===null&&(this.systemLoc=this.loc.redefaultToSystem()),this.systemLoc.dtFormatter(e,{...this.opts,...r}).format()}dtFormatter(e,r={}){return this.loc.dtFormatter(e,{...this.opts,...r})}formatDateTime(e,r){return this.dtFormatter(e,r).format()}formatDateTimeParts(e,r){return this.dtFormatter(e,r).formatToParts()}formatInterval(e,r){return this.dtFormatter(e.start,r).dtf.formatRange(e.start.toJSDate(),e.end.toJSDate())}resolvedOptions(e,r){return this.dtFormatter(e,r).resolvedOptions()}num(e,r=0,o=void 0){if(this.opts.forceSimple)return Ce(e,r);const y={...this.opts};return r>0&&(y.padTo=r),o&&(y.signDisplay=o),this.loc.numberFormatter(y).format(e)}formatDateTimeFromString(e,r){const o=this.loc.listingMode()==="en",y=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",C=(ne,Te)=>this.loc.extract(e,ne,Te),D=ne=>e.isOffsetFixed&&e.offset===0&&ne.allowZ?"Z":e.isValid?e.zone.formatOffset(e.ts,ne.format):"",O=()=>o?ci(e):C({hour:"numeric",hourCycle:"h12"},"dayperiod"),F=(ne,Te)=>o?di(e,ne):C(Te?{month:ne}:{month:ne,day:"numeric"},"month"),z=(ne,Te)=>o?ui(e,ne):C(Te?{weekday:ne}:{weekday:ne,month:"long",day:"numeric"},"weekday"),ee=ne=>{const Te=De.macroTokenToFormatOpts(ne);return Te?this.formatWithSystemDefault(e,Te):ne},ie=ne=>o?hi(e,ne):C({era:ne},"era"),pe=ne=>{switch(ne){case"S":return this.num(e.millisecond);case"u":case"SSS":return this.num(e.millisecond,3);case"s":return this.num(e.second);case"ss":return this.num(e.second,2);case"uu":return this.num(Math.floor(e.millisecond/10),2);case"uuu":return this.num(Math.floor(e.millisecond/100));case"m":return this.num(e.minute);case"mm":return this.num(e.minute,2);case"h":return this.num(e.hour%12===0?12:e.hour%12);case"hh":return this.num(e.hour%12===0?12:e.hour%12,2);case"H":return this.num(e.hour);case"HH":return this.num(e.hour,2);case"Z":return D({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return D({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return D({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return e.zone.offsetName(e.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return e.zone.offsetName(e.ts,{format:"long",locale:this.loc.locale});case"z":return e.zoneName;case"a":return O();case"d":return y?C({day:"numeric"},"day"):this.num(e.day);case"dd":return y?C({day:"2-digit"},"day"):this.num(e.day,2);case"c":return this.num(e.weekday);case"ccc":return z("short",!0);case"cccc":return z("long",!0);case"ccccc":return z("narrow",!0);case"E":return this.num(e.weekday);case"EEE":return z("short",!1);case"EEEE":return z("long",!1);case"EEEEE":return z("narrow",!1);case"L":return y?C({month:"numeric",day:"numeric"},"month"):this.num(e.month);case"LL":return y?C({month:"2-digit",day:"numeric"},"month"):this.num(e.month,2);case"LLL":return F("short",!0);case"LLLL":return F("long",!0);case"LLLLL":return F("narrow",!0);case"M":return y?C({month:"numeric"},"month"):this.num(e.month);case"MM":return y?C({month:"2-digit"},"month"):this.num(e.month,2);case"MMM":return F("short",!1);case"MMMM":return F("long",!1);case"MMMMM":return F("narrow",!1);case"y":return y?C({year:"numeric"},"year"):this.num(e.year);case"yy":return y?C({year:"2-digit"},"year"):this.num(e.year.toString().slice(-2),2);case"yyyy":return y?C({year:"numeric"},"year"):this.num(e.year,4);case"yyyyyy":return y?C({year:"numeric"},"year"):this.num(e.year,6);case"G":return ie("short");case"GG":return ie("long");case"GGGGG":return ie("narrow");case"kk":return this.num(e.weekYear.toString().slice(-2),2);case"kkkk":return this.num(e.weekYear,4);case"W":return this.num(e.weekNumber);case"WW":return this.num(e.weekNumber,2);case"n":return this.num(e.localWeekNumber);case"nn":return this.num(e.localWeekNumber,2);case"ii":return this.num(e.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(e.localWeekYear,4);case"o":return this.num(e.ordinal);case"ooo":return this.num(e.ordinal,3);case"q":return this.num(e.quarter);case"qq":return this.num(e.quarter,2);case"X":return this.num(Math.floor(e.ts/1e3));case"x":return this.num(e.ts);default:return ee(ne)}};return ts(De.parseFormat(r),pe)}formatDurationFromString(e,r){const o=this.opts.signMode==="negativeLargestOnly"?-1:1,y=ee=>{switch(ee[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},C=(ee,ie)=>pe=>{const ne=y(pe);if(ne){const Te=ie.isNegativeDuration&&ne!==ie.largestUnit?o:1;let qe;return this.opts.signMode==="negativeLargestOnly"&&ne!==ie.largestUnit?qe="never":this.opts.signMode==="all"?qe="always":qe="auto",this.num(ee.get(ne)*Te,pe.length,qe)}else return pe},D=De.parseFormat(r),O=D.reduce((ee,{literal:ie,val:pe})=>ie?ee:ee.concat(pe),[]),F=e.shiftTo(...O.map(y).filter(ee=>ee)),z={isNegativeDuration:F<0,largestUnit:Object.keys(F.values)[0]};return ts(D,C(F,z))}}const ns=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function yt(...s){const e=s.reduce((r,o)=>r+o.source,"");return RegExp(`^${e}$`)}function gt(...s){return e=>s.reduce(([r,o,y],C)=>{const[D,O,F]=C(e,y);return[{...r,...D},O||o,F]},[{},null,1]).slice(0,2)}function xt(s,...e){if(s==null)return[null,null];for(const[r,o]of e){const y=r.exec(s);if(y)return o(y)}return[null,null]}function rs(...s){return(e,r)=>{const o={};let y;for(y=0;y<s.length;y++)o[s[y]]=nt(e[r+y]);return[o,null,r+y]}}const ss=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,pi=`(?:${ss.source}?(?:\\[(${ns.source})\\])?)?`,qn=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,as=RegExp(`${qn.source}${pi}`),Wn=RegExp(`(?:[Tt]${as.source})?`),yi=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,gi=/(\d{4})-?W(\d\d)(?:-?(\d))?/,xi=/(\d{4})-?(\d{3})/,bi=rs("weekYear","weekNumber","weekDay"),vi=rs("year","ordinal"),Si=/(\d{4})-(\d\d)-(\d\d)/,is=RegExp(`${qn.source} ?(?:${ss.source}|(${ns.source}))?`),wi=RegExp(`(?: ${is.source})?`);function bt(s,e,r){const o=s[e];return re(o)?r:nt(o)}function ki(s,e){return[{year:bt(s,e),month:bt(s,e+1,1),day:bt(s,e+2,1)},null,e+3]}function vt(s,e){return[{hours:bt(s,e,0),minutes:bt(s,e+1,0),seconds:bt(s,e+2,0),milliseconds:Ln(s[e+3])},null,e+4]}function Nt(s,e){const r=!s[e]&&!s[e+1],o=un(s[e+1],s[e+2]),y=r?null:je.instance(o);return[{},y,e+3]}function At(s,e){const r=s[e]?ce.create(s[e]):null;return[{},r,e+1]}const Ci=RegExp(`^T?${qn.source}$`),Ti=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function Mi(s){const[e,r,o,y,C,D,O,F,z]=s,ee=e[0]==="-",ie=F&&F[0]==="-",pe=(ne,Te=!1)=>ne!==void 0&&(Te||ne&&ee)?-ne:ne;return[{years:pe(it(r)),months:pe(it(o)),weeks:pe(it(y)),days:pe(it(C)),hours:pe(it(D)),minutes:pe(it(O)),seconds:pe(it(F),F==="-0"),milliseconds:pe(Ln(z),ie)}]}const ji={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function zn(s,e,r,o,y,C,D){const O={year:e.length===2?Pn(nt(e)):nt(e),month:Yr.indexOf(r)+1,day:nt(o),hour:nt(y),minute:nt(C)};return D&&(O.second=nt(D)),s&&(O.weekday=s.length>3?Xr.indexOf(s)+1:Kr.indexOf(s)+1),O}const Di=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function Oi(s){const[,e,r,o,y,C,D,O,F,z,ee,ie]=s,pe=zn(e,y,o,r,C,D,O);let ne;return F?ne=ji[F]:z?ne=0:ne=un(ee,ie),[pe,new je(ne)]}function Ei(s){return s.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}const Ii=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,Fi=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,Ni=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function os(s){const[,e,r,o,y,C,D,O]=s;return[zn(e,y,o,r,C,D,O),je.utcInstance]}function Ai(s){const[,e,r,o,y,C,D,O]=s;return[zn(e,O,r,o,y,C,D),je.utcInstance]}const $i=yt(yi,Wn),Ri=yt(gi,Wn),Li=yt(xi,Wn),_i=yt(as),ls=gt(ki,vt,Nt,At),Pi=gt(bi,vt,Nt,At),qi=gt(vi,vt,Nt,At),Wi=gt(vt,Nt,At);function zi(s){return xt(s,[$i,ls],[Ri,Pi],[Li,qi],[_i,Wi])}function Hi(s){return xt(Ei(s),[Di,Oi])}function Vi(s){return xt(s,[Ii,os],[Fi,os],[Ni,Ai])}function Ui(s){return xt(s,[Ti,Mi])}const Bi=gt(vt);function Gi(s){return xt(s,[Ci,Bi])}const Yi=yt(Si,wi),Zi=yt(is),Xi=gt(vt,Nt,At);function Ki(s){return xt(s,[Yi,ls],[Zi,Xi])}const cs="Invalid Duration",us={weeks:{days:7,hours:168,minutes:10080,seconds:10080*60,milliseconds:10080*60*1e3},days:{hours:24,minutes:1440,seconds:1440*60,milliseconds:1440*60*1e3},hours:{minutes:60,seconds:3600,milliseconds:3600*1e3},minutes:{seconds:60,milliseconds:60*1e3},seconds:{milliseconds:1e3}},Qi={years:{quarters:4,months:12,weeks:52,days:365,hours:365*24,minutes:365*24*60,seconds:365*24*60*60,milliseconds:365*24*60*60*1e3},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:2184*60,seconds:2184*60*60,milliseconds:2184*60*60*1e3},months:{weeks:4,days:30,hours:720,minutes:720*60,seconds:720*60*60,milliseconds:720*60*60*1e3},...us},Re=146097/400,St=146097/4800,Ji={years:{quarters:4,months:12,weeks:Re/7,days:Re,hours:Re*24,minutes:Re*24*60,seconds:Re*24*60*60,milliseconds:Re*24*60*60*1e3},quarters:{months:3,weeks:Re/28,days:Re/4,hours:Re*24/4,minutes:Re*24*60/4,seconds:Re*24*60*60/4,milliseconds:Re*24*60*60*1e3/4},months:{weeks:St/7,days:St,hours:St*24,minutes:St*24*60,seconds:St*24*60*60,milliseconds:St*24*60*60*1e3},...us},ot=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],eo=ot.slice(0).reverse();function Ze(s,e,r=!1){const o={values:r?e.values:{...s.values,...e.values||{}},loc:s.loc.clone(e.loc),conversionAccuracy:e.conversionAccuracy||s.conversionAccuracy,matrix:e.matrix||s.matrix};return new oe(o)}function ds(s,e){var r;let o=(r=e.milliseconds)!=null?r:0;for(const y of eo.slice(1))e[y]&&(o+=e[y]*s[y].milliseconds);return o}function hs(s,e){const r=ds(s,e)<0?-1:1;ot.reduceRight((o,y)=>{if(re(e[y]))return o;if(o){const C=e[o]*r,D=s[y][o],O=Math.floor(C/D);e[y]+=O*r,e[o]-=O*D*r}return y},null),ot.reduce((o,y)=>{if(re(e[y]))return o;if(o){const C=e[o]%1;e[o]-=C,e[y]+=C*s[o][y]}return y},null)}function fs(s){const e={};for(const[r,o]of Object.entries(s))o!==0&&(e[r]=o);return e}class oe{constructor(e){const r=e.conversionAccuracy==="longterm"||!1;let o=r?Ji:Qi;e.matrix&&(o=e.matrix),this.values=e.values,this.loc=e.loc||ue.create(),this.conversionAccuracy=r?"longterm":"casual",this.invalid=e.invalid||null,this.matrix=o,this.isLuxonDuration=!0}static fromMillis(e,r){return oe.fromObject({milliseconds:e},r)}static fromObject(e,r={}){if(e==null||typeof e!="object")throw new l(`Duration.fromObject: argument expected to be an object, got ${e===null?"null":typeof e}`);return new oe({values:dn(e,oe.normalizeUnit),loc:ue.fromObject(r),conversionAccuracy:r.conversionAccuracy,matrix:r.matrix})}static fromDurationLike(e){if(tt(e))return oe.fromMillis(e);if(oe.isDuration(e))return e;if(typeof e=="object")return oe.fromObject(e);throw new l(`Unknown duration argument ${e} of type ${typeof e}`)}static fromISO(e,r){const[o]=Ui(e);return o?oe.fromObject(o,r):oe.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static fromISOTime(e,r){const[o]=Gi(e);return o?oe.fromObject(o,r):oe.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static invalid(e,r=null){if(!e)throw new l("need to specify a reason the Duration is invalid");const o=e instanceof _e?e:new _e(e,r);if(ve.throwOnInvalid)throw new a(o);return new oe({invalid:o})}static normalizeUnit(e){const r={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[e&&e.toLowerCase()];if(!r)throw new c(e);return r}static isDuration(e){return e&&e.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(e,r={}){const o={...r,floor:r.round!==!1&&r.floor!==!1};return this.isValid?De.create(this.loc,o).formatDurationFromString(this,e):cs}toHuman(e={}){if(!this.isValid)return cs;const r=e.showZeros!==!1,o=ot.map(y=>{const C=this.values[y];return re(C)||C===0&&!r?null:this.loc.numberFormatter({style:"unit",unitDisplay:"long",...e,unit:y.slice(0,-1)}).format(C)}).filter(y=>y);return this.loc.listFormatter({type:"conjunction",style:e.listStyle||"narrow",...e}).format(o)}toObject(){return this.isValid?{...this.values}:{}}toISO(){if(!this.isValid)return null;let e="P";return this.years!==0&&(e+=this.years+"Y"),(this.months!==0||this.quarters!==0)&&(e+=this.months+this.quarters*3+"M"),this.weeks!==0&&(e+=this.weeks+"W"),this.days!==0&&(e+=this.days+"D"),(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)&&(e+="T"),this.hours!==0&&(e+=this.hours+"H"),this.minutes!==0&&(e+=this.minutes+"M"),(this.seconds!==0||this.milliseconds!==0)&&(e+=_n(this.seconds+this.milliseconds/1e3,3)+"S"),e==="P"&&(e+="T0S"),e}toISOTime(e={}){if(!this.isValid)return null;const r=this.toMillis();return r<0||r>=864e5?null:(e={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...e,includeOffset:!1},se.fromMillis(r,{zone:"UTC"}).toISOTime(e))}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Duration { values: ${JSON.stringify(this.values)} }`:`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){return this.isValid?ds(this.matrix,this.values):NaN}valueOf(){return this.toMillis()}plus(e){if(!this.isValid)return this;const r=oe.fromDurationLike(e),o={};for(const y of ot)(mt(r.values,y)||mt(this.values,y))&&(o[y]=r.get(y)+this.get(y));return Ze(this,{values:o},!0)}minus(e){if(!this.isValid)return this;const r=oe.fromDurationLike(e);return this.plus(r.negate())}mapUnits(e){if(!this.isValid)return this;const r={};for(const o of Object.keys(this.values))r[o]=Gr(e(this.values[o],o));return Ze(this,{values:r},!0)}get(e){return this[oe.normalizeUnit(e)]}set(e){if(!this.isValid)return this;const r={...this.values,...dn(e,oe.normalizeUnit)};return Ze(this,{values:r})}reconfigure({locale:e,numberingSystem:r,conversionAccuracy:o,matrix:y}={}){const D={loc:this.loc.clone({locale:e,numberingSystem:r}),matrix:y,conversionAccuracy:o};return Ze(this,D)}as(e){return this.isValid?this.shiftTo(e).get(e):NaN}normalize(){if(!this.isValid)return this;const e=this.toObject();return hs(this.matrix,e),Ze(this,{values:e},!0)}rescale(){if(!this.isValid)return this;const e=fs(this.normalize().shiftToAll().toObject());return Ze(this,{values:e},!0)}shiftTo(...e){if(!this.isValid)return this;if(e.length===0)return this;e=e.map(D=>oe.normalizeUnit(D));const r={},o={},y=this.toObject();let C;for(const D of ot)if(e.indexOf(D)>=0){C=D;let O=0;for(const z in o)O+=this.matrix[z][D]*o[z],o[z]=0;tt(y[D])&&(O+=y[D]);const F=Math.trunc(O);r[D]=F,o[D]=(O*1e3-F*1e3)/1e3}else tt(y[D])&&(o[D]=y[D]);for(const D in o)o[D]!==0&&(r[C]+=D===C?o[D]:o[D]/this.matrix[C][D]);return hs(this.matrix,r),Ze(this,{values:r},!0)}shiftToAll(){return this.isValid?this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds"):this}negate(){if(!this.isValid)return this;const e={};for(const r of Object.keys(this.values))e[r]=this.values[r]===0?0:-this.values[r];return Ze(this,{values:e},!0)}removeZeros(){if(!this.isValid)return this;const e=fs(this.values);return Ze(this,{values:e},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(e){if(!this.isValid||!e.isValid||!this.loc.equals(e.loc))return!1;function r(o,y){return o===void 0||o===0?y===void 0||y===0:o===y}for(const o of ot)if(!r(this.values[o],e.values[o]))return!1;return!0}}const wt="Invalid Interval";function to(s,e){return!s||!s.isValid?Se.invalid("missing or invalid start"):!e||!e.isValid?Se.invalid("missing or invalid end"):e<s?Se.invalid("end before start",`The end of an interval must be after its start, but you had start=${s.toISO()} and end=${e.toISO()}`):null}class Se{constructor(e){this.s=e.start,this.e=e.end,this.invalid=e.invalid||null,this.isLuxonInterval=!0}static invalid(e,r=null){if(!e)throw new l("need to specify a reason the Interval is invalid");const o=e instanceof _e?e:new _e(e,r);if(ve.throwOnInvalid)throw new h(o);return new Se({invalid:o})}static fromDateTimes(e,r){const o=_t(e),y=_t(r),C=to(o,y);return C??new Se({start:o,end:y})}static after(e,r){const o=oe.fromDurationLike(r),y=_t(e);return Se.fromDateTimes(y,y.plus(o))}static before(e,r){const o=oe.fromDurationLike(r),y=_t(e);return Se.fromDateTimes(y.minus(o),y)}static fromISO(e,r){const[o,y]=(e||"").split("/",2);if(o&&y){let C,D;try{C=se.fromISO(o,r),D=C.isValid}catch{D=!1}let O,F;try{O=se.fromISO(y,r),F=O.isValid}catch{F=!1}if(D&&F)return Se.fromDateTimes(C,O);if(D){const z=oe.fromISO(y,r);if(z.isValid)return Se.after(C,z)}else if(F){const z=oe.fromISO(o,r);if(z.isValid)return Se.before(O,z)}}return Se.invalid("unparsable",`the input "${e}" can't be parsed as ISO 8601`)}static isInterval(e){return e&&e.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid&&this.e?this.e.minus(1):null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(e="milliseconds"){return this.isValid?this.toDuration(e).get(e):NaN}count(e="milliseconds",r){if(!this.isValid)return NaN;const o=this.start.startOf(e,r);let y;return r!=null&&r.useLocaleWeeks?y=this.end.reconfigure({locale:o.locale}):y=this.end,y=y.startOf(e,r),Math.floor(y.diff(o,e).get(e))+(y.valueOf()!==this.end.valueOf())}hasSame(e){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,e):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(e){return this.isValid?this.s>e:!1}isBefore(e){return this.isValid?this.e<=e:!1}contains(e){return this.isValid?this.s<=e&&this.e>e:!1}set({start:e,end:r}={}){return this.isValid?Se.fromDateTimes(e||this.s,r||this.e):this}splitAt(...e){if(!this.isValid)return[];const r=e.map(_t).filter(D=>this.contains(D)).sort((D,O)=>D.toMillis()-O.toMillis()),o=[];let{s:y}=this,C=0;for(;y<this.e;){const D=r[C]||this.e,O=+D>+this.e?this.e:D;o.push(Se.fromDateTimes(y,O)),y=O,C+=1}return o}splitBy(e){const r=oe.fromDurationLike(e);if(!this.isValid||!r.isValid||r.as("milliseconds")===0)return[];let{s:o}=this,y=1,C;const D=[];for(;o<this.e;){const O=this.start.plus(r.mapUnits(F=>F*y));C=+O>+this.e?this.e:O,D.push(Se.fromDateTimes(o,C)),o=C,y+=1}return D}divideEqually(e){return this.isValid?this.splitBy(this.length()/e).slice(0,e):[]}overlaps(e){return this.e>e.s&&this.s<e.e}abutsStart(e){return this.isValid?+this.e==+e.s:!1}abutsEnd(e){return this.isValid?+e.e==+this.s:!1}engulfs(e){return this.isValid?this.s<=e.s&&this.e>=e.e:!1}equals(e){return!this.isValid||!e.isValid?!1:this.s.equals(e.s)&&this.e.equals(e.e)}intersection(e){if(!this.isValid)return this;const r=this.s>e.s?this.s:e.s,o=this.e<e.e?this.e:e.e;return r>=o?null:Se.fromDateTimes(r,o)}union(e){if(!this.isValid)return this;const r=this.s<e.s?this.s:e.s,o=this.e>e.e?this.e:e.e;return Se.fromDateTimes(r,o)}static merge(e){const[r,o]=e.sort((y,C)=>y.s-C.s).reduce(([y,C],D)=>C?C.overlaps(D)||C.abutsStart(D)?[y,C.union(D)]:[y.concat([C]),D]:[y,D],[[],null]);return o&&r.push(o),r}static xor(e){let r=null,o=0;const y=[],C=e.map(F=>[{time:F.s,type:"s"},{time:F.e,type:"e"}]),D=Array.prototype.concat(...C),O=D.sort((F,z)=>F.time-z.time);for(const F of O)o+=F.type==="s"?1:-1,o===1?r=F.time:(r&&+r!=+F.time&&y.push(Se.fromDateTimes(r,F.time)),r=null);return Se.merge(y)}difference(...e){return Se.xor([this].concat(e)).map(r=>this.intersection(r)).filter(r=>r&&!r.isEmpty())}toString(){return this.isValid?`[${this.s.toISO()} – ${this.e.toISO()})`:wt}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`:`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(e=S,r={}){return this.isValid?De.create(this.s.loc.clone(r),e).formatInterval(this):wt}toISO(e){return this.isValid?`${this.s.toISO(e)}/${this.e.toISO(e)}`:wt}toISODate(){return this.isValid?`${this.s.toISODate()}/${this.e.toISODate()}`:wt}toISOTime(e){return this.isValid?`${this.s.toISOTime(e)}/${this.e.toISOTime(e)}`:wt}toFormat(e,{separator:r=" – "}={}){return this.isValid?`${this.s.toFormat(e)}${r}${this.e.toFormat(e)}`:wt}toDuration(e,r){return this.isValid?this.e.diff(this.s,e,r):oe.invalid(this.invalidReason)}mapEndpoints(e){return Se.fromDateTimes(e(this.s),e(this.e))}}class $t{static hasDST(e=ve.defaultZone){const r=se.now().setZone(e).set({month:12});return!e.isUniversal&&r.offset!==r.set({month:6}).offset}static isValidIANAZone(e){return ce.isValidZone(e)}static normalizeZone(e){return et(e,ve.defaultZone)}static getStartOfWeek({locale:e=null,locObj:r=null}={}){return(r||ue.create(e)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:e=null,locObj:r=null}={}){return(r||ue.create(e)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:e=null,locObj:r=null}={}){return(r||ue.create(e)).getWeekendDays().slice()}static months(e="long",{locale:r=null,numberingSystem:o=null,locObj:y=null,outputCalendar:C="gregory"}={}){return(y||ue.create(r,o,C)).months(e)}static monthsFormat(e="long",{locale:r=null,numberingSystem:o=null,locObj:y=null,outputCalendar:C="gregory"}={}){return(y||ue.create(r,o,C)).months(e,!0)}static weekdays(e="long",{locale:r=null,numberingSystem:o=null,locObj:y=null}={}){return(y||ue.create(r,o,null)).weekdays(e)}static weekdaysFormat(e="long",{locale:r=null,numberingSystem:o=null,locObj:y=null}={}){return(y||ue.create(r,o,null)).weekdays(e,!0)}static meridiems({locale:e=null}={}){return ue.create(e).meridiems()}static eras(e="short",{locale:r=null}={}){return ue.create(r,null,"gregory").eras(e)}static features(){return{relative:zr(),localeWeek:Hr()}}}function ms(s,e){const r=y=>y.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),o=r(e)-r(s);return Math.floor(oe.fromMillis(o).as("days"))}function no(s,e,r){const o=[["years",(F,z)=>z.year-F.year],["quarters",(F,z)=>z.quarter-F.quarter+(z.year-F.year)*4],["months",(F,z)=>z.month-F.month+(z.year-F.year)*12],["weeks",(F,z)=>{const ee=ms(F,z);return(ee-ee%7)/7}],["days",ms]],y={},C=s;let D,O;for(const[F,z]of o)r.indexOf(F)>=0&&(D=F,y[F]=z(s,e),O=C.plus(y),O>e?(y[F]--,s=C.plus(y),s>e&&(O=s,y[F]--,s=C.plus(y))):s=O);return[s,y,O,D]}function ro(s,e,r,o){let[y,C,D,O]=no(s,e,r);const F=e-y,z=r.filter(ie=>["hours","minutes","seconds","milliseconds"].indexOf(ie)>=0);z.length===0&&(D<e&&(D=y.plus({[O]:1})),D!==y&&(C[O]=(C[O]||0)+F/(D-y)));const ee=oe.fromObject(C,o);return z.length>0?oe.fromMillis(F,o).shiftTo(...z).plus(ee):ee}const so="missing Intl.DateTimeFormat.formatToParts support";function le(s,e=r=>r){return{regex:s,deser:([r])=>e(Ya(r))}}const ps="[ ]",ys=new RegExp(ps,"g");function ao(s){return s.replace(/\./g,"\\.?").replace(ys,ps)}function gs(s){return s.replace(/\./g,"").replace(ys," ").toLowerCase()}function Pe(s,e){return s===null?null:{regex:RegExp(s.map(ao).join("|")),deser:([r])=>s.findIndex(o=>gs(r)===gs(o))+e}}function xs(s,e){return{regex:s,deser:([,r,o])=>un(r,o),groups:e}}function fn(s){return{regex:s,deser:([e])=>e}}function io(s){return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function oo(s,e){const r=Le(e),o=Le(e,"{2}"),y=Le(e,"{3}"),C=Le(e,"{4}"),D=Le(e,"{6}"),O=Le(e,"{1,2}"),F=Le(e,"{1,3}"),z=Le(e,"{1,6}"),ee=Le(e,"{1,9}"),ie=Le(e,"{2,4}"),pe=Le(e,"{4,6}"),ne=Ve=>({regex:RegExp(io(Ve.val)),deser:([Ct])=>Ct,literal:!0}),qe=(Ve=>{if(s.literal)return ne(Ve);switch(Ve.val){case"G":return Pe(e.eras("short"),0);case"GG":return Pe(e.eras("long"),0);case"y":return le(z);case"yy":return le(ie,Pn);case"yyyy":return le(C);case"yyyyy":return le(pe);case"yyyyyy":return le(D);case"M":return le(O);case"MM":return le(o);case"MMM":return Pe(e.months("short",!0),1);case"MMMM":return Pe(e.months("long",!0),1);case"L":return le(O);case"LL":return le(o);case"LLL":return Pe(e.months("short",!1),1);case"LLLL":return Pe(e.months("long",!1),1);case"d":return le(O);case"dd":return le(o);case"o":return le(F);case"ooo":return le(y);case"HH":return le(o);case"H":return le(O);case"hh":return le(o);case"h":return le(O);case"mm":return le(o);case"m":return le(O);case"q":return le(O);case"qq":return le(o);case"s":return le(O);case"ss":return le(o);case"S":return le(F);case"SSS":return le(y);case"u":return fn(ee);case"uu":return fn(O);case"uuu":return le(r);case"a":return Pe(e.meridiems(),0);case"kkkk":return le(C);case"kk":return le(ie,Pn);case"W":return le(O);case"WW":return le(o);case"E":case"c":return le(r);case"EEE":return Pe(e.weekdays("short",!1),1);case"EEEE":return Pe(e.weekdays("long",!1),1);case"ccc":return Pe(e.weekdays("short",!0),1);case"cccc":return Pe(e.weekdays("long",!0),1);case"Z":case"ZZ":return xs(new RegExp(`([+-]${O.source})(?::(${o.source}))?`),2);case"ZZZ":return xs(new RegExp(`([+-]${O.source})(${o.source})?`),2);case"z":return fn(/[a-z_+-/]{1,256}?/i);case" ":return fn(/[^\S\n\r]/);default:return ne(Ve)}})(s)||{invalidReason:so};return qe.token=s,qe}const lo={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function co(s,e,r){const{type:o,value:y}=s;if(o==="literal"){const F=/^\s+$/.test(y);return{literal:!F,val:F?" ":y}}const C=e[o];let D=o;o==="hour"&&(e.hour12!=null?D=e.hour12?"hour12":"hour24":e.hourCycle!=null?e.hourCycle==="h11"||e.hourCycle==="h12"?D="hour12":D="hour24":D=r.hour12?"hour12":"hour24");let O=lo[D];if(typeof O=="object"&&(O=O[C]),O)return{literal:!1,val:O}}function uo(s){return[`^${s.map(r=>r.regex).reduce((r,o)=>`${r}(${o.source})`,"")}$`,s]}function ho(s,e,r){const o=s.match(e);if(o){const y={};let C=1;for(const D in r)if(mt(r,D)){const O=r[D],F=O.groups?O.groups+1:1;!O.literal&&O.token&&(y[O.token.val[0]]=O.deser(o.slice(C,C+F))),C+=F}return[o,y]}else return[o,{}]}function fo(s){const e=C=>{switch(C){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}};let r=null,o;return re(s.z)||(r=ce.create(s.z)),re(s.Z)||(r||(r=new je(s.Z)),o=s.Z),re(s.q)||(s.M=(s.q-1)*3+1),re(s.h)||(s.h<12&&s.a===1?s.h+=12:s.h===12&&s.a===0&&(s.h=0)),s.G===0&&s.y&&(s.y=-s.y),re(s.u)||(s.S=Ln(s.u)),[Object.keys(s).reduce((C,D)=>{const O=e(D);return O&&(C[O]=s[D]),C},{}),r,o]}let Hn=null;function mo(){return Hn||(Hn=se.fromMillis(1555555555555)),Hn}function po(s,e){if(s.literal)return s;const r=De.macroTokenToFormatOpts(s.val),o=ws(r,e);return o==null||o.includes(void 0)?s:o}function bs(s,e){return Array.prototype.concat(...s.map(r=>po(r,e)))}class vs{constructor(e,r){if(this.locale=e,this.format=r,this.tokens=bs(De.parseFormat(r),e),this.units=this.tokens.map(o=>oo(o,e)),this.disqualifyingUnit=this.units.find(o=>o.invalidReason),!this.disqualifyingUnit){const[o,y]=uo(this.units);this.regex=RegExp(o,"i"),this.handlers=y}}explainFromTokens(e){if(this.isValid){const[r,o]=ho(e,this.regex,this.handlers),[y,C,D]=o?fo(o):[null,null,void 0];if(mt(o,"a")&&mt(o,"H"))throw new p("Can't include meridiem when specifying 24-hour format");return{input:e,tokens:this.tokens,regex:this.regex,rawMatches:r,matches:o,result:y,zone:C,specificOffset:D}}else return{input:e,tokens:this.tokens,invalidReason:this.invalidReason}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function Ss(s,e,r){return new vs(s,r).explainFromTokens(e)}function yo(s,e,r){const{result:o,zone:y,specificOffset:C,invalidReason:D}=Ss(s,e,r);return[o,y,C,D]}function ws(s,e){if(!s)return null;const o=De.create(e,s).dtFormatter(mo()),y=o.formatToParts(),C=o.resolvedOptions();return y.map(D=>co(D,s,C))}const Vn="Invalid DateTime",ks=864e13;function Rt(s){return new _e("unsupported zone",`the zone "${s.name}" is not supported`)}function Un(s){return s.weekData===null&&(s.weekData=an(s.c)),s.weekData}function Bn(s){return s.localWeekData===null&&(s.localWeekData=an(s.c,s.loc.getMinDaysInFirstWeek(),s.loc.getStartOfWeek())),s.localWeekData}function lt(s,e){const r={ts:s.ts,zone:s.zone,c:s.c,o:s.o,loc:s.loc,invalid:s.invalid};return new se({...r,...e,old:r})}function Cs(s,e,r){let o=s-e*60*1e3;const y=r.offset(o);if(e===y)return[o,e];o-=(y-e)*60*1e3;const C=r.offset(o);return y===C?[o,y]:[s-Math.min(y,C)*60*1e3,Math.max(y,C)]}function mn(s,e){s+=e*60*1e3;const r=new Date(s);return{year:r.getUTCFullYear(),month:r.getUTCMonth()+1,day:r.getUTCDate(),hour:r.getUTCHours(),minute:r.getUTCMinutes(),second:r.getUTCSeconds(),millisecond:r.getUTCMilliseconds()}}function pn(s,e,r){return Cs(cn(s),e,r)}function Ts(s,e){const r=s.o,o=s.c.year+Math.trunc(e.years),y=s.c.month+Math.trunc(e.months)+Math.trunc(e.quarters)*3,C={...s.c,year:o,month:y,day:Math.min(s.c.day,ln(o,y))+Math.trunc(e.days)+Math.trunc(e.weeks)*7},D=oe.fromObject({years:e.years-Math.trunc(e.years),quarters:e.quarters-Math.trunc(e.quarters),months:e.months-Math.trunc(e.months),weeks:e.weeks-Math.trunc(e.weeks),days:e.days-Math.trunc(e.days),hours:e.hours,minutes:e.minutes,seconds:e.seconds,milliseconds:e.milliseconds}).as("milliseconds"),O=cn(C);let[F,z]=Cs(O,r,s.zone);return D!==0&&(F+=D,z=s.zone.offset(F)),{ts:F,o:z}}function kt(s,e,r,o,y,C){const{setZone:D,zone:O}=r;if(s&&Object.keys(s).length!==0||e){const F=e||O,z=se.fromObject(s,{...r,zone:F,specificOffset:C});return D?z:z.setZone(O)}else return se.invalid(new _e("unparsable",`the input "${y}" can't be parsed as ${o}`))}function yn(s,e,r=!0){return s.isValid?De.create(ue.create("en-US"),{allowZ:r,forceSimple:!0}).formatDateTimeFromString(s,e):null}function Gn(s,e,r){const o=s.c.year>9999||s.c.year<0;let y="";if(o&&s.c.year>=0&&(y+="+"),y+=Ce(s.c.year,o?6:4),r==="year")return y;if(e){if(y+="-",y+=Ce(s.c.month),r==="month")return y;y+="-"}else if(y+=Ce(s.c.month),r==="month")return y;return y+=Ce(s.c.day),y}function Ms(s,e,r,o,y,C,D){let O=!r||s.c.millisecond!==0||s.c.second!==0,F="";switch(D){case"day":case"month":case"year":break;default:if(F+=Ce(s.c.hour),D==="hour")break;if(e){if(F+=":",F+=Ce(s.c.minute),D==="minute")break;O&&(F+=":",F+=Ce(s.c.second))}else{if(F+=Ce(s.c.minute),D==="minute")break;O&&(F+=Ce(s.c.second))}if(D==="second")break;O&&(!o||s.c.millisecond!==0)&&(F+=".",F+=Ce(s.c.millisecond,3))}return y&&(s.isOffsetFixed&&s.offset===0&&!C?F+="Z":s.o<0?(F+="-",F+=Ce(Math.trunc(-s.o/60)),F+=":",F+=Ce(Math.trunc(-s.o%60))):(F+="+",F+=Ce(Math.trunc(s.o/60)),F+=":",F+=Ce(Math.trunc(s.o%60)))),C&&(F+="["+s.zone.ianaName+"]"),F}const js={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},go={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},xo={ordinal:1,hour:0,minute:0,second:0,millisecond:0},gn=["year","month","day","hour","minute","second","millisecond"],bo=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],vo=["year","ordinal","hour","minute","second","millisecond"];function xn(s){const e={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[s.toLowerCase()];if(!e)throw new c(s);return e}function Ds(s){switch(s.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return xn(s)}}function So(s){if(Lt===void 0&&(Lt=ve.now()),s.type!=="iana")return s.offset(Lt);const e=s.name;let r=Yn.get(e);return r===void 0&&(r=s.offset(Lt),Yn.set(e,r)),r}function Os(s,e){const r=et(e.zone,ve.defaultZone);if(!r.isValid)return se.invalid(Rt(r));const o=ue.fromObject(e);let y,C;if(re(s.year))y=ve.now();else{for(const F of gn)re(s[F])&&(s[F]=js[F]);const D=qr(s)||Wr(s);if(D)return se.invalid(D);const O=So(r);[y,C]=pn(s,O,r)}return new se({ts:y,zone:r,loc:o,o:C})}function Es(s,e,r){const o=re(r.round)?!0:r.round,y=re(r.rounding)?"trunc":r.rounding,C=(O,F)=>(O=_n(O,o||r.calendary?0:2,r.calendary?"round":y),e.loc.clone(r).relFormatter(r).format(O,F)),D=O=>r.calendary?e.hasSame(s,O)?0:e.startOf(O).diff(s.startOf(O),O).get(O):e.diff(s,O).get(O);if(r.unit)return C(D(r.unit),r.unit);for(const O of r.units){const F=D(O);if(Math.abs(F)>=1)return C(F,O)}return C(s>e?-0:0,r.units[r.units.length-1])}function Is(s){let e={},r;return s.length>0&&typeof s[s.length-1]=="object"?(e=s[s.length-1],r=Array.from(s).slice(0,s.length-1)):r=Array.from(s),[e,r]}let Lt;const Yn=new Map;class se{constructor(e){const r=e.zone||ve.defaultZone;let o=e.invalid||(Number.isNaN(e.ts)?new _e("invalid input"):null)||(r.isValid?null:Rt(r));this.ts=re(e.ts)?ve.now():e.ts;let y=null,C=null;if(!o)if(e.old&&e.old.ts===this.ts&&e.old.zone.equals(r))[y,C]=[e.old.c,e.old.o];else{const O=tt(e.o)&&!e.old?e.o:r.offset(this.ts);y=mn(this.ts,O),o=Number.isNaN(y.year)?new _e("invalid input"):null,y=o?null:y,C=o?null:O}this._zone=r,this.loc=e.loc||ue.create(),this.invalid=o,this.weekData=null,this.localWeekData=null,this.c=y,this.o=C,this.isLuxonDateTime=!0}static now(){return new se({})}static local(){const[e,r]=Is(arguments),[o,y,C,D,O,F,z]=r;return Os({year:o,month:y,day:C,hour:D,minute:O,second:F,millisecond:z},e)}static utc(){const[e,r]=Is(arguments),[o,y,C,D,O,F,z]=r;return e.zone=je.utcInstance,Os({year:o,month:y,day:C,hour:D,minute:O,second:F,millisecond:z},e)}static fromJSDate(e,r={}){const o=Ja(e)?e.valueOf():NaN;if(Number.isNaN(o))return se.invalid("invalid input");const y=et(r.zone,ve.defaultZone);return y.isValid?new se({ts:o,zone:y,loc:ue.fromObject(r)}):se.invalid(Rt(y))}static fromMillis(e,r={}){if(tt(e))return e<-ks||e>ks?se.invalid("Timestamp out of range"):new se({ts:e,zone:et(r.zone,ve.defaultZone),loc:ue.fromObject(r)});throw new l(`fromMillis requires a numerical input, but received a ${typeof e} with value ${e}`)}static fromSeconds(e,r={}){if(tt(e))return new se({ts:e*1e3,zone:et(r.zone,ve.defaultZone),loc:ue.fromObject(r)});throw new l("fromSeconds requires a numerical input")}static fromObject(e,r={}){e=e||{};const o=et(r.zone,ve.defaultZone);if(!o.isValid)return se.invalid(Rt(o));const y=ue.fromObject(r),C=dn(e,Ds),{minDaysInFirstWeek:D,startOfWeek:O}=Pr(C,y),F=ve.now(),z=re(r.specificOffset)?o.offset(F):r.specificOffset,ee=!re(C.ordinal),ie=!re(C.year),pe=!re(C.month)||!re(C.day),ne=ie||pe,Te=C.weekYear||C.weekNumber;if((ne||ee)&&Te)throw new p("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(pe&&ee)throw new p("Can't mix ordinal dates with month/day");const qe=Te||C.weekday&&!ne;let Ve,Ct,Pt=mn(F,z);qe?(Ve=bo,Ct=go,Pt=an(Pt,D,O)):ee?(Ve=vo,Ct=xo,Pt=$n(Pt)):(Ve=gn,Ct=js);let Fs=!1;for(const Wt of Ve){const jo=C[Wt];re(jo)?Fs?C[Wt]=Ct[Wt]:C[Wt]=Pt[Wt]:Fs=!0}const ko=qe?Xa(C,D,O):ee?Ka(C):qr(C),Ns=ko||Wr(C);if(Ns)return se.invalid(Ns);const Co=qe?Lr(C,D,O):ee?_r(C):C,[To,Mo]=pn(Co,z,o),qt=new se({ts:To,zone:o,o:Mo,loc:y});return C.weekday&&ne&&e.weekday!==qt.weekday?se.invalid("mismatched weekday",`you can't specify both a weekday of ${C.weekday} and a date of ${qt.toISO()}`):qt.isValid?qt:se.invalid(qt.invalid)}static fromISO(e,r={}){const[o,y]=zi(e);return kt(o,y,r,"ISO 8601",e)}static fromRFC2822(e,r={}){const[o,y]=Hi(e);return kt(o,y,r,"RFC 2822",e)}static fromHTTP(e,r={}){const[o,y]=Vi(e);return kt(o,y,r,"HTTP",r)}static fromFormat(e,r,o={}){if(re(e)||re(r))throw new l("fromFormat requires an input string and a format");const{locale:y=null,numberingSystem:C=null}=o,D=ue.fromOpts({locale:y,numberingSystem:C,defaultToEN:!0}),[O,F,z,ee]=yo(D,e,r);return ee?se.invalid(ee):kt(O,F,o,`format ${r}`,e,z)}static fromString(e,r,o={}){return se.fromFormat(e,r,o)}static fromSQL(e,r={}){const[o,y]=Ki(e);return kt(o,y,r,"SQL",e)}static invalid(e,r=null){if(!e)throw new l("need to specify a reason the DateTime is invalid");const o=e instanceof _e?e:new _e(e,r);if(ve.throwOnInvalid)throw new i(o);return new se({invalid:o})}static isDateTime(e){return e&&e.isLuxonDateTime||!1}static parseFormatForOpts(e,r={}){const o=ws(e,ue.fromObject(r));return o?o.map(y=>y?y.val:null).join(""):null}static expandFormat(e,r={}){return bs(De.parseFormat(e),ue.fromObject(r)).map(y=>y.val).join("")}static resetCache(){Lt=void 0,Yn.clear()}get(e){return this[e]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?Un(this).weekYear:NaN}get weekNumber(){return this.isValid?Un(this).weekNumber:NaN}get weekday(){return this.isValid?Un(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?Bn(this).weekday:NaN}get localWeekNumber(){return this.isValid?Bn(this).weekNumber:NaN}get localWeekYear(){return this.isValid?Bn(this).weekYear:NaN}get ordinal(){return this.isValid?$n(this.c).ordinal:NaN}get monthShort(){return this.isValid?$t.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?$t.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?$t.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?$t.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){return this.isValid?this.zone.offsetName(this.ts,{format:"short",locale:this.locale}):null}get offsetNameLong(){return this.isValid?this.zone.offsetName(this.ts,{format:"long",locale:this.locale}):null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){return this.isOffsetFixed?!1:this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];const e=864e5,r=6e4,o=cn(this.c),y=this.zone.offset(o-e),C=this.zone.offset(o+e),D=this.zone.offset(o-y*r),O=this.zone.offset(o-C*r);if(D===O)return[this];const F=o-D*r,z=o-O*r,ee=mn(F,D),ie=mn(z,O);return ee.hour===ie.hour&&ee.minute===ie.minute&&ee.second===ie.second&&ee.millisecond===ie.millisecond?[lt(this,{ts:F}),lt(this,{ts:z})]:[this]}get isInLeapYear(){return Et(this.year)}get daysInMonth(){return ln(this.year,this.month)}get daysInYear(){return this.isValid?pt(this.year):NaN}get weeksInWeekYear(){return this.isValid?It(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?It(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(e={}){const{locale:r,numberingSystem:o,calendar:y}=De.create(this.loc.clone(e),e).resolvedOptions(this);return{locale:r,numberingSystem:o,outputCalendar:y}}toUTC(e=0,r={}){return this.setZone(je.instance(e),r)}toLocal(){return this.setZone(ve.defaultZone)}setZone(e,{keepLocalTime:r=!1,keepCalendarTime:o=!1}={}){if(e=et(e,ve.defaultZone),e.equals(this.zone))return this;if(e.isValid){let y=this.ts;if(r||o){const C=e.offset(this.ts),D=this.toObject();[y]=pn(D,C,e)}return lt(this,{ts:y,zone:e})}else return se.invalid(Rt(e))}reconfigure({locale:e,numberingSystem:r,outputCalendar:o}={}){const y=this.loc.clone({locale:e,numberingSystem:r,outputCalendar:o});return lt(this,{loc:y})}setLocale(e){return this.reconfigure({locale:e})}set(e){if(!this.isValid)return this;const r=dn(e,Ds),{minDaysInFirstWeek:o,startOfWeek:y}=Pr(r,this.loc),C=!re(r.weekYear)||!re(r.weekNumber)||!re(r.weekday),D=!re(r.ordinal),O=!re(r.year),F=!re(r.month)||!re(r.day),z=O||F,ee=r.weekYear||r.weekNumber;if((z||D)&&ee)throw new p("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(F&&D)throw new p("Can't mix ordinal dates with month/day");let ie;C?ie=Lr({...an(this.c,o,y),...r},o,y):re(r.ordinal)?(ie={...this.toObject(),...r},re(r.day)&&(ie.day=Math.min(ln(ie.year,ie.month),ie.day))):ie=_r({...$n(this.c),...r});const[pe,ne]=pn(ie,this.o,this.zone);return lt(this,{ts:pe,o:ne})}plus(e){if(!this.isValid)return this;const r=oe.fromDurationLike(e);return lt(this,Ts(this,r))}minus(e){if(!this.isValid)return this;const r=oe.fromDurationLike(e).negate();return lt(this,Ts(this,r))}startOf(e,{useLocaleWeeks:r=!1}={}){if(!this.isValid)return this;const o={},y=oe.normalizeUnit(e);switch(y){case"years":o.month=1;case"quarters":case"months":o.day=1;case"weeks":case"days":o.hour=0;case"hours":o.minute=0;case"minutes":o.second=0;case"seconds":o.millisecond=0;break}if(y==="weeks")if(r){const C=this.loc.getStartOfWeek(),{weekday:D}=this;D<C&&(o.weekNumber=this.weekNumber-1),o.weekday=C}else o.weekday=1;if(y==="quarters"){const C=Math.ceil(this.month/3);o.month=(C-1)*3+1}return this.set(o)}endOf(e,r){return this.isValid?this.plus({[e]:1}).startOf(e,r).minus(1):this}toFormat(e,r={}){return this.isValid?De.create(this.loc.redefaultToEN(r)).formatDateTimeFromString(this,e):Vn}toLocaleString(e=S,r={}){return this.isValid?De.create(this.loc.clone(r),e).formatDateTime(this):Vn}toLocaleParts(e={}){return this.isValid?De.create(this.loc.clone(e),e).formatDateTimeParts(this):[]}toISO({format:e="extended",suppressSeconds:r=!1,suppressMilliseconds:o=!1,includeOffset:y=!0,extendedZone:C=!1,precision:D="milliseconds"}={}){if(!this.isValid)return null;D=xn(D);const O=e==="extended";let F=Gn(this,O,D);return gn.indexOf(D)>=3&&(F+="T"),F+=Ms(this,O,r,o,y,C,D),F}toISODate({format:e="extended",precision:r="day"}={}){return this.isValid?Gn(this,e==="extended",xn(r)):null}toISOWeekDate(){return yn(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:e=!1,suppressSeconds:r=!1,includeOffset:o=!0,includePrefix:y=!1,extendedZone:C=!1,format:D="extended",precision:O="milliseconds"}={}){return this.isValid?(O=xn(O),(y&&gn.indexOf(O)>=3?"T":"")+Ms(this,D==="extended",r,e,o,C,O)):null}toRFC2822(){return yn(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return yn(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){return this.isValid?Gn(this,!0):null}toSQLTime({includeOffset:e=!0,includeZone:r=!1,includeOffsetSpace:o=!0}={}){let y="HH:mm:ss.SSS";return(r||e)&&(o&&(y+=" "),r?y+="z":e&&(y+="ZZ")),yn(this,y,!0)}toSQL(e={}){return this.isValid?`${this.toSQLDate()} ${this.toSQLTime(e)}`:null}toString(){return this.isValid?this.toISO():Vn}[Symbol.for("nodejs.util.inspect.custom")](){return this.isValid?`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`:`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1e3:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1e3):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(e={}){if(!this.isValid)return{};const r={...this.c};return e.includeConfig&&(r.outputCalendar=this.outputCalendar,r.numberingSystem=this.loc.numberingSystem,r.locale=this.loc.locale),r}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(e,r="milliseconds",o={}){if(!this.isValid||!e.isValid)return oe.invalid("created by diffing an invalid DateTime");const y={locale:this.locale,numberingSystem:this.numberingSystem,...o},C=ei(r).map(oe.normalizeUnit),D=e.valueOf()>this.valueOf(),O=D?this:e,F=D?e:this,z=ro(O,F,C,y);return D?z.negate():z}diffNow(e="milliseconds",r={}){return this.diff(se.now(),e,r)}until(e){return this.isValid?Se.fromDateTimes(this,e):this}hasSame(e,r,o){if(!this.isValid)return!1;const y=e.valueOf(),C=this.setZone(e.zone,{keepLocalTime:!0});return C.startOf(r,o)<=y&&y<=C.endOf(r,o)}equals(e){return this.isValid&&e.isValid&&this.valueOf()===e.valueOf()&&this.zone.equals(e.zone)&&this.loc.equals(e.loc)}toRelative(e={}){if(!this.isValid)return null;const r=e.base||se.fromObject({},{zone:this.zone}),o=e.padding?this<r?-e.padding:e.padding:0;let y=["years","months","days","hours","minutes","seconds"],C=e.unit;return Array.isArray(e.unit)&&(y=e.unit,C=void 0),Es(r,this.plus(o),{...e,numeric:"always",units:y,unit:C})}toRelativeCalendar(e={}){return this.isValid?Es(e.base||se.fromObject({},{zone:this.zone}),this,{...e,numeric:"auto",units:["years","months","days"],calendary:!0}):null}static min(...e){if(!e.every(se.isDateTime))throw new l("min requires all arguments be DateTimes");return Vr(e,r=>r.valueOf(),Math.min)}static max(...e){if(!e.every(se.isDateTime))throw new l("max requires all arguments be DateTimes");return Vr(e,r=>r.valueOf(),Math.max)}static fromFormatExplain(e,r,o={}){const{locale:y=null,numberingSystem:C=null}=o,D=ue.fromOpts({locale:y,numberingSystem:C,defaultToEN:!0});return Ss(D,e,r)}static fromStringExplain(e,r,o={}){return se.fromFormatExplain(e,r,o)}static buildFormatParser(e,r={}){const{locale:o=null,numberingSystem:y=null}=r,C=ue.fromOpts({locale:o,numberingSystem:y,defaultToEN:!0});return new vs(C,e)}static fromFormatParser(e,r,o={}){if(re(e)||re(r))throw new l("fromFormatParser requires an input string and a format parser");const{locale:y=null,numberingSystem:C=null}=o,D=ue.fromOpts({locale:y,numberingSystem:C,defaultToEN:!0});if(!D.equals(r.locale))throw new l(`fromFormatParser called with a locale of ${D}, but the format parser was created for ${r.locale}`);const{result:O,zone:F,specificOffset:z,invalidReason:ee}=r.explainFromTokens(e);return ee?se.invalid(ee):kt(O,F,o,`format ${r.format}`,e,z)}static get DATE_SHORT(){return S}static get DATE_MED(){return b}static get DATE_MED_WITH_WEEKDAY(){return g}static get DATE_FULL(){return k}static get DATE_HUGE(){return w}static get TIME_SIMPLE(){return T}static get TIME_WITH_SECONDS(){return M}static get TIME_WITH_SHORT_OFFSET(){return j}static get TIME_WITH_LONG_OFFSET(){return I}static get TIME_24_SIMPLE(){return E}static get TIME_24_WITH_SECONDS(){return L}static get TIME_24_WITH_SHORT_OFFSET(){return H}static get TIME_24_WITH_LONG_OFFSET(){return _}static get DATETIME_SHORT(){return Y}static get DATETIME_SHORT_WITH_SECONDS(){return N}static get DATETIME_MED(){return q}static get DATETIME_MED_WITH_SECONDS(){return B}static get DATETIME_MED_WITH_WEEKDAY(){return A}static get DATETIME_FULL(){return P}static get DATETIME_FULL_WITH_SECONDS(){return G}static get DATETIME_HUGE(){return K}static get DATETIME_HUGE_WITH_SECONDS(){return X}}function _t(s){if(se.isDateTime(s))return s;if(s&&s.valueOf&&tt(s.valueOf()))return se.fromJSDate(s);if(s&&typeof s=="object")return se.fromObject(s);throw new l(`Unknown datetime argument: ${s}, of type ${typeof s}`)}const wo="3.7.2";return Ee.DateTime=se,Ee.Duration=oe,Ee.FixedOffsetZone=je,Ee.IANAZone=ce,Ee.Info=$t,Ee.Interval=Se,Ee.InvalidZone=kr,Ee.Settings=ve,Ee.SystemZone=te,Ee.VERSION=wo,Ee.Zone=J,Ee}var Xs;function gr(){return Xs||(Xs=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CronDate=t.DAYS_IN_MONTH=t.DateMathOp=t.TimeUnit=void 0;const i=Xl();var h;(function(c){c.Second="Second",c.Minute="Minute",c.Hour="Hour",c.Day="Day",c.Month="Month",c.Year="Year"})(h||(t.TimeUnit=h={}));var a;(function(c){c.Add="Add",c.Subtract="Subtract"})(a||(t.DateMathOp=a={})),t.DAYS_IN_MONTH=Object.freeze([31,29,31,30,31,30,31,31,30,31,30,31]);class p{#e;#n=null;#a=null;constructor(l,f){const d={zone:f};if(l?l instanceof p?(this.#e=l.#e,this.#n=l.#n,this.#a=l.#a):l instanceof Date?this.#e=i.DateTime.fromJSDate(l,d):typeof l=="number"?this.#e=i.DateTime.fromMillis(l,d):(this.#e=i.DateTime.fromISO(l,d),this.#e.isValid||(this.#e=i.DateTime.fromRFC2822(l,d)),this.#e.isValid||(this.#e=i.DateTime.fromSQL(l,d)),this.#e.isValid||(this.#e=i.DateTime.fromFormat(l,"EEE, d MMM yyyy HH:mm:ss",d))):this.#e=i.DateTime.local(),!this.#e.isValid)throw new Error(`CronDate: unhandled timestamp: ${l}`);f&&f!==this.#e.zoneName&&(this.#e=this.#e.setZone(f))}static#s(l){return l%4===0&&l%100!==0||l%400===0}get dstStart(){return this.#n}set dstStart(l){this.#n=l}get dstEnd(){return this.#a}set dstEnd(l){this.#a=l}addYear(){this.#e=this.#e.plus({years:1})}addMonth(){this.#e=this.#e.plus({months:1}).startOf("month")}addDay(){this.#e=this.#e.plus({days:1}).startOf("day")}addHour(){this.#e=this.#e.plus({hours:1}).startOf("hour")}addMinute(){this.#e=this.#e.plus({minutes:1}).startOf("minute")}addSecond(){this.#e=this.#e.plus({seconds:1})}subtractYear(){this.#e=this.#e.minus({years:1})}subtractMonth(){this.#e=this.#e.minus({months:1}).endOf("month").startOf("second")}subtractDay(){this.#e=this.#e.minus({days:1}).endOf("day").startOf("second")}subtractHour(){this.#e=this.#e.minus({hours:1}).endOf("hour").startOf("second")}subtractMinute(){this.#e=this.#e.minus({minutes:1}).endOf("minute").startOf("second")}subtractSecond(){this.#e=this.#e.minus({seconds:1})}addUnit(l){switch(l){case h.Year:return this.addYear();case h.Month:return this.addMonth();case h.Day:return this.addDay();case h.Hour:return this.addHour();case h.Minute:return this.addMinute();case h.Second:return this.addSecond()}}subtractUnit(l){switch(l){case h.Year:return this.subtractYear();case h.Month:return this.subtractMonth();case h.Day:return this.subtractDay();case h.Hour:return this.subtractHour();case h.Minute:return this.subtractMinute();case h.Second:return this.subtractSecond()}}invokeDateOperation(l,f){if(l===a.Add){this.addUnit(f);return}if(l===a.Subtract){this.subtractUnit(f);return}throw new Error(`Invalid verb: ${l}`)}getDate(){return this.#e.day}getFullYear(){return this.#e.year}getDay(){const l=this.#e.weekday;return l===7?0:l}getMonth(){return this.#e.month-1}getHours(){return this.#e.hour}getMinutes(){return this.#e.minute}getSeconds(){return this.#e.second}getMilliseconds(){return this.#e.millisecond}getUTCOffset(){return this.#e.offset}setStartOfDay(){this.#e=this.#e.startOf("day")}setEndOfDay(){this.#e=this.#e.endOf("day")}getTime(){return this.#e.valueOf()}getUTCDate(){return this.#r().day}getUTCFullYear(){return this.#r().year}getUTCDay(){const l=this.#r().weekday;return l===7?0:l}getUTCMonth(){return this.#r().month-1}getUTCHours(){return this.#r().hour}getUTCMinutes(){return this.#r().minute}getUTCSeconds(){return this.#r().second}toISOString(){return this.#e.toUTC().toISO()}toJSON(){return this.#e.toJSON()}setDate(l){this.#e=this.#e.set({day:l})}setFullYear(l){this.#e=this.#e.set({year:l})}setDay(l){this.#e=this.#e.set({weekday:l})}setMonth(l){this.#e=this.#e.set({month:l+1})}setHours(l){this.#e=this.#e.set({hour:l})}setMinutes(l){this.#e=this.#e.set({minute:l})}setSeconds(l){this.#e=this.#e.set({second:l})}setMilliseconds(l){this.#e=this.#e.set({millisecond:l})}toString(){return this.toDate().toString()}toDate(){return this.#e.toJSDate()}isLastDayOfMonth(){const{day:l,month:f}=this.#e;if(f===2){const d=p.#s(this.#e.year);return l===t.DAYS_IN_MONTH[f-1]-(d?0:1)}return l===t.DAYS_IN_MONTH[f-1]}isLastWeekdayOfMonth(){const{day:l,month:f}=this.#e;let d;return f===2?d=t.DAYS_IN_MONTH[f-1]-(p.#s(this.#e.year)?0:1):d=t.DAYS_IN_MONTH[f-1],l>d-7}applyDateOperation(l,f,d){if(f===h.Month||f===h.Day){this.invokeDateOperation(l,f);return}const m=this.getHours();this.invokeDateOperation(l,f);const x=this.getHours(),S=x-m;S===2?d!==24&&(this.dstStart=m+1):S===0&&this.getMinutes()===0&&this.getSeconds()===0&&d!==24&&(this.dstEnd=x)}#r(){return this.#e.toUTC()}}t.CronDate=p,t.default=p})(Jn)),Jn}var Ks;function Kl(){if(Ks)return Zt;Ks=1,Object.defineProperty(Zt,"__esModule",{value:!0}),Zt.CronMonth=void 0;const t=gr(),i=ft(),h=1,a=12,p=Object.freeze([]);let c=class extends i.CronField{static get min(){return h}static get max(){return a}static get chars(){return p}static get daysInMonth(){return t.DAYS_IN_MONTH}constructor(f,d){super(f,d),this.validate()}get values(){return super.values}};return Zt.CronMonth=c,Zt}var Xt={},Qs;function Ql(){if(Qs)return Xt;Qs=1,Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.CronSecond=void 0;const t=ft(),i=0,h=59,a=Object.freeze([]);let p=class extends t.CronField{static get min(){return i}static get max(){return h}static get chars(){return a}constructor(l,f){super(l,f),this.validate()}get values(){return super.values}};return Xt.CronSecond=p,Xt}var Js;function xr(){return Js||(Js=1,(function(t){var i=ut&&ut.__createBinding||(Object.create?(function(a,p,c,l){l===void 0&&(l=c);var f=Object.getOwnPropertyDescriptor(p,c);(!f||("get"in f?!p.__esModule:f.writable||f.configurable))&&(f={enumerable:!0,get:function(){return p[c]}}),Object.defineProperty(a,l,f)}):(function(a,p,c,l){l===void 0&&(l=c),a[l]=p[c]})),h=ut&&ut.__exportStar||function(a,p){for(var c in a)c!=="default"&&!Object.prototype.hasOwnProperty.call(p,c)&&i(p,a,c)};Object.defineProperty(t,"__esModule",{value:!0}),h(Ul(),t),h(Bl(),t),h(Gl(),t),h(ft(),t),h(Yl(),t),h(Zl(),t),h(Kl(),t),h(Ql(),t)})(ut)),ut}var ea;function ka(){if(ea)return Ht;ea=1,Object.defineProperty(Ht,"__esModule",{value:!0}),Ht.CronFieldCollection=void 0;const t=xr();let i=class en{#e;#n;#a;#s;#r;#t;static from(a,p){return new en({second:this.resolveField(t.CronSecond,a.second,p.second),minute:this.resolveField(t.CronMinute,a.minute,p.minute),hour:this.resolveField(t.CronHour,a.hour,p.hour),dayOfMonth:this.resolveField(t.CronDayOfMonth,a.dayOfMonth,p.dayOfMonth),month:this.resolveField(t.CronMonth,a.month,p.month),dayOfWeek:this.resolveField(t.CronDayOfWeek,a.dayOfWeek,p.dayOfWeek)})}static resolveField(a,p,c){return c?c instanceof t.CronField?c:new a(c):p}constructor({second:a,minute:p,hour:c,dayOfMonth:l,month:f,dayOfWeek:d}){if(!a)throw new Error("Validation error, Field second is missing");if(!p)throw new Error("Validation error, Field minute is missing");if(!c)throw new Error("Validation error, Field hour is missing");if(!l)throw new Error("Validation error, Field dayOfMonth is missing");if(!f)throw new Error("Validation error, Field month is missing");if(!d)throw new Error("Validation error, Field dayOfWeek is missing");if(f.values.length===1&&!l.hasLastChar&&d.isWildcard&&!(parseInt(l.values[0],10)<=t.CronMonth.daysInMonth[f.values[0]-1]))throw new Error("Invalid explicit day of month definition");this.#e=a,this.#n=p,this.#a=c,this.#r=f,this.#t=d,this.#s=l}get second(){return this.#e}get minute(){return this.#n}get hour(){return this.#a}get dayOfMonth(){return this.#s}get month(){return this.#r}get dayOfWeek(){return this.#t}static compactField(a){if(a.length===0)return[];const p=[];let c;return a.forEach((l,f,d)=>{if(c===void 0){c={start:l,count:1};return}const m=d[f-1]||c.start,x=d[f+1];if(l==="L"||l==="W"){p.push(c),p.push({start:l,count:1}),c=void 0;return}if(c.step===void 0&&x!==void 0){const S=l-m,b=x-l;if(S<=b){c={...c,count:2,end:l,step:S};return}c.step=1}l-(c.end??0)===c.step?(c.count++,c.end=l):(c.count===1?p.push({start:c.start,count:1}):c.count===2?(p.push({start:c.start,count:1}),p.push({start:c.end??m,count:1})):p.push(c),c={start:l,count:1})}),c&&p.push(c),p}static#c(a,p,c){const l=p.step;return l?l===1&&p.start===a.min&&p.end&&p.end>=c?a.hasQuestionMarkChar?"?":"*":l!==1&&p.start===a.min&&p.end&&p.end>=c-l+1?`*/${l}`:null:null}static#l(a,p){const c=a.step;if(c===1)return`${a.start}-${a.end}`;const l=a.start===0?a.count-1:a.count;if(!c)throw new Error("Unexpected range step");if(!a.end)throw new Error("Unexpected range end");if(c*l>a.end){const f=(m,x)=>{if(typeof a.start!="number")throw new Error("Unexpected range start");return x%c===0?a.start+x:null};if(typeof a.start!="number")throw new Error("Unexpected range start");const d={length:a.end-a.start+1};return Array.from(d,f).filter(m=>m!==null).join(",")}return a.end===p-c+1?`${a.start}/${c}`:`${a.start}-${a.end}/${c}`}stringifyField(a){let p=a.max,c=a.values;if(a instanceof t.CronDayOfWeek){p=6;const f=this.#t.values;c=f[f.length-1]===7?f.slice(0,-1):f}a instanceof t.CronDayOfMonth&&(p=this.#r.values.length===1?t.CronMonth.daysInMonth[this.#r.values[0]-1]:a.max);const l=en.compactField(c);if(l.length===1){const f=en.#c(a,l[0],p);if(f)return f}return l.map(f=>{const d=f.count===1?f.start.toString():en.#l(f,p);return a instanceof t.CronDayOfWeek&&a.nthDay>0?`${d}#${a.nthDay}`:d}).join(",")}stringify(a=!1){const p=[];return a&&p.push(this.stringifyField(this.#e)),p.push(this.stringifyField(this.#n),this.stringifyField(this.#a),this.stringifyField(this.#s),this.stringifyField(this.#r),this.stringifyField(this.#t)),p.join(" ")}serialize(){return{second:this.#e.serialize(),minute:this.#n.serialize(),hour:this.#a.serialize(),dayOfMonth:this.#s.serialize(),month:this.#r.serialize(),dayOfWeek:this.#t.serialize()}}};return Ht.CronFieldCollection=i,Ht}var er={},ta;function Ca(){return ta||(ta=1,(function(t){Object.defineProperty(t,"__esModule",{value:!0}),t.CronExpression=t.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE=t.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE=void 0;const i=gr();t.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE="Out of the time span range",t.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE="Invalid expression, loop limit exceeded";const h=1e4;class a{#e;#n;#a;#s;#r;#t;#c=null;#l=!1;constructor(c,l){this.#e=l,this.#n=l.tz,this.#s=l.startDate?new i.CronDate(l.startDate,this.#n):null,this.#r=l.endDate?new i.CronDate(l.endDate,this.#n):null;let f=l.currentDate??l.startDate;if(f){const d=new i.CronDate(f,this.#n);this.#s&&d.getTime()<this.#s.getTime()?f=this.#s:this.#r&&d.getTime()>this.#r.getTime()&&(f=this.#r)}this.#a=new i.CronDate(f,this.#n),this.#t=c}get fields(){return this.#t}static fieldsToExpression(c,l){return new a(c,l||{})}static#i(c,l){return l.some(f=>f===c)}#o(c,l){return c[l?c.length-1:0]}#d(c){const l=`${c.getFullYear()}-${c.getMonth()+1}-${c.getDate()}`;if(this.#c===l)return this.#l;const f=new i.CronDate(c);f.setStartOfDay();const d=new i.CronDate(c);return d.setEndOfDay(),this.#c=l,this.#l=f.getUTCOffset()!==d.getUTCOffset(),this.#l}#h(c,l,f){const d=this.#t.second.values,m=c.getSeconds(),x=this.#t.second.findNearestValue(m,f);if(x!==null){c.setSeconds(x);return}c.applyDateOperation(l,i.TimeUnit.Minute,this.#t.hour.values.length),c.setSeconds(this.#o(d,f))}#m(c,l,f){const d=this.#t.minute.values,m=this.#t.second.values,x=c.getMinutes(),S=this.#t.minute.findNearestValue(x,f);if(S!==null){c.setMinutes(S),c.setSeconds(this.#o(m,f));return}c.applyDateOperation(l,i.TimeUnit.Hour,this.#t.hour.values.length),c.setMinutes(this.#o(d,f)),c.setSeconds(this.#o(m,f))}static#p(c,l){const f=l.isLastWeekdayOfMonth();return c.some(d=>{const m=parseInt(d.toString().charAt(0),10)%7;if(Number.isNaN(m))throw new Error(`Invalid last weekday of the month expression: ${d}`);return l.getDay()===m&&f})}next(){return this.#u()}prev(){return this.#u(!0)}hasNext(){const c=this.#a;try{return this.#u(),!0}catch{return!1}finally{this.#a=c}}hasPrev(){const c=this.#a;try{return this.#u(!0),!0}catch{return!1}finally{this.#a=c}}take(c){const l=[];if(c>=0)for(let f=0;f<c;f++)try{l.push(this.next())}catch{return l}else for(let f=0;f>c;f--)try{l.push(this.prev())}catch{return l}return l}reset(c){this.#a=new i.CronDate(c||this.#e.currentDate,this.#n)}stringify(c=!1){return this.#t.stringify(c)}includesDate(c){const{second:l,minute:f,hour:d,month:m}=this.#t,x=new i.CronDate(c,this.#n);return!(!l.values.includes(x.getSeconds())||!f.values.includes(x.getMinutes())||!d.values.includes(x.getHours())||!m.values.includes(x.getMonth()+1)||!this.#f(x)||this.#t.dayOfWeek.nthDay>0&&Math.ceil(x.getDate()/7)!==this.#t.dayOfWeek.nthDay)}toString(){return this.#e.expression||this.stringify(!0)}#f(c){const l=this.#t.dayOfMonth.isWildcard,f=!l,d=this.#t.dayOfWeek.isWildcard,m=!d,x=a.#i(c.getDate(),this.#t.dayOfMonth.values)||this.#t.dayOfMonth.hasLastChar&&c.isLastDayOfMonth(),S=a.#i(c.getDay(),this.#t.dayOfWeek.values)||this.#t.dayOfWeek.hasLastChar&&a.#p(this.#t.dayOfWeek.values,c);return!!(f&&m&&(x||S)||x&&!m||l&&!d&&S)}#y(c,l,f){const d=this.#t.hour.values,m=d,x=c.getHours(),S=a.#i(x,d),b=c.dstEnd===x;if(c.dstStart!==null&&c.dstStart===x-1&&a.#i(c.dstStart,d))return!0;if(b&&!f)return c.dstEnd=null,c.applyDateOperation(i.DateMathOp.Add,i.TimeUnit.Hour,m.length),!1;if(S)return!0;c.dstStart=null;const g=this.#t.hour.findNearestValue(x,f);if(g===null)return c.applyDateOperation(l,i.TimeUnit.Day,m.length),!1;if(this.#d(c)){const k=f?x-g:g-x;for(let w=0;w<k&&(c.applyDateOperation(l,i.TimeUnit.Hour,m.length),!(!f&&c.getHours()>=g||f&&c.getHours()<=g));w++);}else c.setHours(g);return c.setMinutes(this.#o(this.#t.minute.values,f)),c.setSeconds(this.#o(this.#t.second.values,f)),!1}#g(c){if(!this.#s&&!this.#r)return;const l=c.getTime();if(this.#s&&l<this.#s.getTime())throw new Error(t.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE);if(this.#r&&l>this.#r.getTime())throw new Error(t.TIME_SPAN_OUT_OF_BOUNDS_ERROR_MESSAGE)}#u(c=!1){const l=c?i.DateMathOp.Subtract:i.DateMathOp.Add,f=new i.CronDate(this.#a),d=f.getTime();let m=0;for(;++m<h;){if(this.#g(f),!this.#f(f)){f.applyDateOperation(l,i.TimeUnit.Day,this.#t.hour.values.length);continue}if(!(this.#t.dayOfWeek.nthDay<=0||Math.ceil(f.getDate()/7)===this.#t.dayOfWeek.nthDay)){f.applyDateOperation(l,i.TimeUnit.Day,this.#t.hour.values.length);continue}if(!a.#i(f.getMonth()+1,this.#t.month.values)){f.applyDateOperation(l,i.TimeUnit.Month,this.#t.hour.values.length);continue}if(this.#y(f,l,c)){if(!a.#i(f.getMinutes(),this.#t.minute.values)){this.#m(f,l,c);continue}if(!a.#i(f.getSeconds(),this.#t.second.values)){this.#h(f,l,c);continue}if(d===f.getTime()){(l==="Add"||f.getMilliseconds()===0)&&f.applyDateOperation(l,i.TimeUnit.Second,this.#t.hour.values.length);continue}break}}if(m>h)throw new Error(t.LOOPS_LIMIT_EXCEEDED_ERROR_MESSAGE);return f.getMilliseconds()!==0&&f.setMilliseconds(0),this.#a=f,f}[Symbol.iterator](){return{next:()=>{try{return{value:this.#u(),done:!1}}catch{return{value:void 0,done:!0}}}}}}t.CronExpression=a,t.default=a})(er)),er}var bn={},na;function Jl(){if(na)return bn;na=1,Object.defineProperty(bn,"__esModule",{value:!0}),bn.seededRandom=h;function t(a){let p=2166136261;for(let c=0;c<a.length;c++)p^=a.charCodeAt(c),p=Math.imul(p,16777619);return()=>p>>>0}function i(a){return()=>{let p=a+=1831565813;return p=Math.imul(p^p>>>15,p|1),p^=p+Math.imul(p^p>>>7,p|61),((p^p>>>14)>>>0)/4294967296}}function h(a){const p=a?t(a)():Math.floor(Math.random()*1e10);return i(p)}return bn}var ra;function lr(){if(ra)return Ie;ra=1,Object.defineProperty(Ie,"__esModule",{value:!0}),Ie.CronExpressionParser=Ie.DayOfWeek=Ie.Months=Ie.CronUnit=Ie.PredefinedExpressions=void 0;const t=ka(),i=Ca(),h=Jl(),a=xr();var p;(function(m){m["@yearly"]="0 0 0 1 1 *",m["@annually"]="0 0 0 1 1 *",m["@monthly"]="0 0 0 1 * *",m["@weekly"]="0 0 0 * * 0",m["@daily"]="0 0 0 * * *",m["@hourly"]="0 0 * * * *",m["@minutely"]="0 * * * * *",m["@secondly"]="* * * * * *",m["@weekdays"]="0 0 0 * * 1-5",m["@weekends"]="0 0 0 * * 0,6"})(p||(Ie.PredefinedExpressions=p={}));var c;(function(m){m.Second="Second",m.Minute="Minute",m.Hour="Hour",m.DayOfMonth="DayOfMonth",m.Month="Month",m.DayOfWeek="DayOfWeek"})(c||(Ie.CronUnit=c={}));var l;(function(m){m[m.jan=1]="jan",m[m.feb=2]="feb",m[m.mar=3]="mar",m[m.apr=4]="apr",m[m.may=5]="may",m[m.jun=6]="jun",m[m.jul=7]="jul",m[m.aug=8]="aug",m[m.sep=9]="sep",m[m.oct=10]="oct",m[m.nov=11]="nov",m[m.dec=12]="dec"})(l||(Ie.Months=l={}));var f;(function(m){m[m.sun=0]="sun",m[m.mon=1]="mon",m[m.tue=2]="tue",m[m.wed=3]="wed",m[m.thu=4]="thu",m[m.fri=5]="fri",m[m.sat=6]="sat"})(f||(Ie.DayOfWeek=f={}));let d=class Fe{static parse(x,S={}){const{strict:b=!1,hashSeed:g}=S,k=(0,h.seededRandom)(g);x=p[x]||x;const w=Fe.#e(x,b);if(!(w.dayOfMonth==="*"||w.dayOfWeek==="*"||!b))throw new Error("Cannot use both dayOfMonth and dayOfWeek together in strict mode!");const T=Fe.#n(c.Second,w.second,a.CronSecond.constraints,k),M=Fe.#n(c.Minute,w.minute,a.CronMinute.constraints,k),j=Fe.#n(c.Hour,w.hour,a.CronHour.constraints,k),I=Fe.#n(c.Month,w.month,a.CronMonth.constraints,k),E=Fe.#n(c.DayOfMonth,w.dayOfMonth,a.CronDayOfMonth.constraints,k),{dayOfWeek:L,nthDayOfWeek:H}=Fe.#d(w.dayOfWeek),_=Fe.#n(c.DayOfWeek,L,a.CronDayOfWeek.constraints,k),Y=new t.CronFieldCollection({second:new a.CronSecond(T,{rawValue:w.second}),minute:new a.CronMinute(M,{rawValue:w.minute}),hour:new a.CronHour(j,{rawValue:w.hour}),dayOfMonth:new a.CronDayOfMonth(E,{rawValue:w.dayOfMonth}),month:new a.CronMonth(I,{rawValue:w.month}),dayOfWeek:new a.CronDayOfWeek(_,{rawValue:w.dayOfWeek,nthDayOfWeek:H})});return new i.CronExpression(Y,{...S,expression:x})}static#e(x,S){if(S&&!x.length)throw new Error("Invalid cron expression");x=x||"0 * * * * *";const b=x.trim().split(/\s+/);if(S&&b.length<6)throw new Error("Invalid cron expression, expected 6 fields");if(b.length>6)throw new Error("Invalid cron expression, too many fields");const g=["*","*","*","*","*","0"];b.length<g.length&&b.unshift(...g.slice(b.length));const[k,w,T,M,j,I]=b;return{second:k,minute:w,hour:T,dayOfMonth:M,month:j,dayOfWeek:I}}static#n(x,S,b,g){if((x===c.Month||x===c.DayOfWeek)&&(S=S.replace(/[a-z]{3}/gi,k=>{k=k.toLowerCase();const w=l[k]||f[k];if(w===void 0)throw new Error(`Validation error, cannot resolve alias "${k}"`);return w.toString()})),!b.validChars.test(S))throw new Error(`Invalid characters, got value: ${S}`);return S=this.#a(S,b),S=this.#s(S,b,g),this.#r(x,S,b)}static#a(x,S){return x.replace(/[*?]/g,S.min+"-"+S.max)}static#s(x,S,b){const g=b();return x.replace(/H(?:\((\d+)-(\d+)\))?(?:\/(\d+))?/g,(k,w,T,M)=>{if(w&&T&&M){const j=parseInt(w,10),I=parseInt(T,10),E=parseInt(M,10);if(j>I)throw new Error(`Invalid range: ${j}-${I}, min > max`);if(E<=0)throw new Error(`Invalid step: ${E}, must be positive`);const L=Math.max(j,S.min),H=Math.floor(g*E),_=[];for(let Y=Math.floor(L/E)*E+H;Y<=I;Y+=E)Y>=L&&_.push(Y);return _.join(",")}else if(w&&T){const j=parseInt(w,10),I=parseInt(T,10);if(j>I)throw new Error(`Invalid range: ${j}-${I}, min > max`);return String(Math.floor(g*(I-j+1))+j)}else if(M){const j=parseInt(M,10);if(j<=0)throw new Error(`Invalid step: ${j}, must be positive`);const I=Math.floor(g*j),E=[];for(let L=Math.floor(S.min/j)*j+I;L<=S.max;L+=j)L>=S.min&&E.push(L);return E.join(",")}else return String(Math.floor(g*(S.max-S.min+1)+S.min))})}static#r(x,S,b){const g=[];function k(T,M){if(Array.isArray(T))g.push(...T);else if(Fe.#h(M,T))g.push(T);else{const j=parseInt(T.toString(),10);if(!(j>=M.min&&j<=M.max))throw new Error(`Constraint error, got value ${T} expected range ${M.min}-${M.max}`);g.push(x===c.DayOfWeek?j%7:T)}}return S.split(",").forEach(T=>{if(!(T.length>0))throw new Error("Invalid list value format");k(Fe.#t(x,T,b),b)}),g}static#t(x,S,b){const g=S.split("/");if(g.length>2)throw new Error(`Invalid repeat: ${S}`);return g.length===2?(g[0].includes("-")||(g[0]=`${g[0]}-${b.max}`),Fe.#o(x,g[0],parseInt(g[1],10),b)):Fe.#o(x,S,1,b)}static#c(x,S,b){if(!(!isNaN(x)&&!isNaN(S)&&x>=b.min&&S<=b.max))throw new Error(`Constraint error, got range ${x}-${S} expected range ${b.min}-${b.max}`);if(x>S)throw new Error(`Invalid range: ${x}-${S}, min(${x}) > max(${S})`)}static#l(x){if(!(!isNaN(x)&&x>0))throw new Error(`Constraint error, cannot repeat at every ${x} time.`)}static#i(x,S,b,g){const k=[];x===c.DayOfWeek&&b%7===0&&k.push(0);for(let w=S;w<=b;w+=g)k.indexOf(w)===-1&&k.push(w);return k}static#o(x,S,b,g){const k=S.split("-");if(k.length<=1)return isNaN(+S)?S:+S;const[w,T]=k.map(M=>parseInt(M,10));return this.#c(w,T,g),this.#l(b),this.#i(x,w,T,b)}static#d(x){const S=x.split("#");if(S.length<=1)return{dayOfWeek:S[0]};const b=+S[S.length-1],g=x.match(/([,-/])/);if(g!==null)throw new Error(`Constraint error, invalid dayOfWeek \`#\` and \`${g?.[0]}\` special characters are incompatible`);if(!(S.length<=2&&!isNaN(b)&&b>=1&&b<=5))throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return{dayOfWeek:S[0],nthDayOfWeek:b}}static#h(x,S){return x.chars.some(b=>S.toString().includes(b))}};return Ie.CronExpressionParser=d,Ie}var We={};const ec={},tc=Object.freeze(Object.defineProperty({__proto__:null,default:ec},Symbol.toStringTag,{value:"Module"})),sa=u.getAugmentedNamespace(tc);var aa;function nc(){if(aa)return We;aa=1;var t=We&&We.__createBinding||(Object.create?(function(c,l,f,d){d===void 0&&(d=f);var m=Object.getOwnPropertyDescriptor(l,f);(!m||("get"in m?!l.__esModule:m.writable||m.configurable))&&(m={enumerable:!0,get:function(){return l[f]}}),Object.defineProperty(c,d,m)}):(function(c,l,f,d){d===void 0&&(d=f),c[d]=l[f]})),i=We&&We.__setModuleDefault||(Object.create?(function(c,l){Object.defineProperty(c,"default",{enumerable:!0,value:l})}):function(c,l){c.default=l}),h=We&&We.__importStar||(function(){var c=function(l){return c=Object.getOwnPropertyNames||function(f){var d=[];for(var m in f)Object.prototype.hasOwnProperty.call(f,m)&&(d[d.length]=m);return d},c(l)};return function(l){if(l&&l.__esModule)return l;var f={};if(l!=null)for(var d=c(l),m=0;m<d.length;m++)d[m]!=="default"&&t(f,l,d[m]);return i(f,l),f}})();Object.defineProperty(We,"__esModule",{value:!0}),We.CronFileParser=void 0;const a=lr();let p=class Sn{static async parseFile(l){const{readFile:f}=await Promise.resolve().then(()=>h(sa)),d=await f(l,"utf8");return Sn.#e(d)}static parseFileSync(l){const{readFileSync:f}=sa,d=f(l,"utf8");return Sn.#e(d)}static#e(l){const f=l.split(`
|