@duckcodeailabs/dql-cli 1.13.5 → 1.14.1
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/args.d.ts +17 -0
- package/dist/args.d.ts.map +1 -1
- package/dist/args.js +30 -0
- package/dist/args.js.map +1 -1
- package/dist/assets/dql-notebook/assets/{AgentLogPage-BzQOKjyV.js → AgentLogPage-BPz-UWFh.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiBuildDialog-CTxha499.js → AiBuildDialog-BEl53WA_.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiBuildResult--MuD_I6g.js → AiBuildResult-B4yfGTTZ.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiSidePanel-DcI4PMJ1.js → AiSidePanel-CSZAAvuD.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AnalyticsHome-Dq54vjNz.js → AnalyticsHome-D5P6Ujwi.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AppsView-0SlwWYex.js → AppsView-DQOwU9Cg.js} +4 -4
- package/dist/assets/dql-notebook/assets/{BlockStudio-CxxXZD3M.js → BlockStudio-B4ap0GdY.js} +1 -1
- package/dist/assets/dql-notebook/assets/{BusinessArtifactView-DxdAmeUN.js → BusinessArtifactView-BIfNI-0S.js} +1 -1
- package/dist/assets/dql-notebook/assets/{DbtFirstModelingPage-y81gFg_b.js → DbtFirstModelingPage-D72byb2g.js} +1 -1
- package/dist/assets/dql-notebook/assets/{GitPage-GQtcwncb.js → GitPage-lQb1uXH2.js} +1 -1
- package/dist/assets/dql-notebook/assets/{GlobalAiRail-DM4wkxR_.js → GlobalAiRail-CVECf6Xj.js} +1 -1
- package/dist/assets/dql-notebook/assets/{GovernedContextPage-B8Ft6JES.js → GovernedContextPage-trOyMCY6.js} +1 -1
- package/dist/assets/dql-notebook/assets/{HelpDocsPage-DnD4nMuF.js → HelpDocsPage-D8hLS5lE.js} +1 -1
- package/dist/assets/dql-notebook/assets/{HomePage-Ehb0ITj-.js → HomePage-eIkfBIep.js} +1 -1
- package/dist/assets/dql-notebook/assets/{LineageDAG-Lvjc2AQX.js → LineageDAG-CSqcbDrE.js} +1 -1
- package/dist/assets/dql-notebook/assets/{LineageDetailView-DX32pfbp.js → LineageDetailView-DJZZjZu-.js} +1 -1
- package/dist/assets/dql-notebook/assets/{LineageDrawer-CFq3jPfk.js → LineageDrawer-BcIipIc3.js} +1 -1
- package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-CVHXuHls.js → LineagePathBreadcrumb-CviIf8PN.js} +1 -1
- package/dist/assets/dql-notebook/assets/{MiniLineageGraph-BKaeT5Kt.js → MiniLineageGraph-vH_MY_Ju.js} +1 -1
- package/dist/assets/dql-notebook/assets/{NewBlockModal-DI-JDzFH.js → NewBlockModal-DbCQg-pj.js} +1 -1
- package/dist/assets/dql-notebook/assets/{NewNotebookModal-Csw6eF74.js → NewNotebookModal-5Vp6XiuK.js} +1 -1
- package/dist/assets/dql-notebook/assets/{NotebookEditor-FEqs3789.js → NotebookEditor-DjqJS44s.js} +1 -1
- package/dist/assets/dql-notebook/assets/{ReadinessPage-Bk0S_MEA.js → ReadinessPage-BHGrC5ho.js} +1 -1
- package/dist/assets/dql-notebook/assets/{SetupOnboarding-DyLaPFGn.js → SetupOnboarding-BfS9Tdx-.js} +1 -1
- package/dist/assets/dql-notebook/assets/{SkillsPage-DLHyvhci.js → SkillsPage-BFH21wSj.js} +1 -1
- package/dist/assets/dql-notebook/assets/{TrustBadge-CIDLj2A6.js → TrustBadge-zm6g_SxZ.js} +1 -1
- package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel--oxmjlgr.js +88 -0
- package/dist/assets/dql-notebook/assets/{answer-to-notebook-CFEJHLvs.js → answer-to-notebook-DPhxIEzF.js} +1 -1
- package/dist/assets/dql-notebook/assets/{arrow-left-B-Zdcyvm.js → arrow-left-DNEb86Xc.js} +1 -1
- package/dist/assets/dql-notebook/assets/{arrow-right-Cn8TM7cp.js → arrow-right-DpPWbwaD.js} +1 -1
- package/dist/assets/dql-notebook/assets/{book-open-text-Bko2NNUs.js → book-open-text-D7s5jo4X.js} +1 -1
- package/dist/assets/dql-notebook/assets/{circle-x-AWJAmUBB.js → circle-x-Db3dXKg7.js} +1 -1
- package/dist/assets/dql-notebook/assets/{dagre.esm-Cl_ucrRh.js → dagre.esm-C7pppQ1a.js} +1 -1
- package/dist/assets/dql-notebook/assets/{external-link-DN57tb5f.js → external-link-BxwXitO_.js} +1 -1
- package/dist/assets/dql-notebook/assets/{grip-vertical-BOWwFFva.js → grip-vertical-Dt4lkWRi.js} +1 -1
- package/dist/assets/dql-notebook/assets/{index-Ck-wqvV2.js → index-DKo-bwNw.js} +4 -4
- package/dist/assets/dql-notebook/assets/{link-2-xUhbfBs8.js → link-2-Dfo2P6wi.js} +1 -1
- package/dist/assets/dql-notebook/assets/{list-tree-BDWcBr67.js → list-tree-DiTmIWAL.js} +1 -1
- package/dist/assets/dql-notebook/assets/{minimize-2-CEeNoMTS.js → minimize-2-CMTAkPzL.js} +1 -1
- package/dist/assets/dql-notebook/assets/{panel-right-open-DnSeUvOY.js → panel-right-open-DwYr7FW4.js} +1 -1
- package/dist/assets/dql-notebook/assets/{play-EoDj8-fa.js → play-BXhHYQ4x.js} +1 -1
- package/dist/assets/dql-notebook/assets/{rotate-ccw-BAMxWT9A.js → rotate-ccw-BNi6F8pl.js} +1 -1
- package/dist/assets/dql-notebook/assets/{semantic-fields-BwLOs1kl.js → semantic-fields-CNOGysAy.js} +1 -1
- package/dist/assets/dql-notebook/assets/{sliders-horizontal-BYkm8SWW.js → sliders-horizontal-Ec5MUMUW.js} +1 -1
- package/dist/assets/dql-notebook/assets/{star-sVexqNCs.js → star-B9leDkp_.js} +1 -1
- package/dist/assets/dql-notebook/assets/{triangle-alert-D2njv4o4.js → triangle-alert-BefTYCzx.js} +1 -1
- package/dist/assets/dql-notebook/assets/{upload-CXTMxIA8.js → upload-SPiOM2tQ.js} +1 -1
- package/dist/assets/dql-notebook/assets/{usePersistedAgentThreadId-CPDeaAgL.js → usePersistedAgentThreadId-C4foXeiQ.js} +4 -4
- package/dist/assets/dql-notebook/assets/{user-round-zVsI_uud.js → user-round-comGmyw-.js} +1 -1
- package/dist/assets/dql-notebook/assets/{wand-sparkles-BMIwIzXT.js → wand-sparkles-BffR4dF8.js} +1 -1
- package/dist/assets/dql-notebook/assets/{workflow-Dj9y1sNk.js → workflow-ChmPTEzH.js} +1 -1
- package/dist/assets/dql-notebook/assets/{wrench-DPQi6zrs.js → wrench-DovaG_ze.js} +1 -1
- package/dist/assets/dql-notebook/assets/{x-XhhbtinL.js → x-nRx91AgW.js} +1 -1
- package/dist/assets/dql-notebook/index.html +1 -1
- package/dist/commands/agent-eval-cassette.d.ts +73 -0
- package/dist/commands/agent-eval-cassette.d.ts.map +1 -0
- package/dist/commands/agent-eval-cassette.js +170 -0
- package/dist/commands/agent-eval-cassette.js.map +1 -0
- package/dist/commands/agent-eval-runtime.d.ts +97 -0
- package/dist/commands/agent-eval-runtime.d.ts.map +1 -0
- package/dist/commands/agent-eval-runtime.js +155 -0
- package/dist/commands/agent-eval-runtime.js.map +1 -0
- package/dist/commands/agent.d.ts +115 -1
- package/dist/commands/agent.d.ts.map +1 -1
- package/dist/commands/agent.js +289 -62
- package/dist/commands/agent.js.map +1 -1
- package/dist/commands/eval.d.ts +15 -1
- package/dist/commands/eval.d.ts.map +1 -1
- package/dist/commands/eval.js +32 -3
- package/dist/commands/eval.js.map +1 -1
- package/dist/index.js +5 -1
- package/dist/index.js.map +1 -1
- package/dist/llm/analyst-loop-tools.d.ts +19 -0
- package/dist/llm/analyst-loop-tools.d.ts.map +1 -0
- package/dist/llm/analyst-loop-tools.js +56 -0
- package/dist/llm/analyst-loop-tools.js.map +1 -0
- package/dist/llm/providers/dql-agent-provider.d.ts +24 -1
- package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
- package/dist/llm/providers/dql-agent-provider.js +343 -10
- package/dist/llm/providers/dql-agent-provider.js.map +1 -1
- package/dist/llm/types.d.ts +19 -1
- package/dist/llm/types.d.ts.map +1 -1
- package/dist/local-runtime.d.ts +132 -2
- package/dist/local-runtime.d.ts.map +1 -1
- package/dist/local-runtime.js +1120 -184
- package/dist/local-runtime.js.map +1 -1
- package/dist/package.json +10 -10
- package/package.json +10 -10
- package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-C0oKTU6G.js +0 -88
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/HomePage-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/HomePage-eIkfBIep.js","assets/TrustBadge-zm6g_SxZ.js","assets/arrow-right-DpPWbwaD.js","assets/triangle-alert-BefTYCzx.js","assets/book-open-text-D7s5jo4X.js","assets/workflow-ChmPTEzH.js","assets/react-CRB3T2We.js","assets/AnalyticsHome-D5P6Ujwi.js","assets/answer-to-notebook-DPhxIEzF.js","assets/UnifiedAgentRunPanel--oxmjlgr.js","assets/usePersistedAgentThreadId-C4foXeiQ.js","assets/AiBuildResult-B4yfGTTZ.js","assets/user-round-comGmyw-.js","assets/rotate-ccw-BNi6F8pl.js","assets/wrench-DovaG_ze.js","assets/x-nRx91AgW.js","assets/list-tree-DiTmIWAL.js","assets/minimize-2-CMTAkPzL.js","assets/star-B9leDkp_.js","assets/GlobalAiRail-CVECf6Xj.js","assets/AiSidePanel-CSZAAvuD.js","assets/NotebookEditor-DjqJS44s.js","assets/LineagePathBreadcrumb-CviIf8PN.js","assets/codemirror-DXt7RW72.js","assets/semantic-fields-CNOGysAy.js","assets/MiniLineageGraph-vH_MY_Ju.js","assets/dagre.esm-C7pppQ1a.js","assets/dagre-BZV40eAE.css","assets/link-2-Dfo2P6wi.js","assets/upload-SPiOM2tQ.js","assets/NewNotebookModal-5Vp6XiuK.js","assets/NewBlockModal-DbCQg-pj.js","assets/SetupOnboarding-BfS9Tdx-.js","assets/arrow-left-DNEb86Xc.js","assets/BlockStudio-B4ap0GdY.js","assets/play-BXhHYQ4x.js","assets/panel-right-open-DwYr7FW4.js","assets/BusinessArtifactView-BIfNI-0S.js","assets/LineageDetailView-DJZZjZu-.js","assets/LineageDAG-CSqcbDrE.js","assets/HelpDocsPage-D8hLS5lE.js","assets/GitPage-lQb1uXH2.js","assets/external-link-BxwXitO_.js","assets/ReadinessPage-BHGrC5ho.js","assets/ai-build-bus-1BR770pY.js","assets/wand-sparkles-BffR4dF8.js","assets/AgentLogPage-BPz-UWFh.js","assets/circle-x-Db3dXKg7.js","assets/GovernedContextPage-trOyMCY6.js","assets/SkillsPage-BFH21wSj.js","assets/DbtFirstModelingPage-D72byb2g.js","assets/sliders-horizontal-Ec5MUMUW.js","assets/AppsView-DQOwU9Cg.js","assets/grip-vertical-Dt4lkWRi.js","assets/LineageDrawer-BcIipIc3.js","assets/AiBuildDialog-BEl53WA_.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
var Rf=Object.defineProperty;var ec=e=>{throw TypeError(e)};var Of=(e,t,n)=>t in e?Rf(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var Pe=(e,t,n)=>Of(e,typeof t!="symbol"?t+"":t,n),Ms=(e,t,n)=>t.has(e)||ec("Cannot "+n);var R=(e,t,n)=>(Ms(e,t,"read from private field"),n?n.call(e):t.get(e)),le=(e,t,n)=>t.has(e)?ec("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),Z=(e,t,n,r)=>(Ms(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n),fe=(e,t,n)=>(Ms(e,t,"access private method"),n);var $o=(e,t,n,r)=>({set _(o){Z(e,t,o,n)},get _(){return R(e,t,r)}});import{r as Xl,a as Zl,g as ed}from"./react-CRB3T2We.js";function _f(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const o in r)if(o!=="default"&&!(o in e)){const i=Object.getOwnPropertyDescriptor(r,o);i&&Object.defineProperty(e,o,i.get?i:{enumerable:!0,get:()=>r[o]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const o of document.querySelectorAll('link[rel="modulepreload"]'))r(o);new MutationObserver(o=>{for(const i of o)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(o){const i={};return o.integrity&&(i.integrity=o.integrity),o.referrerPolicy&&(i.referrerPolicy=o.referrerPolicy),o.crossOrigin==="use-credentials"?i.credentials="include":o.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(o){if(o.ep)return;o.ep=!0;const i=n(o);fetch(o.href,i)}})();var Ls={exports:{}},Fr={};/**
|
|
3
3
|
* @license React
|
|
4
4
|
* react-jsx-runtime.production.min.js
|
|
@@ -393,7 +393,7 @@ For more information, see https://radix-ui.com/primitives/docs/components/${t.do
|
|
|
393
393
|
* See the LICENSE file in the root directory of this source tree.
|
|
394
394
|
*/const JS=[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]],vp=ne("trash-2",JS);function YS(e,t){if(!t)return 1;const n=(e.label+" "+e.group+" "+(e.keywords||"")).toLowerCase(),r=t.toLowerCase();if(n.includes(r))return 100-n.indexOf(r);let o=0;for(const i of n)if(i===r[o]&&o++,o===r.length)return 10;return 0}function XS(e,t){const n=e.mode??"both";return n==="both"||n===t}function ZS({open:e,onClose:t}){const{state:n,dispatch:r}=et(),[o,i]=p.useState(""),[a,c]=p.useState(0),l=p.useRef(null);p.useEffect(()=>{e&&(i(""),c(0))},[e]);const u=p.useMemo(()=>{const m=x=>r(x),S=()=>t(),v=x=>()=>{x(),S()},b=[["Files","files",Yv],["Lineage","lineage",cS],["Git","git",Nr],["Block Library","block_library",Oa],["Apps","apps",bS],["Connections","connection",AS]],w=[{mode:"obsidian",label:"Obsidian"},{mode:"paper",label:"Paper"},{mode:"white",label:"White"}],j=[];j.push({id:"sidebar.toggle",label:n.sidebarOpen?"Hide sidebar":"Show sidebar",group:"View",icon:ES,shortcut:"⌘B",mode:"studio",run:v(()=>m({type:"TOGGLE_SIDEBAR"}))},{id:"inspector.toggle",label:n.inspectorOpen?"Hide inspector":"Show inspector",group:"View",icon:n.inspectorOpen?Lv:Bv,shortcut:"⌘⇧I",mode:"studio",run:v(()=>m({type:"TOGGLE_INSPECTOR"}))},{id:"dashboard.toggle",label:n.dashboardMode?"Exit dashboard mode":"Enter dashboard mode",group:"View",icon:uS,shortcut:"⌘D",run:v(()=>m({type:"TOGGLE_DASHBOARD_MODE"}))},{id:"dev.toggle",label:"Toggle dev panel",group:"View",icon:QS,shortcut:"⌘J",mode:"studio",run:v(()=>m({type:"TOGGLE_DEV_PANEL"}))});for(const[x,E,P]of b)j.push({id:`panel.${E}`,label:`Go to ${x}`,group:"Navigate",icon:P,mode:"studio",run:v(()=>{m({type:"SET_SIDEBAR_PANEL",panel:E}),E!=="lineage"&&!n.sidebarOpen&&m({type:"TOGGLE_SIDEBAR"})})});j.push({id:"notebook.new",label:"New notebook…",group:"Create",icon:gp,mode:"studio",run:v(()=>m({type:"OPEN_NEW_NOTEBOOK_MODAL"}))},{id:"block.new",label:"New block…",group:"Create",icon:KS,mode:"studio",run:v(()=>m({type:"OPEN_NEW_BLOCK_MODAL"}))});const C=n.themeMode==="dark"||n.themeMode==="midnight"?"obsidian":n.themeMode==="light"?"paper":n.themeMode==="arctic"?"white":n.themeMode;for(const x of w)x.mode!==C&&j.push({id:`theme.${x.mode}`,label:`Switch to ${x.label}`,group:"Theme",icon:CS,keywords:"appearance color",run:v(()=>m({type:"SET_THEME",mode:x.mode}))});return j},[n.sidebarOpen,n.inspectorOpen,n.themeMode,n.dashboardMode,n.appMode,n.sidebarPanel,r,t]),h=p.useMemo(()=>{const S=u.filter(v=>XS(v,n.appMode)).map(v=>({a:v,s:YS(v,o)})).filter(v=>v.s>0);return S.sort((v,b)=>b.s-v.s),S.map(v=>v.a)},[u,o,n.appMode]);p.useEffect(()=>{c(0)},[o]),p.useEffect(()=>{var S;const m=(S=l.current)==null?void 0:S.querySelector(`[data-palette-idx="${a}"]`);m==null||m.scrollIntoView({block:"nearest"})},[a]);const d=m=>{var S;m.key==="ArrowDown"?(m.preventDefault(),c(v=>Math.min(h.length-1,v+1))):m.key==="ArrowUp"?(m.preventDefault(),c(v=>Math.max(0,v-1))):m.key==="Enter"&&(m.preventDefault(),(S=h[a])==null||S.run())};let f="";return s.jsx(Ny,{open:e,onOpenChange:m=>!m&&t(),children:s.jsxs(By,{children:[s.jsx(Fy,{style:{position:"fixed",inset:0,background:pe("surfaceOverlay"),zIndex:io.overlay}}),s.jsxs(zy,{"aria-label":"Command palette",style:{position:"fixed",top:"18vh",left:"50%",transform:"translateX(-50%)",width:"92vw",maxWidth:620,background:pe("surfaceRaised"),color:pe("textPrimary"),border:`1px solid ${pe("borderDefault")}`,borderRadius:wn.lg,boxShadow:pe("shadowLg"),zIndex:io.modal,display:"flex",flexDirection:"column",overflow:"hidden"},onKeyDown:d,children:[s.jsx(qy,{style:{position:"absolute",left:-9999},children:"Command palette"}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:be[2],padding:`${be[3]}px ${be[4]}px`,borderBottom:`1px solid ${pe("borderSubtle")}`},children:[s.jsx(Iv,{size:14,strokeWidth:1.75,color:pe("textMuted")}),s.jsx("input",{autoFocus:!0,value:o,onChange:m=>i(m.target.value),placeholder:"Type a command…",style:{flex:1,border:"none",outline:"none",background:"transparent",color:pe("textPrimary"),fontSize:Ze.md}})]}),s.jsxs("div",{ref:l,style:{maxHeight:360,overflowY:"auto",padding:`${be[1]}px 0`},children:[h.length===0&&s.jsx("div",{style:{padding:be[4],fontSize:Ze.sm,color:pe("textMuted"),textAlign:"center"},children:"No matching commands"}),h.map((m,S)=>{const v=m.group!==f;f=m.group;const b=S===a,w=m.icon;return s.jsxs(qe.Fragment,{children:[v&&s.jsx("div",{style:{padding:`${be[2]}px ${be[4]}px ${be[1]}px`},children:s.jsx(up,{tone:"neutral",children:m.group})}),s.jsxs("div",{"data-palette-idx":S,role:"option","aria-selected":b,onMouseEnter:()=>c(S),onMouseDown:j=>{j.preventDefault(),m.run()},style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:be[3],padding:`${be[2]}px ${be[4]}px`,fontSize:Ze.sm,cursor:"pointer",background:b?pe("surfaceHover"):"transparent",color:pe("textPrimary")},children:[s.jsxs("span",{style:{display:"flex",alignItems:"center",gap:be[2],minWidth:0,flex:1},children:[w&&s.jsx(w,{size:14,strokeWidth:1.75}),s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:m.label})]}),m.shortcut&&s.jsx(Ix,{shortcut:m.shortcut})]})]},m.id)})]})]})]})})}function zi(e){const t=Dt(e);if(!t)return;const n=wp(t.kind),r=tw(t.source);if(!n||!r)return;const o=Cp(t.limit);return{kind:n,source:r,name:yt(t.name),sourcePath:yt(t.sourcePath),metrics:qi(t.metrics),dimensions:qi(t.dimensions),filters:rw(t.filters),timeDimension:ow(t.timeDimension),orderBy:sw(t.orderBy),parameters:iw(t.parameters),parameterValues:dw(t.parameterValues),persistence:uw(t.persistence),trustState:kp(t.trustState),compiledSql:yt(t.compiledSql),executionReceipt:Sp(t.executionReceipt),executableArtifact:ew(t.executableArtifact),filterableColumns:nw(t.filterableColumns),...o===void 0?{}:{limit:o}}}function ew(e){const t=Dt(e);if(!t||t.version!==1)return;const n=wp(t.kind),r=kp(t.trustState),o=yt(t.semanticAdapter),i=Dt(t.previewPolicy),a=(i==null?void 0:i.mode)==="read_only_bounded"||(i==null?void 0:i.mode)==="compiler_governed"?i.mode:void 0,c=Sp(t.receipt),l={dqlFingerprint:pt(t.dqlFingerprint),sourceFingerprint:pt(t.sourceFingerprint),compiledSqlFingerprint:pt(t.compiledSqlFingerprint),normalizedSqlFingerprint:pt(t.normalizedSqlFingerprint),parameterFingerprint:pt(t.parameterFingerprint),provenanceFingerprint:pt(t.provenanceFingerprint),targetFingerprint:pt(t.targetFingerprint),snapshotFingerprint:pt(t.snapshotFingerprint),planFingerprint:pt(t.planFingerprint)};if(!n||!r||!o||!a||!c||Object.values(l).some(h=>!h))return;const u=Cp(i==null?void 0:i.rowLimit);if(!(a==="read_only_bounded"&&u===void 0))return{version:1,kind:n,...l,semanticAdapter:o,previewPolicy:{mode:a,...u===void 0?{}:{rowLimit:u}},trustState:r,receipt:c}}function tw(e){return typeof e=="string"&&e.trim().length>0?e:void 0}function nw(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Dt(n),o=yt(r==null?void 0:r.column),i=yt(r==null?void 0:r.predicateTarget);return o&&i?[{column:o,predicateTarget:i}]:[]});return t.length>0?t:void 0}function Sp(e){const t=Dt(e);if(!t)return;const n=pt(t.sourceFingerprint),r=pt(t.compiledSqlFingerprint),o=pt(t.parameterFingerprint),i=pt(t.resultFingerprint);return n&&r&&o&&i?{sourceFingerprint:n,compiledSqlFingerprint:r,parameterFingerprint:o,resultFingerprint:i}:void 0}function pt(e){return typeof e=="string"&&/^[a-f0-9]{64}$/i.test(e.trim())?e.trim().toLowerCase():void 0}function wp(e){return e==="certified_block"||e==="semantic_block"||e==="sql_block"?e:void 0}function rw(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Dt(n);if(!r)return[];const o=yt(r.dimension),i=yt(r.operator);return!o||!i?[]:[{dimension:o,operator:i,values:qi(r.values)??[]}]});return t.length?t:void 0}function ow(e){const t=Dt(e);if(!t)return;const n=yt(t.name),r=yt(t.granularity);return n&&r?{name:n,granularity:r}:void 0}function sw(e){if(!Array.isArray(e))return;const t=e.flatMap(n=>{const r=Dt(n);if(!r)return[];const o=yt(r.name),i=r.direction==="asc"||r.direction==="desc"?r.direction:void 0;return o&&i?[{name:o,direction:i}]:[]});return t.length?t:void 0}function iw(e){if(!Array.isArray(e))return;const t=new Set,n=e.flatMap(r=>{const o=Dt(r),i=yt(o==null?void 0:o.name),a=aw(o==null?void 0:o.type),c=cw(o==null?void 0:o.policy);if(!o||!i||!a||!c||t.has(i))return[];t.add(i);const l=lw(o.binding);return[{name:i,type:a,required:o.required===!0,...o.default===void 0?{}:{default:o.default},policy:c,...l?{binding:l}:{}}]});return n.length?n:void 0}function aw(e){return e==="string"||e==="number"||e==="boolean"||e==="date"||e==="string[]"||e==="number[]"||e==="date[]"?e:void 0}function cw(e){return e==="dynamic"||e==="static"||e==="business"||e==="derived"||e==="optional"||e==="ambiguous_review_required"?e:void 0}function lw(e){const t=Dt(e);if(!t)return;if(t.kind==="sql_value")return{kind:"sql_value"};if(t.kind==="limit")return{kind:"limit"};const n=yt(t.field);if(t.kind==="semantic_filter"&&n&&(t.operator==="equals"||t.operator==="in"||t.operator==="gte"||t.operator==="lte"))return{kind:"semantic_filter",field:n,operator:t.operator}}function dw(e){const t=Dt(e);if(!t)return;const n=Object.entries(t).filter(([r])=>r.trim().length>0);return n.length?Object.fromEntries(n):void 0}function uw(e){return e==="transient"||e==="saved"?e:void 0}function kp(e){return e==="certified"||e==="governed"||e==="review_required"?e:void 0}function Dt(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function yt(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function qi(e){if(!Array.isArray(e))return;const t=e.filter(n=>typeof n=="string"&&n.trim().length>0).map(n=>n.trim());return t.length?t:void 0}function Cp(e){return typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):void 0}const jp="dql_token",Gc="dql.server-token.v1";function pw(e){var r;return((r=new URLSearchParams(e.replace(/^#/,"")).get(jp))==null?void 0:r.trim())||void 0}function fw(e){const t=new URLSearchParams(e.replace(/^#/,""));t.delete(jp);const n=t.toString();return n?`#${n}`:""}function hw(){var e;if(!(typeof window>"u"))try{const t=pw(window.location.hash);if(t){window.sessionStorage.setItem(Gc,t);const n=fw(window.location.hash);return window.history.replaceState(window.history.state,"",`${window.location.pathname}${window.location.search}${n}`),t}return((e=window.sessionStorage.getItem(Gc))==null?void 0:e.trim())||void 0}catch{return}}const Qc=hw();function lr(e){const t=new Headers(e);return Qc&&t.set("Authorization",`Bearer ${Qc}`),t}async function Ep(e,t,n){const r=await fetch(e,{headers:lr({Accept:"text/event-stream"}),credentials:"same-origin",cache:"no-store",signal:n});if(!r.ok)throw new Error(`Event stream failed with HTTP ${r.status}.`);if(!r.body)throw new Error("Event stream response did not include a body.");const o=r.body.getReader(),i=new TextDecoder;let a="",c="message",l=[];const u=()=>{l.length>0&&t({event:c,data:l.join(`
|
|
395
395
|
`)}),c="message",l=[]};for(;!n.aborted;){const h=await o.read();a+=i.decode(h.value,{stream:!h.done});const d=a.split(/\r?\n/);a=d.pop()??"";for(const f of d)if(f==="")u();else if(!f.startsWith(":")){const m=f.indexOf(":"),S=m<0?f:f.slice(0,m),v=m<0?"":f.slice(m+1).replace(/^ /,"");S==="event"&&(c=v||"message"),S==="data"&&l.push(v)}if(h.done){u();return}}}const mw={totals:{modelsScanned:0,businessModels:0,plumbingExcluded:0,metricsFound:0},willGenerate:0,willSkip:0,domains:[],config:{businessLayers:[],excludeLayers:[],maxPerDomain:0,minScore:0,aiEnrichment:"auto"}};function Ko(){return{total:0,tracked:0,changed:0,untracked:0,ignored:0,paths:[]}}const Qr=window.location.origin;class St extends Error{constructor(n){super(n.message);Pe(this,"status");Pe(this,"code");Pe(this,"recoverable");Pe(this,"details");Pe(this,"nextActions");Pe(this,"requestId");Pe(this,"snapshotId");this.name="DqlApiError",this.status=n.status,this.code=n.code,this.recoverable=n.recoverable,this.details=n.details,this.nextActions=n.nextActions,this.requestId=n.requestId,this.snapshotId=n.snapshotId}}function Ui(e,t){const n=t.trim()||e.statusText||`HTTP ${e.status}`;if(!t.trim())return new St({message:n,status:e.status});try{const r=JSON.parse(t),o=Array.isArray(r==null?void 0:r.errors)?r.errors.filter(a=>typeof a=="string"&&a.trim().length>0):[],i=typeof(r==null?void 0:r.friendlyMessage)=="string"&&r.friendlyMessage.trim()?r.friendlyMessage:typeof(r==null?void 0:r.message)=="string"&&r.message.trim()?r.message:typeof(r==null?void 0:r.error)=="string"&&r.error.trim()?r.error:o.length>0?`${o.slice(0,3).join(" ")}${o.length>3?` ${o.length-3} more blockers.`:""}`:n;return new St({message:i,status:e.status,code:typeof(r==null?void 0:r.code)=="string"?r.code:void 0,recoverable:typeof(r==null?void 0:r.recoverable)=="boolean"?r.recoverable:void 0,details:(r==null?void 0:r.details)??(typeof(r==null?void 0:r.error)=="string"&&r.error.trim()&&r.error!==i?{technicalDetails:r.error}:o.length>0?{errors:o,draft:r==null?void 0:r.draft}:void 0),nextActions:Array.isArray(r==null?void 0:r.nextActions)?r.nextActions.filter(a=>typeof a=="string"):void 0,requestId:typeof(r==null?void 0:r.requestId)=="string"?r.requestId:void 0,snapshotId:typeof(r==null?void 0:r.snapshotId)=="string"?r.snapshotId:void 0})}catch{return new St({message:n,status:e.status})}}const Js=new Map;async function k(e,t){if(((t==null?void 0:t.method)??"GET").toUpperCase()==="GET"&&!(t!=null&&t.signal)&&!(t!=null&&t.body)){const o=Js.get(e);if(o)return o;const i=Jc(e,t).finally(()=>{Js.delete(e)});return Js.set(e,i),i}return Jc(e,t)}async function Jc(e,t){var r;let n;try{const o=lr(t==null?void 0:t.headers);o.has("Content-Type")||o.set("Content-Type","application/json"),n=await fetch(`${Qr}${e}`,{...t,headers:o})}catch(o){if((r=t==null?void 0:t.signal)!=null&&r.aborted)throw o;const i=o instanceof Error&&o.message?` ${o.message}`:"";throw new Error(`Unable to reach the local DQL notebook server. Check that it is still running, then retry.${i}`)}if(!n.ok){const o=await n.text().catch(()=>"");throw Ui(n,o)}if(n.status!==204)return n.json()}async function gw(e,t){if(!e.body)throw new Error("Agent run stream is not available in this browser.");const n=e.body.getReader(),r=new TextDecoder;let o="",i;const a=c=>{const l=c.split(/\r?\n/);let u="message";const h=[];for(const f of l)f.startsWith("event:")&&(u=f.slice(6).trim()),f.startsWith("data:")&&h.push(f.slice(5).trimStart());if(h.length===0)return;const d=JSON.parse(h.join(`
|
|
396
|
-
`));if(u==="agent-run-event")t({kind:"event",event:d});else if(u==="agent-run-answer-delta"){const f=typeof(d==null?void 0:d.delta)=="string"?d.delta:"";f&&t({kind:"answer-delta",delta:f})}else if(u==="agent-run-complete")i=d,t({kind:"complete",run:i});else if(u==="agent-run-error")throw new Error(typeof(d==null?void 0:d.error)=="string"?d.error:"Agent run failed.")};for(;;){const{value:c,done:l}=await n.read();if(c){o+=r.decode(c,{stream:!l});let u=o.search(/\r?\n\r?\n/);for(;u>=0;){const h=o.slice(0,u);o=o.slice(o[u]==="\r"?u+4:u+2),a(h),u=o.search(/\r?\n\r?\n/)}}if(l)break}if(o.trim()&&a(o),!i)throw new Error("Agent run stream ended before completion.");return i}function an(e){var r;const t=Array.isArray(e==null?void 0:e.columns)?e.columns.map(o=>typeof o=="string"?o:typeof(o==null?void 0:o.name)=="string"?o.name:String(o)):[],n=e!=null&&e.semanticRefs&&typeof e.semanticRefs=="object"?{metrics:Array.isArray(e.semanticRefs.metrics)?e.semanticRefs.metrics.map(String):[],dimensions:Array.isArray(e.semanticRefs.dimensions)?e.semanticRefs.dimensions.map(String):[]}:void 0;return{columns:t,rows:Array.isArray(e==null?void 0:e.rows)?e.rows:[],rowCount:(e==null?void 0:e.rowCount)??((r=e==null?void 0:e.rows)==null?void 0:r.length)??0,executionTime:(e==null?void 0:e.executionTime)??(e==null?void 0:e.executionTimeMs)??0,...n?{semanticRefs:n}:{}}}function Vt(e){var n;const t=e!=null&&e.resultPreview&&typeof e.resultPreview=="object"?an(e.resultPreview):void 0;return{...e,domain:typeof(e==null?void 0:e.domain)=="string"&&e.domain.trim()?e.domain:void 0,owner:typeof(e==null?void 0:e.owner)=="string"&&e.owner.trim()?e.owner:void 0,warnings:Array.isArray(e==null?void 0:e.warnings)?e.warnings:[],dqlCandidateIds:Array.isArray(e==null?void 0:e.dqlCandidateIds)?e.dqlCandidateIds:[],dqlArtifact:zi(e==null?void 0:e.dqlArtifact),dqlPromotionAction:Ew((e==null?void 0:e.dqlPromotionAction)??((n=e==null?void 0:e.dqlPromotion)==null?void 0:n.recommendedAction)),dqlPromotion:Tp(e==null?void 0:e.dqlPromotion),researchPlan:yw(e==null?void 0:e.researchPlan),reviewChecklist:Cw(e==null?void 0:e.reviewChecklist,e),...t?{resultPreview:t}:{resultPreview:void 0}}}function yw(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,n=t.evidence&&typeof t.evidence=="object"&&!Array.isArray(t.evidence)?t.evidence:{},r=t.preview&&typeof t.preview=="object"&&!Array.isArray(t.preview)?t.preview:{},o=t.promotion&&typeof t.promotion=="object"&&!Array.isArray(t.promotion)?t.promotion:{},i=t.sqlState==="generated"||t.sqlState==="reviewed"?t.sqlState:"missing",a=r.status==="ready"||r.status==="error"?r.status:"not_run",c=o.path==="review_context"||o.path==="run_preview"||o.path==="reuse_existing"||o.path==="create_dql_draft"||o.path==="open_certification"||o.path==="complete_review"?o.path:"needs_sql",l=typeof r.rowCount=="number"&&Number.isFinite(r.rowCount)?r.rowCount:void 0;return{sqlState:i,grain:typeof t.grain=="string"&&t.grain.trim()?t.grain:void 0,parameterPolicy:bw(t.parameterPolicy),allowedFilters:Array.isArray(t.allowedFilters)?t.allowedFilters.map(String).filter(Boolean):[],evidence:{trustLabel:typeof n.trustLabel=="string"&&n.trustLabel.trim()?n.trustLabel:void 0,contextPackId:typeof n.contextPackId=="string"&&n.contextPackId.trim()?n.contextPackId:void 0,evidenceCount:Ce(n.evidenceCount),relationCount:Ce(n.relationCount),missingContextCount:Ce(n.missingContextCount)},preview:{status:a,...l===void 0?{}:{rowCount:l}},promotion:{path:c,duplicateDecision:typeof o.duplicateDecision=="string"&&o.duplicateDecision.trim()?o.duplicateDecision:void 0},reviewFocus:Array.isArray(t.reviewFocus)?t.reviewFocus.map(String).filter(Boolean):[],generatedAt:typeof t.generatedAt=="string"&&t.generatedAt.trim()?t.generatedAt:new Date(0).toISOString()}}function bw(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];const n=t,r=typeof n.name=="string"&&n.name.trim()?n.name:void 0,o=typeof n.policy=="string"&&n.policy.trim()?n.policy:void 0;return r&&o?[{name:r,policy:o}]:[]}):[]}function Ce(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function rr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function xw(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{totalReviewCount:Ce(t.totalReviewCount),openReviewCount:Ce(t.openReviewCount),terminalReviewCount:Ce(t.terminalReviewCount),draftCreatedCount:Ce(t.draftCreatedCount),certifiedCount:Ce(t.certifiedCount),completedCount:Ce(t.completedCount),rejectedCount:Ce(t.rejectedCount),draftCreationRate:rr(t.draftCreationRate),certifyConversionRate:rr(t.certifyConversionRate),medianOpenReviewAgeMs:rr(t.medianOpenReviewAgeMs),medianTimeToDraftMs:rr(t.medianTimeToDraftMs),medianTimeToCertificationMs:rr(t.medianTimeToCertificationMs),medianTimeToTerminalMs:rr(t.medianTimeToTerminalMs)}}function vw(e){const t=e&&typeof e=="object"?e:{},n=t.counts&&typeof t.counts=="object"?t.counts:{},r=t.health&&typeof t.health=="object"?t.health:{},o=t.search&&typeof t.search=="object"?t.search:{},i=t.updatedAt&&typeof t.updatedAt=="object"?t.updatedAt:{},a=t.limits&&typeof t.limits=="object"?t.limits:{};return{counts:{totalRuns:Ce(n.totalRuns),activeRuns:Ce(n.activeRuns),closedRuns:Ce(n.closedRuns),notebooks:Ce(n.notebooks),domains:Ce(n.domains),owners:Ce(n.owners),sourceLinkedRuns:Ce(n.sourceLinkedRuns)},health:{staleOpenRuns:Ce(r.staleOpenRuns),expiredOpenRuns:Ce(r.expiredOpenRuns),staleThresholdDays:Ce(r.staleThresholdDays)||7,expiredThresholdDays:Ce(r.expiredThresholdDays)||30,oldestOpenUpdatedAt:typeof r.oldestOpenUpdatedAt=="string"&&r.oldestOpenUpdatedAt.trim()?r.oldestOpenUpdatedAt:void 0,newestOpenUpdatedAt:typeof r.newestOpenUpdatedAt=="string"&&r.newestOpenUpdatedAt.trim()?r.newestOpenUpdatedAt:void 0},search:{indexed:o.indexed===!0,indexRows:Ce(o.indexRows),indexVersion:typeof o.indexVersion=="string"&&o.indexVersion.trim()?o.indexVersion:void 0,stale:o.stale===!0},updatedAt:{oldest:typeof i.oldest=="string"&&i.oldest.trim()?i.oldest:void 0,newest:typeof i.newest=="string"&&i.newest.trim()?i.newest:void 0},limits:{pageSize:Ce(a.pageSize)||25,maxPageSize:Ce(a.maxPageSize)||500,sourceCoverageLimit:Ce(a.sourceCoverageLimit)||1e4,seedCellLimit:Ce(a.seedCellLimit)||1e3},warnings:Array.isArray(t.warnings)?t.warnings.filter(c=>typeof c=="string"):[]}}function Sw(e){return e==="diagnose_change"||e==="driver_breakdown"||e==="segment_compare"||e==="entity_drilldown"||e==="anomaly_investigation"||e==="trust_gap_review"?e:"ad_hoc_analysis"}function ww(e){const t=typeof e=="string"?e:"";return(t.split(/[\\/]/).pop()??t).replace(/\.dqlnb$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim()||"Untitled notebook"}function kw(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=r=>typeof t[r]=="number"&&Number.isFinite(t[r])?t[r]:0;return{fix_blockers:n("fix_blockers"),review_sql:n("review_sql"),review_context:n("review_context"),run_preview:n("run_preview"),reuse_existing:n("reuse_existing"),create_dql_draft:n("create_dql_draft"),open_certification:n("open_certification"),complete_review:n("complete_review"),continue_review:n("continue_review")}}function Vo(e){return e==="fix_blockers"||e==="review_sql"||e==="review_context"||e==="run_preview"||e==="reuse_existing"||e==="create_dql_draft"||e==="open_certification"||e==="complete_review"||e==="continue_review"?e:void 0}function Cw(e,t){var u,h;if(e&&typeof e=="object"&&Array.isArray(e.items))return{readyForDqlDraft:e.readyForDqlDraft===!0,readyForCertificationReview:e.readyForCertificationReview===!0,blockers:Array.isArray(e.blockers)?e.blockers.filter(d=>typeof d=="string"):[],warnings:Array.isArray(e.warnings)?e.warnings.filter(d=>typeof d=="string"):[],items:e.items.map(d=>({id:typeof d.id=="string"?d.id:"item",label:typeof d.label=="string"?d.label:"Review item",status:d.status==="passed"||d.status==="pending"||d.status==="warning"||d.status==="blocked"?d.status:"pending",detail:typeof d.detail=="string"?d.detail:""}))};const n=!!t.reviewedSql,r=n||!!t.generatedSql,o=((u=t.resultPreview)==null?void 0:u.rowCount)??((h=t.resultPreview)==null?void 0:h.rows.length)??0,i=!!(t.resultPreview&&(t.resultPreview.columns.length>0||o>0)),a=!!t.draftBlockPath,c=!!(t.contextPackId||t.evidence),l=t.dqlPromotionAction==="reuse_existing";return{readyForDqlDraft:!!(!l&&t.question&&n&&c&&t.status!=="error"),readyForCertificationReview:!!(!l&&t.question&&n&&c&&i&&a),blockers:t.status==="error"?[t.error??"Preview failed."]:[],warnings:i||l?[]:["Run a bounded preview before certification review."],items:[{id:"question",label:"Question",status:t.question?"passed":"blocked",detail:t.question?"Business question is captured.":"Add a business question."},{id:"sql",label:"Reviewed SQL",status:r||l?"passed":"blocked",detail:l&&!r?"Existing DQL should be reused; no new SQL is required.":r?"SQL is available.":"Add SQL before promotion."},{id:"evidence",label:"Evidence",status:c||l?"passed":"warning",detail:c?"Context evidence is saved.":l?"Reuse evidence is captured in the recommendation.":"Preview and save metadata context."},{id:"preview",label:"Preview",status:i||l?"passed":"pending",detail:i?"Preview result is available.":l?"Certified block reuse does not require a new raw SQL preview.":"Run a bounded preview."},{id:"dql_draft",label:"DQL draft",status:a||l?"passed":"pending",detail:a?`Draft saved at ${t.draftBlockPath}.`:l?"No new DQL draft is required.":"Create a DQL draft after review."}]}}function jw(e){var r,o,i,a;const t=e&&typeof e=="object"?e:{},n=t.routeDecision&&typeof t.routeDecision=="object"?{route:typeof t.routeDecision.route=="string"?t.routeDecision.route:void 0,intent:typeof t.routeDecision.intent=="string"?t.routeDecision.intent:void 0,reason:typeof t.routeDecision.reason=="string"?t.routeDecision.reason:void 0}:void 0;return{contextPackId:typeof t.contextPackId=="string"?t.contextPackId:"",trustLabel:typeof t.trustLabel=="string"?t.trustLabel:void 0,routeDecision:n,evidence:Array.isArray(t.evidence)?t.evidence.map(c=>({objectKey:typeof c.objectKey=="string"?c.objectKey:void 0,objectType:typeof c.objectType=="string"?c.objectType:void 0,name:typeof c.name=="string"?c.name:"Evidence",role:typeof c.role=="string"?c.role:void 0,reason:typeof c.reason=="string"?c.reason:""})):[],summaries:Array.isArray(t.summaries)?t.summaries.map(c=>({title:typeof c.title=="string"?c.title:"Context",detail:typeof c.detail=="string"?c.detail:"",objectType:typeof c.objectType=="string"?c.objectType:void 0,reason:typeof c.reason=="string"?c.reason:void 0})):[],relations:Array.isArray(t.relations)?t.relations.map(c=>({relation:typeof c.relation=="string"?c.relation:"",name:typeof c.name=="string"?c.name:"Relation",source:typeof c.source=="string"?c.source:"",columns:Array.isArray(c.columns)?c.columns.map(String):[]})).filter(c=>c.relation||c.name):[],missingContext:Array.isArray(t.missingContext)?t.missingContext.map(c=>({kind:typeof c.kind=="string"?c.kind:"metadata",message:typeof c.message=="string"?c.message:"",severity:typeof c.severity=="string"?c.severity:"warning"})).filter(c=>c.message):[],warnings:Array.isArray(t.warnings)?t.warnings.filter(c=>typeof c=="string"):[],topRejected:Array.isArray(t.topRejected)?t.topRejected.map(c=>({name:typeof c.name=="string"?c.name:"Rejected context",objectType:typeof c.objectType=="string"?c.objectType:void 0,reason:typeof c.reason=="string"?c.reason:"",score:typeof c.score=="number"&&Number.isFinite(c.score)?c.score:void 0})).filter(c=>c.reason):[],counts:{objects:typeof((r=t.counts)==null?void 0:r.objects)=="number"?t.counts.objects:0,evidence:typeof((o=t.counts)==null?void 0:o.evidence)=="number"?t.counts.evidence:0,relations:typeof((i=t.counts)==null?void 0:i.relations)=="number"?t.counts.relations:0,warnings:typeof((a=t.counts)==null?void 0:a.warnings)=="number"?t.counts.warnings:0}}}function Ew(e){return e==="reuse_existing"||e==="extend_existing"||e==="create_replacement"||e==="create_new"||e==="review_required"?e:void 0}function Tp(e){if(!(!e||typeof e!="object"))return{importId:typeof e.importId=="string"?e.importId:"",candidateIds:Array.isArray(e.candidateIds)?e.candidateIds.filter(t=>typeof t=="string"):[],draftBlockPath:typeof e.draftBlockPath=="string"?e.draftBlockPath:void 0,recommendedAction:typeof e.recommendedAction=="string"?e.recommendedAction:void 0,similarityMatches:Array.isArray(e.similarityMatches)?e.similarityMatches:[],candidates:Array.isArray(e.candidates)?e.candidates.map(t=>({...t,similarityMatches:Array.isArray(t.similarityMatches)?t.similarityMatches:[],parameterPolicy:Array.isArray(t.parameterPolicy)?t.parameterPolicy:[],allowedFilters:Array.isArray(t.allowedFilters)?t.allowedFilters:[],warnings:Array.isArray(t.warnings)?t.warnings:[]})):[],createdAt:typeof e.createdAt=="string"?e.createdAt:""}}function Yc(e){return{id:e.sourceId,sourceId:e.sourceId,qualifiedIdentity:e.qualifiedIdentity,sourceRevision:e.sourceRevision,snapshotId:e.snapshotId,lifecycle:e.lifecycle,trust:e.trust,name:e.name,domain:e.domain??"Unassigned",status:e.lifecycle,owner:e.owner??null,tags:e.tags,path:e.executionRef,fingerprint:e.sourceRevision,lastModified:"",description:e.description??"",chartType:e.capabilities.chartType,filterIds:e.capabilities.filters,dimensionIds:e.capabilities.dimensions,capabilities:e.capabilities,eligibility:e.eligibility,score:e.score??0,reasons:e.reasons}}const B={async listOperations(e=50){return k(`/api/operations?limit=${Math.max(1,Math.min(100,Math.floor(e)))}`)},async getOperation(e){return k(`/api/operations/${encodeURIComponent(e)}`)},async cancelOperation(e){return k(`/api/operations/${encodeURIComponent(e)}`,{method:"DELETE"})},async requestBlockStudioCertification(e){return k("/api/block-studio/certifications",{method:"POST",headers:{"Idempotency-Key":e.idempotencyKey},body:JSON.stringify({source:e.source,path:e.path,metadata:e.metadata,expectedSourceFingerprint:e.expectedSourceFingerprint,clientRevision:e.clientRevision})})},async getDbtFirstModeling(){return k("/api/modeling/dbt-first")},async getDbtModelingNode(e){return k(`/api/modeling/dbt-first/nodes/${encodeURIComponent(e)}`)},async getDbtModelingNodes(e){return k("/api/modeling/dbt-first/nodes/batch",{method:"POST",body:JSON.stringify({uniqueIds:e})})},async getDbtModelInventory(e={}){const t=new URLSearchParams;return e.q&&t.set("q",e.q),e.domain&&t.set("domain",e.domain),e.cursor!==void 0&&t.set("cursor",String(e.cursor)),e.limit!==void 0&&t.set("limit",String(e.limit)),e.physicalOnly&&t.set("physicalOnly","true"),k(`/api/modeling/dbt-first/inventory?${t.toString()}`)},async getDomainWorkspaces(){return k("/api/domain-workspaces")},async getRelatedDomainProducts(e){return k(`/api/domain-workspaces/${encodeURIComponent(e)}/related-products`)},async getAllRelatedDomainProducts(){return k("/api/domain-workspaces/related-products")},async getDomainKnowledge(e){return k(`/api/domain-workspaces/${encodeURIComponent(e)}/knowledge`)},async createContextProposal(e){return(await k("/api/context-proposals",{method:"POST",body:JSON.stringify(e)})).proposal},async getContextProposal(e){return(await k(`/api/context-proposals/${encodeURIComponent(e)}`)).proposal},async repreviewContextProposal(e,t,n){return(await k(`/api/context-proposals/${encodeURIComponent(e)}/repreview`,{method:"POST",body:JSON.stringify({selectedOperationIds:t,rebase:(n==null?void 0:n.rebase)===!0})})).proposal},async commitContextProposal(e,t,n){return k(`/api/context-proposals/${encodeURIComponent(e)}/commit`,{method:"POST",body:JSON.stringify({expectedProposalHash:t,idempotencyKey:n})})},async createModelingImport(e){return(await k("/api/modeling/dbt-first/imports",{method:"POST",body:JSON.stringify({source:e})})).session},async previewModelingImport(e,t){return k(`/api/modeling/dbt-first/imports/${encodeURIComponent(e)}/preview`,{method:"POST",body:JSON.stringify(t)})},async previewModelingChange(e,t){return k("/api/modeling/dbt-first/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyModelingChange(e,t,n){return k("/api/modeling/dbt-first/apply",{method:"POST",body:JSON.stringify({change:e,fingerprint:t,expectedSnapshotId:n})})},async validateModelingRelationship(e,t){return(await k("/api/modeling/dbt-first/relationships/validate",{method:"POST",body:JSON.stringify({relationship:e,expectedSnapshotId:t})})).evidence},async previewDbtSourcePatch(e,t){return k("/api/modeling/dbt-first/dbt-source/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyDbtSourcePatch(e,t,n){return k("/api/modeling/dbt-first/dbt-source/apply",{method:"POST",body:JSON.stringify({change:e,expectedFingerprint:t,expectedSnapshotId:n})})},async getSettingsEnvStatus(){try{return await k("/api/settings/env-status")}catch{return{groups:[]}}},async getProposeReadiness(e){try{return await k("/api/propose",{method:"POST",body:JSON.stringify(e??{})})}catch{return{ready:!1,reason:"Unable to reach the propose engine. Is the local DQL server running?",summary:{modelsScanned:0,businessModels:0,plumbingExcluded:0,metricsFound:0,proposalsRanked:0,draftsExisting:0,readyForReview:0,blockingTotal:0,warningTotal:0},plan:mw,proposals:[]}}},async generateProposeDrafts(e){try{return await k("/api/propose/generate",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ready:!1,reason:t instanceof Error?t.message:"Unable to reach the propose engine.",draftsWritten:0,draftsSkipped:0,proposals:[]}}},async proposePreview(e){return k(`/api/propose/preview?slug=${encodeURIComponent(e)}`)},async aiBuild(e){return k("/api/ai/build",{method:"POST",body:JSON.stringify(e)})},async createAgentRun(e){return(await k("/api/agent-runs",{method:"POST",body:JSON.stringify(e)})).run},async createAgentRunStream(e,t,n){let r;try{r=await fetch(`${Qr}/api/agent-runs?stream=1`,{method:"POST",headers:lr({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:n})}catch(o){if(n!=null&&n.aborted)throw o;const i=o instanceof Error&&o.message?` ${o.message}`:"";throw new Error(`Unable to reach the local DQL notebook server. Check that it is still running, then retry.${i}`)}if(!r.ok){const o=await r.text().catch(()=>"");throw Ui(r,o)}return gw(r,t)},async listAgentRuns(e){const t=new URLSearchParams;typeof(e==null?void 0:e.limit)=="number"&&Number.isFinite(e.limit)&&t.set("limit",String(e.limit));const n=t.toString()?`?${t.toString()}`:"";return k(`/api/agent-runs${n}`)},async getAgentRun(e){const t=await this.getAgentRunState(e);if(t.lifecycleState!=="terminal")throw new Error(`Agent run ${e} is still ${t.lifecycleState}.`);return t.run},async getAgentRunState(e){return k(`/api/agent-runs/${encodeURIComponent(e)}`)},async deriveAnalyticalRepair(e,t){return k(`/api/agent-runs/${encodeURIComponent(e)}/analytical-repair`,{method:"POST",body:JSON.stringify({repair:t})})},async repairAgentRunExecution(e,t){return k(`/api/agent-runs/${encodeURIComponent(e)}/repair-execution`,{method:"POST",body:JSON.stringify({threadId:t})})},async repairNotebookCellExecution(e,t,n){var o,i,a,c,l,u;const r=await k("/api/notebook/repair-execution",{method:"POST",body:JSON.stringify({cell:{id:e.id,type:e.type,source:e.content,title:e.name,config:e.chartConfig},error:t,failure:(o=e.execution)==null?void 0:o.error,attemptedSql:((i=e.execution)==null?void 0:i.compiledSql)??e.content,executionTarget:e.executionTarget,parameters:((a=e.blockBinding)==null?void 0:a.state)==="bound"?e.blockBinding.parameterValues:e.dqlParameterValues,executionContext:n})});if(n!=null&&n.runId&&typeof((c=r==null?void 0:r.executionContext)==null?void 0:c.runId)=="string"&&r.executionContext.runId!==n.runId)throw new St({message:"The notebook server returned a repair for a different cell run. The stale result was rejected.",status:409,code:"STALE_CELL_EXECUTION",details:{expected:n,received:r.executionContext}});return{ok:!0,source:String(r.source??e.content),repairedSql:String(r.repairedSql??""),repairMode:r.repairMode==="ai"?"ai":"deterministic",result:an(r.result),executionTarget:((l=r==null?void 0:r.executionTarget)==null?void 0:l.target)==="local"?{target:"local"}:((u=r==null?void 0:r.executionTarget)==null?void 0:u.target)==="connection"?{target:"connection",...typeof r.executionTarget.connectionName=="string"?{connectionName:r.executionTarget.connectionName}:{}}:void 0,compiledSql:typeof(r==null?void 0:r.compiledSql)=="string"?r.compiledSql:void 0,executedSql:typeof(r==null?void 0:r.executedSql)=="string"?r.executedSql:void 0,executionReceipt:r!=null&&r.executionReceipt&&typeof r.executionReceipt=="object"?r.executionReceipt:void 0}},async cancelAgentRun(e){return k(`/api/agent-runs/${encodeURIComponent(e)}/cancel`,{method:"POST"})},async listAgentThreads(e){const t=new URLSearchParams;typeof(e==null?void 0:e.limit)=="number"&&Number.isFinite(e.limit)&&t.set("limit",String(e.limit)),e!=null&&e.archived&&t.set("archived","1");const n=t.toString()?`?${t.toString()}`:"";return k(`/api/agent/threads${n}`)},async createAgentThread(e={}){return(await k("/api/agent/threads",{method:"POST",body:JSON.stringify(e)})).thread},async getAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}`)},async updateAgentThread(e,t){return k(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async archiveAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}/archive`,{method:"POST"})},async deleteAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"DELETE"})},async requestCertification(e){return k("/api/agent-runs/request-certification",{method:"POST",body:JSON.stringify(e)})},async getIdentity(){return k("/api/identity")},async getProviderSettings(){try{return await k("/api/settings/providers")}catch{return{providers:[]}}},async getProviderCliStatus(){try{return await k("/api/settings/providers/cli-status")}catch{return{status:{}}}},async saveProviderSettings(e){return k("/api/settings/providers",{method:"POST",body:JSON.stringify(e)})},async startOAuth(e){return k(`/api/auth/${e}/start`,{method:"POST"})},async getOAuthStatus(e){return k(`/api/auth/${e}/status`)},async signOutOAuth(e){return k(`/api/auth/${e}/signout`,{method:"POST"})},async testProviderSettings(e,t){try{return await k("/api/settings/providers/test",{method:"POST",body:JSON.stringify({id:e,...t})})}catch(n){return{ok:!1,message:n instanceof Error?n.message:String(n)}}},async getRemoteMcpSettings(){try{return await k("/api/settings/mcp")}catch{return{settings:{path:"",entries:[],warnings:[]}}}},async saveRemoteMcpSettings(e){return k("/api/settings/mcp",{method:"POST",body:JSON.stringify({entries:e})})},async recordAgentCorrection(e){return k("/api/agent/learnings/correction",{method:"POST",body:JSON.stringify(e)})},async listAgentHints(e){const t=e?`?status=${encodeURIComponent(e)}`:"";return k(`/api/agent/hints${t}`)},async reviewAgentHint(e,t,n){return k(`/api/agent/hints/${encodeURIComponent(e)}/review`,{method:"POST",body:JSON.stringify({decision:t,...n?{note:n}:{}})})},async updateAgentHint(e,t){return k(`/api/agent/hints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async transitionAgentHint(e,t){return k(`/api/agent/hints/${encodeURIComponent(e)}/lifecycle`,{method:"POST",body:JSON.stringify(t)})},async listAgentMemory(e){const t=e?`?scope=${encodeURIComponent(e)}`:"";try{return await k(`/api/agent/memory${t}`)}catch{return{memories:[]}}},async saveAgentMemory(e){return k("/api/agent/memory",{method:"POST",body:JSON.stringify(e)})},async deleteAgentMemory(e){return k(`/api/agent/memory?id=${encodeURIComponent(e)}`,{method:"DELETE"})},async ensureAgentMemoryFiles(){return k("/api/agent/memory/default-files",{method:"POST"})},async listNotebooks(){try{return await k("/api/notebooks")}catch{return[]}},async readNotebook(e){return k(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async deleteNotebook(e){return k(`/api/notebooks?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async createNotebook(e,t,n={}){return k("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t,...n})})},async createBlock(e,t){return k("/api/blocks",{method:"POST",body:JSON.stringify({name:e,...t})})},async getBlockLibrary(){try{return await k("/api/blocks/library")}catch{return{blocks:[]}}},async getApps(){try{return await k("/api/apps")}catch{return{apps:[]}}},async updateBlockStatus(e,t){return k("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await k(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return k("/api/blocks/run-tests",{method:"POST",body:JSON.stringify({source:e,path:t})})},async getBlockStudioCatalog(e={}){const t=new URLSearchParams;e.includeSemantic===!1&&t.set("includeSemantic","false");const n=t.toString();return k(`/api/block-studio/catalog${n?`?${n}`:""}`)},async getBlockStudioDbtStatus(){return k("/api/block-studio/dbt-status")},async openBlockStudio(e){return k(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async getBlockBody(e){return k(`/api/blocks/body?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t,n){return k("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t}),signal:n})},async runBlockStudio(e,t,n){return k("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t,parameters:n})})},async repairAndRunBlockStudio(e,t,n={},r){const o=await k("/api/block-studio/repair-and-run",{method:"POST",body:JSON.stringify({cell:{id:"block-studio-draft",type:"dql",source:e,title:r||"Block Studio draft"},error:t,attemptedSql:e,parameters:n})}),i=String(o.repairedSql??"");return{source:String(o.source??e),repairedSql:i,repairMode:o.repairMode==="ai"?"ai":"deterministic",preview:{sql:i,result:an(o.result)}}},async getCertifiedBlockParameters(e){return k(`/api/blocks/parameters?name=${encodeURIComponent(e)}`)},async invokeCertifiedBlock(e,t,n){var o,i,a,c,l,u;const r=await k("/api/blocks/invoke",{method:"POST",body:JSON.stringify({blockName:e,parameters:t,question:n})});return{parameters:Array.isArray(r==null?void 0:r.parameters)?r.parameters:[],result:{...an(r==null?void 0:r.result),...typeof((o=r==null?void 0:r.result)==null?void 0:o.sql)=="string"?{sql:r.result.sql}:{},...typeof((i=r==null?void 0:r.result)==null?void 0:i.blockName)=="string"?{blockName:r.result.blockName}:{},...typeof((a=r==null?void 0:r.result)==null?void 0:a.blockPath)=="string"?{blockPath:r.result.blockPath}:{},...(c=r==null?void 0:r.result)!=null&&c.chartConfig?{chartConfig:r.result.chartConfig}:{},...Array.isArray((l=r==null?void 0:r.result)==null?void 0:l.parameters)?{parameters:r.result.parameters}:{},...typeof((u=r==null?void 0:r.result)==null?void 0:u.auditId)=="string"?{auditId:r.result.auditId}:{}}}},async addDqlArtifactResultFilter(e,t,n,r,o){const i=await k("/api/dql/artifacts/add-filter",{method:"POST",body:JSON.stringify({artifact:e,resultColumns:t,column:n,value:r,executionTarget:o})}),a=zi(i==null?void 0:i.artifact);if(!a)throw new Error("Adding the filter input returned an invalid artifact contract.");return{artifact:a,parameterName:String((i==null?void 0:i.parameterName)??n)}},async invokeDqlArtifact(e,t,n,r,o){var c,l,u,h,d,f;const i=await k("/api/dql/artifacts/execute",{method:"POST",body:JSON.stringify({artifact:e,parameters:t,question:n,blockName:r,executionTarget:o})}),a=zi(i==null?void 0:i.artifact);if(!a)throw new Error("DQL artifact execution returned an invalid artifact contract.");return{artifact:a,parameters:a.parameters??[],result:{...an(i==null?void 0:i.result),...typeof((c=i==null?void 0:i.result)==null?void 0:c.sql)=="string"?{sql:i.result.sql}:{},...typeof((l=i==null?void 0:i.result)==null?void 0:l.blockName)=="string"?{blockName:i.result.blockName}:{},...typeof((u=i==null?void 0:i.result)==null?void 0:u.blockPath)=="string"?{blockPath:i.result.blockPath}:{},...(h=i==null?void 0:i.result)!=null&&h.chartConfig?{chartConfig:i.result.chartConfig}:{},...Array.isArray((d=i==null?void 0:i.result)==null?void 0:d.parameters)?{parameters:i.result.parameters}:{},...typeof((f=i==null?void 0:i.result)==null?void 0:f.auditId)=="string"?{auditId:i.result.auditId}:{}}}},async composeSemanticBlock(e){return k("/api/block-studio/compose-semantic",{method:"POST",body:JSON.stringify({question:e})})},async saveBlockStudio(e){return k("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async saveAgentBlockDraft(e){return k("/api/block-studio/agent-drafts",{method:"POST",body:JSON.stringify(e)})},async deleteBlockStudio(e){return k(`/api/block-studio/block?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async previewBlockStudioImport(e){return k("/api/block-studio/import/preview",{method:"POST",body:JSON.stringify(e)})},async listBlockStudioImports(){return k("/api/block-studio/imports")},async createBlockStudioImport(e){return k("/api/block-studio/imports",{method:"POST",body:JSON.stringify(e)})},async createDqlGenerationSession(e){return k("/api/block-studio/ai-imports",{method:"POST",body:JSON.stringify(e)})},async getDqlGenerationSession(e){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}`)},async getBlockStudioImport(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}`)},async deleteBlockStudioImport(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}`,{method:"DELETE"})},async clearBlockStudioImports(){return k("/api/block-studio/imports",{method:"DELETE"})},async updateBlockStudioImportCandidate(e,t,n){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async updateDqlGenerationCandidate(e,t,n){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async matchSqlForBlockReuse(e,t){return k("/api/block-studio/match-sql",{method:"POST",body:JSON.stringify({sql:e,...t??{}})})},async previewDqlGenerationCandidate(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/preview`,{method:"POST"})},async certifyDqlGenerationCandidate(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/certify`,{method:"POST"})},async saveSelectedDqlGenerationCandidates(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify(t)})},async runBlockStudioImportCandidate(e,t){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/run`,{method:"POST"})},async saveBlockStudioImportCandidate(e,t){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/save`,{method:"POST"})},async saveAllBlockStudioImportCandidates(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/save-all`,{method:"POST"})},async assistBlockStudioImportCandidate(e,t,n){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/ai-assist`,{method:"POST",body:JSON.stringify({action:n})})},async getSemanticLayerDiagnostics(){return k("/api/semantic-layer/diagnostics")},async reloadSemanticLayer(){return k("/api/semantic-layer/reload",{method:"POST"})},async assessBlockStudioCertification(e){return k("/api/block-studio/certification-check",{method:"POST",body:JSON.stringify({source:e})})},async certifyBlockStudio(e){const t=await fetch(`${Qr}/api/block-studio/certify`,{headers:lr({"Content-Type":"application/json"}),method:"POST",body:JSON.stringify(e)}),n=await t.json().catch(()=>({ok:!1,error:t.statusText}));if(!t.ok&&t.status!==422)throw new Error(JSON.stringify(n));return n},async saveAsBlock(e){return k("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await k("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await k("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return k("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t,n,r){var i,a,c;const o=await k("/api/query",{method:"POST",body:JSON.stringify({sql:e,executionContext:n,executionTarget:r}),signal:t});if(n!=null&&n.runId&&typeof((i=o==null?void 0:o.executionContext)==null?void 0:i.runId)=="string"&&o.executionContext.runId!==n.runId)throw new St({message:"The notebook server returned a result for a different cell run. The stale result was rejected.",status:409,code:"STALE_CELL_EXECUTION",details:{expected:n,received:o.executionContext}});return{...an(o),executionTarget:((a=o==null?void 0:o.executionTarget)==null?void 0:a.target)==="local"?{target:"local"}:((c=o==null?void 0:o.executionTarget)==null?void 0:c.target)==="connection"?{target:"connection",...typeof o.executionTarget.connectionName=="string"?{connectionName:o.executionTarget.connectionName}:{}}:void 0,compiledSql:typeof(o==null?void 0:o.compiledSql)=="string"?o.compiledSql:void 0,executedSql:typeof(o==null?void 0:o.executedSql)=="string"?o.executedSql:void 0,targetBinding:o!=null&&o.targetBinding&&typeof o.targetBinding=="object"?o.targetBinding:void 0,executionReceipt:o!=null&&o.executionReceipt&&typeof o.executionReceipt=="object"?o.executionReceipt:void 0}},async previewGeneratedSql(e,t){try{const n=await k("/api/ai/sql-draft/preview",{method:"POST",body:JSON.stringify({sql:e}),signal:t});return{ok:!0,result:an(n.result)}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async executeNotebookCell(e,t,n){var o,i,a,c,l,u;const r=await k("/api/notebook/execute",{method:"POST",body:JSON.stringify({cell:{id:e.id,type:e.type,source:e.content,title:e.name,config:e.chartConfig},executionTarget:e.executionTarget,parameters:((o=e.blockBinding)==null?void 0:o.state)==="bound"?e.blockBinding.parameterValues:e.dqlParameterValues,executionContext:n}),signal:t});if(n!=null&&n.runId&&typeof((i=r==null?void 0:r.executionContext)==null?void 0:i.runId)=="string"&&r.executionContext.runId!==n.runId)throw new St({message:"The notebook server returned a result for a different semantic cell run. The stale result was rejected.",status:409,code:"STALE_CELL_EXECUTION",details:{expected:n,received:r.executionContext}});return{cellType:String((r==null?void 0:r.cellType)??e.type),cellId:typeof((a=r==null?void 0:r.executionContext)==null?void 0:a.cellId)=="string"?r.executionContext.cellId:void 0,runId:typeof((c=r==null?void 0:r.executionContext)==null?void 0:c.runId)=="string"?r.executionContext.runId:void 0,title:typeof(r==null?void 0:r.title)=="string"?r.title:void 0,blockName:typeof(r==null?void 0:r.blockName)=="string"?r.blockName:void 0,blockPath:typeof(r==null?void 0:r.blockPath)=="string"?r.blockPath:void 0,chartConfig:r!=null&&r.chartConfig&&typeof r.chartConfig=="object"?r.chartConfig:void 0,tests:Array.isArray(r==null?void 0:r.tests)?r.tests:void 0,result:r!=null&&r.result?an(r.result):null,executionTarget:((l=r==null?void 0:r.executionTarget)==null?void 0:l.target)==="local"?{target:"local"}:((u=r==null?void 0:r.executionTarget)==null?void 0:u.target)==="connection"?{target:"connection",...typeof r.executionTarget.connectionName=="string"?{connectionName:r.executionTarget.connectionName}:{}}:void 0,engine:(r==null?void 0:r.engine)==="native"||(r==null?void 0:r.engine)==="metricflow-cli"||(r==null?void 0:r.engine)==="dbt-cloud"?r.engine:void 0,semanticTrace:r!=null&&r.semanticTrace&&typeof r.semanticTrace=="object"?r.semanticTrace:void 0,compiledSql:typeof(r==null?void 0:r.compiledSql)=="string"?r.compiledSql:void 0,executedSql:typeof(r==null?void 0:r.executedSql)=="string"?r.executedSql:void 0,targetBinding:r!=null&&r.targetBinding&&typeof r.targetBinding=="object"?r.targetBinding:void 0,executionReceipt:r!=null&&r.executionReceipt&&typeof r.executionReceipt=="object"?r.executionReceipt:void 0}},async getDatasets(){return k("/api/datasets")},async importDataset(e){if(e.file){const t=new FormData;t.set("file",e.file,e.file.name);for(const[r,o]of Object.entries(e))r==="file"||o===void 0||t.set(r,Array.isArray(o)?o.join(","):String(o));const n=await fetch(`${Qr}/api/datasets/import`,{method:"POST",headers:lr(),body:t});if(!n.ok){const r=await n.text().catch(()=>"");throw Ui(n,r)}return n.json()}return k("/api/datasets/import",{method:"POST",body:JSON.stringify(e)})},async refreshDataset(e){return k(`/api/datasets/${encodeURIComponent(e)}/refresh`,{method:"POST"})},async updateDatasetSchema(e,t){return k(`/api/datasets/${encodeURIComponent(e)}/schema`,{method:"POST",body:JSON.stringify({overrides:t})})},async renameDataset(e,t,n){return k(`/api/datasets/${encodeURIComponent(e)}/rename`,{method:"POST",body:JSON.stringify({name:t,alias:n})})},async pinDataset(e,t=!0){return k(`/api/datasets/${encodeURIComponent(e)}/pin`,{method:"POST",body:JSON.stringify({pinned:t})})},async removeDataset(e){await k(`/api/datasets/${encodeURIComponent(e)}`,{method:"DELETE"})},async stageDataset(e){return k("/api/datasets/stage",{method:"POST",body:JSON.stringify(e)})},async listNotebookResearch(e){var o,i,a,c,l,u,h,d,f,m,S,v,b,w,j,C,x,E,P,A;const t=new URLSearchParams;typeof e=="string"?e&&t.set("path",e):e&&(e.path&&t.set("path",e.path),e.sourceCellId&&t.set("sourceCellId",e.sourceCellId),e.domain&&t.set("domain",e.domain),e.owner&&t.set("owner",e.owner),e.intent&&t.set("intent",e.intent),e.search&&t.set("q",e.search),e.status&&t.set("status",e.status),e.reviewStatus&&t.set("reviewStatus",e.reviewStatus),e.promotionAction&&t.set("promotionAction",e.promotionAction),e.readiness&&t.set("readiness",e.readiness),e.age&&t.set("age",e.age),e.nextAction&&t.set("nextAction",e.nextAction),e.activeOnly&&t.set("activeOnly","true"),e.sort&&t.set("sort",e.sort),typeof e.limit=="number"&&t.set("limit",String(e.limit)),typeof e.offset=="number"&&t.set("offset",String(e.offset)));const n=t.toString()?`?${t.toString()}`:"",r=await k(`/api/notebook/research${n}`);return{runs:r.runs.map(Vt),total:typeof r.total=="number"?r.total:r.runs.length,domains:Array.isArray(r.domains)?r.domains.map(g=>({domain:typeof g.domain=="string"&&g.domain.trim()?g.domain:"uncategorized",total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],owners:Array.isArray(r.owners)?r.owners.map(g=>({owner:typeof g.owner=="string"&&g.owner.trim()?g.owner:"unassigned",total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],intents:Array.isArray(r.intents)?r.intents.map(g=>({intent:Sw(g.intent),total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],notebooks:Array.isArray(r.notebooks)?r.notebooks.map(g=>({path:typeof g.path=="string"&&g.path.trim()?g.path:"notebooks/untitled.dqlnb",title:typeof g.title=="string"&&g.title.trim()?g.title:ww(g.path),total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],counts:{total:typeof((o=r.counts)==null?void 0:o.total)=="number"?r.counts.total:r.runs.length,ready:typeof((i=r.counts)==null?void 0:i.ready)=="number"?r.counts.ready:0,needsReview:typeof((a=r.counts)==null?void 0:a.needsReview)=="number"?r.counts.needsReview:0,dqlDrafts:typeof((c=r.counts)==null?void 0:c.dqlDrafts)=="number"?r.counts.dqlDrafts:0,errors:typeof((l=r.counts)==null?void 0:l.errors)=="number"?r.counts.errors:0,reuseExisting:typeof((u=r.counts)==null?void 0:u.reuseExisting)=="number"?r.counts.reuseExisting:0,extendExisting:typeof((h=r.counts)==null?void 0:h.extendExisting)=="number"?r.counts.extendExisting:0,replacements:typeof((d=r.counts)==null?void 0:d.replacements)=="number"?r.counts.replacements:0,createNew:typeof((f=r.counts)==null?void 0:f.createNew)=="number"?r.counts.createNew:0,draftReady:typeof((m=r.counts)==null?void 0:m.draftReady)=="number"?r.counts.draftReady:0,certificationReady:typeof((S=r.counts)==null?void 0:S.certificationReady)=="number"?r.counts.certificationReady:0,blocked:typeof((v=r.counts)==null?void 0:v.blocked)=="number"?r.counts.blocked:0,staleOpen:typeof((b=r.counts)==null?void 0:b.staleOpen)=="number"?r.counts.staleOpen:0,expiredOpen:typeof((w=r.counts)==null?void 0:w.expiredOpen)=="number"?r.counts.expiredOpen:0,sourceLinked:typeof((j=r.counts)==null?void 0:j.sourceLinked)=="number"?r.counts.sourceLinked:0,nextActions:kw((C=r.counts)==null?void 0:C.nextActions)},groupCounts:{domains:typeof((x=r.groupCounts)==null?void 0:x.domains)=="number"&&Number.isFinite(r.groupCounts.domains)?Math.max(0,Math.floor(r.groupCounts.domains)):Array.isArray(r.domains)?r.domains.length:0,owners:typeof((E=r.groupCounts)==null?void 0:E.owners)=="number"&&Number.isFinite(r.groupCounts.owners)?Math.max(0,Math.floor(r.groupCounts.owners)):Array.isArray(r.owners)?r.owners.length:0,intents:typeof((P=r.groupCounts)==null?void 0:P.intents)=="number"&&Number.isFinite(r.groupCounts.intents)?Math.max(0,Math.floor(r.groupCounts.intents)):Array.isArray(r.intents)?r.intents.length:0,notebooks:typeof((A=r.groupCounts)==null?void 0:A.notebooks)=="number"&&Number.isFinite(r.groupCounts.notebooks)?Math.max(0,Math.floor(r.groupCounts.notebooks)):Array.isArray(r.notebooks)?r.notebooks.length:0},reviewMetrics:xw(r.reviewMetrics),limit:r.limit,offset:typeof r.offset=="number"?r.offset:0}},async getNotebookResearchDiagnostics(){const e=await k("/api/notebook/research/diagnostics");return vw(e)},async createNotebookResearch(e){const t=await k("/api/notebook/research",{method:"POST",body:JSON.stringify(e)});return Vt(t.run)},async seedNotebookResearchFromCells(e){const t=await k("/api/notebook/research/seed-cells",{method:"POST",body:JSON.stringify(e)});return{created:Array.isArray(t.created)?t.created.map(Vt):[],createdCount:typeof t.createdCount=="number"?t.createdCount:Array.isArray(t.created)?t.created.length:0,skippedCount:typeof t.skippedCount=="number"?t.skippedCount:0,limitApplied:t.limitApplied===!0}},async listNotebookResearchSourceCoverage(e){const t=await k("/api/notebook/research/source-coverage",{method:"POST",body:JSON.stringify({path:e.path,sourceCellIds:e.sourceCellIds,sourceCells:e.sourceCells,limit:e.limit})});return{runs:Array.isArray(t.runs)?t.runs.map(Vt):[],requestedCount:typeof t.requestedCount=="number"?t.requestedCount:e.sourceCellIds.length,matchedCount:typeof t.matchedCount=="number"?t.matchedCount:Array.isArray(t.runs)?t.runs.length:0,limitApplied:t.limitApplied===!0}},async previewNotebookResearchContext(e){const t=await k("/api/notebook/research/context-preview",{method:"POST",body:JSON.stringify(e)});return jw(t)},async getNotebookResearch(e){const t=await k(`/api/notebook/research/${encodeURIComponent(e)}`);return Vt(t.run)},async updateNotebookResearch(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)});return Vt(n.run)},async runNotebookResearch(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t??{})});return Vt(n.run)},async checkNotebookResearchReuse(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/reuse-check`,{method:"POST",body:JSON.stringify(t??{})});return{...n,run:Vt(n.run),promotion:Tp(n.promotion)??n.promotion}},async promoteNotebookResearchToDql(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/promote-dql`,{method:"POST",body:JSON.stringify(t??{})});return{...n,run:Vt(n.run)}},async getSchema(){try{const e=await fetch(`${Qr}/api/schema`,{headers:lr()});if(e.ok)return await e.json();const t=await e.json().catch(()=>null);return t!=null&&t.error&&console.warn(`[dql] schema introspection failed: ${t.error}`),(t==null?void 0:t.fallback)??[]}catch(e){return console.warn("[dql] getSchema request failed",e),[]}},async getConnections(){try{return await k("/api/connections")}catch{return{default:"unknown",connections:{}}}},async previewDbtProfiles(e){return k("/api/connections/dbt-profiles/preview",{method:"POST",body:JSON.stringify({path:e})})},async saveConnections(e,t){return k("/api/connections",{method:"PUT",body:JSON.stringify({connections:e,defaultConnectionName:t})})},async previewConnectionMetadataScope(e,t={}){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope/preview`,{method:"POST",body:JSON.stringify(t)})},async discoverConnectionMetadataScopes(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope/discovery`,{method:"POST"})},async getConnectionMetadataScope(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope`)},async applyConnectionMetadataScope(e,t){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope`,{method:"PUT",body:JSON.stringify(t)})},async refreshConnectionMetadata(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-sync`,{method:"POST"})},async installConnector(e){return k("/api/connectors/install",{method:"POST",body:JSON.stringify({driver:e})})},async testConnection(){try{return await k("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticRuntimeSettings(){return k("/api/semantic-runtime")},async getMetricFlowInstallerStatus(){return k("/api/semantic-runtime/metricflow/installer")},async installMetricFlow(e){return k("/api/semantic-runtime/metricflow/install",{method:"POST",body:JSON.stringify(e?{adapter:e}:{})})},async testDbtCloudSemanticRuntime(e){try{return await k("/api/semantic-runtime/dbt-cloud/test",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:(t==null?void 0:t.message)??"dbt Cloud Semantic Layer test failed."}}},async applyDbtCloudSemanticRuntime(e){return k("/api/semantic-runtime/dbt-cloud/apply",{method:"POST",body:JSON.stringify(e)})},async setSemanticRuntimePreference(e){return k("/api/semantic-runtime/preference",{method:"POST",body:JSON.stringify({preference:e})})},async getSemanticLayer(){try{return await k("/api/semantic-layer")}catch{return{available:!1,provider:null,metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[],domains:[],tags:[],favorites:[],recentlyUsed:[],lastSyncTime:null}}},async getSemanticTree(){return(await k("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return k(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async getSetupLaunch(){return k("/api/onboarding/launch")},async acknowledgeSetupLaunch(){return k("/api/onboarding/acknowledge",{method:"POST",body:"{}"})},async getOnboardingStatus(){return k("/api/onboarding/status")},async previewDbtOnboarding(e){return k("/api/onboarding/dbt/preview",{method:"POST",body:JSON.stringify(e)})},async applyDbtOnboarding(e){return k("/api/onboarding/dbt/apply",{method:"POST",body:JSON.stringify({...e,fingerprint:e.expectedFingerprint})})},async refreshDbtOnboarding(e={}){return k("/api/onboarding/refresh",{method:"POST",body:JSON.stringify(e)})},async getOnboardingJob(e){return k(`/api/onboarding/jobs/${encodeURIComponent(e)}`)},async cancelOnboardingJob(e){return k(`/api/onboarding/jobs/${encodeURIComponent(e)}`,{method:"DELETE"})},async discoverOnboardingDomains(e={}){return k("/api/onboarding/domains/discover",{method:"POST",body:JSON.stringify(e)})},async applyOnboardingDomains(e){return k("/api/onboarding/domains/apply",{method:"POST",body:JSON.stringify(e)})},async importSemanticLayer(e){return k("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return k("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return k("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return k("/api/semantic-layer/sync-preview",{method:"POST",body:JSON.stringify({})})},async searchSemanticLayer(e){const t=new URLSearchParams;e.query&&t.set("q",e.query),e.domain&&t.set("domain",e.domain),e.tag&&t.set("tag",e.tag),e.type&&t.set("type",e.type);try{return await k(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[]}}},async getFavorites(){try{return(await k("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await k("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await k("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await k("/api/user-prefs/recent",{method:"POST",body:JSON.stringify({name:e})})).recentlyUsed}catch{return[]}},async getCompatibleDimensions(e){const t=new URLSearchParams;e.length>0&&t.set("metrics",e.join(","));try{return(await k(`/api/semantic-layer/compatible-dims?${t.toString()}`)).dimensions}catch{return[]}},async getCompatibility(e){const t=new URLSearchParams;e.length>0&&t.set("metrics",e.join(","));const n=await k(`/api/semantic-layer/compatible-dims?${t.toString()}`);return{dimensions:n.dimensions??[],engine:n.engine??"native",incompatible:n.incompatible??[],degraded:n.degraded??null}},async composeQuery(e,t,n){try{return await k("/api/semantic-query",{method:"POST",body:JSON.stringify({metrics:e,dimensions:t,timeDimension:n})})}catch(r){return{error:r.message??"Failed to compose query"}}},async previewSemanticBuilder(e){try{return await k("/api/semantic-builder/preview",{method:"POST",body:JSON.stringify(e)})}catch(t){return t instanceof St?{error:t.message,code:t.code,details:t.details}:{error:t instanceof Error?t.message:"Failed to preview semantic block"}}},async saveSemanticBuilder(e){return k("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await k("/api/semantic-layer/metric",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t.message??"Failed to create metric"}}},async describeTable(e){const t=new URLSearchParams({relation:e});try{return await k(`/api/describe-table?${t.toString()}`)}catch{return[]}},async fetchLineage(){try{return await k("/api/lineage")}catch{return{nodes:[],edges:[]}}},async searchLineage(e){try{return await k(`/api/lineage/search?q=${encodeURIComponent(e)}`)}catch{return{matches:[]}}},async queryLineage(e){var n;const t=new URLSearchParams;e.focus&&t.set("focus",e.focus),e.search&&t.set("search",e.search),(n=e.types)!=null&&n.length&&t.set("types",e.types.join(",")),e.domain&&t.set("domain",e.domain),e.upstreamDepth!==void 0&&t.set("upstreamDepth",String(e.upstreamDepth)),e.downstreamDepth!==void 0&&t.set("downstreamDepth",String(e.downstreamDepth));try{return await k(`/api/lineage/query?${t.toString()}`)}catch{return{graph:{nodes:[],edges:[]},matches:[]}}},async fetchLineageNode(e){try{return await k(`/api/lineage/node/${encodeURIComponent(e)}`)}catch{return null}},async fetchBusiness360(e){try{return await k(`/api/lineage/business-360/${encodeURIComponent(e)}`)}catch{return null}},async fetchBlockLineage(e){try{return await k(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await k(`/api/lineage/impact/${encodeURIComponent(e)}`)}catch{return null}},async fetchLineagePaths(e,t){try{const n=new URLSearchParams;t!=null&&t.maxDepth&&n.set("maxDepth",String(t.maxDepth)),t!=null&&t.maxPaths&&n.set("maxPaths",String(t.maxPaths));const r=n.toString(),o=`/api/lineage/paths/${encodeURIComponent(e)}${r?`?${r}`:""}`;return await k(o)}catch{return null}},async fetchGitStatus(){try{return await k("/api/git/status")}catch{return{inRepo:!1,branch:null,ahead:0,behind:0,changes:[]}}},async fetchGitLog(e=20){try{return await k(`/api/git/log?limit=${e}`)}catch{return{inRepo:!1,commits:[]}}},async fetchRunSnapshot(e){try{return await k(`/api/run-snapshot?path=${encodeURIComponent(e)}`)}catch{return{found:!1,snapshot:null}}},async saveRunSnapshot(e,t){await k("/api/run-snapshot",{method:"PUT",body:JSON.stringify({path:e,snapshot:t})})},async fetchGitDiff(e,t){try{const n=new URLSearchParams;e&&n.set("path",e),t&&n.set("staged","true");const r=n.toString();return await k(`/api/git/diff${r?`?${r}`:""}`)}catch{return{inRepo:!1,diff:"",before:null,after:null,diffReport:null}}},async fetchGitBranches(){try{return await k("/api/git/branches")}catch{return{inRepo:!1,current:null,branches:[]}}},async fetchGitRemote(){try{return await k("/api/git/remote")}catch{return{inRepo:!1,url:null,name:null}}},async fetchGitGovernedContext(){try{return await k("/api/git/governed-context")}catch{return{inRepo:!1,trackingReady:!1,legacyBroadIgnore:!1,domains:Ko(),skills:Ko(),artifacts:Ko(),learning:Ko()}}},async enableGitGovernedContextTracking(){try{return await k("/api/git/governed-context/enable",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitStage(e){try{return await k("/api/git/stage",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitUnstage(e){try{return await k("/api/git/unstage",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitDiscard(e){try{return await k("/api/git/discard",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitCommit(e,t=!1){try{return await k("/api/git/commit",{method:"POST",body:JSON.stringify({message:e,stageAll:t})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async gitPush(){try{return await k("/api/git/push",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitPull(){try{return await k("/api/git/pull",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitCreateBranch(e,t=!0){try{return await k("/api/git/branch",{method:"POST",body:JSON.stringify({name:e,checkout:t})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async gitCreateReview(e){try{return await k("/api/git/review",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitOpenReview(e){try{return await k("/api/git/review/open",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitCheckout(e){try{return await k("/api/git/checkout",{method:"POST",body:JSON.stringify({name:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async listApps(){try{const{apps:e}=await k("/api/apps");return e}catch{return[]}},async listAppsStrict(){const{apps:e}=await k("/api/apps");return e},async recommendAppBlocks(e,t){const{blocks:n}=await k("/api/apps/recommend-blocks",{method:"POST",body:JSON.stringify(e),signal:t});return n},async listAppSourceCandidates(e,t={},n){var i;const r=new URLSearchParams;(i=t.query)!=null&&i.trim()&&r.set("q",t.query.trim()),t.cursor&&r.set("cursor",t.cursor),r.set("limit",String(t.limit??50));for(const a of t.lifecycles??[])r.append("lifecycle",a);for(const a of t.domains??[])r.append("domain",a);t.includeDeprecated&&r.set("includeDeprecated","true");const o=await k(`/api/app-builds/${encodeURIComponent(e)}/source-candidates?${r.toString()}`,{signal:n});return{...o,items:o.items.map(Yc)}},async resolveAppSourceCandidates(e,t){const n=await k(`/api/app-builds/${encodeURIComponent(e)}/source-candidates`,{method:"POST",body:JSON.stringify({sourceIds:t})});return{...n,items:n.items.map(Yc)}},async createApp(e){return k("/api/apps",{method:"POST",body:JSON.stringify(e)})},async createAppBuild(e){return k("/api/app-builds",{method:"POST",body:JSON.stringify(e)})},async listAppBuilds(){return k("/api/app-builds")},async proposeAppBuildChanges(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals`,{method:"POST",body:JSON.stringify(t)})},async reviseAppBuildProposal(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals/${encodeURIComponent(t)}/revisions`,{method:"POST",body:JSON.stringify(n)})},async generateAppBuildGap(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals/${encodeURIComponent(t)}/gaps`,{method:"POST",body:JSON.stringify(n)})},async patchAppBuild(e,t,n,r){return k(`/api/app-builds/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({expectedRevision:t,expectedProposalHash:r,operations:n})})},async composeAppBuild(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/compose`,{method:"POST",body:JSON.stringify(t)})},async addAskResultToAppBuild(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/ask-results`,{method:"POST",body:JSON.stringify(t)})},async preflightAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/preflight`,{method:"POST",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async publishAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/publish-to-project`,{method:"POST",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async deleteAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async commitAppBuild(e,t,n){return this.publishAppBuild(e,t,n)},async generateApp(e){try{return await k("/api/apps/generate",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async createAppAiBuild(e){try{return await k("/api/apps/ai-builds",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async getAppAiBuild(e){try{const{session:t}=await k(`/api/apps/ai-builds/${encodeURIComponent(e)}`);return t}catch{return null}},async proposeAppAiBuild(e){try{return await k("/api/apps/ai-builds/propose",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async proposeAppAiBuildInBackground(e){return k("/api/apps/ai-builds/propose-background",{method:"POST",body:JSON.stringify(e)})},async commitAppAiBuild(e,t={}){try{return await k(`/api/apps/ai-builds/${encodeURIComponent(e)}/commit`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async getApp(e){try{return await k(`/api/apps/${encodeURIComponent(e)}`)}catch{return null}},async deleteApp(e,t){return k(`/api/apps/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({expectedFingerprint:t})})},async restoreApp(e){return k(`/api/app-recoveries/${encodeURIComponent(e)}/restore`,{method:"POST",body:"{}"})},async renameApp(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async attachAppNotebook(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/notebooks`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAppNotebookCandidates(e){try{const{notebooks:t}=await k(`/api/apps/${encodeURIComponent(e)}/notebook-candidates`);return t}catch{return[]}},async createAppNotebook(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/notebooks/create`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async previewAppNotebook(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/notebooks/preview?path=${encodeURIComponent(t)}`)}catch{return null}},async runAppNotebook(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/notebooks/run`,{method:"POST",body:JSON.stringify({path:t})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAppConversations(e){try{const{conversations:t}=await k(`/api/apps/${encodeURIComponent(e)}/conversations`);return t}catch{return[]}},async createAppConversation(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/conversations`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async getAppConversation(e,t){try{const{conversation:n}=await k(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`);return n}catch{return null}},async updateAppConversation(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async deleteAppConversation(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`,{method:"DELETE"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAppInvestigations(e,t){try{const n=new URLSearchParams;t&&n.set("dashboardId",t);const r=n.toString(),{investigations:o}=await k(`/api/apps/${encodeURIComponent(e)}/investigations${r?`?${r}`:""}`);return o}catch{return[]}},async createAppInvestigation(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/investigations`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async getAppInvestigation(e,t){try{const{investigation:n}=await k(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}`);return n}catch{return null}},async runAppInvestigation(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n??{})})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async pinAppInvestigation(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}/pin`,{method:"POST",body:JSON.stringify(n??{})})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async getDashboard(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}`)}catch{return null}},async dashboardFilterOptions(e,t){try{const n=new URLSearchParams({block:e,column:t});return await k(`/api/dashboard/filter-options?${n.toString()}`)}catch{return null}},async getAppEditorCatalog(e,t){try{const n=new URLSearchParams;t!=null&&t.domain&&n.set("domain",t.domain),(t==null?void 0:t.certifiedOnly)===!1&&n.set("certifiedOnly","false");const r=n.toString();return await k(`/api/apps/${encodeURIComponent(e)}/editor/catalog${r?`?${r}`:""}`)}catch{return null}},async createAppDashboard(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async patchDashboardLayout(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/layout`,{method:"PATCH",body:JSON.stringify({layout:n})})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async askApp(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/ask`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async publishAppToProject(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/publish-to-project`,{method:"POST",body:JSON.stringify(t??{})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async promoteApp(e,t){return B.publishAppToProject(e,t)},async approveAppSemanticTiles(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/approve-semantic`,{method:"POST",body:JSON.stringify(n)})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async recommendVisualization(e){try{return await k("/api/visualizations/recommend",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async recommendDashboardTile(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/tiles/recommend`,{method:"POST",body:JSON.stringify(n)})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async createAiPin(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/ai-pins`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAiPins(e,t){try{const n=new URLSearchParams;t&&n.set("dashboardId",t);const r=n.toString(),{pins:o}=await k(`/api/apps/${encodeURIComponent(e)}/ai-pins${r?`?${r}`:""}`);return o}catch{return[]}},async refreshAiPin(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/ai-pins/${encodeURIComponent(t)}/refresh`,{method:"POST"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async promoteAiPin(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/ai-pins/${encodeURIComponent(t)}/promote`,{method:"POST"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async fetchScopedLineage(e){try{const t=new URLSearchParams;return e.domain&&t.set("domain",e.domain),e.appId&&t.set("appId",e.appId),e.dashboardId&&t.set("dashboardId",e.dashboardId),e.blockId&&t.set("blockId",e.blockId),await k(`/api/lineage/scope?${t.toString()}`)}catch{return null}},async runDashboard(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})}catch{return null}},async runAppBuildPreview(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})},async retryDashboardTile(e,t,n,r){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:r??{},tileId:n})})}catch{return null}},async getDashboardStory(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/story`,{method:"POST",body:JSON.stringify({runId:n})})}catch{return null}},async saveDashboard(e,t,n){try{return{ok:!!(await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(n)})).ok}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async getPersona(){try{const{persona:e}=await k("/api/persona");return e}catch{return null}},async setPersona(e,t){try{const{persona:n}=await k("/api/persona",{method:"POST",body:JSON.stringify({userId:e,appId:t})});return n}catch{return null}},async clearPersona(){try{await k("/api/persona",{method:"DELETE"})}catch{}},async getSkills(){return k("/api/skills")},async getSkillPathSettings(){return k("/api/skills/settings")},async updateSkillPath(e){return k("/api/skills/settings",{method:"PUT",body:JSON.stringify({path:e})})},async getSkillOptions(e=""){const t=e.trim()?`?q=${encodeURIComponent(e.trim())}`:"";return k(`/api/skills/options${t}`)},async createSkill(e){return k("/api/skills",{method:"POST",body:JSON.stringify({skill:e})})},async updateSkill(e,t){return k(`/api/skills/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({skill:t})})},async getEmbeddingSettings(){return k("/api/settings/embeddings")},async saveEmbeddingSettings(e){return k("/api/settings/embeddings",{method:"PUT",body:JSON.stringify(e)})},async listEmbeddingModels(e){const t=e?`?endpoint=${encodeURIComponent(e)}`:"";return k(`/api/settings/embeddings/models${t}`)},async installEmbeddingModel(e,t){return k("/api/settings/embeddings/install",{method:"POST",body:JSON.stringify({model:e,endpoint:t})})},async testEmbeddingProvider(){return k("/api/settings/embeddings/test",{method:"POST"})},async reindexEmbeddings(){return k("/api/settings/embeddings/reindex",{method:"POST"})},async deleteSkill(e){return k(`/api/skills/${encodeURIComponent(e)}`,{method:"DELETE"})},async getDomains(){try{return await k("/api/domains")}catch{return{domains:[]}}},async createDomain(e){return k("/api/domains",{method:"POST",body:JSON.stringify({domain:e})})},async updateDomain(e,t){return k(`/api/domains/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({domain:t})})},async deleteDomain(e){return k(`/api/domains/${encodeURIComponent(e)}`,{method:"DELETE"})},async startContextBootstrap(e={}){return k("/api/context-bootstrap",{method:"POST",body:JSON.stringify(e)})},async getContextBootstrap(e){return k(`/api/context-bootstrap/${encodeURIComponent(e)}`)},async getLatestContextBootstrap(){return(await k("/api/context-bootstrap/latest")).session??null},async saveContextBootstrapSelected(e,t){return k(`/api/context-bootstrap/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify({candidateIds:t})})}},Tw={source_table:"#8a8d96",dbt_model:"#4a74c9",dbt_source:"#4a74c9",term:"#0a6b5e",block:"#b26b1f",business_view:"#c14545",metric:"#6b5dd3",dimension:"#0a6b5e",domain:"#7c5cff",chart:"#c14590",notebook:"#2e8b57",dashboard:"#2e8b57",app:"#2e8b57"},Aw={source_table:"TBL",dbt_model:"DBT",dbt_source:"SRC",term:"TERM",block:"BLK",business_view:"VIEW",metric:"MET",dimension:"DIM",domain:"DOM",chart:"CHT",notebook:"NB",dashboard:"DASH",app:"APP"},Ap={source_table:"Source Table",dbt_model:"dbt Model",dbt_source:"dbt Source",term:"Business Term",block:"DQL Block",business_view:"Business View",metric:"Metric",dimension:"Dimension",domain:"Domain",chart:"Chart",notebook:"Notebook",dashboard:"Dashboard",app:"App"},Mj={reads_from:"#8b949e",feeds_into:"#56d364",defines:"#39c5cf",composes:"#f2cc60",aggregates:"#388bfd",visualizes:"#f778ba",depends_on:"#ff7b72",contains:"#d2a8ff",crosses_domain:"#d2a8ff",certified_by:"#56d364"},Lj={reads_from:"reads from",feeds_into:"feeds into",defines:"defines",composes:"composes into",aggregates:"aggregates into",visualizes:"visualizes",depends_on:"dbt depends on",contains:"contains",crosses_domain:"crosses domain",certified_by:"certified by"},Rw={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},Xc={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},Zc=["source","transform","answer","consumption"],Nj=["term","business_view","block","metric","dimension","domain","source_table","dbt_source","dbt_model","chart","notebook","dashboard","app"],Bj=["source_table","dbt_source","dbt_model"],Ow=["term","domain","business_view","metric","dimension","block"];[...Ow];function _w(e){if(e.layer)return e.layer;switch(e.type){case"source_table":case"dbt_source":return"source";case"dbt_model":return"transform";case"term":case"block":case"business_view":case"metric":case"dimension":case"domain":return"answer";case"chart":case"notebook":case"dashboard":case"app":return"consumption";default:return"answer"}}function Pw(){const{state:e,dispatch:t}=et(),n=e.inspectorContext;return s.jsxs("aside",{"aria-label":"Inspector",style:{width:320,borderLeft:`1px solid ${pe("borderSubtle")}`,background:pe("surfaceBase"),color:pe("textPrimary"),display:"flex",flexDirection:"column",overflow:"hidden",flexShrink:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${be[3]}px ${be[4]}px`,borderBottom:`1px solid ${pe("borderSubtle")}`},children:[s.jsx("div",{style:{fontSize:Ze.sm,fontWeight:Xi.semibold},children:n?Iw(n):"Inspector"}),s.jsx("button",{onClick:()=>t({type:"SET_INSPECTOR",open:!1}),"aria-label":"Close inspector",style:{background:"transparent",border:"none",color:pe("textMuted"),cursor:"pointer",fontSize:Ze.md,padding:2,borderRadius:wn.sm},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"auto",padding:be[4]},children:n?s.jsx(Dw,{context:n}):s.jsx(Nw,{})})]})}function Iw(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function Dw({context:e}){return e.kind==="cell"?s.jsx($w,{cellId:e.cellId}):e.kind==="lineage-node"?s.jsx(Mw,{nodeId:e.nodeId}):s.jsx(Lw,{name:e.name})}function $w({cellId:e}){const{state:t}=et(),n=t.cells.find(r=>r.id===e);return n?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3],fontSize:Ze.sm},children:[s.jsx(Ie,{label:"Type",children:n.type}),s.jsx(Ie,{label:"ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),s.jsxs(Ie,{label:"Length",children:[n.content.length," chars"]}),n.status&&s.jsx(Ie,{label:"Status",children:n.status})]}):s.jsx(fs,{children:"No matching cell in the active notebook."})}function Mw({nodeId:e}){const[t,n]=p.useState(null),[r,o]=p.useState(!0);if(p.useEffect(()=>{let c=!1;return o(!0),B.fetchLineageNode(e).then(l=>{c||(n(l),o(!1))}).catch(()=>{c||o(!1)}),()=>{c=!0}},[e]),r)return s.jsx(fs,{children:"Loading node…"});if(!t||!t.node)return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Node ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:e})}),s.jsx(fs,{children:"No metadata available for this node."})]});const i=t.node,a=i.metadata??{};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Name",children:i.name??e}),s.jsx(Ie,{label:"Type",children:Ap[i.type]??i.type}),i.domain&&s.jsx(Ie,{label:"Domain",children:i.domain}),i.owner&&s.jsx(Ie,{label:"Owner",children:i.owner}),i.status&&s.jsx(Ie,{label:"Status",children:i.status}),typeof a.termType=="string"&&s.jsx(Ie,{label:"Term Type",children:a.termType}),typeof a.description=="string"&&s.jsx(Ie,{label:"Description",children:a.description}),Array.isArray(a.identifiers)&&a.identifiers.length>0&&s.jsx(Ie,{label:"Identifiers",children:a.identifiers.map(String).join(", ")}),Array.isArray(a.synonyms)&&a.synonyms.length>0&&s.jsx(Ie,{label:"Synonyms",children:a.synonyms.map(String).join(", ")}),typeof a.businessOutcome=="string"&&s.jsx(Ie,{label:"Business Outcome",children:a.businessOutcome}),i.layer&&s.jsx(Ie,{label:"Layer",children:i.layer}),s.jsx(Ie,{label:"Upstream",children:t.incoming.length}),s.jsx(Ie,{label:"Downstream",children:t.outgoing.length}),(i.path||a.filePath)&&s.jsx(Ie,{label:"Path",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:Ze.xs},children:i.path??a.filePath})})]})}function Lw({name:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Metric",children:e}),s.jsx(fs,{children:"Definition, dimensions, and governance surface will render here."})]})}function Ie({label:e,children:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[s.jsx("div",{style:{fontSize:Ze.xs,color:pe("textMuted"),textTransform:"uppercase",letterSpacing:.5,fontWeight:Xi.medium},children:e}),s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textPrimary")},children:t})]})}function fs({children:e}){return s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textSecondary"),lineHeight:1.5,background:pe("surfaceSunken"),border:`1px solid ${pe("borderSubtle")}`,borderRadius:wn.md,padding:be[3]},children:e})}function Nw(){return s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textMuted"),lineHeight:1.5},children:"Select a cell, lineage node, or metric to inspect its details here."})}const Jr={appBg:"--color-bg-primary",sidebarBg:"--color-bg-secondary",activityBarBg:"--color-bg-sunken",headerBg:"--color-bg-toolbar",headerBorder:"--color-border-primary",cellBg:"--color-bg-card",cellBorder:"--color-border-subtle",cellBorderActive:"--color-accent-blue",cellBorderRunning:"--color-status-success",textPrimary:"--color-text-primary",textSecondary:"--color-text-secondary",textMuted:"--color-text-tertiary",editorBg:"--color-bg-surface",editorBorder:"--color-border-subtle",tableBorder:"--color-border-subtle",tableHeaderBg:"--color-bg-secondary",tableRowHover:"--color-bg-hover",accent:"--color-accent-blue",accentHover:"--color-accent-blue",success:"--color-status-success",error:"--color-status-error",warning:"--color-status-warning",btnBg:"--color-bg-tertiary",btnBorder:"--color-border-primary",btnHover:"--color-bg-hover",sidebarItemHover:"--color-bg-hover",sidebarItemActive:"--color-bg-active",scrollbarThumb:"--color-border-secondary",modalBg:"--color-bg-secondary",modalOverlay:"--color-bg-overlay",inputBg:"--color-bg-sunken",inputBorder:"--color-border-subtle",pillBg:"--color-bg-tertiary",font:"--font-ui",fontMono:"--font-mono",fontSerif:"--font-ui"},el={appBg:"#fbfaf7",sidebarBg:"#fbfaf7",activityBarBg:"#ffffff",headerBg:"#ffffff",headerBorder:"#e9e6e0",cellBg:"#ffffff",cellBorder:"#e9e6e0",cellBorderActive:"#6b5dd3",cellBorderRunning:"#2e8b57",textPrimary:"#1a1a1a",textSecondary:"#4a4a52",textMuted:"#8a8d96",editorBg:"#fbfaf7",editorBorder:"#e9e6e0",tableBorder:"#f0eee9",tableHeaderBg:"#faf9f7",tableRowHover:"#f3f0ea",accent:"#6b5dd3",accentHover:"#5c4fc2",success:"#2e8b57",error:"#c14545",warning:"#b26b1f",btnBg:"#ffffff",btnBorder:"#e9e6e0",btnHover:"#f3f0ea",sidebarItemHover:"#f3f0ea",sidebarItemActive:"#f3f0fb",scrollbarThumb:"#d9d5cc",modalBg:"#ffffff",modalOverlay:"rgba(26,26,26,0.40)",inputBg:"#fbfaf7",inputBorder:"#e9e6e0",pillBg:"#f3f0ea",font:"'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontMono:"'JetBrains Mono', ui-monospace, 'SFMono-Regular', Menlo, Monaco, Consolas, monospace",fontSerif:"'Inter', -apple-system, BlinkMacSystemFont, sans-serif"};function tl(e){if(typeof document>"u")return el[e];const t=Jr[e];return getComputedStyle(document.documentElement).getPropertyValue(t).trim()||el[e]}function Bw(){return new Proxy({},{get(e,t){if(typeof t=="string"&&t in Jr)return tl(t)},has(e,t){return typeof t=="string"&&t in Jr},ownKeys(){return Object.keys(Jr)},getOwnPropertyDescriptor(e,t){if(!(typeof t!="string"||!(t in Jr)))return{enumerable:!0,configurable:!0,value:tl(t)}}})}const On=Bw(),Qe={obsidian:On,paper:On,white:On,dark:On,light:On,midnight:On,arctic:On};function Ct(e,t="0 0 24 24"){return function({size:r=16,strokeWidth:o=1.75,...i}){return s.jsx("svg",{width:r,height:r,viewBox:t,fill:"none",stroke:"currentColor",strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round",...i,children:e})}}const Fw=Ct(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1.5"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 2l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V5l8-3z"}),s.jsx("path",{d:"M9 12l2 2 4-4"})]}));const zw=Ct(s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"5",cy:"12",r:"2"}),s.jsx("circle",{cx:"19",cy:"5",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("path",{d:"M7 12l10-6M7 12l10 6"})]})),Fj=Ct(s.jsxs(s.Fragment,{children:[s.jsx("ellipse",{cx:"12",cy:"5",rx:"8",ry:"3"}),s.jsx("path",{d:"M4 5v6c0 1.66 3.58 3 8 3s8-1.34 8-3V5"}),s.jsx("path",{d:"M4 11v6c0 1.66 3.58 3 8 3s8-1.34 8-3v-6"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h8a8 8 0 010 16H4z"}),s.jsx("path",{d:"M16 20l4 4"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 3v18h18"}),s.jsx("path",{d:"M7 15l4-4 4 4 5-7"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("path",{d:"M3 9h18M9 3v18"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),s.jsx("path",{d:"M8 12h8M12 8v8"})]}));const zj=Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 7h16M4 12h16M4 17h10"}),s.jsx("circle",{cx:"18",cy:"17",r:"2"})]}));Ct(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M3 5h18l-7 9v5l-4-2v-3L3 5z"})}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h10l6 6v10H4z"}),s.jsx("path",{d:"M14 4v6h6"}),s.jsx("path",{d:"M8 14l3 3 5-5"})]}));Ct(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M21 12a8 8 0 01-11.5 7.2L4 21l1.8-5.5A8 8 0 1121 12z"})}));const Rp=44,Op=188,_p="dql-activitybar-expanded";function qw(){var e;if(typeof window>"u")return!1;try{return((e=window.localStorage)==null?void 0:e.getItem(_p))==="1"}catch{return!1}}function Uw(e){var t;try{(t=window.localStorage)==null||t.setItem(_p,e?"1":"0")}catch{}}function nl({title:e,icon:t,active:n,expanded:r,onClick:o,t:i}){const[a,c]=p.useState(!1),l=s.jsxs("button",{"aria-label":e,onClick:o,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{width:r?Op-12:Rp-8,height:32,display:"flex",alignItems:"center",justifyContent:r?"flex-start":"center",gap:10,padding:r?"0 10px":0,marginLeft:r?6:4,marginRight:r?6:4,background:n?i.accent+"1f":a?i.textPrimary+"0f":"transparent",border:"none",borderRadius:6,cursor:"pointer",color:n?i.accent:a?i.textPrimary:i.textSecondary,transition:"background 0.15s, color 0.15s",fontFamily:i.font,fontSize:13,fontWeight:n?500:400,textAlign:"left",overflow:"hidden",whiteSpace:"nowrap"},children:[s.jsx("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,width:18,height:18},children:t}),r&&s.jsx("span",{style:{flex:1,textOverflow:"ellipsis",overflow:"hidden"},children:e})]});return r?l:s.jsx(Qd,{content:e,side:"right",children:l})}function Ww(){const e=Ge(Lr(l=>({mainView:l.mainView,sidebarOpen:l.sidebarOpen,sidebarPanel:l.sidebarPanel,themeMode:l.themeMode}))),t=jn(),n=Qe[e.themeMode],[r,o]=p.useState(qw);p.useEffect(()=>{Uw(r)},[r]);function i(l){if(l==="home"||l==="ask"||l==="modeling"){t({type:"SET_MAIN_VIEW",view:l});return}if(l==="lineage"){t({type:"SET_SIDEBAR_PANEL",panel:"lineage"});return}if(l==="connection"||l==="git"||l==="apps"||l==="readiness"||l==="skills"||l==="domains"||l==="settings"){t({type:"SET_SIDEBAR_PANEL",panel:l});return}e.sidebarPanel===l&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:l})}const a=[{label:"Insights",items:[{key:"apps",title:"Apps",icon:s.jsx(wS,{size:16,strokeWidth:1.75}),active:e.mainView==="apps"},{key:"ask",title:"Ask",icon:s.jsx(hS,{size:16,strokeWidth:1.75}),active:e.mainView==="ask"}]},{label:"Build",items:[{key:"files",title:"Notebooks",icon:s.jsx(Pa,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="files"&&e.sidebarOpen},{key:"block_library",title:"Blocks",icon:s.jsx(Fw,{size:16}),active:e.sidebarPanel==="block_library"&&e.sidebarOpen},{key:"lineage",title:"Lineage",icon:s.jsx(zw,{size:16}),active:e.mainView==="lineage"||e.mainView==="lineage_detail"}]},{label:"Govern",items:[{key:"domains",title:"Modeling",icon:s.jsx(Fi,{size:16,strokeWidth:1.75}),active:e.mainView==="domains"||e.mainView==="modeling"||e.mainView==="skills"},{key:"git",title:"Source control",icon:s.jsx(Nr,{size:16,strokeWidth:1.75}),active:e.mainView==="git"},{key:"settings",title:"Settings",icon:s.jsx(MS,{size:16,strokeWidth:1.75}),active:e.mainView==="settings"||e.mainView==="connection"}]}],c=[{key:"help",title:"Help",icon:s.jsx(Rv,{size:16,strokeWidth:1.75}),active:e.mainView==="help",onClick:()=>t({type:"SET_MAIN_VIEW",view:"help"})}];return s.jsxs("div",{style:{width:r?Op:Rp,flexShrink:0,background:n.activityBarBg,borderRight:`1px solid ${n.headerBorder}`,display:"flex",flexDirection:"column",paddingTop:6,paddingBottom:6,gap:2,userSelect:"none",transition:"width 0.18s ease",overflow:"hidden"},children:[s.jsx("div",{style:{display:"flex",justifyContent:r?"flex-end":"center",paddingLeft:r?6:0,paddingRight:r?6:0,marginBottom:4},children:s.jsx(Qd,{content:r?"Collapse":"Expand",side:"right",children:s.jsx("button",{"aria-label":r?"Collapse sidebar rail":"Expand sidebar rail",onClick:()=>o(l=>!l),style:{width:28,height:26,display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",borderRadius:5,cursor:"pointer",color:n.textMuted,padding:0},onMouseEnter:l=>{l.currentTarget.style.color=n.textPrimary,l.currentTarget.style.background=n.textPrimary+"0f"},onMouseLeave:l=>{l.currentTarget.style.color=n.textMuted,l.currentTarget.style.background="transparent"},children:r?s.jsx(wv,{size:14,strokeWidth:2}):s.jsx(Cv,{size:14,strokeWidth:2})})})}),a.map((l,u)=>s.jsxs(qe.Fragment,{children:[u>0?s.jsx("div",{style:{height:1,margin:r?"8px 10px 2px":"8px 12px",background:n.headerBorder}}):null,r?s.jsx("div",{style:{fontSize:10,fontWeight:600,color:n.textMuted,letterSpacing:"0.04em",padding:"4px 12px 2px"},children:l.label}):null,l.items.map(h=>s.jsx(nl,{title:h.title,icon:h.icon,active:h.active,expanded:r,onClick:()=>i(h.key),t:n},h.key))]},l.label)),s.jsx("div",{style:{flex:1}}),c.map(l=>s.jsx(nl,{title:l.title,icon:l.icon,active:l.active,expanded:r,onClick:l.onClick,t:n},l.key))]})}const Kw=2e4,qj="application/dql-semantic-ref",rl=new Map;let po=null;function Vw(e){B.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function ol(e,t){const n=`${e}:${t.toLowerCase()}`,r=rl.get(n);if(r&&Date.now()<r.expiresAt)return r.items;const o=new URLSearchParams({kind:e,q:t,limit:"50"}),i=await fetch(`${window.location.origin}/api/editor/completions?${o.toString()}`);if(!i.ok)throw new Error(`Failed to load semantic completions: HTTP ${i.status}`);const a=await i.json(),c=Array.isArray(a.completions)?a.completions:[];return rl.set(n,{items:c,expiresAt:Date.now()+Kw}),c}function Pp(e,t,n){const r=n??e.state.selection.main.from;e.dispatch({changes:{from:r,to:n??e.state.selection.main.to,insert:t},selection:{anchor:r+t.length}}),e.focus()}function Uj(e){po=e}function Wj(e){po===e&&(po=null)}function Hw(e){return po?(Pp(po,e),!0):!1}function Kj(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;Pp(e,t,r)}function sl(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
|
|
396
|
+
`));if(u==="agent-run-event")t({kind:"event",event:d});else if(u==="agent-run-answer-delta"){const f=typeof(d==null?void 0:d.delta)=="string"?d.delta:"";f&&t({kind:"answer-delta",delta:f})}else if(u==="agent-run-complete")i=d,t({kind:"complete",run:i});else if(u==="agent-run-error")throw new Error(typeof(d==null?void 0:d.error)=="string"?d.error:"Agent run failed.")};for(;;){const{value:c,done:l}=await n.read();if(c){o+=r.decode(c,{stream:!l});let u=o.search(/\r?\n\r?\n/);for(;u>=0;){const h=o.slice(0,u);o=o.slice(o[u]==="\r"?u+4:u+2),a(h),u=o.search(/\r?\n\r?\n/)}}if(l)break}if(o.trim()&&a(o),!i)throw new Error("Agent run stream ended before completion.");return i}function an(e){const t=Array.isArray(e==null?void 0:e.columns)?e.columns.map(a=>typeof a=="string"?a:typeof(a==null?void 0:a.name)=="string"?a.name:String(a)):[],n=e!=null&&e.semanticRefs&&typeof e.semanticRefs=="object"?{metrics:Array.isArray(e.semanticRefs.metrics)?e.semanticRefs.metrics.map(String):[],dimensions:Array.isArray(e.semanticRefs.dimensions)?e.semanticRefs.dimensions.map(String):[]}:void 0,r=Array.isArray(e==null?void 0:e.rows)?e.rows:[],o=t.length>0?t:r.find(a=>a&&typeof a=="object"&&!Array.isArray(a))?Object.keys(r.find(a=>a&&typeof a=="object"&&!Array.isArray(a))):r.find(a=>Array.isArray(a))?r.find(a=>Array.isArray(a)).map((a,c)=>`column_${c+1}`):[],i=r.map(a=>{if(Array.isArray(a))return Object.fromEntries(o.map((c,l)=>[c,a[l]]));if(a&&typeof a=="object"){const c=a;return Object.fromEntries(o.map(l=>[l,c[l]]))}return Object.fromEntries(o.map(c=>[c,void 0]))});return{columns:o,rows:i,...typeof(e==null?void 0:e.resultFingerprint)=="string"?{resultFingerprint:e.resultFingerprint}:{},...e!=null&&e.executionReceipt&&typeof e.executionReceipt=="object"?{executionReceipt:e.executionReceipt}:{},...typeof(e==null?void 0:e.trustState)=="string"?{trustState:e.trustState}:{},...typeof(e==null?void 0:e.answerTier)=="string"?{answerTier:e.answerTier}:{},rowCount:typeof(e==null?void 0:e.rowCount)=="number"?e.rowCount:i.length,executionTime:(e==null?void 0:e.executionTime)??(e==null?void 0:e.executionTimeMs)??0,...n?{semanticRefs:n}:{}}}function Vt(e){var n;const t=e!=null&&e.resultPreview&&typeof e.resultPreview=="object"?an(e.resultPreview):void 0;return{...e,domain:typeof(e==null?void 0:e.domain)=="string"&&e.domain.trim()?e.domain:void 0,owner:typeof(e==null?void 0:e.owner)=="string"&&e.owner.trim()?e.owner:void 0,warnings:Array.isArray(e==null?void 0:e.warnings)?e.warnings:[],dqlCandidateIds:Array.isArray(e==null?void 0:e.dqlCandidateIds)?e.dqlCandidateIds:[],dqlArtifact:zi(e==null?void 0:e.dqlArtifact),dqlPromotionAction:Ew((e==null?void 0:e.dqlPromotionAction)??((n=e==null?void 0:e.dqlPromotion)==null?void 0:n.recommendedAction)),dqlPromotion:Tp(e==null?void 0:e.dqlPromotion),researchPlan:yw(e==null?void 0:e.researchPlan),reviewChecklist:Cw(e==null?void 0:e.reviewChecklist,e),...t?{resultPreview:t}:{resultPreview:void 0}}}function yw(e){if(!e||typeof e!="object"||Array.isArray(e))return;const t=e,n=t.evidence&&typeof t.evidence=="object"&&!Array.isArray(t.evidence)?t.evidence:{},r=t.preview&&typeof t.preview=="object"&&!Array.isArray(t.preview)?t.preview:{},o=t.promotion&&typeof t.promotion=="object"&&!Array.isArray(t.promotion)?t.promotion:{},i=t.sqlState==="generated"||t.sqlState==="reviewed"?t.sqlState:"missing",a=r.status==="ready"||r.status==="error"?r.status:"not_run",c=o.path==="review_context"||o.path==="run_preview"||o.path==="reuse_existing"||o.path==="create_dql_draft"||o.path==="open_certification"||o.path==="complete_review"?o.path:"needs_sql",l=typeof r.rowCount=="number"&&Number.isFinite(r.rowCount)?r.rowCount:void 0;return{sqlState:i,grain:typeof t.grain=="string"&&t.grain.trim()?t.grain:void 0,parameterPolicy:bw(t.parameterPolicy),allowedFilters:Array.isArray(t.allowedFilters)?t.allowedFilters.map(String).filter(Boolean):[],evidence:{trustLabel:typeof n.trustLabel=="string"&&n.trustLabel.trim()?n.trustLabel:void 0,contextPackId:typeof n.contextPackId=="string"&&n.contextPackId.trim()?n.contextPackId:void 0,evidenceCount:Ce(n.evidenceCount),relationCount:Ce(n.relationCount),missingContextCount:Ce(n.missingContextCount)},preview:{status:a,...l===void 0?{}:{rowCount:l}},promotion:{path:c,duplicateDecision:typeof o.duplicateDecision=="string"&&o.duplicateDecision.trim()?o.duplicateDecision:void 0},reviewFocus:Array.isArray(t.reviewFocus)?t.reviewFocus.map(String).filter(Boolean):[],generatedAt:typeof t.generatedAt=="string"&&t.generatedAt.trim()?t.generatedAt:new Date(0).toISOString()}}function bw(e){return Array.isArray(e)?e.flatMap(t=>{if(!t||typeof t!="object"||Array.isArray(t))return[];const n=t,r=typeof n.name=="string"&&n.name.trim()?n.name:void 0,o=typeof n.policy=="string"&&n.policy.trim()?n.policy:void 0;return r&&o?[{name:r,policy:o}]:[]}):[]}function Ce(e){return typeof e=="number"&&Number.isFinite(e)?e:0}function rr(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function xw(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{};return{totalReviewCount:Ce(t.totalReviewCount),openReviewCount:Ce(t.openReviewCount),terminalReviewCount:Ce(t.terminalReviewCount),draftCreatedCount:Ce(t.draftCreatedCount),certifiedCount:Ce(t.certifiedCount),completedCount:Ce(t.completedCount),rejectedCount:Ce(t.rejectedCount),draftCreationRate:rr(t.draftCreationRate),certifyConversionRate:rr(t.certifyConversionRate),medianOpenReviewAgeMs:rr(t.medianOpenReviewAgeMs),medianTimeToDraftMs:rr(t.medianTimeToDraftMs),medianTimeToCertificationMs:rr(t.medianTimeToCertificationMs),medianTimeToTerminalMs:rr(t.medianTimeToTerminalMs)}}function vw(e){const t=e&&typeof e=="object"?e:{},n=t.counts&&typeof t.counts=="object"?t.counts:{},r=t.health&&typeof t.health=="object"?t.health:{},o=t.search&&typeof t.search=="object"?t.search:{},i=t.updatedAt&&typeof t.updatedAt=="object"?t.updatedAt:{},a=t.limits&&typeof t.limits=="object"?t.limits:{};return{counts:{totalRuns:Ce(n.totalRuns),activeRuns:Ce(n.activeRuns),closedRuns:Ce(n.closedRuns),notebooks:Ce(n.notebooks),domains:Ce(n.domains),owners:Ce(n.owners),sourceLinkedRuns:Ce(n.sourceLinkedRuns)},health:{staleOpenRuns:Ce(r.staleOpenRuns),expiredOpenRuns:Ce(r.expiredOpenRuns),staleThresholdDays:Ce(r.staleThresholdDays)||7,expiredThresholdDays:Ce(r.expiredThresholdDays)||30,oldestOpenUpdatedAt:typeof r.oldestOpenUpdatedAt=="string"&&r.oldestOpenUpdatedAt.trim()?r.oldestOpenUpdatedAt:void 0,newestOpenUpdatedAt:typeof r.newestOpenUpdatedAt=="string"&&r.newestOpenUpdatedAt.trim()?r.newestOpenUpdatedAt:void 0},search:{indexed:o.indexed===!0,indexRows:Ce(o.indexRows),indexVersion:typeof o.indexVersion=="string"&&o.indexVersion.trim()?o.indexVersion:void 0,stale:o.stale===!0},updatedAt:{oldest:typeof i.oldest=="string"&&i.oldest.trim()?i.oldest:void 0,newest:typeof i.newest=="string"&&i.newest.trim()?i.newest:void 0},limits:{pageSize:Ce(a.pageSize)||25,maxPageSize:Ce(a.maxPageSize)||500,sourceCoverageLimit:Ce(a.sourceCoverageLimit)||1e4,seedCellLimit:Ce(a.seedCellLimit)||1e3},warnings:Array.isArray(t.warnings)?t.warnings.filter(c=>typeof c=="string"):[]}}function Sw(e){return e==="diagnose_change"||e==="driver_breakdown"||e==="segment_compare"||e==="entity_drilldown"||e==="anomaly_investigation"||e==="trust_gap_review"?e:"ad_hoc_analysis"}function ww(e){const t=typeof e=="string"?e:"";return(t.split(/[\\/]/).pop()??t).replace(/\.dqlnb$/i,"").replace(/[-_]+/g," ").replace(/\s+/g," ").trim()||"Untitled notebook"}function kw(e){const t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},n=r=>typeof t[r]=="number"&&Number.isFinite(t[r])?t[r]:0;return{fix_blockers:n("fix_blockers"),review_sql:n("review_sql"),review_context:n("review_context"),run_preview:n("run_preview"),reuse_existing:n("reuse_existing"),create_dql_draft:n("create_dql_draft"),open_certification:n("open_certification"),complete_review:n("complete_review"),continue_review:n("continue_review")}}function Vo(e){return e==="fix_blockers"||e==="review_sql"||e==="review_context"||e==="run_preview"||e==="reuse_existing"||e==="create_dql_draft"||e==="open_certification"||e==="complete_review"||e==="continue_review"?e:void 0}function Cw(e,t){var u,h;if(e&&typeof e=="object"&&Array.isArray(e.items))return{readyForDqlDraft:e.readyForDqlDraft===!0,readyForCertificationReview:e.readyForCertificationReview===!0,blockers:Array.isArray(e.blockers)?e.blockers.filter(d=>typeof d=="string"):[],warnings:Array.isArray(e.warnings)?e.warnings.filter(d=>typeof d=="string"):[],items:e.items.map(d=>({id:typeof d.id=="string"?d.id:"item",label:typeof d.label=="string"?d.label:"Review item",status:d.status==="passed"||d.status==="pending"||d.status==="warning"||d.status==="blocked"?d.status:"pending",detail:typeof d.detail=="string"?d.detail:""}))};const n=!!t.reviewedSql,r=n||!!t.generatedSql,o=((u=t.resultPreview)==null?void 0:u.rowCount)??((h=t.resultPreview)==null?void 0:h.rows.length)??0,i=!!(t.resultPreview&&(t.resultPreview.columns.length>0||o>0)),a=!!t.draftBlockPath,c=!!(t.contextPackId||t.evidence),l=t.dqlPromotionAction==="reuse_existing";return{readyForDqlDraft:!!(!l&&t.question&&n&&c&&t.status!=="error"),readyForCertificationReview:!!(!l&&t.question&&n&&c&&i&&a),blockers:t.status==="error"?[t.error??"Preview failed."]:[],warnings:i||l?[]:["Run a bounded preview before certification review."],items:[{id:"question",label:"Question",status:t.question?"passed":"blocked",detail:t.question?"Business question is captured.":"Add a business question."},{id:"sql",label:"Reviewed SQL",status:r||l?"passed":"blocked",detail:l&&!r?"Existing DQL should be reused; no new SQL is required.":r?"SQL is available.":"Add SQL before promotion."},{id:"evidence",label:"Evidence",status:c||l?"passed":"warning",detail:c?"Context evidence is saved.":l?"Reuse evidence is captured in the recommendation.":"Preview and save metadata context."},{id:"preview",label:"Preview",status:i||l?"passed":"pending",detail:i?"Preview result is available.":l?"Certified block reuse does not require a new raw SQL preview.":"Run a bounded preview."},{id:"dql_draft",label:"DQL draft",status:a||l?"passed":"pending",detail:a?`Draft saved at ${t.draftBlockPath}.`:l?"No new DQL draft is required.":"Create a DQL draft after review."}]}}function jw(e){var r,o,i,a;const t=e&&typeof e=="object"?e:{},n=t.routeDecision&&typeof t.routeDecision=="object"?{route:typeof t.routeDecision.route=="string"?t.routeDecision.route:void 0,intent:typeof t.routeDecision.intent=="string"?t.routeDecision.intent:void 0,reason:typeof t.routeDecision.reason=="string"?t.routeDecision.reason:void 0}:void 0;return{contextPackId:typeof t.contextPackId=="string"?t.contextPackId:"",trustLabel:typeof t.trustLabel=="string"?t.trustLabel:void 0,routeDecision:n,evidence:Array.isArray(t.evidence)?t.evidence.map(c=>({objectKey:typeof c.objectKey=="string"?c.objectKey:void 0,objectType:typeof c.objectType=="string"?c.objectType:void 0,name:typeof c.name=="string"?c.name:"Evidence",role:typeof c.role=="string"?c.role:void 0,reason:typeof c.reason=="string"?c.reason:""})):[],summaries:Array.isArray(t.summaries)?t.summaries.map(c=>({title:typeof c.title=="string"?c.title:"Context",detail:typeof c.detail=="string"?c.detail:"",objectType:typeof c.objectType=="string"?c.objectType:void 0,reason:typeof c.reason=="string"?c.reason:void 0})):[],relations:Array.isArray(t.relations)?t.relations.map(c=>({relation:typeof c.relation=="string"?c.relation:"",name:typeof c.name=="string"?c.name:"Relation",source:typeof c.source=="string"?c.source:"",columns:Array.isArray(c.columns)?c.columns.map(String):[]})).filter(c=>c.relation||c.name):[],missingContext:Array.isArray(t.missingContext)?t.missingContext.map(c=>({kind:typeof c.kind=="string"?c.kind:"metadata",message:typeof c.message=="string"?c.message:"",severity:typeof c.severity=="string"?c.severity:"warning"})).filter(c=>c.message):[],warnings:Array.isArray(t.warnings)?t.warnings.filter(c=>typeof c=="string"):[],topRejected:Array.isArray(t.topRejected)?t.topRejected.map(c=>({name:typeof c.name=="string"?c.name:"Rejected context",objectType:typeof c.objectType=="string"?c.objectType:void 0,reason:typeof c.reason=="string"?c.reason:"",score:typeof c.score=="number"&&Number.isFinite(c.score)?c.score:void 0})).filter(c=>c.reason):[],counts:{objects:typeof((r=t.counts)==null?void 0:r.objects)=="number"?t.counts.objects:0,evidence:typeof((o=t.counts)==null?void 0:o.evidence)=="number"?t.counts.evidence:0,relations:typeof((i=t.counts)==null?void 0:i.relations)=="number"?t.counts.relations:0,warnings:typeof((a=t.counts)==null?void 0:a.warnings)=="number"?t.counts.warnings:0}}}function Ew(e){return e==="reuse_existing"||e==="extend_existing"||e==="create_replacement"||e==="create_new"||e==="review_required"?e:void 0}function Tp(e){if(!(!e||typeof e!="object"))return{importId:typeof e.importId=="string"?e.importId:"",candidateIds:Array.isArray(e.candidateIds)?e.candidateIds.filter(t=>typeof t=="string"):[],draftBlockPath:typeof e.draftBlockPath=="string"?e.draftBlockPath:void 0,recommendedAction:typeof e.recommendedAction=="string"?e.recommendedAction:void 0,similarityMatches:Array.isArray(e.similarityMatches)?e.similarityMatches:[],candidates:Array.isArray(e.candidates)?e.candidates.map(t=>({...t,similarityMatches:Array.isArray(t.similarityMatches)?t.similarityMatches:[],parameterPolicy:Array.isArray(t.parameterPolicy)?t.parameterPolicy:[],allowedFilters:Array.isArray(t.allowedFilters)?t.allowedFilters:[],warnings:Array.isArray(t.warnings)?t.warnings:[]})):[],createdAt:typeof e.createdAt=="string"?e.createdAt:""}}function Yc(e){return{id:e.sourceId,sourceId:e.sourceId,qualifiedIdentity:e.qualifiedIdentity,sourceRevision:e.sourceRevision,snapshotId:e.snapshotId,lifecycle:e.lifecycle,trust:e.trust,name:e.name,domain:e.domain??"Unassigned",status:e.lifecycle,owner:e.owner??null,tags:e.tags,path:e.executionRef,fingerprint:e.sourceRevision,lastModified:"",description:e.description??"",chartType:e.capabilities.chartType,filterIds:e.capabilities.filters,dimensionIds:e.capabilities.dimensions,capabilities:e.capabilities,eligibility:e.eligibility,score:e.score??0,reasons:e.reasons}}const B={async listOperations(e=50){return k(`/api/operations?limit=${Math.max(1,Math.min(100,Math.floor(e)))}`)},async getOperation(e){return k(`/api/operations/${encodeURIComponent(e)}`)},async cancelOperation(e){return k(`/api/operations/${encodeURIComponent(e)}`,{method:"DELETE"})},async requestBlockStudioCertification(e){return k("/api/block-studio/certifications",{method:"POST",headers:{"Idempotency-Key":e.idempotencyKey},body:JSON.stringify({source:e.source,path:e.path,metadata:e.metadata,expectedSourceFingerprint:e.expectedSourceFingerprint,clientRevision:e.clientRevision})})},async getDbtFirstModeling(){return k("/api/modeling/dbt-first")},async getDbtModelingNode(e){return k(`/api/modeling/dbt-first/nodes/${encodeURIComponent(e)}`)},async getDbtModelingNodes(e){return k("/api/modeling/dbt-first/nodes/batch",{method:"POST",body:JSON.stringify({uniqueIds:e})})},async getDbtModelInventory(e={}){const t=new URLSearchParams;return e.q&&t.set("q",e.q),e.domain&&t.set("domain",e.domain),e.cursor!==void 0&&t.set("cursor",String(e.cursor)),e.limit!==void 0&&t.set("limit",String(e.limit)),e.physicalOnly&&t.set("physicalOnly","true"),k(`/api/modeling/dbt-first/inventory?${t.toString()}`)},async getDomainWorkspaces(){return k("/api/domain-workspaces")},async getRelatedDomainProducts(e){return k(`/api/domain-workspaces/${encodeURIComponent(e)}/related-products`)},async getAllRelatedDomainProducts(){return k("/api/domain-workspaces/related-products")},async getDomainKnowledge(e){return k(`/api/domain-workspaces/${encodeURIComponent(e)}/knowledge`)},async createContextProposal(e){return(await k("/api/context-proposals",{method:"POST",body:JSON.stringify(e)})).proposal},async getContextProposal(e){return(await k(`/api/context-proposals/${encodeURIComponent(e)}`)).proposal},async repreviewContextProposal(e,t,n){return(await k(`/api/context-proposals/${encodeURIComponent(e)}/repreview`,{method:"POST",body:JSON.stringify({selectedOperationIds:t,rebase:(n==null?void 0:n.rebase)===!0})})).proposal},async commitContextProposal(e,t,n){return k(`/api/context-proposals/${encodeURIComponent(e)}/commit`,{method:"POST",body:JSON.stringify({expectedProposalHash:t,idempotencyKey:n})})},async createModelingImport(e){return(await k("/api/modeling/dbt-first/imports",{method:"POST",body:JSON.stringify({source:e})})).session},async previewModelingImport(e,t){return k(`/api/modeling/dbt-first/imports/${encodeURIComponent(e)}/preview`,{method:"POST",body:JSON.stringify(t)})},async previewModelingChange(e,t){return k("/api/modeling/dbt-first/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyModelingChange(e,t,n){return k("/api/modeling/dbt-first/apply",{method:"POST",body:JSON.stringify({change:e,fingerprint:t,expectedSnapshotId:n})})},async validateModelingRelationship(e,t){return(await k("/api/modeling/dbt-first/relationships/validate",{method:"POST",body:JSON.stringify({relationship:e,expectedSnapshotId:t})})).evidence},async previewDbtSourcePatch(e,t){return k("/api/modeling/dbt-first/dbt-source/preview",{method:"POST",body:JSON.stringify({change:e,expectedSnapshotId:t})})},async applyDbtSourcePatch(e,t,n){return k("/api/modeling/dbt-first/dbt-source/apply",{method:"POST",body:JSON.stringify({change:e,expectedFingerprint:t,expectedSnapshotId:n})})},async getSettingsEnvStatus(){try{return await k("/api/settings/env-status")}catch{return{groups:[]}}},async getProposeReadiness(e){try{return await k("/api/propose",{method:"POST",body:JSON.stringify(e??{})})}catch{return{ready:!1,reason:"Unable to reach the propose engine. Is the local DQL server running?",summary:{modelsScanned:0,businessModels:0,plumbingExcluded:0,metricsFound:0,proposalsRanked:0,draftsExisting:0,readyForReview:0,blockingTotal:0,warningTotal:0},plan:mw,proposals:[]}}},async generateProposeDrafts(e){try{return await k("/api/propose/generate",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ready:!1,reason:t instanceof Error?t.message:"Unable to reach the propose engine.",draftsWritten:0,draftsSkipped:0,proposals:[]}}},async proposePreview(e){return k(`/api/propose/preview?slug=${encodeURIComponent(e)}`)},async aiBuild(e){return k("/api/ai/build",{method:"POST",body:JSON.stringify(e)})},async createAgentRun(e){return(await k("/api/agent-runs",{method:"POST",body:JSON.stringify(e)})).run},async createAgentRunStream(e,t,n){let r;try{r=await fetch(`${Qr}/api/agent-runs?stream=1`,{method:"POST",headers:lr({"Content-Type":"application/json"}),body:JSON.stringify(e),signal:n})}catch(o){if(n!=null&&n.aborted)throw o;const i=o instanceof Error&&o.message?` ${o.message}`:"";throw new Error(`Unable to reach the local DQL notebook server. Check that it is still running, then retry.${i}`)}if(!r.ok){const o=await r.text().catch(()=>"");throw Ui(r,o)}return gw(r,t)},async listAgentRuns(e){const t=new URLSearchParams;typeof(e==null?void 0:e.limit)=="number"&&Number.isFinite(e.limit)&&t.set("limit",String(e.limit));const n=t.toString()?`?${t.toString()}`:"";return k(`/api/agent-runs${n}`)},async getAgentRun(e){const t=await this.getAgentRunState(e);if(t.lifecycleState!=="terminal")throw new Error(`Agent run ${e} is still ${t.lifecycleState}.`);return t.run},async getAgentRunState(e){return k(`/api/agent-runs/${encodeURIComponent(e)}`)},async deriveAnalyticalRepair(e,t){return k(`/api/agent-runs/${encodeURIComponent(e)}/analytical-repair`,{method:"POST",body:JSON.stringify({repair:t})})},async repairAgentRunExecution(e,t){return k(`/api/agent-runs/${encodeURIComponent(e)}/repair-execution`,{method:"POST",body:JSON.stringify({threadId:t})})},async repairNotebookCellExecution(e,t,n){var o,i,a,c,l,u;const r=await k("/api/notebook/repair-execution",{method:"POST",body:JSON.stringify({cell:{id:e.id,type:e.type,source:e.content,title:e.name,config:e.chartConfig},error:t,failure:(o=e.execution)==null?void 0:o.error,attemptedSql:((i=e.execution)==null?void 0:i.compiledSql)??e.content,executionTarget:e.executionTarget,parameters:((a=e.blockBinding)==null?void 0:a.state)==="bound"?e.blockBinding.parameterValues:e.dqlParameterValues,executionContext:n})});if(n!=null&&n.runId&&typeof((c=r==null?void 0:r.executionContext)==null?void 0:c.runId)=="string"&&r.executionContext.runId!==n.runId)throw new St({message:"The notebook server returned a repair for a different cell run. The stale result was rejected.",status:409,code:"STALE_CELL_EXECUTION",details:{expected:n,received:r.executionContext}});return{ok:!0,source:String(r.source??e.content),repairedSql:String(r.repairedSql??""),repairMode:r.repairMode==="ai"?"ai":"deterministic",result:an(r.result),executionTarget:((l=r==null?void 0:r.executionTarget)==null?void 0:l.target)==="local"?{target:"local"}:((u=r==null?void 0:r.executionTarget)==null?void 0:u.target)==="connection"?{target:"connection",...typeof r.executionTarget.connectionName=="string"?{connectionName:r.executionTarget.connectionName}:{}}:void 0,compiledSql:typeof(r==null?void 0:r.compiledSql)=="string"?r.compiledSql:void 0,executedSql:typeof(r==null?void 0:r.executedSql)=="string"?r.executedSql:void 0,executionReceipt:r!=null&&r.executionReceipt&&typeof r.executionReceipt=="object"?r.executionReceipt:void 0}},async cancelAgentRun(e){return k(`/api/agent-runs/${encodeURIComponent(e)}/cancel`,{method:"POST"})},async listAgentThreads(e){const t=new URLSearchParams;typeof(e==null?void 0:e.limit)=="number"&&Number.isFinite(e.limit)&&t.set("limit",String(e.limit)),e!=null&&e.archived&&t.set("archived","1");const n=t.toString()?`?${t.toString()}`:"";return k(`/api/agent/threads${n}`)},async createAgentThread(e={}){return(await k("/api/agent/threads",{method:"POST",body:JSON.stringify(e)})).thread},async getAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}`)},async updateAgentThread(e,t){return k(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async archiveAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}/archive`,{method:"POST"})},async deleteAgentThread(e){return k(`/api/agent/threads/${encodeURIComponent(e)}`,{method:"DELETE"})},async requestCertification(e){return k("/api/agent-runs/request-certification",{method:"POST",body:JSON.stringify(e)})},async getIdentity(){return k("/api/identity")},async getProviderSettings(){try{return await k("/api/settings/providers")}catch{return{providers:[]}}},async getProviderCliStatus(){try{return await k("/api/settings/providers/cli-status")}catch{return{status:{}}}},async saveProviderSettings(e){return k("/api/settings/providers",{method:"POST",body:JSON.stringify(e)})},async startOAuth(e){return k(`/api/auth/${e}/start`,{method:"POST"})},async getOAuthStatus(e){return k(`/api/auth/${e}/status`)},async signOutOAuth(e){return k(`/api/auth/${e}/signout`,{method:"POST"})},async testProviderSettings(e,t){try{return await k("/api/settings/providers/test",{method:"POST",body:JSON.stringify({id:e,...t})})}catch(n){return{ok:!1,message:n instanceof Error?n.message:String(n)}}},async getRemoteMcpSettings(){try{return await k("/api/settings/mcp")}catch{return{settings:{path:"",entries:[],warnings:[]}}}},async saveRemoteMcpSettings(e){return k("/api/settings/mcp",{method:"POST",body:JSON.stringify({entries:e})})},async recordAgentCorrection(e){return k("/api/agent/learnings/correction",{method:"POST",body:JSON.stringify(e)})},async listAgentHints(e){const t=e?`?status=${encodeURIComponent(e)}`:"";return k(`/api/agent/hints${t}`)},async reviewAgentHint(e,t,n){return k(`/api/agent/hints/${encodeURIComponent(e)}/review`,{method:"POST",body:JSON.stringify({decision:t,...n?{note:n}:{}})})},async updateAgentHint(e,t){return k(`/api/agent/hints/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})},async transitionAgentHint(e,t){return k(`/api/agent/hints/${encodeURIComponent(e)}/lifecycle`,{method:"POST",body:JSON.stringify(t)})},async listAgentMemory(e){const t=e?`?scope=${encodeURIComponent(e)}`:"";try{return await k(`/api/agent/memory${t}`)}catch{return{memories:[]}}},async saveAgentMemory(e){return k("/api/agent/memory",{method:"POST",body:JSON.stringify(e)})},async deleteAgentMemory(e){return k(`/api/agent/memory?id=${encodeURIComponent(e)}`,{method:"DELETE"})},async ensureAgentMemoryFiles(){return k("/api/agent/memory/default-files",{method:"POST"})},async listNotebooks(){try{return await k("/api/notebooks")}catch{return[]}},async readNotebook(e){return k(`/api/notebook-content?path=${encodeURIComponent(e)}`)},async deleteNotebook(e){return k(`/api/notebooks?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async createNotebook(e,t,n={}){return k("/api/notebooks",{method:"POST",body:JSON.stringify({name:e,template:t,...n})})},async createBlock(e,t){return k("/api/blocks",{method:"POST",body:JSON.stringify({name:e,...t})})},async getBlockLibrary(){try{return await k("/api/blocks/library")}catch{return{blocks:[]}}},async getApps(){try{return await k("/api/apps")}catch{return{apps:[]}}},async updateBlockStatus(e,t){return k("/api/blocks/status",{method:"POST",body:JSON.stringify({path:e,newStatus:t})})},async getBlockHistory(e){try{return await k(`/api/blocks/history?path=${encodeURIComponent(e)}`)}catch{return{entries:[]}}},async runBlockTests(e,t){return k("/api/blocks/run-tests",{method:"POST",body:JSON.stringify({source:e,path:t})})},async getBlockStudioCatalog(e={}){const t=new URLSearchParams;e.includeSemantic===!1&&t.set("includeSemantic","false");const n=t.toString();return k(`/api/block-studio/catalog${n?`?${n}`:""}`)},async getBlockStudioDbtStatus(){return k("/api/block-studio/dbt-status")},async openBlockStudio(e){return k(`/api/block-studio/open?path=${encodeURIComponent(e)}`)},async getBlockBody(e){return k(`/api/blocks/body?path=${encodeURIComponent(e)}`)},async validateBlockStudio(e,t,n){return k("/api/block-studio/validate",{method:"POST",body:JSON.stringify({source:e,path:t}),signal:n})},async runBlockStudio(e,t,n){return k("/api/block-studio/run",{method:"POST",body:JSON.stringify({source:e,path:t,parameters:n})})},async repairAndRunBlockStudio(e,t,n={},r){const o=await k("/api/block-studio/repair-and-run",{method:"POST",body:JSON.stringify({cell:{id:"block-studio-draft",type:"dql",source:e,title:r||"Block Studio draft"},error:t,attemptedSql:e,parameters:n})}),i=String(o.repairedSql??"");return{source:String(o.source??e),repairedSql:i,repairMode:o.repairMode==="ai"?"ai":"deterministic",preview:{sql:i,result:an(o.result)}}},async getCertifiedBlockParameters(e){return k(`/api/blocks/parameters?name=${encodeURIComponent(e)}`)},async invokeCertifiedBlock(e,t,n){var o,i,a,c,l,u;const r=await k("/api/blocks/invoke",{method:"POST",body:JSON.stringify({blockName:e,parameters:t,question:n})});return{parameters:Array.isArray(r==null?void 0:r.parameters)?r.parameters:[],result:{...an(r==null?void 0:r.result),...typeof((o=r==null?void 0:r.result)==null?void 0:o.sql)=="string"?{sql:r.result.sql}:{},...typeof((i=r==null?void 0:r.result)==null?void 0:i.blockName)=="string"?{blockName:r.result.blockName}:{},...typeof((a=r==null?void 0:r.result)==null?void 0:a.blockPath)=="string"?{blockPath:r.result.blockPath}:{},...(c=r==null?void 0:r.result)!=null&&c.chartConfig?{chartConfig:r.result.chartConfig}:{},...Array.isArray((l=r==null?void 0:r.result)==null?void 0:l.parameters)?{parameters:r.result.parameters}:{},...typeof((u=r==null?void 0:r.result)==null?void 0:u.auditId)=="string"?{auditId:r.result.auditId}:{}}}},async addDqlArtifactResultFilter(e,t,n,r,o){const i=await k("/api/dql/artifacts/add-filter",{method:"POST",body:JSON.stringify({artifact:e,resultColumns:t,column:n,value:r,executionTarget:o})}),a=zi(i==null?void 0:i.artifact);if(!a)throw new Error("Adding the filter input returned an invalid artifact contract.");return{artifact:a,parameterName:String((i==null?void 0:i.parameterName)??n)}},async invokeDqlArtifact(e,t,n,r,o){var c,l,u,h,d,f;const i=await k("/api/dql/artifacts/execute",{method:"POST",body:JSON.stringify({artifact:e,parameters:t,question:n,blockName:r,executionTarget:o})}),a=zi(i==null?void 0:i.artifact);if(!a)throw new Error("DQL artifact execution returned an invalid artifact contract.");return{artifact:a,parameters:a.parameters??[],result:{...an(i==null?void 0:i.result),...typeof((c=i==null?void 0:i.result)==null?void 0:c.sql)=="string"?{sql:i.result.sql}:{},...typeof((l=i==null?void 0:i.result)==null?void 0:l.blockName)=="string"?{blockName:i.result.blockName}:{},...typeof((u=i==null?void 0:i.result)==null?void 0:u.blockPath)=="string"?{blockPath:i.result.blockPath}:{},...(h=i==null?void 0:i.result)!=null&&h.chartConfig?{chartConfig:i.result.chartConfig}:{},...Array.isArray((d=i==null?void 0:i.result)==null?void 0:d.parameters)?{parameters:i.result.parameters}:{},...typeof((f=i==null?void 0:i.result)==null?void 0:f.auditId)=="string"?{auditId:i.result.auditId}:{}}}},async composeSemanticBlock(e){return k("/api/block-studio/compose-semantic",{method:"POST",body:JSON.stringify({question:e})})},async saveBlockStudio(e){return k("/api/block-studio/save",{method:"POST",body:JSON.stringify(e)})},async saveAgentBlockDraft(e){return k("/api/block-studio/agent-drafts",{method:"POST",body:JSON.stringify(e)})},async deleteBlockStudio(e){return k(`/api/block-studio/block?path=${encodeURIComponent(e)}`,{method:"DELETE"})},async previewBlockStudioImport(e){return k("/api/block-studio/import/preview",{method:"POST",body:JSON.stringify(e)})},async listBlockStudioImports(){return k("/api/block-studio/imports")},async createBlockStudioImport(e){return k("/api/block-studio/imports",{method:"POST",body:JSON.stringify(e)})},async createDqlGenerationSession(e){return k("/api/block-studio/ai-imports",{method:"POST",body:JSON.stringify(e)})},async getDqlGenerationSession(e){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}`)},async getBlockStudioImport(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}`)},async deleteBlockStudioImport(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}`,{method:"DELETE"})},async clearBlockStudioImports(){return k("/api/block-studio/imports",{method:"DELETE"})},async updateBlockStudioImportCandidate(e,t,n){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async updateDqlGenerationCandidate(e,t,n){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})},async matchSqlForBlockReuse(e,t){return k("/api/block-studio/match-sql",{method:"POST",body:JSON.stringify({sql:e,...t??{}})})},async previewDqlGenerationCandidate(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/preview`,{method:"POST"})},async certifyDqlGenerationCandidate(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/certify`,{method:"POST"})},async saveSelectedDqlGenerationCandidates(e,t){return k(`/api/block-studio/ai-imports/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify(t)})},async runBlockStudioImportCandidate(e,t){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/run`,{method:"POST"})},async saveBlockStudioImportCandidate(e,t){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/save`,{method:"POST"})},async saveAllBlockStudioImportCandidates(e){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/save-all`,{method:"POST"})},async assistBlockStudioImportCandidate(e,t,n){return k(`/api/block-studio/imports/${encodeURIComponent(e)}/candidates/${encodeURIComponent(t)}/ai-assist`,{method:"POST",body:JSON.stringify({action:n})})},async getSemanticLayerDiagnostics(){return k("/api/semantic-layer/diagnostics")},async reloadSemanticLayer(){return k("/api/semantic-layer/reload",{method:"POST"})},async assessBlockStudioCertification(e){return k("/api/block-studio/certification-check",{method:"POST",body:JSON.stringify({source:e})})},async certifyBlockStudio(e){const t=await fetch(`${Qr}/api/block-studio/certify`,{headers:lr({"Content-Type":"application/json"}),method:"POST",body:JSON.stringify(e)}),n=await t.json().catch(()=>({ok:!1,error:t.statusText}));if(!t.ok&&t.status!==422)throw new Error(JSON.stringify(n));return n},async saveAsBlock(e){return k("/api/blocks/save-from-cell",{method:"POST",body:JSON.stringify(e)})},async getBlockTemplates(){try{return(await k("/api/blocks/templates")).templates}catch{return[]}},async listBlocks(e){try{return(await k("/api/notebooks")).filter(n=>n.type==="block"&&(!e||n.path.startsWith(`blocks/${e}/`)))}catch{return[]}},async saveNotebook(e,t){return k("/api/notebook-content",{method:"PUT",body:JSON.stringify({path:e,content:t})})},async executeQuery(e,t,n,r){var i,a,c;const o=await k("/api/query",{method:"POST",body:JSON.stringify({sql:e,executionContext:n,executionTarget:r}),signal:t});if(n!=null&&n.runId&&typeof((i=o==null?void 0:o.executionContext)==null?void 0:i.runId)=="string"&&o.executionContext.runId!==n.runId)throw new St({message:"The notebook server returned a result for a different cell run. The stale result was rejected.",status:409,code:"STALE_CELL_EXECUTION",details:{expected:n,received:o.executionContext}});return{...an(o),executionTarget:((a=o==null?void 0:o.executionTarget)==null?void 0:a.target)==="local"?{target:"local"}:((c=o==null?void 0:o.executionTarget)==null?void 0:c.target)==="connection"?{target:"connection",...typeof o.executionTarget.connectionName=="string"?{connectionName:o.executionTarget.connectionName}:{}}:void 0,compiledSql:typeof(o==null?void 0:o.compiledSql)=="string"?o.compiledSql:void 0,executedSql:typeof(o==null?void 0:o.executedSql)=="string"?o.executedSql:void 0,targetBinding:o!=null&&o.targetBinding&&typeof o.targetBinding=="object"?o.targetBinding:void 0,executionReceipt:o!=null&&o.executionReceipt&&typeof o.executionReceipt=="object"?o.executionReceipt:void 0}},async previewGeneratedSql(e,t){try{const n=await k("/api/ai/sql-draft/preview",{method:"POST",body:JSON.stringify({sql:e}),signal:t});return{ok:!0,result:an(n.result)}}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async executeNotebookCell(e,t,n){var o,i,a,c,l,u;const r=await k("/api/notebook/execute",{method:"POST",body:JSON.stringify({cell:{id:e.id,type:e.type,source:e.content,title:e.name,config:e.chartConfig},executionTarget:e.executionTarget,parameters:((o=e.blockBinding)==null?void 0:o.state)==="bound"?e.blockBinding.parameterValues:e.dqlParameterValues,executionContext:n}),signal:t});if(n!=null&&n.runId&&typeof((i=r==null?void 0:r.executionContext)==null?void 0:i.runId)=="string"&&r.executionContext.runId!==n.runId)throw new St({message:"The notebook server returned a result for a different semantic cell run. The stale result was rejected.",status:409,code:"STALE_CELL_EXECUTION",details:{expected:n,received:r.executionContext}});return{cellType:String((r==null?void 0:r.cellType)??e.type),cellId:typeof((a=r==null?void 0:r.executionContext)==null?void 0:a.cellId)=="string"?r.executionContext.cellId:void 0,runId:typeof((c=r==null?void 0:r.executionContext)==null?void 0:c.runId)=="string"?r.executionContext.runId:void 0,title:typeof(r==null?void 0:r.title)=="string"?r.title:void 0,blockName:typeof(r==null?void 0:r.blockName)=="string"?r.blockName:void 0,blockPath:typeof(r==null?void 0:r.blockPath)=="string"?r.blockPath:void 0,chartConfig:r!=null&&r.chartConfig&&typeof r.chartConfig=="object"?r.chartConfig:void 0,tests:Array.isArray(r==null?void 0:r.tests)?r.tests:void 0,result:r!=null&&r.result?an(r.result):null,executionTarget:((l=r==null?void 0:r.executionTarget)==null?void 0:l.target)==="local"?{target:"local"}:((u=r==null?void 0:r.executionTarget)==null?void 0:u.target)==="connection"?{target:"connection",...typeof r.executionTarget.connectionName=="string"?{connectionName:r.executionTarget.connectionName}:{}}:void 0,engine:(r==null?void 0:r.engine)==="native"||(r==null?void 0:r.engine)==="metricflow-cli"||(r==null?void 0:r.engine)==="dbt-cloud"?r.engine:void 0,semanticTrace:r!=null&&r.semanticTrace&&typeof r.semanticTrace=="object"?r.semanticTrace:void 0,compiledSql:typeof(r==null?void 0:r.compiledSql)=="string"?r.compiledSql:void 0,executedSql:typeof(r==null?void 0:r.executedSql)=="string"?r.executedSql:void 0,targetBinding:r!=null&&r.targetBinding&&typeof r.targetBinding=="object"?r.targetBinding:void 0,executionReceipt:r!=null&&r.executionReceipt&&typeof r.executionReceipt=="object"?r.executionReceipt:void 0}},async getDatasets(){return k("/api/datasets")},async importDataset(e){if(e.file){const t=new FormData;t.set("file",e.file,e.file.name);for(const[r,o]of Object.entries(e))r==="file"||o===void 0||t.set(r,Array.isArray(o)?o.join(","):String(o));const n=await fetch(`${Qr}/api/datasets/import`,{method:"POST",headers:lr(),body:t});if(!n.ok){const r=await n.text().catch(()=>"");throw Ui(n,r)}return n.json()}return k("/api/datasets/import",{method:"POST",body:JSON.stringify(e)})},async refreshDataset(e){return k(`/api/datasets/${encodeURIComponent(e)}/refresh`,{method:"POST"})},async updateDatasetSchema(e,t){return k(`/api/datasets/${encodeURIComponent(e)}/schema`,{method:"POST",body:JSON.stringify({overrides:t})})},async renameDataset(e,t,n){return k(`/api/datasets/${encodeURIComponent(e)}/rename`,{method:"POST",body:JSON.stringify({name:t,alias:n})})},async pinDataset(e,t=!0){return k(`/api/datasets/${encodeURIComponent(e)}/pin`,{method:"POST",body:JSON.stringify({pinned:t})})},async removeDataset(e){await k(`/api/datasets/${encodeURIComponent(e)}`,{method:"DELETE"})},async stageDataset(e){return k("/api/datasets/stage",{method:"POST",body:JSON.stringify(e)})},async listNotebookResearch(e){var o,i,a,c,l,u,h,d,f,m,S,v,b,w,j,C,x,E,P,A;const t=new URLSearchParams;typeof e=="string"?e&&t.set("path",e):e&&(e.path&&t.set("path",e.path),e.sourceCellId&&t.set("sourceCellId",e.sourceCellId),e.domain&&t.set("domain",e.domain),e.owner&&t.set("owner",e.owner),e.intent&&t.set("intent",e.intent),e.search&&t.set("q",e.search),e.status&&t.set("status",e.status),e.reviewStatus&&t.set("reviewStatus",e.reviewStatus),e.promotionAction&&t.set("promotionAction",e.promotionAction),e.readiness&&t.set("readiness",e.readiness),e.age&&t.set("age",e.age),e.nextAction&&t.set("nextAction",e.nextAction),e.activeOnly&&t.set("activeOnly","true"),e.sort&&t.set("sort",e.sort),typeof e.limit=="number"&&t.set("limit",String(e.limit)),typeof e.offset=="number"&&t.set("offset",String(e.offset)));const n=t.toString()?`?${t.toString()}`:"",r=await k(`/api/notebook/research${n}`);return{runs:r.runs.map(Vt),total:typeof r.total=="number"?r.total:r.runs.length,domains:Array.isArray(r.domains)?r.domains.map(g=>({domain:typeof g.domain=="string"&&g.domain.trim()?g.domain:"uncategorized",total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],owners:Array.isArray(r.owners)?r.owners.map(g=>({owner:typeof g.owner=="string"&&g.owner.trim()?g.owner:"unassigned",total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],intents:Array.isArray(r.intents)?r.intents.map(g=>({intent:Sw(g.intent),total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],notebooks:Array.isArray(r.notebooks)?r.notebooks.map(g=>({path:typeof g.path=="string"&&g.path.trim()?g.path:"notebooks/untitled.dqlnb",title:typeof g.title=="string"&&g.title.trim()?g.title:ww(g.path),total:typeof g.total=="number"?g.total:0,draftReady:typeof g.draftReady=="number"?g.draftReady:0,certificationReady:typeof g.certificationReady=="number"?g.certificationReady:0,blocked:typeof g.blocked=="number"?g.blocked:0,staleOpen:typeof g.staleOpen=="number"?g.staleOpen:0,expiredOpen:typeof g.expiredOpen=="number"?g.expiredOpen:0,nextAction:Vo(g.nextAction),nextActionCount:typeof g.nextActionCount=="number"&&Number.isFinite(g.nextActionCount)?Math.max(0,Math.floor(g.nextActionCount)):void 0})):[],counts:{total:typeof((o=r.counts)==null?void 0:o.total)=="number"?r.counts.total:r.runs.length,ready:typeof((i=r.counts)==null?void 0:i.ready)=="number"?r.counts.ready:0,needsReview:typeof((a=r.counts)==null?void 0:a.needsReview)=="number"?r.counts.needsReview:0,dqlDrafts:typeof((c=r.counts)==null?void 0:c.dqlDrafts)=="number"?r.counts.dqlDrafts:0,errors:typeof((l=r.counts)==null?void 0:l.errors)=="number"?r.counts.errors:0,reuseExisting:typeof((u=r.counts)==null?void 0:u.reuseExisting)=="number"?r.counts.reuseExisting:0,extendExisting:typeof((h=r.counts)==null?void 0:h.extendExisting)=="number"?r.counts.extendExisting:0,replacements:typeof((d=r.counts)==null?void 0:d.replacements)=="number"?r.counts.replacements:0,createNew:typeof((f=r.counts)==null?void 0:f.createNew)=="number"?r.counts.createNew:0,draftReady:typeof((m=r.counts)==null?void 0:m.draftReady)=="number"?r.counts.draftReady:0,certificationReady:typeof((S=r.counts)==null?void 0:S.certificationReady)=="number"?r.counts.certificationReady:0,blocked:typeof((v=r.counts)==null?void 0:v.blocked)=="number"?r.counts.blocked:0,staleOpen:typeof((b=r.counts)==null?void 0:b.staleOpen)=="number"?r.counts.staleOpen:0,expiredOpen:typeof((w=r.counts)==null?void 0:w.expiredOpen)=="number"?r.counts.expiredOpen:0,sourceLinked:typeof((j=r.counts)==null?void 0:j.sourceLinked)=="number"?r.counts.sourceLinked:0,nextActions:kw((C=r.counts)==null?void 0:C.nextActions)},groupCounts:{domains:typeof((x=r.groupCounts)==null?void 0:x.domains)=="number"&&Number.isFinite(r.groupCounts.domains)?Math.max(0,Math.floor(r.groupCounts.domains)):Array.isArray(r.domains)?r.domains.length:0,owners:typeof((E=r.groupCounts)==null?void 0:E.owners)=="number"&&Number.isFinite(r.groupCounts.owners)?Math.max(0,Math.floor(r.groupCounts.owners)):Array.isArray(r.owners)?r.owners.length:0,intents:typeof((P=r.groupCounts)==null?void 0:P.intents)=="number"&&Number.isFinite(r.groupCounts.intents)?Math.max(0,Math.floor(r.groupCounts.intents)):Array.isArray(r.intents)?r.intents.length:0,notebooks:typeof((A=r.groupCounts)==null?void 0:A.notebooks)=="number"&&Number.isFinite(r.groupCounts.notebooks)?Math.max(0,Math.floor(r.groupCounts.notebooks)):Array.isArray(r.notebooks)?r.notebooks.length:0},reviewMetrics:xw(r.reviewMetrics),limit:r.limit,offset:typeof r.offset=="number"?r.offset:0}},async getNotebookResearchDiagnostics(){const e=await k("/api/notebook/research/diagnostics");return vw(e)},async createNotebookResearch(e){const t=await k("/api/notebook/research",{method:"POST",body:JSON.stringify(e)});return Vt(t.run)},async seedNotebookResearchFromCells(e){const t=await k("/api/notebook/research/seed-cells",{method:"POST",body:JSON.stringify(e)});return{created:Array.isArray(t.created)?t.created.map(Vt):[],createdCount:typeof t.createdCount=="number"?t.createdCount:Array.isArray(t.created)?t.created.length:0,skippedCount:typeof t.skippedCount=="number"?t.skippedCount:0,limitApplied:t.limitApplied===!0}},async listNotebookResearchSourceCoverage(e){const t=await k("/api/notebook/research/source-coverage",{method:"POST",body:JSON.stringify({path:e.path,sourceCellIds:e.sourceCellIds,sourceCells:e.sourceCells,limit:e.limit})});return{runs:Array.isArray(t.runs)?t.runs.map(Vt):[],requestedCount:typeof t.requestedCount=="number"?t.requestedCount:e.sourceCellIds.length,matchedCount:typeof t.matchedCount=="number"?t.matchedCount:Array.isArray(t.runs)?t.runs.length:0,limitApplied:t.limitApplied===!0}},async previewNotebookResearchContext(e){const t=await k("/api/notebook/research/context-preview",{method:"POST",body:JSON.stringify(e)});return jw(t)},async getNotebookResearch(e){const t=await k(`/api/notebook/research/${encodeURIComponent(e)}`);return Vt(t.run)},async updateNotebookResearch(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)});return Vt(n.run)},async runNotebookResearch(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/run`,{method:"POST",body:JSON.stringify(t??{})});return Vt(n.run)},async checkNotebookResearchReuse(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/reuse-check`,{method:"POST",body:JSON.stringify(t??{})});return{...n,run:Vt(n.run),promotion:Tp(n.promotion)??n.promotion}},async promoteNotebookResearchToDql(e,t){const n=await k(`/api/notebook/research/${encodeURIComponent(e)}/promote-dql`,{method:"POST",body:JSON.stringify(t??{})});return{...n,run:Vt(n.run)}},async getSchema(){try{const e=await fetch(`${Qr}/api/schema`,{headers:lr()});if(e.ok)return await e.json();const t=await e.json().catch(()=>null);return t!=null&&t.error&&console.warn(`[dql] schema introspection failed: ${t.error}`),(t==null?void 0:t.fallback)??[]}catch(e){return console.warn("[dql] getSchema request failed",e),[]}},async getConnections(){try{return await k("/api/connections")}catch{return{default:"unknown",connections:{}}}},async previewDbtProfiles(e){return k("/api/connections/dbt-profiles/preview",{method:"POST",body:JSON.stringify({path:e})})},async saveConnections(e,t){return k("/api/connections",{method:"PUT",body:JSON.stringify({connections:e,defaultConnectionName:t})})},async previewConnectionMetadataScope(e,t={}){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope/preview`,{method:"POST",body:JSON.stringify(t)})},async discoverConnectionMetadataScopes(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope/discovery`,{method:"POST"})},async getConnectionMetadataScope(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope`)},async applyConnectionMetadataScope(e,t){return k(`/api/connections/${encodeURIComponent(e)}/metadata-scope`,{method:"PUT",body:JSON.stringify(t)})},async refreshConnectionMetadata(e){return k(`/api/connections/${encodeURIComponent(e)}/metadata-sync`,{method:"POST"})},async installConnector(e){return k("/api/connectors/install",{method:"POST",body:JSON.stringify({driver:e})})},async testConnection(){try{return await k("/api/test-connection",{method:"POST",body:JSON.stringify({})})}catch(e){return{ok:!1,message:e.message??"Connection failed"}}},async getSemanticRuntimeSettings(){return k("/api/semantic-runtime")},async getMetricFlowInstallerStatus(){return k("/api/semantic-runtime/metricflow/installer")},async installMetricFlow(e){return k("/api/semantic-runtime/metricflow/install",{method:"POST",body:JSON.stringify(e?{adapter:e}:{})})},async testDbtCloudSemanticRuntime(e){try{return await k("/api/semantic-runtime/dbt-cloud/test",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:(t==null?void 0:t.message)??"dbt Cloud Semantic Layer test failed."}}},async applyDbtCloudSemanticRuntime(e){return k("/api/semantic-runtime/dbt-cloud/apply",{method:"POST",body:JSON.stringify(e)})},async setSemanticRuntimePreference(e){return k("/api/semantic-runtime/preference",{method:"POST",body:JSON.stringify({preference:e})})},async getSemanticLayer(){try{return await k("/api/semantic-layer")}catch{return{available:!1,provider:null,metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[],domains:[],tags:[],favorites:[],recentlyUsed:[],lastSyncTime:null}}},async getSemanticTree(){return(await k("/api/semantic-layer/tree")).tree},async getSemanticObject(e){return k(`/api/semantic-layer/object/${encodeURIComponent(e)}`)},async getSetupLaunch(){return k("/api/onboarding/launch")},async acknowledgeSetupLaunch(){return k("/api/onboarding/acknowledge",{method:"POST",body:"{}"})},async getOnboardingStatus(){return k("/api/onboarding/status")},async previewDbtOnboarding(e){return k("/api/onboarding/dbt/preview",{method:"POST",body:JSON.stringify(e)})},async applyDbtOnboarding(e){return k("/api/onboarding/dbt/apply",{method:"POST",body:JSON.stringify({...e,fingerprint:e.expectedFingerprint})})},async refreshDbtOnboarding(e={}){return k("/api/onboarding/refresh",{method:"POST",body:JSON.stringify(e)})},async getOnboardingJob(e){return k(`/api/onboarding/jobs/${encodeURIComponent(e)}`)},async cancelOnboardingJob(e){return k(`/api/onboarding/jobs/${encodeURIComponent(e)}`,{method:"DELETE"})},async discoverOnboardingDomains(e={}){return k("/api/onboarding/domains/discover",{method:"POST",body:JSON.stringify(e)})},async applyOnboardingDomains(e){return k("/api/onboarding/domains/apply",{method:"POST",body:JSON.stringify(e)})},async importSemanticLayer(e){return k("/api/semantic-layer/import",{method:"POST",body:JSON.stringify(e)})},async syncSemanticLayer(){return k("/api/semantic-layer/sync",{method:"POST",body:JSON.stringify({})})},async previewSemanticImport(e){return k("/api/semantic-layer/import-preview",{method:"POST",body:JSON.stringify(e)})},async previewSyncDiff(){return k("/api/semantic-layer/sync-preview",{method:"POST",body:JSON.stringify({})})},async searchSemanticLayer(e){const t=new URLSearchParams;e.query&&t.set("q",e.query),e.domain&&t.set("domain",e.domain),e.tag&&t.set("tag",e.tag),e.type&&t.set("type",e.type);try{return await k(`/api/semantic-layer/search?${t.toString()}`)}catch{return{metrics:[],measures:[],dimensions:[],timeDimensions:[],entities:[],hierarchies:[],semanticModels:[],savedQueries:[]}}},async getFavorites(){try{return(await k("/api/user-prefs/favorites")).favorites}catch{return[]}},async toggleFavorite(e){return(await k("/api/user-prefs/favorites",{method:"POST",body:JSON.stringify({name:e})})).favorites},async getRecentlyUsed(){try{return(await k("/api/user-prefs/recent")).recentlyUsed}catch{return[]}},async trackUsage(e){try{return(await k("/api/user-prefs/recent",{method:"POST",body:JSON.stringify({name:e})})).recentlyUsed}catch{return[]}},async getCompatibleDimensions(e){const t=new URLSearchParams;e.length>0&&t.set("metrics",e.join(","));try{return(await k(`/api/semantic-layer/compatible-dims?${t.toString()}`)).dimensions}catch{return[]}},async getCompatibility(e){const t=new URLSearchParams;e.length>0&&t.set("metrics",e.join(","));const n=await k(`/api/semantic-layer/compatible-dims?${t.toString()}`);return{dimensions:n.dimensions??[],engine:n.engine??"native",incompatible:n.incompatible??[],degraded:n.degraded??null}},async composeQuery(e,t,n){try{return await k("/api/semantic-query",{method:"POST",body:JSON.stringify({metrics:e,dimensions:t,timeDimension:n})})}catch(r){return{error:r.message??"Failed to compose query"}}},async previewSemanticBuilder(e){try{return await k("/api/semantic-builder/preview",{method:"POST",body:JSON.stringify(e)})}catch(t){return t instanceof St?{error:t.message,code:t.code,details:t.details}:{error:t instanceof Error?t.message:"Failed to preview semantic block"}}},async saveSemanticBuilder(e){return k("/api/semantic-builder/save",{method:"POST",body:JSON.stringify(e)})},async createMetric(e){try{return await k("/api/semantic-layer/metric",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t.message??"Failed to create metric"}}},async describeTable(e){const t=new URLSearchParams({relation:e});try{return await k(`/api/describe-table?${t.toString()}`)}catch{return[]}},async fetchLineage(){try{return await k("/api/lineage")}catch{return{nodes:[],edges:[]}}},async searchLineage(e){try{return await k(`/api/lineage/search?q=${encodeURIComponent(e)}`)}catch{return{matches:[]}}},async queryLineage(e){var n;const t=new URLSearchParams;e.focus&&t.set("focus",e.focus),e.search&&t.set("search",e.search),(n=e.types)!=null&&n.length&&t.set("types",e.types.join(",")),e.domain&&t.set("domain",e.domain),e.upstreamDepth!==void 0&&t.set("upstreamDepth",String(e.upstreamDepth)),e.downstreamDepth!==void 0&&t.set("downstreamDepth",String(e.downstreamDepth));try{return await k(`/api/lineage/query?${t.toString()}`)}catch{return{graph:{nodes:[],edges:[]},matches:[]}}},async fetchLineageNode(e){try{return await k(`/api/lineage/node/${encodeURIComponent(e)}`)}catch{return null}},async fetchBusiness360(e){try{return await k(`/api/lineage/business-360/${encodeURIComponent(e)}`)}catch{return null}},async fetchBlockLineage(e){try{return await k(`/api/lineage/block/${encodeURIComponent(e)}`)}catch{return null}},async fetchImpactAnalysis(e){try{return await k(`/api/lineage/impact/${encodeURIComponent(e)}`)}catch{return null}},async fetchLineagePaths(e,t){try{const n=new URLSearchParams;t!=null&&t.maxDepth&&n.set("maxDepth",String(t.maxDepth)),t!=null&&t.maxPaths&&n.set("maxPaths",String(t.maxPaths));const r=n.toString(),o=`/api/lineage/paths/${encodeURIComponent(e)}${r?`?${r}`:""}`;return await k(o)}catch{return null}},async fetchGitStatus(){try{return await k("/api/git/status")}catch{return{inRepo:!1,branch:null,ahead:0,behind:0,changes:[]}}},async fetchGitLog(e=20){try{return await k(`/api/git/log?limit=${e}`)}catch{return{inRepo:!1,commits:[]}}},async fetchRunSnapshot(e){try{return await k(`/api/run-snapshot?path=${encodeURIComponent(e)}`)}catch{return{found:!1,snapshot:null}}},async saveRunSnapshot(e,t){await k("/api/run-snapshot",{method:"PUT",body:JSON.stringify({path:e,snapshot:t})})},async fetchGitDiff(e,t){try{const n=new URLSearchParams;e&&n.set("path",e),t&&n.set("staged","true");const r=n.toString();return await k(`/api/git/diff${r?`?${r}`:""}`)}catch{return{inRepo:!1,diff:"",before:null,after:null,diffReport:null}}},async fetchGitBranches(){try{return await k("/api/git/branches")}catch{return{inRepo:!1,current:null,branches:[]}}},async fetchGitRemote(){try{return await k("/api/git/remote")}catch{return{inRepo:!1,url:null,name:null}}},async fetchGitGovernedContext(){try{return await k("/api/git/governed-context")}catch{return{inRepo:!1,trackingReady:!1,legacyBroadIgnore:!1,domains:Ko(),skills:Ko(),artifacts:Ko(),learning:Ko()}}},async enableGitGovernedContextTracking(){try{return await k("/api/git/governed-context/enable",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitStage(e){try{return await k("/api/git/stage",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitUnstage(e){try{return await k("/api/git/unstage",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitDiscard(e){try{return await k("/api/git/discard",{method:"POST",body:JSON.stringify({paths:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitCommit(e,t=!1){try{return await k("/api/git/commit",{method:"POST",body:JSON.stringify({message:e,stageAll:t})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async gitPush(){try{return await k("/api/git/push",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitPull(){try{return await k("/api/git/pull",{method:"POST",body:"{}"})}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},async gitCreateBranch(e,t=!0){try{return await k("/api/git/branch",{method:"POST",body:JSON.stringify({name:e,checkout:t})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async gitCreateReview(e){try{return await k("/api/git/review",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitOpenReview(e){try{return await k("/api/git/review/open",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async gitCheckout(e){try{return await k("/api/git/checkout",{method:"POST",body:JSON.stringify({name:e})})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async listApps(){try{const{apps:e}=await k("/api/apps");return e}catch{return[]}},async listAppsStrict(){const{apps:e}=await k("/api/apps");return e},async recommendAppBlocks(e,t){const{blocks:n}=await k("/api/apps/recommend-blocks",{method:"POST",body:JSON.stringify(e),signal:t});return n},async listAppSourceCandidates(e,t={},n){var i;const r=new URLSearchParams;(i=t.query)!=null&&i.trim()&&r.set("q",t.query.trim()),t.cursor&&r.set("cursor",t.cursor),r.set("limit",String(t.limit??50));for(const a of t.lifecycles??[])r.append("lifecycle",a);for(const a of t.domains??[])r.append("domain",a);t.includeDeprecated&&r.set("includeDeprecated","true");const o=await k(`/api/app-builds/${encodeURIComponent(e)}/source-candidates?${r.toString()}`,{signal:n});return{...o,items:o.items.map(Yc)}},async resolveAppSourceCandidates(e,t){const n=await k(`/api/app-builds/${encodeURIComponent(e)}/source-candidates`,{method:"POST",body:JSON.stringify({sourceIds:t})});return{...n,items:n.items.map(Yc)}},async createApp(e){return k("/api/apps",{method:"POST",body:JSON.stringify(e)})},async createAppBuild(e){return k("/api/app-builds",{method:"POST",body:JSON.stringify(e)})},async listAppBuilds(){return k("/api/app-builds")},async proposeAppBuildChanges(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals`,{method:"POST",body:JSON.stringify(t)})},async reviseAppBuildProposal(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals/${encodeURIComponent(t)}/revisions`,{method:"POST",body:JSON.stringify(n)})},async generateAppBuildGap(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/ai-proposals/${encodeURIComponent(t)}/gaps`,{method:"POST",body:JSON.stringify(n)})},async patchAppBuild(e,t,n,r){return k(`/api/app-builds/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify({expectedRevision:t,expectedProposalHash:r,operations:n})})},async composeAppBuild(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/compose`,{method:"POST",body:JSON.stringify(t)})},async addAskResultToAppBuild(e,t){return k(`/api/app-builds/${encodeURIComponent(e)}/ask-results`,{method:"POST",body:JSON.stringify(t)})},async preflightAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/preflight`,{method:"POST",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async publishAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/publish-to-project`,{method:"POST",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async deleteAppBuild(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({expectedRevision:t,proposalHash:n})})},async commitAppBuild(e,t,n){return this.publishAppBuild(e,t,n)},async generateApp(e){try{return await k("/api/apps/generate",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async createAppAiBuild(e){try{return await k("/api/apps/ai-builds",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async getAppAiBuild(e){try{const{session:t}=await k(`/api/apps/ai-builds/${encodeURIComponent(e)}`);return t}catch{return null}},async proposeAppAiBuild(e){try{return await k("/api/apps/ai-builds/propose",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async proposeAppAiBuildInBackground(e){return k("/api/apps/ai-builds/propose-background",{method:"POST",body:JSON.stringify(e)})},async commitAppAiBuild(e,t={}){try{return await k(`/api/apps/ai-builds/${encodeURIComponent(e)}/commit`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async getApp(e){try{return await k(`/api/apps/${encodeURIComponent(e)}`)}catch{return null}},async deleteApp(e,t){return k(`/api/apps/${encodeURIComponent(e)}`,{method:"DELETE",body:JSON.stringify({expectedFingerprint:t})})},async restoreApp(e){return k(`/api/app-recoveries/${encodeURIComponent(e)}/restore`,{method:"POST",body:"{}"})},async renameApp(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async attachAppNotebook(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/notebooks`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAppNotebookCandidates(e){try{const{notebooks:t}=await k(`/api/apps/${encodeURIComponent(e)}/notebook-candidates`);return t}catch{return[]}},async createAppNotebook(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/notebooks/create`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async previewAppNotebook(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/notebooks/preview?path=${encodeURIComponent(t)}`)}catch{return null}},async runAppNotebook(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/notebooks/run`,{method:"POST",body:JSON.stringify({path:t})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAppConversations(e){try{const{conversations:t}=await k(`/api/apps/${encodeURIComponent(e)}/conversations`);return t}catch{return[]}},async createAppConversation(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/conversations`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async getAppConversation(e,t){try{const{conversation:n}=await k(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`);return n}catch{return null}},async updateAppConversation(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(n)})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async deleteAppConversation(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/conversations/${encodeURIComponent(t)}`,{method:"DELETE"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAppInvestigations(e,t){try{const n=new URLSearchParams;t&&n.set("dashboardId",t);const r=n.toString(),{investigations:o}=await k(`/api/apps/${encodeURIComponent(e)}/investigations${r?`?${r}`:""}`);return o}catch{return[]}},async createAppInvestigation(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/investigations`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async getAppInvestigation(e,t){try{const{investigation:n}=await k(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}`);return n}catch{return null}},async runAppInvestigation(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify(n??{})})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async pinAppInvestigation(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/investigations/${encodeURIComponent(t)}/pin`,{method:"POST",body:JSON.stringify(n??{})})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async getDashboard(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}`)}catch{return null}},async dashboardFilterOptions(e,t){try{const n=new URLSearchParams({block:e,column:t});return await k(`/api/dashboard/filter-options?${n.toString()}`)}catch{return null}},async getAppEditorCatalog(e,t){try{const n=new URLSearchParams;t!=null&&t.domain&&n.set("domain",t.domain),(t==null?void 0:t.certifiedOnly)===!1&&n.set("certifiedOnly","false");const r=n.toString();return await k(`/api/apps/${encodeURIComponent(e)}/editor/catalog${r?`?${r}`:""}`)}catch{return null}},async createAppDashboard(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async patchDashboardLayout(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/layout`,{method:"PATCH",body:JSON.stringify({layout:n})})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async askApp(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/ask`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async publishAppToProject(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/publish-to-project`,{method:"POST",body:JSON.stringify(t??{})})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async promoteApp(e,t){return B.publishAppToProject(e,t)},async approveAppSemanticTiles(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/approve-semantic`,{method:"POST",body:JSON.stringify(n)})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async recommendVisualization(e){try{return await k("/api/visualizations/recommend",{method:"POST",body:JSON.stringify(e)})}catch(t){return{ok:!1,error:t instanceof Error?t.message:String(t)}}},async recommendDashboardTile(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/tiles/recommend`,{method:"POST",body:JSON.stringify(n)})}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async createAiPin(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/ai-pins`,{method:"POST",body:JSON.stringify(t)})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async listAiPins(e,t){try{const n=new URLSearchParams;t&&n.set("dashboardId",t);const r=n.toString(),{pins:o}=await k(`/api/apps/${encodeURIComponent(e)}/ai-pins${r?`?${r}`:""}`);return o}catch{return[]}},async refreshAiPin(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/ai-pins/${encodeURIComponent(t)}/refresh`,{method:"POST"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async promoteAiPin(e,t){try{return await k(`/api/apps/${encodeURIComponent(e)}/ai-pins/${encodeURIComponent(t)}/promote`,{method:"POST"})}catch(n){return{ok:!1,error:n instanceof Error?n.message:String(n)}}},async fetchScopedLineage(e){try{const t=new URLSearchParams;return e.domain&&t.set("domain",e.domain),e.appId&&t.set("appId",e.appId),e.dashboardId&&t.set("dashboardId",e.dashboardId),e.blockId&&t.set("blockId",e.blockId),await k(`/api/lineage/scope?${t.toString()}`)}catch{return null}},async runDashboard(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})}catch{return null}},async runAppBuildPreview(e,t,n){return k(`/api/app-builds/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:n??{}})})},async retryDashboardTile(e,t,n,r){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/run`,{method:"POST",body:JSON.stringify({variables:r??{},tileId:n})})}catch{return null}},async getDashboardStory(e,t,n){try{return await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}/story`,{method:"POST",body:JSON.stringify({runId:n})})}catch{return null}},async saveDashboard(e,t,n){try{return{ok:!!(await k(`/api/apps/${encodeURIComponent(e)}/dashboards/${encodeURIComponent(t)}`,{method:"PUT",body:JSON.stringify(n)})).ok}}catch(r){return{ok:!1,error:r instanceof Error?r.message:String(r)}}},async getPersona(){try{const{persona:e}=await k("/api/persona");return e}catch{return null}},async setPersona(e,t){try{const{persona:n}=await k("/api/persona",{method:"POST",body:JSON.stringify({userId:e,appId:t})});return n}catch{return null}},async clearPersona(){try{await k("/api/persona",{method:"DELETE"})}catch{}},async getSkills(){return k("/api/skills")},async getSkillPathSettings(){return k("/api/skills/settings")},async updateSkillPath(e){return k("/api/skills/settings",{method:"PUT",body:JSON.stringify({path:e})})},async getSkillOptions(e=""){const t=e.trim()?`?q=${encodeURIComponent(e.trim())}`:"";return k(`/api/skills/options${t}`)},async createSkill(e){return k("/api/skills",{method:"POST",body:JSON.stringify({skill:e})})},async updateSkill(e,t){return k(`/api/skills/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({skill:t})})},async getEmbeddingSettings(){return k("/api/settings/embeddings")},async saveEmbeddingSettings(e){return k("/api/settings/embeddings",{method:"PUT",body:JSON.stringify(e)})},async listEmbeddingModels(e){const t=e?`?endpoint=${encodeURIComponent(e)}`:"";return k(`/api/settings/embeddings/models${t}`)},async installEmbeddingModel(e,t){return k("/api/settings/embeddings/install",{method:"POST",body:JSON.stringify({model:e,endpoint:t})})},async testEmbeddingProvider(){return k("/api/settings/embeddings/test",{method:"POST"})},async reindexEmbeddings(){return k("/api/settings/embeddings/reindex",{method:"POST"})},async deleteSkill(e){return k(`/api/skills/${encodeURIComponent(e)}`,{method:"DELETE"})},async getDomains(){try{return await k("/api/domains")}catch{return{domains:[]}}},async createDomain(e){return k("/api/domains",{method:"POST",body:JSON.stringify({domain:e})})},async updateDomain(e,t){return k(`/api/domains/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify({domain:t})})},async deleteDomain(e){return k(`/api/domains/${encodeURIComponent(e)}`,{method:"DELETE"})},async startContextBootstrap(e={}){return k("/api/context-bootstrap",{method:"POST",body:JSON.stringify(e)})},async getContextBootstrap(e){return k(`/api/context-bootstrap/${encodeURIComponent(e)}`)},async getLatestContextBootstrap(){return(await k("/api/context-bootstrap/latest")).session??null},async saveContextBootstrapSelected(e,t){return k(`/api/context-bootstrap/${encodeURIComponent(e)}/save-selected`,{method:"POST",body:JSON.stringify({candidateIds:t})})}},Tw={source_table:"#8a8d96",dbt_model:"#4a74c9",dbt_source:"#4a74c9",term:"#0a6b5e",block:"#b26b1f",business_view:"#c14545",metric:"#6b5dd3",dimension:"#0a6b5e",domain:"#7c5cff",chart:"#c14590",notebook:"#2e8b57",dashboard:"#2e8b57",app:"#2e8b57"},Aw={source_table:"TBL",dbt_model:"DBT",dbt_source:"SRC",term:"TERM",block:"BLK",business_view:"VIEW",metric:"MET",dimension:"DIM",domain:"DOM",chart:"CHT",notebook:"NB",dashboard:"DASH",app:"APP"},Ap={source_table:"Source Table",dbt_model:"dbt Model",dbt_source:"dbt Source",term:"Business Term",block:"DQL Block",business_view:"Business View",metric:"Metric",dimension:"Dimension",domain:"Domain",chart:"Chart",notebook:"Notebook",dashboard:"Dashboard",app:"App"},Mj={reads_from:"#8b949e",feeds_into:"#56d364",defines:"#39c5cf",composes:"#f2cc60",aggregates:"#388bfd",visualizes:"#f778ba",depends_on:"#ff7b72",contains:"#d2a8ff",crosses_domain:"#d2a8ff",certified_by:"#56d364"},Lj={reads_from:"reads from",feeds_into:"feeds into",defines:"defines",composes:"composes into",aggregates:"aggregates into",visualizes:"visualizes",depends_on:"dbt depends on",contains:"contains",crosses_domain:"crosses domain",certified_by:"certified by"},Rw={source:"#79c0ff",transform:"#ff7b72",answer:"#56d364",consumption:"#d2a8ff"},Xc={source:"Sources",transform:"Transform",answer:"Answer",consumption:"Consumption"},Zc=["source","transform","answer","consumption"],Nj=["term","business_view","block","metric","dimension","domain","source_table","dbt_source","dbt_model","chart","notebook","dashboard","app"],Bj=["source_table","dbt_source","dbt_model"],Ow=["term","domain","business_view","metric","dimension","block"];[...Ow];function _w(e){if(e.layer)return e.layer;switch(e.type){case"source_table":case"dbt_source":return"source";case"dbt_model":return"transform";case"term":case"block":case"business_view":case"metric":case"dimension":case"domain":return"answer";case"chart":case"notebook":case"dashboard":case"app":return"consumption";default:return"answer"}}function Pw(){const{state:e,dispatch:t}=et(),n=e.inspectorContext;return s.jsxs("aside",{"aria-label":"Inspector",style:{width:320,borderLeft:`1px solid ${pe("borderSubtle")}`,background:pe("surfaceBase"),color:pe("textPrimary"),display:"flex",flexDirection:"column",overflow:"hidden",flexShrink:0},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:`${be[3]}px ${be[4]}px`,borderBottom:`1px solid ${pe("borderSubtle")}`},children:[s.jsx("div",{style:{fontSize:Ze.sm,fontWeight:Xi.semibold},children:n?Iw(n):"Inspector"}),s.jsx("button",{onClick:()=>t({type:"SET_INSPECTOR",open:!1}),"aria-label":"Close inspector",style:{background:"transparent",border:"none",color:pe("textMuted"),cursor:"pointer",fontSize:Ze.md,padding:2,borderRadius:wn.sm},children:"×"})]}),s.jsx("div",{style:{flex:1,overflow:"auto",padding:be[4]},children:n?s.jsx(Dw,{context:n}):s.jsx(Nw,{})})]})}function Iw(e){switch(e.kind){case"cell":return"Cell";case"lineage-node":return"Lineage node";case"metric":return"Metric"}}function Dw({context:e}){return e.kind==="cell"?s.jsx($w,{cellId:e.cellId}):e.kind==="lineage-node"?s.jsx(Mw,{nodeId:e.nodeId}):s.jsx(Lw,{name:e.name})}function $w({cellId:e}){const{state:t}=et(),n=t.cells.find(r=>r.id===e);return n?s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3],fontSize:Ze.sm},children:[s.jsx(Ie,{label:"Type",children:n.type}),s.jsx(Ie,{label:"ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:n.id})}),s.jsxs(Ie,{label:"Length",children:[n.content.length," chars"]}),n.status&&s.jsx(Ie,{label:"Status",children:n.status})]}):s.jsx(fs,{children:"No matching cell in the active notebook."})}function Mw({nodeId:e}){const[t,n]=p.useState(null),[r,o]=p.useState(!0);if(p.useEffect(()=>{let c=!1;return o(!0),B.fetchLineageNode(e).then(l=>{c||(n(l),o(!1))}).catch(()=>{c||o(!1)}),()=>{c=!0}},[e]),r)return s.jsx(fs,{children:"Loading node…"});if(!t||!t.node)return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Node ID",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)"},children:e})}),s.jsx(fs,{children:"No metadata available for this node."})]});const i=t.node,a=i.metadata??{};return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Name",children:i.name??e}),s.jsx(Ie,{label:"Type",children:Ap[i.type]??i.type}),i.domain&&s.jsx(Ie,{label:"Domain",children:i.domain}),i.owner&&s.jsx(Ie,{label:"Owner",children:i.owner}),i.status&&s.jsx(Ie,{label:"Status",children:i.status}),typeof a.termType=="string"&&s.jsx(Ie,{label:"Term Type",children:a.termType}),typeof a.description=="string"&&s.jsx(Ie,{label:"Description",children:a.description}),Array.isArray(a.identifiers)&&a.identifiers.length>0&&s.jsx(Ie,{label:"Identifiers",children:a.identifiers.map(String).join(", ")}),Array.isArray(a.synonyms)&&a.synonyms.length>0&&s.jsx(Ie,{label:"Synonyms",children:a.synonyms.map(String).join(", ")}),typeof a.businessOutcome=="string"&&s.jsx(Ie,{label:"Business Outcome",children:a.businessOutcome}),i.layer&&s.jsx(Ie,{label:"Layer",children:i.layer}),s.jsx(Ie,{label:"Upstream",children:t.incoming.length}),s.jsx(Ie,{label:"Downstream",children:t.outgoing.length}),(i.path||a.filePath)&&s.jsx(Ie,{label:"Path",children:s.jsx("code",{style:{fontFamily:"var(--dql-font-mono, monospace)",fontSize:Ze.xs},children:i.path??a.filePath})})]})}function Lw({name:e}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:be[3]},children:[s.jsx(Ie,{label:"Metric",children:e}),s.jsx(fs,{children:"Definition, dimensions, and governance surface will render here."})]})}function Ie({label:e,children:t}){return s.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2},children:[s.jsx("div",{style:{fontSize:Ze.xs,color:pe("textMuted"),textTransform:"uppercase",letterSpacing:.5,fontWeight:Xi.medium},children:e}),s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textPrimary")},children:t})]})}function fs({children:e}){return s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textSecondary"),lineHeight:1.5,background:pe("surfaceSunken"),border:`1px solid ${pe("borderSubtle")}`,borderRadius:wn.md,padding:be[3]},children:e})}function Nw(){return s.jsx("div",{style:{fontSize:Ze.sm,color:pe("textMuted"),lineHeight:1.5},children:"Select a cell, lineage node, or metric to inspect its details here."})}const Jr={appBg:"--color-bg-primary",sidebarBg:"--color-bg-secondary",activityBarBg:"--color-bg-sunken",headerBg:"--color-bg-toolbar",headerBorder:"--color-border-primary",cellBg:"--color-bg-card",cellBorder:"--color-border-subtle",cellBorderActive:"--color-accent-blue",cellBorderRunning:"--color-status-success",textPrimary:"--color-text-primary",textSecondary:"--color-text-secondary",textMuted:"--color-text-tertiary",editorBg:"--color-bg-surface",editorBorder:"--color-border-subtle",tableBorder:"--color-border-subtle",tableHeaderBg:"--color-bg-secondary",tableRowHover:"--color-bg-hover",accent:"--color-accent-blue",accentHover:"--color-accent-blue",success:"--color-status-success",error:"--color-status-error",warning:"--color-status-warning",btnBg:"--color-bg-tertiary",btnBorder:"--color-border-primary",btnHover:"--color-bg-hover",sidebarItemHover:"--color-bg-hover",sidebarItemActive:"--color-bg-active",scrollbarThumb:"--color-border-secondary",modalBg:"--color-bg-secondary",modalOverlay:"--color-bg-overlay",inputBg:"--color-bg-sunken",inputBorder:"--color-border-subtle",pillBg:"--color-bg-tertiary",font:"--font-ui",fontMono:"--font-mono",fontSerif:"--font-ui"},el={appBg:"#fbfaf7",sidebarBg:"#fbfaf7",activityBarBg:"#ffffff",headerBg:"#ffffff",headerBorder:"#e9e6e0",cellBg:"#ffffff",cellBorder:"#e9e6e0",cellBorderActive:"#6b5dd3",cellBorderRunning:"#2e8b57",textPrimary:"#1a1a1a",textSecondary:"#4a4a52",textMuted:"#8a8d96",editorBg:"#fbfaf7",editorBorder:"#e9e6e0",tableBorder:"#f0eee9",tableHeaderBg:"#faf9f7",tableRowHover:"#f3f0ea",accent:"#6b5dd3",accentHover:"#5c4fc2",success:"#2e8b57",error:"#c14545",warning:"#b26b1f",btnBg:"#ffffff",btnBorder:"#e9e6e0",btnHover:"#f3f0ea",sidebarItemHover:"#f3f0ea",sidebarItemActive:"#f3f0fb",scrollbarThumb:"#d9d5cc",modalBg:"#ffffff",modalOverlay:"rgba(26,26,26,0.40)",inputBg:"#fbfaf7",inputBorder:"#e9e6e0",pillBg:"#f3f0ea",font:"'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif",fontMono:"'JetBrains Mono', ui-monospace, 'SFMono-Regular', Menlo, Monaco, Consolas, monospace",fontSerif:"'Inter', -apple-system, BlinkMacSystemFont, sans-serif"};function tl(e){if(typeof document>"u")return el[e];const t=Jr[e];return getComputedStyle(document.documentElement).getPropertyValue(t).trim()||el[e]}function Bw(){return new Proxy({},{get(e,t){if(typeof t=="string"&&t in Jr)return tl(t)},has(e,t){return typeof t=="string"&&t in Jr},ownKeys(){return Object.keys(Jr)},getOwnPropertyDescriptor(e,t){if(!(typeof t!="string"||!(t in Jr)))return{enumerable:!0,configurable:!0,value:tl(t)}}})}const On=Bw(),Qe={obsidian:On,paper:On,white:On,dark:On,light:On,midnight:On,arctic:On};function Ct(e,t="0 0 24 24"){return function({size:r=16,strokeWidth:o=1.75,...i}){return s.jsx("svg",{width:r,height:r,viewBox:t,fill:"none",stroke:"currentColor",strokeWidth:o,strokeLinecap:"round",strokeLinejoin:"round",...i,children:e})}}const Fw=Ct(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"13",y:"3",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"3",y:"13",width:"8",height:"8",rx:"1.5"}),s.jsx("rect",{x:"13",y:"13",width:"8",height:"8",rx:"1.5"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M12 2l8 3v6c0 5-3.5 9-8 11-4.5-2-8-6-8-11V5l8-3z"}),s.jsx("path",{d:"M9 12l2 2 4-4"})]}));const zw=Ct(s.jsxs(s.Fragment,{children:[s.jsx("circle",{cx:"5",cy:"12",r:"2"}),s.jsx("circle",{cx:"19",cy:"5",r:"2"}),s.jsx("circle",{cx:"19",cy:"19",r:"2"}),s.jsx("path",{d:"M7 12l10-6M7 12l10 6"})]})),Fj=Ct(s.jsxs(s.Fragment,{children:[s.jsx("ellipse",{cx:"12",cy:"5",rx:"8",ry:"3"}),s.jsx("path",{d:"M4 5v6c0 1.66 3.58 3 8 3s8-1.34 8-3V5"}),s.jsx("path",{d:"M4 11v6c0 1.66 3.58 3 8 3s8-1.34 8-3v-6"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h8a8 8 0 010 16H4z"}),s.jsx("path",{d:"M16 20l4 4"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M3 3v18h18"}),s.jsx("path",{d:"M7 15l4-4 4 4 5-7"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),s.jsx("path",{d:"M3 9h18M9 3v18"})]}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),s.jsx("path",{d:"M8 12h8M12 8v8"})]}));const zj=Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 7h16M4 12h16M4 17h10"}),s.jsx("circle",{cx:"18",cy:"17",r:"2"})]}));Ct(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M3 5h18l-7 9v5l-4-2v-3L3 5z"})}));Ct(s.jsxs(s.Fragment,{children:[s.jsx("path",{d:"M4 4h10l6 6v10H4z"}),s.jsx("path",{d:"M14 4v6h6"}),s.jsx("path",{d:"M8 14l3 3 5-5"})]}));Ct(s.jsx(s.Fragment,{children:s.jsx("path",{d:"M21 12a8 8 0 01-11.5 7.2L4 21l1.8-5.5A8 8 0 1121 12z"})}));const Rp=44,Op=188,_p="dql-activitybar-expanded";function qw(){var e;if(typeof window>"u")return!1;try{return((e=window.localStorage)==null?void 0:e.getItem(_p))==="1"}catch{return!1}}function Uw(e){var t;try{(t=window.localStorage)==null||t.setItem(_p,e?"1":"0")}catch{}}function nl({title:e,icon:t,active:n,expanded:r,onClick:o,t:i}){const[a,c]=p.useState(!1),l=s.jsxs("button",{"aria-label":e,onClick:o,onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),style:{width:r?Op-12:Rp-8,height:32,display:"flex",alignItems:"center",justifyContent:r?"flex-start":"center",gap:10,padding:r?"0 10px":0,marginLeft:r?6:4,marginRight:r?6:4,background:n?i.accent+"1f":a?i.textPrimary+"0f":"transparent",border:"none",borderRadius:6,cursor:"pointer",color:n?i.accent:a?i.textPrimary:i.textSecondary,transition:"background 0.15s, color 0.15s",fontFamily:i.font,fontSize:13,fontWeight:n?500:400,textAlign:"left",overflow:"hidden",whiteSpace:"nowrap"},children:[s.jsx("span",{style:{display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,width:18,height:18},children:t}),r&&s.jsx("span",{style:{flex:1,textOverflow:"ellipsis",overflow:"hidden"},children:e})]});return r?l:s.jsx(Qd,{content:e,side:"right",children:l})}function Ww(){const e=Ge(Lr(l=>({mainView:l.mainView,sidebarOpen:l.sidebarOpen,sidebarPanel:l.sidebarPanel,themeMode:l.themeMode}))),t=jn(),n=Qe[e.themeMode],[r,o]=p.useState(qw);p.useEffect(()=>{Uw(r)},[r]);function i(l){if(l==="home"||l==="ask"||l==="modeling"){t({type:"SET_MAIN_VIEW",view:l});return}if(l==="lineage"){t({type:"SET_SIDEBAR_PANEL",panel:"lineage"});return}if(l==="connection"||l==="git"||l==="apps"||l==="readiness"||l==="skills"||l==="domains"||l==="settings"){t({type:"SET_SIDEBAR_PANEL",panel:l});return}e.sidebarPanel===l&&e.sidebarOpen?t({type:"TOGGLE_SIDEBAR"}):t({type:"SET_SIDEBAR_PANEL",panel:l})}const a=[{label:"Insights",items:[{key:"apps",title:"Apps",icon:s.jsx(wS,{size:16,strokeWidth:1.75}),active:e.mainView==="apps"},{key:"ask",title:"Ask",icon:s.jsx(hS,{size:16,strokeWidth:1.75}),active:e.mainView==="ask"}]},{label:"Build",items:[{key:"files",title:"Notebooks",icon:s.jsx(Pa,{size:16,strokeWidth:1.75}),active:e.sidebarPanel==="files"&&e.sidebarOpen},{key:"block_library",title:"Blocks",icon:s.jsx(Fw,{size:16}),active:e.sidebarPanel==="block_library"&&e.sidebarOpen},{key:"lineage",title:"Lineage",icon:s.jsx(zw,{size:16}),active:e.mainView==="lineage"||e.mainView==="lineage_detail"}]},{label:"Govern",items:[{key:"domains",title:"Modeling",icon:s.jsx(Fi,{size:16,strokeWidth:1.75}),active:e.mainView==="domains"||e.mainView==="modeling"||e.mainView==="skills"},{key:"git",title:"Source control",icon:s.jsx(Nr,{size:16,strokeWidth:1.75}),active:e.mainView==="git"},{key:"settings",title:"Settings",icon:s.jsx(MS,{size:16,strokeWidth:1.75}),active:e.mainView==="settings"||e.mainView==="connection"}]}],c=[{key:"help",title:"Help",icon:s.jsx(Rv,{size:16,strokeWidth:1.75}),active:e.mainView==="help",onClick:()=>t({type:"SET_MAIN_VIEW",view:"help"})}];return s.jsxs("div",{style:{width:r?Op:Rp,flexShrink:0,background:n.activityBarBg,borderRight:`1px solid ${n.headerBorder}`,display:"flex",flexDirection:"column",paddingTop:6,paddingBottom:6,gap:2,userSelect:"none",transition:"width 0.18s ease",overflow:"hidden"},children:[s.jsx("div",{style:{display:"flex",justifyContent:r?"flex-end":"center",paddingLeft:r?6:0,paddingRight:r?6:0,marginBottom:4},children:s.jsx(Qd,{content:r?"Collapse":"Expand",side:"right",children:s.jsx("button",{"aria-label":r?"Collapse sidebar rail":"Expand sidebar rail",onClick:()=>o(l=>!l),style:{width:28,height:26,display:"flex",alignItems:"center",justifyContent:"center",background:"transparent",border:"none",borderRadius:5,cursor:"pointer",color:n.textMuted,padding:0},onMouseEnter:l=>{l.currentTarget.style.color=n.textPrimary,l.currentTarget.style.background=n.textPrimary+"0f"},onMouseLeave:l=>{l.currentTarget.style.color=n.textMuted,l.currentTarget.style.background="transparent"},children:r?s.jsx(wv,{size:14,strokeWidth:2}):s.jsx(Cv,{size:14,strokeWidth:2})})})}),a.map((l,u)=>s.jsxs(qe.Fragment,{children:[u>0?s.jsx("div",{style:{height:1,margin:r?"8px 10px 2px":"8px 12px",background:n.headerBorder}}):null,r?s.jsx("div",{style:{fontSize:10,fontWeight:600,color:n.textMuted,letterSpacing:"0.04em",padding:"4px 12px 2px"},children:l.label}):null,l.items.map(h=>s.jsx(nl,{title:h.title,icon:h.icon,active:h.active,expanded:r,onClick:()=>i(h.key),t:n},h.key))]},l.label)),s.jsx("div",{style:{flex:1}}),c.map(l=>s.jsx(nl,{title:l.title,icon:l.icon,active:l.active,expanded:r,onClick:l.onClick,t:n},l.key))]})}const Kw=2e4,qj="application/dql-semantic-ref",rl=new Map;let po=null;function Vw(e){B.trackUsage(e),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:e}}))}async function ol(e,t){const n=`${e}:${t.toLowerCase()}`,r=rl.get(n);if(r&&Date.now()<r.expiresAt)return r.items;const o=new URLSearchParams({kind:e,q:t,limit:"50"}),i=await fetch(`${window.location.origin}/api/editor/completions?${o.toString()}`);if(!i.ok)throw new Error(`Failed to load semantic completions: HTTP ${i.status}`);const a=await i.json(),c=Array.isArray(a.completions)?a.completions:[];return rl.set(n,{items:c,expiresAt:Date.now()+Kw}),c}function Pp(e,t,n){const r=n??e.state.selection.main.from;e.dispatch({changes:{from:r,to:n??e.state.selection.main.to,insert:t},selection:{anchor:r+t.length}}),e.focus()}function Uj(e){po=e}function Wj(e){po===e&&(po=null)}function Hw(e){return po?(Pp(po,e),!0):!1}function Kj(e,t,n){const r=n?e.posAtCoords(n)??e.state.selection.main.from:e.state.selection.main.from;Pp(e,t,r)}function sl(e,t,n){return{label:e.name,detail:e.type==="metric"?"@metric":"@dim",type:e.type==="metric"?"function":"variable",info:`${e.label}${e.description?`
|
|
397
397
|
${e.description}`:""}${e.sql?`
|
|
398
398
|
${e.sql}`:""}`,apply(r){const i=r.state.sliceDoc(n,n+1)===")"?e.name:`${e.name})`;r.dispatch({changes:{from:t,to:n,insert:i},selection:{anchor:t+i.length}}),Vw(e.name)}}}function Gw(e){return{from:e,options:[{label:"@metric(",detail:"semantic metric",type:"function",apply(t,n,r,o){t.dispatch({changes:{from:r,to:o,insert:"@metric("},selection:{anchor:r+8}})}},{label:"@dim(",detail:"semantic dimension",type:"function",apply(t,n,r,o){t.dispatch({changes:{from:r,to:o,insert:"@dim("},selection:{anchor:r+5}})}}]}}const Vj=async e=>{const{state:t,pos:n}=e,r=t.sliceDoc(Math.max(0,n-120),n),o=/@metric\(([^)]*)$/i.exec(r);if(o){const c=o[1].trim().toLowerCase(),l=n-o[1].length,u=await ol("metric",c);return{from:l,options:u.map(h=>sl(h,l,n)),validFor:/^[\w-]*$/}}const i=/@dim\(([^)]*)$/i.exec(r);if(i){const c=i[1].trim().toLowerCase(),l=n-i[1].length,u=await ol("dimension",c);return{from:l,options:u.map(h=>sl(h,l,n)),validFor:/^[\w-]*$/}}const a=/@([md][a-z_]*)?$/i.exec(r);return a?Gw(n-a[0].length):(e.explicit,null)};function Hj(e){if(!e)return null;try{const t=JSON.parse(e);return(t.type==="metric"||t.type==="dimension")&&t.name&&t.reference?{type:t.type,name:t.name,reference:t.reference}:null}catch{return null}}const Qw=6,Jw=999,Yw={xs:{height:22,fontSize:10.5,paddingX:7,gap:4,icon:11},sm:{height:26,fontSize:11.5,paddingX:9,gap:5,icon:12},md:{height:32,fontSize:12.5,paddingX:12,gap:6,icon:14},lg:{height:54,fontSize:12.5,paddingX:17,gap:7,icon:15}};function Re(e,t={}){const{variant:n="secondary",size:r="sm",active:o=!1,disabled:i=!1,pill:a=!1}=t,c=Yw[r],l=n==="danger"?e.error:n==="success"?e.success:n==="accent"?e.accent:void 0,u={boxSizing:"border-box",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:c.gap,height:c.height,padding:`0 ${c.paddingX}px`,borderRadius:a?Jw:Qw,fontSize:c.fontSize,fontWeight:n==="primary"?700:600,fontFamily:e.font,lineHeight:1,whiteSpace:"nowrap",cursor:i?"not-allowed":"pointer",opacity:i?.55:1,transition:"background 0.15s, border-color 0.15s, color 0.15s"};return n==="primary"?{...u,background:e.accent,border:`1px solid ${e.accent}`,color:"#ffffff"}:n==="ghost"?{...u,background:o?`${e.accent}14`:"transparent",border:"1px solid transparent",color:o?e.accent:e.textMuted,fontWeight:550}:l?{...u,background:o?`${l}22`:`${l}12`,border:`1px solid ${l}${o?"66":"33"}`,color:l}:{...u,background:o?`${e.accent}14`:e.btnBg,border:`1px solid ${o?e.accent:e.btnBorder}`,color:o?e.accent:e.textSecondary}}const Xw=new Set(["metric","measure","dimension","time_dimension"]);function Ds(e){var r;if(typeof((r=e.meta)==null?void 0:r.reference)=="string"&&e.meta.reference.trim())return e.meta.reference;const t=`${e.kind}:`;if(e.id.startsWith(t))return e.id.slice(t.length);const n=e.id.lastIndexOf(":");return n>=0?e.id.slice(n+1):e.id}function Wi(e){const t=Ds(e);return e.kind==="metric"||e.kind==="measure"?`@metric(${t})`:`@dim(${t})`}function Ip(e){var r,o;const t=typeof((r=e.meta)==null?void 0:r.qualifiedName)=="string"?e.meta.qualifiedName.trim():"";return t||(typeof((o=e.meta)==null?void 0:o.localName)=="string"?e.meta.localName.trim():"")||Ds(e)}function Ia(e,t){return!t||e.label.toLowerCase().includes(t)||e.id.toLowerCase().includes(t)||Ds(e).toLowerCase().includes(t)||Ip(e).toLowerCase().includes(t)?!0:(e.children??[]).some(n=>Ia(n,t))}function Dp(e){var r;const t=[],n=new Map;for(const o of e){const i=(((r=o.children)==null?void 0:r.length)??0)>0,a=i?`group:${o.label.toLowerCase()}`:`leaf:${Wi(o).toLowerCase()}`,c=n.get(a);if(c){i&&c.children&&(c.children=c.children.concat(o.children??[]));continue}const l=o.children?{...o,children:[...o.children]}:o;n.set(a,l),t.push(l)}for(const o of t)o.children&&(o.children=Dp(o.children));return t}const Ys={metric:{Icon:rS,tone:e=>e.accent},measure:{Icon:qS,tone:e=>e.accent},dimension:{Icon:HS,tone:e=>e.success},time_dimension:{Icon:_v,tone:e=>e.warning},entity:{Icon:fv,tone:e=>e.textSecondary},segment:{Icon:tS,tone:e=>e.textMuted},hierarchy:{Icon:Nr,tone:e=>e.textMuted},pre_aggregation:{Icon:bp,tone:e=>e.textMuted},cube:{Icon:Fi,tone:e=>e.textSecondary},semantic_model:{Icon:Fi,tone:e=>e.textSecondary},saved_query:{Icon:uv,tone:e=>e.textMuted},provider:{Icon:ro,tone:e=>e.textMuted},domain:{Icon:ro,tone:e=>e.textMuted},group:{Icon:ro,tone:e=>e.textMuted}};function Zw(e){var t;if(e.kind==="group"){const n=typeof((t=e.meta)==null?void 0:t.objectKind)=="string"?e.meta.objectKind:"";return Ys[n]??Ys.group}return Ys[e.kind]}function e0({tree:e,themeMode:t,search:n="",onInsert:r,selectionMode:o=!1,selected:i=new Set,onToggleSelection:a,canSelect:c=()=>({allowed:!0})}){const l=Qe[t],u=n.trim().toLowerCase(),h=Dp(e.children??[]).filter(d=>Ia(d,u));return h.length===0?s.jsx("div",{style:{padding:"16px 12px",fontSize:11.5,color:l.textMuted,textAlign:"center"},children:u?"No matches.":"No semantic objects."}):s.jsx(s.Fragment,{children:h.map(d=>s.jsx($p,{node:d,t:l,q:u,onInsert:r,depth:0,selectionMode:o,selected:i,onToggleSelection:a,canSelect:c},d.id))})}function $p({node:e,t,q:n,onInsert:r,depth:o,selectionMode:i,selected:a,onToggleSelection:c,canSelect:l}){var A;const u=(((A=e.children)==null?void 0:A.length)??0)>0,[h,d]=p.useState(o<1||!!n);p.useEffect(()=>{n&&d(!0)},[n]);const f=Xw.has(e.kind),m=Zw(e),S=m==null?void 0:m.Icon,v=10+o*13,b=e.kind==="metric"||e.kind==="measure"?"metric":e.kind==="dimension"||e.kind==="time_dimension"?"dimension":null,w=Ds(e),j=Ip(e),C=w!==j?` · DQL ${w}`:"",x=b?`${b}:${w}`:"",E=b?l(b,w):{allowed:!1};if(!u)return s.jsx("div",{style:{display:"flex",alignItems:"center",width:"100%",minWidth:0,borderBottom:`1px solid ${t.cellBorder}`},children:s.jsxs("button",{type:"button",onClick:()=>{i&&b&&E.allowed?c==null||c(b,w):!i&&f&&r(Wi(e))},disabled:i&&!!b&&!E.allowed,title:i&&b?E.allowed?`Select ${e.label} · dbt ${j}${C}`:E.reason||"Not compatible with the current selection":f?`Insert ${Wi(e)} · dbt ${j}${C}`:e.label,style:{display:"flex",alignItems:"center",gap:7,flex:1,minWidth:0,boxSizing:"border-box",padding:`5px 6px 5px ${v+15}px`,border:"none",background:"transparent",cursor:i&&b?E.allowed?"pointer":"not-allowed":f?"pointer":"default",textAlign:"left",fontFamily:t.font,color:E.allowed||!b?t.textPrimary:t.textMuted,opacity:i&&b&&!E.allowed?.55:1},children:[i&&b&&s.jsx("input",{type:"checkbox",readOnly:!0,checked:a.has(x),disabled:!E.allowed,style:{accentColor:t.accent,margin:0,flexShrink:0}}),S&&s.jsx(S,{size:13,color:m.tone(t),style:{flexShrink:0}}),s.jsxs("span",{style:{flex:1,minWidth:0,display:"grid",gap:1,overflow:"hidden"},children:[s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:11.5},children:e.label}),j!==e.label?s.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:9.5,fontFamily:t.fontMono,color:t.textMuted},children:j}):null]})]})});const P=(e.children??[]).filter(g=>Ia(g,n));return s.jsxs("div",{children:[s.jsxs("button",{type:"button",onClick:()=>d(g=>!g),style:{display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,boxSizing:"border-box",padding:`6px 10px 6px ${v}px`,border:"none",borderBottom:`1px solid ${t.cellBorder}`,background:"transparent",cursor:"pointer",textAlign:"left",fontFamily:t.font,color:t.textPrimary},children:[h?s.jsx(_a,{size:13,color:t.textMuted,style:{flexShrink:0}}):s.jsx(Is,{size:13,color:t.textMuted,style:{flexShrink:0}}),S&&s.jsx(S,{size:13,color:m.tone(t),style:{flexShrink:0}}),s.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:12,fontWeight:600},children:e.label}),s.jsx("span",{style:{fontSize:10,color:t.textMuted,flexShrink:0},children:e.count??P.length})]}),h&&P.map(g=>s.jsx($p,{node:g,t,q:n,onInsert:r,depth:o+1,selectionMode:i,selected:a,onToggleSelection:c,canSelect:l},g.id))]})}function qt(e){return(e==null?void 0:e.trim())??""}function Jn(e){const t=new Map;for(const r of e){const o=qt(r.id);o&&!t.has(o)&&t.set(o,{...r,id:o})}const n=r=>{const o=[qt(r.name)||r.id],i=new Set([r.id]);let a=qt(r.parent);for(;a&&!i.has(a);){i.add(a);const c=t.get(a);if(!c)break;o.unshift(qt(c.name)||c.id),a=qt(c.parent)}return o.join(" / ")};return[...t.values()].map(r=>({value:r.id,label:n(r)})).sort((r,o)=>r.label.localeCompare(o.label))}function Gj(e,t){const n=Jn(t),r=qt(e??void 0);return!r||n.some(o=>o.value===r)?n:[{value:r,label:`${r} (missing Domain page)`,disabled:!0},...n]}function Ao(e){return new Set(Jn(e).map(t=>t.value))}function Qj(e,t){const n=qt(e??void 0).toLowerCase();if(!n)return"";const r=t.find(o=>qt(o.id).toLowerCase()===n||qt(o.name).toLowerCase()===n);return qt(r==null?void 0:r.id)}function t0(e,t){const n=Ao(t),r=e.some(o=>{var i;return!n.has(((i=o.domain)==null?void 0:i.trim())??"")});return[...Jn(t).map(o=>o.value),...r?["uncategorized"]:[]]}function n0(e,t,n="",r=[]){const o=n.trim().toLowerCase(),i=Ao(r);return Array.from(new Map(e.map(a=>[a.path,a])).values()).filter(a=>{var l;const c=((l=a.domain)==null?void 0:l.trim())??"";return t==="uncategorized"&&i.has(c)||t&&t!=="uncategorized"&&(!i.has(t)||c!==t)?!1:!o||a.name.toLowerCase().includes(o)||(a.description??"").toLowerCase().includes(o)})}var Q;(function(e){e.Program="Program",e.Workbook="Workbook",e.Page="Page",e.Dashboard="Dashboard",e.ChartCall="ChartCall",e.FilterCall="FilterCall",e.VariableDecl="VariableDecl",e.ParamDecl="ParamDecl",e.ImportDecl="ImportDecl",e.UseDecl="UseDecl",e.LayoutBlock="LayoutBlock",e.LayoutRow="LayoutRow",e.Decorator="Decorator",e.SQLQuery="SQLQuery",e.NamedArg="NamedArg",e.StringLiteral="StringLiteral",e.NumberLiteral="NumberLiteral",e.BooleanLiteral="BooleanLiteral",e.ArrayLiteral="ArrayLiteral",e.Identifier="Identifier",e.BinaryExpr="BinaryExpr",e.IntervalExpr="IntervalExpr",e.FunctionCall="FunctionCall",e.TemplateString="TemplateString",e.BlockDecl="BlockDecl",e.DomainDecl="DomainDecl",e.TermDecl="TermDecl",e.BusinessViewDecl="BusinessViewDecl",e.BusinessViewInclude="BusinessViewInclude",e.BlockParams="BlockParams",e.BlockVisualization="BlockVisualization",e.BlockTest="BlockTest",e.Digest="Digest",e.Narrative="Narrative"})(Q||(Q={}));var dr;(function(e){e.Error="error",e.Warning="warning",e.Info="info"})(dr||(dr={}));class r0{constructor(){Pe(this,"diagnostics",[])}report(t){this.diagnostics.push(t)}error(t,n,r){this.report({severity:dr.Error,message:t,span:n,hint:r})}warning(t,n,r){this.report({severity:dr.Warning,message:t,span:n,hint:r})}hasErrors(){return this.diagnostics.some(t=>t.severity===dr.Error)}getErrors(){return this.diagnostics.filter(t=>t.severity===dr.Error)}getAll(){return[...this.diagnostics]}clear(){this.diagnostics=[]}format(t){return this.diagnostics.map(n=>o0(n,t)).join(`
|
|
399
399
|
|
|
@@ -607,7 +607,7 @@ ${t}`;return r.replace(/\n\}\s*$/,`${o}
|
|
|
607
607
|
</div>
|
|
608
608
|
<p class="exported-by">Built with DQL Workbench</p>
|
|
609
609
|
</body>
|
|
610
|
-
</html>`}function hC(e,t){const n=fC(e,t),r=new Blob([n],{type:"text/html;charset=utf-8"}),o=URL.createObjectURL(r),i=document.createElement("a");i.href=o,i.download=`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-dashboard.html`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}const mC=new Set(["succeeded","failed","cancelled","interrupted"]);function Ir(e){return mC.has(e.status)}function gC(e,t){if(e.id!==t.id)return t;const n=Ir(e),r=Ir(t);return n&&!r||t.updatedAt<e.updatedAt?e:t.updatedAt>e.updatedAt?t:n!==r?r?t:e:t.progress!==e.progress?t.progress>e.progress?t:e:t}function eo(e,t){const n=e.find(o=>o.id===t.id),r=n?gC(n,t):t;return kC([...e.filter(o=>o.id!==t.id),r])}function yC(e,t){return t.reduce(eo,e)}function bC(e){return e.filter(t=>!Ir(t)).map(t=>t.id)}function xC(e,t){for(const n of bC(t))e.add(n)}async function vC(e,t,n){await Promise.all([...e].map(async r=>{try{const o=await t(r);if(n(o)===!1)return;Ir(o)&&e.delete(r)}catch{}}))}function SC(e,t=new Set){return e.filter(n=>n.type==="block_certification"&&n.status==="succeeded").filter(n=>!t.has(n.id)).filter(n=>{const r=n.result;return!!(r!=null&&r.block&&r.outcome)}).sort((n,r)=>n.updatedAt.localeCompare(r.updatedAt)||n.createdAt.localeCompare(r.createdAt)||n.id.localeCompare(r.id))}function fE(e,t){var o;if(t.operationId){const i=e.find(a=>a.type==="block_certification"&&a.id===t.operationId);if(i)return i}const n=Vr(t.activePath),r=(o=t.sourceFingerprint)==null?void 0:o.trim();return e.filter(i=>i.type==="block_certification").filter(i=>{const a=wC(i),c=[Vr(i.scope.startsWith("block:")?i.scope.slice(6):void 0),Vr(a==null?void 0:a.oldPath),Vr(a==null?void 0:a.draftPath),Vr(a==null?void 0:a.newPath)].filter(h=>!!h),l=!!(n&&c.includes(n)),u=!!(r&&i.resourceRevision&&(i.resourceRevision===r||i.resourceRevision.startsWith(`${r}:`)));return l||u}).sort((i,a)=>a.updatedAt.localeCompare(i.updatedAt)||a.createdAt.localeCompare(i.createdAt))[0]}function wC(e){return e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:void 0}function Vr(e){if(!(typeof e!="string"||!e.trim()))return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function kC(e,t=50){let n=0;return[...e].sort((r,o)=>o.updatedAt.localeCompare(r.updatedAt)||o.createdAt.localeCompare(r.createdAt)||o.id.localeCompare(r.id)).filter(r=>Ir(r)?(n+=1,n<=t):!0)}const ir=["local-operations"],pf=p.createContext(null);function CC({children:e}){const t=Yi(),n=p.useRef(new Set),r=p.useRef(new Set),o=Ge(l=>l.dispatch),i=Ri({queryKey:ir,queryFn:async()=>{const l=(await B.listOperations(50)).operations,u=t.getQueryData(ir)??[];return yC(u,l)},staleTime:15e3,refetchOnWindowFocus:!1,refetchInterval:1500}),a=i.data??[];p.useEffect(()=>{let l=!0,u,h;const d=()=>{h=new AbortController,Ep("/api/operations/events",f=>{if(f.event==="operation")try{const m=JSON.parse(f.data);t.setQueryData(ir,(S=[])=>eo(S,m))}catch{}},h.signal).catch(()=>{!l||h!=null&&h.signal.aborted||(u=setTimeout(d,5e3))})};return d(),()=>{l=!1,u&&clearTimeout(u),h==null||h.abort()}},[t]),p.useEffect(()=>{xC(r.current,a)},[a]),p.useEffect(()=>{let l=!0,u=!1;const h=async()=>{if(!(u||r.current.size===0)){u=!0;try{await vC(r.current,f=>B.getOperation(f),f=>{if(!l)return!1;t.setQueryData(ir,(m=[])=>eo(m,f))})}finally{u=!1}}};h();const d=window.setInterval(()=>void h(),1e3);return()=>{l=!1,window.clearInterval(d)}},[t]),p.useEffect(()=>{for(const l of SC(a,n.current)){const u=l.result;n.current.add(l.id),o({type:"RECONCILE_BLOCK_CERTIFICATION",outcome:u.outcome,oldPath:u.oldPath,draftPath:u.draftPath,newPath:u.newPath,payload:u.block}),window.dispatchEvent(new CustomEvent("dql:block-library-invalidated",{detail:{operationId:l.id,outcome:u.outcome}}))}},[o,a]);const c=p.useMemo(()=>({operations:a,activeCount:a.filter(l=>l.status==="queued"||l.status==="running").length,loading:i.isLoading,cancel:async l=>{const u=await B.cancelOperation(l);r.current.delete(l),t.setQueryData(ir,(h=[])=>eo(h,u))},track:l=>{Ir(l)?r.current.delete(l.id):r.current.add(l.id),t.setQueryData(ir,(u=[])=>eo(u,l))}}),[a,i.isLoading,t]);return s.jsx(pf.Provider,{value:c,children:e})}function jC(){const e=p.useContext(pf);if(!e)throw new Error("useOperations must be used inside OperationsProvider.");return e}const EC=new Set(["succeeded","failed","cancelled","interrupted"]);function TC(e,t=8){const n=AC(e).filter(o=>!EC.has(o.status)||o.type!=="project_refresh"),r=n.map(ff);return{operations:n.slice(0,t),activeCount:r.filter(o=>o.active).length,attentionCount:r.filter(o=>o.tone==="attention").length}}function AC(e){const t=e.filter(l=>l.type==="block_certification"),n=t.map((l,u)=>u),r=new Map,o=l=>{let u=l;for(;n[u]!==u;)n[u]=n[n[u]],u=n[u];return u},i=(l,u)=>{const h=o(l),d=o(u);h!==d&&(n[d]=h)};t.forEach((l,u)=>{for(const h of RC(l)){const d=r.get(h);d===void 0?r.set(h,u):i(u,d)}});const a=new Map;t.forEach((l,u)=>{const h=o(u),d=a.get(h);(!d||OC(l,d)<0)&&a.set(h,l)});const c=new Set([...a.values()].map(l=>l.id));return e.filter(l=>l.type!=="block_certification"||c.has(l.id))}function ff(e){var n,r,o,i,a,c;if(e.status==="queued"||e.status==="running")return{active:!0,tone:"active",statusLabel:e.status,message:e.message,guidance:e.type==="block_certification"?"You can change pages while certification continues.":void 0};if(e.type==="block_certification"&&e.status==="succeeded"){const l=e.result;if((l==null?void 0:l.outcome)==="draft_saved_with_blockers"){const u=((r=(n=l.checklist)==null?void 0:n.issues)==null?void 0:r.length)??((o=l.blockers)==null?void 0:o.length)??((i=l.checklist)==null?void 0:i.blockers.length)??0;return{active:!1,tone:"attention",statusLabel:"needs attention",message:u>0?`Draft saved with ${u} certification blocker${u===1?"":"s"}.`:"Draft saved, but certification requirements are not ready.",guidance:"Open Block Studio to review the exact fixes and retry."}}if((l==null?void 0:l.outcome)==="certified")return{active:!1,tone:"success",statusLabel:"certified",message:"The block passed its required gates and was certified."}}return e.status==="failed"||e.status==="interrupted"?{active:!1,tone:"failure",statusLabel:e.status,message:((a=e.error)==null?void 0:a.message)??e.message,guidance:e.type==="block_certification"?"The saved draft is preserved for review or retry.":void 0}:e.status==="cancelled"?{active:!1,tone:"neutral",statusLabel:"cancelled",message:e.message}:{active:!1,tone:e.status==="succeeded"?"success":"neutral",statusLabel:e.status,message:((c=e.error)==null?void 0:c.message)??e.message}}function RC(e){const t=hi(e.result),n=hi(t==null?void 0:t.block),r=hi(n==null?void 0:n.metadata),o=e.scope.startsWith("block:")?e.scope.slice(6):void 0;return Array.from(new Set([ar(n==null?void 0:n.path),ar(r==null?void 0:r.path),ar(t==null?void 0:t.oldPath),ar(t==null?void 0:t.draftPath),ar(t==null?void 0:t.newPath),ar(o)].filter(i=>!!i)))}function hi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ar(e){if(!(typeof e!="string"||!e.trim()))return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function OC(e,t){return t.createdAt.localeCompare(e.createdAt)||t.updatedAt.localeCompare(e.updatedAt)||t.id.localeCompare(e.id)}function _C(){const e=Ge(d=>d.themeMode),t=Qe[e],{operations:n,loading:r,cancel:o}=jC(),[i,a]=p.useState(!1),c=p.useRef(null),{operations:l,activeCount:u,attentionCount:h}=TC(n);return p.useEffect(()=>{if(!i)return;const d=m=>{c.current&&!c.current.contains(m.target)&&a(!1)},f=m=>{m.key==="Escape"&&a(!1)};return document.addEventListener("mousedown",d),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",f)}},[i]),!r&&l.length===0?null:s.jsxs("div",{ref:c,style:{position:"relative"},children:[s.jsxs("button",{type:"button","aria-label":"Background tasks","aria-expanded":i,onClick:()=>a(d=>!d),style:{height:28,padding:"0 9px",borderRadius:6,border:`1px solid ${u>0?t.accent:h>0?t.warning:t.btnBorder}`,background:i?t.btnHover:t.btnBg,color:t.textSecondary,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:6,fontFamily:t.font,fontSize:11,fontWeight:600},children:[s.jsx("span",{"aria-hidden":"true",style:{width:7,height:7,borderRadius:999,background:u>0?t.accent:h>0?t.warning:t.success,boxShadow:u>0?`0 0 0 3px ${t.accent}20`:"none"}}),u>0?`${u} running`:h>0?`${h} needs attention`:"Tasks"]}),i&&s.jsxs("div",{role:"dialog","aria-label":"Background tasks",style:{position:"absolute",top:34,right:0,zIndex:1200,width:340,maxHeight:420,overflowY:"auto",background:t.modalBg,border:`1px solid ${t.cellBorder}`,borderRadius:9,boxShadow:"0 14px 36px rgba(0,0,0,0.28)",padding:8},children:[s.jsx("div",{style:{padding:"4px 6px 8px",color:t.textPrimary,fontSize:12,fontWeight:700},children:"Background tasks"}),l.map(d=>{const f=ff(d),m=f.active,S=f.tone==="failure"?t.error:f.tone==="attention"?t.warning:f.tone==="success"?t.success:t.textMuted;return s.jsxs("div",{style:{padding:"9px 8px",borderTop:`1px solid ${t.headerBorder}`,display:"flex",flexDirection:"column",gap:6},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("span",{style:{flex:1,color:t.textPrimary,fontSize:11.5,fontWeight:650},children:PC(d.type)}),s.jsx("span",{style:{color:S,fontSize:10},children:f.statusLabel})]}),s.jsx("div",{style:{color:f.tone==="failure"?t.error:f.tone==="attention"?t.warning:t.textSecondary,fontSize:10.5,lineHeight:1.4},children:f.message}),m&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("div",{style:{flex:1,height:3,borderRadius:99,overflow:"hidden",background:t.headerBorder},children:s.jsx("div",{style:{width:`${Math.max(3,d.progress)}%`,height:"100%",background:t.accent,transition:"width 180ms ease"}})}),d.cancellable&&s.jsx("button",{type:"button",onClick:()=>void o(d.id),style:{border:0,background:"transparent",color:t.textMuted,cursor:"pointer",fontSize:10,padding:0},children:"Cancel"})]}),d.type==="block_certification"&&s.jsx("div",{style:{color:t.textMuted,fontSize:9.5},children:f.guidance??(f.tone==="success"?"Certification is complete.":"The saved draft is preserved for review or retry.")}),(d.type==="agent_run"||d.type==="app_ai_build")&&s.jsx("div",{style:{color:t.textMuted,fontSize:9.5},children:m?"This continues while you work on another page.":d.status==="succeeded"?"Completed in the background.":"Open the original surface to review or retry."})]},d.id)})]})]})}function PC(e){return e==="block_certification"?"Block certification":e==="project_refresh"?"Project metadata refresh":e==="agent_run"?"AI request":e==="app_ai_build"?"App proposal":e.replace(/_/g," ")}const rs=new Map;function IC(e,t){let n=rs.get(e);n||(n={running:!1},rs.set(e,n));const r=n,o=new Promise((i,a)=>{r.pending?(r.pending.content=t,r.pending.waiters.push({resolve:i,reject:a})):r.pending={content:t,waiters:[{resolve:i,reject:a}]}});return r.running||(r.running=!0,(async()=>{for(;r.pending;){const i=r.pending;r.pending=void 0;try{await B.saveNotebook(e,i.content);for(const a of i.waiters)a.resolve()}catch(a){for(const c of i.waiters)c.reject(a)}}})().finally(()=>{r.running=!1,r.pending||rs.delete(e)})),o}function DC(e){const t=rs.get(e);return!!(t!=null&&t.running||t!=null&&t.pending)}function $C({t:e}){return s.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"linear-gradient(135deg, #5b8cff 0%, #7c5cff 100%)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx("span",{style:{color:"#ffffff",fontSize:10,fontWeight:700,fontFamily:e.fontMono,letterSpacing:"-0.5px"},children:"DQL"})})}function MC(){var te;const e=Ge(Lr(F=>({activeBlockPath:F.activeBlockPath,activeFile:F.activeFile,appMode:F.appMode,autoSave:F.autoSave,blockStudioDirty:F.blockStudioDirty,blockStudioDraft:F.blockStudioDraft,blockStudioMetadata:F.blockStudioMetadata,cells:F.cells,files:F.files,mainView:F.mainView,notebookDirty:F.notebookDirty,notebookMetadata:F.notebookMetadata,notebookTitle:F.notebookTitle,savingFile:F.savingFile,themeMode:F.themeMode}))),t=jn(),n=Qe[e.themeMode],{executeAll:r}=uf(),[o,i]=p.useState(!1),[a,c]=p.useState(""),[l,u]=p.useState(!1),[h,d]=p.useState(!1),[f,m]=p.useState(!1),[S,v]=p.useState(!1),[b,w]=p.useState(!1),j=p.useRef(null),[C,x]=p.useState(!1),[E,P]=p.useState(!1),A=p.useRef(null),g=p.useRef(null),I=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,T=e.mainView==="notebook",O=e.mainView==="notebook"||e.mainView==="block_studio",_=O&&!!e.activeFile,M={home:"Home",business_artifact:((te=e.activeFile)==null?void 0:te.name.replace(/\.(dqlnb|dql)$/i,""))??"Business Definition",lineage:"Lineage",lineage_detail:"Lineage",connection:"Settings",apps:"Apps",git:"Source control",settings:"Settings",imports:"Import SQL",domains:"Modeling",modeling:"Modeling"},q=O?e.activeFile?e.notebookTitle||"Untitled":e.mainView==="block_studio"?"Blocks":"Notebooks":M[e.mainView]??"DQL Workbench";p.useEffect(()=>{o&&g.current&&(g.current.focus(),g.current.select())},[o]),p.useEffect(()=>{if(!E)return;function F(K){A.current&&!A.current.contains(K.target)&&P(!1)}return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[E]);const G=()=>{c(e.notebookTitle),i(!0)},J=()=>{i(!1),a.trim()&&a!==e.notebookTitle&&(e.mainView==="block_studio"&&e.blockStudioMetadata?(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,name:a.trim()}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:J1(e.blockStudioDraft,a.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},H=p.useCallback(async()=>{var K,oe,ee;const F=In.getState();if(F.activeFile){t({type:"SET_SAVING",saving:!0});try{if(F.mainView==="block_studio"){if(!F.blockStudioMetadata)return;const ce=await B.saveBlockStudio({path:F.activeBlockPath,source:F.blockStudioDraft,metadata:{name:F.blockStudioMetadata.name,domain:F.blockStudioMetadata.domain,folderPath:F.blockStudioMetadata.folderPath,description:F.blockStudioMetadata.description,owner:F.blockStudioMetadata.owner,tags:F.blockStudioMetadata.tags}});t({type:"OPEN_BLOCK_STUDIO",file:{name:`${ce.metadata.name}.dql`,path:ce.path,type:"block",folder:"blocks"},payload:ce}),F.files.some(ke=>ke.path===ce.path)||t({type:"FILE_ADDED",file:{name:`${ce.metadata.name}.dql`,path:ce.path,type:"block",folder:"blocks"}})}else{const ce=F.activeFile,ke=F.cells,xe=F.notebookTitle,De=F.notebookMetadata,We=ce.type==="block"?((K=ke[0])==null?void 0:K.content)??"":L1(xe,ke,De);await IC(ce.path,We);const Be=In.getState();((oe=Be.activeFile)==null?void 0:oe.path)===ce.path&&Be.cells===ke&&Be.notebookTitle===xe&&Be.notebookMetadata===De&&t({type:"SET_NOTEBOOK_DIRTY",dirty:!1})}u(!0),setTimeout(()=>u(!1),2e3)}catch(ce){console.error("Save failed:",ce)}finally{const ce=(ee=In.getState().activeFile)==null?void 0:ee.path;(!ce||!DC(ce))&&t({type:"SET_SAVING",saving:!1})}}},[t]);p.useEffect(()=>{const F=K=>{(K.metaKey||K.ctrlKey)&&K.key==="s"&&(K.preventDefault(),H())};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[H]),p.useEffect(()=>{if(!e.autoSave||!I||!e.activeFile||e.mainView==="block_studio")return;const F=setTimeout(()=>{H()},750);return()=>clearTimeout(F)},[e.autoSave,I,e.activeFile,e.cells,e.blockStudioDraft,H]);const L=[{mode:"obsidian",label:"Obsidian",glyph:"●",swatch:"#0d0e11"},{mode:"paper",label:"Paper",glyph:"☼",swatch:"#f7f4ed"},{mode:"white",label:"White",glyph:"○",swatch:"#ffffff"}],$=e.themeMode==="dark"||e.themeMode==="midnight"?"obsidian":e.themeMode==="light"?"paper":e.themeMode==="arctic"?"white":e.themeMode,X=L.find(F=>F.mode===$)??L[0];p.useEffect(()=>{if(!b)return;const F=oe=>{j.current&&!j.current.contains(oe.target)&&w(!1)},K=oe=>{oe.key==="Escape"&&w(!1)};return document.addEventListener("mousedown",F),document.addEventListener("keydown",K),()=>{document.removeEventListener("mousedown",F),document.removeEventListener("keydown",K)}},[b]);const W={height:28,padding:"0 10px",borderRadius:6,border:`1px solid ${n.btnBorder}`,cursor:"pointer",fontSize:12,fontWeight:500,fontFamily:n.font,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s, color 0.15s",whiteSpace:"nowrap"};return s.jsxs("div",{style:{height:48,flexShrink:0,background:n.headerBg,borderBottom:`1px solid ${n.headerBorder}`,display:"flex",alignItems:"center",padding:"0 12px",gap:8,userSelect:"none"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[s.jsx($C,{t:n}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&O&&s.jsx("span",{style:{fontSize:10,fontWeight:600,color:e.activeFile.type==="block"?"#e3b341":n.accent,background:`${e.activeFile.type==="block"?"#e3b341":n.accent}18`,borderRadius:4,padding:"2px 6px",fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em",flexShrink:0},children:e.activeFile.type}),e.activeFile&&O?o?s.jsx("input",{ref:g,value:a,onChange:F=>c(F.target.value),onBlur:J,onKeyDown:F=>{F.key==="Enter"&&J(),F.key==="Escape"&&i(!1)},style:{background:"transparent",border:`1px solid ${n.cellBorderActive}`,borderRadius:4,color:n.textPrimary,fontSize:13,fontWeight:500,fontFamily:n.font,padding:"2px 6px",outline:"none",minWidth:120,maxWidth:320}}):s.jsxs("span",{onClick:G,title:"Click to rename",style:{color:n.textPrimary,fontSize:13,fontWeight:500,fontFamily:n.font,cursor:"text",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",padding:"2px 4px",borderRadius:4,border:"1px solid transparent"},children:[q,I&&s.jsx("span",{style:{color:n.textMuted,marginLeft:4},children:"●"})]}):s.jsx("span",{style:{color:n.textSecondary,fontSize:13,fontFamily:n.font,padding:"2px 4px"},children:q||"DQL Workbench"})]}),s.jsx("div",{style:{flex:1}}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx(_C,{}),e.appMode==="studio"&&_&&e.mainView!=="block_studio"&&s.jsx(s.Fragment,{children:s.jsxs("button",{onClick:T?r:void 0,disabled:!e.activeFile||!T,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),style:{...W,height:30,padding:"0 14px",borderRadius:999,background:n.accent,color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!T?.4:h?.9:1,boxShadow:"0 1px 2px rgba(107,93,211,0.25)",gap:6},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})}),"Run all"]})}),s.jsxs("div",{ref:j,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>w(F=>!F),onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),title:`Theme: ${X.label}`,"aria-haspopup":"true","aria-expanded":b,style:{...W,background:S||b?n.btnHover:n.btnBg,color:n.textSecondary,padding:"0 10px",fontSize:12,display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:{width:12,height:12,borderRadius:3,background:X.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10,letterSpacing:"0.04em"},children:X.label}),s.jsx("span",{style:{fontSize:8,color:n.textMuted},children:"▾"})]}),b&&s.jsx("div",{role:"menu",style:{position:"absolute",top:"100%",right:0,marginTop:4,minWidth:160,background:n.headerBg,border:`1px solid ${n.headerBorder}`,borderRadius:6,boxShadow:"0 8px 24px rgba(0,0,0,0.32)",padding:4,zIndex:1e3,display:"flex",flexDirection:"column",gap:1},children:L.map(F=>{const K=F.mode===$;return s.jsxs("button",{role:"menuitemradio","aria-checked":K,onClick:()=>{t({type:"SET_THEME",mode:F.mode}),w(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",background:K?n.btnHover:"transparent",color:n.textPrimary,cursor:"pointer",borderRadius:4,fontSize:12,fontFamily:n.font,textAlign:"left"},onMouseEnter:oe=>{K||(oe.currentTarget.style.background=n.btnHover)},onMouseLeave:oe=>{K||(oe.currentTarget.style.background="transparent")},children:[s.jsx("span",{style:{width:14,height:14,borderRadius:3,background:F.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{flex:1},children:F.label}),K&&s.jsx("span",{style:{color:n.accent,fontSize:11},children:"✓"})]},F.mode)})})]}),e.appMode==="studio"&&_&&e.mainView!=="block_studio"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:H,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),title:"Save (Cmd+S)",style:{...W,background:f&&e.activeFile?n.btnHover:n.btnBg,color:l?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?s.jsxs(s.Fragment,{children:[s.jsx(NC,{}),"Saving…"]}):l?s.jsx(s.Fragment,{children:"✓ Saved"}):s.jsx(s.Fragment,{children:"Save"})}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder}})]}),_&&e.mainView!=="block_studio"&&s.jsxs("div",{ref:A,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>{e.activeFile&&P(F=>!F)},disabled:!e.activeFile,onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),title:"Share / export",style:{...W,height:30,padding:"0 14px",borderRadius:999,background:(C||E)&&e.activeFile?"#2a2a30":"#1a1a1a",color:"#ffffff",border:"1px solid #1a1a1a",opacity:e.activeFile?1:.4,gap:6},children:[s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M5.5 10.75a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 0 1.5h-3.5a.75.75 0 0 1-.75-.75Zm0-3a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 0 1.5h-3.5a.75.75 0 0 1-.75-.75ZM3 3.75A1.75 1.75 0 0 1 4.75 2h6.586c.464 0 .909.184 1.237.513l1.914 1.914c.329.328.513.773.513 1.237v6.586A1.75 1.75 0 0 1 13.25 14h-8.5A1.75 1.75 0 0 1 3 12.25Z"})}),"Share",s.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"currentColor",style:{marginLeft:1,opacity:.7},children:s.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),E&&s.jsx("div",{style:{position:"absolute",top:32,right:0,zIndex:200,background:n.modalBg,border:`1px solid ${n.cellBorder}`,borderRadius:8,boxShadow:"0 8px 24px rgba(0,0,0,0.3)",padding:4,minWidth:160,display:"flex",flexDirection:"column",gap:2},children:s.jsx(LC,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{hC(e.notebookTitle||"dashboard",e.cells),P(!1)}})})]})]})]})}function LC({label:e,description:t,t:n,onClick:r}){const[o,i]=p.useState(!1);return s.jsxs("button",{onClick:r,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:o?n.btnHover:"transparent",border:"none",borderRadius:5,cursor:"pointer",padding:"6px 10px",textAlign:"left",display:"flex",flexDirection:"column",gap:1,transition:"background 0.12s"},children:[s.jsx("span",{style:{fontSize:12,fontWeight:500,color:n.textPrimary,fontFamily:n.font},children:e}),s.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:t})]})}function NC(){return s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{animation:"spin 0.8s linear infinite"},children:[s.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),s.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"14 7"})]})}function BC(e){return e.toTimeString().slice(0,8)}function FC(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function zC(){const{state:e,dispatch:t}=et(),n=Qe[e.themeMode],[r,o]=p.useState(!1),i=e.queryLog.filter(c=>c.error),a=c=>t({type:"SET_DEV_PANEL_TAB",tab:c});return s.jsxs("div",{style:{height:e.devPanelOpen?180:0,flexShrink:0,background:n.sidebarBg,borderTop:`1px solid ${n.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden",transition:"height 0.2s ease",position:"relative"},children:[e.devPanelOpen&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{height:32,flexShrink:0,display:"flex",alignItems:"center",borderBottom:`1px solid ${n.headerBorder}`,padding:"0 8px",gap:2},children:[["logs","errors"].map(c=>s.jsx(qC,{label:c==="errors"?`Errors${i.length>0?` (${i.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===c,onClick:()=>a(c),t:n},c)),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>t({type:"SET_CELLS",cells:e.cells}),title:"Clear logs",style:{background:"transparent",borderTop:"none",borderLeft:"none",borderRight:"none",borderBottom:"none",cursor:"pointer",color:n.textMuted,fontSize:11,fontFamily:n.font,padding:"2px 6px",borderRadius:4},children:"Clear"})]}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[e.devPanelTab==="logs"&&(e.queryLog.length===0?s.jsx(Bl,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(c=>s.jsx(Fl,{entry:c,t:n},c.id))),e.devPanelTab==="errors"&&(i.length===0?s.jsx(Bl,{t:n,message:"No errors."}):[...i].reverse().map(c=>s.jsx(Fl,{entry:c,t:n},c.id)))]})]}),s.jsxs("button",{onClick:()=>t({type:"TOGGLE_DEV_PANEL"}),onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),title:e.devPanelOpen?"Close panel":"Open dev panel",style:{position:"absolute",bottom:e.devPanelOpen?4:-28,right:8,height:22,padding:"0 8px",borderRadius:"4px 4px 0 0",borderTop:`1px solid ${n.headerBorder}`,borderLeft:`1px solid ${n.headerBorder}`,borderRight:`1px solid ${n.headerBorder}`,borderBottom:e.devPanelOpen?`1px solid ${n.sidebarBg}`:`1px solid ${n.headerBorder}`,background:r?n.btnHover:n.sidebarBg,color:n.textMuted,cursor:"pointer",fontSize:11,fontFamily:n.font,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s, bottom 0.2s ease",zIndex:10},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:e.devPanelOpen?"M1 7l4-4 4 4":"M1 3l4 4 4-4",strokeWidth:"1.5",stroke:"currentColor",fill:"none"})}),"Dev"]})]})}function qC({label:e,active:t,onClick:n,t:r}){const[o,i]=p.useState(!1);return s.jsx("button",{onClick:n,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:"transparent",borderTop:"none",borderLeft:"none",borderRight:"none",borderBottom:t?`2px solid ${r.accent}`:"2px solid transparent",cursor:"pointer",color:t?r.textPrimary:o?r.textSecondary:r.textMuted,fontSize:12,fontFamily:r.font,fontWeight:t?500:400,padding:"4px 8px",height:32,transition:"color 0.15s"},children:e})}function Bl({t:e,message:t}){return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:e.textMuted,fontSize:12,fontFamily:e.font,fontStyle:"italic"},children:t})}function Fl({entry:e,t}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"3px 12px",fontSize:11,fontFamily:t.fontMono,color:e.error?t.error:t.textSecondary,borderLeft:e.error?`2px solid ${t.error}`:"2px solid transparent"},children:[s.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:BC(e.ts)}),s.jsx("span",{style:{flexShrink:0,color:t.textPrimary,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.cellName}),e.error?s.jsx("span",{style:{color:t.error,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.error}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:{color:t.textMuted},children:[e.rows.toLocaleString()," rows"]}),s.jsx("span",{style:{color:t.textMuted},children:FC(e.time)})]})]})}function UC(){const{state:e,dispatch:t}=et(),{executeAll:n}=uf();p.useEffect(()=>{const r=o=>{const i=o.metaKey||o.ctrlKey;if(i&&o.key==="b"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_SIDEBAR"});return}if(i&&o.shiftKey&&o.key==="Enter"){o.preventDefault(),e.activeFile&&n();return}if(i&&o.key==="j"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_DEV_PANEL"});return}if(i&&o.key==="d"&&!o.shiftKey){o.preventDefault(),e.activeFile&&t({type:"TOGGLE_DASHBOARD_MODE"});return}if(o.key==="Escape"){if(e.dashboardMode){t({type:"TOGGLE_DASHBOARD_MODE"});return}if(e.newNotebookModalOpen){t({type:"CLOSE_NEW_NOTEBOOK_MODAL"});return}if(e.newBlockModalOpen){t({type:"CLOSE_NEW_BLOCK_MODAL"});return}}};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,n,e.activeFile,e.newNotebookModalOpen,e.newBlockModalOpen,e.dashboardMode])}const WC=600;function KC(e,t){const n=t.filter(r=>r.result||r.error||(r.executionCount??0)>0).map(r=>{var o;return{cellId:r.id,status:r.status,result:r.result,error:r.error,executionCount:r.executionCount,executedAt:((o=r.execution)==null?void 0:o.completedAt)??new Date().toISOString(),execution:r.execution}});return{version:1,notebookPath:e,capturedAt:new Date().toISOString(),cells:n}}function zl(e){return e.map(t=>{var n,r;return`${t.id}:${((n=t.execution)==null?void 0:n.runId)??""}:${t.executionCount??0}:${((r=t.result)==null?void 0:r.rowCount)??-1}:${t.error??""}`}).join("|")}function VC(){var o;const{state:e}=et(),t=p.useRef(null),n=p.useRef(""),r=p.useRef(null);p.useEffect(()=>{var c;const i=((c=e.activeFile)==null?void 0:c.path)??null;if(!i)return;if(i!==r.current){r.current=i,n.current=zl(e.cells);return}const a=zl(e.cells);return a!==n.current&&(n.current=a,t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{const l=KC(i,e.cells);B.saveRunSnapshot(i,l).catch(()=>{})},WC)),()=>{t.current&&(clearTimeout(t.current),t.current=null)}},[e.cells,(o=e.activeFile)==null?void 0:o.path])}const hE="core";function HC(e){var n;const t=e==null?void 0:e.trim();if(t)return((n=t.split("::").at(-1))==null?void 0:n.trim())||void 0}const GC=[{items:[{id:"diagram",label:"Modeling"},{id:"skills",label:"Skills"},{id:"blocks",label:"Blocks"},{id:"notebooks",label:"Notebooks"},{id:"apps",label:"Apps"}]}],QC=new Set(GC.flatMap(e=>e.items.map(t=>t.id)));function hf(e){return e!==null&&QC.has(e)}function mE(e,t){const n=new URL(e);return t.domain?n.searchParams.set("domain",t.domain):n.searchParams.delete("domain"),n.searchParams.set("domainSection",t.section),t.modelAreaId?n.searchParams.set("modelArea",t.modelAreaId):n.searchParams.delete("modelArea"),t.selectedId?n.searchParams.set("domainObject",t.selectedId):n.searchParams.delete("domainObject"),`${n.pathname}${n.search}${n.hash}`}function JC(e){const t=new URL(e);for(const n of mf)t.searchParams.delete(n);return`${t.pathname}${t.search}${t.hash}`}const mf=["domain","domainSection","modelArea","domainObject"],gE="dql.domain-studio.location";function yE(e,t){const n=new URL(e).searchParams;if(mf.some(r=>n.has(r))){const r=n.get("domainSection"),o=hf(r)?r:"diagram";return{domain:n.get("domain"),section:o,modelAreaId:n.get("modelArea"),selectedId:r==="diagram"?n.get("domainObject"):null}}return YC(t)}function YC(e){const t={domain:null,section:"diagram",modelAreaId:null,selectedId:null};if(!e)return t;try{const n=JSON.parse(e),r=typeof n.section=="string"&&hf(n.section)?n.section:"diagram",o=i=>typeof i=="string"&&i.trim()?i:null;return{domain:o(n.domain),section:r,modelAreaId:o(n.modelAreaId),selectedId:o(n.selectedId)}}catch{return t}}function bE(e){return`modeling:${e??"all"}`}function xE(e){const t=Object.values(e),n=new Map;for(const a of t){const c=a.parent&&e[a.parent]?a.parent:void 0;n.set(c,[...n.get(c)??[],a])}for(const a of n.values())a.sort((c,l)=>c.id.localeCompare(l.id));const r=[],o=new Set,i=(a,c)=>{for(const l of n.get(a)??[])o.has(l.id)||(o.add(l.id),r.push({id:l.id,parent:l.parent,depth:c,label:c===0?l.id:`${"— ".repeat(c)}${l.id.split(".").at(-1)??l.id}`}),i(l.id,c+1))};i(void 0,0);for(const a of t.sort((c,l)=>c.id.localeCompare(l.id)))o.has(a.id)||r.push({id:a.id,parent:a.parent,depth:0,label:a.id});return r}function vE(e){const t=(e??"").toLowerCase();return t==="dimension"?"var(--status-success)":t==="bridge"?"var(--status-warning)":t==="event"||t==="snapshot"?"var(--accent)":"var(--text-tertiary)"}function gf(e){return Object.entries(e.entities).map(([t,n])=>({recordKey:t,entity:n}))}function SE(e,t){if(e.entities[t])return t;const n=gf(e).filter(({entity:r})=>r.id===t||r.qualifiedId===t);return n.length===1?n[0].recordKey:void 0}function wE(e,t){return gf(e).filter(({entity:n})=>!t||n.domain===t)}function kE(e,t,n){if(e.operation==="upsert_entity"){if(!t)return!1;const r=e.value;return r.dbtModel===t.dbtUniqueId&&(r.grain??void 0)===(t.grain??void 0)&&JSON.stringify(r.keys??[])===JSON.stringify(t.keys??[])&&(r.status??t.status)===t.status&&(r.areaId??void 0)===HC(t.areaId)&&r.domain===t.domain}return e.operation==="upsert_area"?!!n&&e.value.domain===n.domain&&e.value.id===n.localId:!1}const XC=p.lazy(()=>_e(()=>import("./HomePage-Ehb0ITj-.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.HomePage}))),ZC=p.lazy(()=>_e(()=>import("./AnalyticsHome-Dq54vjNz.js"),__vite__mapDeps([7,8,9,10,1,11,12,3,13,14,15,16,17,2,18,6])).then(e=>({default:e.AnalyticsHome}))),ej=p.lazy(()=>_e(()=>import("./GlobalAiRail-DM4wkxR_.js"),__vite__mapDeps([19,9,10,1,11,12,3,13,14,15,16,17,2,20,6])).then(e=>({default:e.GlobalAiRail}))),tj=p.lazy(()=>_e(()=>import("./NotebookEditor-FEqs3789.js"),__vite__mapDeps([21,4,2,5,22,23,24,10,1,11,12,3,13,14,9,15,16,17,8,25,26,6,27,28,20,29])).then(e=>({default:e.NotebookEditor}))),nj=p.lazy(()=>_e(()=>import("./NewNotebookModal-Csw6eF74.js"),__vite__mapDeps([30,4,15,6])).then(e=>({default:e.NewNotebookModal}))),rj=p.lazy(()=>_e(()=>import("./NewBlockModal-DI-JDzFH.js"),__vite__mapDeps([31,6])).then(e=>({default:e.NewBlockModal}))),oj=p.lazy(()=>_e(()=>import("./SetupOnboarding-DyLaPFGn.js"),__vite__mapDeps([32,33,2,6])).then(e=>({default:e.SetupOnboarding}))),sj=p.lazy(()=>_e(()=>import("./BlockStudio-CxxXZD3M.js"),__vite__mapDeps([34,22,23,10,1,11,12,3,13,14,25,26,6,27,9,15,16,17,2,20,35,36])).then(e=>({default:e.BlockStudio}))),ij=p.lazy(()=>_e(()=>import("./BusinessArtifactView-DxdAmeUN.js"),__vite__mapDeps([37,25,26,6,27])).then(e=>({default:e.BusinessArtifactView}))),aj=p.lazy(()=>_e(()=>import("./LineageDetailView-DX32pfbp.js"),__vite__mapDeps([38,25,26,6,27,39,33,16])).then(e=>({default:e.LineageDetailView}))),cj=p.lazy(()=>_e(()=>import("./LineageDAG-Lvjc2AQX.js"),__vite__mapDeps([39,26,6,27])).then(e=>({default:e.LineageDAG}))),lj=p.lazy(()=>_e(()=>import("./HelpDocsPage-DnD4nMuF.js"),__vite__mapDeps([40,6])).then(e=>({default:e.HelpDocsPage}))),dj=p.lazy(()=>_e(()=>Promise.resolve().then(()=>i1),void 0).then(e=>({default:e.ConnectionPanel}))),uj=p.lazy(()=>_e(()=>import("./GitPage-GQtcwncb.js"),__vite__mapDeps([41,42,15,6])).then(e=>({default:e.GitPage}))),pj=p.lazy(()=>_e(()=>import("./ReadinessPage-Bk0S_MEA.js"),__vite__mapDeps([43,1,44,45,12,3,2,6])).then(e=>({default:e.ReadinessPage}))),fj=p.lazy(()=>_e(()=>import("./AgentLogPage-BzQOKjyV.js"),__vite__mapDeps([46,33,14,47,6])).then(e=>({default:e.AgentLogPage}))),hj=p.lazy(()=>_e(()=>import("./GovernedContextPage-B8Ft6JES.js"),__vite__mapDeps([48,3,12,9,10,1,11,13,14,15,16,17,2,49,6])).then(e=>({default:e.GovernedContextPage}))),mj=p.lazy(()=>_e(()=>import("./DbtFirstModelingPage-y81gFg_b.js"),__vite__mapDeps([50,49,9,10,1,11,12,3,13,14,15,16,17,2,26,6,27,28,29,36,51,47])).then(e=>({default:e.DbtFirstModelingPage}))),gj=p.lazy(()=>_e(()=>import("./AppsView-0SlwWYex.js"),__vite__mapDeps([52,20,17,10,1,11,12,3,13,14,15,33,35,29,4,5,24,8,45,53,51,2,18,6])).then(e=>({default:e.AppsView}))),yj=p.lazy(()=>_e(()=>import("./LineageDrawer-CFq3jPfk.js"),__vite__mapDeps([54,25,26,6,27,36,15,17,13,53,42])).then(e=>({default:e.LineageDrawer}))),bj=p.lazy(()=>_e(()=>import("./AiBuildDialog-CTxha499.js"),__vite__mapDeps([55,44,11,12,3,13,15,6])).then(e=>({default:e.AiBuildDialog})));function xj(){const e=Ge(Lr(d=>({appMode:d.appMode,dashboardMode:d.dashboardMode,globalAi:d.globalAi,inspectorOpen:d.inspectorOpen,lineageDrawerOpen:d.lineageDrawerOpen,lineageFullscreen:d.lineageFullscreen,mainView:d.mainView,newBlockModalOpen:d.newBlockModalOpen,newNotebookModalOpen:d.newNotebookModalOpen,setupOpen:d.setupOpen,sidebarOpen:d.sidebarOpen,sidebarPanel:d.sidebarPanel,themeMode:d.themeMode}))),t=jn(),n=Qe[e.themeMode],r=p.useRef({}),o=e.mainView==="block_studio"||e.mainView==="imports",[i,a]=p.useState(!1),[c,l]=p.useState(null);p.useEffect(()=>{let d=!0;return B.getSetupLaunch().then(f=>{d&&(l(f),f.shouldOpen&&t({type:"OPEN_SETUP"}))}).catch(()=>{}),()=>{d=!1}},[t]),p.useEffect(()=>{const d=()=>t({type:"SET_MAIN_VIEW",view:"modeling"});return window.addEventListener("dql:open-context-proposal",d),()=>window.removeEventListener("dql:open-context-proposal",d)},[t]),p.useEffect(()=>{if(e.mainView==="domains"||e.mainView==="modeling"||e.mainView==="skills")return;const d=JC(window.location.href),f=`${window.location.pathname}${window.location.search}${window.location.hash}`;d!==f&&window.history.replaceState(window.history.state,"",d)},[e.mainView]),UC(),VC(),p.useEffect(()=>{const d=f=>{(f.metaKey||f.ctrlKey)&&f.key.toLowerCase()==="k"&&!f.shiftKey&&(f.preventDefault(),a(m=>!m)),(f.metaKey||f.ctrlKey)&&f.shiftKey&&f.key.toLowerCase()==="i"&&(f.preventDefault(),t({type:"TOGGLE_INSPECTOR"}))};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);const u=p.useCallback(async d=>{try{if(d.type==="term"||d.type==="business_view"){e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"}),t({type:"OPEN_BUSINESS_ARTIFACT",file:d});return}if(d.type==="block"){const j=await B.openBlockStudio(d.path);t({type:"OPEN_BLOCK_STUDIO",file:d,payload:j});return}const{content:f}=await B.readNotebook(d.path),{title:m,cells:S,metadata:v}=N1(d.path,f),b=d.path.endsWith(".dqlnb")?await B.fetchRunSnapshot(d.path):null;let w=S;if(b!=null&&b.found&&b.snapshot){const j=new Map(b.snapshot.cells.map(C=>[C.cellId,C]));w=S.map(C=>{const x=j.get(C.id);return x?{...C,status:x.status??C.status,result:x.result??C.result,error:x.error??C.error,executionCount:x.executionCount??C.executionCount,execution:x.execution??C.execution,fromSnapshot:x.result!=null}:C})}t({type:"OPEN_FILE",file:d,cells:w,title:m,metadata:v}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(f){if(console.error("Failed to open file:",f),d.type==="block")try{const{content:m}=await B.readNotebook(d.path);t({type:"OPEN_BLOCK_STUDIO",file:d,payload:{path:d.path,source:m,companionPath:null,metadata:{name:d.name.replace(/\.dql$/i,""),path:d.path,domain:d.path.split("/").slice(1,-1).join("/")||"uncategorized",description:"",owner:"",tags:[]},validation:{valid:!1,diagnostics:[{severity:"warning",message:"Opened block without studio metadata. Save once to normalize it."}],semanticRefs:{metrics:[],dimensions:[],segments:[]}}}});return}catch(m){console.error("Failed to open block fallback:",m)}else t({type:"OPEN_FILE",file:d,cells:[Ra("sql")],title:d.name})}},[t,e.sidebarPanel]);p.useCallback(d=>{const f=r.current[d];f&&f.scrollIntoView({behavior:"smooth",block:"start"})},[]);const h=p.useCallback((d,f)=>{f?r.current[d]=f:delete r.current[d]},[]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100vh",width:"100vw",background:n.appBg,fontFamily:n.font,color:n.textPrimary,overflow:"hidden"},children:[s.jsx(MC,{}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[e.appMode==="studio"&&s.jsx(Ww,{}),e.appMode==="studio"&&e.sidebarOpen&&!o&&s.jsx(_1,{onOpenFile:u}),s.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:s.jsx(p.Suspense,{fallback:s.jsx(vj,{t:n}),children:e.mainView==="home"?s.jsx(XC,{}):e.mainView==="ask"?s.jsx(ZC,{}):e.mainView==="business_artifact"?s.jsx(ij,{}):e.mainView==="lineage"?s.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:s.jsx(cj,{})}):e.mainView==="lineage_detail"?s.jsx(aj,{}):e.mainView==="help"?s.jsx(lj,{}):e.mainView==="connection"||e.mainView==="settings"?s.jsx(wj,{children:s.jsx(dj,{variant:"page"})}):e.mainView==="git"?s.jsx(uj,{}):e.mainView==="readiness"?s.jsx(pj,{}):e.mainView==="skills"?s.jsx(hj,{initialTab:"skills"}):e.mainView==="domains"||e.mainView==="modeling"?s.jsx(mj,{}):e.mainView==="apps"?s.jsx(gj,{}):e.mainView==="agent_log"?s.jsx(kj,{title:"Agent steps",description:"What the agent did to answer this question, and where the time went — route, tools, checks, and per-step timing.",children:s.jsx(fj,{})}):s.jsx(s.Fragment,{children:e.mainView==="imports"||e.mainView==="block_studio"?s.jsx(sj,{},"block-editor"):s.jsxs(s.Fragment,{children:[s.jsx(tj,{onOpenFile:u,registerCellRef:h}),e.appMode==="studio"&&s.jsx(zC,{})]})})})}),e.appMode==="studio"&&e.lineageDrawerOpen&&!e.lineageFullscreen&&!e.dashboardMode&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(yj,{})}),e.appMode==="studio"&&e.inspectorOpen&&!e.lineageFullscreen&&!e.lineageDrawerOpen&&!e.dashboardMode&&s.jsx(Pw,{}),e.globalAi.open&&e.mainView==="apps"&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(ej,{})})]}),e.newNotebookModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(nj,{onFileOpened:u})}),e.newBlockModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(rj,{onFileOpened:u})}),s.jsx(ZS,{open:i,onClose:()=>a(!1)}),s.jsx(p.Suspense,{fallback:null,children:s.jsx(bj,{})}),e.setupOpen&&s.jsx(p.Suspense,{fallback:s.jsx(Sj,{t:n}),children:s.jsx(oj,{launch:c!=null&&c.shouldOpen?c:void 0,onAcknowledged:()=>l(d=>d&&{...d,shouldOpen:!1,reason:null})})})]})}function vj({t:e}){return s.jsx("div",{role:"status","aria-live":"polite",style:{flex:1,minWidth:0,display:"grid",placeItems:"center",background:e.appBg,color:e.textSecondary,fontFamily:e.font},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,fontSize:12.5},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:999,background:e.accent}}),"Loading workspace…"]})})}function Sj({t:e}){return s.jsx("div",{role:"status","aria-live":"polite",style:{position:"fixed",inset:0,zIndex:1100,display:"grid",placeItems:"center",background:e.appBg,color:e.textSecondary,fontFamily:e.font},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,fontSize:12.5},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:999,background:e.accent}}),"Checking workspace setup…"]})})}function wj({children:e}){return s.jsx("div",{style:{flex:1,minWidth:0,overflow:"auto"},children:s.jsx("div",{style:{maxWidth:1120,margin:"0 auto",padding:"18px 28px 32px"},children:e})})}function kj({title:e,description:t,children:n}){return s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"18px 24px 12px",borderBottom:"1px solid rgba(127, 127, 127, 0.16)"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700},children:e}),s.jsx("div",{style:{fontSize:13,opacity:.72,marginTop:6,maxWidth:760,lineHeight:1.5},children:t})]}),s.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:n})]})}function Cj(){const e=jn(),t=Yi(),n=p.useRef(null);p.useEffect(()=>{let r=!0,o=null,i=null,a=null,c=null;const l=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,B.listNotebooks().then(f=>{r&&(t.setQueryData(["notebooks"],f),e({type:"SET_FILES",files:f}))}).catch(()=>{})},150)},u=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,B.getDomains().then(({domains:f})=>{r&&(t.setQueryData(["authored-domains"],{domains:f}),e({type:"SET_AUTHORED_DOMAINS",domains:f}))}).catch(()=>{})},150)},h=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null,e({type:"SET_SEMANTIC_LOADING",loading:!0}),B.getSemanticLayer().then(f=>{r&&(t.setQueryData(["semantic-layer"],f),e({type:"SET_SEMANTIC_LAYER",layer:f}))}).catch(()=>{})},100)},d=()=>{if(!r)return;const f=new AbortController;n.current=f,Ep("/api/watch",m=>{if(m.event==="change")try{const S=JSON.parse(m.data);if(S.type==="file-added"||S.type==="file-deleted"||S.type==="file-changed"){const v=S.path??"";/^(?:notebooks|workbooks|blocks|skills|apps|dashboards)\//.test(v)&&l(),v.startsWith("domains/")&&(l(),u())}S.type==="semantic-reload"&&h()}catch{}},f.signal).catch(()=>{!r||f.signal.aborted||(o&&clearTimeout(o),o=setTimeout(d,5e3))})};return d(),()=>{var f;r=!1,o&&clearTimeout(o),i&&clearTimeout(i),a&&clearTimeout(a),c&&clearTimeout(c),(f=n.current)==null||f.abort(),n.current=null}},[e,t])}const jj=new ah({defaultOptions:{queries:{staleTime:15e3,gcTime:5*6e4,retry:1,refetchOnWindowFocus:!1}}});function Ej(){const e=Ge(i=>i.themeMode),t=Ge(i=>i.dispatch),n=Qe[e];p.useEffect(()=>{const i="dql-global-styles";let a=document.getElementById(i);a||(a=document.createElement("style"),a.id=i,document.head.appendChild(a)),a.textContent=`
|
|
610
|
+
</html>`}function hC(e,t){const n=fC(e,t),r=new Blob([n],{type:"text/html;charset=utf-8"}),o=URL.createObjectURL(r),i=document.createElement("a");i.href=o,i.download=`${e.toLowerCase().replace(/[^a-z0-9]+/g,"-")}-dashboard.html`,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(o)}const mC=new Set(["succeeded","failed","cancelled","interrupted"]);function Ir(e){return mC.has(e.status)}function gC(e,t){if(e.id!==t.id)return t;const n=Ir(e),r=Ir(t);return n&&!r||t.updatedAt<e.updatedAt?e:t.updatedAt>e.updatedAt?t:n!==r?r?t:e:t.progress!==e.progress?t.progress>e.progress?t:e:t}function eo(e,t){const n=e.find(o=>o.id===t.id),r=n?gC(n,t):t;return kC([...e.filter(o=>o.id!==t.id),r])}function yC(e,t){return t.reduce(eo,e)}function bC(e){return e.filter(t=>!Ir(t)).map(t=>t.id)}function xC(e,t){for(const n of bC(t))e.add(n)}async function vC(e,t,n){await Promise.all([...e].map(async r=>{try{const o=await t(r);if(n(o)===!1)return;Ir(o)&&e.delete(r)}catch{}}))}function SC(e,t=new Set){return e.filter(n=>n.type==="block_certification"&&n.status==="succeeded").filter(n=>!t.has(n.id)).filter(n=>{const r=n.result;return!!(r!=null&&r.block&&r.outcome)}).sort((n,r)=>n.updatedAt.localeCompare(r.updatedAt)||n.createdAt.localeCompare(r.createdAt)||n.id.localeCompare(r.id))}function fE(e,t){var o;if(t.operationId){const i=e.find(a=>a.type==="block_certification"&&a.id===t.operationId);if(i)return i}const n=Vr(t.activePath),r=(o=t.sourceFingerprint)==null?void 0:o.trim();return e.filter(i=>i.type==="block_certification").filter(i=>{const a=wC(i),c=[Vr(i.scope.startsWith("block:")?i.scope.slice(6):void 0),Vr(a==null?void 0:a.oldPath),Vr(a==null?void 0:a.draftPath),Vr(a==null?void 0:a.newPath)].filter(h=>!!h),l=!!(n&&c.includes(n)),u=!!(r&&i.resourceRevision&&(i.resourceRevision===r||i.resourceRevision.startsWith(`${r}:`)));return l||u}).sort((i,a)=>a.updatedAt.localeCompare(i.updatedAt)||a.createdAt.localeCompare(i.createdAt))[0]}function wC(e){return e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:void 0}function Vr(e){if(!(typeof e!="string"||!e.trim()))return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function kC(e,t=50){let n=0;return[...e].sort((r,o)=>o.updatedAt.localeCompare(r.updatedAt)||o.createdAt.localeCompare(r.createdAt)||o.id.localeCompare(r.id)).filter(r=>Ir(r)?(n+=1,n<=t):!0)}const ir=["local-operations"],pf=p.createContext(null);function CC({children:e}){const t=Yi(),n=p.useRef(new Set),r=p.useRef(new Set),o=Ge(l=>l.dispatch),i=Ri({queryKey:ir,queryFn:async()=>{const l=(await B.listOperations(50)).operations,u=t.getQueryData(ir)??[];return yC(u,l)},staleTime:15e3,refetchOnWindowFocus:!1,refetchInterval:1500}),a=i.data??[];p.useEffect(()=>{let l=!0,u,h;const d=()=>{h=new AbortController,Ep("/api/operations/events",f=>{if(f.event==="operation")try{const m=JSON.parse(f.data);t.setQueryData(ir,(S=[])=>eo(S,m))}catch{}},h.signal).catch(()=>{!l||h!=null&&h.signal.aborted||(u=setTimeout(d,5e3))})};return d(),()=>{l=!1,u&&clearTimeout(u),h==null||h.abort()}},[t]),p.useEffect(()=>{xC(r.current,a)},[a]),p.useEffect(()=>{let l=!0,u=!1;const h=async()=>{if(!(u||r.current.size===0)){u=!0;try{await vC(r.current,f=>B.getOperation(f),f=>{if(!l)return!1;t.setQueryData(ir,(m=[])=>eo(m,f))})}finally{u=!1}}};h();const d=window.setInterval(()=>void h(),1e3);return()=>{l=!1,window.clearInterval(d)}},[t]),p.useEffect(()=>{for(const l of SC(a,n.current)){const u=l.result;n.current.add(l.id),o({type:"RECONCILE_BLOCK_CERTIFICATION",outcome:u.outcome,oldPath:u.oldPath,draftPath:u.draftPath,newPath:u.newPath,payload:u.block}),window.dispatchEvent(new CustomEvent("dql:block-library-invalidated",{detail:{operationId:l.id,outcome:u.outcome}}))}},[o,a]);const c=p.useMemo(()=>({operations:a,activeCount:a.filter(l=>l.status==="queued"||l.status==="running").length,loading:i.isLoading,cancel:async l=>{const u=await B.cancelOperation(l);r.current.delete(l),t.setQueryData(ir,(h=[])=>eo(h,u))},track:l=>{Ir(l)?r.current.delete(l.id):r.current.add(l.id),t.setQueryData(ir,(u=[])=>eo(u,l))}}),[a,i.isLoading,t]);return s.jsx(pf.Provider,{value:c,children:e})}function jC(){const e=p.useContext(pf);if(!e)throw new Error("useOperations must be used inside OperationsProvider.");return e}const EC=new Set(["succeeded","failed","cancelled","interrupted"]);function TC(e,t=8){const n=AC(e).filter(o=>!EC.has(o.status)||o.type!=="project_refresh"),r=n.map(ff);return{operations:n.slice(0,t),activeCount:r.filter(o=>o.active).length,attentionCount:r.filter(o=>o.tone==="attention").length}}function AC(e){const t=e.filter(l=>l.type==="block_certification"),n=t.map((l,u)=>u),r=new Map,o=l=>{let u=l;for(;n[u]!==u;)n[u]=n[n[u]],u=n[u];return u},i=(l,u)=>{const h=o(l),d=o(u);h!==d&&(n[d]=h)};t.forEach((l,u)=>{for(const h of RC(l)){const d=r.get(h);d===void 0?r.set(h,u):i(u,d)}});const a=new Map;t.forEach((l,u)=>{const h=o(u),d=a.get(h);(!d||OC(l,d)<0)&&a.set(h,l)});const c=new Set([...a.values()].map(l=>l.id));return e.filter(l=>l.type!=="block_certification"||c.has(l.id))}function ff(e){var n,r,o,i,a,c;if(e.status==="queued"||e.status==="running")return{active:!0,tone:"active",statusLabel:e.status,message:e.message,guidance:e.type==="block_certification"?"You can change pages while certification continues.":void 0};if(e.type==="block_certification"&&e.status==="succeeded"){const l=e.result;if((l==null?void 0:l.outcome)==="draft_saved_with_blockers"){const u=((r=(n=l.checklist)==null?void 0:n.issues)==null?void 0:r.length)??((o=l.blockers)==null?void 0:o.length)??((i=l.checklist)==null?void 0:i.blockers.length)??0;return{active:!1,tone:"attention",statusLabel:"needs attention",message:u>0?`Draft saved with ${u} certification blocker${u===1?"":"s"}.`:"Draft saved, but certification requirements are not ready.",guidance:"Open Block Studio to review the exact fixes and retry."}}if((l==null?void 0:l.outcome)==="certified")return{active:!1,tone:"success",statusLabel:"certified",message:"The block passed its required gates and was certified."}}return e.status==="failed"||e.status==="interrupted"?{active:!1,tone:"failure",statusLabel:e.status,message:((a=e.error)==null?void 0:a.message)??e.message,guidance:e.type==="block_certification"?"The saved draft is preserved for review or retry.":void 0}:e.status==="cancelled"?{active:!1,tone:"neutral",statusLabel:"cancelled",message:e.message}:{active:!1,tone:e.status==="succeeded"?"success":"neutral",statusLabel:e.status,message:((c=e.error)==null?void 0:c.message)??e.message}}function RC(e){const t=hi(e.result),n=hi(t==null?void 0:t.block),r=hi(n==null?void 0:n.metadata),o=e.scope.startsWith("block:")?e.scope.slice(6):void 0;return Array.from(new Set([ar(n==null?void 0:n.path),ar(r==null?void 0:r.path),ar(t==null?void 0:t.oldPath),ar(t==null?void 0:t.draftPath),ar(t==null?void 0:t.newPath),ar(o)].filter(i=>!!i)))}function hi(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}function ar(e){if(!(typeof e!="string"||!e.trim()))return e.trim().replace(/\\/g,"/").replace(/^\.\//,"").replace(/^\/+/,"")}function OC(e,t){return t.createdAt.localeCompare(e.createdAt)||t.updatedAt.localeCompare(e.updatedAt)||t.id.localeCompare(e.id)}function _C(){const e=Ge(d=>d.themeMode),t=Qe[e],{operations:n,loading:r,cancel:o}=jC(),[i,a]=p.useState(!1),c=p.useRef(null),{operations:l,activeCount:u,attentionCount:h}=TC(n);return p.useEffect(()=>{if(!i)return;const d=m=>{c.current&&!c.current.contains(m.target)&&a(!1)},f=m=>{m.key==="Escape"&&a(!1)};return document.addEventListener("mousedown",d),document.addEventListener("keydown",f),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",f)}},[i]),!r&&l.length===0?null:s.jsxs("div",{ref:c,style:{position:"relative"},children:[s.jsxs("button",{type:"button","aria-label":"Background tasks","aria-expanded":i,onClick:()=>a(d=>!d),style:{height:28,padding:"0 9px",borderRadius:6,border:`1px solid ${u>0?t.accent:h>0?t.warning:t.btnBorder}`,background:i?t.btnHover:t.btnBg,color:t.textSecondary,cursor:"pointer",display:"inline-flex",alignItems:"center",gap:6,fontFamily:t.font,fontSize:11,fontWeight:600},children:[s.jsx("span",{"aria-hidden":"true",style:{width:7,height:7,borderRadius:999,background:u>0?t.accent:h>0?t.warning:t.success,boxShadow:u>0?`0 0 0 3px ${t.accent}20`:"none"}}),u>0?`${u} running`:h>0?`${h} needs attention`:"Tasks"]}),i&&s.jsxs("div",{role:"dialog","aria-label":"Background tasks",style:{position:"absolute",top:34,right:0,zIndex:1200,width:340,maxHeight:420,overflowY:"auto",background:t.modalBg,border:`1px solid ${t.cellBorder}`,borderRadius:9,boxShadow:"0 14px 36px rgba(0,0,0,0.28)",padding:8},children:[s.jsx("div",{style:{padding:"4px 6px 8px",color:t.textPrimary,fontSize:12,fontWeight:700},children:"Background tasks"}),l.map(d=>{const f=ff(d),m=f.active,S=f.tone==="failure"?t.error:f.tone==="attention"?t.warning:f.tone==="success"?t.success:t.textMuted;return s.jsxs("div",{style:{padding:"9px 8px",borderTop:`1px solid ${t.headerBorder}`,display:"flex",flexDirection:"column",gap:6},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("span",{style:{flex:1,color:t.textPrimary,fontSize:11.5,fontWeight:650},children:PC(d.type)}),s.jsx("span",{style:{color:S,fontSize:10},children:f.statusLabel})]}),s.jsx("div",{style:{color:f.tone==="failure"?t.error:f.tone==="attention"?t.warning:t.textSecondary,fontSize:10.5,lineHeight:1.4},children:f.message}),m&&s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[s.jsx("div",{style:{flex:1,height:3,borderRadius:99,overflow:"hidden",background:t.headerBorder},children:s.jsx("div",{style:{width:`${Math.max(3,d.progress)}%`,height:"100%",background:t.accent,transition:"width 180ms ease"}})}),d.cancellable&&s.jsx("button",{type:"button",onClick:()=>void o(d.id),style:{border:0,background:"transparent",color:t.textMuted,cursor:"pointer",fontSize:10,padding:0},children:"Cancel"})]}),d.type==="block_certification"&&s.jsx("div",{style:{color:t.textMuted,fontSize:9.5},children:f.guidance??(f.tone==="success"?"Certification is complete.":"The saved draft is preserved for review or retry.")}),(d.type==="agent_run"||d.type==="app_ai_build")&&s.jsx("div",{style:{color:t.textMuted,fontSize:9.5},children:m?"This continues while you work on another page.":d.status==="succeeded"?"Completed in the background.":"Open the original surface to review or retry."})]},d.id)})]})]})}function PC(e){return e==="block_certification"?"Block certification":e==="project_refresh"?"Project metadata refresh":e==="agent_run"?"AI request":e==="app_ai_build"?"App proposal":e.replace(/_/g," ")}const rs=new Map;function IC(e,t){let n=rs.get(e);n||(n={running:!1},rs.set(e,n));const r=n,o=new Promise((i,a)=>{r.pending?(r.pending.content=t,r.pending.waiters.push({resolve:i,reject:a})):r.pending={content:t,waiters:[{resolve:i,reject:a}]}});return r.running||(r.running=!0,(async()=>{for(;r.pending;){const i=r.pending;r.pending=void 0;try{await B.saveNotebook(e,i.content);for(const a of i.waiters)a.resolve()}catch(a){for(const c of i.waiters)c.reject(a)}}})().finally(()=>{r.running=!1,r.pending||rs.delete(e)})),o}function DC(e){const t=rs.get(e);return!!(t!=null&&t.running||t!=null&&t.pending)}function $C({t:e}){return s.jsx("div",{style:{width:28,height:28,borderRadius:6,background:"linear-gradient(135deg, #5b8cff 0%, #7c5cff 100%)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:s.jsx("span",{style:{color:"#ffffff",fontSize:10,fontWeight:700,fontFamily:e.fontMono,letterSpacing:"-0.5px"},children:"DQL"})})}function MC(){var te;const e=Ge(Lr(F=>({activeBlockPath:F.activeBlockPath,activeFile:F.activeFile,appMode:F.appMode,autoSave:F.autoSave,blockStudioDirty:F.blockStudioDirty,blockStudioDraft:F.blockStudioDraft,blockStudioMetadata:F.blockStudioMetadata,cells:F.cells,files:F.files,mainView:F.mainView,notebookDirty:F.notebookDirty,notebookMetadata:F.notebookMetadata,notebookTitle:F.notebookTitle,savingFile:F.savingFile,themeMode:F.themeMode}))),t=jn(),n=Qe[e.themeMode],{executeAll:r}=uf(),[o,i]=p.useState(!1),[a,c]=p.useState(""),[l,u]=p.useState(!1),[h,d]=p.useState(!1),[f,m]=p.useState(!1),[S,v]=p.useState(!1),[b,w]=p.useState(!1),j=p.useRef(null),[C,x]=p.useState(!1),[E,P]=p.useState(!1),A=p.useRef(null),g=p.useRef(null),I=e.mainView==="block_studio"?e.blockStudioDirty:e.notebookDirty,T=e.mainView==="notebook",O=e.mainView==="notebook"||e.mainView==="block_studio",_=O&&!!e.activeFile,M={home:"Home",business_artifact:((te=e.activeFile)==null?void 0:te.name.replace(/\.(dqlnb|dql)$/i,""))??"Business Definition",lineage:"Lineage",lineage_detail:"Lineage",connection:"Settings",apps:"Apps",git:"Source control",settings:"Settings",imports:"Import SQL",domains:"Modeling",modeling:"Modeling"},q=O?e.activeFile?e.notebookTitle||"Untitled":e.mainView==="block_studio"?"Blocks":"Notebooks":M[e.mainView]??"DQL Workbench";p.useEffect(()=>{o&&g.current&&(g.current.focus(),g.current.select())},[o]),p.useEffect(()=>{if(!E)return;function F(K){A.current&&!A.current.contains(K.target)&&P(!1)}return document.addEventListener("mousedown",F),()=>document.removeEventListener("mousedown",F)},[E]);const G=()=>{c(e.notebookTitle),i(!0)},J=()=>{i(!1),a.trim()&&a!==e.notebookTitle&&(e.mainView==="block_studio"&&e.blockStudioMetadata?(t({type:"SET_BLOCK_STUDIO_METADATA",metadata:{...e.blockStudioMetadata,name:a.trim()}}),t({type:"SET_BLOCK_STUDIO_DRAFT",draft:J1(e.blockStudioDraft,a.trim())})):t({type:"SET_NOTEBOOK_DIRTY",dirty:!0}))},H=p.useCallback(async()=>{var K,oe,ee;const F=In.getState();if(F.activeFile){t({type:"SET_SAVING",saving:!0});try{if(F.mainView==="block_studio"){if(!F.blockStudioMetadata)return;const ce=await B.saveBlockStudio({path:F.activeBlockPath,source:F.blockStudioDraft,metadata:{name:F.blockStudioMetadata.name,domain:F.blockStudioMetadata.domain,folderPath:F.blockStudioMetadata.folderPath,description:F.blockStudioMetadata.description,owner:F.blockStudioMetadata.owner,tags:F.blockStudioMetadata.tags}});t({type:"OPEN_BLOCK_STUDIO",file:{name:`${ce.metadata.name}.dql`,path:ce.path,type:"block",folder:"blocks"},payload:ce}),F.files.some(ke=>ke.path===ce.path)||t({type:"FILE_ADDED",file:{name:`${ce.metadata.name}.dql`,path:ce.path,type:"block",folder:"blocks"}})}else{const ce=F.activeFile,ke=F.cells,xe=F.notebookTitle,De=F.notebookMetadata,We=ce.type==="block"?((K=ke[0])==null?void 0:K.content)??"":L1(xe,ke,De);await IC(ce.path,We);const Be=In.getState();((oe=Be.activeFile)==null?void 0:oe.path)===ce.path&&Be.cells===ke&&Be.notebookTitle===xe&&Be.notebookMetadata===De&&t({type:"SET_NOTEBOOK_DIRTY",dirty:!1})}u(!0),setTimeout(()=>u(!1),2e3)}catch(ce){console.error("Save failed:",ce)}finally{const ce=(ee=In.getState().activeFile)==null?void 0:ee.path;(!ce||!DC(ce))&&t({type:"SET_SAVING",saving:!1})}}},[t]);p.useEffect(()=>{const F=K=>{(K.metaKey||K.ctrlKey)&&K.key==="s"&&(K.preventDefault(),H())};return document.addEventListener("keydown",F),()=>document.removeEventListener("keydown",F)},[H]),p.useEffect(()=>{if(!e.autoSave||!I||!e.activeFile||e.mainView==="block_studio")return;const F=setTimeout(()=>{H()},750);return()=>clearTimeout(F)},[e.autoSave,I,e.activeFile,e.cells,e.blockStudioDraft,H]);const L=[{mode:"obsidian",label:"Obsidian",glyph:"●",swatch:"#0d0e11"},{mode:"paper",label:"Paper",glyph:"☼",swatch:"#f7f4ed"},{mode:"white",label:"White",glyph:"○",swatch:"#ffffff"}],$=e.themeMode==="dark"||e.themeMode==="midnight"?"obsidian":e.themeMode==="light"?"paper":e.themeMode==="arctic"?"white":e.themeMode,X=L.find(F=>F.mode===$)??L[0];p.useEffect(()=>{if(!b)return;const F=oe=>{j.current&&!j.current.contains(oe.target)&&w(!1)},K=oe=>{oe.key==="Escape"&&w(!1)};return document.addEventListener("mousedown",F),document.addEventListener("keydown",K),()=>{document.removeEventListener("mousedown",F),document.removeEventListener("keydown",K)}},[b]);const W={height:28,padding:"0 10px",borderRadius:6,border:`1px solid ${n.btnBorder}`,cursor:"pointer",fontSize:12,fontWeight:500,fontFamily:n.font,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s, color 0.15s",whiteSpace:"nowrap"};return s.jsxs("div",{style:{height:48,flexShrink:0,background:n.headerBg,borderBottom:`1px solid ${n.headerBorder}`,display:"flex",alignItems:"center",padding:"0 12px",gap:8,userSelect:"none"},children:[s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[s.jsx($C,{t:n}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder,flexShrink:0}}),e.activeFile&&O&&s.jsx("span",{style:{fontSize:10,fontWeight:600,color:e.activeFile.type==="block"?"#e3b341":n.accent,background:`${e.activeFile.type==="block"?"#e3b341":n.accent}18`,borderRadius:4,padding:"2px 6px",fontFamily:n.font,textTransform:"uppercase",letterSpacing:"0.05em",flexShrink:0},children:e.activeFile.type}),e.activeFile&&O?o?s.jsx("input",{ref:g,value:a,onChange:F=>c(F.target.value),onBlur:J,onKeyDown:F=>{F.key==="Enter"&&J(),F.key==="Escape"&&i(!1)},style:{background:"transparent",border:`1px solid ${n.cellBorderActive}`,borderRadius:4,color:n.textPrimary,fontSize:13,fontWeight:500,fontFamily:n.font,padding:"2px 6px",outline:"none",minWidth:120,maxWidth:320}}):s.jsxs("span",{onClick:G,title:"Click to rename",style:{color:n.textPrimary,fontSize:13,fontWeight:500,fontFamily:n.font,cursor:"text",maxWidth:320,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",padding:"2px 4px",borderRadius:4,border:"1px solid transparent"},children:[q,I&&s.jsx("span",{style:{color:n.textMuted,marginLeft:4},children:"●"})]}):s.jsx("span",{style:{color:n.textSecondary,fontSize:13,fontFamily:n.font,padding:"2px 4px"},children:q||"DQL Workbench"})]}),s.jsx("div",{style:{flex:1}}),s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[s.jsx(_C,{}),e.appMode==="studio"&&_&&e.mainView!=="block_studio"&&s.jsx(s.Fragment,{children:s.jsxs("button",{onClick:T?r:void 0,disabled:!e.activeFile||!T,onMouseEnter:()=>d(!0),onMouseLeave:()=>d(!1),style:{...W,height:30,padding:"0 14px",borderRadius:999,background:n.accent,color:"#ffffff",border:`1px solid ${n.accent}`,opacity:!e.activeFile||!T?.4:h?.9:1,boxShadow:"0 1px 2px rgba(107,93,211,0.25)",gap:6},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})}),"Run all"]})}),s.jsxs("div",{ref:j,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>w(F=>!F),onMouseEnter:()=>v(!0),onMouseLeave:()=>v(!1),title:`Theme: ${X.label}`,"aria-haspopup":"true","aria-expanded":b,style:{...W,background:S||b?n.btnHover:n.btnBg,color:n.textSecondary,padding:"0 10px",fontSize:12,display:"flex",alignItems:"center",gap:6},children:[s.jsx("span",{style:{width:12,height:12,borderRadius:3,background:X.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{fontFamily:n.fontMono,fontSize:10,letterSpacing:"0.04em"},children:X.label}),s.jsx("span",{style:{fontSize:8,color:n.textMuted},children:"▾"})]}),b&&s.jsx("div",{role:"menu",style:{position:"absolute",top:"100%",right:0,marginTop:4,minWidth:160,background:n.headerBg,border:`1px solid ${n.headerBorder}`,borderRadius:6,boxShadow:"0 8px 24px rgba(0,0,0,0.32)",padding:4,zIndex:1e3,display:"flex",flexDirection:"column",gap:1},children:L.map(F=>{const K=F.mode===$;return s.jsxs("button",{role:"menuitemradio","aria-checked":K,onClick:()=>{t({type:"SET_THEME",mode:F.mode}),w(!1)},style:{display:"flex",alignItems:"center",gap:8,padding:"6px 8px",border:"none",background:K?n.btnHover:"transparent",color:n.textPrimary,cursor:"pointer",borderRadius:4,fontSize:12,fontFamily:n.font,textAlign:"left"},onMouseEnter:oe=>{K||(oe.currentTarget.style.background=n.btnHover)},onMouseLeave:oe=>{K||(oe.currentTarget.style.background="transparent")},children:[s.jsx("span",{style:{width:14,height:14,borderRadius:3,background:F.swatch,border:`1px solid ${n.headerBorder}`,flexShrink:0}}),s.jsx("span",{style:{flex:1},children:F.label}),K&&s.jsx("span",{style:{color:n.accent,fontSize:11},children:"✓"})]},F.mode)})})]}),e.appMode==="studio"&&_&&e.mainView!=="block_studio"&&s.jsxs(s.Fragment,{children:[s.jsx("button",{onClick:H,disabled:!e.activeFile||e.savingFile,onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),title:"Save (Cmd+S)",style:{...W,background:f&&e.activeFile?n.btnHover:n.btnBg,color:l?n.success:n.textSecondary,opacity:e.activeFile?1:.4},children:e.savingFile?s.jsxs(s.Fragment,{children:[s.jsx(NC,{}),"Saving…"]}):l?s.jsx(s.Fragment,{children:"✓ Saved"}):s.jsx(s.Fragment,{children:"Save"})}),s.jsx("div",{style:{width:1,height:20,background:n.headerBorder}})]}),_&&e.mainView!=="block_studio"&&s.jsxs("div",{ref:A,style:{position:"relative"},children:[s.jsxs("button",{onClick:()=>{e.activeFile&&P(F=>!F)},disabled:!e.activeFile,onMouseEnter:()=>x(!0),onMouseLeave:()=>x(!1),title:"Share / export",style:{...W,height:30,padding:"0 14px",borderRadius:999,background:(C||E)&&e.activeFile?"#2a2a30":"#1a1a1a",color:"#ffffff",border:"1px solid #1a1a1a",opacity:e.activeFile?1:.4,gap:6},children:[s.jsx("svg",{width:"11",height:"11",viewBox:"0 0 16 16",fill:"currentColor",children:s.jsx("path",{d:"M5.5 10.75a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 0 1.5h-3.5a.75.75 0 0 1-.75-.75Zm0-3a.75.75 0 0 1 .75-.75h3.5a.75.75 0 0 1 0 1.5h-3.5a.75.75 0 0 1-.75-.75ZM3 3.75A1.75 1.75 0 0 1 4.75 2h6.586c.464 0 .909.184 1.237.513l1.914 1.914c.329.328.513.773.513 1.237v6.586A1.75 1.75 0 0 1 13.25 14h-8.5A1.75 1.75 0 0 1 3 12.25Z"})}),"Share",s.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"currentColor",style:{marginLeft:1,opacity:.7},children:s.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),E&&s.jsx("div",{style:{position:"absolute",top:32,right:0,zIndex:200,background:n.modalBg,border:`1px solid ${n.cellBorder}`,borderRadius:8,boxShadow:"0 8px 24px rgba(0,0,0,0.3)",padding:4,minWidth:160,display:"flex",flexDirection:"column",gap:2},children:s.jsx(LC,{label:"Export HTML",description:"Standalone dashboard",t:n,onClick:()=>{hC(e.notebookTitle||"dashboard",e.cells),P(!1)}})})]})]})]})}function LC({label:e,description:t,t:n,onClick:r}){const[o,i]=p.useState(!1);return s.jsxs("button",{onClick:r,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:o?n.btnHover:"transparent",border:"none",borderRadius:5,cursor:"pointer",padding:"6px 10px",textAlign:"left",display:"flex",flexDirection:"column",gap:1,transition:"background 0.12s"},children:[s.jsx("span",{style:{fontSize:12,fontWeight:500,color:n.textPrimary,fontFamily:n.font},children:e}),s.jsx("span",{style:{fontSize:10,color:n.textMuted,fontFamily:n.font},children:t})]})}function NC(){return s.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",style:{animation:"spin 0.8s linear infinite"},children:[s.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"}),s.jsx("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.5",strokeDasharray:"14 7"})]})}function BC(e){return e.toTimeString().slice(0,8)}function FC(e){return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}function zC(){const{state:e,dispatch:t}=et(),n=Qe[e.themeMode],[r,o]=p.useState(!1),i=e.queryLog.filter(c=>c.error),a=c=>t({type:"SET_DEV_PANEL_TAB",tab:c});return s.jsxs("div",{style:{height:e.devPanelOpen?180:0,flexShrink:0,background:n.sidebarBg,borderTop:`1px solid ${n.headerBorder}`,display:"flex",flexDirection:"column",overflow:"hidden",transition:"height 0.2s ease",position:"relative"},children:[e.devPanelOpen&&s.jsxs(s.Fragment,{children:[s.jsxs("div",{style:{height:32,flexShrink:0,display:"flex",alignItems:"center",borderBottom:`1px solid ${n.headerBorder}`,padding:"0 8px",gap:2},children:[["logs","errors"].map(c=>s.jsx(qC,{label:c==="errors"?`Errors${i.length>0?` (${i.length})`:""}`:`Logs (${e.queryLog.length})`,active:e.devPanelTab===c,onClick:()=>a(c),t:n},c)),s.jsx("div",{style:{flex:1}}),s.jsx("button",{onClick:()=>t({type:"SET_CELLS",cells:e.cells}),title:"Clear logs",style:{background:"transparent",borderTop:"none",borderLeft:"none",borderRight:"none",borderBottom:"none",cursor:"pointer",color:n.textMuted,fontSize:11,fontFamily:n.font,padding:"2px 6px",borderRadius:4},children:"Clear"})]}),s.jsxs("div",{style:{flex:1,overflow:"auto",padding:"4px 0"},children:[e.devPanelTab==="logs"&&(e.queryLog.length===0?s.jsx(Bl,{t:n,message:"No queries executed yet."}):[...e.queryLog].reverse().map(c=>s.jsx(Fl,{entry:c,t:n},c.id))),e.devPanelTab==="errors"&&(i.length===0?s.jsx(Bl,{t:n,message:"No errors."}):[...i].reverse().map(c=>s.jsx(Fl,{entry:c,t:n},c.id)))]})]}),s.jsxs("button",{onClick:()=>t({type:"TOGGLE_DEV_PANEL"}),onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),title:e.devPanelOpen?"Close panel":"Open dev panel",style:{position:"absolute",bottom:e.devPanelOpen?4:-28,right:8,height:22,padding:"0 8px",borderRadius:"4px 4px 0 0",borderTop:`1px solid ${n.headerBorder}`,borderLeft:`1px solid ${n.headerBorder}`,borderRight:`1px solid ${n.headerBorder}`,borderBottom:e.devPanelOpen?`1px solid ${n.sidebarBg}`:`1px solid ${n.headerBorder}`,background:r?n.btnHover:n.sidebarBg,color:n.textMuted,cursor:"pointer",fontSize:11,fontFamily:n.font,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s, bottom 0.2s ease",zIndex:10},children:[s.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",children:s.jsx("path",{d:e.devPanelOpen?"M1 7l4-4 4 4":"M1 3l4 4 4-4",strokeWidth:"1.5",stroke:"currentColor",fill:"none"})}),"Dev"]})]})}function qC({label:e,active:t,onClick:n,t:r}){const[o,i]=p.useState(!1);return s.jsx("button",{onClick:n,onMouseEnter:()=>i(!0),onMouseLeave:()=>i(!1),style:{background:"transparent",borderTop:"none",borderLeft:"none",borderRight:"none",borderBottom:t?`2px solid ${r.accent}`:"2px solid transparent",cursor:"pointer",color:t?r.textPrimary:o?r.textSecondary:r.textMuted,fontSize:12,fontFamily:r.font,fontWeight:t?500:400,padding:"4px 8px",height:32,transition:"color 0.15s"},children:e})}function Bl({t:e,message:t}){return s.jsx("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",height:"100%",color:e.textMuted,fontSize:12,fontFamily:e.font,fontStyle:"italic"},children:t})}function Fl({entry:e,t}){return s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"3px 12px",fontSize:11,fontFamily:t.fontMono,color:e.error?t.error:t.textSecondary,borderLeft:e.error?`2px solid ${t.error}`:"2px solid transparent"},children:[s.jsx("span",{style:{color:t.textMuted,flexShrink:0},children:BC(e.ts)}),s.jsx("span",{style:{flexShrink:0,color:t.textPrimary,maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.cellName}),e.error?s.jsx("span",{style:{color:t.error,flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.error}):s.jsxs(s.Fragment,{children:[s.jsxs("span",{style:{color:t.textMuted},children:[e.rows.toLocaleString()," rows"]}),s.jsx("span",{style:{color:t.textMuted},children:FC(e.time)})]})]})}function UC(){const{state:e,dispatch:t}=et(),{executeAll:n}=uf();p.useEffect(()=>{const r=o=>{const i=o.metaKey||o.ctrlKey;if(i&&o.key==="b"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_SIDEBAR"});return}if(i&&o.shiftKey&&o.key==="Enter"){o.preventDefault(),e.activeFile&&n();return}if(i&&o.key==="j"&&!o.shiftKey){o.preventDefault(),t({type:"TOGGLE_DEV_PANEL"});return}if(i&&o.key==="d"&&!o.shiftKey){o.preventDefault(),e.activeFile&&t({type:"TOGGLE_DASHBOARD_MODE"});return}if(o.key==="Escape"){if(e.dashboardMode){t({type:"TOGGLE_DASHBOARD_MODE"});return}if(e.newNotebookModalOpen){t({type:"CLOSE_NEW_NOTEBOOK_MODAL"});return}if(e.newBlockModalOpen){t({type:"CLOSE_NEW_BLOCK_MODAL"});return}}};return document.addEventListener("keydown",r),()=>document.removeEventListener("keydown",r)},[t,n,e.activeFile,e.newNotebookModalOpen,e.newBlockModalOpen,e.dashboardMode])}const WC=600;function KC(e,t){const n=t.filter(r=>r.result||r.error||(r.executionCount??0)>0).map(r=>{var o;return{cellId:r.id,status:r.status,result:r.result,error:r.error,executionCount:r.executionCount,executedAt:((o=r.execution)==null?void 0:o.completedAt)??new Date().toISOString(),execution:r.execution}});return{version:1,notebookPath:e,capturedAt:new Date().toISOString(),cells:n}}function zl(e){return e.map(t=>{var n,r;return`${t.id}:${((n=t.execution)==null?void 0:n.runId)??""}:${t.executionCount??0}:${((r=t.result)==null?void 0:r.rowCount)??-1}:${t.error??""}`}).join("|")}function VC(){var o;const{state:e}=et(),t=p.useRef(null),n=p.useRef(""),r=p.useRef(null);p.useEffect(()=>{var c;const i=((c=e.activeFile)==null?void 0:c.path)??null;if(!i)return;if(i!==r.current){r.current=i,n.current=zl(e.cells);return}const a=zl(e.cells);return a!==n.current&&(n.current=a,t.current&&clearTimeout(t.current),t.current=setTimeout(()=>{const l=KC(i,e.cells);B.saveRunSnapshot(i,l).catch(()=>{})},WC)),()=>{t.current&&(clearTimeout(t.current),t.current=null)}},[e.cells,(o=e.activeFile)==null?void 0:o.path])}const hE="core";function HC(e){var n;const t=e==null?void 0:e.trim();if(t)return((n=t.split("::").at(-1))==null?void 0:n.trim())||void 0}const GC=[{items:[{id:"diagram",label:"Modeling"},{id:"skills",label:"Skills"},{id:"blocks",label:"Blocks"},{id:"notebooks",label:"Notebooks"},{id:"apps",label:"Apps"}]}],QC=new Set(GC.flatMap(e=>e.items.map(t=>t.id)));function hf(e){return e!==null&&QC.has(e)}function mE(e,t){const n=new URL(e);return t.domain?n.searchParams.set("domain",t.domain):n.searchParams.delete("domain"),n.searchParams.set("domainSection",t.section),t.modelAreaId?n.searchParams.set("modelArea",t.modelAreaId):n.searchParams.delete("modelArea"),t.selectedId?n.searchParams.set("domainObject",t.selectedId):n.searchParams.delete("domainObject"),`${n.pathname}${n.search}${n.hash}`}function JC(e){const t=new URL(e);for(const n of mf)t.searchParams.delete(n);return`${t.pathname}${t.search}${t.hash}`}const mf=["domain","domainSection","modelArea","domainObject"],gE="dql.domain-studio.location";function yE(e,t){const n=new URL(e).searchParams;if(mf.some(r=>n.has(r))){const r=n.get("domainSection"),o=hf(r)?r:"diagram";return{domain:n.get("domain"),section:o,modelAreaId:n.get("modelArea"),selectedId:r==="diagram"?n.get("domainObject"):null}}return YC(t)}function YC(e){const t={domain:null,section:"diagram",modelAreaId:null,selectedId:null};if(!e)return t;try{const n=JSON.parse(e),r=typeof n.section=="string"&&hf(n.section)?n.section:"diagram",o=i=>typeof i=="string"&&i.trim()?i:null;return{domain:o(n.domain),section:r,modelAreaId:o(n.modelAreaId),selectedId:o(n.selectedId)}}catch{return t}}function bE(e){return`modeling:${e??"all"}`}function xE(e){const t=Object.values(e),n=new Map;for(const a of t){const c=a.parent&&e[a.parent]?a.parent:void 0;n.set(c,[...n.get(c)??[],a])}for(const a of n.values())a.sort((c,l)=>c.id.localeCompare(l.id));const r=[],o=new Set,i=(a,c)=>{for(const l of n.get(a)??[])o.has(l.id)||(o.add(l.id),r.push({id:l.id,parent:l.parent,depth:c,label:c===0?l.id:`${"— ".repeat(c)}${l.id.split(".").at(-1)??l.id}`}),i(l.id,c+1))};i(void 0,0);for(const a of t.sort((c,l)=>c.id.localeCompare(l.id)))o.has(a.id)||r.push({id:a.id,parent:a.parent,depth:0,label:a.id});return r}function vE(e){const t=(e??"").toLowerCase();return t==="dimension"?"var(--status-success)":t==="bridge"?"var(--status-warning)":t==="event"||t==="snapshot"?"var(--accent)":"var(--text-tertiary)"}function gf(e){return Object.entries(e.entities).map(([t,n])=>({recordKey:t,entity:n}))}function SE(e,t){if(e.entities[t])return t;const n=gf(e).filter(({entity:r})=>r.id===t||r.qualifiedId===t);return n.length===1?n[0].recordKey:void 0}function wE(e,t){return gf(e).filter(({entity:n})=>!t||n.domain===t)}function kE(e,t,n){if(e.operation==="upsert_entity"){if(!t)return!1;const r=e.value;return r.dbtModel===t.dbtUniqueId&&(r.grain??void 0)===(t.grain??void 0)&&JSON.stringify(r.keys??[])===JSON.stringify(t.keys??[])&&(r.status??t.status)===t.status&&(r.areaId??void 0)===HC(t.areaId)&&r.domain===t.domain}return e.operation==="upsert_area"?!!n&&e.value.domain===n.domain&&e.value.id===n.localId:!1}const XC=p.lazy(()=>_e(()=>import("./HomePage-eIkfBIep.js"),__vite__mapDeps([0,1,2,3,4,5,6])).then(e=>({default:e.HomePage}))),ZC=p.lazy(()=>_e(()=>import("./AnalyticsHome-D5P6Ujwi.js"),__vite__mapDeps([7,8,9,10,1,11,12,3,13,14,15,16,17,2,18,6])).then(e=>({default:e.AnalyticsHome}))),ej=p.lazy(()=>_e(()=>import("./GlobalAiRail-CVECf6Xj.js"),__vite__mapDeps([19,9,10,1,11,12,3,13,14,15,16,17,2,20,6])).then(e=>({default:e.GlobalAiRail}))),tj=p.lazy(()=>_e(()=>import("./NotebookEditor-DjqJS44s.js"),__vite__mapDeps([21,4,2,5,22,23,24,10,1,11,12,3,13,14,9,15,16,17,8,25,26,6,27,28,20,29])).then(e=>({default:e.NotebookEditor}))),nj=p.lazy(()=>_e(()=>import("./NewNotebookModal-5Vp6XiuK.js"),__vite__mapDeps([30,4,15,6])).then(e=>({default:e.NewNotebookModal}))),rj=p.lazy(()=>_e(()=>import("./NewBlockModal-DbCQg-pj.js"),__vite__mapDeps([31,6])).then(e=>({default:e.NewBlockModal}))),oj=p.lazy(()=>_e(()=>import("./SetupOnboarding-BfS9Tdx-.js"),__vite__mapDeps([32,33,2,6])).then(e=>({default:e.SetupOnboarding}))),sj=p.lazy(()=>_e(()=>import("./BlockStudio-B4ap0GdY.js"),__vite__mapDeps([34,22,23,10,1,11,12,3,13,14,25,26,6,27,9,15,16,17,2,20,35,36])).then(e=>({default:e.BlockStudio}))),ij=p.lazy(()=>_e(()=>import("./BusinessArtifactView-BIfNI-0S.js"),__vite__mapDeps([37,25,26,6,27])).then(e=>({default:e.BusinessArtifactView}))),aj=p.lazy(()=>_e(()=>import("./LineageDetailView-DJZZjZu-.js"),__vite__mapDeps([38,25,26,6,27,39,33,16])).then(e=>({default:e.LineageDetailView}))),cj=p.lazy(()=>_e(()=>import("./LineageDAG-CSqcbDrE.js"),__vite__mapDeps([39,26,6,27])).then(e=>({default:e.LineageDAG}))),lj=p.lazy(()=>_e(()=>import("./HelpDocsPage-D8hLS5lE.js"),__vite__mapDeps([40,6])).then(e=>({default:e.HelpDocsPage}))),dj=p.lazy(()=>_e(()=>Promise.resolve().then(()=>i1),void 0).then(e=>({default:e.ConnectionPanel}))),uj=p.lazy(()=>_e(()=>import("./GitPage-lQb1uXH2.js"),__vite__mapDeps([41,42,15,6])).then(e=>({default:e.GitPage}))),pj=p.lazy(()=>_e(()=>import("./ReadinessPage-BHGrC5ho.js"),__vite__mapDeps([43,1,44,45,12,3,2,6])).then(e=>({default:e.ReadinessPage}))),fj=p.lazy(()=>_e(()=>import("./AgentLogPage-BPz-UWFh.js"),__vite__mapDeps([46,33,14,47,6])).then(e=>({default:e.AgentLogPage}))),hj=p.lazy(()=>_e(()=>import("./GovernedContextPage-trOyMCY6.js"),__vite__mapDeps([48,3,12,9,10,1,11,13,14,15,16,17,2,49,6])).then(e=>({default:e.GovernedContextPage}))),mj=p.lazy(()=>_e(()=>import("./DbtFirstModelingPage-D72byb2g.js"),__vite__mapDeps([50,49,9,10,1,11,12,3,13,14,15,16,17,2,26,6,27,28,29,36,51,47])).then(e=>({default:e.DbtFirstModelingPage}))),gj=p.lazy(()=>_e(()=>import("./AppsView-DQOwU9Cg.js"),__vite__mapDeps([52,20,17,10,1,11,12,3,13,14,15,33,35,29,4,5,24,8,45,53,51,2,18,6])).then(e=>({default:e.AppsView}))),yj=p.lazy(()=>_e(()=>import("./LineageDrawer-BcIipIc3.js"),__vite__mapDeps([54,25,26,6,27,36,15,17,13,53,42])).then(e=>({default:e.LineageDrawer}))),bj=p.lazy(()=>_e(()=>import("./AiBuildDialog-BEl53WA_.js"),__vite__mapDeps([55,44,11,12,3,13,15,6])).then(e=>({default:e.AiBuildDialog})));function xj(){const e=Ge(Lr(d=>({appMode:d.appMode,dashboardMode:d.dashboardMode,globalAi:d.globalAi,inspectorOpen:d.inspectorOpen,lineageDrawerOpen:d.lineageDrawerOpen,lineageFullscreen:d.lineageFullscreen,mainView:d.mainView,newBlockModalOpen:d.newBlockModalOpen,newNotebookModalOpen:d.newNotebookModalOpen,setupOpen:d.setupOpen,sidebarOpen:d.sidebarOpen,sidebarPanel:d.sidebarPanel,themeMode:d.themeMode}))),t=jn(),n=Qe[e.themeMode],r=p.useRef({}),o=e.mainView==="block_studio"||e.mainView==="imports",[i,a]=p.useState(!1),[c,l]=p.useState(null);p.useEffect(()=>{let d=!0;return B.getSetupLaunch().then(f=>{d&&(l(f),f.shouldOpen&&t({type:"OPEN_SETUP"}))}).catch(()=>{}),()=>{d=!1}},[t]),p.useEffect(()=>{const d=()=>t({type:"SET_MAIN_VIEW",view:"modeling"});return window.addEventListener("dql:open-context-proposal",d),()=>window.removeEventListener("dql:open-context-proposal",d)},[t]),p.useEffect(()=>{if(e.mainView==="domains"||e.mainView==="modeling"||e.mainView==="skills")return;const d=JC(window.location.href),f=`${window.location.pathname}${window.location.search}${window.location.hash}`;d!==f&&window.history.replaceState(window.history.state,"",d)},[e.mainView]),UC(),VC(),p.useEffect(()=>{const d=f=>{(f.metaKey||f.ctrlKey)&&f.key.toLowerCase()==="k"&&!f.shiftKey&&(f.preventDefault(),a(m=>!m)),(f.metaKey||f.ctrlKey)&&f.shiftKey&&f.key.toLowerCase()==="i"&&(f.preventDefault(),t({type:"TOGGLE_INSPECTOR"}))};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[t]);const u=p.useCallback(async d=>{try{if(d.type==="term"||d.type==="business_view"){e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"}),t({type:"OPEN_BUSINESS_ARTIFACT",file:d});return}if(d.type==="block"){const j=await B.openBlockStudio(d.path);t({type:"OPEN_BLOCK_STUDIO",file:d,payload:j});return}const{content:f}=await B.readNotebook(d.path),{title:m,cells:S,metadata:v}=N1(d.path,f),b=d.path.endsWith(".dqlnb")?await B.fetchRunSnapshot(d.path):null;let w=S;if(b!=null&&b.found&&b.snapshot){const j=new Map(b.snapshot.cells.map(C=>[C.cellId,C]));w=S.map(C=>{const x=j.get(C.id);return x?{...C,status:x.status??C.status,result:x.result??C.result,error:x.error??C.error,executionCount:x.executionCount??C.executionCount,execution:x.execution??C.execution,fromSnapshot:x.result!=null}:C})}t({type:"OPEN_FILE",file:d,cells:w,title:m,metadata:v}),e.sidebarPanel!=="files"&&t({type:"SET_SIDEBAR_PANEL",panel:"files"})}catch(f){if(console.error("Failed to open file:",f),d.type==="block")try{const{content:m}=await B.readNotebook(d.path);t({type:"OPEN_BLOCK_STUDIO",file:d,payload:{path:d.path,source:m,companionPath:null,metadata:{name:d.name.replace(/\.dql$/i,""),path:d.path,domain:d.path.split("/").slice(1,-1).join("/")||"uncategorized",description:"",owner:"",tags:[]},validation:{valid:!1,diagnostics:[{severity:"warning",message:"Opened block without studio metadata. Save once to normalize it."}],semanticRefs:{metrics:[],dimensions:[],segments:[]}}}});return}catch(m){console.error("Failed to open block fallback:",m)}else t({type:"OPEN_FILE",file:d,cells:[Ra("sql")],title:d.name})}},[t,e.sidebarPanel]);p.useCallback(d=>{const f=r.current[d];f&&f.scrollIntoView({behavior:"smooth",block:"start"})},[]);const h=p.useCallback((d,f)=>{f?r.current[d]=f:delete r.current[d]},[]);return s.jsxs("div",{style:{display:"flex",flexDirection:"column",height:"100vh",width:"100vw",background:n.appBg,fontFamily:n.font,color:n.textPrimary,overflow:"hidden"},children:[s.jsx(MC,{}),s.jsxs("div",{style:{flex:1,display:"flex",overflow:"hidden"},children:[e.appMode==="studio"&&s.jsx(Ww,{}),e.appMode==="studio"&&e.sidebarOpen&&!o&&s.jsx(_1,{onOpenFile:u}),s.jsx("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",minWidth:0},children:s.jsx(p.Suspense,{fallback:s.jsx(vj,{t:n}),children:e.mainView==="home"?s.jsx(XC,{}):e.mainView==="ask"?s.jsx(ZC,{}):e.mainView==="business_artifact"?s.jsx(ij,{}):e.mainView==="lineage"?s.jsx("div",{style:{flex:1,minWidth:0,minHeight:0,display:"flex",flexDirection:"column",overflow:"hidden"},children:s.jsx(cj,{})}):e.mainView==="lineage_detail"?s.jsx(aj,{}):e.mainView==="help"?s.jsx(lj,{}):e.mainView==="connection"||e.mainView==="settings"?s.jsx(wj,{children:s.jsx(dj,{variant:"page"})}):e.mainView==="git"?s.jsx(uj,{}):e.mainView==="readiness"?s.jsx(pj,{}):e.mainView==="skills"?s.jsx(hj,{initialTab:"skills"}):e.mainView==="domains"||e.mainView==="modeling"?s.jsx(mj,{}):e.mainView==="apps"?s.jsx(gj,{}):e.mainView==="agent_log"?s.jsx(kj,{title:"Agent steps",description:"What the agent did to answer this question, and where the time went — route, tools, checks, and per-step timing.",children:s.jsx(fj,{})}):s.jsx(s.Fragment,{children:e.mainView==="imports"||e.mainView==="block_studio"?s.jsx(sj,{},"block-editor"):s.jsxs(s.Fragment,{children:[s.jsx(tj,{onOpenFile:u,registerCellRef:h}),e.appMode==="studio"&&s.jsx(zC,{})]})})})}),e.appMode==="studio"&&e.lineageDrawerOpen&&!e.lineageFullscreen&&!e.dashboardMode&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(yj,{})}),e.appMode==="studio"&&e.inspectorOpen&&!e.lineageFullscreen&&!e.lineageDrawerOpen&&!e.dashboardMode&&s.jsx(Pw,{}),e.globalAi.open&&e.mainView==="apps"&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(ej,{})})]}),e.newNotebookModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(nj,{onFileOpened:u})}),e.newBlockModalOpen&&s.jsx(p.Suspense,{fallback:null,children:s.jsx(rj,{onFileOpened:u})}),s.jsx(ZS,{open:i,onClose:()=>a(!1)}),s.jsx(p.Suspense,{fallback:null,children:s.jsx(bj,{})}),e.setupOpen&&s.jsx(p.Suspense,{fallback:s.jsx(Sj,{t:n}),children:s.jsx(oj,{launch:c!=null&&c.shouldOpen?c:void 0,onAcknowledged:()=>l(d=>d&&{...d,shouldOpen:!1,reason:null})})})]})}function vj({t:e}){return s.jsx("div",{role:"status","aria-live":"polite",style:{flex:1,minWidth:0,display:"grid",placeItems:"center",background:e.appBg,color:e.textSecondary,fontFamily:e.font},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,fontSize:12.5},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:999,background:e.accent}}),"Loading workspace…"]})})}function Sj({t:e}){return s.jsx("div",{role:"status","aria-live":"polite",style:{position:"fixed",inset:0,zIndex:1100,display:"grid",placeItems:"center",background:e.appBg,color:e.textSecondary,fontFamily:e.font},children:s.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,fontSize:12.5},children:[s.jsx("span",{style:{width:8,height:8,borderRadius:999,background:e.accent}}),"Checking workspace setup…"]})})}function wj({children:e}){return s.jsx("div",{style:{flex:1,minWidth:0,overflow:"auto"},children:s.jsx("div",{style:{maxWidth:1120,margin:"0 auto",padding:"18px 28px 32px"},children:e})})}function kj({title:e,description:t,children:n}){return s.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",minWidth:0,overflow:"hidden"},children:[s.jsxs("div",{style:{padding:"18px 24px 12px",borderBottom:"1px solid rgba(127, 127, 127, 0.16)"},children:[s.jsx("div",{style:{fontSize:22,fontWeight:700},children:e}),s.jsx("div",{style:{fontSize:13,opacity:.72,marginTop:6,maxWidth:760,lineHeight:1.5},children:t})]}),s.jsx("div",{style:{flex:1,minHeight:0,overflow:"auto"},children:n})]})}function Cj(){const e=jn(),t=Yi(),n=p.useRef(null);p.useEffect(()=>{let r=!0,o=null,i=null,a=null,c=null;const l=()=>{i&&clearTimeout(i),i=setTimeout(()=>{i=null,B.listNotebooks().then(f=>{r&&(t.setQueryData(["notebooks"],f),e({type:"SET_FILES",files:f}))}).catch(()=>{})},150)},u=()=>{a&&clearTimeout(a),a=setTimeout(()=>{a=null,B.getDomains().then(({domains:f})=>{r&&(t.setQueryData(["authored-domains"],{domains:f}),e({type:"SET_AUTHORED_DOMAINS",domains:f}))}).catch(()=>{})},150)},h=()=>{c&&clearTimeout(c),c=setTimeout(()=>{c=null,e({type:"SET_SEMANTIC_LOADING",loading:!0}),B.getSemanticLayer().then(f=>{r&&(t.setQueryData(["semantic-layer"],f),e({type:"SET_SEMANTIC_LAYER",layer:f}))}).catch(()=>{})},100)},d=()=>{if(!r)return;const f=new AbortController;n.current=f,Ep("/api/watch",m=>{if(m.event==="change")try{const S=JSON.parse(m.data);if(S.type==="file-added"||S.type==="file-deleted"||S.type==="file-changed"){const v=S.path??"";/^(?:notebooks|workbooks|blocks|skills|apps|dashboards)\//.test(v)&&l(),v.startsWith("domains/")&&(l(),u())}S.type==="semantic-reload"&&h()}catch{}},f.signal).catch(()=>{!r||f.signal.aborted||(o&&clearTimeout(o),o=setTimeout(d,5e3))})};return d(),()=>{var f;r=!1,o&&clearTimeout(o),i&&clearTimeout(i),a&&clearTimeout(a),c&&clearTimeout(c),(f=n.current)==null||f.abort(),n.current=null}},[e,t])}const jj=new ah({defaultOptions:{queries:{staleTime:15e3,gcTime:5*6e4,retry:1,refetchOnWindowFocus:!1}}});function Ej(){const e=Ge(i=>i.themeMode),t=Ge(i=>i.dispatch),n=Qe[e];p.useEffect(()=>{const i="dql-global-styles";let a=document.getElementById(i);a||(a=document.createElement("style"),a.id=i,document.head.appendChild(a)),a.textContent=`
|
|
611
611
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
|
612
612
|
body {
|
|
613
613
|
font-family: var(--font-ui, ${n.font});
|
|
@@ -632,4 +632,4 @@ ${t}`;return r.replace(/\n\}\s*$/,`${o}
|
|
|
632
632
|
background: var(--dql-pill-hover-bg) !important;
|
|
633
633
|
border-color: var(--dql-pill-hover-border) !important;
|
|
634
634
|
}
|
|
635
|
-
`},[n]),p.useEffect(()=>{const i=e==="dark"||e==="midnight"?"obsidian":e==="light"?"paper":e==="arctic"?"white":e;document.documentElement.setAttribute("data-theme",i)},[e]);const r=Ri({queryKey:["notebooks"],queryFn:()=>B.listNotebooks()}),o=Ri({queryKey:["authored-domains"],queryFn:()=>B.getDomains()});return p.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:r.isLoading}),r.data&&t({type:"SET_FILES",files:r.data})},[t,r.data,r.isLoading]),p.useEffect(()=>{o.data&&t({type:"SET_AUTHORED_DOMAINS",domains:o.data.domains})},[t,o.data]),Cj(),s.jsx(wh,{theme:e,applyGlobal:!0,children:s.jsx(Ig,{delayDuration:200,skipDelayDuration:400,children:s.jsx(xj,{})})})}function Tj(){return s.jsx(ch,{client:jj,children:s.jsx(Qx,{children:s.jsx(CC,{children:s.jsx(Ej,{})})})})}$f.createRoot(document.getElementById("root")).render(s.jsx(Tj,{}));export{yp as $,ef as A,Oa as B,Rv as C,To as D,q1 as E,Pa as F,Nr as G,eE as H,Zj as I,In as J,uf as K,Un as L,vt as M,bS as N,pE as O,OS as P,xk as Q,qe as R,xp as S,vp as T,Ao as U,Jn as V,Fw as W,Fj as X,zj as Y,Hj as Z,qj as _,B as a,N1 as a$,ps as a0,Uk as a1,Qp as a2,ti as a3,Fi as a4,Gj as a5,jC as a6,Ri as a7,fE as a8,oE as a9,Bj as aA,Ow as aB,_w as aC,Mj as aD,Zc as aE,hS as aF,ov as aG,cv as aH,iS as aI,tS as aJ,_v as aK,Ev as aL,SE as aM,gf as aN,vE as aO,hE as aP,wE as aQ,gE as aR,yE as aS,mE as aT,xE as aU,Fp as aV,GC as aW,Lv as aX,mp as aY,bE as aZ,kE as a_,ik as aa,cE as ab,lE as ac,Q1 as ad,J1 as ae,sE as af,Xj as ag,tf as ah,Yj as ai,iE as aj,X1 as ak,Y1 as al,rE as am,Il as an,aE as ao,ys as ap,M0 as aq,St as ar,Hc as as,Kj as at,Vj as au,Wj as av,Uj as aw,Ap as ax,Lj as ay,Nj as az,Re as b,uS as b0,gS as b1,DS as b2,rS as b3,_e as b4,Yi as b5,Qj as b6,Bv as b7,up as b8,NS as b9,Uv as ba,zi as bb,nE as bc,
|
|
635
|
+
`},[n]),p.useEffect(()=>{const i=e==="dark"||e==="midnight"?"obsidian":e==="light"?"paper":e==="arctic"?"white":e;document.documentElement.setAttribute("data-theme",i)},[e]);const r=Ri({queryKey:["notebooks"],queryFn:()=>B.listNotebooks()}),o=Ri({queryKey:["authored-domains"],queryFn:()=>B.getDomains()});return p.useEffect(()=>{t({type:"SET_FILES_LOADING",loading:r.isLoading}),r.data&&t({type:"SET_FILES",files:r.data})},[t,r.data,r.isLoading]),p.useEffect(()=>{o.data&&t({type:"SET_AUTHORED_DOMAINS",domains:o.data.domains})},[t,o.data]),Cj(),s.jsx(wh,{theme:e,applyGlobal:!0,children:s.jsx(Ig,{delayDuration:200,skipDelayDuration:400,children:s.jsx(xj,{})})})}function Tj(){return s.jsx(ch,{client:jj,children:s.jsx(Qx,{children:s.jsx(CC,{children:s.jsx(Ej,{})})})})}$f.createRoot(document.getElementById("root")).render(s.jsx(Tj,{}));export{yp as $,ef as A,Oa as B,Rv as C,To as D,q1 as E,Pa as F,Nr as G,eE as H,Zj as I,In as J,uf as K,Un as L,vt as M,bS as N,pE as O,OS as P,xk as Q,qe as R,xp as S,vp as T,Ao as U,Jn as V,Fw as W,Fj as X,zj as Y,Hj as Z,qj as _,B as a,N1 as a$,ps as a0,Uk as a1,Qp as a2,ti as a3,Fi as a4,Gj as a5,jC as a6,Ri as a7,fE as a8,oE as a9,Bj as aA,Ow as aB,_w as aC,Mj as aD,Zc as aE,hS as aF,ov as aG,cv as aH,iS as aI,tS as aJ,_v as aK,Ev as aL,SE as aM,gf as aN,vE as aO,hE as aP,wE as aQ,gE as aR,yE as aS,mE as aT,xE as aU,Fp as aV,GC as aW,Lv as aX,mp as aY,bE as aZ,kE as a_,ik as aa,cE as ab,lE as ac,Q1 as ad,J1 as ae,sE as af,Xj as ag,tf as ah,Yj as ai,iE as aj,X1 as ak,Y1 as al,rE as am,Il as an,aE as ao,ys as ap,M0 as aq,St as ar,Hc as as,Kj as at,Vj as au,Wj as av,Uj as aw,Ap as ax,Lj as ay,Nj as az,Re as b,uS as b0,gS as b1,DS as b2,rS as b3,_e as b4,Yi as b5,Qj as b6,Bv as b7,up as b8,NS as b9,Uv as ba,zi as bb,nE as bc,an as bd,Zi as be,ne as c,_a as d,Is as e,hp as f,bv as g,Ge as h,Lr as i,s as j,jn as k,FS as l,Ra as m,H1 as n,Jj as o,Tw as p,Aw as q,p as r,dE as s,Qe as t,et as u,uE as v,nf as w,rf as x,tE as y,K1 as z};
|