@malloy-publisher/sdk 0.12.2 → 0.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Gu=Object.create;var Ci=Object.defineProperty;var Yu=Object.getOwnPropertyDescriptor;var Ku=Object.getOwnPropertyNames;var Qu=Object.getPrototypeOf,Zu=Object.prototype.hasOwnProperty;var Xu=(e,n,r,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Ku(n))!Zu.call(e,i)&&i!==r&&Ci(e,i,{get:()=>n[i],enumerable:!(s=Yu(n,i))||s.enumerable});return e};var ji=(e,n,r)=>(r=e!=null?Gu(Qu(e)):{},Xu(n||!e||!e.__esModule?Ci(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),m=require("@mui/material"),j=require("react"),c=require("./useCompiledDocument-D88_2cGS.cjs.js"),q=require("./ServerProvider-BRQl_cBo.cjs.js"),yt=require("@tanstack/react-query"),Sr=require("@mui/system"),_t=require("@mui/icons-material"),Ju=require("@malloydata/malloy-tag"),io=require("./text-entry-BJwltZiy.cjs.js"),fn=require("./RenderedResult-Cgw4iqev.cjs.js"),ed=require("@malloydata/malloy-filter"),Yr=require("react-router-dom");function td(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return n.default=e,Object.freeze(n)}const we=td(j),nd=c.createSvgIcon(t.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function rd({label:e,href:n,onClick:r}){const s=i=>{const l=i.metaKey||i.ctrlKey||i.shiftKey||i.altKey||i.button!==0;n!==void 0&&l||(i.preventDefault(),r(i))};return t.jsxs(m.Link,{...n===void 0?{component:"button",type:"button"}:{href:n},onClick:s,underline:"none","aria-label":`Back to ${e}`,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:[t.jsx(nd,{sx:{fontSize:18}}),"Back to ",e]})}const Aa="(max-width:599.95px)";function La(){return m.useMediaQuery(Aa,{noSsr:!0})}function Na(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Aa).matches}function sd({children:e}){const[n]=j.useState(Na),[r,s]=j.useState(!1);return!n||r?t.jsx(t.Fragment,{children:e}):t.jsxs(m.Stack,{sx:{alignItems:"flex-start",gap:1.5,py:3},children:[t.jsx(m.Typography,{variant:"h6",children:"Editing works best on a larger screen"}),t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"The editor is built for a wider window. You can still try it here."}),t.jsx(m.Button,{variant:"outlined",onClick:()=>s(!0),children:"Edit anyway"})]})}function od(){const e=Yr.useNavigate();return(n,r)=>{if(!r||!r.metaKey&&!r.ctrlKey&&!r.shiftKey&&r.button!==1){e(n);return}const s=new URL(n,window.location.href).href;(r.metaKey||r.ctrlKey||r.button===1||r.shiftKey)&&window.open(s,"_blank")}}function Pa(e,n){return e.flatMap(({filter:r})=>{if(r.kind!=="literal_equality"||r.expression.kind!=="field_reference")return[];const s=id(r.value,n);return s===void 0?[]:[{field:r.expression.name,label:s,expression:r.expression}]})}function _a(e,n){switch(e.kind){case"string_literal":return`'${c.escapeMalloyString(e.string_value)}'`;case"number_literal":return e.string_value!==void 0?/^-?\d+(\.\d+)?$/.test(e.string_value)?e.string_value:void 0:Number.isFinite(e.number_value)?String(e.number_value):void 0;case"boolean_literal":return String(e.boolean_value);case"date_literal":{const r=za(e.date_value);return r&&`@${r[0]}-${r[1]}-${r[2]}`}case"timestamp_literal":{const r=qa(e.timestamp_value,n);return r&&`@${r[0]}-${r[1]}-${r[2]} ${r[3]}:${r[4]}:${r[5]}${Wa(e.timestamp_value)}`}default:return}}function id(e,n){switch(e.kind){case"string_literal":return e.string_value;case"null_literal":return"null";case"date_literal":{const r=za(e.date_value);return r&&Ti([...r,"00","00","00"],e.granularity??"day")}case"timestamp_literal":{const r=qa(e.timestamp_value,n);return r&&Ti(r,e.granularity??"second")+(e.granularity===void 0?Wa(e.timestamp_value):"")}default:return _a(e)}}function za(e){const n=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);return n?[n[1],n[2],n[3]]:void 0}function Wa(e){const n=/:\d{2}\.(\d+)/.exec(e)?.[1]?.replace(/0+$/,"");return n?`.${n}`:""}function qa(e,n){const r=new Date(e);if(Number.isNaN(r.getTime()))return;let s;try{s=new Intl.DateTimeFormat("en-US",{timeZone:n??"UTC",hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(r)}catch{return}const i=l=>s.find(a=>a.type===l)?.value??"";return[i("year").padStart(4,"0"),i("month"),i("day"),i("hour"),i("minute"),i("second")]}function Ti([e,n,r,s,i,l],a){switch(a){case"year":return e;case"quarter":return`${e}-Q${Math.floor((Number(n)-1)/3)+1}`;case"month":return`${e}-${n}`;case"week":case"day":return`${e}-${n}-${r}`;case"hour":return`${e}-${n}-${r} ${s}`;case"minute":return`${e}-${n}-${r} ${s}:${i}`;default:return`${e}-${n}-${r} ${s}:${i}:${l}`}}const ad="drill_metadata_corrected",Xr=e=>e,An=e=>{try{return e?.()}catch{return}},Ba=e=>An(e.isBasic?.bind(e))===!0&&An(e.wasDimension?.bind(e))===!0,ld=e=>[e.isString,e.isNumber,e.isBoolean,e.isTime].some(n=>An(n?.bind(e))===!0);function Jr(e){const n=e.metadataTag?.text("drill_expression","code");return n===void 0||n.trim()===""?void 0:n}function Va(e){const n=[];for(let r=e.parent;r;r=r.parent)n.push(r);return n}function Ha(e){const n=Va(e),s=(n[n.length-1]??e).metadataTag,i=s?.text("source","name");if(!i||!s?.array||s.array("source","parameters")!==void 0||s.has?.(ad)!==!0)return;const l=[];for(const d of[...n].reverse())if(An(d.isArray?.bind(d))===!0){if(d.metadataTag?.has?.("drillable")!==!0)return;for(const u of d.metadataTag?.array?.("drill_filters")??[]){const h=u.text("code");if(!h)return;l.push(h)}}const a=s?.text("query_name");return{source:i,filters:l,...a&&!a.startsWith("__")?{queryName:a}:{}}}function Er(e){const n=new Set;for(const r of Va(e))for(const s of r.fields??[])Ba(s)&&n.add(s);return[...n]}function Ua(e){const n=new Set(Er(e).filter(r=>An(r.isTime?.bind(r))===!0).map(r=>An(r.getEffectiveQueryTimezone?.bind(r))));return n.size>1?null:[...n][0]}function Mi(e){return!Ba(e)||Jr(e)===void 0||Ha(e)===void 0||Ua(e)===null?!1:Er(e).every(n=>Jr(n)!==void 0&&n.drillStableExpression!==void 0&&ld(n))}function cd(e,n){const r=Er(e),s=[],i=new Set;for(const l of n){if(l.kind==="drill")continue;const{filter:a}=l;if(a.kind!=="literal_equality")return;const d=JSON.stringify(a.expression),u=r.find(g=>JSON.stringify(g.drillStableExpression)===d),h=u&&Jr(u);if(u===void 0||h===void 0)return;s.push({code:h,value:a.value}),i.add(u)}return r.every(l=>i.has(l))&&s.length>0?s:void 0}const ud=360;function Gs(e){return e?e.getLabel?.()??e.tag?.text("label")??Xr(e).metadataTag?.text("label")??e.name:""}function dd(e,n){const r=e.drillClauses?Pa(e.drillClauses,e.timezone):[];if(r.length===0)return`${Gs(n)}: ${e.label}`;const s=Er(Xr(n));return r.map(i=>{const l=JSON.stringify(i.expression),a=s.find(d=>JSON.stringify(d.drillStableExpression)===l);return`${a?Gs(a):i.field}: ${i.label}`}).join(", ")}function ao({onNavigate:e,onSelf:n,destinationTitle:r,canSelf:s,onRows:i}){const[l,a]=j.useState(null),d=j.useCallback((S,T)=>S.filter(M=>M===c.DRILL_SELF?n!==void 0&&(s?.(T)??!0):e!==void 0),[e,n,s]),u=j.useCallback((S,T,M)=>{if(T===c.DRILL_SELF){n?.(S.given,S.rawValue);return}e?.({path:T,dashboard:T,givens:{[S.given]:S.value}},M)},[e,n]),h=j.useCallback(S=>{if(!i||S.noRows||S.isHeader||!S.field)return;const T=Xr(S.field);if(!Mi(T))return;const M=Ha(T);if(M===void 0)return;const O=S.drillClauses;let I;if(O!==void 0){const _=cd(T,O);if(_===void 0)return;I={dimensions:_}}else{const _=Jr(T);if(_===void 0||Er(T).length!==1||c.drillValueToFilter(S.value)===void 0||typeof S.value=="number"&&Number.isInteger(S.value)&&!Number.isSafeInteger(S.value))return;I={code:_}}const R=Ua(T)??void 0;return{field:S.field.name,rawValue:S.value,label:c.drillValueLabel(S.value),target:M,...I,...S.context===void 0?{}:{context:S.context},...O===void 0?{}:{drillClauses:O},...R===void 0?{}:{timezone:R}}},[i]),g=j.useCallback(S=>{const T=c.resolveDrill(S),M=h(S),O=T?Array.from(new Set(d(T.to,T.given))).sort((_,$)=>+($===c.DRILL_SELF)-+(_===c.DRILL_SELF)):[],I=`${Gs(S.field)}: ${T?.label??c.drillValueLabel(S.value)}`,R=O.map(_=>({key:`to:${_}`,label:_===c.DRILL_SELF?`Filter to ${I}`:`Open ${r?.(_)??c.humanizeSlug(_.split("/").pop()??_)} (${I})`,run:()=>{T&&u(T,_,S.event)}}));M&&S.field&&R.push({key:"rows",label:`Show rows (${dd(M,S.field)})`,run:()=>i?.(M)}),R.length!==0&&a({items:R,top:S.event?.clientY??0,left:S.event?.clientX??0})},[u,d,i,h,r]),b=j.useCallback(S=>d(c.drillDestinations(S),c.drillGivenName(S)).length>0,[d]),x=j.useCallback(S=>i!==void 0&&Mi(Xr(S)),[i]),v=j.useMemo(()=>({onClick:g,canDrill:S=>b(S)||x(S)}),[g,b,x]),C=j.useCallback((S,T)=>({canDrill:M=>b(M)||T&&x(M),onClick:M=>g({...M,...S===void 0?{}:{context:S},...T?{}:{noRows:!0}})}),[g,b,x]),k=j.useCallback(()=>a(null),[]);return{drill:v,bindingFor:C,drillMenu:t.jsx(m.Menu,{open:l!==null,onClose:k,anchorReference:"anchorPosition",anchorPosition:{top:l?.top??0,left:l?.left??0},children:(l?.items??[]).map(S=>t.jsx(m.MenuItem,{title:S.label,"aria-label":S.label,onClick:()=>{k(),S.run()},sx:{maxWidth:ud},children:t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.label})},S.key))})}}const hd=e=>{const n=we.useRef({});return we.useEffect(()=>{n.current=e}),n.current};function fd(){const[e]=Yr.useSearchParams(),n=Yr.useNavigate(),r=Yr.useLocation(),s=j.useMemo(()=>Object.fromEntries(e.entries()),[e]),i=j.useRef(new Set),l=j.useRef(null),a=j.useCallback(h=>{const g=l.current,b=new URLSearchParams(g?.key===r.key?g.search:r.search);h(b);const x=b.toString();l.current={key:r.key,search:x},n({search:x,hash:r.hash},{replace:!0})},[n,r]),d=j.useCallback((h,g)=>{const b=new Set([...g,...i.current]);i.current=new Set([...i.current,...Object.keys(h),...g]),a(x=>{for(const v of b)Object.prototype.hasOwnProperty.call(h,v)||x.delete(v);for(const[v,C]of Object.entries(h))x.set(v,C)})},[a]),u=j.useCallback((h,g)=>a(b=>{g===void 0?b.delete(h):b.set(h,g)}),[a]);return{params:s,onGivensChange:d,setParam:u}}const pd=c.createSvgIcon(t.jsx("path",{d:"M5 20h14v-2H5zM19 9h-4V3H9v6H5l7 7z"}));function fr(e){return/^[=+\-@\t\r]/.test(e)?`'${e}`:e}function pr(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function md(e){if(e===void 0)return"";switch(e.kind){case"null_cell":return"";case"number_cell":return e.string_value??String(e.number_value);case"boolean_cell":return e.boolean_value?"true":"false";case"date_cell":return e.date_value;case"timestamp_cell":return e.timestamp_value;case"string_cell":return pr(fr(e.string_value));case"json_cell":return pr(fr(e.json_value));case"sql_native_cell":return pr(fr(e.sql_native_value));default:return pr(fr(JSON.stringify(e)))}}function Ga(e){const n=e.data;return n?.kind!=="array_cell"?[]:n.array_value.flatMap(r=>r.kind==="record_cell"?[r.record_value]:[])}function gd(e){const n=e.schema.fields;return`\uFEFF${[n.map(s=>pr(fr(s.name))).join(","),...Ga(e).map(s=>n.map((i,l)=>md(s[l])).join(","))].join(`\r
1
+ "use strict";var Gu=Object.create;var Ci=Object.defineProperty;var Yu=Object.getOwnPropertyDescriptor;var Ku=Object.getOwnPropertyNames;var Qu=Object.getPrototypeOf,Zu=Object.prototype.hasOwnProperty;var Xu=(e,n,r,s)=>{if(n&&typeof n=="object"||typeof n=="function")for(let i of Ku(n))!Zu.call(e,i)&&i!==r&&Ci(e,i,{get:()=>n[i],enumerable:!(s=Yu(n,i))||s.enumerable});return e};var ji=(e,n,r)=>(r=e!=null?Gu(Qu(e)):{},Xu(n||!e||!e.__esModule?Ci(r,"default",{value:e,enumerable:!0}):r,e));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("react/jsx-runtime"),m=require("@mui/material"),j=require("react"),c=require("./useCompiledDocument--Z7vKZL5.cjs.js"),q=require("./ServerProvider-CqL6xzta.cjs.js"),yt=require("@tanstack/react-query"),Sr=require("@mui/system"),_t=require("@mui/icons-material"),Ju=require("@malloydata/malloy-tag"),io=require("./text-entry-BJwltZiy.cjs.js"),fn=require("./RenderedResult-C2arX5Zz.cjs.js"),ed=require("@malloydata/malloy-filter"),Yr=require("react-router-dom");function td(e){const n=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e){for(const r in e)if(r!=="default"){const s=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(n,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}return n.default=e,Object.freeze(n)}const we=td(j),nd=c.createSvgIcon(t.jsx("path",{d:"M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"}));function rd({label:e,href:n,onClick:r}){const s=i=>{const l=i.metaKey||i.ctrlKey||i.shiftKey||i.altKey||i.button!==0;n!==void 0&&l||(i.preventDefault(),r(i))};return t.jsxs(m.Link,{...n===void 0?{component:"button",type:"button"}:{href:n},onClick:s,underline:"none","aria-label":`Back to ${e}`,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:[t.jsx(nd,{sx:{fontSize:18}}),"Back to ",e]})}const Aa="(max-width:599.95px)";function La(){return m.useMediaQuery(Aa,{noSsr:!0})}function Na(){return typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia(Aa).matches}function sd({children:e}){const[n]=j.useState(Na),[r,s]=j.useState(!1);return!n||r?t.jsx(t.Fragment,{children:e}):t.jsxs(m.Stack,{sx:{alignItems:"flex-start",gap:1.5,py:3},children:[t.jsx(m.Typography,{variant:"h6",children:"Editing works best on a larger screen"}),t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"The editor is built for a wider window. You can still try it here."}),t.jsx(m.Button,{variant:"outlined",onClick:()=>s(!0),children:"Edit anyway"})]})}function od(){const e=Yr.useNavigate();return(n,r)=>{if(!r||!r.metaKey&&!r.ctrlKey&&!r.shiftKey&&r.button!==1){e(n);return}const s=new URL(n,window.location.href).href;(r.metaKey||r.ctrlKey||r.button===1||r.shiftKey)&&window.open(s,"_blank")}}function Pa(e,n){return e.flatMap(({filter:r})=>{if(r.kind!=="literal_equality"||r.expression.kind!=="field_reference")return[];const s=id(r.value,n);return s===void 0?[]:[{field:r.expression.name,label:s,expression:r.expression}]})}function _a(e,n){switch(e.kind){case"string_literal":return`'${c.escapeMalloyString(e.string_value)}'`;case"number_literal":return e.string_value!==void 0?/^-?\d+(\.\d+)?$/.test(e.string_value)?e.string_value:void 0:Number.isFinite(e.number_value)?String(e.number_value):void 0;case"boolean_literal":return String(e.boolean_value);case"date_literal":{const r=za(e.date_value);return r&&`@${r[0]}-${r[1]}-${r[2]}`}case"timestamp_literal":{const r=qa(e.timestamp_value,n);return r&&`@${r[0]}-${r[1]}-${r[2]} ${r[3]}:${r[4]}:${r[5]}${Wa(e.timestamp_value)}`}default:return}}function id(e,n){switch(e.kind){case"string_literal":return e.string_value;case"null_literal":return"null";case"date_literal":{const r=za(e.date_value);return r&&Ti([...r,"00","00","00"],e.granularity??"day")}case"timestamp_literal":{const r=qa(e.timestamp_value,n);return r&&Ti(r,e.granularity??"second")+(e.granularity===void 0?Wa(e.timestamp_value):"")}default:return _a(e)}}function za(e){const n=/^(\d{4})-(\d{2})-(\d{2})/.exec(e);return n?[n[1],n[2],n[3]]:void 0}function Wa(e){const n=/:\d{2}\.(\d+)/.exec(e)?.[1]?.replace(/0+$/,"");return n?`.${n}`:""}function qa(e,n){const r=new Date(e);if(Number.isNaN(r.getTime()))return;let s;try{s=new Intl.DateTimeFormat("en-US",{timeZone:n??"UTC",hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}).formatToParts(r)}catch{return}const i=l=>s.find(a=>a.type===l)?.value??"";return[i("year").padStart(4,"0"),i("month"),i("day"),i("hour"),i("minute"),i("second")]}function Ti([e,n,r,s,i,l],a){switch(a){case"year":return e;case"quarter":return`${e}-Q${Math.floor((Number(n)-1)/3)+1}`;case"month":return`${e}-${n}`;case"week":case"day":return`${e}-${n}-${r}`;case"hour":return`${e}-${n}-${r} ${s}`;case"minute":return`${e}-${n}-${r} ${s}:${i}`;default:return`${e}-${n}-${r} ${s}:${i}:${l}`}}const ad="drill_metadata_corrected",Xr=e=>e,An=e=>{try{return e?.()}catch{return}},Ba=e=>An(e.isBasic?.bind(e))===!0&&An(e.wasDimension?.bind(e))===!0,ld=e=>[e.isString,e.isNumber,e.isBoolean,e.isTime].some(n=>An(n?.bind(e))===!0);function Jr(e){const n=e.metadataTag?.text("drill_expression","code");return n===void 0||n.trim()===""?void 0:n}function Va(e){const n=[];for(let r=e.parent;r;r=r.parent)n.push(r);return n}function Ha(e){const n=Va(e),s=(n[n.length-1]??e).metadataTag,i=s?.text("source","name");if(!i||!s?.array||s.array("source","parameters")!==void 0||s.has?.(ad)!==!0)return;const l=[];for(const d of[...n].reverse())if(An(d.isArray?.bind(d))===!0){if(d.metadataTag?.has?.("drillable")!==!0)return;for(const u of d.metadataTag?.array?.("drill_filters")??[]){const h=u.text("code");if(!h)return;l.push(h)}}const a=s?.text("query_name");return{source:i,filters:l,...a&&!a.startsWith("__")?{queryName:a}:{}}}function Er(e){const n=new Set;for(const r of Va(e))for(const s of r.fields??[])Ba(s)&&n.add(s);return[...n]}function Ua(e){const n=new Set(Er(e).filter(r=>An(r.isTime?.bind(r))===!0).map(r=>An(r.getEffectiveQueryTimezone?.bind(r))));return n.size>1?null:[...n][0]}function Mi(e){return!Ba(e)||Jr(e)===void 0||Ha(e)===void 0||Ua(e)===null?!1:Er(e).every(n=>Jr(n)!==void 0&&n.drillStableExpression!==void 0&&ld(n))}function cd(e,n){const r=Er(e),s=[],i=new Set;for(const l of n){if(l.kind==="drill")continue;const{filter:a}=l;if(a.kind!=="literal_equality")return;const d=JSON.stringify(a.expression),u=r.find(g=>JSON.stringify(g.drillStableExpression)===d),h=u&&Jr(u);if(u===void 0||h===void 0)return;s.push({code:h,value:a.value}),i.add(u)}return r.every(l=>i.has(l))&&s.length>0?s:void 0}const ud=360;function Gs(e){return e?e.getLabel?.()??e.tag?.text("label")??Xr(e).metadataTag?.text("label")??e.name:""}function dd(e,n){const r=e.drillClauses?Pa(e.drillClauses,e.timezone):[];if(r.length===0)return`${Gs(n)}: ${e.label}`;const s=Er(Xr(n));return r.map(i=>{const l=JSON.stringify(i.expression),a=s.find(d=>JSON.stringify(d.drillStableExpression)===l);return`${a?Gs(a):i.field}: ${i.label}`}).join(", ")}function ao({onNavigate:e,onSelf:n,destinationTitle:r,canSelf:s,onRows:i}){const[l,a]=j.useState(null),d=j.useCallback((S,T)=>S.filter(M=>M===c.DRILL_SELF?n!==void 0&&(s?.(T)??!0):e!==void 0),[e,n,s]),u=j.useCallback((S,T,M)=>{if(T===c.DRILL_SELF){n?.(S.given,S.rawValue);return}e?.({path:T,dashboard:T,givens:{[S.given]:S.value}},M)},[e,n]),h=j.useCallback(S=>{if(!i||S.noRows||S.isHeader||!S.field)return;const T=Xr(S.field);if(!Mi(T))return;const M=Ha(T);if(M===void 0)return;const O=S.drillClauses;let I;if(O!==void 0){const _=cd(T,O);if(_===void 0)return;I={dimensions:_}}else{const _=Jr(T);if(_===void 0||Er(T).length!==1||c.drillValueToFilter(S.value)===void 0||typeof S.value=="number"&&Number.isInteger(S.value)&&!Number.isSafeInteger(S.value))return;I={code:_}}const R=Ua(T)??void 0;return{field:S.field.name,rawValue:S.value,label:c.drillValueLabel(S.value),target:M,...I,...S.context===void 0?{}:{context:S.context},...O===void 0?{}:{drillClauses:O},...R===void 0?{}:{timezone:R}}},[i]),g=j.useCallback(S=>{const T=c.resolveDrill(S),M=h(S),O=T?Array.from(new Set(d(T.to,T.given))).sort((_,$)=>+($===c.DRILL_SELF)-+(_===c.DRILL_SELF)):[],I=`${Gs(S.field)}: ${T?.label??c.drillValueLabel(S.value)}`,R=O.map(_=>({key:`to:${_}`,label:_===c.DRILL_SELF?`Filter to ${I}`:`Open ${r?.(_)??c.humanizeSlug(_.split("/").pop()??_)} (${I})`,run:()=>{T&&u(T,_,S.event)}}));M&&S.field&&R.push({key:"rows",label:`Show rows (${dd(M,S.field)})`,run:()=>i?.(M)}),R.length!==0&&a({items:R,top:S.event?.clientY??0,left:S.event?.clientX??0})},[u,d,i,h,r]),b=j.useCallback(S=>d(c.drillDestinations(S),c.drillGivenName(S)).length>0,[d]),x=j.useCallback(S=>i!==void 0&&Mi(Xr(S)),[i]),v=j.useMemo(()=>({onClick:g,canDrill:S=>b(S)||x(S)}),[g,b,x]),C=j.useCallback((S,T)=>({canDrill:M=>b(M)||T&&x(M),onClick:M=>g({...M,...S===void 0?{}:{context:S},...T?{}:{noRows:!0}})}),[g,b,x]),k=j.useCallback(()=>a(null),[]);return{drill:v,bindingFor:C,drillMenu:t.jsx(m.Menu,{open:l!==null,onClose:k,anchorReference:"anchorPosition",anchorPosition:{top:l?.top??0,left:l?.left??0},children:(l?.items??[]).map(S=>t.jsx(m.MenuItem,{title:S.label,"aria-label":S.label,onClick:()=>{k(),S.run()},sx:{maxWidth:ud},children:t.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S.label})},S.key))})}}const hd=e=>{const n=we.useRef({});return we.useEffect(()=>{n.current=e}),n.current};function fd(){const[e]=Yr.useSearchParams(),n=Yr.useNavigate(),r=Yr.useLocation(),s=j.useMemo(()=>Object.fromEntries(e.entries()),[e]),i=j.useRef(new Set),l=j.useRef(null),a=j.useCallback(h=>{const g=l.current,b=new URLSearchParams(g?.key===r.key?g.search:r.search);h(b);const x=b.toString();l.current={key:r.key,search:x},n({search:x,hash:r.hash},{replace:!0})},[n,r]),d=j.useCallback((h,g)=>{const b=new Set([...g,...i.current]);i.current=new Set([...i.current,...Object.keys(h),...g]),a(x=>{for(const v of b)Object.prototype.hasOwnProperty.call(h,v)||x.delete(v);for(const[v,C]of Object.entries(h))x.set(v,C)})},[a]),u=j.useCallback((h,g)=>a(b=>{g===void 0?b.delete(h):b.set(h,g)}),[a]);return{params:s,onGivensChange:d,setParam:u}}const pd=c.createSvgIcon(t.jsx("path",{d:"M5 20h14v-2H5zM19 9h-4V3H9v6H5l7 7z"}));function fr(e){return/^[=+\-@\t\r]/.test(e)?`'${e}`:e}function pr(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function md(e){if(e===void 0)return"";switch(e.kind){case"null_cell":return"";case"number_cell":return e.string_value??String(e.number_value);case"boolean_cell":return e.boolean_value?"true":"false";case"date_cell":return e.date_value;case"timestamp_cell":return e.timestamp_value;case"string_cell":return pr(fr(e.string_value));case"json_cell":return pr(fr(e.json_value));case"sql_native_cell":return pr(fr(e.sql_native_value));default:return pr(fr(JSON.stringify(e)))}}function Ga(e){const n=e.data;return n?.kind!=="array_cell"?[]:n.array_value.flatMap(r=>r.kind==="record_cell"?[r.record_value]:[])}function gd(e){const n=e.schema.fields;return`\uFEFF${[n.map(s=>pr(fr(s.name))).join(","),...Ga(e).map(s=>n.map((i,l)=>md(s[l])).join(","))].join(`\r
2
2
  `)}\r
3
3
  `}function yd(e,n){return[e,"rows",...n].join("_").replace(/[^A-Za-z0-9._-]+/g,"_").replace(/_+/g,"_").replace(/^[_.]+|[_.]+$/g,"").slice(0,120)||"rows"}function xd(e,n,r){return r==="server_default"&&n!==void 0&&e>=n?n:void 0}const Oi="Download the rows behind this value as CSV, up to the server's row limit",vd=4e4;function bd(e,n){const r=URL.createObjectURL(new Blob([e],{type:"text/csv;charset=utf-8"})),s=document.createElement("a");s.href=r,s.download=n,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),vd)}function wd(e){const r=e?.response?.data?.message;return typeof r=="string"&&r!==""?r:e instanceof Error&&e.message!==""?e.message:"The request failed."}function Ya({query:e,preamble:n,environmentName:r,packageName:s,modelPath:i,versionId:l,givens:a,fileName:d}){const{apiClients:u}=q.useServer(),[h,g]=j.useState(!1),[b,x]=j.useState(Oi),[v,C]=j.useState(void 0),k=j.useRef(void 0);j.useEffect(()=>()=>k.current?.abort(),[]);const S=async()=>{k.current?.abort();const T=new AbortController;k.current=T,g(!0),C(void 0);try{const M=await u.models.executeQueryModel(r,s,i,{query:n===void 0?e:c.withPreamble(n,e),givens:a,versionId:l},void 0,{signal:T.signal});if(T.signal.aborted)return;const O=M.data,I=JSON.parse(O.result??"{}"),R=xd(Ga(I).length,O.queryRowLimit,O.queryRowLimitSource);x(R===void 0?Oi:`First ${R} rows: the server's row limit, so there may be more`),bd(gd(I),R===void 0?`${d}.csv`:`${d}_first_${R}_rows_server_limit.csv`)}catch(M){if(T.signal.aborted)return;C(`Download failed: ${wd(M)}`)}finally{k.current===T&&(k.current=void 0,g(!1))}};return t.jsxs(m.Box,{sx:{display:"flex",alignItems:"center",gap:1},children:[v&&t.jsx(m.Typography,{role:"alert",variant:"caption",color:"error",sx:{maxWidth:320},children:v}),t.jsx(m.Tooltip,{title:b,children:t.jsx("span",{children:t.jsx(m.Button,{size:"small",startIcon:t.jsx(pd,{fontSize:"small"}),onClick:()=>void S(),disabled:h,children:"Download CSV"})})})]})}const Ka=200;function Sd(e){const{target:n}=e;if(n!==void 0&&!(e.dimensions===void 0&&e.code===void 0))return{...e,target:n}}function Ii(e,n=Ka){const r=Cd(e);if(r===void 0)return;const s=[...e.target.filters,...r].join(", "),i=e.timezone?`timezone: '${c.escapeMalloyString(e.timezone)}'; `:"",l=n===null?"":`; limit: ${n}`,a=kd(e.target.source);if(a!==void 0)return`run: ${a} -> { ${i}where: ${s}; select: *${l} }`}function kd(e){return io.isBareName(e)?e:e.includes("`")?void 0:`\`${e}\``}function js(e){return/^[A-Za-z_][A-Za-z0-9_]*(\.[A-Za-z_][A-Za-z0-9_]*)*$/.test(e)?e:`(${e})`}function Cd(e){if(e.dimensions){const r=[];for(const{code:s,value:i}of e.dimensions){if(i.kind==="null_literal"){r.push(`${js(s)} is null`);continue}const l=_a(i,e.timezone);if(l===void 0)return;r.push(`${js(s)} = ${l}`)}return r}const n=c.malloyLiteral(e.rawValue);return e.code!==void 0&&n?[`${js(e.code)} = ${n}`]:void 0}const jd="This value cannot be written as a filter, so its rows cannot be fetched.";function Ei(e){const n=e.drillClauses?Pa(e.drillClauses,e.timezone):[];return n.length>0?n:[{field:e.field,label:e.label}]}function Td({request:e,environmentName:n,packageName:r,versionId:s,modelPath:i,preamble:l,givens:a,onClose:d,onDone:u,actions:h}){const{theme:g}=q.usePublisherTheme(),b=e?Ii(e):void 0,x=e?Ii(e,null):void 0,v=e&&x!==void 0?{query:x,...l===void 0?{}:{preamble:l},environmentName:n,packageName:r,modelPath:i,...s===void 0?{}:{versionId:s},givens:a,fileName:yd(e.target.source,Ei(e).map(C=>C.label))}:void 0;return t.jsxs(m.Dialog,{open:e!==void 0,onClose:d,maxWidth:"lg",fullWidth:!0,children:[t.jsxs(m.DialogTitle,{sx:{display:"flex",alignItems:"flex-start",justifyContent:"space-between",pb:.5},children:[t.jsxs(m.Box,{children:[e?t.jsxs(t.Fragment,{children:["Rows where"," ",Ei(e).map((C,k)=>t.jsxs(j.Fragment,{children:[k>0&&" and ",t.jsx(m.Box,{component:"code",sx:{fontSize:"0.9em"},children:C.field})," ","is ",C.label]},k))]}):"Rows",t.jsx(m.Typography,{component:"div",variant:"caption",sx:{color:g.tileTitle,mt:.25},children:e?`The first ${Ka} rows of ${e.target.source} behind this value, with the tile's own filters and the controls applied.`:""})]}),t.jsxs(m.Box,{sx:{display:"flex",alignItems:"center",gap:1,ml:1},children:[v&&(h?h(v):t.jsx(Ya,{...v})),t.jsx(m.IconButton,{onClick:d,"aria-label":"Close",size:"small",sx:{color:"text.secondary"},children:t.jsx(c.CloseIcon,{fontSize:"small"})})]})]}),t.jsxs(m.DialogContent,{dividers:!0,sx:{p:0,minHeight:240},children:[b===void 0&&e&&t.jsx(m.Typography,{variant:"body2",sx:{p:2},children:jd}),b!==void 0&&t.jsx(Md,{query:l===void 0?b:c.withPreamble(l,b),environmentName:n,packageName:r,...s===void 0?{}:{versionId:s},modelPath:i,givens:a,...u?{onDone:u}:{}})]}),t.jsxs(m.DialogActions,{sx:{px:3,py:1.5},children:[b!==void 0&&t.jsx(m.Typography,{variant:"caption",sx:{mr:"auto",color:g.tileTitle,fontFamily:g.ui.font.mono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:b,children:b}),t.jsx(m.Button,{onClick:d,children:"Close"})]})]})}function Md({query:e,environmentName:n,packageName:r,versionId:s,modelPath:i,givens:l,onDone:a}){const d=c.useQueryResult({environmentName:n,packageName:r,modelPath:i,...s===void 0?{}:{versionId:s},query:e,givens:l}),{isSuccess:u,isError:h}=d,g=j.useRef(void 0);return j.useEffect(()=>{g.current=c.now()},[e]),j.useEffect(()=>{g.current===void 0||!u&&!h||(a?.(u,c.now()-g.current),g.current=void 0)},[u,h,a]),t.jsx(m.Box,{sx:{p:1},children:t.jsx(c.ResultPanel,{state:d,context:e})})}function ss({manifest:e,environmentName:n,packageName:r,versionId:s,documentName:i,givens:l,onGivensChange:a,onNavigate:d,height:u,maxResultSize:h,controlsLayout:g="bar",preamble:b,runModelPath:x,hiddenGivens:v,literalReads:C,onLinkNavigate:k,actions:S,rowsActions:T}){const M=j.useMemo(()=>k?{environmentName:n,packageName:r,sourcePath:e.path??i,onNavigate:k}:void 0,[n,r,e.path,i,k]),O=j.useMemo(()=>(e.givens??[]).filter(ae=>!(b!==void 0&&ae.secure===!0)&&!(ae.name!==void 0&&v?.includes(ae.name))),[e,v,b]),I=j.useMemo(()=>l===void 0?void 0:Object.fromEntries(Object.entries(l).filter(([,ae])=>typeof ae=="string")),[l]),R=c.useDocumentControls({specs:O,loaded:!0,startingValues:e.startingGivens,params:I,onGivensChange:a,documentKey:`${n}/${r}/${s??""}/${i}`,autorun:e.autorun!==!1,environmentName:n,packageName:r,modelPath:x??e.path,versionId:s,documentName:i,...b!==void 0?{preamble:b}:{},...l?{hostGivens:l}:{}}),{applied:_,declaredTypes:$,canSelf:B,onSelf:F}=R,N=c.useReportEvents(),H=j.useMemo(()=>{const ae=new Set((e.tiles??[]).flatMap(Z=>Z.givenNames??[]));return Object.fromEntries(Object.entries(l??{}).filter(([Z])=>ae.has(Z)&&!$.has(Z)))},[e,l,$]),[D,W]=j.useState(void 0),K=j.useCallback(ae=>{const Z=Sd(ae);Z!==void 0&&W(Z)},[]),J=j.useMemo(()=>c.withHostGivens(c.givensToRequest(_,$),H),[_,$,H]),{reports:X}=c.useReportListing(n,r,s,d!==void 0),G=j.useCallback(ae=>{const Z=c.resolveDrillTarget(ae,X);if(Z.kind!=="path")return;const ce=Z.report.path;return X.find(be=>be.path===ce)?.title||void 0},[X]),{bindingFor:Q,drillMenu:ie}=ao({onNavigate:d,onSelf:F,canSelf:B,onRows:K,destinationTitle:G}),z=j.useCallback((ae,Z)=>Q(ae,Z!==!0),[Q]),{columns:re,layout:se,tileMaxHeight:ne,tableMaxHeight:Me}=c.layoutRules(e.layout,e.dashboardColumns),oe=j.useMemo(()=>c.missingRequiredGivens(O,_,l),[O,_,l]);if(e.error)return t.jsx(c.ReportPage,{layout:se,header:t.jsx(Di,{manifest:e,links:M,actions:S}),children:t.jsx(m.Alert,{severity:"error",children:e.error})});const ue=x??e.path,De=e.tiles??[],Ne=c.isPlaced(De);return t.jsxs(c.ReportPage,{layout:se,header:t.jsx(Di,{manifest:e,links:M,actions:S}),controls:O.length>0?t.jsx(c.StickyControls,{children:t.jsx(c.GivensPanel,{...R.panel,layout:g})}):void 0,children:[oe.length>0&&t.jsx(m.Alert,{severity:"info",children:c.requiredPrompt(oe)}),ue===void 0?t.jsx(m.Alert,{severity:"error",children:"This dashboard has no model path, so there is nothing to run."}):De.length>0?t.jsx(c.DashboardGrid,{tiles:De,columns:re,minTilePx:c.MIN_TILE_PX,rowGapPx:c.GRID_GAP_PX,keyOf:(ae,Z)=>`${Z}:${ae.kind==="text"?`text:${ae.name}`:ae.query}`,renderTile:(ae,Z)=>ae.kind==="text"||ae.query===void 0?t.jsx(m.Box,{sx:ae.rowspan!==void 0||Ne?{minHeight:0,overflow:"auto"}:void 0,children:t.jsx(Od,{markdown:ae.markdown??"",links:M})}):t.jsx(c.DashboardTile,{index:Z,environmentName:n,packageName:r,versionId:s,modelPath:ue,tile:ae.query,label:ae.label,subtitle:ae.subtitle,borderless:ae.borderless,givens:_,hostGivens:H,declaredTypes:$,givenNames:ae.givenNames,height:ae.rowspan!==void 0||Ne?c.tileHeightPx(ae.rowspan??c.PLACED_DEFAULT_ROWSPAN.query):se==="grid"?u??ne:ne,tableMaxHeight:Me,fixedHeight:ae.rowspan!==void 0||Ne,maxResultSize:h,drill:z(ae.query,ae.restricted),ignoredFilters:c.tileIgnoredFilterLabels(ae.givenNames&&(ae.query&&C?.[ae.query]?[...ae.givenNames,...C[ae.query]]:ae.givenNames),O),...b!==void 0?{preamble:b,restricted:ae.restricted}:{},...(()=>{const ce=c.waitingOn(oe,ae.givenNames);return ce.length>0?{waitingFor:c.waitingText(ce)}:{}})()})}):t.jsx(m.Alert,{severity:"warning",children:"This dashboard names neither a query nor any tiles."}),ie,ue!==void 0&&t.jsx(Td,{request:D,environmentName:n,packageName:r,...s===void 0?{}:{versionId:s},modelPath:ue,...b===void 0?{}:{preamble:b},givens:J,...T===void 0?{}:{actions:T},onClose:()=>W(void 0),onDone:(ae,Z)=>{D&&N.emit({type:"report.rows_shown",source:D.target.source,view:D.target.queryName??"",field:D.field,ok:ae,durationMs:Z})}})]})}function Od({markdown:e,links:n}){return t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e})})}function Di({manifest:e,links:n,actions:r}){return t.jsx(c.ReportHeader,{title:e.title??e.name,actions:r,description:e.description?t.jsx(c.TextTileFrame,{children:t.jsx(c.Prose,{variant:"document",links:n,children:e.description})}):void 0})}const Qa=c.createSvgIcon(t.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"})),Id="publisher:resize";function Ed(e){return typeof e=="object"&&e!==null&&e.type===Id&&typeof e.height=="number"}function Za(e){return e.replace(/\/api\/v0\/?$/,"")}function Xa({server:e,environmentName:n,packageName:r,path:s,versionId:i}){const l=s.startsWith("public/")?s.slice(7):s,a=`${Za(e)}/environments/${encodeURIComponent(n)}/packages/${encodeURIComponent(r)}/`+l;return i===void 0?a:`${a}${a.includes("?")?"&":"?"}versionId=${encodeURIComponent(i)}`}function Dd(e){try{const{environmentName:n,packageName:r,modelPath:s,versionId:i}=c.parseResourceUri(e);return!n||!r||!s?null:{environmentName:n,packageName:r,dataAppPath:s,versionId:i}}catch{return null}}function Fd({resourceUri:e}){const{server:n,apiClients:r}=q.useServer(),s=Dd(e),i=s?.environmentName??"",l=s?.packageName??"",a=s?.dataAppPath??"",d=s?.versionId,u=j.useMemo(()=>Xa({server:n,environmentName:i,packageName:l,path:a,...d!==void 0?{versionId:d}:{}}),[n,i,l,a,d]),g=c.useQueryWithApiError({queryKey:["data-apps",i,l,d],queryFn:()=>r.dataApps.listDataApps(i,l,d),enabled:!!s}).data?.data?.find(S=>S.path===a),b=g?.title??a,x=g?.fit==="viewport",v=j.useRef(null),[C,k]=j.useState(120);return j.useEffect(()=>{if(x)return;function S(T){Ed(T.data)&&T.source===v.current?.contentWindow&&T.data.height>0&&k(Math.ceil(T.data.height))}return window.addEventListener("message",S),()=>window.removeEventListener("message",S)},[x]),s?t.jsxs(m.Box,{sx:{p:3,...x?{height:"100%",display:"flex",flexDirection:"column"}:{maxWidth:1600,mx:"auto"}},children:[t.jsxs(m.Stack,{direction:"row",alignItems:"baseline",spacing:1,sx:{mb:1,flexShrink:0},children:[t.jsx(m.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium",letterSpacing:"-0.025em"},children:b}),t.jsx(m.Typography,{variant:"caption",color:"text.secondary",sx:{fontFamily:q.MONO_FONT_FAMILY},children:a}),t.jsx(m.Box,{sx:{flex:1}}),t.jsx(m.Tooltip,{title:"Open standalone in new tab",children:t.jsx(m.IconButton,{size:"small",href:u,target:"_blank",rel:"noopener noreferrer","aria-label":"Open standalone in new tab",sx:{color:"text.secondary"},children:t.jsx(Qa,{fontSize:"small"})})})]}),t.jsx(m.Box,{sx:{border:"1px solid",borderColor:"divider",borderRadius:1.5,overflow:"hidden",backgroundColor:"background.paper",...x?{flex:1,minHeight:0}:{}},children:t.jsx("iframe",{ref:v,src:u,title:b,sandbox:"allow-scripts allow-same-origin allow-forms",style:{display:"block",width:"100%",height:x?"100%":C,border:0}})})]}):t.jsxs(m.Box,{sx:{p:3,maxWidth:1600,mx:"auto"},children:[t.jsx(m.Typography,{variant:"h6",sx:{fontWeight:"fontWeightMedium"},children:"Can't open data app"}),t.jsxs(m.Typography,{variant:"body2",color:"text.secondary",sx:{mt:1},children:["This data app link is missing an environment, package, or path:",t.jsx(m.Box,{component:"span",sx:{fontFamily:q.MONO_FONT_FAMILY,ml:1},children:e})]})]})}function Pt({title:e,count:n,description:r,action:s,children:i}){const l=j.useId();return t.jsxs(m.Box,{component:"section","aria-labelledby":l,sx:{mb:4},children:[t.jsxs(m.Stack,{direction:"row",alignItems:"center",justifyContent:"space-between",sx:{mb:r?0:1,minHeight:40},children:[t.jsxs(m.Stack,{direction:"row",alignItems:"baseline",spacing:1,children:[t.jsx(m.Typography,{id:l,variant:"h6",sx:{fontWeight:600,letterSpacing:"-0.025em",lineHeight:1.2},children:e}),n!==void 0&&t.jsxs(m.Typography,{variant:"caption",color:"text.secondary",children:["(",n,")"]})]}),s]}),r&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{mb:1.5},children:r}),t.jsx(m.Box,{children:i})]})}function $d({resourceUri:e}){const{environmentName:n}=c.parseResourceUri(e),{apiClients:r}=q.useServer(),[s,i]=j.useState(!1),l=90,{data:a,isSuccess:d,isError:u,error:h}=c.useQueryWithApiError({queryKey:["about",n],queryFn:()=>r.environments.getEnvironment(n,!1)}),g=a?.data?.readme||"",b=g.split(/\s+/),x=b.length>l,v=b.slice(0,l).join(" ");return t.jsxs(t.Fragment,{children:[!d&&!u&&t.jsx(c.Loading,{text:"Fetching About..."}),d&&g&&t.jsxs(Pt,{title:"Readme",children:[t.jsx(c.Prose,{variant:"caption",children:s||!x?g:v}),x&&t.jsx(m.Box,{sx:{mt:1},children:t.jsx(c.SecondaryButton,{label:s?"Read less":"Read more",onClick:()=>i(!s)})})]}),u&&t.jsx(c.ApiErrorDisplay,{error:h,context:`${n} > About`})]})}function Rd(e={}){const{autoHideDuration:n=null,disableWindowBlurListener:r=!1,onClose:s,open:i,resumeHideDuration:l}=e,a=c.useTimeout();we.useEffect(()=>{if(!i)return;function T(M){M.defaultPrevented||M.key==="Escape"&&s?.(M,"escapeKeyDown")}return document.addEventListener("keydown",T),()=>{document.removeEventListener("keydown",T)}},[i,s]);const d=c.useEventCallback((T,M)=>{s?.(T,M)}),u=c.useEventCallback(T=>{!s||T==null||a.start(T,()=>{d(null,"timeout")})});we.useEffect(()=>(i&&u(n),a.clear),[i,n,u,a]);const h=T=>{s?.(T,"clickaway")},g=a.clear,b=we.useCallback(()=>{n!=null&&u(l??n*.5)},[n,l,u]),x=T=>M=>{const O=T.onBlur;O?.(M),b()},v=T=>M=>{const O=T.onFocus;O?.(M),g()},C=T=>M=>{const O=T.onMouseEnter;O?.(M),g()},k=T=>M=>{const O=T.onMouseLeave;O?.(M),b()};return we.useEffect(()=>{if(!r&&i)return window.addEventListener("focus",b),window.addEventListener("blur",g),()=>{window.removeEventListener("focus",b),window.removeEventListener("blur",g)}},[r,i,b,g]),{getRootProps:(T={})=>{const M={...c.extractEventHandlers(e),...c.extractEventHandlers(T)};return{role:"presentation",...T,...M,onBlur:x(M),onFocus:v(M),onMouseEnter:C(M),onMouseLeave:k(M)}},onClickAway:h}}function Fi(e){return e.substring(2).toLowerCase()}function Ad(e,n){return n.documentElement.clientWidth<e.clientX||n.documentElement.clientHeight<e.clientY}function Ld(e){const{children:n,disableReactTree:r=!1,mouseEvent:s="onClick",onClickAway:i,touchEvent:l="onTouchEnd"}=e,a=we.useRef(!1),d=we.useRef(null),u=we.useRef(!1),h=we.useRef(!1);we.useEffect(()=>(setTimeout(()=>{u.current=!0},0),()=>{u.current=!1}),[]);const g=c.useForkRef(c.getReactElementRef(n),d),b=c.useEventCallback(C=>{const k=h.current;h.current=!1;const S=c.ownerDocument(d.current);if(!u.current||!d.current||"clientX"in C&&Ad(C,S))return;if(a.current){a.current=!1;return}let T;C.composedPath?T=C.composedPath().includes(d.current):T=!S.documentElement.contains(C.target)||d.current.contains(C.target),!T&&(r||!k)&&i(C)}),x=C=>k=>{h.current=!0;const S=n.props[C];S&&S(k)},v={ref:g};return l!==!1&&(v[l]=x(l)),we.useEffect(()=>{if(l!==!1){const C=Fi(l),k=c.ownerDocument(d.current),S=()=>{a.current=!0};return k.addEventListener(C,b),k.addEventListener("touchmove",S),()=>{k.removeEventListener(C,b),k.removeEventListener("touchmove",S)}}},[b,l]),s!==!1&&(v[s]=x(s)),we.useEffect(()=>{if(s!==!1){const C=Fi(s),k=c.ownerDocument(d.current);return k.addEventListener(C,b),()=>{k.removeEventListener(C,b)}}},[b,s]),we.cloneElement(n,v)}function Nd(e){return c.generateUtilityClass("MuiSnackbarContent",e)}c.generateUtilityClasses("MuiSnackbarContent",["root","message","action"]);const Pd=e=>{const{classes:n}=e,r={root:["root"],action:["action"],message:["message"]};return c.composeClasses(r,Nd,n)},_d=c.styled(c.Paper,{name:"MuiSnackbarContent",slot:"Root"})(c.memoTheme(({theme:e})=>{const n=e.palette.mode==="light"?.8:.98;return{...e.typography.body2,color:e.vars?e.vars.palette.SnackbarContent.color:e.palette.getContrastText(c.emphasize(e.palette.background.default,n)),backgroundColor:e.vars?e.vars.palette.SnackbarContent.bg:c.emphasize(e.palette.background.default,n),display:"flex",alignItems:"center",flexWrap:"wrap",padding:"6px 16px",flexGrow:1,[e.breakpoints.up("sm")]:{flexGrow:"initial",minWidth:288}}})),zd=c.styled("div",{name:"MuiSnackbarContent",slot:"Message"})({padding:"8px 0"}),Wd=c.styled("div",{name:"MuiSnackbarContent",slot:"Action"})({display:"flex",alignItems:"center",marginLeft:"auto",paddingLeft:16,marginRight:-8}),qd=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiSnackbarContent"}),{action:i,className:l,message:a,role:d="alert",...u}=s,h=s,g=Pd(h);return t.jsxs(_d,{role:d,elevation:6,className:c.clsx(g.root,l),ownerState:h,ref:r,...u,children:[t.jsx(zd,{className:g.message,ownerState:h,children:a}),i?t.jsx(Wd,{className:g.action,ownerState:h,children:i}):null]})});function Bd(e){return c.generateUtilityClass("MuiSnackbar",e)}c.generateUtilityClasses("MuiSnackbar",["root","anchorOriginTopCenter","anchorOriginBottomCenter","anchorOriginTopRight","anchorOriginBottomRight","anchorOriginTopLeft","anchorOriginBottomLeft"]);const Vd=e=>{const{classes:n,anchorOrigin:r}=e,s={root:["root",`anchorOrigin${c.capitalize(r.vertical)}${c.capitalize(r.horizontal)}`]};return c.composeClasses(s,Bd,n)},Hd=c.styled("div",{name:"MuiSnackbar",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,n[`anchorOrigin${c.capitalize(r.anchorOrigin.vertical)}${c.capitalize(r.anchorOrigin.horizontal)}`]]}})(c.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.snackbar,position:"fixed",display:"flex",left:8,right:8,justifyContent:"center",alignItems:"center",variants:[{props:({ownerState:n})=>n.anchorOrigin.vertical==="top",style:{top:8,[e.breakpoints.up("sm")]:{top:24}}},{props:({ownerState:n})=>n.anchorOrigin.vertical!=="top",style:{bottom:8,[e.breakpoints.up("sm")]:{bottom:24}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="left",style:{justifyContent:"flex-start",[e.breakpoints.up("sm")]:{left:24,right:"auto"}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="right",style:{justifyContent:"flex-end",[e.breakpoints.up("sm")]:{right:24,left:"auto"}}},{props:({ownerState:n})=>n.anchorOrigin.horizontal==="center",style:{[e.breakpoints.up("sm")]:{left:"50%",right:"auto",transform:"translateX(-50%)"}}}]}))),Ud=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiSnackbar"}),i=c.useTheme(),l={enter:i.transitions.duration.enteringScreen,exit:i.transitions.duration.leavingScreen},{action:a,anchorOrigin:{vertical:d,horizontal:u}={vertical:"bottom",horizontal:"left"},autoHideDuration:h=null,children:g,className:b,ClickAwayListenerProps:x,ContentProps:v,disableWindowBlurListener:C=!1,message:k,onBlur:S,onClose:T,onFocus:M,onMouseEnter:O,onMouseLeave:I,open:R,resumeHideDuration:_,slots:$={},slotProps:B={},TransitionComponent:F,transitionDuration:N=l,TransitionProps:{onEnter:H,onExited:D,...W}={},...K}=s,J={...s,anchorOrigin:{vertical:d,horizontal:u},autoHideDuration:h,disableWindowBlurListener:C,TransitionComponent:F,transitionDuration:N},X=Vd(J),{getRootProps:G,onClickAway:Q}=Rd({...J}),[ie,z]=we.useState(!0),re=ge=>{z(!0),D&&D(ge)},se=(ge,he)=>{z(!1),H&&H(ge,he)},ne={slots:{transition:F,...$},slotProps:{content:v,clickAwayListener:x,transition:W,...B}},[Me,oe]=c.useSlot("root",{ref:r,className:[X.root,b],elementType:Hd,getSlotProps:G,externalForwardedProps:{...ne,...K},ownerState:J}),[ue,{ownerState:De,...Ne}]=c.useSlot("clickAwayListener",{elementType:Ld,externalForwardedProps:ne,getSlotProps:ge=>({onClickAway:(...he)=>{const ye=he[0];ge.onClickAway?.(...he),!ye?.defaultMuiPrevented&&Q(...he)}}),ownerState:J}),[ae,Z]=c.useSlot("content",{elementType:qd,shouldForwardComponentProp:!0,externalForwardedProps:ne,additionalProps:{message:k,action:a},ownerState:J}),[ce,be]=c.useSlot("transition",{elementType:c.Grow,externalForwardedProps:ne,getSlotProps:ge=>({onEnter:(...he)=>{ge.onEnter?.(...he),se(...he)},onExited:(...he)=>{ge.onExited?.(...he),re(...he)}}),additionalProps:{appear:!0,in:R,timeout:N,direction:d==="top"?"down":"up"},ownerState:J});return!R&&ie?null:t.jsx(ue,{...Ne,...$.clickAwayListener&&{ownerState:De},children:t.jsx(Me,{...oe,children:t.jsx(ce,{...be,children:g||t.jsx(ae,{...Z})})})})});let Ys;function Gd(e){Ys=e}function $i(e){if(Ys)try{Ys(e)}catch{}}function Ht(e,n,r){return(async s=>{const i=Date.now();try{const l=await r(s);return $i({type:"console.mutation",resource:e,action:n,ok:!0,durationMs:Date.now()-i}),l}catch(l){throw $i({type:"console.mutation",resource:e,action:n,ok:!1,durationMs:Date.now()-i,reason:l instanceof Error?l.message:"An unknown error occurred"}),l}})}function Pn({mutationFn:e,success:n,invalidates:r,closeDialog:s,resource:i,action:l}){const a=yt.useQueryClient(),[d,u]=j.useState(""),h=c.useMutationWithApiError({mutationFn:Ht(i,l,e),onSuccess(){s();for(const g of r)a.invalidateQueries({queryKey:g});u(n)},onError(g){u(g instanceof Error?g.message:"An unknown error occurred")}});return{mutate:h.mutate,isPending:h.isPending,notice:t.jsx(Ud,{open:d!=="",autoHideDuration:6e3,onClose:()=>u(""),message:d})}}const Ja="https://docs.malloydata.dev/documentation",Ts=`${Ja}/user_guides/publishing`,En="https://github.com/malloydata/publisher/blob/main/docs",Vt={docsHome:`${Ja}/`,publishing:`${Ts}/publishing`,explorer:`${Ts}/explorer`,mcpAgents:`${Ts}/mcp_agents`,surfaces:`${En}/choosing-a-surface.md`,dashboards:`${En}/dashboards.md`,dataApps:`${En}/html-data-apps.md`,givens:`${En}/givens.md`,materialization:`${En}/materialization.md`,connections:`${En}/connections.md`};function Yd({resourceUri:e}){const[n,r]=j.useState(!1),{apiClients:s}=q.useServer(),{environmentName:i}=c.parseResourceUri(e),l=Pn({mutationFn(d){return s.packages.createPackage(i,{name:d.name,description:d.description,location:d.location})},success:"Package created",invalidates:[["packages",i]],closeDialog:()=>r(!1),resource:"package",action:"create"}),a=d=>{d.preventDefault();const u=new FormData(d.currentTarget),h=u.get("name")?.toString(),g=u.get("description")?.toString(),b=u.get("location")?.toString();l.mutate({name:h,description:g,location:b})};return t.jsxs(t.Fragment,{children:[t.jsx(c.AddButton,{label:"Package",onClick:()=>r(!0)}),t.jsx(c.AppDialog,{open:n,onClose:()=>r(!1),title:"New package",description:t.jsxs(t.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"," ",t.jsx(m.Box,{component:"a",href:Vt.publishing,target:"_blank",rel:"noopener noreferrer",sx:{color:"text.primary"},children:"package format"}),"."]}),actions:t.jsxs(t.Fragment,{children:[t.jsx(m.Button,{disabled:l.isPending,onClick:()=>r(!1),children:"Cancel"}),t.jsx(m.Button,{type:"submit",form:"package-form",variant:"contained",loading:l.isPending,children:"Create package"})]}),children:t.jsx("form",{onSubmit:a,id:"package-form",children:t.jsxs(m.Stack,{sx:{gap:2},children:[t.jsx(m.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(m.TextField,{id:"description",name:"description",label:"Description",multiline:!0,rows:3,fullWidth:!0,size:"small",InputLabelProps:{shrink:!0}}),t.jsx(m.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}})]})})}),l.notice]})}const Kd=c.createSvgIcon(t.jsx("path",{d:"M2 20h20v-4H2zm2-3h2v2H4zM2 4v4h20V4zm4 3H4V5h2zm-4 7h20v-4H2zm2-3h2v2H4z"}));function os({icon:e,tint:n,label:r,mono:s,description:i,rightLabel:l,trailingAction:a,onClick:d,ariaLabel:u}){const h=!!d,g=b=>{d&&(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),d(b))};return t.jsxs(m.Box,{onClick:d,onKeyDown:h?g:void 0,role:h?"button":void 0,tabIndex:h?0:void 0,"aria-label":u,sx:b=>({display:"flex",alignItems:"center",gap:1.5,py:1,px:1,mx:-1,cursor:h?"pointer":"default",borderRadius:1.5,transition:"background-color 0.1s","&:hover":h?{backgroundColor:b.palette.mode==="dark"?"rgba(255, 255, 255, 0.08)":"grey.100"}:void 0,"&:focus-visible":h?{outline:"2px solid",outlineColor:"primary.main",outlineOffset:2}:void 0}),children:[t.jsx(m.Box,{sx:{width:32,height:32,borderRadius:1,bgcolor:n,color:"#FFFFFF",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:e}),t.jsxs(m.Box,{sx:{flex:1,minWidth:0,display:"flex",alignItems:"baseline",gap:1.5},children:[t.jsx(m.Typography,{variant:"body2",sx:{...s?{fontFamily:q.MONO_FONT_FAMILY}:{},flexShrink:0,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:r}),i&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",sx:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:i})]}),l&&t.jsx(m.Typography,{variant:"caption",color:"text.secondary",sx:{flexShrink:0},children:l}),a&&t.jsx(m.Box,{sx:{flexShrink:0,display:"flex",alignItems:"center"},children:a})]})}const el=c.createSvgIcon(t.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"})),Qd=c.generateUtilityClasses("MuiBox",["root"]),Zd=c.createTheme(),Ye=Sr.createBox({themeId:c.THEME_ID,defaultTheme:Zd,defaultClassName:Qd.root,generateClassName:c.ClassNameGenerator.generate}),is=Sr.createStack({createStyledComponent:c.styled("div",{name:"MuiStack",slot:"Root"}),useThemeProps:e=>c.useDefaultProps({props:e,name:"MuiStack"})}),Ri=c.generateUtilityClasses("MuiDivider",["root","absolute","fullWidth","inset","middle","flexItem","light","vertical","withChildren","withChildrenVertical","textAlignRight","textAlignLeft","wrapper","wrapperVertical"]);function Xd(e){return c.generateUtilityClass("MuiListItemIcon",e)}const Ai=c.generateUtilityClasses("MuiListItemIcon",["root","alignItemsFlexStart"]),Jd=e=>{const{alignItems:n,classes:r}=e,s={root:["root",n==="flex-start"&&"alignItemsFlexStart"]};return c.composeClasses(s,Xd,r)},eh=c.styled("div",{name:"MuiListItemIcon",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,r.alignItems==="flex-start"&&n.alignItemsFlexStart]}})(c.memoTheme(({theme:e})=>({minWidth:56,color:(e.vars||e).palette.action.active,flexShrink:0,display:"inline-flex",variants:[{props:{alignItems:"flex-start"},style:{marginTop:8}}]}))),lo=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiListItemIcon"}),{className:i,...l}=s,a=we.useContext(c.ListContext),d={...s,alignItems:a.alignItems},u=Jd(d);return t.jsx(eh,{className:c.clsx(u.root,i),ownerState:d,ref:r,...l})});function th(e){return c.generateUtilityClass("MuiListItemText",e)}const Fn=c.generateUtilityClasses("MuiListItemText",["root","multiline","dense","inset","primary","secondary"]),nh=e=>{const{classes:n,inset:r,primary:s,secondary:i,dense:l}=e,a={root:["root",r&&"inset",l&&"dense",s&&i&&"multiline"],primary:["primary"],secondary:["secondary"]};return c.composeClasses(a,th,n)},rh=c.styled("div",{name:"MuiListItemText",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${Fn.primary}`]:n.primary},{[`& .${Fn.secondary}`]:n.secondary},n.root,r.inset&&n.inset,r.primary&&r.secondary&&n.multiline,r.dense&&n.dense]}})({flex:"1 1 auto",minWidth:0,marginTop:4,marginBottom:4,[`.${c.typographyClasses.root}:where(& .${Fn.primary})`]:{display:"block"},[`.${c.typographyClasses.root}:where(& .${Fn.secondary})`]:{display:"block"},variants:[{props:({ownerState:e})=>e.primary&&e.secondary,style:{marginTop:6,marginBottom:6}},{props:({ownerState:e})=>e.inset,style:{paddingLeft:56}}]}),co=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiListItemText"}),{children:i,className:l,disableTypography:a=!1,inset:d=!1,primary:u,primaryTypographyProps:h,secondary:g,secondaryTypographyProps:b,slots:x={},slotProps:v={},...C}=s,{dense:k}=we.useContext(c.ListContext);let S=u??i,T=g;const M={...s,disableTypography:a,inset:d,primary:!!S,secondary:!!T,dense:k},O=nh(M),I={slots:x,slotProps:{primary:h,secondary:b,...v}},[R,_]=c.useSlot("root",{className:c.clsx(O.root,l),elementType:rh,externalForwardedProps:{...I,...C},ownerState:M,ref:r}),[$,B]=c.useSlot("primary",{className:O.primary,elementType:c.Typography,externalForwardedProps:I,ownerState:M}),[F,N]=c.useSlot("secondary",{className:O.secondary,elementType:c.Typography,externalForwardedProps:I,ownerState:M});return S!=null&&S.type!==c.Typography&&!a&&(S=t.jsx($,{variant:k?"body2":"body1",component:B?.variant?void 0:"span",...B,children:S})),T!=null&&T.type!==c.Typography&&!a&&(T=t.jsx(F,{variant:"body2",color:"textSecondary",...N,children:T})),t.jsxs(R,{..._,children:[S,T]})});function sh(e){return c.generateUtilityClass("MuiMenuItem",e)}const er=c.generateUtilityClasses("MuiMenuItem",["root","focusVisible","dense","disabled","divider","gutters","selected"]),oh=(e,n)=>{const{ownerState:r}=e;return[n.root,r.dense&&n.dense,r.divider&&n.divider,!r.disableGutters&&n.gutters]},ih=e=>{const{disabled:n,dense:r,divider:s,disableGutters:i,selected:l,classes:a}=e,d={root:["root",r&&"dense",n&&"disabled",!i&&"gutters",s&&"divider",l&&"selected"]},u=c.composeClasses(d,sh,a);return{...a,...u}},ah=c.styled(c.ButtonBase,{shouldForwardProp:e=>c.rootShouldForwardProp(e)||e==="classes",name:"MuiMenuItem",slot:"Root",overridesResolver:oh})(c.memoTheme(({theme:e})=>({...e.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:(e.vars||e).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},[`&.${er.selected}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity),[`&.${er.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}},[`&.${er.selected}:hover`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity)}},[`&.${er.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},[`&.${er.disabled}`]:{opacity:(e.vars||e).palette.action.disabledOpacity},[`& + .${Ri.root}`]:{marginTop:e.spacing(1),marginBottom:e.spacing(1)},[`& + .${Ri.inset}`]:{marginLeft:52},[`& .${Fn.root}`]:{marginTop:0,marginBottom:0},[`& .${Fn.inset}`]:{paddingLeft:36},[`& .${Ai.root}`]:{minWidth:36},variants:[{props:({ownerState:n})=>!n.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:n})=>n.divider,style:{borderBottom:`1px solid ${(e.vars||e).palette.divider}`,backgroundClip:"padding-box"}},{props:({ownerState:n})=>!n.dense,style:{[e.breakpoints.up("sm")]:{minHeight:"auto"}}},{props:({ownerState:n})=>n.dense,style:{minHeight:32,paddingTop:4,paddingBottom:4,...e.typography.body2,[`& .${Ai.root} svg`]:{fontSize:"1.25rem"}}}]}))),tt=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiMenuItem"}),{autoFocus:i=!1,component:l="li",dense:a=!1,divider:d=!1,disableGutters:u=!1,focusVisibleClassName:h,role:g="menuitem",tabIndex:b,className:x,...v}=s,C=we.useContext(c.ListContext),k=we.useMemo(()=>({dense:a||C.dense||!1,disableGutters:u}),[C.dense,a,u]),S=we.useRef(null);c.useEnhancedEffect(()=>{i&&S.current&&S.current.focus()},[i]);const T={...s,dense:k.dense,divider:d,disableGutters:u},M=ih(s),O=c.useForkRef(S,r);let I;return s.disabled||(I=b!==void 0?b:-1),t.jsx(c.ListContext.Provider,{value:k,children:t.jsx(ah,{ref:O,role:g,tabIndex:I,component:l,focusVisibleClassName:c.clsx(M.focusVisible,h),className:c.clsx(M.root,x),...v,ownerState:T,classes:M})})}),Gt={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}],sqlserver:[{label:"Server",name:"server",type:"text",required:!0},{label:"Port",name:"port",type:"number",required:!1},{label:"Database",name:"database",type:"text",required:!0},{label:"User",name:"user",type:"text",required:!0},{label:"Password",name:"password",type:"password",required:!0},{label:"Encrypt",name:"encrypt",type:"text",required:!1,selectOptions:[{label:"Yes",value:"true"},{label:"No",value:"false"}]},{label:"Trust server certificate",name:"trustServerCertificate",type:"text",required:!1,selectOptions:[{label:"No",value:"false"},{label:"Yes",value:"true"}]},{label:"Host name in certificate",name:"hostNameInCertificate",type:"text",required:!1},{label:"Instance name",name:"instanceName",type:"text",required:!1}],duckdb:[],motherduck:[{label:"Access Token",name:"accessToken",type:"text",required:!0},{label:"Database",name:"database",type:"text",required:!1}],ducklake:[],publisher:[]},mr={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",trino:"trinoConnection",databricks:"databricksConnection",mysql:"mysqlConnection",sqlserver:"sqlserverConnection",duckdb:"duckdbConnection",motherduck:"motherduckConnection",ducklake:"ducklakeConnection",publisher:"publisherConnection"},lh={sqlserver:{port:"integer",encrypt:"boolean",trustServerCertificate:"boolean"}},ch={sqlserver:["hostNameInCertificate","instanceName"]};function tl(e,n){const r=lh[e],s=ch[e];if(!r&&!s)return n;const i={...n};for(const l of s??[])i[l]===""&&delete i[l];for(const[l,a]of Object.entries(r??{})){const d=n[l];if(d!==void 0){if(d===""){delete i[l];continue}if(a==="integer"){const u=Number(d);Number.isInteger(u)&&(i[l]=u)}else(d==="true"||d==="false")&&(i[l]=d==="true")}}return i}const nl=Object.values(q.ConnectionTypeEnum).filter(e=>e!==q.ConnectionTypeEnum.Publisher),Ks={postgres:"postgresConnection",bigquery:"bigqueryConnection",snowflake:"snowflakeConnection",gcs:"gcsConnection",s3:"s3Connection",azure:"azureConnection"},kr=[{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"}}],Cr=[{label:"Key ID",name:"keyId",type:"text",required:!0},{label:"Secret",name:"secret",type:"password",required:!0}],uh=[{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 es(e){return e==="postgres"||e==="bigquery"||e==="snowflake"?Gt[e]||[]:e==="s3"?kr:e==="gcs"?Cr:e==="azure"?uh:[]}function dh({onSubmit:e,isSubmitting:n}){const[r,s]=j.useState(!1),[i,l]=j.useState("postgres"),[a,d]=j.useState([]),[u,h]=j.useState("postgres"),[g,b]=j.useState("s3"),[x,v]=j.useState("config"),C=()=>{s(!0)},k=()=>{s(!1),d([]),l("postgres"),h("postgres"),b("s3"),v("config")},S=async I=>{I.preventDefault();const R=new FormData(I.currentTarget),_=R.get("name")?.toString(),$=R.get("type")?.toString(),B=Gt[$];if(!_)throw new Error("Name is required");if(!$)throw new Error("Type is required");let F;if($==="ducklake"){const N={};if(u==="postgres"){const W=Gt.postgres,K={};if(W.forEach(J=>{const X=R.get(`ducklake_pg_${J.name}`)?.toString();X&&(K[J.name]=X)}),Object.keys(K).length===0)throw new Error("DuckLake requires catalog connection");N.postgresConnection=K}const H=R.get("ducklake_bucketUrl")?.toString();if(!H)throw new Error("DuckLake requires a bucket URL");const D={bucketUrl:H};if(g==="s3"){const W={};if(kr.forEach(K=>{const J=R.get(`ducklake_s3_${K.name}`)?.toString();J&&(W[K.name]=J)}),W.provider==="credential_chain")delete W.accessKeyId,delete W.secretAccessKey,delete W.sessionToken;else{if(delete W.chain,!W.accessKeyId)throw new Error("S3 Access Key ID is required");if(!W.secretAccessKey)throw new Error("S3 Secret Access Key is required")}Object.keys(W).length>0&&(D.s3Connection=W)}else if(g==="gcs"){const W={};if(Cr.forEach(K=>{const J=R.get(`ducklake_gcs_${K.name}`)?.toString();J&&(W[K.name]=J)}),!W.keyId)throw new Error("GCS Key ID is required");if(!W.secret)throw new Error("GCS Secret is required");Object.keys(W).length>0&&(D.gcsConnection=W)}F={name:_,type:$,ducklakeConnection:{catalog:N,storage:D}}}else if($==="duckdb"){if(a.length===0)throw new Error("DuckDB connection must have at least one attached database");const N=a.map((H,D)=>{const W=H.dbType,K=R.get(`attachedDb_${D}_name`)?.toString();if(!K)throw new Error(`Attached database at index ${D} must have a name`);const J={name:K,type:W},X=es(W);if(X&&X.length>0){const G={};if(X.forEach(ie=>{const z=R.get(`attachedDb_${D}_${ie.name}`)?.toString();z&&(G[ie.name]=z)}),W==="s3"){if(G.provider==="credential_chain")delete G.accessKeyId,delete G.secretAccessKey,delete G.sessionToken;else if(delete G.chain,!G.accessKeyId||!G.secretAccessKey)throw new Error(`Attached database "${K}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const Q=Ks[W];Q&&(J[Q]=G)}return J});F={name:_,type:$,duckdbConnection:{attachedDatabases:N}}}else{const N={};if(B.forEach(H=>{const D=R.get(H.name)?.toString();D&&(N[H.name]=D)}),$==="postgres"){if(!!!N.connectionString?.trim()){const D=["host","port","databaseName","userName","password"];for(const W of D)if(!N[W])throw new Error(`${B.find(K=>K.name===W)?.label||W} is required`)}}else if($==="bigquery"){if(!N.serviceAccountKeyJson)throw new Error("Service Account Key JSON is required")}else if($==="snowflake"){if(!N.account)throw new Error("Account is required");if(!N.username)throw new Error("Username is required");if(!N.warehouse)throw new Error("Warehouse is required");if(!N.password&&!N.privateKey)throw new Error("Either password or private key is required")}else if($==="trino"){if(!N.server)throw new Error("Server is required");if(!N.user)throw new Error("User is required");if(N.server.trim().startsWith("https://")&&!N.password&&!N.peakaKey)throw new Error("Password is required for HTTPS connections (or use Peaka Key)")}else if($==="mysql"){const H=["host","port","database","user","password"];for(const D of H)if(!N[D])throw new Error(`${B.find(W=>W.name===D)?.label||D} is required`)}else if($==="sqlserver"){const H=["server","database","user","password"];if(!N.instanceName&&!N.port)throw new Error("Port is required unless an instance name is given");for(const D of H)if(!N[D])throw new Error(`${B.find(W=>W.name===D)?.label||D} is required`)}else if($==="motherduck"){if(!N.accessToken)throw new Error("Access Token is required")}else if($==="databricks"){if(!N.host)throw new Error("Host is required");if(!N.path)throw new Error("HTTP Path is required");const H=N.oauthClientId&&N.oauthClientSecret;if(!N.token&&!H)throw new Error("Either Access Token or OAuth Client ID + Secret is required")}F={name:_,type:$,[mr[$]]:tl($,N)}}await e(F),k()},T=()=>{d([...a,{name:"",dbType:"postgres"}])},M=I=>{d(a.filter((R,_)=>_!==I))},O=(I,R)=>{const _=[...a];_[I]={..._[I],dbType:R},d(_)};return t.jsxs(j.Fragment,{children:[t.jsx(c.AddButton,{label:"Connection",onClick:C}),t.jsx(c.AppDialog,{open:r,onClose:k,title:"New connection",description:"Add a connection so packages in this environment can query your database with Malloy.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:n,onClick:k,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"connection-form",variant:"contained",loading:n,children:"Create connection"})]}),children:t.jsx("form",{onSubmit:S,id:"connection-form",children:t.jsxs(is,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small"}),t.jsx(c.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:i,select:!0,onChange:I=>l(I.target.value),children:nl.map(I=>t.jsx(tt,{value:I,children:I},I))}),i==="ducklake"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(c.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:u,select:!0,onChange:I=>h(I.target.value),children:t.jsx(tt,{value:"postgres",children:"PostgreSQL"})}),u==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(I=>t.jsx(c.TextField,{id:`ducklake_pg_${I.name}`,name:`ducklake_pg_${I.name}`,label:I.label,type:I.type,fullWidth:!0,size:"small"},`pg_${I.name}`))})]}),t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(c.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:g,select:!0,onChange:I=>b(I.target.value),children:[t.jsx(tt,{value:"s3",children:"S3"}),t.jsx(tt,{value:"gcs",children:"GCS"})]}),t.jsx(c.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"}),g==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),kr.filter(I=>I.visibleWhen?x===I.visibleWhen.value:!0).map(I=>t.jsx(c.TextField,{id:`ducklake_s3_${I.name}`,name:`ducklake_s3_${I.name}`,label:I.label,type:I.selectOptions?void 0:I.type,fullWidth:!0,size:"small",required:I.required,select:!!I.selectOptions,defaultValue:I.selectOptions?x:void 0,onChange:I.name==="provider"?R=>v(R.target.value):void 0,placeholder:I.name==="region"?"us-east-1":void 0,children:I.selectOptions?.map(R=>t.jsx(tt,{value:R.value,children:R.label},R.value))},`s3_${I.name}`))]}),g==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),Cr.map(I=>t.jsx(c.TextField,{id:`ducklake_gcs_${I.name}`,name:`ducklake_gcs_${I.name}`,label:I.label,type:I.type,fullWidth:!0,size:"small",required:I.required},`gcs_${I.name}`))]})]})]}):i==="duckdb"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(c.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(c.SecondaryButton,{label:"Database",icon:t.jsx(c.AddIcon,{}),onClick:T,ariaLabel:"Add database"})]}),a.length===0&&t.jsx(c.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),a.map((I,R)=>{const _=es(I.dbType);return t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ye,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",R+1]}),t.jsx(c.IconButton,{onClick:()=>M(R),size:"small",color:"error",children:t.jsx(el,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${R}_name`,name:`attachedDb_${R}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:I.name}),t.jsx(c.TextField,{id:`attachedDb_${R}_type`,name:`attachedDb_${R}_type`,label:"Database Type",fullWidth:!0,size:"small",value:I.dbType,select:!0,onChange:$=>O(R,$.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map($=>t.jsx(tt,{value:$,children:$},$))}),_.filter($=>$.visibleWhen?(I[$.visibleWhen.field]||_.find(F=>F.name===$.visibleWhen?.field)?.selectOptions?.[0]?.value)===$.visibleWhen.value:!0).map($=>t.jsx(c.TextField,{id:`attachedDb_${R}_${$.name}`,name:`attachedDb_${R}_${$.name}`,label:$.label,type:$.selectOptions?void 0:$.type,fullWidth:!0,size:"small",required:$.required,select:!!$.selectOptions,defaultValue:$.selectOptions?.[0]?.value,onChange:$.selectOptions?B=>{const F=[...a];F[R]={...F[R],[$.name]:B.target.value},d(F)}:void 0,children:$.selectOptions?.map(B=>t.jsx(tt,{value:B.value,children:B.label},B.value))},$.name))]},R)})]}):Gt[i].map(I=>t.jsx(c.TextField,{id:I.name,name:I.name,label:I.label,type:I.type,fullWidth:!0,size:"small",required:I.required,select:!!I.selectOptions,defaultValue:I.selectOptions?I.selectOptions[0]?.value:void 0,children:I.selectOptions?.map(R=>t.jsx(tt,{value:R.value,children:R.label},R.value))},I.name))]})})})]})}function hh({connection:e,onCloseDialog:n,isMutating:r,onDelete:s}){const[i,l]=j.useState(!1),a=()=>{l(!0)},d=()=>{l(!1),n()};return t.jsxs(j.Fragment,{children:[t.jsxs(tt,{"aria-label":`Delete connection ${e?.name??""}`.trim(),onClick:u=>{u.stopPropagation(),a()},sx:{color:"error.main"},children:[t.jsx(lo,{sx:{color:"inherit"},children:t.jsx(_t.Delete,{fontSize:"small"})}),t.jsx(co,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:i,onClose:d,title:"Delete connection",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:d,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>s(),loading:r,children:"Delete connection"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:e.name}),"? Packages that query through it stop working, and this cannot be undone."]})})]})}const Li=new Set(["password","connectionString","privateKey","privateKeyPass","serviceAccountKeyJson","token","oauthClientSecret","accessToken","peakaKey","secret","secretAccessKey","sessionToken","clientSecret","sasUrl"]);function Ni(e){const n=e.duckdbConnection?.attachedDatabases;return!n||n.length===0?[]:n.map(r=>({name:r.name||"",dbType:r.type||"postgres"}))}function Pi(e){const n=e.ducklakeConnection;return n&&n.storage?.gcsConnection?"gcs":"s3"}function fh({connection:e,onSubmit:n,isSubmitting:r,onCloseDialog:s}){const[i,l]=j.useState(!1),[a,d]=j.useState(e.type),u=j.useMemo(()=>new Set(e.withheldFields??[]),[e.withheldFields]),[h,g]=j.useState(()=>Ni(e)),[b,x]=j.useState("postgres"),[v,C]=j.useState(()=>Pi(e)),[k,S]=j.useState(()=>e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),T=()=>{g(Ni(e)),d(e.type),S(e.ducklakeConnection?.storage?.s3Connection?.provider??"config"),x("postgres"),C(Pi(e)),l(!0)},M=()=>{l(!1),s?.()},O=async F=>{F.preventDefault();const N=new FormData(F.currentTarget),H=N.get("name")?.toString(),D=N.get("type")?.toString(),W=Gt[D];if(!H)throw new Error("Name is required");if(!D)throw new Error("Type is required");let K;if(D==="ducklake"){const J={};if(b==="postgres"){const Q=Gt.postgres,ie={};if(Q.forEach(z=>{const re=N.get(`ducklake_pg_${z.name}`)?.toString();re&&(ie[z.name]=re)}),Object.keys(ie).length===0)throw new Error("DuckLake requires catalog connection");J.postgresConnection=ie}const X=N.get("ducklake_bucketUrl")?.toString();if(!X)throw new Error("DuckLake requires a bucket URL");const G={bucketUrl:X};if(v==="s3"){const Q={};kr.forEach(z=>{const re=N.get(`ducklake_s3_${z.name}`)?.toString();re&&(Q[z.name]=re)});const ie=e.ducklakeConnection?.storage?.s3Connection;if(ie&&(!Q.provider&&ie.provider&&(Q.provider=ie.provider),!Q.chain&&ie.chain&&(Q.chain=ie.chain),!Q.accessKeyId&&ie.accessKeyId&&(Q.accessKeyId=ie.accessKeyId)),Q.provider==="credential_chain")delete Q.accessKeyId,delete Q.secretAccessKey,delete Q.sessionToken;else if(delete Q.chain,!Q.accessKeyId)throw new Error("S3 Access Key ID is required");Object.keys(Q).length>0&&(G.s3Connection=Q)}else if(v==="gcs"){const Q={};Cr.forEach(z=>{const re=N.get(`ducklake_gcs_${z.name}`)?.toString();re&&(Q[z.name]=re)});const ie=e.ducklakeConnection?.storage?.gcsConnection;if(ie&&!Q.keyId&&ie.keyId&&(Q.keyId=ie.keyId),!Q.keyId)throw new Error("GCS Key ID is required");Object.keys(Q).length>0&&(G.gcsConnection=Q)}K={name:H,type:D,ducklakeConnection:{catalog:J,storage:G}}}else if(D==="duckdb"){if(h.length===0)throw new Error("DuckDB connection must have at least one attached database");const J=h.map((X,G)=>{const Q=X.dbType,ie=N.get(`attachedDb_${G}_name`)?.toString();if(!ie)throw new Error(`Attached database at index ${G} must have a name`);const z={name:ie,type:Q},re=es(Q);if(re&&re.length>0){const se={};if(re.forEach(Me=>{const oe=N.get(`attachedDb_${G}_${Me.name}`)?.toString();oe&&(se[Me.name]=oe)}),Q==="s3"){if(se.provider==="credential_chain")delete se.accessKeyId,delete se.secretAccessKey,delete se.sessionToken;else if(delete se.chain,!se.accessKeyId||!se.secretAccessKey)throw new Error(`Attached database "${ie}" requires an S3 Access Key ID and Secret Access Key, or Credential Provider set to the host credential chain`)}const ne=Ks[Q];ne&&(z[ne]=se)}return z});K={name:H,type:D,duckdbConnection:{attachedDatabases:J}}}else{const J=e[mr[D]]||{},X={};if(W.forEach(G=>{const Q=N.get(G.name)?.toString(),ie=J[G.name];Q?X[G.name]=Q:Li.has(G.name)||(Q!==void 0?X[G.name]=Q:ie&&(X[G.name]=ie))}),D==="postgres"){const G=["host","port","databaseName","userName"],Q=u.has("postgresConnection.connectionString");if(!(!!X.connectionString?.trim()||Q)){const z=G;for(const re of z)if(!X[re])throw new Error(`${W.find(se=>se.name===re)?.label||re} is required`)}}else if(D==="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(D==="trino"){if(!X.server)throw new Error("Server is required");if(!X.user)throw new Error("User is required")}else if(D==="mysql"){const G=["host","port","database","user"];for(const Q of G)if(!X[Q])throw new Error(`${W.find(ie=>ie.name===Q)?.label||Q} is required`)}else if(D==="sqlserver"){const G=["server","database","user"];if(!X.instanceName&&!X.port)throw new Error("Port is required unless an instance name is given");for(const Q of G)if(!X[Q])throw new Error(`${W.find(ie=>ie.name===Q)?.label||Q} is required`)}else if(D==="databricks"){if(!X.host)throw new Error("Host is required");if(!X.path)throw new Error("HTTP Path is required")}K={name:H,type:D,[mr[D]]:tl(D,X)}}await n(K),M()},I=()=>{g([...h,{name:"",dbType:"postgres"}])},R=F=>{g(h.filter((N,H)=>H!==F))},_=(F,N)=>{const H=[...h];H[F]={...H[F],dbType:N},g(H)},$=(F,N)=>{const H=e.duckdbConnection?.attachedDatabases;if(!H||!H[F])return"";const D=H[F],W=Ks[D.type||""];return W&&D[W]?D[W][N]??"":""},B=F=>{const N=e.ducklakeConnection;if(!N)return"";if(F.startsWith("pg_")){const H=F.replace("pg_","");return N.catalog?.postgresConnection?.[H]??""}if(F==="bucketUrl")return N.storage?.bucketUrl??"";if(F.startsWith("s3_")){const H=F.replace("s3_","");return N.storage?.s3Connection?.[H]??""}if(F.startsWith("gcs_")){const H=F.replace("gcs_","");return N.storage?.gcsConnection?.[H]??""}return""};return t.jsxs(j.Fragment,{children:[t.jsxs(tt,{"aria-label":`Edit connection ${e?.name??""}`.trim(),onClick:F=>{F.preventDefault(),F.stopPropagation(),T()},children:[t.jsx(lo,{children:t.jsx(_t.Edit,{fontSize:"small"})}),t.jsx(co,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:i,onClose:M,title:"Edit connection",description:"Change how packages in this environment reach your database.",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:r,onClick:M,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"connection-form",variant:"contained",loading:r,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:O,id:"connection-form",children:t.jsxs(is,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",type:"text",fullWidth:!0,size:"small",defaultValue:e.name}),t.jsx(c.TextField,{id:"type",name:"type",label:"Connection Type",fullWidth:!0,size:"small",value:a,select:!0,onChange:F=>d(F.target.value),children:nl.map(F=>t.jsx(tt,{value:F,children:F},F))}),a==="ducklake"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Catalog"}),t.jsx(c.TextField,{id:"ducklake_catalogType",label:"Catalog Type",fullWidth:!0,size:"small",value:b,select:!0,onChange:F=>x(F.target.value),children:t.jsx(tt,{value:"postgres",children:"PostgreSQL"})}),b==="postgres"&&t.jsx(t.Fragment,{children:Gt.postgres.map(F=>t.jsx(c.TextField,{id:`ducklake_pg_${F.name}`,name:`ducklake_pg_${F.name}`,label:F.label,type:F.type,fullWidth:!0,size:"small",defaultValue:B(`pg_${F.name}`)},`pg_${F.name}`))})]}),t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsx(c.Typography,{variant:"subtitle2",sx:{mb:2},fontWeight:500,children:"Storage"}),t.jsxs(c.TextField,{id:"ducklake_storageType",label:"Storage Type",fullWidth:!0,size:"small",value:v,select:!0,onChange:F=>C(F.target.value),children:[t.jsx(tt,{value:"s3",children:"S3"}),t.jsx(tt,{value:"gcs",children:"GCS"})]}),t.jsx(c.TextField,{required:!0,id:"ducklake_bucketUrl",name:"ducklake_bucketUrl",label:v==="s3"?"Bucket URL (e.g. s3://my-bucket/path)":"Bucket URL (e.g. gs://my-bucket/path)",type:"text",fullWidth:!0,size:"small",defaultValue:B("bucketUrl")}),v==="s3"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"S3 Credentials"}),kr.filter(F=>F.visibleWhen?k===F.visibleWhen.value:!0).map(F=>t.jsx(c.TextField,{id:`ducklake_s3_${F.name}`,name:`ducklake_s3_${F.name}`,label:F.label,type:F.selectOptions?void 0:F.type,fullWidth:!0,size:"small",required:F.required&&F.name!=="secretAccessKey",select:!!F.selectOptions,defaultValue:F.selectOptions?k:B(`s3_${F.name}`),onChange:F.name==="provider"?N=>S(N.target.value):void 0,placeholder:F.name==="region"?"us-east-1":F.name==="secretAccessKey"&&u.has("ducklakeConnection.storage.s3Connection.secretAccessKey")?"Leave empty to keep existing":void 0,children:F.selectOptions?.map(N=>t.jsx(tt,{value:N.value,children:N.label},N.value))},`s3_${F.name}`))]}),v==="gcs"&&t.jsxs(t.Fragment,{children:[t.jsx(c.Typography,{variant:"caption",sx:{mt:2,mb:1,display:"block"},color:"text.secondary",children:"GCS Credentials"}),Cr.map(F=>t.jsx(c.TextField,{id:`ducklake_gcs_${F.name}`,name:`ducklake_gcs_${F.name}`,label:F.label,type:F.type,fullWidth:!0,size:"small",required:F.required&&F.name!=="secret",defaultValue:B(`gcs_${F.name}`),placeholder:F.name==="secret"&&u.has("ducklakeConnection.storage.gcsConnection.secret")?"Leave empty to keep existing":void 0},`gcs_${F.name}`))]})]})]}):a==="duckdb"?t.jsxs(Ye,{sx:{mt:2},children:[t.jsxs(Ye,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsx(c.Typography,{variant:"subtitle1",fontWeight:500,children:"Attached Databases"}),t.jsx(c.SecondaryButton,{label:"Database",icon:t.jsx(c.AddIcon,{}),onClick:I,ariaLabel:"Add database"})]}),h.length===0&&t.jsx(c.Typography,{variant:"body2",color:"text.secondary",sx:{mb:2},children:'DuckDB connections require at least one attached database. Click "Add Database" to get started.'}),h.map((F,N)=>{const H=es(F.dbType);return t.jsxs(Ye,{sx:{mb:3,p:2,border:"1px solid",borderColor:"divider",borderRadius:1},children:[t.jsxs(Ye,{sx:{display:"flex",justifyContent:"space-between",alignItems:"center",mb:2},children:[t.jsxs(c.Typography,{variant:"subtitle2",children:["Database ",N+1]}),t.jsx(c.IconButton,{"aria-label":`Remove attached database ${N+1}`,onClick:()=>R(N),size:"small",color:"error",children:t.jsx(el,{fontSize:"small"})})]}),t.jsx(c.TextField,{required:!0,id:`attachedDb_${N}_name`,name:`attachedDb_${N}_name`,label:"Database Name",type:"text",fullWidth:!0,size:"small",defaultValue:F.name}),t.jsx(c.TextField,{id:`attachedDb_${N}_type`,name:`attachedDb_${N}_type`,label:"Database Type",fullWidth:!0,size:"small",value:F.dbType,select:!0,onChange:D=>_(N,D.target.value),children:Object.values(q.AttachedDatabaseTypeEnum).map(D=>t.jsx(tt,{value:D,children:D},D))}),H.filter(D=>D.visibleWhen?(F[D.visibleWhen.field]||$(N,D.visibleWhen.field)||H.find(K=>K.name===D.visibleWhen?.field)?.selectOptions?.[0]?.value)===D.visibleWhen.value:!0).map(D=>t.jsx(c.TextField,{id:`attachedDb_${N}_${D.name}`,name:`attachedDb_${N}_${D.name}`,label:D.label,type:D.selectOptions?void 0:D.type,fullWidth:!0,size:"small",required:D.required,select:!!D.selectOptions,defaultValue:$(N,D.name)||D.selectOptions?.[0]?.value,onChange:D.selectOptions?W=>{const K=[...h];K[N]={...K[N],[D.name]:W.target.value},g(K)}:void 0,children:D.selectOptions?.map(W=>t.jsx(tt,{value:W.value,children:W.label},W.value))},D.name))]},N)})]}):Gt[a].map(F=>{const N=e?.[mr[a]??""]?.[F.name??""]??"",H=F.type==="password"||Li.has(F.name),D=u.has(`${mr[a]??""}.${F.name}`),W=F.selectOptions?N===""||N===void 0?F.selectOptions[0]?.value:String(N):void 0;return t.jsx(c.TextField,{id:F.name,name:F.name,label:F.label,type:F.type,fullWidth:!0,size:"small",required:F.required&&!H&&!N,select:!!F.selectOptions,defaultValue:F.selectOptions?W:N,placeholder:D?"Leave empty to keep existing":void 0,helperText:H?D?"Stored value is not shown. Leave empty to keep it.":"No value stored.":void 0,children:F.selectOptions?.map(K=>t.jsx(tt,{value:K.value,children:K.label},K.value))},F.name)})]})})})]})}function _i(e,n){return!e||e.type!=="duckdb"?!1:(e.duckdbConnection?.attachedDatabases||[]).some(s=>s.type==="azure"&&s.name===n)}function ph(e){return e.startsWith("gs://")||e.startsWith("s3://")||e.startsWith("https://")||e.startsWith("abfss://")||e.startsWith("az://")}function rl({connectionName:e,resourceUri:n,schema:r,connection:s}){const{apiClients:i}=q.useServer(),{environmentName:l}=c.parseResourceUri(n),[a,d]=j.useState(null),[u,h]=j.useState(r||null),[g,b]=j.useState(!1),{data:x,isError:v,isLoading:C,error:k}=c.useQueryWithApiError({queryKey:["schemas",l,e],queryFn:()=>i.connections.listSchemas(l,e)}),S=x?.data||[];return t.jsxs(m.Grid,{container:!0,spacing:1,children:[!r&&t.jsx(m.Grid,{size:{xs:12,md:4},children:t.jsxs(m.Paper,{sx:{p:1,m:0},children:[t.jsxs(m.Box,{sx:{display:"flex",alignItems:"center",justifyContent:"space-between",mb:0},children:[t.jsx(m.Typography,{variant:"overline",fontWeight:"bold",children:"Table Paths"}),t.jsx(m.FormControlLabel,{control:t.jsx(m.Switch,{checked:g,onChange:T=>b(T.target.checked)}),label:"Hidden Schemas"})]}),t.jsx(m.Divider,{sx:{mt:"2px"}}),t.jsxs(m.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[C&&t.jsx(c.Loading,{text:"Loading schemas..."}),v&&t.jsx(c.ApiErrorDisplay,{error:k,context:`${l} > ${e} > Schemas`}),!C&&!v&&S.length===0&&t.jsx(m.Typography,{variant:"body2",children:"No Schemas"}),!C&&!v&&S.length>0&&t.jsx(m.List,{dense:!0,disablePadding:!0,children:S.map(T=>{const M=T.name;if(T.isHidden&&!g)return null;const I=u===M;return t.jsx(m.ListItemButton,{selected:I,onClick:()=>{h(M),d(null)},children:t.jsx(m.ListItemText,{primary:M})},M)})})]})]})}),t.jsx(m.Grid,{size:{xs:12,md:r?6:4},children:u&&t.jsx(m.Paper,{sx:{p:1,m:0},children:t.jsx(yh,{connectionName:e,schemaName:u,onTableSelect:T=>{d(T)},resourceUri:n,connection:s})})}),t.jsx(m.Grid,{size:{xs:12,md:r?6:4},children:u&&a&&t.jsx(mh,{environmentName:l,connectionName:e,schemaName:u,tableResource:a})})]})}function mh({environmentName:e,connectionName:n,schemaName:r,tableResource:s}){const{apiClients:i}=q.useServer(),{data:l,isLoading:a,isError:d,error:u}=c.useQueryWithApiError({queryKey:["connectionTableDetail",e,n,r,s],queryFn:()=>i.connections.getTable(e,n,r,s),enabled:!!r&&!!s}),h={resource:l?.data?.resource??s,columns:l?.data?.columns??[]};return t.jsxs(m.Paper,{sx:{p:1,m:0},children:[d&&t.jsx(c.ApiErrorDisplay,{error:u,context:`${e} > ${n} > ${r} > ${s}`}),!d&&t.jsx(gh,{table:h,loading:a})]})}function gh({table:e,loading:n}){return n?t.jsx(c.Loading,{text:"Loading columns..."}):t.jsxs(t.Fragment,{children:[t.jsxs(m.Typography,{variant:"overline",fontWeight:"bold",sx:{display:"block",wordBreak:"break-all"},children:[e.resource.includes("://")||/\.(parquet|csv|json|tsv|ndjson)$/i.test(e.resource)?"File":"Table",": ",e.resource]}),t.jsx(m.Divider,{}),t.jsx(m.Box,{sx:{mt:"10px",maxHeight:"600px",overflowY:"auto"},children:t.jsx(m.TableContainer,{children:t.jsxs(m.Table,{size:"small",sx:{"& .MuiTableCell-root":{padding:"10px"}},children:[t.jsx(m.TableHead,{children:t.jsxs(m.TableRow,{children:[t.jsx(m.TableCell,{children:"NAME"}),t.jsx(m.TableCell,{children:"TYPE"})]})}),t.jsx(m.TableBody,{children:e.columns?.sort((r,s)=>r.name.localeCompare(s.name))?.map(r=>t.jsxs(m.TableRow,{children:[t.jsx(m.TableCell,{children:r.name}),t.jsx(m.TableCell,{children:r.type})]},r.name))})]})})})]})}function yh({connectionName:e,schemaName:n,onTableSelect:r,resourceUri:s,connection:i}){const{environmentName:l}=c.parseResourceUri(s),{apiClients:a}=q.useServer(),[d,u]=j.useState(""),{data:h,isSuccess:g,isError:b,error:x,isLoading:v}=c.useQueryWithApiError({queryKey:["tablesInSchema",l,e,n],queryFn:()=>a.connections.listTables(l,e,n)}),C=_i(i,n),k=T=>C?T:T.split(".").pop()||T,S=g&&h?.data?h.data.filter(T=>k(T.resource).toLowerCase().includes(d.toLowerCase())).sort((T,M)=>k(T.resource).localeCompare(k(M.resource))):[];return t.jsxs(t.Fragment,{children:[t.jsx(m.Typography,{variant:"overline",fontWeight:"bold",children:ph(n)||_i(i,n)?`Files in ${n}`:`Tables in ${n}`}),t.jsx(m.Divider,{}),t.jsx(m.Box,{sx:{mt:1,mb:1},children:t.jsx(m.TextField,{size:"small",fullWidth:!0,placeholder:"Search tables...",value:d,onChange:T=>u(T.target.value),variant:"outlined"})}),t.jsx(m.Divider,{}),t.jsxs(m.Box,{sx:{mt:"2px",maxHeight:"600px",overflowY:"auto"},children:[v&&t.jsx(c.Loading,{text:"Fetching Tables..."}),b&&t.jsx(c.ApiErrorDisplay,{error:x,context:`${l} > ${e} > ${n}`}),g&&S.length===0&&t.jsx(m.Typography,{variant:"body2",children:"No Tables"}),g&&h?.data&&h.data.length>0&&t.jsx(m.List,{dense:!0,disablePadding:!0,children:S.map(T=>{let M=k(T.resource);return!C&&T.resource.includes("://")&&(M=T.resource.split("/").pop()||T.resource),t.jsx(m.ListItemButton,{onClick:()=>r(T.resource),children:t.jsx(m.ListItemText,{primary:M,secondary:T.columns.length>0?`${T.columns.length} columns`:void 0})},T.resource)})})]})]})}const xh={bigquery:"BigQuery",snowflake:"Snowflake",postgres:"PostgreSQL",mysql:"MySQL",sqlserver:"SQL Server",trino:"Trino",databricks:"Databricks",duckdb:"DuckDB",ducklake:"DuckLake",s3:"S3",gcs:"GCS",azure:"Azure"};function vh(e){return e?xh[e]??e:""}function bh({resourceUri:e}){const{apiClients:n,mutable:r}=q.useServer(),s=yt.useQueryClient(),{environmentName:i}=c.parseResourceUri(e),[l,a]=j.useState(""),[d,u]=j.useState(null),h=c.encodeResourceUri({environmentName:i,connectionName:d}),{data:g,isSuccess:b,isError:x,error:v}=c.useQueryWithApiError({queryKey:["connections",i],queryFn:()=>n.connections.listConnections(i)}),C=c.useMutationWithApiError({mutationFn:Ht("connection","create",O=>n.environments.updateEnvironment(i,{name:i,connections:[...g.data,O]})),onSuccess(){a("Connection added successfully"),s.invalidateQueries({queryKey:["connections",i]})},onError(O){a(O.message)}}),k=c.useMutationWithApiError({mutationFn:Ht("connection","update",O=>n.environments.updateEnvironment(i,{name:i,connections:g.data.map(I=>I.name===O.name?O:I)})),onSuccess(O,I){a(`Connection ${I.name} updated successfully`),s.invalidateQueries({queryKey:["connections",i]})},onError(O){a(O.message)}}),S=c.useMutationWithApiError({mutationFn:Ht("connection","delete",O=>{if(!O.name)throw new Error("Cannot delete a connection with no name");return n.connections.deleteConnection(i,O.name)}),onSuccess(O,I){a(`Connection ${I.name} deleted successfully`),s.invalidateQueries({queryKey:["connections",i]})},onError(O){a(O.message)}}),T=b?[...g.data].sort((O,I)=>(O.name??"").localeCompare(I.name??"")):[],M=C.isPending||k.isPending||S.isPending;return t.jsxs(Pt,{title:"Connections",...b?{count:T.length}:{},description:"Database connections available to packages in this environment",...r&&b?{action:t.jsx(dh,{onSubmit:O=>C.mutateAsync(O),isSubmitting:C.isPending})}:{},children:[!b&&!x&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"Fetching Connections..."}),x&&t.jsx(c.ApiErrorDisplay,{error:v,context:`${i} > Connections`}),b&&T.length===0&&t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"No connections yet."}),b&&T.length>0&&t.jsx(m.Stack,{children:T.map(O=>t.jsx(wh,{connection:O,mutable:r,isMutating:M,onOpenExplorer:()=>u(O.name??null),onEdit:I=>k.mutateAsync(I),onDelete:I=>S.mutateAsync(I)},O.name))}),t.jsx(m.Snackbar,{open:l!=="",autoHideDuration:6e3,onClose:()=>a(""),message:l}),t.jsx(c.AppDialog,{open:d!==null,onClose:()=>u(null),maxWidth:"lg",title:`Connection explorer: ${d??""}`,showClose:!0,children:d&&t.jsx(rl,{resourceUri:h,connectionName:d,connection:g?.data?.find(O=>O.name===d)})})]})}function wh({connection:e,mutable:n,isMutating:r,onOpenExplorer:s,onEdit:i,onDelete:l}){const[a,d]=j.useState(null),u=!!a,h=b=>{b.stopPropagation(),d(b.currentTarget)},g=()=>d(null);return t.jsx(os,{icon:t.jsx(Kd,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.connection,label:e.name??"",ariaLabel:e.name??"",description:vh(e.type),onClick:s,...n?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(m.IconButton,{size:"small",onClick:h,"aria-label":`Connection actions for ${e.name??""}`.trim(),children:t.jsx(_t.MoreVert,{fontSize:"small"})}),t.jsxs(m.Menu,{anchorEl:a,open:u,onClose:g,onClick:b=>b.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[t.jsx(fh,{connection:e,onSubmit:i,isSubmitting:r,onCloseDialog:g}),t.jsx(hh,{connection:e,onCloseDialog:g,isMutating:r,onDelete:()=>l(e)})]})]})}:{}})}const Sh=c.createSvgIcon([t.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"),t.jsx("path",{d:"M9 12h6v2H9z"},"1")]);function kh({resourceUri:e,onCloseDialog:n}){const[r,s]=j.useState(!1),{apiClients:i}=q.useServer(),l=()=>{s(!0)},a=()=>{s(!1),n()},{environmentName:d,packageName:u}=c.parseResourceUri(e),h=Pn({mutationFn:()=>i.packages.deletePackage(d,u),success:"Package deleted",invalidates:[["packages",d]],closeDialog:a,resource:"package",action:"delete"});return t.jsxs(j.Fragment,{children:[t.jsxs(m.MenuItem,{onClick:l,children:[t.jsx(m.ListItemIcon,{children:t.jsx(_t.Delete,{fontSize:"small"})}),t.jsx(m.ListItemText,{children:"Delete"})]}),t.jsx(c.AppDialog,{open:r,onClose:a,title:"Delete package",actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{onClick:a,children:"Cancel"}),t.jsx(c.Button,{variant:"contained",color:"error",autoFocus:!0,onClick:()=>h.mutate(),loading:h.isPending,children:"Delete package"})]}),children:t.jsxs(c.Typography,{variant:"body2",children:["Delete ",t.jsx("strong",{children:u}),"? The package stops being served and this cannot be undone."]})}),h.notice]})}function Ch({package:e,resourceUri:n,onCloseDialog:r}){const[s,i]=j.useState(!1),{apiClients:l}=q.useServer(),a=()=>{i(!0)},d=()=>{i(!1),r()},{packageName:u,environmentName:h}=c.parseResourceUri(n),g=Pn({mutationFn(x){return l.packages.updatePackage(h,u,{name:u,description:x.description})},success:"Package updated",invalidates:[["packages",h]],closeDialog:d,resource:"package",action:"update"}),b=x=>{x.preventDefault();const C=new FormData(x.currentTarget).get("description")?.toString();g.mutate({description:C})};return t.jsxs(j.Fragment,{children:[t.jsxs(m.MenuItem,{onClick:a,children:[t.jsx(m.ListItemIcon,{children:t.jsx(_t.Edit,{fontSize:"small"})}),t.jsx(m.ListItemText,{children:"Edit"})]}),t.jsx(c.AppDialog,{open:s,onClose:d,title:"Edit package",description:`What ${e.name} is, for the people who open it.`,actions:t.jsxs(t.Fragment,{children:[t.jsx(c.Button,{disabled:g.isPending,onClick:d,children:"Cancel"}),t.jsx(c.Button,{type:"submit",form:"package-form",variant:"contained",loading:g.isPending,children:"Save changes"})]}),children:t.jsx("form",{onSubmit:b,id:"package-form",children:t.jsxs(m.Stack,{sx:{gap:2},children:[t.jsx(c.TextField,{autoFocus:!0,required:!0,id:"name",name:"name",label:"Name",disabled:!0,type:"text",fullWidth:!0,size:"small",defaultValue:e.name,InputLabelProps:{shrink:!0}}),t.jsx(c.TextField,{id:"description",name:"description",label:"Description",multiline:!0,fullWidth:!0,rows:4,size:"small",defaultValue:e.description,InputLabelProps:{shrink:!0}})]})})}),g.notice]})}function sl({onSelectPackage:e,resourceUri:n}){const{apiClients:r}=q.useServer(),{environmentName:s}=c.parseResourceUri(n),{data:i,isSuccess:l,isError:a,error:d}=c.useQueryWithApiError({queryKey:["packages",s],queryFn:()=>r.packages.listPackages(s)});if(a)return t.jsx(c.ApiErrorDisplay,{error:d,context:`${s} > Packages`});if(!l)return t.jsx(c.Loading,{text:"Fetching Packages..."});const u=[...i.data].sort((h,g)=>h.name.localeCompare(g.name));return t.jsx(m.Stack,{children:u.map(h=>{const g=c.encodeResourceUri({environmentName:s,packageName:h.name});return t.jsx(jh,{pkg:h,packageResourceUri:g,onSelectPackage:e},h.name)})})}function jh({pkg:e,packageResourceUri:n,onSelectPackage:r}){const{mutable:s}=q.useServer(),i=e.versionId!==void 0||e.latestVersion!==void 0,[l,a]=j.useState(null),d=!!l,u=g=>{g.stopPropagation(),a(g.currentTarget)},h=()=>a(null);return t.jsx(os,{icon:t.jsx(Sh,{sx:{fontSize:18}}),tint:q.SURFACE_TINT.package,label:e.name,ariaLabel:e.name,...e.description?{description:e.description}:{},onClick:g=>r(e.name,g),...s?{trailingAction:t.jsxs(t.Fragment,{children:[t.jsx(m.IconButton,{size:"small",onClick:u,"aria-label":`Package actions for ${e.name}`,children:t.jsx(_t.MoreVert,{fontSize:"small"})}),t.jsxs(m.Menu,{anchorEl:l,open:d,onClose:h,onClick:g=>g.stopPropagation(),anchorOrigin:{vertical:"bottom",horizontal:"right"},transformOrigin:{vertical:"top",horizontal:"right"},children:[!i&&t.jsx(Ch,{package:e,resourceUri:n,onCloseDialog:h}),t.jsx(kh,{resourceUri:n,onCloseDialog:h})]})]})}:{}})}function Th({onSelectPackage:e,resourceUri:n}){const{apiClients:r,mutable:s}=q.useServer(),{environmentName:i}=c.parseResourceUri(n),l=c.useQueryWithApiError({queryKey:["packages",i],queryFn:()=>r.packages.listPackages(i)});return j.useEffect(()=>{window.scrollTo({top:0,behavior:"auto"})},[]),t.jsxs(m.Container,{maxWidth:!1,sx:{maxWidth:1024,mx:"auto",px:3,py:6},children:[t.jsxs(m.Box,{sx:{mb:4},children:[t.jsx(m.Typography,{variant:"h4",component:"h1",sx:{fontWeight:600,letterSpacing:"-0.025em",mb:.5},children:i}),t.jsx(m.Typography,{variant:"body2",color:"text.secondary",children:"Manage packages and database connections in this environment. Open a package to explore its models and notebooks."})]}),t.jsx(Pt,{title:"Packages",...l.isSuccess?{count:l.data.data.length}:{},description:"Published packages available for use in this environment",...s?{action:t.jsx(Yd,{resourceUri:n})}:{},children:t.jsx(sl,{onSelectPackage:e,resourceUri:n})}),t.jsx(bh,{resourceUri:n}),t.jsx($d,{resourceUri:n})]})}function zi({array1:e,array2:n,parser:r=s=>s}){return e&&n&&e.length===n.length&&e.every((s,i)=>r(s)===r(n[i]))}function Wi(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"")}function Mh(e={}){const{ignoreAccents:n=!0,ignoreCase:r=!0,limit:s,matchFrom:i="any",stringify:l,trim:a=!1}=e;return(d,{inputValue:u,getOptionLabel:h})=>{let g=a?u.trim():u;r&&(g=g.toLowerCase()),n&&(g=Wi(g));const b=g?d.filter(x=>{let v=(l||h)(x);return r&&(v=v.toLowerCase()),n&&(v=Wi(v)),i==="start"?v.startsWith(g):v.includes(g)}):d;return typeof s=="number"?b.slice(0,s):b}}const Oh=Mh(),qi=5,Ih=e=>e.current!==null&&e.current.parentElement?.contains(document.activeElement),Eh=[];function Bi(e,n,r,s){if(n||e==null||s)return"";const i=r(e);return typeof i=="string"?i:""}function Dh(e){const{unstable_isActiveElementInListbox:n=Ih,unstable_classNamePrefix:r="Mui",autoComplete:s=!1,autoHighlight:i=!1,autoSelect:l=!1,blurOnSelect:a=!1,clearOnBlur:d=!e.freeSolo,clearOnEscape:u=!1,componentName:h="useAutocomplete",defaultValue:g=e.multiple?Eh:null,disableClearable:b=!1,disableCloseOnSelect:x=!1,disabled:v,disabledItemsFocusable:C=!1,disableListWrap:k=!1,filterOptions:S=Oh,filterSelectedOptions:T=!1,freeSolo:M=!1,getOptionDisabled:O,getOptionKey:I,getOptionLabel:R=U=>U.label??U,groupBy:_,handleHomeEndKeys:$=!e.freeSolo,id:B,includeInputInList:F=!1,inputValue:N,isOptionEqualToValue:H=(U,V)=>U===V,multiple:D=!1,onChange:W,onClose:K,onHighlightChange:J,onInputChange:X,onOpen:G,open:Q,openOnFocus:ie=!1,options:z,readOnly:re=!1,renderValue:se,selectOnFocus:ne=!e.freeSolo,value:Me}=e,oe=c.useId(B);let ue=R;ue=U=>{const V=R(U);return typeof V!="string"?String(V):V};const De=we.useRef(!1),Ne=we.useRef(!0),ae=we.useRef(null),Z=we.useRef(null),[ce,be]=we.useState(null),[ge,he]=we.useState(-1),ye=i?0:-1,Fe=we.useRef(ye),ze=we.useRef(Bi(g??Me,D,ue)).current,[me,Y]=c.useControlled({controlled:Me,default:g,name:h}),[le,Oe]=c.useControlled({controlled:N,default:ze,name:h,state:"inputValue"}),[Re,at]=we.useState(!1),Ie=we.useCallback((U,V,de)=>{if(!(D?me.length<V.length:V!==null)&&!d)return;const te=Bi(V,D,ue,se);le!==te&&(Oe(te),X&&X(U,te,de))},[ue,le,D,X,Oe,d,me,se]),[lt,xt]=c.useControlled({controlled:Q,default:!1,name:h,state:"open"}),[vt,Mt]=we.useState(!0),mt=!D&&me!=null&&le===ue(me),Ke=lt&&!re,fe=Ke?S(z.filter(U=>!(T&&(D?me:[me]).some(V=>V!==null&&H(U,V)))),{inputValue:mt&&vt?"":le,getOptionLabel:ue}):[],Qe=hd({filteredOptions:fe,value:me,inputValue:le});we.useEffect(()=>{const U=me!==Qe.value;Re&&!U||M&&!U||Ie(null,me,"reset")},[me,Ie,Re,Qe.value,M]);const qe=lt&&fe.length>0&&!re,ct=c.useEventCallback(U=>{if(U===-1)ae.current.focus();else{const V=se?"data-item-index":"data-tag-index";ce.querySelector(`[${V}="${U}"]`).focus()}});we.useEffect(()=>{D&&ge>me.length-1&&(he(-1),ct(-1))},[me,D,ge,ct]);function ut(U,V){if(!Z.current||U<0||U>=fe.length)return-1;let de=U;for(;;){const ve=Z.current.querySelector(`[data-option-index="${de}"]`),te=C?!1:!ve||ve.disabled||ve.getAttribute("aria-disabled")==="true";if(ve&&ve.hasAttribute("tabindex")&&!te)return de;if(V==="next"?de=(de+1)%fe.length:de=(de-1+fe.length)%fe.length,de===U)return-1}}const Ze=c.useEventCallback(({event:U,index:V,reason:de})=>{if(Fe.current=V,V===-1?ae.current.removeAttribute("aria-activedescendant"):ae.current.setAttribute("aria-activedescendant",`${oe}-option-${V}`),J&&["mouse","keyboard","touch"].includes(de)&&J(U,V===-1?null:fe[V],de),!Z.current)return;const ve=Z.current.querySelector(`[role="option"].${r}-focused`);ve&&(ve.classList.remove(`${r}-focused`),ve.classList.remove(`${r}-focusVisible`));let te=Z.current;if(Z.current.getAttribute("role")!=="listbox"&&(te=Z.current.parentElement.querySelector('[role="listbox"]')),!te)return;if(V===-1){te.scrollTop=0;return}const Ve=Z.current.querySelector(`[data-option-index="${V}"]`);if(Ve&&(Ve.classList.add(`${r}-focused`),de==="keyboard"&&Ve.classList.add(`${r}-focusVisible`),te.scrollHeight>te.clientHeight&&de!=="mouse"&&de!=="touch")){const Ge=Ve,Ct=te.clientHeight+te.scrollTop,vn=Ge.offsetTop+Ge.offsetHeight;vn>Ct?te.scrollTop=vn-te.clientHeight:Ge.offsetTop-Ge.offsetHeight*(_?1.3:0)<te.scrollTop&&(te.scrollTop=Ge.offsetTop-Ge.offsetHeight*(_?1.3:0))}}),pe=c.useEventCallback(({event:U,diff:V,direction:de="next",reason:ve})=>{if(!Ke)return;const Ve=ut((()=>{const Ge=fe.length-1;if(V==="reset")return ye;if(V==="start")return 0;if(V==="end")return Ge;const Ct=Fe.current+V;return Ct<0?Ct===-1&&F?-1:k&&Fe.current!==-1||Math.abs(V)>1?0:Ge:Ct>Ge?Ct===Ge+1&&F?-1:k||Math.abs(V)>1?Ge:0:Ct})(),de);if(Ze({index:Ve,reason:ve,event:U}),s&&V!=="reset")if(Ve===-1)ae.current.value=le;else{const Ge=ue(fe[Ve]);ae.current.value=Ge,Ge.toLowerCase().indexOf(le.toLowerCase())===0&&le.length>0&&ae.current.setSelectionRange(le.length,Ge.length)}}),Ue=!zi({array1:Qe.filteredOptions,array2:fe,parser:ue}),bt=()=>{const U=(V,de)=>{const ve=V?ue(V):"",te=de?ue(de):"";return ve===te};if(Fe.current!==-1&&!zi({array1:Qe.filteredOptions,array2:fe,parser:ue})&&Qe.inputValue===le&&(D?me.length===Qe.value.length&&Qe.value.every((V,de)=>ue(me[de])===ue(V)):U(Qe.value,me))){const V=Qe.filteredOptions[Fe.current];if(V)return fe.findIndex(de=>ue(de)===ue(V))}return-1},Ce=we.useCallback(()=>{if(!Ke)return;const U=bt();if(U!==-1){Fe.current=U;return}const V=D?me[0]:me;if(fe.length===0||V==null){pe({diff:"reset"});return}if(Z.current){if(V!=null){const de=fe[Fe.current];if(D&&de&&me.findIndex(te=>H(de,te))!==-1)return;const ve=fe.findIndex(te=>H(te,V));ve===-1?pe({diff:"reset"}):Ze({index:ve});return}if(Fe.current>=fe.length-1){Ze({index:fe.length-1});return}Ze({index:Fe.current})}},[fe.length,D?!1:me,T,pe,Ze,Ke,le,D]),Le=c.useEventCallback(U=>{c.setRef(Z,U),U&&Ce()});we.useEffect(()=>{Ue&&Ce()},[Ce,Ue]);const Ee=U=>{lt||(xt(!0),Mt(!0),G&&G(U))},Be=(U,V)=>{lt&&(xt(!1),K&&K(U,V))},ht=(U,V,de,ve)=>{if(D){if(me.length===V.length&&me.every((te,Ve)=>te===V[Ve]))return}else if(me===V)return;W&&W(U,V,de,ve),Y(V)},We=we.useRef(!1),nt=(U,V,de="selectOption",ve="options")=>{let te=de,Ve=V;if(D){Ve=Array.isArray(me)?me.slice():[];const Ge=Ve.findIndex(Ct=>H(V,Ct));Ge===-1?Ve.push(V):ve!=="freeSolo"&&(Ve.splice(Ge,1),te="removeOption")}Ie(U,Ve,te),ht(U,Ve,te,{option:V}),!x&&(!U||!U.ctrlKey&&!U.metaKey)&&Be(U,te),(a===!0||a==="touch"&&We.current||a==="mouse"&&!We.current)&&ae.current.blur()};function Ot(U,V){if(U===-1)return-1;let de=U;for(;;){if(V==="next"&&de===me.length||V==="previous"&&de===-1)return-1;const ve=se?"data-item-index":"data-tag-index",te=ce.querySelector(`[${ve}="${de}"]`);if(!te||!te.hasAttribute("tabindex")||te.disabled||te.getAttribute("aria-disabled")==="true")de+=V==="next"?1:-1;else return de}}const kt=(U,V)=>{if(!D)return;le===""&&Be(U,"toggleInput");let de=ge;ge===-1?le===""&&V==="previous"&&(de=me.length-1):(de+=V==="next"?1:-1,de<0&&(de=0),de===me.length&&(de=-1)),de=Ot(de,V),he(de),ct(de)},$t=U=>{De.current=!0,Oe(""),X&&X(U,"","clear"),ht(U,D?[]:null,"clear")},gn=U=>V=>{if(U.onKeyDown&&U.onKeyDown(V),!V.defaultMuiPrevented&&(ge!==-1&&!["ArrowLeft","ArrowRight"].includes(V.key)&&(he(-1),ct(-1)),V.which!==229))switch(V.key){case"Home":Ke&&$&&(V.preventDefault(),pe({diff:"start",direction:"next",reason:"keyboard",event:V}));break;case"End":Ke&&$&&(V.preventDefault(),pe({diff:"end",direction:"previous",reason:"keyboard",event:V}));break;case"PageUp":V.preventDefault(),pe({diff:-qi,direction:"previous",reason:"keyboard",event:V}),Ee(V);break;case"PageDown":V.preventDefault(),pe({diff:qi,direction:"next",reason:"keyboard",event:V}),Ee(V);break;case"ArrowDown":V.preventDefault(),pe({diff:1,direction:"next",reason:"keyboard",event:V}),Ee(V);break;case"ArrowUp":V.preventDefault(),pe({diff:-1,direction:"previous",reason:"keyboard",event:V}),Ee(V);break;case"ArrowLeft":!D&&se?ct(0):kt(V,"previous");break;case"ArrowRight":!D&&se?ct(-1):kt(V,"next");break;case"Enter":if(Fe.current!==-1&&Ke){const de=fe[Fe.current],ve=O?O(de):!1;if(V.preventDefault(),ve)return;nt(V,de,"selectOption"),s&&ae.current.setSelectionRange(ae.current.value.length,ae.current.value.length)}else M&&le!==""&&mt===!1&&(D&&V.preventDefault(),nt(V,le,"createOption","freeSolo"));break;case"Escape":Ke?(V.preventDefault(),V.stopPropagation(),Be(V,"escape")):u&&(le!==""||D&&me.length>0||se)&&(V.preventDefault(),V.stopPropagation(),$t(V));break;case"Backspace":if(D&&!re&&le===""&&me.length>0){const de=ge===-1?me.length-1:ge,ve=me.slice();ve.splice(de,1),ht(V,ve,"removeOption",{option:me[de]})}!D&&se&&!re&&(Y(null),ct(-1));break;case"Delete":if(D&&!re&&le===""&&me.length>0&&ge!==-1){const de=ge,ve=me.slice();ve.splice(de,1),ht(V,ve,"removeOption",{option:me[de]})}!D&&se&&!re&&(Y(null),ct(-1));break}},_e=U=>{at(!0),ie&&!De.current&&Ee(U)},dt=U=>{if(n(Z)){ae.current.focus();return}at(!1),Ne.current=!0,De.current=!1,l&&Fe.current!==-1&&Ke?nt(U,fe[Fe.current],"blur"):l&&M&&le!==""?nt(U,le,"blur","freeSolo"):d&&Ie(U,me,"blur"),Be(U,"blur")},Kt=U=>{const V=U.target.value;le!==V&&(Oe(V),Mt(!1),X&&X(U,V,"input")),V===""?!b&&!D&&ht(U,null,"clear"):Ee(U)},yn=U=>{const V=Number(U.currentTarget.getAttribute("data-option-index"));Fe.current!==V&&Ze({event:U,index:V,reason:"mouse"})},ft=U=>{Ze({event:U,index:Number(U.currentTarget.getAttribute("data-option-index")),reason:"touch"}),We.current=!0},en=U=>{const V=Number(U.currentTarget.getAttribute("data-option-index"));nt(U,fe[V],"selectOption"),We.current=!1},xn=U=>V=>{const de=me.slice();de.splice(U,1),ht(V,de,"removeOption",{option:me[U]})},Qt=U=>{ht(U,null,"removeOption",{option:me})},Xe=U=>{lt?Be(U,"toggleInput"):Ee(U)},Je=U=>{U.currentTarget.contains(U.target)&&U.target.getAttribute("id")!==oe&&U.preventDefault()},Rt=U=>{U.currentTarget.contains(U.target)&&(ae.current.focus(),ne&&Ne.current&&ae.current.selectionEnd-ae.current.selectionStart===0&&ae.current.select(),Ne.current=!1)},tn=U=>{!v&&(le===""||!lt)&&Xe(U)};let Zt=M&&le.length>0;Zt=Zt||(D?me.length>0:me!==null);let nn=fe;return _&&(nn=fe.reduce((U,V,de)=>{const ve=_(V);return U.length>0&&U[U.length-1].group===ve?U[U.length-1].options.push(V):U.push({key:de,index:de,group:ve,options:[V]}),U},[])),v&&Re&&dt(),{getRootProps:(U={})=>({...U,onKeyDown:gn(U),onMouseDown:Je,onClick:Rt}),getInputLabelProps:()=>({id:`${oe}-label`,htmlFor:oe}),getInputProps:()=>({id:oe,value:le,onBlur:dt,onFocus:_e,onChange:Kt,onMouseDown:tn,"aria-activedescendant":Ke?"":null,"aria-autocomplete":s?"both":"list","aria-controls":qe?`${oe}-listbox`:void 0,"aria-expanded":qe,autoComplete:"off",ref:ae,autoCapitalize:"none",spellCheck:"false",role:"combobox",disabled:v}),getClearProps:()=>({tabIndex:-1,type:"button",onClick:$t}),getItemProps:({index:U=0}={})=>({...D&&{key:U},...se?{"data-item-index":U}:{"data-tag-index":U},tabIndex:-1,...!re&&{onDelete:D?xn(U):Qt}}),getPopupIndicatorProps:()=>({tabIndex:-1,type:"button",onClick:Xe}),getTagProps:({index:U})=>({key:U,"data-tag-index":U,tabIndex:-1,...!re&&{onDelete:xn(U)}}),getListboxProps:()=>({role:"listbox",id:`${oe}-listbox`,"aria-labelledby":`${oe}-label`,ref:Le,onMouseDown:U=>{U.preventDefault()}}),getOptionProps:({index:U,option:V})=>{const de=(D?me:[me]).some(te=>te!=null&&H(V,te)),ve=O?O(V):!1;return{key:I?.(V)??ue(V),tabIndex:-1,role:"option",id:`${oe}-option-${U}`,onMouseMove:yn,onClick:en,onTouchStart:ft,"data-option-index":U,"aria-disabled":ve,"aria-selected":de}},id:oe,inputValue:le,value:me,dirty:Zt,expanded:Ke&&ce,popupOpen:Ke,focused:Re||ge!==-1,anchorEl:ce,setAnchorEl:be,focusedItem:ge,focusedTag:ge,groupedOptions:nn}}function Fh(e){return c.generateUtilityClass("MuiListSubheader",e)}c.generateUtilityClasses("MuiListSubheader",["root","colorPrimary","colorInherit","gutters","inset","sticky"]);const $h=e=>{const{classes:n,color:r,disableGutters:s,inset:i,disableSticky:l}=e,a={root:["root",r!=="default"&&`color${c.capitalize(r)}`,!s&&"gutters",i&&"inset",!l&&"sticky"]};return c.composeClasses(a,Fh,n)},Rh=c.styled("li",{name:"MuiListSubheader",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.root,r.color!=="default"&&n[`color${c.capitalize(r.color)}`],!r.disableGutters&&n.gutters,r.inset&&n.inset,!r.disableSticky&&n.sticky]}})(c.memoTheme(({theme:e})=>({boxSizing:"border-box",lineHeight:"48px",listStyle:"none",color:(e.vars||e).palette.text.secondary,fontFamily:e.typography.fontFamily,fontWeight:e.typography.fontWeightMedium,fontSize:e.typography.pxToRem(14),variants:[{props:{color:"primary"},style:{color:(e.vars||e).palette.primary.main}},{props:{color:"inherit"},style:{color:"inherit"}},{props:({ownerState:n})=>!n.disableGutters,style:{paddingLeft:16,paddingRight:16}},{props:({ownerState:n})=>n.inset,style:{paddingLeft:72}},{props:({ownerState:n})=>!n.disableSticky,style:{position:"sticky",top:0,zIndex:1,backgroundColor:(e.vars||e).palette.background.paper}}]}))),Qs=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiListSubheader"}),{className:i,color:l="default",component:a="li",disableGutters:d=!1,disableSticky:u=!1,inset:h=!1,...g}=s,b={...s,color:l,component:a,disableGutters:d,disableSticky:u,inset:h},x=$h(b);return t.jsx(Rh,{as:a,className:c.clsx(x.root,i),ref:r,ownerState:b,...g})});Qs&&(Qs.muiSkipListHighlight=!0);const Ah=c.createSvgIcon(t.jsx("path",{d:"M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"}));function Lh(e){return c.generateUtilityClass("MuiAutocomplete",e)}const Te=c.generateUtilityClasses("MuiAutocomplete",["root","expanded","fullWidth","focused","focusVisible","tag","tagSizeSmall","tagSizeMedium","hasPopupIcon","hasClearIcon","inputRoot","input","inputFocused","endAdornment","clearIndicator","popupIndicator","popupIndicatorOpen","popper","popperDisablePortal","paper","listbox","loading","noOptions","option","groupLabel","groupUl"]);var Vi,Hi;const Nh=e=>{const{classes:n,disablePortal:r,expanded:s,focused:i,fullWidth:l,hasClearIcon:a,hasPopupIcon:d,inputFocused:u,popupOpen:h,size:g}=e,b={root:["root",s&&"expanded",i&&"focused",l&&"fullWidth",a&&"hasClearIcon",d&&"hasPopupIcon"],inputRoot:["inputRoot"],input:["input",u&&"inputFocused"],tag:["tag",`tagSize${c.capitalize(g)}`],endAdornment:["endAdornment"],clearIndicator:["clearIndicator"],popupIndicator:["popupIndicator",h&&"popupIndicatorOpen"],popper:["popper",r&&"popperDisablePortal"],paper:["paper"],listbox:["listbox"],loading:["loading"],noOptions:["noOptions"],option:["option"],groupLabel:["groupLabel"],groupUl:["groupUl"]};return c.composeClasses(b,Lh,n)},Ph=c.styled("div",{name:"MuiAutocomplete",slot:"Root",overridesResolver:(e,n)=>{const{ownerState:r}=e,{fullWidth:s,hasClearIcon:i,hasPopupIcon:l,inputFocused:a,size:d}=r;return[{[`& .${Te.tag}`]:n.tag},{[`& .${Te.tag}`]:n[`tagSize${c.capitalize(d)}`]},{[`& .${Te.inputRoot}`]:n.inputRoot},{[`& .${Te.input}`]:n.input},{[`& .${Te.input}`]:a&&n.inputFocused},n.root,s&&n.fullWidth,l&&n.hasPopupIcon,i&&n.hasClearIcon]}})({[`&.${Te.focused} .${Te.clearIndicator}`]:{visibility:"visible"},"@media (pointer: fine)":{[`&:hover .${Te.clearIndicator}`]:{visibility:"visible"}},[`& .${Te.tag}`]:{margin:3,maxWidth:"calc(100% - 6px)"},[`& .${Te.inputRoot}`]:{[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:30},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:56},[`& .${Te.input}`]:{width:0,minWidth:30}},[`& .${c.inputClasses.root}`]:{paddingBottom:1,"& .MuiInput-input":{padding:"4px 4px 4px 0px"}},[`& .${c.inputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${c.inputClasses.input}`]:{padding:"2px 4px 3px 0"}},[`& .${c.outlinedInputClasses.root}`]:{padding:9,[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:39},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:65},[`& .${Te.input}`]:{padding:"7.5px 4px 7.5px 5px"},[`& .${Te.endAdornment}`]:{right:9}},[`& .${c.outlinedInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingTop:6,paddingBottom:6,paddingLeft:6,[`& .${Te.input}`]:{padding:"2.5px 4px 2.5px 8px"}},[`& .${c.filledInputClasses.root}`]:{paddingTop:19,paddingLeft:8,[`.${Te.hasPopupIcon}&, .${Te.hasClearIcon}&`]:{paddingRight:39},[`.${Te.hasPopupIcon}.${Te.hasClearIcon}&`]:{paddingRight:65},[`& .${c.filledInputClasses.input}`]:{padding:"7px 4px"},[`& .${Te.endAdornment}`]:{right:9}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.sizeSmall}`]:{paddingBottom:1,[`& .${c.filledInputClasses.input}`]:{padding:"2.5px 4px"}},[`& .${c.inputBaseClasses.hiddenLabel}`]:{paddingTop:8},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}`]:{paddingTop:0,paddingBottom:0,[`& .${Te.input}`]:{paddingTop:16,paddingBottom:17}},[`& .${c.filledInputClasses.root}.${c.inputBaseClasses.hiddenLabel}.${c.inputBaseClasses.sizeSmall}`]:{[`& .${Te.input}`]:{paddingTop:8,paddingBottom:9}},[`& .${Te.input}`]:{flexGrow:1,textOverflow:"ellipsis",opacity:0},variants:[{props:{fullWidth:!0},style:{width:"100%"}},{props:{size:"small"},style:{[`& .${Te.tag}`]:{margin:2,maxWidth:"calc(100% - 4px)"}}},{props:{inputFocused:!0},style:{[`& .${Te.input}`]:{opacity:1}}},{props:{multiple:!0},style:{[`& .${Te.inputRoot}`]:{flexWrap:"wrap"}}}]}),_h=c.styled("div",{name:"MuiAutocomplete",slot:"EndAdornment"})({position:"absolute",right:0,top:"50%",transform:"translate(0, -50%)"}),zh=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"ClearIndicator"})({marginRight:-2,padding:4,visibility:"hidden"}),Wh=c.styled(c.IconButton,{name:"MuiAutocomplete",slot:"PopupIndicator",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[n.popupIndicator,r.popupOpen&&n.popupIndicatorOpen]}})({padding:2,marginRight:-2,variants:[{props:{popupOpen:!0},style:{transform:"rotate(180deg)"}}]}),qh=c.styled(c.Popper,{name:"MuiAutocomplete",slot:"Popper",overridesResolver:(e,n)=>{const{ownerState:r}=e;return[{[`& .${Te.option}`]:n.option},n.popper,r.disablePortal&&n.popperDisablePortal]}})(c.memoTheme(({theme:e})=>({zIndex:(e.vars||e).zIndex.modal,variants:[{props:{disablePortal:!0},style:{position:"absolute"}}]}))),Bh=c.styled(c.Paper,{name:"MuiAutocomplete",slot:"Paper"})(c.memoTheme(({theme:e})=>({...e.typography.body1,overflow:"auto"}))),Vh=c.styled("div",{name:"MuiAutocomplete",slot:"Loading"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Hh=c.styled("div",{name:"MuiAutocomplete",slot:"NoOptions"})(c.memoTheme(({theme:e})=>({color:(e.vars||e).palette.text.secondary,padding:"14px 16px"}))),Uh=c.styled("ul",{name:"MuiAutocomplete",slot:"Listbox"})(c.memoTheme(({theme:e})=>({listStyle:"none",margin:0,padding:"8px 0",maxHeight:"40vh",overflow:"auto",position:"relative",[`& .${Te.option}`]:{minHeight:48,display:"flex",overflow:"hidden",justifyContent:"flex-start",alignItems:"center",cursor:"pointer",paddingTop:6,boxSizing:"border-box",outline:"0",WebkitTapHighlightColor:"transparent",paddingBottom:6,paddingLeft:16,paddingRight:16,[e.breakpoints.up("sm")]:{minHeight:"auto"},[`&.${Te.focused}`]:{backgroundColor:(e.vars||e).palette.action.hover,"@media (hover: none)":{backgroundColor:"transparent"}},'&[aria-disabled="true"]':{opacity:(e.vars||e).palette.action.disabledOpacity,pointerEvents:"none"},[`&.${Te.focusVisible}`]:{backgroundColor:(e.vars||e).palette.action.focus},'&[aria-selected="true"]':{backgroundColor:e.alpha((e.vars||e).palette.primary.main,(e.vars||e).palette.action.selectedOpacity),[`&.${Te.focused}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.hoverOpacity}`),"@media (hover: none)":{backgroundColor:(e.vars||e).palette.action.selected}},[`&.${Te.focusVisible}`]:{backgroundColor:e.alpha((e.vars||e).palette.primary.main,`${(e.vars||e).palette.action.selectedOpacity} + ${(e.vars||e).palette.action.focusOpacity}`)}}}}))),Gh=c.styled(Qs,{name:"MuiAutocomplete",slot:"GroupLabel"})(c.memoTheme(({theme:e})=>({backgroundColor:(e.vars||e).palette.background.paper,top:-8}))),Yh=c.styled("ul",{name:"MuiAutocomplete",slot:"GroupUl"})({padding:0,[`& .${Te.option}`]:{paddingLeft:24}}),Zs=we.forwardRef(function(n,r){const s=c.useDefaultProps({props:n,name:"MuiAutocomplete"}),{autoComplete:i=!1,autoHighlight:l=!1,autoSelect:a=!1,blurOnSelect:d=!1,ChipProps:u,className:h,clearIcon:g=Vi||(Vi=t.jsx(Ah,{fontSize:"small"})),clearOnBlur:b=!s.freeSolo,clearOnEscape:x=!1,clearText:v="Clear",closeText:C="Close",componentsProps:k,defaultValue:S=s.multiple?[]:null,disableClearable:T=!1,disableCloseOnSelect:M=!1,disabled:O=!1,disabledItemsFocusable:I=!1,disableListWrap:R=!1,disablePortal:_=!1,filterOptions:$,filterSelectedOptions:B=!1,forcePopupIcon:F="auto",freeSolo:N=!1,fullWidth:H=!1,getLimitTagsText:D=$e=>`+${$e}`,getOptionDisabled:W,getOptionKey:K,getOptionLabel:J,isOptionEqualToValue:X,groupBy:G,handleHomeEndKeys:Q=!s.freeSolo,id:ie,includeInputInList:z=!1,inputValue:re,limitTags:se=-1,ListboxComponent:ne,ListboxProps:Me,loading:oe=!1,loadingText:ue="Loading…",multiple:De=!1,noOptionsText:Ne="No options",onChange:ae,onClose:Z,onHighlightChange:ce,onInputChange:be,onOpen:ge,open:he,openOnFocus:ye=!1,openText:Fe="Open",options:ze,PaperComponent:me,PopperComponent:Y,popupIcon:le=Hi||(Hi=t.jsx(c.ArrowDropDownIcon,{})),readOnly:Oe=!1,renderGroup:Re,renderInput:at,renderOption:Ie,renderTags:lt,renderValue:xt,selectOnFocus:vt=!s.freeSolo,size:Mt="medium",slots:mt={},slotProps:Ke={},value:fe,...Qe}=s,{getRootProps:qe,getInputProps:ct,getInputLabelProps:ut,getPopupIndicatorProps:Ze,getClearProps:pe,getItemProps:Ue,getListboxProps:bt,getOptionProps:Ce,value:Le,dirty:Ee,expanded:Be,id:ht,popupOpen:We,focused:nt,focusedItem:Ot,anchorEl:kt,setAnchorEl:$t,inputValue:gn,groupedOptions:_e}=Dh({...s,componentName:"Autocomplete"}),dt=!T&&!O&&Ee&&!Oe,Kt=(!N||F===!0)&&F!==!1,{onMouseDown:yn}=ct(),{ref:ft,...en}=bt(),Qt=J||($e=>$e.label??$e),Xe={...s,disablePortal:_,expanded:Be,focused:nt,fullWidth:H,getOptionLabel:Qt,hasClearIcon:dt,hasPopupIcon:Kt,inputFocused:Ot===-1,popupOpen:We,size:Mt},Je=Nh(Xe),Rt={slots:{paper:me,popper:Y,...mt},slotProps:{chip:u,listbox:Me,...k,...Ke}},[tn,Zt]=c.useSlot("listbox",{elementType:Uh,externalForwardedProps:Rt,ownerState:Xe,className:Je.listbox,additionalProps:en,ref:ft}),[nn,U]=c.useSlot("paper",{elementType:c.Paper,externalForwardedProps:Rt,ownerState:Xe,className:Je.paper}),[V,de]=c.useSlot("popper",{elementType:c.Popper,externalForwardedProps:Rt,ownerState:Xe,className:Je.popper,additionalProps:{disablePortal:_,style:{width:kt?kt.clientWidth:null},role:"presentation",anchorEl:kt,open:We}});let ve;const te=$e=>({className:Je.tag,disabled:O,...Ue($e)});if(De?Le.length>0&&(lt?ve=lt(Le,te,Xe):xt?ve=xt(Le,te,Xe):ve=Le.map(($e,zt)=>{const{key:gt,...qt}=te({index:zt});return t.jsx(c.Chip,{label:Qt($e),size:Mt,...qt,...Rt.slotProps.chip},gt)})):xt&&Le!=null&&(ve=xt(Le,te,Xe)),se>-1&&Array.isArray(ve)){const $e=ve.length-se;!nt&&$e>0&&(ve=ve.splice(0,se),ve.push(t.jsx("span",{className:Je.tag,children:D($e)},ve.length)))}const Ge=Re||($e=>t.jsxs("li",{children:[t.jsx(Gh,{className:Je.groupLabel,ownerState:Xe,component:"div",children:$e.group}),t.jsx(Yh,{className:Je.groupUl,ownerState:Xe,children:$e.children})]},$e.key)),vn=Ie||(($e,zt)=>{const{key:gt,...qt}=$e;return t.jsx("li",{...qt,children:Qt(zt)},gt)}),zn=($e,zt)=>{const gt=Ce({option:$e,index:zt});return vn({...gt,className:Je.option},$e,{selected:gt["aria-selected"],index:zt,inputValue:gn},Xe)},Wn=Rt.slotProps.clearIndicator,Fr=Rt.slotProps.popupIndicator;return t.jsxs(we.Fragment,{children:[t.jsx(Ph,{ref:r,className:c.clsx(Je.root,h),ownerState:Xe,...qe(Qe),children:at({id:ht,disabled:O,fullWidth:!0,size:Mt==="small"?"small":void 0,InputLabelProps:ut(),InputProps:{ref:$t,className:Je.inputRoot,startAdornment:ve,onMouseDown:$e=>{$e.target===$e.currentTarget&&yn($e)},...(dt||Kt)&&{endAdornment:t.jsxs(_h,{className:Je.endAdornment,ownerState:Xe,children:[dt?t.jsx(zh,{...pe(),"aria-label":v,title:v,ownerState:Xe,...Wn,className:c.clsx(Je.clearIndicator,Wn?.className),children:g}):null,Kt?t.jsx(Wh,{...Ze(),disabled:O,"aria-label":We?C:Fe,title:We?C:Fe,ownerState:Xe,...Fr,className:c.clsx(Je.popupIndicator,Fr?.className),children:le}):null]})}},inputProps:{className:Je.input,disabled:O,readOnly:Oe,...ct()}})}),kt?t.jsx(qh,{as:V,...de,children:t.jsxs(Bh,{as:nn,...U,children:[oe&&_e.length===0?t.jsx(Vh,{className:Je.loading,ownerState:Xe,children:ue}):null,_e.length===0&&!N&&!oe?t.jsx(Hh,{className:Je.noOptions,ownerState:Xe,role:"presentation",onMouseDown:$e=>{$e.preventDefault()},children:Ne}):null,_e.length>0?t.jsx(tn,{as:ne,...Zt,children:_e.map(($e,zt)=>G?Ge({key:$e.key,group:$e.group,children:$e.options.map((gt,qt)=>zn(gt,$e.index+qt))}):zn($e,zt))}):null]})}):null]})});c.dayjs.extend(c.utc);function Ms(e){switch(e){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 Kh(e){return e==="DateMinMax"}function Os(e){return e==="Between"}function Qh({spec:e,values:n,selection:r,onChange:s,retrievalFn:i}){const l=()=>r?.matchType?r.matchType:e.defaultMatchType?e.defaultMatchType:e.filterType==="DateMinMax"?"Between":Ms(e.filterType)[0]||"Equals",[a,d]=j.useState(l()),[u,h]=j.useState(r?.value??""),[g,b]=j.useState(r?.value2??""),[x,v]=j.useState([]),[C,k]=j.useState(!1),[S,T]=j.useState(""),[M,O]=j.useState(!1),[I,R]=j.useState(!1),_=j.useRef(null),$=j.useRef(0),[B,F]=j.useState(!1);j.useEffect(()=>{if(e.filterType!=="Retrieval"||!i)return;const z=S.trim();if(z.length<=2){v([]),O(!1);return}return _.current&&clearTimeout(_.current),_.current=setTimeout(async()=>{$.current+=1;const re=$.current;k(!0);try{const se=await i(z,e);re===$.current&&v(se)}catch(se){re===$.current&&(console.error("Retrieval failed",se),v([]))}finally{re===$.current&&(k(!1),O(!0))}},500),()=>{_.current&&clearTimeout(_.current)}},[S,e,i]),j.useEffect(()=>{r===null?(h(""),b(""),d(e.defaultMatchType??(e.filterType==="DateMinMax"?"Between":Ms(e.filterType)[0]||"Equals"))):r&&(d(r.matchType),h(r.value??""),b(r.value2??""))},[r,e.filterType,e.defaultMatchType]);const N=Ms(e.filterType),H=Kh(e.filterType),D=Os(a),W=H&&n.length>=2&&n[0].value instanceof Date?c.dayjs.utc(n[0].value):void 0,K=H&&n.length>=2&&n[1].value instanceof Date?c.dayjs.utc(n[1].value):void 0,J=e.filterType==="MinMax"&&n.length>=2&&typeof n[0].value=="number"?n[0].value:void 0,X=e.filterType==="MinMax"&&n.length>=2&&typeof n[1].value=="number"?n[1].value:void 0;if(N.length===0)return null;const G=z=>{const re=z.target.value;d(re),Os(re)||b(""),u&&s({dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:re,value:u,...Os(re)&&g&&{value2:g}})},Q=(z,re)=>{h(z??""),re!==void 0&&b(re??"");const se=Array.isArray(z)&&z.length===0;s(!se&&z!==""&&z!==null&&z!==void 0?{dimensionName:e.dimensionName,source:e.source,filterName:e.filterName,matchType:a,value:z,...D&&re&&{value2:re}}:null)},ie=()=>{h(""),b(""),s(null)};return t.jsxs(Ye,{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:[t.jsxs(Ye,{sx:{fontWeight:600,color:e.required&&!r?"error.main":"text.primary"},children:[e.label??e.dimensionName,e.required&&t.jsx(Ye,{component:"span",sx:{color:r?"text.secondary":"error.main",fontWeight:400,fontSize:"0.7rem",ml:.5},children:"(required)"})]}),e.filterType!=="Boolean"&&!e.defaultMatchType&&N.length>1&&t.jsxs(c.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(c.InputLabel,{children:"Match Type"}),t.jsx(c.Select,{value:a,label:"Match Type",onChange:G,MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:N.map(z=>t.jsx(tt,{value:z,children:z},z))})]}),e.filterType==="Star"&&a==="Equals"&&t.jsx(Zs,{multiple:!0,size:"small",options:n,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(u)?u.map(z=>n.find(re=>re.value===z)||z):u?[n.find(z=>z.value===u)||u]:[],onChange:(z,re)=>{const se=re.map(ne=>typeof ne=="string"?ne:ne&&typeof ne=="object"&&"value"in ne?ne.value:ne);Q(se)},noOptionsText:"No matches found",renderInput:z=>t.jsx(c.TextField,{...z,size:"small",label:"Values",placeholder:"Select values..."}),freeSolo:!e.values||e.values.length===0,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),e.filterType==="Star"&&a==="Contains"&&t.jsx(c.TextField,{size:"small",label:"Search Text",value:u,onChange:z=>h(z.target.value),onBlur:()=>Q(u),onKeyDown:z=>{z.key==="Enter"&&Q(u)},placeholder:"Enter text to search...",fullWidth:!0}),e.filterType==="Boolean"&&t.jsxs(c.FormControl,{size:"small",fullWidth:!0,children:[t.jsx(c.InputLabel,{children:"Value"}),t.jsxs(c.Select,{value:u===!0?"true":u===!1?"false":"",label:"Value",onChange:z=>{const re=z.target.value;re==="true"?Q(!0):re==="false"?Q(!1):ie()},MenuProps:{PaperProps:{sx:{"& .MuiMenuItem-root":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}},children:[t.jsx(tt,{value:"",children:t.jsx("em",{children:"Blank"})}),t.jsx(tt,{value:"true",children:"True"}),t.jsx(tt,{value:"false",children:"False"})]})]}),e.filterType==="Retrieval"&&a==="Semantic Search"&&t.jsx(Zs,{multiple:!0,size:"small",options:x,loading:C,getOptionLabel:z=>typeof z=="string"?z:typeof z=="object"&&z!==null&&"value"in z?String(z.value):String(z),value:Array.isArray(u)?u.map(z=>x.find(se=>se.value===z)||{value:z}):u?[{value:u}]:[],onInputChange:(z,re)=>{T(re)},onChange:(z,re)=>{const se=re.map(ne=>typeof ne=="string"?ne:ne&&typeof ne=="object"&&"value"in ne?ne.value:ne);Q(se)},noOptionsText:S.trim().length<=2?"Type at least 3 characters to search":"No matches found",renderInput:z=>t.jsx(c.TextField,{...z,size:"small",label:"Search Values",placeholder:"Type to search...",onFocus:()=>R(!0),onBlur:()=>R(!1),helperText:I&&!C&&M&&x.length===0?"No matches found":void 0,InputProps:{...z.InputProps,endAdornment:t.jsxs(t.Fragment,{children:[C?t.jsx(c.CircularProgress,{color:"inherit",size:20}):null,z.InputProps.endAdornment]})}}),freeSolo:!0,filterOptions:z=>z,slotProps:{paper:{sx:{"& .MuiAutocomplete-option":{fontSize:"0.75rem",minHeight:"auto",padding:"4px 10px"}}}}}),e.filterType==="MinMax"&&!D&&t.jsx(c.TextField,{size:"small",type:"number",label:"Value",value:u,onChange:z=>Q(parseFloat(z.target.value)||""),onFocus:()=>F(!0),onBlur:()=>F(!1),placeholder:"Enter number...",fullWidth:!0,inputProps:{min:J,max:X},helperText:B&&J!==void 0&&X!==void 0?`Valid range: [${J} - ${X}]`:void 0}),e.filterType==="MinMax"&&D&&t.jsxs(Ye,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ye,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(c.TextField,{size:"small",type:"number",label:"From",value:u,onChange:z=>Q(parseFloat(z.target.value)||"",g),onFocus:()=>F(!0),onBlur:()=>F(!1),placeholder:"Min...",fullWidth:!0,inputProps:{min:J,max:g||X}}),t.jsx(Ye,{children:"to"}),t.jsx(c.TextField,{size:"small",type:"number",label:"To",value:g,onChange:z=>Q(u,parseFloat(z.target.value)||""),onFocus:()=>F(!0),onBlur:()=>F(!1),placeholder:"Max...",fullWidth:!0,inputProps:{min:u||J,max:X}})]}),B&&J!==void 0&&X!==void 0&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",J," - ",X,"]"]})]}),H&&!D&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsx(c.DatePicker,{label:"Date",value:u instanceof Date?c.dayjs.utc(u):null,onChange:z=>{z===null?Q(null):z.isValid()&&Q(z.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?void 0:W,maxDate:u instanceof Date?void 0:K,referenceDate:a==="After"&&W?W:void 0,slotProps:{textField:{size:"small",fullWidth:!0,sx:{minWidth:150},onFocus:()=>F(!0),onBlur:()=>F(!1),helperText:B&&W&&K?`Valid range: [${W.format("YYYY-MM-DD")} - ${K.format("YYYY-MM-DD")}]`:void 0},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),H&&D&&t.jsx(c.LocalizationProvider,{dateAdapter:c.AdapterDayjs,children:t.jsxs(Ye,{sx:{display:"flex",flexDirection:"column",gap:1},children:[t.jsxs(Ye,{sx:{display:"flex",gap:1,alignItems:"center"},children:[t.jsx(Ye,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"From",value:u instanceof Date?c.dayjs.utc(u):null,onChange:z=>{z===null?Q(null,g):z.isValid()&&Q(z.utc().toDate(),g)},timezone:"UTC",minDate:u instanceof Date?void 0:W,maxDate:g instanceof Date?c.dayjs.utc(g):u instanceof Date?void 0:K,referenceDate:W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>F(!0),onBlur:()=>F(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})}),t.jsx(Ye,{children:"to"}),t.jsx(Ye,{sx:{flex:1,minWidth:0},children:t.jsx(c.DatePicker,{label:"To",value:g instanceof Date?c.dayjs.utc(g):null,onChange:z=>{z===null?Q(u,null):z.isValid()&&Q(u,z.utc().toDate())},timezone:"UTC",minDate:u instanceof Date?c.dayjs.utc(u):g instanceof Date?void 0:W,maxDate:g instanceof Date?void 0:K,referenceDate:u instanceof Date?c.dayjs.utc(u):W,slotProps:{textField:{size:"small",fullWidth:!0,onFocus:()=>F(!0),onBlur:()=>F(!1)},openPickerButton:{sx:{backgroundColor:"transparent"}}}})})]}),B&&W&&K&&t.jsxs(c.Typography,{variant:"caption",color:"text.secondary",sx:{mt:-.5,ml:1.5},children:["Valid range: [",W.format("YYYY-MM-DD")," -"," ",K.format("YYYY-MM-DD"),"]"]})]})})]})}function as(e,n){const{matchType:r,value:s,value2:i}=n;if(Array.isArray(s))return r!=="Equals"&&r!=="Semantic Search"||s.length===0?"":`(${s.map(a=>`${e} = ${c.formatMalloyValue(a)}`).join(" or ")})`;switch(r){case"Equals":case"Semantic Search":return`${e} = ${c.formatMalloyValue(s)}`;case"Contains":if(typeof s=="string"){const l=ed.StringFilterExpression.unparse({operator:"contains",values:[s]});return`${e} ~ ${c.malloyFilterLiteral(l)}`}return`${e} = ${c.formatMalloyValue(s)}`;case"After":case"Greater Than":return`${e} > ${c.formatMalloyValue(s)}`;case"Before":case"Less Than":return`${e} < ${c.formatMalloyValue(s)}`;case"Between":return i!==void 0?`${e} >= ${c.formatMalloyValue(s)} and ${e} <= ${c.formatMalloyValue(i)}`:`${e} >= ${c.formatMalloyValue(s)}`;default:return""}}function Zh(e){const n=new Set,r=e.schema?.fields;if(!r)return n;for(const s of r)"kind"in s&&s.kind==="join"&&s.name&&n.add(s.name);return n}function Xh(e){if(!e)return null;for(const n of e)if(n.startsWith("##(filters)")){const r=n.slice(11).trim();try{const s=JSON.parse(r);if(Array.isArray(s)){const i=[];for(const l of s)if(typeof l=="string"){const a=l.indexOf(".");a>0&&a<l.length-1&&i.push({source:l.substring(0,a),dimension:l.substring(a+1)})}if(i.length>0)return{filters:i}}}catch(s){console.error(`Failed to parse "${n}" annotation:`,s)}}return null}function ol(e){if(e.startsWith("#(filter)")){const n=e.slice(9).trim();try{const r=JSON.parse(n);if(r.type)return r}catch(r){console.error(`Failed to parse "${e}" annotation:`,r)}}return null}function Jh(e){const n=e.match(/^#\s*label\s*=\s*"([^"]+)"/);return n?n[1]:null}function ef(e){const n=new Map;let r="";for(const s of e)if(s.type==="code"){if(!r&&s.text){const l=s.text.split(`
4
4
  `).map(a=>a.trim()).find(a=>a.startsWith("import "))?.match(/['"]([^'"\n]+)['"]/);l&&(r=l[1])}if(s.newSources&&s.newSources.length>0)for(const i of s.newSources)try{const l=JSON.parse(i);l.name&&n.set(l.name,l)}catch(l){console.error("Failed to parse SourceInfo:",l)}}return{sourceInfoMap:n,modelPath:r}}function tf(e,n,r){const s=[];for(const{source:i,dimension:l}of n){const a=e.get(i);if(!a){console.warn(`Source "${i}" not found in notebook sources`),s.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}const d=a.schema?.fields;if(!d){s.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}const u=d.find(b=>b.name===l);if(!u){console.warn(`Dimension "${l}" not found in source "${i}"`),s.push({source:i,model:r,dimensionName:l,filterType:"Star"});continue}let h="Star",g;if("annotations"in u&&u.annotations){for(const b of u.annotations)if(b.value){const x=ol(b.value);x&&(h=x.type);const v=Jh(b.value);v&&(g=v)}}s.push({source:i,model:r,dimensionName:l,filterType:h,label:g})}return s}function nf(e,n,r){return e.length===0?"":e.map(i=>{const{dimensionName:l,source:a}=i,u=a&&a!==r?`\`${a}\`.\`${l}\``:`\`${l}\``;return as(u,i)}).filter(i=>i.length>0).join(" and ")}function rf(e){const n=e.match(/run\s*:\s*(\w+)\s*->/);if(n)return n[1];const r=e.match(/^\s*(\w+)\s*->/m);return r?r[1]:null}function sf(e,n){return`${e.trimEnd()} + {where: ${n}}`}const of=c.createSvgIcon(t.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"})),il=e=>{if(!e)return"Explore semantic models, run queries, and build reports";const n=e.replace(/^#+\s+/gm,"").replace(/\*\*(.*?)\*\*/g,"$1").replace(/\*(.*?)\*/g,"$1").replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/`([^`]+)`/g,"$1").trim(),s=n.split(/\n\s*\n/)[1]||n;if(s.length<=120)return s;const i=s.substring(0,120).split(" ");return i.pop(),i.join(" ")+"..."},al=(e,n)=>{const r=(e.readme||void 0)?.split(`
package/dist/index.es.js CHANGED
@@ -2,16 +2,16 @@ import { jsx as r, jsxs as k, Fragment as pe } from "react/jsx-runtime";
2
2
  import { Link as So, useMediaQuery as sf, Stack as Ye, Typography as re, Button as Ke, Menu as zn, MenuItem as an, Box as A, Tooltip as xt, Dialog as Ls, DialogTitle as zs, IconButton as qt, DialogContent as Ws, DialogActions as af, Alert as yt, TextField as er, Grid as kr, Paper as Ss, FormControlLabel as Rc, Switch as Fc, Divider as Wn, List as Ac, ListItemButton as Pc, ListItemText as tn, TableContainer as lf, Table as pi, TableHead as gi, TableRow as qn, TableCell as ze, TableBody as yi, Snackbar as Nr, ListItemIcon as xn, Container as si, FormGroup as cf, Chip as _c, Collapse as vi, ButtonBase as qs, CircularProgress as bi, Popover as uf, AlertTitle as df, InputBase as hf, InputAdornment as ff, alpha as mf, LinearProgress as pf } from "@mui/material";
3
3
  import * as ke from "react";
4
4
  import $e, { useState as Z, useCallback as je, useMemo as fe, useRef as gt, useEffect as rt, Fragment as gf, useId as wi, forwardRef as No, createContext as xi, useContext as Ro, createElement as yf } from "react";
5
- import { n as Oe, bk as Lc, bl as Zr, bm as vf, bn as cl, bo as bf, bp as wf, bq as xf, br as Sf, bs as zc, bt as Vs, bu as Hs, al as yo, bv as Us, aw as kf, aG as Bs, bw as Wc, bx as Cf, by as Fo, aF as qc, bz as Tf, ar as Of, aH as Mf, au as ks, J as Df, aN as If, ac as Ef, G as $f, bA as Nf, aJ as Vc, aL as Rf, aM as Ff, aK as Af, a4 as Pf, P as _f, ag as Hc, aO as Si, ae as Uc, a1 as ki, $ as Mr, aB as vt, bB as Ze, aI as Nt, S as Ao, b6 as Vt, bC as Lf, bD as Jn, bE as ul, bF as Bc, bG as zf, bH as Yi, bI as Sn, bJ as dn, bK as kn, bL as ln, bM as Cn, bN as lt, bO as js, bP as Zt, bQ as dl, bR as Wf, bS as Kt, bT as qf, bU as Ht, bV as wn, bW as Po, t as Tt, bX as Vf, bY as Hf, bZ as Uf, b_ as ai, b$ as at, c0 as hl, c1 as Bf, c2 as jc, c3 as Gs, c4 as Pe, A as Gc, c5 as Ci, c6 as Rt, c7 as Ti, c8 as jf, c9 as ni, ca as Gf, cb as Kf, cc as Kc, cd as Yf, ce as wr, cf as Yn, cg as fl, ch as Zi, ci as Mn, cj as ml, ck as pl, cl as gl, cm as Yc, cn as yl, co as vl, cp as Xi, cq as Zf, cr as _n, cs as Xf, ct as Qf, cu as Jf, cv as Rr, cw as Zc, cx as em, cy as bl, cz as tm, cA as nm, C as rm, cB as Xc, cC as om, cD as im, cE as sm, E as am, cF as lm, cG as cm, cH as Ks, cI as um, cJ as dm, cK as hm, cL as fm, cM as vo, cN as ko, cO as mm, cP as pm, aC as gm, cQ as Qc, aV as Cs, cR as Jc, bj as ym, v as Qi, b9 as vm, bg as bm, cS as wm, bd as xm, p as eu, r as wl, V as Sm, a$ as Ys, ba as km, cT as Cm, B as tu, b2 as nu, aQ as ru, bb as Tm, aY as Om, b1 as Oi, cU as Mm, cV as Dm, cW as li, cX as ou, cY as Im, aS as Em, aa as xl, cZ as $m, ab as Nm, c_ as Rm, c$ as Fm, d0 as Am, d1 as Sl } from "./useCompiledDocument-Dmm6xkom.es.js";
6
- import { d2 as yx, d3 as vx, d4 as bx, o as wx, d5 as xx, d6 as Sx, d7 as kx, d8 as Cx, d9 as Tx, da as Ox, db as Mx, dc as Dx, U as Ix, d as Ex, b7 as $x, g as Nx, z as Rx, aE as Fx, dd as Ax, de as Px, df as _x, dg as Lx, av as zx, dh as Wx, di as qx, m as Vx, dj as Hx, K as Ux, e as Bx, b4 as jx, dk as Gx, dl as Kx, b as Yx, ak as Zx, aD as Xx, dm as Qx, dn as Jx, dp as eS, dq as tS } from "./useCompiledDocument-Dmm6xkom.es.js";
7
- import { bs as _e, br as Nn, bx as Dt, m as kl, d as iu, by as Zs, a2 as Wt, aq as Xo, a1 as Pm, bz as _t, bA as su, bB as au, bC as _m, bD as lu, bE as Lm, bF as zm } from "./ServerProvider-RnliA2Ao.es.js";
8
- import { bG as rS, bw as oS, b1 as iS, bH as sS, bI as aS, bJ as lS, bK as cS, bL as uS, bu as dS } from "./ServerProvider-RnliA2Ao.es.js";
5
+ import { n as Oe, bk as Lc, bl as Zr, bm as vf, bn as cl, bo as bf, bp as wf, bq as xf, br as Sf, bs as zc, bt as Vs, bu as Hs, al as yo, bv as Us, aw as kf, aG as Bs, bw as Wc, bx as Cf, by as Fo, aF as qc, bz as Tf, ar as Of, aH as Mf, au as ks, J as Df, aN as If, ac as Ef, G as $f, bA as Nf, aJ as Vc, aL as Rf, aM as Ff, aK as Af, a4 as Pf, P as _f, ag as Hc, aO as Si, ae as Uc, a1 as ki, $ as Mr, aB as vt, bB as Ze, aI as Nt, S as Ao, b6 as Vt, bC as Lf, bD as Jn, bE as ul, bF as Bc, bG as zf, bH as Yi, bI as Sn, bJ as dn, bK as kn, bL as ln, bM as Cn, bN as lt, bO as js, bP as Zt, bQ as dl, bR as Wf, bS as Kt, bT as qf, bU as Ht, bV as wn, bW as Po, t as Tt, bX as Vf, bY as Hf, bZ as Uf, b_ as ai, b$ as at, c0 as hl, c1 as Bf, c2 as jc, c3 as Gs, c4 as Pe, A as Gc, c5 as Ci, c6 as Rt, c7 as Ti, c8 as jf, c9 as ni, ca as Gf, cb as Kf, cc as Kc, cd as Yf, ce as wr, cf as Yn, cg as fl, ch as Zi, ci as Mn, cj as ml, ck as pl, cl as gl, cm as Yc, cn as yl, co as vl, cp as Xi, cq as Zf, cr as _n, cs as Xf, ct as Qf, cu as Jf, cv as Rr, cw as Zc, cx as em, cy as bl, cz as tm, cA as nm, C as rm, cB as Xc, cC as om, cD as im, cE as sm, E as am, cF as lm, cG as cm, cH as Ks, cI as um, cJ as dm, cK as hm, cL as fm, cM as vo, cN as ko, cO as mm, cP as pm, aC as gm, cQ as Qc, aV as Cs, cR as Jc, bj as ym, v as Qi, b9 as vm, bg as bm, cS as wm, bd as xm, p as eu, r as wl, V as Sm, a$ as Ys, ba as km, cT as Cm, B as tu, b2 as nu, aQ as ru, bb as Tm, aY as Om, b1 as Oi, cU as Mm, cV as Dm, cW as li, cX as ou, cY as Im, aS as Em, aa as xl, cZ as $m, ab as Nm, c_ as Rm, c$ as Fm, d0 as Am, d1 as Sl } from "./useCompiledDocument-BnT2QpG0.es.js";
6
+ import { d2 as yx, d3 as vx, d4 as bx, o as wx, d5 as xx, d6 as Sx, d7 as kx, d8 as Cx, d9 as Tx, da as Ox, db as Mx, dc as Dx, U as Ix, d as Ex, b7 as $x, g as Nx, z as Rx, aE as Fx, dd as Ax, de as Px, df as _x, dg as Lx, av as zx, dh as Wx, di as qx, m as Vx, dj as Hx, K as Ux, e as Bx, b4 as jx, dk as Gx, dl as Kx, b as Yx, ak as Zx, aD as Xx, dm as Qx, dn as Jx, dp as eS, dq as tS } from "./useCompiledDocument-BnT2QpG0.es.js";
7
+ import { bs as _e, br as Nn, bx as Dt, m as kl, d as iu, by as Zs, a2 as Wt, aq as Xo, a1 as Pm, bz as _t, bA as su, bB as au, bC as _m, bD as lu, bE as Lm, bF as zm } from "./ServerProvider-DRbZ6tLP.es.js";
8
+ import { bG as rS, bw as oS, b1 as iS, bH as sS, bI as aS, bJ as lS, bK as cS, bL as uS, bu as dS } from "./ServerProvider-DRbZ6tLP.es.js";
9
9
  import { useQueryClient as rr, useQuery as Co, useMutation as Ji } from "@tanstack/react-query";
10
10
  import { createBox as Wm, createStack as qm, Stack as Vm, Box as cu } from "@mui/system";
11
11
  import { Delete as Mi, Edit as Xs, MoreVert as Di } from "@mui/icons-material";
12
12
  import { parseAnnotation as Hm } from "@malloydata/malloy-tag";
13
13
  import { i as Um, n as Bm } from "./text-entry-YKJZbRPo.es.js";
14
- import { D as fS, R as mS, b as pS, a as gS, d as yS, m as vS, r as bS } from "./RenderedResult-DEjFM1DL.es.js";
14
+ import { D as fS, R as mS, b as pS, a as gS, d as yS, m as vS, r as bS } from "./RenderedResult-DqPvGZgL.es.js";
15
15
  import { StringFilterExpression as jm } from "@malloydata/malloy-filter";
16
16
  import { useNavigate as uu, useSearchParams as Gm, useLocation as Km } from "react-router-dom";
17
17
  const Ym = Oe(/* @__PURE__ */ r("path", {