react-semaphor 0.1.423 → 0.1.425
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/analytics-protocol/index.cjs +1 -1
- package/dist/analytics-protocol/index.js +243 -91
- package/dist/appearance/index.cjs +1 -1
- package/dist/appearance/index.js +1 -1
- package/dist/brand-studio/index.cjs +2 -2
- package/dist/brand-studio/index.js +8 -8
- package/dist/chunks/{analyze-result-contract-D7pjjYPy.js → analyze-result-contract-DnfF8kBb.js} +434 -427
- package/dist/chunks/analyze-result-contract-ege_u6Nl.js +1 -0
- package/dist/chunks/{braces-8TRlDwDw.js → braces-BdbUk_r9.js} +1 -1
- package/dist/chunks/{braces-D2tStQjF.js → braces-CbO-aIwH.js} +1 -1
- package/dist/chunks/calendar-preferences-dialog-BLaSWhLl.js +1 -0
- package/dist/chunks/{calendar-preferences-dialog-t5ET6MON.js → calendar-preferences-dialog-DJwV0aqn.js} +4 -4
- package/dist/chunks/{catalog-field-grounding-CJKAqtiC.js → catalog-field-grounding-DcxPLns0.js} +10 -10
- package/dist/chunks/{switch-2bh3Hka1.js → code-editor-Bkk7s8hI.js} +7382 -6809
- package/dist/chunks/code-editor-CkXyNgYc.js +138 -0
- package/dist/chunks/{common-types-4bjoIgvm.js → common-types-ClkOI-3O.js} +4 -4
- package/dist/chunks/comparison-document-migration-CQJ0DZlL.js +414 -0
- package/dist/chunks/comparison-document-migration-Db64RWYD.js +1 -0
- package/dist/chunks/{index-yHe0SeLO.js → dashboard-5agU0G_D.js} +56752 -55440
- package/dist/chunks/dashboard-MKIqgGDp.js +1402 -0
- package/dist/chunks/{dashboard-briefing-launcher-S2akO-ub.js → dashboard-briefing-launcher-CII8-4qo.js} +11 -6
- package/dist/chunks/{dashboard-briefing-launcher-Cavd0QJb.js → dashboard-briefing-launcher-qyEVfuOm.js} +226 -209
- package/dist/chunks/dashboard-controls-PJpeYZHw.js +36 -0
- package/dist/chunks/dashboard-controls-aJY0FNPP.js +2196 -0
- package/dist/chunks/dashboard-input-contract-BFpERluO.js +18 -0
- package/dist/chunks/dashboard-input-contract-DV3cshjz.js +1 -0
- package/dist/chunks/{dashboard-json-Do2-pdPZ.js → dashboard-json-CzHSP6Fa.js} +16 -15
- package/dist/chunks/dashboard-json-DtmR5yCf.js +1 -0
- package/dist/chunks/date-formatter-BTTYdAik.js +1 -0
- package/dist/chunks/date-formatter-D-89jTjG.js +514 -0
- package/dist/chunks/{edit-dashboard-visual-Cw6bq4_w.js → edit-dashboard-visual-AkZzwBCV.js} +8892 -8996
- package/dist/chunks/edit-dashboard-visual-Cif6uDqN.js +182 -0
- package/dist/chunks/{index-CjzRe2su.js → index-CnujJ3fa.js} +3 -3
- package/dist/chunks/{index-DRlMUglg.js → index-Dpm_VET4.js} +2 -2
- package/dist/chunks/{index-CJdxSyQq.js → index-If0wlXGi.js} +308 -308
- package/dist/chunks/index-jSrCwPQz.js +31 -0
- package/dist/chunks/{x-CXDkqdur.js → index-xHCrHprY.js} +59 -59
- package/dist/chunks/{layout-grid-C0OI-MRn.js → layout-grid-B08pP7v6.js} +1 -1
- package/dist/chunks/{layout-grid-CiubineE.js → layout-grid-D5tYJg1-.js} +1 -1
- package/dist/chunks/metric-comparison-4oA4ouU9.js +354 -0
- package/dist/chunks/metric-comparison-nQKquVnx.js +1 -0
- package/dist/chunks/{palette-C4KTXOug.js → palette-C0yjT5Tv.js} +1 -1
- package/dist/chunks/{palette-Cp1hqZtm.js → palette-jqaAcwiQ.js} +1 -1
- package/dist/chunks/{save-DgMfP0j8.js → save-HCJjjzdX.js} +1 -1
- package/dist/chunks/{save-C__QggEE.js → save-Xdc4pnys.js} +1 -1
- package/dist/chunks/{search-BHsQIWBV.js → search-DHZCro8B.js} +1 -1
- package/dist/chunks/{search-DNCejM7Z.js → search-Dcud9ajy.js} +1 -1
- package/dist/chunks/{update-policy-C1pmhLz9.js → update-policy-BgONreNd.js} +1 -1
- package/dist/chunks/{update-policy-BCJc0oI5.js → update-policy-CY2k-pJP.js} +9 -9
- package/dist/chunks/{use-create-flow-overlay-state-5MDbZcs1.js → use-create-flow-overlay-state-ByOKVV2K.js} +62 -62
- package/dist/chunks/{use-create-flow-overlay-state-BNczg9Gj.js → use-create-flow-overlay-state-DmuReEnk.js} +2 -2
- package/dist/chunks/validators-B4VMLX3_.js +1 -0
- package/dist/chunks/{validators-PXkij33j.js → validators-Cz-XuORM.js} +123 -119
- package/dist/dashboard/index.cjs +1 -1
- package/dist/dashboard/index.js +2 -2
- package/dist/dashboard-authoring/index.cjs +2 -2
- package/dist/dashboard-authoring/index.js +6 -4
- package/dist/data-app-builder/index.cjs +6 -6
- package/dist/data-app-builder/index.js +5 -5
- package/dist/data-app-codegen/index.cjs +1 -1
- package/dist/data-app-codegen/index.js +2 -2
- package/dist/data-app-codegen-node/index.cjs +1 -1
- package/dist/data-app-codegen-node/index.js +3 -3
- package/dist/data-app-sdk/index.cjs +1 -1
- package/dist/data-app-sdk/index.js +6 -6
- package/dist/data-app-sdk-adapters/index.cjs +1 -1
- package/dist/data-app-sdk-adapters/index.js +1 -1
- package/dist/data-app-sdk-validation/index.cjs +1 -1
- package/dist/data-app-sdk-validation/index.js +65 -68
- package/dist/format-utils/index.cjs +2 -2
- package/dist/format-utils/index.js +59 -58
- package/dist/index.cjs +1 -1
- package/dist/index.js +19 -19
- package/dist/style.css +1 -1
- package/dist/surfboard/index.cjs +1 -1
- package/dist/surfboard/index.js +3 -3
- package/dist/types/analytics-protocol.d.ts +299 -3
- package/dist/types/brand-studio.d.ts +2 -2
- package/dist/types/briefings.d.ts +65 -41
- package/dist/types/dashboard-assistant.d.ts +28 -7
- package/dist/types/dashboard-authoring.d.ts +123 -43
- package/dist/types/dashboard.d.ts +97 -48
- package/dist/types/data-app-builder.d.ts +2 -2
- package/dist/types/data-app-sdk.d.ts +1 -1
- package/dist/types/format-utils.d.ts +98 -10
- package/dist/types/index.js +1 -1
- package/dist/types/main.d.ts +229 -95
- package/dist/types/shared.d.ts +84 -43
- package/dist/types/surfboard.d.ts +99 -49
- package/dist/types/types.d.ts +110 -50
- package/package.json +2 -1
- package/dist/chunks/analyze-result-contract-DpDcImgk.js +0 -1
- package/dist/chunks/calendar-preferences-dialog-CTmeASaM.js +0 -1
- package/dist/chunks/contracts-CoCOpd_i.js +0 -11
- package/dist/chunks/contracts-CtB2VONT.js +0 -1
- package/dist/chunks/dashboard-controls-BJLrErjW.js +0 -2322
- package/dist/chunks/dashboard-controls-DzbP8AXA.js +0 -52
- package/dist/chunks/dashboard-json-5tWb5KD6.js +0 -1
- package/dist/chunks/date-formatter-B4EBSe9C.js +0 -1
- package/dist/chunks/date-formatter-BlhBftA9.js +0 -416
- package/dist/chunks/edit-dashboard-visual-Yh5YFgMF.js +0 -178
- package/dist/chunks/index-BPM3gDRw.js +0 -1406
- package/dist/chunks/switch-DMT7qf_R.js +0 -138
- package/dist/chunks/validators-DMlVbd1p.js +0 -1
- package/dist/chunks/x-B6ghREd2.js +0 -31
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";const C=require("react"),s=require("./
|
|
1
|
+
"use strict";const C=require("react"),s=require("./code-editor-CkXyNgYc.js"),f=require("./dashboard-MKIqgGDp.js"),e=require("react/jsx-runtime"),ee=require("./index-jSrCwPQz.js");require("./analyze-result-contract-ege_u6Nl.js");const ke=require("./save-Xdc4pnys.js"),ye=require("./search-Dcud9ajy.js");/**
|
|
2
2
|
* @license lucide-react v0.453.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -8,4 +8,4 @@
|
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
10
10
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const Ee=ee.createLucideIcon("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);function Ie(r){const[a,o]=C.useState(null),[n,i]=C.useState(null),c=f.useEnsureReactGlobals();return C.useEffect(()=>{if(!r||r.trim()===""){o(null),i(null);return}if(!c)return;(async()=>{try{if(!r.startsWith("http://")&&!r.startsWith("https://"))throw new Error(`Invalid URL format: ${r}`);try{new URL(r)}catch{throw new Error(`Invalid URL: ${r}`)}const p=`${r.endsWith("/")?r:`${r}/`}index.js`;try{if(!(await fetch(p,{method:"HEAD"})).ok)throw new Error(`Module not found at ${p}`)}catch{}const v=await import(p);if(typeof v.useChartStore!="function")throw new Error("useChartStore is not a function");o(()=>v.useChartStore),i(null)}catch(x){const p=x instanceof Error?x.message:"Unknown error";console.error("Failed to load remote chart store:",p),i(p),o(null)}})()},[r,c]),a}function Te(r,a){if(r.length===0)return"";const o=r.find(n=>{var i,c;return((i=n.customCardPreferences)==null?void 0:i.visualType)==="multiple"||!!((c=n.customCardPreferences)!=null&&c.dataInputCardIds)});if(o)return o.id;if(a){const n=r.find(i=>i.id===a);if(n){const i=n.tabTitle;if(i=="All__Header")return r[0].id;if(i&&i.endsWith("__Header")){const m=i.split("__")[0],x=r.find(p=>p.tabTitle===m);return x?x.id:r[0].id}return a}}return r[0].id}const ue=new Set;function Le(r){return ue.add(r),()=>{ue.delete(r)}}function we(){ue.forEach(r=>{r()})}const Ae=r=>{if(!r||!("detailTableBackup"in r))return r;const{detailTableBackup:a,...o}=r;return o};async function ve(r,a,o,n,i="Opening library visual..."){if(!a||!o)throw new Error("Missing auth token or visual ID");const c=["resource-by-id","visual",o],m=n.getQueryData(c);if(m)return console.log("Using cached visual data for:",o),{data:m,fromCache:!0};console.log("Fetching visual data from network for:",o);const x=f.ue.loading(i,{position:"top-center"});try{const p=await fetch(`${r}/management/v1/visuals/${o}`,{headers:{Authorization:`Bearer ${a}`}});if(!p.ok)throw new Error("Failed to load visual");const v=await p.json();return n.setQueryData(c,v),f.ue.dismiss(x),{data:v,fromCache:!1}}catch(p){throw f.ue.dismiss(x),p}}function De(r){if(typeof r=="string")return JSON.parse(r);if(typeof r=="object")return r;throw new Error("Invalid frame object format")}function _e(r,a){var c,m;const o=(r==null?void 0:r.frameObject)??((c=r==null?void 0:r.visual)==null?void 0:c.frameObject);if(!o)return!1;const n=De(o);if(!(n!=null&&n.cards)||n.cards.length===0)return!1;const i=(m=n.cards)==null?void 0:m.find(x=>x.id===n.activeCardId);return i?(f.setupEditorWithCard({...a,frame:n,card:i,visualId:(r==null?void 0:r.id)||n.visualId}),!0):!1}function Be(){const r=s.useEditorStore(n=>{var i;return((i=n.card.customCardPreferences)==null?void 0:i.url)||""}),a=Ie(r);return{getUpdatedFrame:C.useCallback(()=>{var I;we();const{frame:n,card:i,isDevMode:c,isShowingVisual:m,selectedSchemaName:x,selectedDatamodelId:p,selectedDatabaseName:v,selectedTableName:g,selectedConnectionId:h}=s.useEditorStore.getState(),S=i.sql,w=(I=a==null?void 0:a.getState())==null?void 0:I.settings,k=s.buildSavedEditorCard(i,{isDevMode:c,cardSql:S,isShowingVisual:m,selectedSchemaName:x,selectedDatamodelId:p,selectedDatabaseName:v,selectedTableName:g,selectedConnectionId:h,remoteChartSettings:w,stripConfig:Ae}),E=n.cards.map(U=>U.id===i.id?k:U);return{...n,cards:E,activeCardId:Te(E,n.activeCardId)}},[a])}}function ae(){const{authToken:r,tokenProps:a}=f.useSemaphorContext(),o=f.useQueryClient(),n=f.useAddFrameWithFreshSemanticExecutionPayload(),i=f.useSelectedVisual(),{selectVisual:c}=f.useManagementActions(),{setFrame:m,setCard:x,setIsDevMode:p,initializeModeDrafts:v,setActiveTabCardId:g,updateDataSource:h,setQueryResultColumns:S,setSelectedConnectionId:w,setSelectedDatabaseName:k,setSelectedSchemaName:E,setSelectedTableName:I,setSelectedDatamodelId:U,setFilterValues:Y,setInlineFilterValuesMap:H,setApplyFilters:K,clearEditorContext:J}=s.useEditorActions(),{setIsDashboardEditing:q,setIsVisualEditing:l,setSelectedFrameId:D,clearSelectedFrameId:T}=s.useDashboardActions(),M=s.useDashboardStore(A=>A.selectedSheetId),Q=s.useDashboardStore(A=>A.selectedFrameId),W=s.useDashboardStore(A=>A.dashboard),G=s.useDashboardStore(A=>A.filterValues),_=s.useDashboardStore(A=>A.inlineFilterValuesMap),z=f.useVisualById((i==null?void 0:i.id)||"",{enabled:!!(i!=null&&i.id)&&!!(r!=null&&r.accessToken)}),$=C.useCallback(async A=>{try{c(A),T(),J();const{data:F,fromCache:P}=await ve(a.apiServiceUrl,(r==null?void 0:r.accessToken)||"",A.id,o,"Opening library visual...");if(!_e(F,{setFrame:m,setCard:x,setIsDevMode:p,initializeModeDrafts:v,setActiveTabCardId:g,updateDataSource:h,setQueryResultColumns:S,setSelectedConnectionId:w,setSelectedDatabaseName:k,setSelectedSchemaName:E,setSelectedTableName:I,setSelectedDatamodelId:U,setFilterValues:Y,setInlineFilterValuesMap:H,setApplyFilters:K,setIsDashboardEditing:q,setIsVisualEditing:l,dashboard:W,selectedSheetId:M,selectedFrameId:Q,filterValues:G,inlineFilterValuesMap:_}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:P}}catch(F){return console.error("Error editing visual:",F),{success:!1,error:"Failed to load visual for editing"}}},[r==null?void 0:r.accessToken,a.apiServiceUrl,o,c,m,x,q,l,p,v,g,h,S,w,k,E,I,U,Y,H,K,J,T,W,M,Q,G,_]),ne=C.useCallback(async A=>{var P;const F=B=>(f.ue.error(B),{success:!1,error:B});try{if(c(A),!M)return F("No sheet selected. Please select a sheet first.");const{data:B,fromCache:oe}=await ve(a.apiServiceUrl,(r==null?void 0:r.accessToken)||"",A.id,o,"Adding visual to dashboard..."),re=(B==null?void 0:B.frameObject)??((P=B==null?void 0:B.visual)==null?void 0:P.frameObject);if(!re)return F("Visual has no frame data");const R=De(re);if(!(R!=null&&R.cards)||R.cards.length===0)return F("Visual frame is malformed");const te={...f.cloneLinkedFrameWithSourceMapping(R),visualId:A.id};return await n(M,te,"end"),q(!0),D(te.id),{success:!0,fromCache:oe}}catch(B){return console.error("Error adding visual:",B),F(B instanceof Error?B.message:"Failed to add visual to dashboard")}},[r==null?void 0:r.accessToken,a.apiServiceUrl,o,c,M,q,D,n]);return{visual:z.data,isLoading:z.isLoading,isError:z.isError,error:z.error,handleEditLibraryVisual:$,handleAddLibraryVisual:ne,getUpdatedFrame:Be().getUpdatedFrame,refetch:z.refetch}}function qe(){const r=s.useEditorStore(m=>m.card.dataSource),{setSelectedConnectionId:a,setSelectedDatabaseName:o,setSelectedSchemaName:n,setSelectedTableName:i,setSelectedDatamodelId:c}=s.useEditorActions();C.useEffect(()=>{var w;if(!r)return;const{tableName:m,schemaName:x,databaseName:p,connectionId:v}=f.extractTableMetadata(r),g=(w=r.selectedEntities)==null?void 0:w[0],S=(g==null?void 0:g.type)==="model"&&"id"in g?g.id:"";a(v||""),o(p||""),n(x||""),i(m||""),c(S)},[r,a,o,n,i,c])}function pe(){var p,v;const r=s.useEditorStore(g=>g.card),a=s.useEditorStore(g=>g.frame),o=C.useMemo(()=>f.findCustomVisualConfigCard(a,r),[a,r]),{manifest:n}=f.useCustomVisual(((p=o==null?void 0:o.customCardPreferences)==null?void 0:p.url)||""),i=C.useMemo(()=>{var g;return(g=n==null?void 0:n.visuals)==null?void 0:g.find(h=>{var S;return h.name===((S=o==null?void 0:o.customCardPreferences)==null?void 0:S.componentName)})},[n,(v=o==null?void 0:o.customCardPreferences)==null?void 0:v.componentName]),c=f.resolveMultiInputType(o,i),m=C.useMemo(()=>f.getCustomVisualInputCards({frame:a,configCard:o,isMultiInputVisual:c==="multiple"}),[a,o,c]),x=C.useMemo(()=>{const g=m.findIndex(h=>(h==null?void 0:h.id)===r.id);return g<0?-1:f.getSlotIndexForCard(r,g)},[m,r]);return C.useMemo(()=>!o||c!=="multiple"||x<0?r.type:f.getEffectiveCardTypeForSlot(r,x,i==null?void 0:i.slots)??r.type,[o,c,x,r,i==null?void 0:i.slots])}function Me({type:r,isLinked:a,className:o,showLabel:n=!1,showLocal:i=!1}){const c=s.useDashboardStore(E=>E.selectedFrameId),m=f.useManagementStore(E=>E.selectedVisual),x=s.useEditorStore(E=>E.frame);let p;if(r)p=r;else if(a!==void 0)p=a?"linked":"library";else if(!!!(x!=null&&x.visualId||m!=null&&m.id)&&c)p="local";else if(m&&!c)p="library";else if(x!=null&&x.visualId&&c)p="linked";else if(m!=null&&m.id&&c)p="library";else return null;if(p==="local"&&!i)return null;const v={local:"border-slate-200/70 bg-slate-50/80 text-slate-700 shadow-sm hover:bg-slate-100/80 dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:bg-slate-800/80",linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},g={local:"Local to this dashboard: Changes made here only affect this dashboard copy.",linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},h={local:"border-slate-200 bg-slate-50 text-slate-900 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100",linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},S={local:"fill-slate-50 dark:fill-slate-900",linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},w={local:e.jsx("span",{className:"h-2 w-2 rounded-full bg-current/70"}),linked:e.jsx(Ee,{className:"h-3.5 w-3.5"}),library:e.jsx(Ne,{className:"h-3.5 w-3.5"})},k={local:"Local",linked:"Linked",library:"Library"};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(f.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",v[p],o),children:[w[p],n&&e.jsx("span",{className:"ml-1 text-xs font-medium leading-none",children:k[p]})]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",h[p]),children:[e.jsx(s.TooltipArrow,{className:S[p]}),e.jsx("p",{children:g[p]})]})]})})}function Oe(r,a){return{...r,sql:"",python:"",config:void 0,customCfg:"",preferences:{},interactionConfig:void 0,linkedInteractionTargetOverrides:void 0,dynamicCardPreferences:void 0,customCardPreferences:a?r.customCardPreferences:void 0,visualizationMode:"builtin",type:a?r.type:"bar"}}function me(r){const a=s.getDynamicFrameSaveIssue(r);return a?(f.ue.error(a),!1):!0}function Ue({className:r,variant:a="outline"}){const o=s.useEditorStore(c=>c.onSave),{getUpdatedFrame:n}=ae();function i(){const c=n();me(c)&&(o==null||o(c))}return e.jsxs(s.Button,{onClick:i,className:r,size:"xs",variant:a,children:[e.jsx(s.Check,{className:"h-3.5 w-3.5"}),"Accept"]})}function ze({className:r,variant:a="default"}){const o=f.useQueryClient(),[n,i]=C.useState(!1),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:m}=ae(),x=f.useSelectedVisual(),p=s.useEditorStore(h=>h.frame),v=f.useUpdateVisualMutation(),g=()=>{const h=m();if(!me(h))return;const S=(p==null?void 0:p.visualId)||(x==null?void 0:x.id);if(!S){f.ue.error("No visual to save");return}i(!0),v.mutate({visualId:S,data:{frameObject:h}},{onSuccess:()=>{i(!1),f.ue.success("Visual updated successfully"),o.invalidateQueries({queryKey:["resource-by-id","visual",S],exact:!0})},onError:()=>{i(!1),f.ue.error("Failed to update visual")}})};return e.jsx(s.Button,{onClick:g,className:r,size:"xs",variant:a,children:n?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Saving"]}):e.jsxs(e.Fragment,{children:[e.jsx(ke.Save,{className:"h-3.5 w-3.5"}),"Save to Library"]})})}function Re({className:r}){const a=f.useQueryClient(),[o,n]=C.useState(!1),i=f.useSelectedVisual(),c=s.useEditorStore(k=>k.frame),m=s.useDashboardStore(k=>k.selectedSheetId),x=s.useDashboardStore(k=>k.dashboard),{updateFrame:p,setIsVisualEditing:v}=s.useDashboardActions(),{getUpdatedFrame:g}=ae(),h=f.useUpdateVisualMutation(),S=f.useResolveExistingFrameSemanticExecutionPayload(),w=async()=>{if(!m){f.ue.error("No sheet selected");return}const k=(c==null?void 0:c.visualId)||(i==null?void 0:i.id);if(!k){f.ue.error("No visual to update");return}n(!0);try{const E=g();if(!me(E)){n(!1);return}const I={...E,visualId:k},U=f.findDashboardFrameById(x,I.id),Y=await S(I,{previousFrame:U});await h.mutateAsync({visualId:k,data:{frameObject:E}}),p(m,I,{semanticExecutionPayload:Y}),a.invalidateQueries({queryKey:["visuals"]}),a.invalidateQueries({queryKey:["visual",k]}),f.ue.success("Saved to library and applied locally"),setTimeout(()=>{v(!1)},300)}catch(E){console.error("Failed to save and apply:",E),f.ue.error(E instanceof Error?E.message:"Failed to save and apply changes")}finally{n(!1)}};return e.jsx(s.Button,{onClick:w,className:r,size:"xs",variant:"default",disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ke.Save,{className:"h-3.5 w-3.5"}),"Save & Apply"]})})}function Qe({className:r}){const{setTempQueryData:a,setSqlGen:o}=s.useEditorActions(),n=f.useQueryClient(),i=s.useEditorStore(h=>h.tempQueryData),c=s.useEditorStore(h=>h.onClose),m=s.useEditorStore(h=>h.card),x=pe(),p=C.useMemo(()=>x!==m.type?{...m,type:x}:m,[m,x]),{queryKey:v}=f.useEditorCardQuery(p);function g(){if(i){const{queryKey:h,queryData:S}=i;h&&S&&n.setQueryData(h,S)}o({}),c==null||c()}return e.jsxs(s.Button,{onClick:g,className:r,size:"xs",variant:"outline",children:[e.jsx(ee.X,{className:"h-3.5 w-3.5"}),"Close"]})}function Pe({label:r="Clear",variant:a="secondary",className:o}={}){const{setTempQueryData:n}=s.useEditorActions(),i=f.useQueryClient(),c=s.useEditorStore(q=>q.tempQueryData),m=s.useEditorStore(q=>q.card),x=pe(),p=C.useMemo(()=>x!==m.type?{...m,type:x}:m,[m,x]),{queryKey:v}=f.useEditorCardQuery(p),{setCardSql:g,setSqlGen:h,setCardPython:S,setCardCustomCfg:w,setCardPreferences:k,clearQueryConfig:E,setCardConfig:I,setCardType:U,setFrame:Y,setCard:H,setActiveTabCardId:K}=s.useEditorActions();function J(){var W,G,_,z;const q=i.getQueryData(v);c!=null&&c.queryData||n({queryKey:v,queryData:q}),i.setQueryData(v,null),i.removeQueries({queryKey:v,exact:!0}),g(""),h({}),E(),I(void 0),S(""),w(""),k({});const l=s.useEditorStore.getState().frame,D=s.useEditorStore.getState().card,T=f.findCustomVisualConfigCard(l,D),M=((W=T==null?void 0:T.customCardPreferences)==null?void 0:W.visualType)==="multiple"||!!((G=T==null?void 0:T.customCardPreferences)!=null&&G.dataInputCardIds)||(((_=T==null?void 0:T.customCardPreferences)==null?void 0:_.minInputs)||0)>1||(((z=T==null?void 0:T.customCardPreferences)==null?void 0:z.maxInputs)||0)>1,Q=Oe(D,M);Y({...l,cards:l.cards.map($=>$.id===Q.id?Q:$)}),K(Q.id),H(Q),M||U("bar")}return e.jsxs(s.Button,{onClick:J,className:o,size:"xs",variant:a,children:[e.jsx(ee.X,{className:"h-3.5 w-3.5"}),r]})}function Fe(r){const{control:a,onChange:o}=r;return e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),e.jsx(s.Input,{size:"xs",value:a.label,placeholder:"Control label",onChange:n=>o(n.target.value)})]})}function $e(r){const{currentStep:a,labels:o}=r;return e.jsx("div",{className:"sticky top-0 z-10 -mx-1 border-b border-border/60 bg-background/95 px-1 pb-2.5 pt-1 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:e.jsx("div",{className:"flex flex-wrap items-center gap-2 sm:gap-2.5",children:o.map((n,i)=>{const c=i+1,m=c===a,x=c<a;return e.jsxs(C.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:s.cn("flex h-5 w-5 items-center justify-center rounded-full border text-[10px] font-medium tabular-nums",m?"border-foreground bg-foreground text-background":x?"border-foreground/30 bg-foreground/10 text-foreground":"border-border/60 bg-background text-muted-foreground"),children:c}),e.jsx("span",{className:s.cn("text-[12px]",m?"font-medium text-foreground":"text-muted-foreground"),children:n})]}),i<o.length-1?e.jsx("span",{className:"h-px w-4 bg-border/60 sm:w-6","aria-hidden":"true"}):null]},n)})})})}function se(r){const{secondary:a,tertiary:o,primary:n}=r;return e.jsxs("div",{className:"sticky bottom-0 z-10 -mx-1 flex justify-end gap-2 border-t bg-background/95 px-1 pb-1 pt-3 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:[a,o,n]})}function Ye(r){const{control:a,scope:o,detail:n}=r;return e.jsxs("div",{className:"flex items-start gap-2.5 rounded-control border border-border/60 bg-muted/30 px-3 py-2.5",children:[e.jsx(f.CircleCheck,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground"}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:a.label}),e.jsxs("div",{className:"text-[12px] text-muted-foreground",children:[s.getFriendlyTypeOption(a.type).label," ·"," ",s.getControlOptionPreview(a)," ·"," ",s.getPlacementLabel(o,a.placement)]}),n?e.jsx("div",{className:"text-[12px] text-muted-foreground",children:n}):null]})]})}function Ce(r){const{control:a,defaultValue:o,availableFieldChoices:n,availableMetricChoices:i,previewControlDefinitions:c,previewControlValues:m,onControlChange:x,onLabelChange:p,onDefaultValueChange:v,onBack:g,onNext:h,nextDisabled:S}=r;return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fe,{control:a,onChange:p}),e.jsx(f.ControlDefinitionOptionsEditor,{control:a,availableFieldChoices:n,availableMetricChoices:i,previewControlDefinitions:c,previewControlValues:m,controlLifecycle:"create",onChange:x}),e.jsx(f.ControlDefaultValueEditor,{control:a,value:o,onChange:v,allowNoDefault:!0,allowCardDefault:!0,hint:"This is the value viewers will see first.",previewControlDefinitions:c,previewControlValues:m}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:g,children:"Back"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:h,disabled:S,children:"Next"})})]})}const Ke=new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]);function Se(r){const{text:a,ariaLabel:o}=r,[n,i]=C.useState(!1);return e.jsxs("button",{type:"button","aria-label":o,onClick:async()=>{try{await navigator.clipboard.writeText(a),i(!0),setTimeout(()=>i(!1),1200)}catch(c){console.error("Failed to copy",c)}},className:"group flex w-full items-center justify-between gap-2 rounded-control bg-muted/40 px-2 py-1 text-left transition-colors hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none",children:[e.jsx("code",{className:"min-w-0 truncate font-mono text-[12px] text-foreground",children:a}),e.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:n?"Copied":"Click to copy"})]})}function je(r){const{control:a,scope:o,createdReference:n,explorerContent:i,sqlDescription:c,summaryDetail:m,onBack:x,onCancel:p,onDone:v}=r,g=Ke.has(a.type),h=n.match(/\[\[param\.(.+?)\]\]/),S=h?`{{ param('${h[1]}') }}`:"";return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ye,{control:a,scope:o,detail:m}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[13px] font-medium text-foreground",children:"How cards use this control"}),e.jsxs("div",{className:"divide-y divide-border/60 overflow-hidden rounded-control border border-border/60",children:[g?e.jsxs("div",{className:"space-y-1 px-3 py-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Explorer cards"}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:i})]}):null,e.jsxs("div",{className:"space-y-1.5 px-3 py-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL cards"}),e.jsx(Se,{text:n,ariaLabel:"Copy SQL control reference"}),S?e.jsx(Se,{text:S,ariaLabel:"Copy Jinja control reference"}):null,e.jsxs("p",{className:"text-[12px] text-muted-foreground",children:[c," ",e.jsx("a",{href:"https://docs.semaphor.cloud/docs/concepts/template-expressions",target:"_blank",rel:"noreferrer",className:"underline underline-offset-2 hover:text-foreground",children:"Template expressions docs"}),"."]})]})]})]}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:x,children:"Back"}),tertiary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:p,children:"Cancel"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:v,children:"Done"})})]})}function We(r){const a=s.createBlankControl(r.scope,r.existingControls,r.reservedIds),o=r.type===a.type?{...a,label:s.DEFAULT_LABEL_BY_TYPE[r.type]}:{...s.applyControlTypeChange({controls:[{...a,label:s.DEFAULT_LABEL_BY_TYPE[r.type]}],controlId:a.id,nextType:r.type}).controls[0],label:s.DEFAULT_LABEL_BY_TYPE[r.type]};return{step:2,control:o,defaultValue:s.getDefaultValueForType(o,void 0)}}function He({scope:r,controls:a,reservedControlIds:o,defaultValues:n,onChange:i,emptyMessage:c,initialCreateFlow:m=!1,usageByControlId:x,availableFieldChoices:p,availableMetricChoices:v,structuralParticipants:g,structuralParticipantIdsByControlId:h,card:S,allowedControlTypes:w,onCreateFlowActiveChange:k,onCreateFlowComplete:E}){const I=C.useMemo(()=>new Set(o||[]),[o]),U=s.getPlacementOptionsForScope(r),Y=s.getDefaultPlacement(r),[H,K]=C.useState(null),[J,q]=C.useState(null),[l,D]=C.useState(()=>m?{step:1,control:s.createBlankControl(r,a,Array.from(I))}:null),T=C.useRef({}),M=C.useRef(void 0),Q=C.useRef(m),W=C.useMemo(()=>{const t=s.getFriendlyControlTypeOptions({scope:r,card:S});if(!w)return t;const u=new Set(w);return t.filter(d=>u.has(d.value))},[w,S,r]),G=C.useCallback(t=>{const u=s.getFriendlyControlTypeOptions({scope:r,card:S,includeType:w?void 0:t});if(!w)return u;const d=new Set(w);return u.filter(b=>d.has(b.value))},[w,S,r]),_=C.useCallback(t=>r==="dashboard"&&(t==="field_selector"||t==="metric_selector"),[r]),z=C.useMemo(()=>l?s.getEligibleParticipantsForStructuralControl(g||[],l.control.type):[],[l,g]),$=C.useMemo(()=>{if(!l)return{fields:p||[],metrics:v||[]};if(!_(l.control.type))return{fields:p||[],metrics:v||[]};const t=l.selectedCardIds||[],u=s.getCompatibleStructuralChoiceCatalog({controlType:l.control.type,participants:g||[],selectedCardIds:t});return{fields:l.control.type==="field_selector"?u.choices.map(d=>({option:d,target:u.fieldTargetMap[d.value]})):[],metrics:l.control.type==="metric_selector"?u.choices.map(d=>({option:d,target:u.metricTargetMap[d.value]})):[]}},[p,v,l,_,g]);C.useEffect(()=>{k==null||k(!!l)},[l,k]),C.useEffect(()=>{const t=m&&!Q.current;Q.current=m,t&&(D({step:1,control:s.createBlankControl(r,a,Array.from(I))}),q(null),K(null))},[a,m,I,r]);const ne=t=>{if(!_(t.type))return{fields:p||[],metrics:v||[]};const u=(h==null?void 0:h[t.id])||[];if(u.length===0)return{fields:p||[],metrics:v||[]};const d=s.getCompatibleStructuralChoiceCatalog({controlType:t.type,participants:g||[],selectedCardIds:u});return{fields:t.type==="field_selector"?d.choices.map(b=>({option:b,target:d.fieldTargetMap[b.value]})):[],metrics:t.type==="metric_selector"?d.choices.map(b=>({option:b,target:d.metricTargetMap[b.value]})):[]}},A=t=>{if(!_(t.control.type))return{nextControl:t.control,cardBindingsById:void 0};const u=(h==null?void 0:h[t.control.id])||[],d=s.getCompatibleStructuralChoiceCatalog({controlType:t.control.type,participants:g||[],selectedCardIds:t.nextSelectedCardIds}),b=s.reconcileStructuralControlChoices({control:t.control,choices:d.choices}),j=Object.fromEntries(u.filter(N=>!t.nextSelectedCardIds.includes(N)).map(N=>[N,void 0]));return t.nextSelectedCardIds.length>0&&b.source.kind==="manual"&&b.source.options.length>0&&Object.assign(j,s.buildStructuralControlBindingsForParticipants({control:b,participants:g||[],selectedCardIds:t.nextSelectedCardIds})),{nextControl:b,cardBindingsById:j}},F=C.useCallback((t,u=n,d={type:"update"})=>{const b=t.map(j=>(s.resolveAuthoringControlDefaultValue({control:j,defaultValues:u}),s.syncSqlQueryControlExecutionRequirement(j)));i(b,u,d)},[n,i]),P=(t,u)=>{const d=a.find(L=>L.id===t);let b=a.map(L=>L.id!==t?L:u(L));const j=b.find(L=>L.id===t);let N,y;if(j&&r==="dashboard"&&(j.type==="field_selector"||j.type==="metric_selector")){const L=(h==null?void 0:h[j.id])||[],Z=A({control:j,nextSelectedCardIds:L});b=b.map(X=>X.id===t?Z.nextControl:X),N=Z.cardBindingsById,y=[j.id]}else if(d&&r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")){const L=(h==null?void 0:h[d.id])||[];N=Object.fromEntries(L.map(Z=>[Z,void 0])),y=[d.id]}const V=b.find(L=>L.id===t);let O=n;if(d&&V){const L=s.resolveAuthoringControlDefaultValue({control:d,defaultValues:n});d.source.kind==="manual"&&V.source.kind==="sql_query"&&(T.current[t]=L);const Z=L===void 0&&d.source.kind==="sql_query"&&V.source.kind==="manual"?T.current[t]:L,X=s.getNextEditedControlDefaultValue({previousControl:d,nextControl:V,currentDefaultValue:Z});V.source.kind==="manual"&&(T.current[t]=X),n&&(O={...n},X===void 0?delete O[t]:O[t]=X),b=b.map(be=>be.id===t?{...V,defaultValue:X}:be)}F(b,O,{type:"update",cardBindingsById:N,affectedBindingControlIds:y})},B=(t,u)=>{if(!u.trim())return;const d=f.normalizeDashboardInputVariableName(u);if(d===t||I.has(d)||a.some(N=>N.id===d&&N.id!==t))return;const b=a.map(N=>N.id===t?{...N,id:d}:N);if(!n){F(b,void 0,{type:"rename",oldId:t,newId:d});return}const j={...n};Object.prototype.hasOwnProperty.call(j,t)&&(j[d]=j[t],delete j[t]),F(b,j,{type:"rename",oldId:t,newId:d})},oe=t=>{const u=a.filter(b=>b.id!==t);if(!n){F(u,void 0,{type:"remove",controlId:t});return}const d={...n};delete d[t],F(u,d,{type:"remove",controlId:t})},re=C.useCallback(()=>{M.current=void 0,D({step:1,control:s.createBlankControl(r,a,Array.from(I))}),q(null),K(null)},[a,I,r]),R=t=>{D(u=>u&&(()=>{const d=t(u.control);u.control.source.kind==="manual"&&d.source.kind==="sql_query"&&(M.current=u.defaultValue);const b=u.defaultValue===void 0&&u.control.source.kind==="sql_query"&&d.source.kind==="manual"?M.current:u.defaultValue,j=s.getNextEditedControlDefaultValue({previousControl:u.control,nextControl:d,currentDefaultValue:b});return d.source.kind==="manual"&&(M.current=j),{...u,control:d,defaultValue:j}})())},te=t=>{D(u=>u&&(u.control.source.kind==="manual"&&(M.current=t),{...u,defaultValue:t}))},le=(()=>{if(!l)return!1;if(l.step===2&&_(l.control.type))return(l.selectedCardIds||[]).length>0;if(l.step!==2&&l.step!==3||!l.control.label.trim())return!1;const u=l.control.source.kind==="sql_query"?l.control:s.ensureManualSource(l.control);if(u.source.kind==="manual"&&(s.needsManualOptions(u)&&u.source.options.length===0||u.source.options.some(b=>b.label.trim().length===0||b.value.trim().length===0)))return!1;if(u.source.kind==="sql_query"){const{connectionId:d,sql:b,valueColumn:j}=u.source;return d.trim().length>0&&b.trim().length>0&&j.trim().length>0}return s.hasConcreteDefaultValue(s.getDefaultValueForType(u,l.defaultValue))})(),fe=()=>{var N;if(!l)return;const t=s.ensureManualSource(l.control),u=s.deriveUniqueControlId({label:t.label,fallbackId:t.id,existingControls:a,reservedIds:Array.from(I)}),d={...t,id:u},b=r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")&&((N=l.selectedCardIds)!=null&&N.length)?s.buildStructuralControlBindingsForParticipants({control:d,participants:g||[],selectedCardIds:l.selectedCardIds}):void 0,j=s.getDefaultValueForType(d,l.defaultValue);D({step:r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")?4:3,control:d,defaultValue:j,createdControlId:u,selectedCardIds:l.selectedCardIds,cardBindingsById:b})},ie=C.useCallback(()=>{D(null)},[]),xe=C.useCallback(()=>{if(!(l!=null&&l.createdControlId)){D(null);return}const t=l.control,u=l.createdControlId,d=s.getDefaultValueForType(t,l.defaultValue);if(n){const b={...n};d===void 0?delete b[u]:b[u]=d,F([...a,{...t,defaultValue:d}],b,{type:"add",cardBindingsById:l.cardBindingsById})}else F([...a,{...t,defaultValue:d}],void 0,{type:"add",cardBindingsById:l.cardBindingsById});q(u),D(null),E==null||E()},[a,l,n,F,E]),Ve=l?_(l.control.type)?["Choose type","Select cards","Configure","Finish"]:["Choose type","Configure","Finish"]:[],he=l!=null&&l.createdControlId?`[[param.${l.createdControlId}]]`:l?`[[param.${s.slugifyControlValue(l.control.label)||l.control.id}]]`:"",de=s.buildAuthoringPreviewControlValues({controls:a,defaultValues:n}),ce=l?[...a,l.control]:a,ge=l?s.buildAuthoringPreviewControlValues({controls:ce,defaultValues:n,overrides:[{controlId:l.control.id,value:l.defaultValue}]}):de;return e.jsxs("div",{className:"space-y-4",children:[l?e.jsxs("div",{className:"space-y-4 pb-1",children:[e.jsx($e,{currentStep:l.step,labels:Ve}),l.step===1&&(()=>{const t=new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]),u=new Set(["date","text"]),d=W.filter(N=>!t.has(N.value)&&!u.has(N.value)),b=W.filter(N=>t.has(N.value)),j=N=>e.jsxs("button",{type:"button",className:"rounded-control border border-border/60 bg-background px-3 py-2.5 text-left transition-colors hover:bg-muted/40 focus-visible:bg-muted/40 focus-visible:outline-none",onClick:()=>D(We({scope:r,existingControls:a,reservedIds:Array.from(I),type:N.value})),children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:N.label}),e.jsx("p",{className:"mt-0.5 text-[12px] text-muted-foreground",children:N.description})]},N.value);return e.jsxs("div",{className:"space-y-4",children:[r==="card"&&(S==null?void 0:S.sql)==null?e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Explorer cards support displayed metric, group by field, aggregation, and time grain controls here."}):null,d.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Input controls"}),e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:d.map(j)})]}),b.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data-driven controls"}),e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:b.map(j)})]}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:ie,children:"Back to controls"})})]})})(),l.step===2&&_(l.control.type)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fe,{control:l.control,onChange:t=>R(u=>({...u,label:t}))}),e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Choose which cards should respond to this shared control."})]}),z.length===0?e.jsx("div",{className:"rounded-control border border-border/60 bg-muted/30 px-3 py-2.5 text-[12px] text-muted-foreground",children:"No eligible cards are available yet. Add compatible metrics or group-by fields to cards first."}):e.jsx("div",{className:"space-y-1 rounded-control border border-border/60 bg-background p-2",children:z.map(t=>{const u=(l.selectedCardIds||[]).includes(t.cardId);return e.jsxs("label",{className:"flex items-start gap-2 rounded-control px-1.5 py-1 text-[13px] hover:bg-muted/40",children:[e.jsx(f.Checkbox,{checked:u,onCheckedChange:d=>D(b=>b&&{...b,selectedCardIds:d===!0?[...b.selectedCardIds||[],t.cardId]:(b.selectedCardIds||[]).filter(j=>j!==t.cardId)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-foreground",children:t.title}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:l.control.type==="field_selector"?`${t.fieldChoices.length} compatible group-by fields`:`${t.metricChoices.length} compatible metrics`})]})]},t.cardId)})}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:()=>D(t=>t&&{...t,step:1,selectedCardIds:[]}),children:"Back"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:()=>D(t=>t&&{...t,step:3}),disabled:!le,children:"Next"})})]}),l.step===2&&!_(l.control.type)&&e.jsx(Ce,{control:l.control,defaultValue:l.defaultValue,availableFieldChoices:$.fields,availableMetricChoices:$.metrics,previewControlDefinitions:ce,previewControlValues:ge,onControlChange:t=>R(()=>t),onLabelChange:t=>R(u=>({...u,label:t})),onDefaultValueChange:te,onBack:()=>D(t=>t&&{...t,step:1}),onNext:fe,nextDisabled:!le}),l.step===3&&_(l.control.type)&&e.jsx(Ce,{control:l.control,defaultValue:l.defaultValue,availableFieldChoices:$.fields,availableMetricChoices:$.metrics,previewControlDefinitions:ce,previewControlValues:ge,onControlChange:t=>R(()=>t),onLabelChange:t=>R(u=>({...u,label:t})),onDefaultValueChange:te,onBack:()=>D(t=>t&&{...t,step:2}),onNext:fe,nextDisabled:!le}),l.step===3&&!_(l.control.type)&&e.jsx(je,{control:l.control,scope:r,createdReference:he,explorerContent:e.jsxs(e.Fragment,{children:["Open the card and use"," ",e.jsx("span",{className:"font-medium text-foreground",children:"Settings → Controls"})," ","to choose what this control changes."]}),sqlDescription:"Reference this control directly in the SQL editor.",onBack:()=>D(t=>t&&{...t,step:2}),onCancel:ie,onDone:xe}),l.step===4&&_(l.control.type)&&e.jsx(je,{control:l.control,scope:r,createdReference:he,summaryDetail:e.jsxs(e.Fragment,{children:["Used by ",(l.selectedCardIds||[]).length," selected card",(l.selectedCardIds||[]).length===1?"":"s"]}),explorerContent:e.jsx(e.Fragment,{children:"Selected cards have been set up to respond to this control automatically."}),sqlDescription:"SQL cards can still reference this control directly in the SQL editor.",onBack:()=>D(t=>t&&{...t,step:3}),onCancel:ie,onDone:xe})]}):null,!l&&a.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:c}):null,!l&&a.map(t=>{const u=ne(t),d=x==null?void 0:x[t.id],b=s.resolveAuthoringControlDefaultValue({control:t,defaultValues:n}),j=J===t.id,N="inline-flex shrink-0 items-center rounded-[4px] border border-border/60 bg-muted/40 px-1.5 py-0.5 text-[11px] font-medium text-muted-foreground";return e.jsxs("div",{className:"rounded-control border border-border/60",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 rounded-control text-left focus:outline-none focus-visible:bg-muted/40",onClick:()=>q(y=>y===t.id?null:t.id),children:[j?e.jsx(ee.ChevronDown,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(ye.ChevronRight,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:t.label||"Untitled control"}),e.jsx("span",{className:N,children:s.getFriendlyTypeOption(t.type).label}),e.jsx("span",{className:N,children:s.getPlacementLabel(r,t.placement)})]}),e.jsxs("div",{className:"mt-0.5 text-[12px] text-muted-foreground",children:[s.getControlOptionPreview(t),d!=null&&d.status?` · ${d.status}`:""]})]})]}),e.jsx(s.Button,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0 text-muted-foreground",onClick:()=>oe(t.id),"aria-label":`Remove ${t.label}`,children:e.jsx(f.Trash2,{className:"h-3.5 w-3.5"})})]}),j&&e.jsxs("div",{className:"space-y-4 border-t border-border/60 px-3 py-3",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),e.jsx(s.Input,{size:"xs",value:t.label,placeholder:"Control label",onChange:y=>P(t.id,V=>({...V,label:y.target.value}))})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Type"}),e.jsxs(s.Select,{value:t.type,onValueChange:y=>{const V=s.applyControlTypeChange({controls:a,controlId:t.id,nextType:y,defaultValues:n});F(V.controls,V.defaultValues)},children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:G(t.type).map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Show in"}),e.jsxs(s.Select,{value:t.placement||Y,onValueChange:y=>P(t.id,V=>({...V,placement:y})),children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:U.map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]})]}),_(t.type)?e.jsx(f.StructuralParticipantSelector,{type:t.type,participants:s.getEligibleParticipantsForStructuralControl(g||[],t.type).map(y=>({cardId:y.cardId,title:y.title,choiceCount:t.type==="field_selector"?y.fieldChoices.length:y.metricChoices.length})),selectedCardIds:(h==null?void 0:h[t.id])||[],onChange:y=>{const V=A({control:t,nextSelectedCardIds:y}),O=a.map(L=>L.id===t.id?V.nextControl:L);F(O,n,{type:"update",cardBindingsById:V.cardBindingsById})}}):null,e.jsx(f.ControlDefinitionOptionsEditor,{control:t,availableFieldChoices:u.fields,availableMetricChoices:u.metrics,previewControlDefinitions:a,previewControlValues:de,controlLifecycle:"edit",onChange:y=>P(t.id,()=>y)}),t.initialValueStrategy==="saved_default"&&e.jsx(f.ControlDefaultValueEditor,{control:t,value:b,allowNoDefault:!0,allowCardDefault:!0,previewControlDefinitions:a,previewControlValues:de,onChange:y=>{const V=a.map(O=>O.id===t.id?{...O,defaultValue:y}:O);if(t.source.kind==="manual"&&(T.current[t.id]=y),n){const O={...n};y===void 0?delete O[t.id]:O[t.id]=y,F(V,O);return}F(V,void 0)}}),e.jsxs(f.Collapsible,{open:H===t.id,onOpenChange:y=>K(y?t.id:null),children:[e.jsx(f.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{type:"button",variant:"ghost",size:"xs",className:"-ml-2 gap-1 text-muted-foreground hover:text-foreground",children:[H===t.id?e.jsx(ee.ChevronDown,{className:"h-3.5 w-3.5"}):e.jsx(ye.ChevronRight,{className:"h-3.5 w-3.5"}),"Advanced"]})}),e.jsxs(f.CollapsibleContent,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Variable name"}),e.jsx(f.ControlIdInput,{controlId:t.id,onCommit:y=>B(t.id,y)},t.id)]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Initial value"}),e.jsxs(s.Select,{value:t.initialValueStrategy,onValueChange:y=>P(t.id,V=>({...V,initialValueStrategy:y})),children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:s.INITIAL_VALUE_STRATEGY_OPTIONS.map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]})]}),e.jsx(f.ControlVisibilitySettings,{control:t,onChange:y=>P(t.id,()=>y)})]})]})]})]},t.id)}),!l&&e.jsxs(s.Button,{type:"button",variant:"outline",size:"xs",onClick:re,children:[e.jsx(f.Plus,{className:"h-3.5 w-3.5"}),"Add control"]})]})}function Ge(r){const{open:a,onOpenChange:o,initialCreateFlowActive:n=!1,dismissMode:i="passive"}=r,c=a!==void 0,[m,x]=C.useState(!1),[p,v]=C.useState(n),g=c?a:m,h=C.useCallback(k=>{!k&&p&&i==="passive"||(c||x(k),k||v(!1),o==null||o(k))},[c,p,i,o]),S=C.useCallback(()=>{c||x(!1),v(!1),o==null||o(!1)},[c,o]);C.useEffect(()=>{g||v(!1)},[g]);const w=C.useCallback(k=>{p&&k.preventDefault()},[p]);return{forceClose:S,handleOpenChange:h,isCreateFlowActive:p,preventPassiveDismissDuringCreate:w,resolvedOpen:g,setIsCreateFlowActive:v}}exports.ControlDefinitionListEditor=He;exports.EditorAcceptButton=Ue;exports.EditorCancelButton=Qe;exports.EditorClearButton=Pe;exports.Library=Ne;exports.Link2=Ee;exports.VisualBadge=Me;exports.VisualSaveAndApplyButton=Re;exports.VisualSaveButton=ze;exports.flushPendingEditorDrafts=we;exports.registerPendingEditorDraftFlusher=Le;exports.useCreateFlowOverlayState=Ge;exports.useEffectiveEditorCardType=pe;exports.useSyncLegacyEditorState=qe;exports.useVisualUtils=ae;
|
|
11
|
+
*/const Ee=ee.createLucideIcon("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);function Ie(r){const[a,o]=C.useState(null),[n,i]=C.useState(null),c=f.useEnsureReactGlobals();return C.useEffect(()=>{if(!r||r.trim()===""){o(null),i(null);return}if(!c)return;(async()=>{try{if(!r.startsWith("http://")&&!r.startsWith("https://"))throw new Error(`Invalid URL format: ${r}`);try{new URL(r)}catch{throw new Error(`Invalid URL: ${r}`)}const p=`${r.endsWith("/")?r:`${r}/`}index.js`;try{if(!(await fetch(p,{method:"HEAD"})).ok)throw new Error(`Module not found at ${p}`)}catch{}const v=await import(p);if(typeof v.useChartStore!="function")throw new Error("useChartStore is not a function");o(()=>v.useChartStore),i(null)}catch(x){const p=x instanceof Error?x.message:"Unknown error";console.error("Failed to load remote chart store:",p),i(p),o(null)}})()},[r,c]),a}function Te(r,a){if(r.length===0)return"";const o=r.find(n=>{var i,c;return((i=n.customCardPreferences)==null?void 0:i.visualType)==="multiple"||!!((c=n.customCardPreferences)!=null&&c.dataInputCardIds)});if(o)return o.id;if(a){const n=r.find(i=>i.id===a);if(n){const i=n.tabTitle;if(i=="All__Header")return r[0].id;if(i&&i.endsWith("__Header")){const m=i.split("__")[0],x=r.find(p=>p.tabTitle===m);return x?x.id:r[0].id}return a}}return r[0].id}const ue=new Set;function Le(r){return ue.add(r),()=>{ue.delete(r)}}function De(){ue.forEach(r=>{r()})}const Ae=r=>{if(!r||!("detailTableBackup"in r))return r;const{detailTableBackup:a,...o}=r;return o};async function ve(r,a,o,n,i="Opening library visual..."){if(!a||!o)throw new Error("Missing auth token or visual ID");const c=["resource-by-id","visual",o],m=n.getQueryData(c);if(m)return console.log("Using cached visual data for:",o),{data:m,fromCache:!0};console.log("Fetching visual data from network for:",o);const x=f.ue.loading(i,{position:"top-center"});try{const p=await fetch(`${r}/management/v1/visuals/${o}`,{headers:{Authorization:`Bearer ${a}`}});if(!p.ok)throw new Error("Failed to load visual");const v=await p.json();return n.setQueryData(c,v),f.ue.dismiss(x),{data:v,fromCache:!1}}catch(p){throw f.ue.dismiss(x),p}}function we(r){if(typeof r=="string")return JSON.parse(r);if(typeof r=="object")return r;throw new Error("Invalid frame object format")}function _e(r,a){var c,m;const o=(r==null?void 0:r.frameObject)??((c=r==null?void 0:r.visual)==null?void 0:c.frameObject);if(!o)return!1;const n=we(o);if(!(n!=null&&n.cards)||n.cards.length===0)return!1;const i=(m=n.cards)==null?void 0:m.find(x=>x.id===n.activeCardId);return i?(f.setupEditorWithCard({...a,frame:n,card:i,visualId:(r==null?void 0:r.id)||n.visualId}),!0):!1}function Be(){const r=s.useEditorStore(n=>{var i;return((i=n.card.customCardPreferences)==null?void 0:i.url)||""}),a=Ie(r);return{getUpdatedFrame:C.useCallback(()=>{var I;De();const{frame:n,card:i,isDevMode:c,isShowingVisual:m,selectedSchemaName:x,selectedDatamodelId:p,selectedDatabaseName:v,selectedTableName:g,selectedConnectionId:h}=s.useEditorStore.getState(),S=i.sql,D=(I=a==null?void 0:a.getState())==null?void 0:I.settings,k=s.buildSavedEditorCard(i,{isDevMode:c,cardSql:S,isShowingVisual:m,selectedSchemaName:x,selectedDatamodelId:p,selectedDatabaseName:v,selectedTableName:g,selectedConnectionId:h,remoteChartSettings:D,stripConfig:Ae}),E=n.cards.map(U=>U.id===i.id?k:U);return{...n,cards:E,activeCardId:Te(E,n.activeCardId)}},[a])}}function ae(){const{authToken:r,tokenProps:a}=f.useSemaphorContext(),o=f.useQueryClient(),n=f.useAddFrameWithFreshSemanticExecutionPayload(),i=f.useSelectedVisual(),{selectVisual:c}=f.useManagementActions(),{setFrame:m,setCard:x,setIsDevMode:p,initializeModeDrafts:v,setActiveTabCardId:g,updateDataSource:h,setQueryResultColumns:S,setSelectedConnectionId:D,setSelectedDatabaseName:k,setSelectedSchemaName:E,setSelectedTableName:I,setSelectedDatamodelId:U,setFilterValues:Y,setInlineFilterValuesMap:H,setApplyFilters:K,clearEditorContext:J}=s.useEditorActions(),{setIsDashboardEditing:q,setIsVisualEditing:l,setSelectedFrameId:w,clearSelectedFrameId:T}=s.useDashboardActions(),M=s.useDashboardStore(A=>A.selectedSheetId),Q=s.useDashboardStore(A=>A.selectedFrameId),W=s.useDashboardStore(A=>A.dashboard),G=s.useDashboardStore(A=>A.filterValues),_=s.useDashboardStore(A=>A.inlineFilterValuesMap),z=f.useVisualById((i==null?void 0:i.id)||"",{enabled:!!(i!=null&&i.id)&&!!(r!=null&&r.accessToken)}),$=C.useCallback(async A=>{try{c(A),T(),J();const{data:F,fromCache:P}=await ve(a.apiServiceUrl,(r==null?void 0:r.accessToken)||"",A.id,o,"Opening library visual...");if(!_e(F,{setFrame:m,setCard:x,setIsDevMode:p,initializeModeDrafts:v,setActiveTabCardId:g,updateDataSource:h,setQueryResultColumns:S,setSelectedConnectionId:D,setSelectedDatabaseName:k,setSelectedSchemaName:E,setSelectedTableName:I,setSelectedDatamodelId:U,setFilterValues:Y,setInlineFilterValuesMap:H,setApplyFilters:K,setIsDashboardEditing:q,setIsVisualEditing:l,dashboard:W,selectedSheetId:M,selectedFrameId:Q,filterValues:G,inlineFilterValuesMap:_}))throw new Error("Failed to setup editor with visual data");return{success:!0,fromCache:P}}catch(F){return console.error("Error editing visual:",F),{success:!1,error:"Failed to load visual for editing"}}},[r==null?void 0:r.accessToken,a.apiServiceUrl,o,c,m,x,q,l,p,v,g,h,S,D,k,E,I,U,Y,H,K,J,T,W,M,Q,G,_]),ne=C.useCallback(async A=>{var P;const F=B=>(f.ue.error(B),{success:!1,error:B});try{if(c(A),!M)return F("No sheet selected. Please select a sheet first.");const{data:B,fromCache:oe}=await ve(a.apiServiceUrl,(r==null?void 0:r.accessToken)||"",A.id,o,"Adding visual to dashboard..."),re=(B==null?void 0:B.frameObject)??((P=B==null?void 0:B.visual)==null?void 0:P.frameObject);if(!re)return F("Visual has no frame data");const R=we(re);if(!(R!=null&&R.cards)||R.cards.length===0)return F("Visual frame is malformed");const te={...f.cloneLinkedFrameWithSourceMapping(R),visualId:A.id};return await n(M,te,"end"),q(!0),w(te.id),{success:!0,fromCache:oe}}catch(B){return console.error("Error adding visual:",B),F(B instanceof Error?B.message:"Failed to add visual to dashboard")}},[r==null?void 0:r.accessToken,a.apiServiceUrl,o,c,M,q,w,n]);return{visual:z.data,isLoading:z.isLoading,isError:z.isError,error:z.error,handleEditLibraryVisual:$,handleAddLibraryVisual:ne,getUpdatedFrame:Be().getUpdatedFrame,refetch:z.refetch}}function qe(){const r=s.useEditorStore(m=>m.card.dataSource),{setSelectedConnectionId:a,setSelectedDatabaseName:o,setSelectedSchemaName:n,setSelectedTableName:i,setSelectedDatamodelId:c}=s.useEditorActions();C.useEffect(()=>{var D;if(!r)return;const{tableName:m,schemaName:x,databaseName:p,connectionId:v}=f.extractTableMetadata(r),g=(D=r.selectedEntities)==null?void 0:D[0],S=(g==null?void 0:g.type)==="model"&&"id"in g?g.id:"";a(v||""),o(p||""),n(x||""),i(m||""),c(S)},[r,a,o,n,i,c])}function pe(){var p,v;const r=s.useEditorStore(g=>g.card),a=s.useEditorStore(g=>g.frame),o=C.useMemo(()=>f.findCustomVisualConfigCard(a,r),[a,r]),{manifest:n}=f.useCustomVisual(((p=o==null?void 0:o.customCardPreferences)==null?void 0:p.url)||""),i=C.useMemo(()=>{var g;return(g=n==null?void 0:n.visuals)==null?void 0:g.find(h=>{var S;return h.name===((S=o==null?void 0:o.customCardPreferences)==null?void 0:S.componentName)})},[n,(v=o==null?void 0:o.customCardPreferences)==null?void 0:v.componentName]),c=f.resolveMultiInputType(o,i),m=C.useMemo(()=>f.getCustomVisualInputCards({frame:a,configCard:o,isMultiInputVisual:c==="multiple"}),[a,o,c]),x=C.useMemo(()=>{const g=m.findIndex(h=>(h==null?void 0:h.id)===r.id);return g<0?-1:f.getSlotIndexForCard(r,g)},[m,r]);return C.useMemo(()=>!o||c!=="multiple"||x<0?r.type:f.getEffectiveCardTypeForSlot(r,x,i==null?void 0:i.slots)??r.type,[o,c,x,r,i==null?void 0:i.slots])}function Me({type:r,isLinked:a,className:o,showLabel:n=!1,showLocal:i=!1}){const c=s.useDashboardStore(E=>E.selectedFrameId),m=f.useManagementStore(E=>E.selectedVisual),x=s.useEditorStore(E=>E.frame);let p;if(r)p=r;else if(a!==void 0)p=a?"linked":"library";else if(!!!(x!=null&&x.visualId||m!=null&&m.id)&&c)p="local";else if(m&&!c)p="library";else if(x!=null&&x.visualId&&c)p="linked";else if(m!=null&&m.id&&c)p="library";else return null;if(p==="local"&&!i)return null;const v={local:"border-slate-200/70 bg-slate-50/80 text-slate-700 shadow-sm hover:bg-slate-100/80 dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:bg-slate-800/80",linked:"border-purple-200/70 bg-gradient-to-r from-purple-50/50 to-purple-100/30 text-purple-900 shadow-sm hover:from-purple-100/60 hover:to-purple-100/50 hover:shadow-md dark:border-purple-800/50 dark:from-purple-950/40 dark:to-purple-900/30 dark:text-purple-100 dark:hover:from-purple-950/60 dark:hover:to-purple-900/50",library:"border-blue-200/70 bg-gradient-to-r from-blue-50/50 to-blue-100/30 text-blue-900 shadow-sm hover:from-blue-100/60 hover:to-blue-100/50 hover:shadow-md dark:border-blue-800/50 dark:from-blue-950/40 dark:to-blue-900/30 dark:text-blue-100 dark:hover:from-blue-950/60 dark:hover:to-blue-900/50"},g={local:"Local to this dashboard: Changes made here only affect this dashboard copy.",linked:"Linked to library: Changes made here update the library visual and all linked instances.",library:"Library visual: Share and reuse this visual across multiple dashboards."},h={local:"border-slate-200 bg-slate-50 text-slate-900 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-100",linked:"border-purple-200 bg-purple-50 text-purple-900 dark:border-purple-800 dark:bg-purple-950 dark:text-purple-100",library:"border-blue-200 bg-blue-50 text-blue-900 dark:border-blue-800 dark:bg-blue-950 dark:text-blue-100"},S={local:"fill-slate-50 dark:fill-slate-900",linked:"fill-purple-50 dark:fill-purple-950",library:"fill-blue-50 dark:fill-blue-950"},D={local:e.jsx("span",{className:"h-2 w-2 rounded-full bg-current/70"}),linked:e.jsx(Ee,{className:"h-3.5 w-3.5"}),library:e.jsx(Ne,{className:"h-3.5 w-3.5"})},k={local:"Local",linked:"Linked",library:"Library"};return e.jsx(s.TooltipProvider,{children:e.jsxs(s.Tooltip,{delayDuration:300,children:[e.jsx(s.TooltipTrigger,{asChild:!0,children:e.jsxs(f.Badge,{variant:"outline",className:s.cn("cursor-help select-none transition-all",v[p],o),children:[D[p],n&&e.jsx("span",{className:"ml-1 text-xs font-medium leading-none",children:k[p]})]})}),e.jsxs(s.TooltipContent,{side:"bottom",className:s.cn("max-w-xs",h[p]),children:[e.jsx(s.TooltipArrow,{className:S[p]}),e.jsx("p",{children:g[p]})]})]})})}function Oe(r,a){return{...r,sql:"",python:"",config:void 0,customCfg:"",preferences:{},interactionConfig:void 0,linkedInteractionTargetOverrides:void 0,dynamicCardPreferences:void 0,customCardPreferences:a?r.customCardPreferences:void 0,visualizationMode:"builtin",type:a?r.type:"bar"}}function me(r){const a=s.getDynamicFrameSaveIssue(r);return a?(f.ue.error(a),!1):!0}function Ue({className:r,variant:a="outline"}){const o=s.useEditorStore(c=>c.onSave),{getUpdatedFrame:n}=ae();function i(){const c=n();me(c)&&(o==null||o(c))}return e.jsxs(s.Button,{onClick:i,className:r,size:"xs",variant:a,children:[e.jsx(s.Check,{className:"h-3.5 w-3.5"}),"Accept"]})}function ze({className:r,variant:a="default"}){const o=f.useQueryClient(),[n,i]=C.useState(!1),{setIsVisualEditing:c}=s.useDashboardActions(),{getUpdatedFrame:m}=ae(),x=f.useSelectedVisual(),p=s.useEditorStore(h=>h.frame),v=f.useUpdateVisualMutation(),g=()=>{const h=m();if(!me(h))return;const S=(p==null?void 0:p.visualId)||(x==null?void 0:x.id);if(!S){f.ue.error("No visual to save");return}i(!0),v.mutate({visualId:S,data:{frameObject:h}},{onSuccess:()=>{i(!1),f.ue.success("Visual updated successfully"),o.invalidateQueries({queryKey:["resource-by-id","visual",S],exact:!0})},onError:()=>{i(!1),f.ue.error("Failed to update visual")}})};return e.jsx(s.Button,{onClick:g,className:r,size:"xs",variant:a,children:n?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Saving"]}):e.jsxs(e.Fragment,{children:[e.jsx(ke.Save,{className:"h-3.5 w-3.5"}),"Save to Library"]})})}function Re({className:r}){const a=f.useQueryClient(),[o,n]=C.useState(!1),i=f.useSelectedVisual(),c=s.useEditorStore(k=>k.frame),m=s.useDashboardStore(k=>k.selectedSheetId),x=s.useDashboardStore(k=>k.dashboard),{updateFrame:p,setIsVisualEditing:v}=s.useDashboardActions(),{getUpdatedFrame:g}=ae(),h=f.useUpdateVisualMutation(),S=f.useResolveExistingFrameSemanticExecutionPayload(),D=async()=>{if(!m){f.ue.error("No sheet selected");return}const k=(c==null?void 0:c.visualId)||(i==null?void 0:i.id);if(!k){f.ue.error("No visual to update");return}n(!0);try{const E=g();if(!me(E)){n(!1);return}const I={...E,visualId:k},U=s.findDashboardFrameById(x,I.id),Y=await S(I,{previousFrame:U});await h.mutateAsync({visualId:k,data:{frameObject:E}}),p(m,I,{semanticExecutionPayload:Y}),a.invalidateQueries({queryKey:["visuals"]}),a.invalidateQueries({queryKey:["visual",k]}),f.ue.success("Saved to library and applied locally"),setTimeout(()=>{v(!1)},300)}catch(E){console.error("Failed to save and apply:",E),f.ue.error(E instanceof Error?E.message:"Failed to save and apply changes")}finally{n(!1)}};return e.jsx(s.Button,{onClick:D,className:r,size:"xs",variant:"default",disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(s.LoaderCircle,{className:"h-3.5 w-3.5 animate-spin"}),"Saving..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ke.Save,{className:"h-3.5 w-3.5"}),"Save & Apply"]})})}function Qe({className:r}){const{setTempQueryData:a,setSqlGen:o}=s.useEditorActions(),n=f.useQueryClient(),i=s.useEditorStore(h=>h.tempQueryData),c=s.useEditorStore(h=>h.onClose),m=s.useEditorStore(h=>h.card),x=pe(),p=C.useMemo(()=>x!==m.type?{...m,type:x}:m,[m,x]),{queryKey:v}=f.useEditorCardQuery(p);function g(){if(i){const{queryKey:h,queryData:S}=i;h&&S&&n.setQueryData(h,S)}o({}),c==null||c()}return e.jsxs(s.Button,{onClick:g,className:r,size:"xs",variant:"outline",children:[e.jsx(ee.X,{className:"h-3.5 w-3.5"}),"Close"]})}function Pe({label:r="Clear",variant:a="secondary",className:o}={}){const{setTempQueryData:n}=s.useEditorActions(),i=f.useQueryClient(),c=s.useEditorStore(q=>q.tempQueryData),m=s.useEditorStore(q=>q.card),x=pe(),p=C.useMemo(()=>x!==m.type?{...m,type:x}:m,[m,x]),{queryKey:v}=f.useEditorCardQuery(p),{setCardSql:g,setSqlGen:h,setCardPython:S,setCardCustomCfg:D,setCardPreferences:k,clearQueryConfig:E,setCardConfig:I,setCardType:U,setFrame:Y,setCard:H,setActiveTabCardId:K}=s.useEditorActions();function J(){var W,G,_,z;const q=i.getQueryData(v);c!=null&&c.queryData||n({queryKey:v,queryData:q}),i.setQueryData(v,null),i.removeQueries({queryKey:v,exact:!0}),g(""),h({}),E(),I(void 0),S(""),D(""),k({});const l=s.useEditorStore.getState().frame,w=s.useEditorStore.getState().card,T=f.findCustomVisualConfigCard(l,w),M=((W=T==null?void 0:T.customCardPreferences)==null?void 0:W.visualType)==="multiple"||!!((G=T==null?void 0:T.customCardPreferences)!=null&&G.dataInputCardIds)||(((_=T==null?void 0:T.customCardPreferences)==null?void 0:_.minInputs)||0)>1||(((z=T==null?void 0:T.customCardPreferences)==null?void 0:z.maxInputs)||0)>1,Q=Oe(w,M);Y({...l,cards:l.cards.map($=>$.id===Q.id?Q:$)}),K(Q.id),H(Q),M||U("bar")}return e.jsxs(s.Button,{onClick:J,className:o,size:"xs",variant:a,children:[e.jsx(ee.X,{className:"h-3.5 w-3.5"}),r]})}function Fe(r){const{control:a,onChange:o}=r;return e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),e.jsx(s.Input,{size:"xs",value:a.label,placeholder:"Control label",onChange:n=>o(n.target.value)})]})}function $e(r){const{currentStep:a,labels:o}=r;return e.jsx("div",{className:"sticky top-0 z-10 -mx-1 border-b border-border/60 bg-background/95 px-1 pb-2.5 pt-1 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:e.jsx("div",{className:"flex flex-wrap items-center gap-2 sm:gap-2.5",children:o.map((n,i)=>{const c=i+1,m=c===a,x=c<a;return e.jsxs(C.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:s.cn("flex h-5 w-5 items-center justify-center rounded-full border text-[10px] font-medium tabular-nums",m?"border-foreground bg-foreground text-background":x?"border-foreground/30 bg-foreground/10 text-foreground":"border-border/60 bg-background text-muted-foreground"),children:c}),e.jsx("span",{className:s.cn("text-[12px]",m?"font-medium text-foreground":"text-muted-foreground"),children:n})]}),i<o.length-1?e.jsx("span",{className:"h-px w-4 bg-border/60 sm:w-6","aria-hidden":"true"}):null]},n)})})})}function se(r){const{secondary:a,tertiary:o,primary:n}=r;return e.jsxs("div",{className:"sticky bottom-0 z-10 -mx-1 flex justify-end gap-2 border-t bg-background/95 px-1 pb-1 pt-3 backdrop-blur supports-[backdrop-filter]:bg-background/85",children:[a,o,n]})}function Ye(r){const{control:a,scope:o,detail:n}=r;return e.jsxs("div",{className:"flex items-start gap-2.5 rounded-control border border-border/60 bg-muted/30 px-3 py-2.5",children:[e.jsx(f.CircleCheck,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-foreground"}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:a.label}),e.jsxs("div",{className:"text-[12px] text-muted-foreground",children:[s.getFriendlyTypeOption(a.type).label," ·"," ",s.getControlOptionPreview(a)," ·"," ",s.getPlacementLabel(o,a.placement)]}),n?e.jsx("div",{className:"text-[12px] text-muted-foreground",children:n}):null]})]})}function Ce(r){const{control:a,defaultValue:o,availableFieldChoices:n,availableMetricChoices:i,previewControlDefinitions:c,previewControlValues:m,onControlChange:x,onLabelChange:p,onDefaultValueChange:v,onBack:g,onNext:h,nextDisabled:S}=r;return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fe,{control:a,onChange:p}),e.jsx(f.ControlDefinitionOptionsEditor,{control:a,availableFieldChoices:n,availableMetricChoices:i,previewControlDefinitions:c,previewControlValues:m,controlLifecycle:"create",onChange:x}),e.jsx(f.ControlDefaultValueEditor,{control:a,value:o,onChange:v,allowNoDefault:!0,allowCardDefault:!0,hint:"This is the value viewers will see first.",previewControlDefinitions:c,previewControlValues:m}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:g,children:"Back"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:h,disabled:S,children:"Next"})})]})}const Ke=new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]);function Se(r){const{text:a,ariaLabel:o}=r,[n,i]=C.useState(!1);return e.jsxs("button",{type:"button","aria-label":o,onClick:async()=>{try{await navigator.clipboard.writeText(a),i(!0),setTimeout(()=>i(!1),1200)}catch(c){console.error("Failed to copy",c)}},className:"group flex w-full items-center justify-between gap-2 rounded-control bg-muted/40 px-2 py-1 text-left transition-colors hover:bg-muted/60 focus-visible:bg-muted/60 focus-visible:outline-none",children:[e.jsx("code",{className:"min-w-0 truncate font-mono text-[12px] text-foreground",children:a}),e.jsx("span",{className:"shrink-0 text-[11px] text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100",children:n?"Copied":"Click to copy"})]})}function je(r){const{control:a,scope:o,createdReference:n,explorerContent:i,sqlDescription:c,summaryDetail:m,onBack:x,onCancel:p,onDone:v}=r,g=Ke.has(a.type),h=n.match(/\[\[param\.(.+?)\]\]/),S=h?`{{ param('${h[1]}') }}`:"";return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ye,{control:a,scope:o,detail:m}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-[13px] font-medium text-foreground",children:"How cards use this control"}),e.jsxs("div",{className:"divide-y divide-border/60 overflow-hidden rounded-control border border-border/60",children:[g?e.jsxs("div",{className:"space-y-1 px-3 py-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Explorer cards"}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:i})]}):null,e.jsxs("div",{className:"space-y-1.5 px-3 py-2.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"SQL cards"}),e.jsx(Se,{text:n,ariaLabel:"Copy SQL control reference"}),S?e.jsx(Se,{text:S,ariaLabel:"Copy Jinja control reference"}):null,e.jsxs("p",{className:"text-[12px] text-muted-foreground",children:[c," ",e.jsx("a",{href:"https://docs.semaphor.cloud/docs/concepts/template-expressions",target:"_blank",rel:"noreferrer",className:"underline underline-offset-2 hover:text-foreground",children:"Template expressions docs"}),"."]})]})]})]}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:x,children:"Back"}),tertiary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:p,children:"Cancel"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:v,children:"Done"})})]})}function We(r){const a=s.createBlankControl(r.scope,r.existingControls,r.reservedIds),o=r.type===a.type?{...a,label:s.DEFAULT_LABEL_BY_TYPE[r.type]}:{...s.applyControlTypeChange({controls:[{...a,label:s.DEFAULT_LABEL_BY_TYPE[r.type]}],controlId:a.id,nextType:r.type}).controls[0],label:s.DEFAULT_LABEL_BY_TYPE[r.type]};return{step:2,control:o,defaultValue:s.getDefaultValueForType(o,void 0)}}function He({scope:r,controls:a,reservedControlIds:o,defaultValues:n,onChange:i,emptyMessage:c,initialCreateFlow:m=!1,usageByControlId:x,availableFieldChoices:p,availableMetricChoices:v,structuralParticipants:g,structuralParticipantIdsByControlId:h,card:S,allowedControlTypes:D,onCreateFlowActiveChange:k,onCreateFlowComplete:E}){const I=C.useMemo(()=>new Set(o||[]),[o]),U=s.getPlacementOptionsForScope(r),Y=s.getDefaultPlacement(r),[H,K]=C.useState(null),[J,q]=C.useState(null),[l,w]=C.useState(()=>m?{step:1,control:s.createBlankControl(r,a,Array.from(I))}:null),T=C.useRef({}),M=C.useRef(void 0),Q=C.useRef(m),W=C.useMemo(()=>{const t=s.getFriendlyControlTypeOptions({scope:r,card:S});if(!D)return t;const u=new Set(D);return t.filter(d=>u.has(d.value))},[D,S,r]),G=C.useCallback(t=>{const u=s.getFriendlyControlTypeOptions({scope:r,card:S,includeType:D?void 0:t});if(!D)return u;const d=new Set(D);return u.filter(b=>d.has(b.value))},[D,S,r]),_=C.useCallback(t=>r==="dashboard"&&(t==="field_selector"||t==="metric_selector"),[r]),z=C.useMemo(()=>l?s.getEligibleParticipantsForStructuralControl(g||[],l.control.type):[],[l,g]),$=C.useMemo(()=>{if(!l)return{fields:p||[],metrics:v||[]};if(!_(l.control.type))return{fields:p||[],metrics:v||[]};const t=l.selectedCardIds||[],u=s.getCompatibleStructuralChoiceCatalog({controlType:l.control.type,participants:g||[],selectedCardIds:t});return{fields:l.control.type==="field_selector"?u.choices.map(d=>({option:d,target:u.fieldTargetMap[d.value]})):[],metrics:l.control.type==="metric_selector"?u.choices.map(d=>({option:d,target:u.metricTargetMap[d.value]})):[]}},[p,v,l,_,g]);C.useEffect(()=>{k==null||k(!!l)},[l,k]),C.useEffect(()=>{const t=m&&!Q.current;Q.current=m,t&&(w({step:1,control:s.createBlankControl(r,a,Array.from(I))}),q(null),K(null))},[a,m,I,r]);const ne=t=>{if(!_(t.type))return{fields:p||[],metrics:v||[]};const u=(h==null?void 0:h[t.id])||[];if(u.length===0)return{fields:p||[],metrics:v||[]};const d=s.getCompatibleStructuralChoiceCatalog({controlType:t.type,participants:g||[],selectedCardIds:u});return{fields:t.type==="field_selector"?d.choices.map(b=>({option:b,target:d.fieldTargetMap[b.value]})):[],metrics:t.type==="metric_selector"?d.choices.map(b=>({option:b,target:d.metricTargetMap[b.value]})):[]}},A=t=>{if(!_(t.control.type))return{nextControl:t.control,cardBindingsById:void 0};const u=(h==null?void 0:h[t.control.id])||[],d=s.getCompatibleStructuralChoiceCatalog({controlType:t.control.type,participants:g||[],selectedCardIds:t.nextSelectedCardIds}),b=s.reconcileStructuralControlChoices({control:t.control,choices:d.choices}),j=Object.fromEntries(u.filter(N=>!t.nextSelectedCardIds.includes(N)).map(N=>[N,void 0]));return t.nextSelectedCardIds.length>0&&b.source.kind==="manual"&&b.source.options.length>0&&Object.assign(j,s.buildStructuralControlBindingsForParticipants({control:b,participants:g||[],selectedCardIds:t.nextSelectedCardIds})),{nextControl:b,cardBindingsById:j}},F=C.useCallback((t,u=n,d={type:"update"})=>{const b=t.map(j=>(s.resolveAuthoringControlDefaultValue({control:j,defaultValues:u}),s.syncSqlQueryControlExecutionRequirement(j)));i(b,u,d)},[n,i]),P=(t,u)=>{const d=a.find(L=>L.id===t);let b=a.map(L=>L.id!==t?L:u(L));const j=b.find(L=>L.id===t);let N,y;if(j&&r==="dashboard"&&(j.type==="field_selector"||j.type==="metric_selector")){const L=(h==null?void 0:h[j.id])||[],Z=A({control:j,nextSelectedCardIds:L});b=b.map(X=>X.id===t?Z.nextControl:X),N=Z.cardBindingsById,y=[j.id]}else if(d&&r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")){const L=(h==null?void 0:h[d.id])||[];N=Object.fromEntries(L.map(Z=>[Z,void 0])),y=[d.id]}const V=b.find(L=>L.id===t);let O=n;if(d&&V){const L=s.resolveAuthoringControlDefaultValue({control:d,defaultValues:n});d.source.kind==="manual"&&V.source.kind==="sql_query"&&(T.current[t]=L);const Z=L===void 0&&d.source.kind==="sql_query"&&V.source.kind==="manual"?T.current[t]:L,X=s.getNextEditedControlDefaultValue({previousControl:d,nextControl:V,currentDefaultValue:Z});V.source.kind==="manual"&&(T.current[t]=X),n&&(O={...n},X===void 0?delete O[t]:O[t]=X),b=b.map(be=>be.id===t?{...V,defaultValue:X}:be)}F(b,O,{type:"update",cardBindingsById:N,affectedBindingControlIds:y})},B=(t,u)=>{if(!u.trim())return;const d=f.normalizeDashboardInputVariableName(u);if(d===t||I.has(d)||a.some(N=>N.id===d&&N.id!==t))return;const b=a.map(N=>N.id===t?{...N,id:d}:N);if(!n){F(b,void 0,{type:"rename",oldId:t,newId:d});return}const j={...n};Object.prototype.hasOwnProperty.call(j,t)&&(j[d]=j[t],delete j[t]),F(b,j,{type:"rename",oldId:t,newId:d})},oe=t=>{const u=a.filter(b=>b.id!==t);if(!n){F(u,void 0,{type:"remove",controlId:t});return}const d={...n};delete d[t],F(u,d,{type:"remove",controlId:t})},re=C.useCallback(()=>{M.current=void 0,w({step:1,control:s.createBlankControl(r,a,Array.from(I))}),q(null),K(null)},[a,I,r]),R=t=>{w(u=>u&&(()=>{const d=t(u.control);u.control.source.kind==="manual"&&d.source.kind==="sql_query"&&(M.current=u.defaultValue);const b=u.defaultValue===void 0&&u.control.source.kind==="sql_query"&&d.source.kind==="manual"?M.current:u.defaultValue,j=s.getNextEditedControlDefaultValue({previousControl:u.control,nextControl:d,currentDefaultValue:b});return d.source.kind==="manual"&&(M.current=j),{...u,control:d,defaultValue:j}})())},te=t=>{w(u=>u&&(u.control.source.kind==="manual"&&(M.current=t),{...u,defaultValue:t}))},le=(()=>{if(!l)return!1;if(l.step===2&&_(l.control.type))return(l.selectedCardIds||[]).length>0;if(l.step!==2&&l.step!==3||!l.control.label.trim())return!1;const u=l.control.source.kind==="sql_query"?l.control:s.ensureManualSource(l.control);if(u.source.kind==="manual"&&(s.needsManualOptions(u)&&u.source.options.length===0||u.source.options.some(b=>b.label.trim().length===0||b.value.trim().length===0)))return!1;if(u.source.kind==="sql_query"){const{connectionId:d,sql:b,valueColumn:j}=u.source;return d.trim().length>0&&b.trim().length>0&&j.trim().length>0}return s.hasConcreteDefaultValue(s.getDefaultValueForType(u,l.defaultValue))})(),fe=()=>{var N;if(!l)return;const t=s.ensureManualSource(l.control),u=s.deriveUniqueControlId({label:t.label,fallbackId:t.id,existingControls:a,reservedIds:Array.from(I)}),d={...t,id:u},b=r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")&&((N=l.selectedCardIds)!=null&&N.length)?s.buildStructuralControlBindingsForParticipants({control:d,participants:g||[],selectedCardIds:l.selectedCardIds}):void 0,j=s.getDefaultValueForType(d,l.defaultValue);w({step:r==="dashboard"&&(d.type==="field_selector"||d.type==="metric_selector")?4:3,control:d,defaultValue:j,createdControlId:u,selectedCardIds:l.selectedCardIds,cardBindingsById:b})},ie=C.useCallback(()=>{w(null)},[]),xe=C.useCallback(()=>{if(!(l!=null&&l.createdControlId)){w(null);return}const t=l.control,u=l.createdControlId,d=s.getDefaultValueForType(t,l.defaultValue);if(n){const b={...n};d===void 0?delete b[u]:b[u]=d,F([...a,{...t,defaultValue:d}],b,{type:"add",cardBindingsById:l.cardBindingsById})}else F([...a,{...t,defaultValue:d}],void 0,{type:"add",cardBindingsById:l.cardBindingsById});q(u),w(null),E==null||E()},[a,l,n,F,E]),Ve=l?_(l.control.type)?["Choose type","Select cards","Configure","Finish"]:["Choose type","Configure","Finish"]:[],he=l!=null&&l.createdControlId?`[[param.${l.createdControlId}]]`:l?`[[param.${s.slugifyControlValue(l.control.label)||l.control.id}]]`:"",de=s.buildAuthoringPreviewControlValues({controls:a,defaultValues:n}),ce=l?[...a,l.control]:a,ge=l?s.buildAuthoringPreviewControlValues({controls:ce,defaultValues:n,overrides:[{controlId:l.control.id,value:l.defaultValue}]}):de;return e.jsxs("div",{className:"space-y-4",children:[l?e.jsxs("div",{className:"space-y-4 pb-1",children:[e.jsx($e,{currentStep:l.step,labels:Ve}),l.step===1&&(()=>{const t=new Set(["grain_selector","aggregation_selector","field_selector","metric_selector"]),u=new Set(["date","text"]),d=W.filter(N=>!t.has(N.value)&&!u.has(N.value)),b=W.filter(N=>t.has(N.value)),j=N=>e.jsxs("button",{type:"button",className:"rounded-control border border-border/60 bg-background px-3 py-2.5 text-left transition-colors hover:bg-muted/40 focus-visible:bg-muted/40 focus-visible:outline-none",onClick:()=>w(We({scope:r,existingControls:a,reservedIds:Array.from(I),type:N.value})),children:[e.jsx("div",{className:"text-[13px] font-medium text-foreground",children:N.label}),e.jsx("p",{className:"mt-0.5 text-[12px] text-muted-foreground",children:N.description})]},N.value);return e.jsxs("div",{className:"space-y-4",children:[r==="card"&&(S==null?void 0:S.sql)==null?e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Explorer cards support displayed metric, group by field, aggregation, and time grain controls here."}):null,d.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Input controls"}),e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:d.map(j)})]}),b.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Data-driven controls"}),e.jsx("div",{className:"grid gap-1.5 sm:grid-cols-2",children:b.map(j)})]}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:ie,children:"Back to controls"})})]})})(),l.step===2&&_(l.control.type)&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx(Fe,{control:l.control,onChange:t=>R(u=>({...u,label:t}))}),e.jsx("p",{className:"text-[12px] text-muted-foreground",children:"Choose which cards should respond to this shared control."})]}),z.length===0?e.jsx("div",{className:"rounded-control border border-border/60 bg-muted/30 px-3 py-2.5 text-[12px] text-muted-foreground",children:"No eligible cards are available yet. Add compatible metrics or group-by fields to cards first."}):e.jsx("div",{className:"space-y-1 rounded-control border border-border/60 bg-background p-2",children:z.map(t=>{const u=(l.selectedCardIds||[]).includes(t.cardId);return e.jsxs("label",{className:"flex items-start gap-2 rounded-control px-1.5 py-1 text-[13px] hover:bg-muted/40",children:[e.jsx(f.Checkbox,{checked:u,onCheckedChange:d=>w(b=>b&&{...b,selectedCardIds:d===!0?[...b.selectedCardIds||[],t.cardId]:(b.selectedCardIds||[]).filter(j=>j!==t.cardId)})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium text-foreground",children:t.title}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:l.control.type==="field_selector"?`${t.fieldChoices.length} compatible group-by fields`:`${t.metricChoices.length} compatible metrics`})]})]},t.cardId)})}),e.jsx(se,{secondary:e.jsx(s.Button,{type:"button",variant:"outline",size:"xs",onClick:()=>w(t=>t&&{...t,step:1,selectedCardIds:[]}),children:"Back"}),primary:e.jsx(s.Button,{type:"button",size:"xs",onClick:()=>w(t=>t&&{...t,step:3}),disabled:!le,children:"Next"})})]}),l.step===2&&!_(l.control.type)&&e.jsx(Ce,{control:l.control,defaultValue:l.defaultValue,availableFieldChoices:$.fields,availableMetricChoices:$.metrics,previewControlDefinitions:ce,previewControlValues:ge,onControlChange:t=>R(()=>t),onLabelChange:t=>R(u=>({...u,label:t})),onDefaultValueChange:te,onBack:()=>w(t=>t&&{...t,step:1}),onNext:fe,nextDisabled:!le}),l.step===3&&_(l.control.type)&&e.jsx(Ce,{control:l.control,defaultValue:l.defaultValue,availableFieldChoices:$.fields,availableMetricChoices:$.metrics,previewControlDefinitions:ce,previewControlValues:ge,onControlChange:t=>R(()=>t),onLabelChange:t=>R(u=>({...u,label:t})),onDefaultValueChange:te,onBack:()=>w(t=>t&&{...t,step:2}),onNext:fe,nextDisabled:!le}),l.step===3&&!_(l.control.type)&&e.jsx(je,{control:l.control,scope:r,createdReference:he,explorerContent:e.jsxs(e.Fragment,{children:["Open the card and use"," ",e.jsx("span",{className:"font-medium text-foreground",children:"Settings → Controls"})," ","to choose what this control changes."]}),sqlDescription:"Reference this control directly in the SQL editor.",onBack:()=>w(t=>t&&{...t,step:2}),onCancel:ie,onDone:xe}),l.step===4&&_(l.control.type)&&e.jsx(je,{control:l.control,scope:r,createdReference:he,summaryDetail:e.jsxs(e.Fragment,{children:["Used by ",(l.selectedCardIds||[]).length," selected card",(l.selectedCardIds||[]).length===1?"":"s"]}),explorerContent:e.jsx(e.Fragment,{children:"Selected cards have been set up to respond to this control automatically."}),sqlDescription:"SQL cards can still reference this control directly in the SQL editor.",onBack:()=>w(t=>t&&{...t,step:3}),onCancel:ie,onDone:xe})]}):null,!l&&a.length===0?e.jsx("div",{className:"rounded-md border border-dashed p-3 text-sm text-muted-foreground",children:c}):null,!l&&a.map(t=>{const u=ne(t),d=x==null?void 0:x[t.id],b=s.resolveAuthoringControlDefaultValue({control:t,defaultValues:n}),j=J===t.id,N="inline-flex shrink-0 items-center rounded-[4px] border border-border/60 bg-muted/40 px-1.5 py-0.5 text-[11px] font-medium text-muted-foreground";return e.jsxs("div",{className:"rounded-control border border-border/60",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2.5",children:[e.jsxs("button",{type:"button",className:"flex min-w-0 flex-1 items-start gap-2 rounded-control text-left focus:outline-none focus-visible:bg-muted/40",onClick:()=>q(y=>y===t.id?null:t.id),children:[j?e.jsx(ee.ChevronDown,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}):e.jsx(ye.ChevronRight,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[e.jsx("span",{className:"truncate text-[13px] font-medium text-foreground",children:t.label||"Untitled control"}),e.jsx("span",{className:N,children:s.getFriendlyTypeOption(t.type).label}),e.jsx("span",{className:N,children:s.getPlacementLabel(r,t.placement)})]}),e.jsxs("div",{className:"mt-0.5 text-[12px] text-muted-foreground",children:[s.getControlOptionPreview(t),d!=null&&d.status?` · ${d.status}`:""]})]})]}),e.jsx(s.Button,{type:"button",size:"xs",variant:"ghost",className:"h-7 w-7 shrink-0 p-0 text-muted-foreground",onClick:()=>oe(t.id),"aria-label":`Remove ${t.label}`,children:e.jsx(f.Trash2,{className:"h-3.5 w-3.5"})})]}),j&&e.jsxs("div",{className:"space-y-4 border-t border-border/60 px-3 py-3",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Label"}),e.jsx(s.Input,{size:"xs",value:t.label,placeholder:"Control label",onChange:y=>P(t.id,V=>({...V,label:y.target.value}))})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Type"}),e.jsxs(s.Select,{value:t.type,onValueChange:y=>{const V=s.applyControlTypeChange({controls:a,controlId:t.id,nextType:y,defaultValues:n});F(V.controls,V.defaultValues)},children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:G(t.type).map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Show in"}),e.jsxs(s.Select,{value:t.placement||Y,onValueChange:y=>P(t.id,V=>({...V,placement:y})),children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:U.map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]})]}),_(t.type)?e.jsx(f.StructuralParticipantSelector,{type:t.type,participants:s.getEligibleParticipantsForStructuralControl(g||[],t.type).map(y=>({cardId:y.cardId,title:y.title,choiceCount:t.type==="field_selector"?y.fieldChoices.length:y.metricChoices.length})),selectedCardIds:(h==null?void 0:h[t.id])||[],onChange:y=>{const V=A({control:t,nextSelectedCardIds:y}),O=a.map(L=>L.id===t.id?V.nextControl:L);F(O,n,{type:"update",cardBindingsById:V.cardBindingsById})}}):null,e.jsx(f.ControlDefinitionOptionsEditor,{control:t,availableFieldChoices:u.fields,availableMetricChoices:u.metrics,previewControlDefinitions:a,previewControlValues:de,controlLifecycle:"edit",onChange:y=>P(t.id,()=>y)}),t.initialValueStrategy==="saved_default"&&e.jsx(f.ControlDefaultValueEditor,{control:t,value:b,allowNoDefault:!0,allowCardDefault:!0,previewControlDefinitions:a,previewControlValues:de,onChange:y=>{const V=a.map(O=>O.id===t.id?{...O,defaultValue:y}:O);if(t.source.kind==="manual"&&(T.current[t.id]=y),n){const O={...n};y===void 0?delete O[t.id]:O[t.id]=y,F(V,O);return}F(V,void 0)}}),e.jsxs(f.Collapsible,{open:H===t.id,onOpenChange:y=>K(y?t.id:null),children:[e.jsx(f.CollapsibleTrigger,{asChild:!0,children:e.jsxs(s.Button,{type:"button",variant:"ghost",size:"xs",className:"-ml-2 gap-1 text-muted-foreground hover:text-foreground",children:[H===t.id?e.jsx(ee.ChevronDown,{className:"h-3.5 w-3.5"}):e.jsx(ye.ChevronRight,{className:"h-3.5 w-3.5"}),"Advanced"]})}),e.jsxs(f.CollapsibleContent,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Variable name"}),e.jsx(f.ControlIdInput,{controlId:t.id,onCommit:y=>B(t.id,y)},t.id)]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(s.Label,{className:"text-[10px] font-medium uppercase tracking-[0.08em] text-muted-foreground",children:"Initial value"}),e.jsxs(s.Select,{value:t.initialValueStrategy,onValueChange:y=>P(t.id,V=>({...V,initialValueStrategy:y})),children:[e.jsx(s.SelectTrigger,{size:"xs",children:e.jsx(s.SelectValue,{})}),e.jsx(s.SelectContent,{children:s.INITIAL_VALUE_STRATEGY_OPTIONS.map(y=>e.jsx(s.SelectItem,{value:y.value,children:y.label},y.value))})]})]})]}),e.jsx(f.ControlVisibilitySettings,{control:t,onChange:y=>P(t.id,()=>y)})]})]})]})]},t.id)}),!l&&e.jsxs(s.Button,{type:"button",variant:"outline",size:"xs",onClick:re,children:[e.jsx(f.Plus,{className:"h-3.5 w-3.5"}),"Add control"]})]})}function Ge(r){const{open:a,onOpenChange:o,initialCreateFlowActive:n=!1,dismissMode:i="passive"}=r,c=a!==void 0,[m,x]=C.useState(!1),[p,v]=C.useState(n),g=c?a:m,h=C.useCallback(k=>{!k&&p&&i==="passive"||(c||x(k),k||v(!1),o==null||o(k))},[c,p,i,o]),S=C.useCallback(()=>{c||x(!1),v(!1),o==null||o(!1)},[c,o]);C.useEffect(()=>{g||v(!1)},[g]);const D=C.useCallback(k=>{p&&k.preventDefault()},[p]);return{forceClose:S,handleOpenChange:h,isCreateFlowActive:p,preventPassiveDismissDuringCreate:D,resolvedOpen:g,setIsCreateFlowActive:v}}exports.ControlDefinitionListEditor=He;exports.EditorAcceptButton=Ue;exports.EditorCancelButton=Qe;exports.EditorClearButton=Pe;exports.Library=Ne;exports.Link2=Ee;exports.VisualBadge=Me;exports.VisualSaveAndApplyButton=Re;exports.VisualSaveButton=ze;exports.flushPendingEditorDrafts=De;exports.registerPendingEditorDraftFlusher=Le;exports.useCreateFlowOverlayState=Ge;exports.useEffectiveEditorCardType=pe;exports.useSyncLegacyEditorState=qe;exports.useVisualUtils=ae;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";const L=require("./analyze-result-contract-ege_u6Nl.js");function a(e,i,t){return t?{code:e,message:i,path:t}:{code:e,message:i}}function W(e){for(let i=0;i<e.length;i+=1){const t=e[i];if(e.some((n,o)=>o!==i&&V(n,t)))return!1}return!0}function U(e,i){return L.semaphorFieldRefsMatch(e,i)}function V(e,i){return U(e,i)&&g(e)===g(i)}function ee(e){return`Metric intent has duplicate measure "${e.name}" with the same aggregate (${g(e)}). Use different aggregates to request both, or remove one entry.`}function E(e){return typeof e=="string"||typeof e=="number"||typeof e=="boolean"||e===null}function ie(e,i,t){if(e!==void 0){if(!e||typeof e!="object"||Array.isArray(e)){t.push(a("invalid_sql_default_parameters","SQL defaultParameters must be an object keyed by parameter name.",i));return}Object.entries(e).forEach(([n,o])=>{if(!n.trim()){t.push(a("invalid_sql_default_parameter_name","SQL defaultParameters names must be non-empty strings.",`${i}.${n}`));return}(Array.isArray(o)?o.every(E):E(o))||t.push(a("invalid_sql_default_parameter_value","SQL defaultParameters values must be strings, numbers, booleans, nulls, or arrays of those scalar values.",`${i}.${n}`))})}}function te(e,i){return M(e,i).length===1}function ae(e,i){return M(e,i).length===1}function M(e,i){return i.filter(n=>ne(e,n))}function ne(e,i){return se(e,i)?e.source?U(i,e):!0:!1}function se(e,i){return!(i.name!==e.name||e.role!==void 0&&i.role!==void 0&&i.role!==e.role||oe(e,i)&&g(i)!==g(e))}function oe(e,i){return e.role==="measure"||i.role==="measure"||e.aggregate!==void 0||i.aggregate!==void 0}function g(e){return L.semaphorMetricAggregate(e)}const re=/^(\d{4})-(\d{2})-(\d{2})$/,G=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d+))?)?(Z|[+-]\d{2}:\d{2})$/;function x(e){if(typeof e!="string")return null;const i=e.trim(),t=re.exec(i);if(t){const[,y,P,T]=t;return N(y,P,T)?new Date(Date.UTC(Number(y),Number(P)-1,Number(T))):null}const n=G.exec(i);if(!n)return null;const[,o,s,r,c,d,p="00",,f]=n;if(!N(o,s,r)||!v(c,0,23)||!v(d,0,59)||!v(p,0,59)||!le(f))return null;const b=new Date(i);return Number.isFinite(b.getTime())?b:null}function de(e){return typeof e!="string"||!G.test(e.trim())?null:x(e)}function N(e,i,t){const n=Number(e),o=Number(i),s=Number(t);if(!Number.isInteger(n)||!Number.isInteger(o)||!Number.isInteger(s)||o<1||o>12)return!1;const r=new Date(Date.UTC(n,o-1,s));return r.getUTCFullYear()===n&&r.getUTCMonth()===o-1&&r.getUTCDate()===s}function v(e,i,t){const n=Number(e);return Number.isInteger(n)&&n>=i&&n<=t}function le(e){if(e==="Z")return!0;const i=/^([+-])(\d{2}):(\d{2})$/.exec(e);return!!(i&&v(i[2],0,23)&&v(i[3],0,59))}function l(e){return typeof e=="string"&&e.trim().length>0}function ue(e){const i=new Set;let t=0;for(;t<e.length;){const n=e[t];if(n==="'"||n==='"'){t=ce(e,t);continue}if(n==="{"){const o=e.indexOf("}",t+1);if(o===-1){t+=1;continue}const s=e.slice(t+1,o);/^[A-Za-z_][A-Za-z0-9_]*$/.test(s)&&i.add(s),t=o+1;continue}t+=1}return Array.from(i)}function ce(e,i){const t=e[i];let n=i+1;for(;n<e.length;){if(e[n]===t){if(e[n+1]===t){n+=2;continue}return n+1}n+=1}return e.length}function u(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function O(e,i,t){if(e!==void 0){if(!u(e)){t.push(a("invalid_pagination","Pagination must be an object with positive integer page and pageSize.",i));return}(!Number.isInteger(e.page)||typeof e.page!="number"||e.page<1)&&t.push(a("invalid_pagination_page","Pagination page must be a positive integer.",`${i}.page`)),(!Number.isInteger(e.pageSize)||typeof e.pageSize!="number"||e.pageSize<1)&&t.push(a("invalid_pagination_page_size","Pagination pageSize must be a positive integer.",`${i}.pageSize`))}}function I(e){const i=new Set;for(const t of e){if(i.has(t))return t;i.add(t)}return null}function $(e,i,t,n){I(e.filter(s=>l(s)))&&n.push(a("duplicate_matrix_public_id",`Matrix ${t} ids must be unique so sort and expansion references are unambiguous.`,i))}const pe=new Set(["SUM","COUNT","AVG","MIN","MAX","MEDIAN","DISTINCT"]);function k(e,i,t){if(!e||typeof e!="object"){t.push(a("missing_source","Analytics intent needs a source.",i));return}if(e.kind==="semantic"){l(e.domainId)||t.push(a("missing_semantic_domain","Semantic source needs a domainId.",`${i}.domainId`)),l(e.datasetName)||t.push(a("missing_dataset_name","Semantic source needs a datasetName.",`${i}.datasetName`));return}if(e.kind==="physical"){l(e.connectionId)||t.push(a("missing_connection_id","Physical source needs a connectionId.",`${i}.connectionId`)),l(e.tableName)||t.push(a("missing_table_name","Physical source needs a tableName.",`${i}.tableName`));return}if(e.kind==="sql"){l(e.connectionId)||t.push(a("missing_connection_id","SQL source needs a connectionId.",`${i}.connectionId`));return}t.push(a("invalid_source_kind","Source kind is not supported.",i))}function m(e,i,t,n={}){if(!e||!u(e)){n.required&&t.push(a("missing_field_ref","Field reference needs a name.",i));return}l(e.name)||t.push(a("missing_field_ref","Field reference needs a name.",`${i}.name`)),e.source!==void 0&&k(e.source,`${i}.source`,t),_(e.aggregate,`${i}.aggregate`,t)}function me(e,i,t){if(!u(e)){t.push(a("invalid_input_binding","Input bindings must be structured objects.",i));return}l(e.inputId)||t.push(a("invalid_input_binding","Input bindings need a non-empty inputId.",`${i}.inputId`)),e.kind!==void 0&&e.kind!=="filter"&&e.kind!=="control"&&t.push(a("invalid_input_binding","Input binding kind must be filter or control.",`${i}.kind`)),e.field!==void 0&&m(e.field,`${i}.field`,t),e.relationshipHint!==void 0&&R(e.relationshipHint,`${i}.relationshipHint`,t)}function R(e,i,t){if(!u(e)){t.push(a("invalid_relationship_hint","Relationship hints must be structured objects.",i));return}e.relationshipIds!==void 0&&(!Array.isArray(e.relationshipIds)||e.relationshipIds.some(n=>!l(n)))&&t.push(a("invalid_relationship_hint","Relationship hint relationshipIds must be non-empty strings.",`${i}.relationshipIds`))}function fe(e,i){if(l(e.inputId)||i.push(a("missing_input_options_input_id","Input options intent needs the inputId it populates.","inputId")),(!e.labelField||!l(e.labelField.name))&&i.push(a("missing_input_options_label_field","Input options intent needs a labelField.","labelField")),m(e.labelField,"labelField",i,{required:!0}),(!e.valueField||!l(e.valueField.name))&&i.push(a("missing_input_options_value_field","Input options intent needs a valueField.","valueField")),m(e.valueField,"valueField",i,{required:!0}),e.searchField!==void 0&&m(e.searchField,"searchField",i,{required:!0}),e.disambiguationFields!==void 0&&(Array.isArray(e.disambiguationFields)?e.disambiguationFields.forEach((t,n)=>{m(t,`disambiguationFields.${n}`,i,{required:!0})}):i.push(a("invalid_input_options_disambiguation_fields","Input options disambiguationFields must be an array of field refs.","disambiguationFields"))),e.dependencies!==void 0){const t=e.dependencies;if(!u(t))i.push(a("invalid_input_options_dependencies","Input options dependencies must be a structured object.","dependencies"));else{const n=t.mode;n!==void 0&&n!=="independent"&&n!=="explicit"&&i.push(a("invalid_input_options_dependencies","Input options dependencies mode must be independent or explicit.","dependencies.mode")),j(t.includeInputIds,"dependencies.includeInputIds",i,"Input options includeInputIds must be non-empty strings."),j(t.excludeInputIds,"dependencies.excludeInputIds",i,"Input options excludeInputIds must be non-empty strings."),ve(e,i)}}if(e.population!==void 0){const t=e.population;if(!u(t))i.push(a("invalid_input_options_population","Input options population must be a structured object.","population"));else{const n=t.kind;n!=="option_source"&&n!=="related_population"&&i.push(a("invalid_input_options_population","Input options population kind must be option_source or related_population.","population.kind")),n==="option_source"&&t.baseSource!==void 0&&i.push(a("invalid_input_options_population","Input options population baseSource is only valid for related_population.","population.baseSource")),n==="option_source"&&t.relationshipHint!==void 0&&i.push(a("invalid_input_options_population","Input options population relationshipHint is only valid for related_population.","population.relationshipHint")),n==="related_population"&&(k(t.baseSource,"population.baseSource",i),t.relationshipHint!==void 0&&R(t.relationshipHint,"population.relationshipHint",i))}}}function _e(e,i){if(!(!("inputs"in e)||e.inputs===void 0)){if(!Array.isArray(e.inputs)){i.push(a("invalid_input_binding","Analytics intent inputs must be an array of input bindings.","inputs"));return}e.inputs.forEach((t,n)=>me(t,`inputs.${n}`,i))}}function ve(e,i){var n,o;const t=new Set(Array.isArray(e.inputs)?e.inputs.map(s=>u(s)?s.inputId:void 0).filter(s=>typeof s=="string"):[]);for(const s of((n=e.dependencies)==null?void 0:n.includeInputIds)||[])t.has(s)||i.push(a("invalid_input_options_dependencies",`Input options dependency "${s}" is not declared in inputs.`,"dependencies.includeInputIds"));for(const s of((o=e.dependencies)==null?void 0:o.excludeInputIds)||[])s!==e.inputId&&!t.has(s)&&i.push(a("invalid_input_options_dependencies",`Input options dependency exclusion "${s}" is not the populated inputId and is not declared in inputs.`,"dependencies.excludeInputIds"))}function j(e,i,t,n){e!==void 0&&(!Array.isArray(e)||e.some(o=>!l(o)))&&t.push(a("invalid_input_options_dependencies",n,i))}function _(e,i,t){e!==void 0&&(typeof e!="string"||!pe.has(e))&&t.push(a("invalid_aggregate","Field aggregate must be SUM, COUNT, AVG, MIN, MAX, MEDIAN, or DISTINCT.",i))}const ge=new Set(["measure","dimension","date","id","unknown"]),be=new Set(["row","aggregate"]),z=new Set(["string","number","boolean","date","datetime","unknown"]),ye=new Set(["number","currency","percent","percentage","scientific","date","datetime","duration","string"]),he=new Set(["millisecond","second","minute","hour","day"]),xe=new Set(["compact","digital","long"]);function D(e,i,t){if(e===void 0)return;if(!u(e)){t.push(a("invalid_value_format","Value format must be a structured object.",i));return}const n=e;(typeof n.type!="string"||!ye.has(n.type))&&t.push(a("invalid_value_format_type","Value format type must be number, currency, percent, scientific, date, datetime, duration, or string.",`${i}.type`)),h(e.minimumFractionDigits,`${i}.minimumFractionDigits`,t),h(e.maximumFractionDigits,`${i}.maximumFractionDigits`,t),h(e.scale,`${i}.scale`,t),h(e.maxUnits,`${i}.maxUnits`,t),e.useGrouping!==void 0&&typeof e.useGrouping!="boolean"&&t.push(a("invalid_value_format_use_grouping","Value format useGrouping must be boolean.",`${i}.useGrouping`)),e.negativeStyle!==void 0&&e.negativeStyle!=="minus"&&e.negativeStyle!=="parentheses"&&t.push(a("invalid_value_format_negative_style","Value format negativeStyle must be minus or parentheses.",`${i}.negativeStyle`)),e.percentValueMode!==void 0&&e.percentValueMode!=="fraction"&&e.percentValueMode!=="whole"&&t.push(a("invalid_value_format_percent_mode","Value format percentValueMode must be fraction or whole.",`${i}.percentValueMode`));for(const o of["inputUnit","largestUnit","smallestUnit"]){const s=e[o];s!==void 0&&(typeof s!="string"||!he.has(s))&&t.push(a("invalid_value_format_duration_unit","Duration format units must be millisecond, second, minute, hour, or day.",`${i}.${o}`))}e.outputStyle!==void 0&&(typeof e.outputStyle!="string"||!xe.has(e.outputStyle))&&t.push(a("invalid_value_format_duration_style","Duration format outputStyle must be compact, digital, or long.",`${i}.outputStyle`))}function h(e,i,t){e!==void 0&&(typeof e!="number"||!Number.isFinite(e))&&t.push(a("invalid_value_format_number","Value format numeric options must be finite numbers.",i))}const we=new Set(["additive","non_additive","ratio_of_sums","weighted","pre_aggregated","snapshot"]),$e=new Set(["default","symmetric_aggregate","aggregate_then_join","weighted"]);function Ie(e,i,t){if(!e||!u(e)){t.push(a("invalid_derived_field_input","Derived field inputs must be structured input references.",i));return}if(e.kind==="field"){m(e.field,`${i}.field`,t,{required:!0}),_(e.aggregate,`${i}.aggregate`,t);return}t.push(a("invalid_derived_field_input","Derived field input kind must be field.",`${i}.kind`))}function B(e,i,t){if(!u(e)){t.push(a("invalid_result_column_ref","Result calculation references must use columnKey or field.",i));return}const n=l(e.columnKey),o=u(e.field);if(n===o){t.push(a("invalid_result_column_ref","Result calculation references must identify exactly one of columnKey or field.",i));return}o&&m(e.field,`${i}.field`,t,{required:!0})}function Ae(e,i,t){if(!u(e)){t.push(a("invalid_result_calculation_output","Result calculation output must be a structured object.",i));return}l(e.key)||t.push(a("invalid_result_calculation_output","Result calculation output needs a stable key.",`${i}.key`)),e.dataType!==void 0&&(typeof e.dataType!="string"||!z.has(e.dataType))&&t.push(a("invalid_result_calculation_output","Result calculation output dataType must be string, number, boolean, date, datetime, or unknown.",`${i}.dataType`)),D(e.format,`${i}.format`,t)}function Se(e,i,t){e!==void 0&&e!=="hour"&&e!=="day"&&e!=="week"&&e!=="month"&&e!=="quarter"&&e!=="year"&&t.push(a("invalid_time_grain","Time grain must be hour, day, week, month, quarter, or year.",i))}function Q(e,i,t,n){e!=="asc"&&e!=="desc"&&t.push(a(n,"Sort direction must be asc or desc.",i))}function Y(e,i,t,n){e!==void 0&&e!=="warehouseDefault"&&e!=="first"&&e!=="last"&&t.push(a(n,"Null ordering must be warehouseDefault, first, or last.",i))}function K(e,i,t,n){e!==void 0&&e!=="global"&&e!=="withinParent"&&t.push(a(n,"Sort scope must be global or withinParent.",i))}function Me(e,i,t){e.enabled!==void 0&&typeof e.enabled!="boolean"&&t.push(a("invalid_matrix_subtotal","Matrix subtotal enabled must be a boolean.",`${i}.enabled`)),e.position!==void 0&&e.position!=="before"&&e.position!=="after"&&t.push(a("invalid_matrix_subtotal","Matrix subtotal position must be before or after.",`${i}.position`)),e.label!==void 0&&typeof e.label!="string"&&t.push(a("invalid_matrix_subtotal","Matrix subtotal label must be a string.",`${i}.label`))}function ke(e,i,t){if(Q(e.direction,`${i}.direction`,t,"invalid_matrix_sort_direction"),Y(e.nulls,`${i}.nulls`,t,"invalid_matrix_sort_nulls"),K(e.scope,`${i}.scope`,t,"invalid_matrix_sort_scope"),!u(e.by)){t.push(a("invalid_matrix_sort_by","Matrix sort by must be a structured object.",`${i}.by`));return}if(e.by.kind!=="label"){if(e.by.kind==="field"){m(e.by.field,`${i}.by.field`,t,{required:!0}),_(e.by.aggregate,`${i}.by.aggregate`,t);return}t.push(a("invalid_matrix_sort_by","Matrix axis sort by must be label or field.",`${i}.by.kind`))}}function q(e,i,t,n){if(!Array.isArray(e))return n.required?t.push(a("missing_matrix_rows","Matrix intent needs at least one row axis level.",i)):e!==void 0&&t.push(a("invalid_matrix_columns","Matrix columns must be an array of axis levels.",i)),[];n.required&&e.length===0&&t.push(a("missing_matrix_rows","Matrix intent needs at least one row axis level.",i));const o=[];return e.forEach((s,r)=>{const c=`${i}.${r}`;if(!u(s)){t.push(a("invalid_matrix_axis_level","Matrix axis levels must be structured objects.",c));return}const d=s;o.push(d),d.id!==void 0&&!l(d.id)&&t.push(a("invalid_matrix_axis_level_id","Matrix axis level id must be a non-empty string.",`${c}.id`)),m(d.field,`${c}.field`,t,{required:!0}),Se(d.grain,`${c}.grain`,t),d.label!==void 0&&typeof d.label!="string"&&t.push(a("invalid_matrix_axis_label","Matrix axis level label must be a string.",`${c}.label`)),d.subtotal!==void 0&&typeof d.subtotal!="boolean"&&(u(d.subtotal)?Me(d.subtotal,`${c}.subtotal`,t):t.push(a("invalid_matrix_subtotal","Matrix subtotal must be a boolean or structured options object.",`${c}.subtotal`))),d.sortBy!==void 0&&(u(d.sortBy)?ke(d.sortBy,`${c}.sortBy`,t):t.push(a("invalid_matrix_sort_by","Matrix axis sortBy must be a structured object.",`${c}.sortBy`)))}),o}function Re(e,i,t){if(!u(e)){t.push(a("invalid_matrix_total_behavior","Matrix total behavior must be a structured object.",i));return}if(e.kind!=="defaultAggregate"&&e.kind!=="blank"&&e.kind!=="labelOnly"&&e.kind!=="customAggregate"&&e.kind!=="percentOfParent"&&e.kind!=="percentOfGrandTotal"&&e.kind!=="customExpression"){t.push(a("invalid_matrix_total_behavior","Matrix total behavior kind is not supported.",`${i}.kind`));return}e.kind==="customAggregate"&&(Object.prototype.hasOwnProperty.call(e,"aggregate")?_(e.aggregate,`${i}.aggregate`,t):t.push(a("invalid_matrix_total_behavior","Custom matrix total behavior needs an aggregate.",`${i}.aggregate`))),e.kind==="customExpression"&&!l(e.expressionId)&&t.push(a("invalid_matrix_total_behavior","Custom matrix total behavior needs an expressionId.",`${i}.expressionId`)),e.kind==="labelOnly"&&e.label!==void 0&&typeof e.label!="string"&&t.push(a("invalid_matrix_total_behavior","Matrix label-only total behavior label must be a string.",`${i}.label`))}function De(e,i,t){if(!Array.isArray(e)||e.length===0)return t.push(a("missing_matrix_values","Matrix intent needs at least one value field.",i)),[];const n=[];return e.forEach((o,s)=>{const r=`${i}.${s}`;if(!u(o)){t.push(a("invalid_matrix_value","Matrix values must be structured objects.",r));return}const c=o;n.push(c),c.id!==void 0&&!l(c.id)&&t.push(a("invalid_matrix_value_id","Matrix value id must be a non-empty string.",`${r}.id`)),m(c.field,`${r}.field`,t,{required:!0}),_(c.aggregate,`${r}.aggregate`,t),D(c.format,`${r}.format`,t),c.label!==void 0&&typeof c.label!="string"&&t.push(a("invalid_matrix_value_label","Matrix value label must be a string.",`${r}.label`)),c.totalBehavior!==void 0&&Re(c.totalBehavior,`${r}.totalBehavior`,t)}),n}function Fe(e,i,t){if(!u(e)){t.push(a("invalid_matrix_totals","Matrix totals must be a structured object.",i));return}for(const n of["rows","columns"]){const o=e[n];o!==void 0&&o!==!0&&o!==!1&&o!=="perLevel"&&t.push(a("invalid_matrix_totals","Matrix total axis setting must be a boolean or perLevel.",`${i}.${n}`))}if(e.grandTotal!==void 0&&typeof e.grandTotal!="boolean")if(!u(e.grandTotal))t.push(a("invalid_matrix_totals","Matrix grandTotal must be a boolean or structured object.",`${i}.grandTotal`));else for(const n of["rows","columns"]){const o=e.grandTotal[n];o!==void 0&&typeof o!="boolean"&&t.push(a("invalid_matrix_totals","Matrix grandTotal rows/columns must be booleans.",`${i}.grandTotal.${n}`))}e.rowPosition!==void 0&&e.rowPosition!=="top"&&e.rowPosition!=="bottom"&&t.push(a("invalid_matrix_totals","Matrix row total position must be top or bottom.",`${i}.rowPosition`)),e.columnPosition!==void 0&&e.columnPosition!=="left"&&e.columnPosition!=="right"&&t.push(a("invalid_matrix_totals","Matrix column total position must be left or right.",`${i}.columnPosition`))}function A(e,i,t,n){if(!Array.isArray(e)){n.push(a("invalid_matrix_path","Matrix member path must be an array of path segments.",i));return}e.forEach((o,s)=>{const r=`${i}.${s}`;if(!u(o)){n.push(a("invalid_matrix_path","Matrix path segment must be a structured object.",r));return}const c=o;if(!l(c.levelId)){n.push(a("stable_id_required","Matrix path segments must reference an explicit public axis level id.",`${r}.levelId`));return}Object.prototype.hasOwnProperty.call(o,"value")||n.push(a("invalid_matrix_path","Matrix path segments must include a value property; use explicit null for null members.",`${r}.value`)),t.has(c.levelId)||n.push(a("stable_id_required","Matrix path segment levelId must match an explicit public axis level id.",`${r}.levelId`))})}function H(e,i,t,n){if(!u(e)){n.push(a("invalid_matrix_expansion","Matrix expansion axis options must be structured objects.",i));return}e.defaultDepth!==void 0&&(typeof e.defaultDepth!="number"||!Number.isInteger(e.defaultDepth)||e.defaultDepth<0)&&n.push(a("invalid_matrix_expansion","Matrix expansion defaultDepth must be a non-negative integer.",`${i}.defaultDepth`)),e.lazy!==void 0&&typeof e.lazy!="boolean"&&n.push(a("invalid_matrix_expansion","Matrix expansion lazy must be a boolean.",`${i}.lazy`)),e.expandedPaths!==void 0&&(Array.isArray(e.expandedPaths)?e.expandedPaths.forEach((o,s)=>{A(o,`${i}.expandedPaths.${s}`,t,n)}):n.push(a("invalid_matrix_expansion","Matrix expandedPaths must be an array of member paths.",`${i}.expandedPaths`)))}function Pe(e,i,t,n){if(e!==void 0){if(!u(e)){n.push(a("invalid_matrix_expansion","Matrix expansion must be a structured object.","expansion"));return}e.rows!==void 0&&H(e.rows,"expansion.rows",i,n),e.columns!==void 0&&H(e.columns,"expansion.columns",t,n)}}function Te(e,i,t,n,o){if(e!==void 0){if(!Array.isArray(e)){o.push(a("invalid_matrix_sort","Matrix sort must be an array of sort rules.","sort"));return}e.forEach((s,r)=>{const c=`sort.${r}`;if(!u(s)){o.push(a("invalid_matrix_sort","Matrix sort rule must be a structured object.",c));return}const d=s;d.axis!=="row"&&d.axis!=="column"&&o.push(a("invalid_matrix_sort","Matrix sort axis must be row or column.",`${c}.axis`));const p=d.axis==="column"?t:i;if(d.targetId!==void 0&&!p.has(d.targetId)&&o.push(a("stable_id_required","Matrix sort targetId must reference an explicit public axis level id.",`${c}.targetId`)),Q(d.direction,`${c}.direction`,o,"invalid_matrix_sort_direction"),Y(d.nulls,`${c}.nulls`,o,"invalid_matrix_sort_nulls"),K(d.scope,`${c}.scope`,o,"invalid_matrix_sort_scope"),!u(d.by)){o.push(a("invalid_matrix_sort_by","Matrix sort by must be a structured object.",`${c}.by`));return}if(d.by.kind!=="label"){if(d.by.kind==="field"){m(d.by.field,`${c}.by.field`,o,{required:!0}),_(d.by.aggregate,`${c}.by.aggregate`,o);return}if(d.by.kind==="value"){(!l(d.by.valueId)||!n.has(d.by.valueId))&&o.push(a("stable_id_required","Matrix value sort must reference an explicit public value id.",`${c}.by.valueId`)),d.by.rowPath!==void 0&&A(d.by.rowPath,`${c}.by.rowPath`,i,o),d.by.columnPath!==void 0&&A(d.by.columnPath,`${c}.by.columnPath`,t,o);return}o.push(a("invalid_matrix_sort_by","Matrix sort by must be label, field, or value.",`${c}.by.kind`))}})}}function Ee(e,i){if(e!==void 0){if(!u(e)){i.push(a("invalid_matrix_layout","Matrix layout must be a structured object.","layout"));return}e.hierarchy!==void 0&&e.hierarchy!=="compact"&&e.hierarchy!=="tabular"&&e.hierarchy!=="outline"&&i.push(a("invalid_matrix_layout","Matrix hierarchy layout must be compact, tabular, or outline.","layout.hierarchy")),e.valuesPlacement!==void 0&&e.valuesPlacement!=="columns"&&e.valuesPlacement!=="rows"&&i.push(a("invalid_matrix_layout","Matrix valuesPlacement must be columns or rows.","layout.valuesPlacement")),e.stickyRowHeaders!==void 0&&typeof e.stickyRowHeaders!="boolean"&&i.push(a("invalid_matrix_layout","Matrix stickyRowHeaders must be a boolean.","layout.stickyRowHeaders")),e.stickyColumnHeaders!==void 0&&typeof e.stickyColumnHeaders!="boolean"&&i.push(a("invalid_matrix_layout","Matrix stickyColumnHeaders must be a boolean.","layout.stickyColumnHeaders"))}}function C(e,i,t){if(!u(e)){t.push(a("invalid_matrix_display_limits","Matrix display limit must be a structured object.",i));return}(typeof e.limit!="number"||!Number.isInteger(e.limit)||e.limit<1)&&t.push(a("invalid_matrix_display_limits","Matrix display limit must be a positive integer.",`${i}.limit`));for(const n of Object.keys(e))n!=="limit"&&t.push(a("invalid_matrix_display_limits",`Matrix display limit ${n} is not supported in v1; use count-only { limit } display limits.`,`${i}.${n}`))}function Ne(e,i){if(e!==void 0){if(!u(e)){i.push(a("invalid_matrix_display_limits","Matrix displayLimits must be a structured object.","displayLimits"));return}e.rows!==void 0&&C(e.rows,"displayLimits.rows",i),e.columns!==void 0&&C(e.columns,"displayLimits.columns",i);for(const t of Object.keys(e))t==="rows"||t==="columns"||i.push(a("invalid_matrix_display_limits",`Matrix displayLimits ${t} is not supported in v1; use rows and columns count limits only.`,`displayLimits.${t}`))}}function Oe(e,i){var d;((d=e.source)==null?void 0:d.kind)==="sql"&&i.push(a("unsupported_matrix_sql_source","Matrix analytics intent does not support raw SQL sources.","source.kind"));const t=q(e.rows,"rows",i,{required:!0}),n=q(e.columns,"columns",i,{required:!1}),o=De(e.values,"values",i);w(e.filters,"filters",i),e.totals!==void 0&&Fe(e.totals,"totals",i),$(t.map(p=>p.id),"rows","row axis level",i),$(n.map(p=>p.id),"columns","column axis level",i),$(o.map(p=>p.id),"values","value",i);const s=new Set(t.map(p=>p.id).filter(p=>l(p))),r=new Set(n.map(p=>p.id).filter(p=>l(p))),c=new Set(o.map(p=>p.id).filter(p=>l(p)));Te(e.sort,s,r,c,i),Pe(e.expansion,s,r,i),Ee(e.layout,i),Ne(e.displayLimits,i)}function je(e,i){if(e.analysis===void 0)return;if(!u(e.analysis)){i.push(a("invalid_measure_analysis","Metric analysis must be a structured object.","analysis"));return}if(e.analysis.kind!=="period_change"){i.push(a("invalid_measure_analysis","Metric analysis kind is not supported.","analysis.kind"));return}e.dateField||i.push(a("missing_analysis_date_field","Period-change analysis needs a dateField.","dateField")),e.timeGrain||i.push(a("missing_analysis_time_grain","Period-change analysis needs a timeGrain.","timeGrain")),e.analysis.orderBy!==void 0&&e.analysis.orderBy!=="absolute_change"&&e.analysis.orderBy!=="positive_change"&&e.analysis.orderBy!=="negative_change"&&e.analysis.orderBy!=="period"&&i.push(a("invalid_measure_analysis","Period-change analysis orderBy must be absolute_change, positive_change, negative_change, or period.","analysis.orderBy"));const{timeWindow:t}=e.analysis;t!==void 0&&S(t,"analysis.timeWindow",i)}function S(e,i,t){if(!u(e)){t.push(a("invalid_time_window","Time window must be a structured object.",i));return}if(e.kind!==void 0&&e.kind!=="relative"&&e.kind!=="absolute"&&t.push(a("invalid_time_window","Time window kind must be relative or absolute.",`${i}.kind`)),e.kind==="absolute"){if(l(e.start)||t.push(a("invalid_time_window","Absolute time window start must be a non-empty ISO date or timestamp string.",`${i}.start`)),l(e.end)||t.push(a("invalid_time_window","Absolute time window end must be a non-empty ISO date or timestamp string.",`${i}.end`)),l(e.start)&&l(e.end)){const n=x(e.start),o=x(e.end);n||t.push(a("invalid_time_window","Absolute time window start must be a valid ISO date or timestamp.",`${i}.start`)),o||t.push(a("invalid_time_window","Absolute time window end must be a valid ISO date or timestamp.",`${i}.end`)),n&&o&&n.getTime()>o.getTime()&&t.push(a("invalid_time_window","Absolute time window start must be before or equal to end.",i))}return}e.unit!=="second"&&e.unit!=="minute"&&e.unit!=="hour"&&e.unit!=="day"&&e.unit!=="week"&&e.unit!=="month"&&e.unit!=="quarter"&&e.unit!=="year"&&t.push(a("invalid_time_window","Time window unit must be second, minute, hour, day, week, month, quarter, or year.",`${i}.unit`)),(typeof e.value!="number"||!Number.isFinite(e.value)||e.value<=0)&&t.push(a("invalid_time_window","Time window value must be a positive number.",`${i}.value`)),e.anchor!==void 0&&e.anchor!=="now"&&e.anchor!=="latest_available"&&t.push(a("invalid_time_window","Time window anchor must be now or latest_available.",`${i}.anchor`)),e.completeness!==void 0&&e.completeness!=="include_partial"&&e.completeness!=="complete_periods"&&t.push(a("invalid_time_window","Time window completeness must be include_partial or complete_periods.",`${i}.completeness`))}function w(e,i,t){if(e!==void 0){if(!Array.isArray(e)){t.push(a("invalid_analytics_filters","Analytics filters must be an array.",i));return}e.forEach((n,o)=>{var d;const s=`${i}.${o}`;if(!u(n)){t.push(a("invalid_analytics_filter","Analytics filter must be a structured object.",s));return}const r=n;m(r.field,`${s}.field`,t,{required:!0}),r.scope!==void 0&&r.scope!=="row"&&r.scope!=="aggregate"&&t.push(a("invalid_analytics_filter_scope","Analytics filter scope must be row or aggregate.",`${s}.scope`)),r.scope==="aggregate"&&((d=r.field)==null?void 0:d.role)!==void 0&&r.field.role!=="measure"&&t.push(a("invalid_analytics_filter_scope","Aggregate-scope analytics filters must target a measure field.",`${s}.scope`));const c=r.operator==="is_null"||r.operator==="is_not_null";if(r.operator!==void 0&&r.operator!=="="&&r.operator!=="!="&&r.operator!=="in"&&r.operator!=="not_in"&&r.operator!=="contains"&&r.operator!=="not_contains"&&r.operator!=="between"&&r.operator!=="not_between"&&r.operator!==">"&&r.operator!==">="&&r.operator!=="<"&&r.operator!=="<="&&r.operator!=="is_null"&&r.operator!=="is_not_null"&&t.push(a("invalid_analytics_filter_operator","Analytics filter operator is not supported.",`${s}.operator`)),r.values===void 0&&!c&&t.push(a("missing_analytics_filter_value","Analytics filter needs values unless it is a null check.",s)),c&&r.values!==void 0){t.push(a("invalid_analytics_filter_values","Null-check analytics filters must not include values.",`${s}.values`));return}if(r.values!==void 0&&!Array.isArray(r.values)){t.push(a("invalid_analytics_filter_values","Analytics filter values must be an array when provided.",`${s}.values`));return}if(r.values!==void 0){const p=r.values.length;if(r.operator==="between"||r.operator==="not_between"){p!==2&&t.push(a("invalid_analytics_filter_values","Between analytics filters must include exactly two values.",`${s}.values`));return}(r.operator==="contains"||r.operator==="not_contains"||r.operator==="="||r.operator==="!="||r.operator===">"||r.operator===">="||r.operator==="<"||r.operator==="<="||r.operator===void 0)&&p!==1&&t.push(a("invalid_analytics_filter_values","Scalar analytics filters must include exactly one value. Use in/not_in for multiple values.",`${s}.values`))}})}}function X(e){const i=[];if(!u(e))return i.push(a("invalid_derived_field","Derived field definition must be a structured object.")),{ok:!1,errors:i,warnings:[]};if(e.kind!=="derived_field"&&i.push(a("invalid_derived_field_kind","Derived field kind must be derived_field.","kind")),l(e.name)||i.push(a("invalid_derived_field_name","Derived field needs a name.","name")),l(e.label)||i.push(a("invalid_derived_field_label","Derived field needs a label.","label")),ge.has(e.resultRole)||i.push(a("invalid_derived_field_role","Derived field resultRole must be measure, dimension, date, id, or unknown.","resultRole")),z.has(e.dataType)||i.push(a("invalid_derived_field_data_type","Derived field dataType must be string, number, boolean, date, datetime, or unknown.","dataType")),be.has(e.computeStage)||i.push(a("invalid_derived_field_compute_stage","Derived field computeStage must be row or aggregate.","computeStage")),e.computeStage==="aggregate"&&e.resultRole!=="measure"&&i.push(a("invalid_derived_field_compute_stage","Aggregate-stage derived fields must have resultRole measure.","computeStage")),e.resultRole!=="measure"&&e.defaultAggregate!==void 0&&i.push(a("invalid_derived_field_aggregate","Only measure derived fields may declare defaultAggregate.","defaultAggregate")),e.computeStage==="row"&&e.resultRole==="measure"&&e.defaultAggregate===void 0&&i.push(a("missing_derived_field_default_aggregate","Row-stage measure derived fields must declare defaultAggregate so row results have explicit rollup semantics.","defaultAggregate")),_(e.defaultAggregate,"defaultAggregate",i),e.aggregationBehavior!==void 0&&!we.has(e.aggregationBehavior)&&i.push(a("invalid_derived_field_aggregation_behavior","Derived field aggregationBehavior is not supported.","aggregationBehavior")),e.aggregationStrategy!==void 0&&!$e.has(e.aggregationStrategy)&&i.push(a("invalid_derived_field_aggregation_strategy","Derived field aggregationStrategy is not supported.","aggregationStrategy")),l(e.expression)||i.push(a("invalid_derived_field_expression","Derived field needs a named-token expression.","expression")),e.expressionLanguage!==void 0&&e.expressionLanguage!=="semaphor_sql_template"&&i.push(a("invalid_derived_field_expression_language","Derived field expressionLanguage must be semaphor_sql_template.","expressionLanguage")),!u(e.inputs)||Object.keys(e.inputs).length===0?i.push(a("invalid_derived_field_inputs","Derived field needs at least one typed input.","inputs")):Object.entries(e.inputs).forEach(([t,n])=>{if(!l(t)){i.push(a("invalid_derived_field_input_name","Derived field input names must be non-empty strings.","inputs"));return}Ie(n,`inputs.${t}`,i)}),l(e.expression)&&u(e.inputs)){const t=ue(e.expression),n=new Set(t),o=Object.keys(e.inputs).filter(s=>l(s));t.forEach(s=>{Object.prototype.hasOwnProperty.call(e.inputs,s)||i.push(a("invalid_derived_field_expression_token",`Derived field expression token "{${s}}" needs a matching inputs.${s} entry.`,"expression"))}),o.forEach(s=>{n.has(s)||i.push(a("unused_derived_field_input",`Derived field input "${s}" is not referenced by expression.`,`inputs.${s}`))})}return D(e.format,"format",i),e.tags!==void 0&&(!Array.isArray(e.tags)||e.tags.some(t=>!l(t)))&&i.push(a("invalid_derived_field_tags","Derived field tags must be non-empty strings.","tags")),{ok:i.length===0,errors:i,warnings:[]}}function Be(e){const i=[];if(!u(e))return i.push(a("invalid_result_calculation","Result calculation must be a structured object.")),{ok:!1,errors:i,warnings:[]};if(l(e.id)||i.push(a("invalid_result_calculation_id","Result calculation needs an id.","id")),l(e.label)||i.push(a("invalid_result_calculation_label","Result calculation needs a label.","label")),e.kind!=="percent_of_total"&&e.kind!=="rank"&&e.kind!=="running_total"&&e.kind!=="previous_row_delta"&&i.push(a("invalid_result_calculation_kind","Result calculation kind must be percent_of_total, rank, running_total, or previous_row_delta.","kind")),B(e.input,"input",i),Ae(e.output,"output",i),e.kind==="percent_of_total"){const t=e.denominator;t!==void 0&&(u(t)?t.scope==="population"?(m(t.metric,"denominator.metric",i,{required:!0}),w(t.filters,"denominator.filters",i)):t.scope!=="returned_result"&&i.push(a("invalid_result_calculation_denominator","Percent-of-total denominator scope must be returned_result or population.","denominator.scope")):i.push(a("invalid_result_calculation_denominator","Percent-of-total denominator must be a structured object.","denominator")))}return e.kind==="rank"&&e.order!==void 0&&e.order!=="asc"&&e.order!=="desc"&&i.push(a("invalid_result_calculation_order","Rank result calculation order must be asc or desc.","order")),(e.kind==="running_total"||e.kind==="previous_row_delta")&&e.orderBy!==void 0&&B(e.orderBy,"orderBy",i),{ok:i.length===0,errors:i,warnings:[]}}function F(e){var n;const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_analytics_intent","Analytics intent must be a structured object.")],warnings:t,repairHints:[{code:"invalid_analytics_intent",recommendedNextStep:"Send one structured analytics intent object with kind, source, and required fields."}]};if(e.version!==void 0&&e.version!==1&&i.push(a("invalid_version","Analytics intent version must be 1.","version")),k(e.source,"source",i),qe(e,i),_e(e,i),"relationshipHint"in e&&e.relationshipHint!==void 0&&R(e.relationshipHint,"relationshipHint",i),e.kind==="metric"){const o=Array.isArray(e.measures)?e.measures.filter(s=>u(s)&&l(s.name)):[];if(!Array.isArray(e.measures)||e.measures.length===0?i.push(a("missing_measure","Metric intent needs at least one measure.","measures")):e.measures.some(s=>!u(s)||!l(s.name))&&i.push(a("invalid_measure_list","Metric intent measures must be an array of field references with names.","measures")),o.forEach((s,r)=>{m(s,`measures.${r}`,i,{required:!0})}),o.length>0&&!W(o)){const s=o.find((r,c)=>o.some((d,p)=>p!==c&&V(d,r)));s&&i.push(a("duplicate_measure",ee(s),"measures"))}if(u(e.primaryMeasure)&&l(e.primaryMeasure.name)&&M(e.primaryMeasure,o).length>1&&i.push(a("ambiguous_primary_measure","Metric intent primaryMeasure must identify exactly one selected measure.","primaryMeasure")),e.primaryMeasure!==void 0&&(m(e.primaryMeasure,"primaryMeasure",i,{required:!0}),u(e.primaryMeasure)&&l(e.primaryMeasure.name)&&o.length>0&&!te(e.primaryMeasure,o)&&i.push(a("invalid_primary_measure","Metric intent primaryMeasure must match one measure field reference.","primaryMeasure"))),e.dimensions!==void 0&&!Array.isArray(e.dimensions)?i.push(a("invalid_measure_dimensions","Metric intent dimensions must be an array of field references.","dimensions")):Array.isArray(e.dimensions)&&e.dimensions.some(s=>!u(s)||!l(s.name))&&i.push(a("invalid_measure_dimensions","Metric intent dimensions must be an array of field references with names.","dimensions")),e.dateField!==void 0&&m(e.dateField,"dateField",i),e.timeWindow!==void 0&&(S(e.timeWindow,"timeWindow",i),e.dateField||i.push(a("missing_time_window_date_field","Metric timeWindow needs a dateField.","dateField"))),w(e.filters,"filters",i),Array.isArray(e.dimensions)&&e.dimensions.forEach((s,r)=>{m(s,`dimensions.${r}`,i)}),e.orderBy!==void 0){if(!u(e.orderBy))i.push(a("invalid_measure_order_by","Metric intent orderBy must be a structured object.","orderBy"));else if(m(e.orderBy.field,"orderBy.field",i,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&i.push(a("invalid_measure_order_direction","Metric intent orderBy direction must be asc or desc.","orderBy.direction")),u(e.orderBy.field)&&l(e.orderBy.field.name)){const s=[...o,...e.timeGrain&&e.dateField&&u(e.dateField)?[e.dateField]:[],...Array.isArray(e.dimensions)?e.dimensions.filter(r=>u(r)&&l(r.name)):[]];s.length>0&&!ae(e.orderBy.field,s)&&i.push(a("invalid_measure_order_by","Metric intent orderBy.field must match one selected measure, grouped dateField, or dimension.","orderBy.field"))}}je(e,i)}else if(e.kind==="records"){if(!Array.isArray(e.fields)||e.fields.length===0?i.push(a("missing_record_fields","Records intent needs at least one field.","fields")):e.fields.some(o=>!u(o)||!l(o.name))&&i.push(a("invalid_record_fields","Records intent fields must be field references with names.","fields")),Array.isArray(e.fields)&&e.fields.forEach((o,s)=>{m(o,`fields.${s}`,i)}),e.dateField!==void 0&&m(e.dateField,"dateField",i),O(e.pagination,"pagination",i),e.timeWindow!==void 0&&(S(e.timeWindow,"timeWindow",i),e.dateField||i.push(a("missing_time_window_date_field","Records timeWindow needs a dateField.","dateField"))),w(e.filters,"filters",i),Array.isArray(e.filters)&&e.filters.forEach((o,s)=>{u(o)&&o.scope==="aggregate"&&i.push(a("unsupported_record_filter_scope","Records intents support row-scope filters only. Use a metric intent for aggregate-scope filters.",`filters.${s}.scope`))}),e.orderBy!==void 0&&(u(e.orderBy)?(m(e.orderBy.field,"orderBy.field",i,{required:!0}),e.orderBy.direction!=="asc"&&e.orderBy.direction!=="desc"&&i.push(a("invalid_record_order_direction","Records intent orderBy direction must be asc or desc.","orderBy.direction"))):i.push(a("invalid_record_order_by","Records intent orderBy must be a structured object.","orderBy"))),e.totals!==void 0)if(!u(e.totals))i.push(a("invalid_records_totals","Records totals must be a structured server totals request.","totals"));else{e.totals.mode!=="server"&&i.push(a("invalid_records_totals","Records totals mode must be server.","totals.mode"));const o=e.totals.measures;!Array.isArray(o)||o.length===0?i.push(a("missing_records_totals_measures","Records server totals need at least one measure.","totals.measures")):o.forEach((s,r)=>{m(s,`totals.measures.${r}`,i,{required:!0}),(!u(s)||s.role!=="measure")&&i.push(a("invalid_records_totals_measure","Records server totals measures must be measure field references.",`totals.measures.${r}.role`))})}}else e.kind==="inputOptions"?fe(e,i):e.kind==="matrix"?Oe(e,i):e.kind==="sql"?(((n=e.source)==null?void 0:n.kind)!=="sql"&&i.push(a("invalid_sql_source","SQL analytics intent must use a SQL execution source.","source")),l(e.sql)||i.push(a("missing_sql","SQL analytics intent needs SQL text.","sql")),ie(e.defaultParameters,"defaultParameters",i),Array.isArray(e.fields)&&e.fields.forEach((o,s)=>{m(o,`fields.${s}`,i)}),O(e.pagination,"pagination",i)):i.push(a("invalid_analytics_kind","Analytics kind is not supported.","kind"));return{ok:i.length===0,errors:i,warnings:t,repairHints:Ce(i)}}function qe(e,i){if(!(!("derivedFields"in e)||e.derivedFields===void 0)){if(!Array.isArray(e.derivedFields)){i.push(a("invalid_derived_fields","Analytics intent derivedFields must be an array of derived field definitions.","derivedFields"));return}e.derivedFields.forEach((t,n)=>{X(t).errors.forEach(s=>{i.push({...s,path:s.path?`derivedFields.${n}.${s.path}`:`derivedFields.${n}`})})})}}function Z(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_operation_intent","Operation intent must be a structured object.")],warnings:t,repairHints:[{code:"invalid_operation_intent",recommendedNextStep:"Send one typed operation intent with version, kind, and required operation fields."}]};if(e.version!==1&&i.push(a("invalid_version","Operation intent version must be 1.","version")),e.kind==="answer_obligations")!Array.isArray(e.obligations)||e.obligations.length===0?i.push(a("missing_obligations","Answer-obligations operation intent needs at least one obligation.","obligations")):e.obligations.forEach((n,o)=>{l(n.id)||i.push(a("missing_obligation_id","Each analytics obligation needs an id.",`obligations.${o}.id`)),l(n.prompt)||i.push(a("missing_obligation_prompt","Each analytics obligation needs a prompt.",`obligations.${o}.prompt`))});else if(e.kind==="dashboard_change"||e.kind==="data_app_change"){if(l(e.instruction)||i.push(a("missing_instruction","Change operation intent needs an instruction.","instruction")),e.analyticsIntent){const n=F(e.analyticsIntent);i.push(...n.errors),t.push(...n.warnings)}}else i.push(a("invalid_operation_kind","Operation intent kind is not supported.","kind"));return{ok:i.length===0,errors:i,warnings:t,repairHints:J(i)}}function He(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_recovery_plan","Analytics recovery plan must be a structured object.")],warnings:t,repairHints:[{code:"invalid_recovery_plan",recommendedNextStep:"Return a typed recovery plan with operationIntent and plannedToolCalls."}]};e.version!==1&&i.push(a("invalid_version","Recovery plan version must be 1.","version")),e.kind!=="analytics_recovery_plan"&&i.push(a("invalid_recovery_plan_kind","Recovery plan kind must be analytics_recovery_plan.","kind"));const n=Z(e.operationIntent);return i.push(...n.errors),t.push(...n.warnings),Array.isArray(e.plannedToolCalls)||i.push(a("invalid_planned_tool_calls","Recovery plan plannedToolCalls must be an array.","plannedToolCalls")),{ok:i.length===0,errors:i,warnings:t,repairHints:J(i)}}function J(e){return e.map(i=>({code:i.code,recommendedNextStep:i.code==="missing_obligations"?"Normalize the user request into one or more typed analytics obligations before recovery planning.":"Correct the operation/recovery contract shape before planning execution."}))}function Ce(e){return e.map(i=>{switch(i.code){case"missing_source":return{code:i.code,fieldRole:"source",recommendedNextStep:"Provide a semantic, physical, or SQL source before executing analytics."};case"missing_measure":return{code:i.code,fieldRole:"measure",recommendedNextStep:"Choose one exact measure from the grounded schema candidates."};case"missing_record_fields":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Provide at least one field for the records intent."};case"missing_matrix_rows":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Choose at least one row axis level for the matrix table."};case"missing_matrix_values":return{code:i.code,fieldRole:"measure",recommendedNextStep:"Choose at least one value field for the matrix table."};case"unsupported_matrix_sql_source":return{code:i.code,fieldRole:"source",recommendedNextStep:"Use a semantic or explorer-backed source for matrix tables; raw SQL matrix tables are not supported."};case"missing_input_options_input_id":return{code:i.code,fieldRole:"input",recommendedNextStep:"Provide the inputId that these option values populate."};case"missing_input_options_label_field":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Provide the human-readable field used as option labels."};case"missing_input_options_value_field":return{code:i.code,fieldRole:"dimension",recommendedNextStep:"Provide the stable field used as option values."};case"missing_sql":return{code:i.code,fieldRole:"sql",recommendedNextStep:"Provide bounded read-only SQL with an explicit outer LIMIT."};case"conflicting_sql":return{code:i.code,fieldRole:"sql",recommendedNextStep:"Use one canonical SQL text location for the intent; prefer top-level sql."};case"missing_semantic_domain":case"missing_dataset_name":case"missing_connection_id":case"missing_table_name":return{code:i.code,fieldRole:"source",recommendedNextStep:"Use grounded catalog metadata to fill the missing source reference."};default:return}}).filter(i=>!!i)}function Le(e,i,t,n){if(!e||typeof e!="object"){t.push(a("invalid_view","Dashboard view must be an object.",i));return}if(l(e.title)||t.push(a("missing_view_title","Dashboard view needs a title.",i)),!e.presentation||typeof e.presentation!="object"){t.push(a("missing_presentation","Dashboard view needs a presentation.",`${i}.presentation`));return}if(e.presentation.kind==="text"){l(e.text)||n.push(a("missing_text_content","Text views should include text content.",`${i}.text`));return}if(!e.analytics){t.push(a("missing_view_analytics","Non-text dashboard views need analytics intent.",`${i}.analytics`));return}e.presentation.kind==="matrixTable"&&e.analytics.kind!=="matrix"&&t.push(a("invalid_matrix_view_analytics","Matrix table views need matrix analytics intent.",`${i}.analytics.kind`));const o=F(e.analytics);for(const s of o.errors)t.push(a(s.code,s.message,`${i}.analytics${s.path?`.${s.path}`:""}`));for(const s of o.warnings)n.push(a(s.code,s.message,`${i}.analytics${s.path?`.${s.path}`:""}`))}function Ue(e){const i=[],t=[];if(!e||typeof e!="object")return{ok:!1,errors:[a("invalid_dashboard_intent","Dashboard intent must be a structured object.")],warnings:t};e.version!==1&&i.push(a("invalid_version","Dashboard intent version must be 1.")),e.kind!=="dashboard"&&i.push(a("invalid_kind","Experience intent kind must be dashboard.")),l(e.title)||i.push(a("missing_title","Dashboard intent needs a title.","title"));const n=Array.isArray(e.inputs)?e.inputs:[],o=I(n.filter(u).map(d=>d.id).filter(d=>typeof d=="string"));o&&i.push(a("duplicate_input_id",`Duplicate input id: ${o}.`,"inputs"));for(const[d,p]of n.entries()){const f=`inputs.${d}`;if(!u(p)){i.push(a("invalid_input","Dashboard input must be an object.",f));continue}l(p.id)||i.push(a("missing_input_id","Input needs an id.",`${f}.id`)),l(p.label)||i.push(a("missing_input_label","Input needs a label.",`${f}.label`)),!p.field||!l(p.field.name)?i.push(a("missing_input_field","Input needs a field.",`${f}.field`)):m(p.field,`${f}.field`,i)}const s=Array.isArray(e.sections)?e.sections:[];s.length===0&&i.push(a("missing_sections","Dashboard intent needs at least one section.","sections"));const r=s.flatMap(d=>d&&typeof d=="object"&&Array.isArray(d.views)?d.views.filter(u).map(p=>p.id).filter(p=>!!p):[]),c=I(r);c&&i.push(a("duplicate_view_id",`Duplicate dashboard view id: ${c}.`,"sections"));for(const[d,p]of s.entries()){const f=`sections.${d}`;if(!p||typeof p!="object"){i.push(a("invalid_section","Dashboard section must be an object.",f));continue}if(l(p.title)||i.push(a("missing_section_title","Dashboard section needs a title.",f)),!Array.isArray(p.views)||p.views.length===0){i.push(a("missing_section_views","Dashboard section needs at least one view.",`${f}.views`));continue}for(const[b,y]of p.views.entries())Le(y,`${f}.views.${b}`,i,t)}return{ok:i.length===0,errors:i,warnings:t}}exports.parseSemaphorIsoInstant=de;exports.parseSemaphorIsoTimeWindowBoundary=x;exports.validateSemaphorAnalyticsIntent=F;exports.validateSemaphorAnalyticsRecoveryPlan=He;exports.validateSemaphorDashboardIntent=Ue;exports.validateSemaphorDerivedFieldDefinition=X;exports.validateSemaphorOperationIntent=Z;exports.validateSemaphorResultCalculation=Be;
|