@duckcodeailabs/dql-cli 1.13.1 → 1.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/dist/apps-api.d.ts +249 -7
  2. package/dist/apps-api.d.ts.map +1 -1
  3. package/dist/apps-api.js +2855 -160
  4. package/dist/apps-api.js.map +1 -1
  5. package/dist/assets/dql-notebook/assets/{AgentLogPage-D6fgEAEy.js → AgentLogPage-B3ugEb3H.js} +1 -1
  6. package/dist/assets/dql-notebook/assets/{AiBuildDialog-8miXFPse.js → AiBuildDialog-BK_TDNcM.js} +1 -1
  7. package/dist/assets/dql-notebook/assets/{AiBuildResult-DPJ_SI0R.js → AiBuildResult-Cob_Lj05.js} +8 -8
  8. package/dist/assets/dql-notebook/assets/{AiSidePanel-NVA6lZnn.js → AiSidePanel-CzIgxmP9.js} +1 -1
  9. package/dist/assets/dql-notebook/assets/AnalyticsHome-C2vJ2fxY.js +6 -0
  10. package/dist/assets/dql-notebook/assets/AppsView-DEWQ0sHT.js +5588 -0
  11. package/dist/assets/dql-notebook/assets/BlockStudio-CaDNTKMM.js +55 -0
  12. package/dist/assets/dql-notebook/assets/{BusinessArtifactView-DtRMiaF4.js → BusinessArtifactView-zwUOtddi.js} +1 -1
  13. package/dist/assets/dql-notebook/assets/DbtFirstModelingPage-BlnhTMu3.js +22 -0
  14. package/dist/assets/dql-notebook/assets/{GitPage-CazC-eTR.js → GitPage-Coevr9NJ.js} +3 -3
  15. package/dist/assets/dql-notebook/assets/GlobalAiRail-BTZS11x5.js +1 -0
  16. package/dist/assets/dql-notebook/assets/GovernedContextPage-CjyyM_ne.js +7 -0
  17. package/dist/assets/dql-notebook/assets/{HelpDocsPage-DMHPsVqP.js → HelpDocsPage-C1UeP85v.js} +1 -1
  18. package/dist/assets/dql-notebook/assets/{HomePage-DcSI4dnU.js → HomePage-zGPFIvOY.js} +1 -1
  19. package/dist/assets/dql-notebook/assets/{LineageDAG-BJ6xz06u.js → LineageDAG-DbXnQWu3.js} +1 -1
  20. package/dist/assets/dql-notebook/assets/{LineageDetailView-8WrQm-MF.js → LineageDetailView-Ch1Db01I.js} +1 -1
  21. package/dist/assets/dql-notebook/assets/{LineageDrawer-hnqCW_t-.js → LineageDrawer-DLxqJO6D.js} +1 -1
  22. package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-B4LZTUsl.js → LineagePathBreadcrumb-B2tNdkr_.js} +3 -3
  23. package/dist/assets/dql-notebook/assets/{MiniLineageGraph-CotnRuxa.js → MiniLineageGraph-0gY-ZwCy.js} +1 -1
  24. package/dist/assets/dql-notebook/assets/{NewBlockModal-DHn-CEEW.js → NewBlockModal-DKVkXD20.js} +1 -1
  25. package/dist/assets/dql-notebook/assets/{NewNotebookModal-BPGp-8oq.js → NewNotebookModal-BUIByvYT.js} +1 -1
  26. package/dist/assets/dql-notebook/assets/{NotebookEditor-B0OTHM6W.js → NotebookEditor-D2fIUxjE.js} +5 -5
  27. package/dist/assets/dql-notebook/assets/{ReadinessPage-CoOIpxWq.js → ReadinessPage-Ci4LyNiQ.js} +1 -1
  28. package/dist/assets/dql-notebook/assets/{SetupOnboarding-DxK_mFzf.js → SetupOnboarding-BF7ai_0t.js} +1 -1
  29. package/dist/assets/dql-notebook/assets/SkillsPage-BgYrgirJ.js +10 -0
  30. package/dist/assets/dql-notebook/assets/{TrustBadge-ZuD5N5Ww.js → TrustBadge-Bob1Laiq.js} +1 -1
  31. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-IxDUKSG8.js +88 -0
  32. package/dist/assets/dql-notebook/assets/{answer-to-notebook-WAVAYjBv.js → answer-to-notebook-Dk42N0pU.js} +1 -1
  33. package/dist/assets/dql-notebook/assets/{arrow-left-L8odLbyN.js → arrow-left-DKuuTw9l.js} +1 -1
  34. package/dist/assets/dql-notebook/assets/{arrow-right-WIF1V9a9.js → arrow-right-TH8_ufKG.js} +1 -1
  35. package/dist/assets/dql-notebook/assets/{book-open-text-BpqWMa4m.js → book-open-text-B-dcHHn0.js} +1 -1
  36. package/dist/assets/dql-notebook/assets/{circle-x-CQBOM0b0.js → circle-x-BOc2KCZQ.js} +1 -1
  37. package/dist/assets/dql-notebook/assets/{dagre.esm-DlZi7NR3.js → dagre.esm-CPT_vn5p.js} +1 -1
  38. package/dist/assets/dql-notebook/assets/{external-link-DYqdQIGp.js → external-link-DtOfpYc6.js} +1 -1
  39. package/dist/assets/dql-notebook/assets/{grip-vertical-HmUijbwN.js → grip-vertical-B8joDDH9.js} +1 -1
  40. package/dist/assets/dql-notebook/assets/index-B3shyZsg.css +1 -0
  41. package/dist/assets/dql-notebook/assets/index-DJRMz64S.js +635 -0
  42. package/dist/assets/dql-notebook/assets/link-2-DMZPHawg.js +6 -0
  43. package/dist/assets/dql-notebook/assets/{list-tree-DGKqCxmz.js → list-tree-Dw0qlxPK.js} +1 -1
  44. package/dist/assets/dql-notebook/assets/{minimize-2-C8dvqCxX.js → minimize-2-DUiSrPS3.js} +1 -1
  45. package/dist/assets/dql-notebook/assets/{panel-right-open-yuVkIo5n.js → panel-right-open-BrrFrRZQ.js} +1 -1
  46. package/dist/assets/dql-notebook/assets/{bot-CLR1V6dO.js → play-Ced0HT9g.js} +7 -2
  47. package/dist/assets/dql-notebook/assets/{rotate-ccw-Di0kRnrM.js → rotate-ccw-D_9U9o7X.js} +1 -1
  48. package/dist/assets/dql-notebook/assets/{semantic-fields-BMQV0li8.js → semantic-fields-BlDOaonV.js} +1 -1
  49. package/dist/assets/dql-notebook/assets/{sliders-horizontal-alebptlJ.js → sliders-horizontal-BDt6KRGR.js} +1 -1
  50. package/dist/assets/dql-notebook/assets/{star-CgCQbnXc.js → star-CxUbF_BW.js} +1 -1
  51. package/dist/assets/dql-notebook/assets/{triangle-alert-SyuSZ4ht.js → triangle-alert-COWnsSdh.js} +1 -1
  52. package/dist/assets/dql-notebook/assets/upload-DSFC2kJX.js +6 -0
  53. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-DYdx896E.js +32 -0
  54. package/dist/assets/dql-notebook/assets/{user-round-J4PQHxo9.js → user-round-Bfu7fosn.js} +1 -1
  55. package/dist/assets/dql-notebook/assets/{wand-sparkles-c4WDXTCk.js → wand-sparkles-DSpG0c0j.js} +1 -1
  56. package/dist/assets/dql-notebook/assets/{workflow-NtRLaq7n.js → workflow-B1_pj9gq.js} +1 -1
  57. package/dist/assets/dql-notebook/assets/{wrench-CS1f1Zv4.js → wrench-CvfM03KZ.js} +1 -1
  58. package/dist/assets/dql-notebook/assets/{x-CbKEfe5m.js → x-B4coLiOl.js} +1 -1
  59. package/dist/assets/dql-notebook/index.html +2 -2
  60. package/dist/commands/app.d.ts.map +1 -1
  61. package/dist/commands/app.js +65 -133
  62. package/dist/commands/app.js.map +1 -1
  63. package/dist/commands/model.js +21 -2
  64. package/dist/commands/model.js.map +1 -1
  65. package/dist/llm/providers/dql-agent-provider.d.ts +16 -0
  66. package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
  67. package/dist/llm/providers/dql-agent-provider.js +65 -2
  68. package/dist/llm/providers/dql-agent-provider.js.map +1 -1
  69. package/dist/local-runtime.d.ts +112 -19
  70. package/dist/local-runtime.d.ts.map +1 -1
  71. package/dist/local-runtime.js +2026 -694
  72. package/dist/local-runtime.js.map +1 -1
  73. package/dist/package.json +10 -10
  74. package/dist/sql-result-filter.d.ts +9 -0
  75. package/dist/sql-result-filter.d.ts.map +1 -1
  76. package/dist/sql-result-filter.js +25 -0
  77. package/dist/sql-result-filter.js.map +1 -1
  78. package/package.json +10 -10
  79. package/dist/assets/dql-notebook/assets/AgentAnswerCard-c8QUo6NH.js +0 -5
  80. package/dist/assets/dql-notebook/assets/AnalyticsHome-DgwnRW71.js +0 -6
  81. package/dist/assets/dql-notebook/assets/AppsView-B6LYUpgm.js +0 -4578
  82. package/dist/assets/dql-notebook/assets/BlockStudio--jNw9XUI.js +0 -60
  83. package/dist/assets/dql-notebook/assets/DbtFirstModelingPage-DhBsLCYr.js +0 -22
  84. package/dist/assets/dql-notebook/assets/GlobalAiRail-1Tgweuu2.js +0 -1
  85. package/dist/assets/dql-notebook/assets/GovernedContextPage-C7qGrH3d.js +0 -16
  86. package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-duFXXNV_.js +0 -88
  87. package/dist/assets/dql-notebook/assets/index-Cpx47jCH.js +0 -634
  88. package/dist/assets/dql-notebook/assets/index-DKu4CZt3.css +0 -1
  89. package/dist/assets/dql-notebook/assets/upload-BPhfea_E.js +0 -11
  90. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-Bnl9gWhj.js +0 -28
@@ -1,4 +1,4 @@
1
- import{j as E,c as at,n as xn,r as l,a as Q,u as Pe,t as se,B as Ds,F as gn,o as yn,m as Se,p as We,q as Ps,s as Ms,v as ms,D as vt,w as fs,x as ar,y as hs,z as Rr,A as Ar,E as Sr,H as lr,I as Ir,R as Yt,h as Fe,i as Rt,k as Vt,J as Kt,K as BE,M as Us,O as xs,l as Gn,S as qe,b as Ne,Q as gs,g as ys,U as Gs,V as Bs,W as Or,X as bs,Y as Fs,Z as Hs,_ as Nr,$ as vs,a0 as Ys,T as Vs,P as Ws}from"./index-Cpx47jCH.js";import{B as cr}from"./book-open-text-BpqWMa4m.js";import{A as ws}from"./arrow-right-WIF1V9a9.js";import{W as Xs}from"./workflow-NtRLaq7n.js";import{L as dr,S as ks}from"./LineagePathBreadcrumb-B4LZTUsl.js";import{f as ot,a as Tt,b as Cr,c as Wt,M as js}from"./semantic-fields-BMQV0li8.js";import{c as $s,i as Ks,C as wt,r as bE,T as FE,a as ME,u as qs}from"./usePersistedAgentThreadId-Bnl9gWhj.js";import{U as Bn,S as Js,B as bn,a as Qs}from"./UnifiedAgentRunPanel-duFXXNV_.js";import{c as nt,N as Lr,u as zs,f as Ot}from"./answer-to-notebook-WAVAYjBv.js";import{M as Zs}from"./MiniLineageGraph-CotnRuxa.js";import{L as Fn,U as eo}from"./upload-BPhfea_E.js";import{X as Hn}from"./x-CbKEfe5m.js";import{T as _r}from"./triangle-alert-SyuSZ4ht.js";import{g as to}from"./react-CRB3T2We.js";import{M as Eo,A as ro,c as no}from"./AiSidePanel-NVA6lZnn.js";import{u as so}from"./AiBuildResult-DPJ_SI0R.js";import"./codemirror-DXt7RW72.js";import"./wrench-CS1f1Zv4.js";import"./AgentAnswerCard-c8QUo6NH.js";import"./TrustBadge-ZuD5N5Ww.js";import"./user-round-J4PQHxo9.js";import"./list-tree-DGKqCxmz.js";import"./minimize-2-C8dvqCxX.js";import"./dagre.esm-DlZi7NR3.js";import"./rotate-ccw-Di0kRnrM.js";function vn({typeLabel:e,typeColor:t,accent:r,idleBorder:n,background:s,headerBackground:T,active:i=!1,title:o,status:S,actions:a,toolbar:A,subheader:R,footer:N,children:O,onMouseEnter:c,onMouseLeave:C,onClick:I,gutter:d,className:L,style:f}){const v=t??"var(--color-accent-blue, #388bfd)",U=r??n??"var(--color-border-subtle, rgba(148,163,184,0.18))",F=n??"var(--color-border-subtle, rgba(148,163,184,0.18))",h=s??"var(--color-bg-1, rgba(22,27,34,0.5))",p=T??"transparent";return E.jsxs("div",{onMouseEnter:c,onMouseLeave:C,onClick:I,className:L,style:{display:"flex",gap:0,marginBottom:2,...f},children:[d!==void 0&&d,E.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${i?U:F}`,background:h,overflow:"hidden",transition:"border-color 0.2s, box-shadow 0.2s",boxShadow:i?`0 0 0 3px ${v}14, 0 1px 2px rgba(0,0,0,0.04)`:"0 1px 2px rgba(0,0,0,0.02)"},children:[E.jsxs("div",{style:{minHeight:32,display:"flex",alignItems:"center",padding:"8px 14px",gap:8,background:p},children:[E.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:v,flexShrink:0}}),E.jsx("span",{style:{fontSize:11,fontWeight:500,letterSpacing:"0.2px",color:"var(--color-text-secondary, #4a4a52)",flexShrink:0,whiteSpace:"nowrap"},children:e}),o!==void 0&&E.jsxs(E.Fragment,{children:[E.jsx("span",{style:{color:"var(--color-text-tertiary, #8a8d96)",fontSize:11},children:"·"}),o]}),A!==void 0&&A,E.jsx("span",{style:{flex:1}}),S!==void 0&&S,a!==void 0&&a]}),R!==void 0&&R,O,N!==void 0&&N]})]})}/**
1
+ import{j as E,c as at,n as xn,r as l,a as Q,u as Pe,t as se,B as Ds,F as gn,o as yn,m as Se,p as We,q as Ps,s as Ms,v as ms,D as vt,w as fs,x as ar,y as hs,z as Rr,A as Ar,E as Sr,H as lr,I as Ir,R as Yt,h as Fe,i as Rt,k as Vt,J as Kt,K as BE,M as Us,O as xs,l as Gn,S as qe,b as Ne,Q as gs,g as ys,U as Gs,V as Bs,W as Or,X as bs,Y as Fs,Z as Hs,_ as Nr,$ as vs,a0 as Ys,T as Vs,P as Ws}from"./index-DJRMz64S.js";import{B as cr}from"./book-open-text-B-dcHHn0.js";import{A as ws}from"./arrow-right-TH8_ufKG.js";import{W as Xs}from"./workflow-B1_pj9gq.js";import{L as dr,S as ks}from"./LineagePathBreadcrumb-B2tNdkr_.js";import{f as ot,a as Tt,b as Cr,c as Wt,M as js}from"./semantic-fields-BlDOaonV.js";import{c as $s,i as Ks,C as wt,r as bE,T as FE,a as ME,u as qs}from"./usePersistedAgentThreadId-DYdx896E.js";import{U as Bn,S as Js,B as bn,a as Qs}from"./UnifiedAgentRunPanel-IxDUKSG8.js";import{c as nt,N as Lr,u as zs,f as Ot}from"./answer-to-notebook-Dk42N0pU.js";import{M as Zs}from"./MiniLineageGraph-0gY-ZwCy.js";import{L as Fn}from"./link-2-DMZPHawg.js";import{X as Hn}from"./x-B4coLiOl.js";import{T as _r}from"./triangle-alert-COWnsSdh.js";import{g as eo}from"./react-CRB3T2We.js";import{M as to,A as Eo,c as ro}from"./AiSidePanel-CzIgxmP9.js";import{U as no}from"./upload-DSFC2kJX.js";import{u as so}from"./AiBuildResult-Cob_Lj05.js";import"./codemirror-DXt7RW72.js";import"./TrustBadge-Bob1Laiq.js";import"./wrench-CvfM03KZ.js";import"./user-round-Bfu7fosn.js";import"./list-tree-Dw0qlxPK.js";import"./minimize-2-DUiSrPS3.js";import"./dagre.esm-CPT_vn5p.js";import"./rotate-ccw-D_9U9o7X.js";function vn({typeLabel:e,typeColor:t,accent:r,idleBorder:n,background:s,headerBackground:T,active:i=!1,title:o,status:S,actions:a,toolbar:A,subheader:R,footer:N,children:O,onMouseEnter:c,onMouseLeave:C,onClick:I,gutter:d,className:L,style:f}){const v=t??"var(--color-accent-blue, #388bfd)",U=r??n??"var(--color-border-subtle, rgba(148,163,184,0.18))",F=n??"var(--color-border-subtle, rgba(148,163,184,0.18))",h=s??"var(--color-bg-1, rgba(22,27,34,0.5))",p=T??"transparent";return E.jsxs("div",{onMouseEnter:c,onMouseLeave:C,onClick:I,className:L,style:{display:"flex",gap:0,marginBottom:2,...f},children:[d!==void 0&&d,E.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${i?U:F}`,background:h,overflow:"hidden",transition:"border-color 0.2s, box-shadow 0.2s",boxShadow:i?`0 0 0 3px ${v}14, 0 1px 2px rgba(0,0,0,0.04)`:"0 1px 2px rgba(0,0,0,0.02)"},children:[E.jsxs("div",{style:{minHeight:32,display:"flex",alignItems:"center",padding:"8px 14px",gap:8,background:p},children:[E.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:v,flexShrink:0}}),E.jsx("span",{style:{fontSize:11,fontWeight:500,letterSpacing:"0.2px",color:"var(--color-text-secondary, #4a4a52)",flexShrink:0,whiteSpace:"nowrap"},children:e}),o!==void 0&&E.jsxs(E.Fragment,{children:[E.jsx("span",{style:{color:"var(--color-text-tertiary, #8a8d96)",fontSize:11},children:"·"}),o]}),A!==void 0&&A,E.jsx("span",{style:{flex:1}}),S!==void 0&&S,a!==void 0&&a]}),R!==void 0&&R,O,N!==void 0&&N]})]})}/**
2
2
  * @license lucide-react v0.563.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
@@ -160,7 +160,7 @@ If possible, please select a more specific dialect (like sqlite, postgresql, etc
160
160
  `,A}else return A+" at index "+(this.index-1);function I(d,L){var f=String(d);return Array(L-f.length+1).join(" ")+f}};function i(a,A,R){if(a instanceof s)var N=a,R=A;else var N=s.fromCompiled(a,A);this.grammar=N,this.options={keepHistory:!1,lexer:N.lexer||new T};for(var O in R||{})this.options[O]=R[O];this.lexer=this.options.lexer,this.lexerState=void 0;var c=new n(N,0);this.table=[c],c.wants[N.start]=[],c.predict(N.start),c.process(),this.current=0}i.fail={},i.prototype.feed=function(a){var A=this.lexer;A.reset(a,this.lexerState);for(var R;;){try{if(R=A.next(),!R)break}catch(h){var C=new n(this.grammar,this.current+1);this.table.push(C);var N=new Error(this.reportLexerError(h));throw N.offset=this.current,N.token=h.token,N}var O=this.table[this.current];this.options.keepHistory||delete this.table[this.current-1];var c=this.current+1,C=new n(this.grammar,c);this.table.push(C);for(var I=R.text!==void 0?R.text:R.value,d=A.constructor===T?R.value:R,L=O.scannable,f=L.length;f--;){var v=L[f],U=v.rule.symbols[v.dot];if(U.test?U.test(d):U.type?U.type===R.type:U.literal===I){var F=v.nextState({data:d,token:R,isToken:!0,reference:c-1});C.states.push(F)}}if(C.process(),C.states.length===0){var N=new Error(this.reportError(R));throw N.offset=this.current,N.token=R,N}this.options.keepHistory&&(O.lexerState=A.save()),this.current++}return O&&(this.lexerState=A.save()),this.results=this.finish(),this},i.prototype.reportLexerError=function(a){var A,R,N=a.token;return N?(A="input "+JSON.stringify(N.text[0])+" (lexer error)",R=this.lexer.formatError(N,"Syntax error")):(A="input (lexer error)",R=a.message),this.reportErrorCommon(R,A)},i.prototype.reportError=function(a){var A=(a.type?a.type+" token: ":"")+JSON.stringify(a.value!==void 0?a.value:a),R=this.lexer.formatError(a,"Syntax error");return this.reportErrorCommon(R,A)},i.prototype.reportErrorCommon=function(a,A){var R=[];R.push(a);var N=this.table.length-2,O=this.table[N],c=O.states.filter(function(I){var d=I.rule.symbols[I.dot];return d&&typeof d!="string"});if(c.length===0)R.push("Unexpected "+A+`. I did not expect any more input. Here is the state of my parse table:
161
161
  `),this.displayStateStack(O.states,R);else{R.push("Unexpected "+A+`. Instead, I was expecting to see one of the following:
162
162
  `);var C=c.map(function(I){return this.buildFirstStateStack(I,[])||[I]},this);C.forEach(function(I){var d=I[0],L=d.rule.symbols[d.dot],f=this.getSymbolDisplay(L);R.push("A "+f+" based on:"),this.displayStateStack(I,R)},this)}return R.push(""),R.join(`
163
- `)},i.prototype.displayStateStack=function(a,A){for(var R,N=0,O=0;O<a.length;O++){var c=a[O],C=c.rule.toString(c.dot);C===R?N++:(N>0&&A.push(" ^ "+N+" more lines identical to this"),N=0,A.push(" "+C)),R=C}},i.prototype.getSymbolDisplay=function(a){return o(a)},i.prototype.buildFirstStateStack=function(a,A){if(A.indexOf(a)!==-1)return null;if(a.wantedBy.length===0)return[a];var R=a.wantedBy[0],N=[a].concat(A),O=this.buildFirstStateStack(R,N);return O===null?null:[a].concat(O)},i.prototype.save=function(){var a=this.table[this.current];return a.lexerState=this.lexerState,a},i.prototype.restore=function(a){var A=a.index;this.current=A,this.table[A]=a,this.table.splice(A+1),this.lexerState=a.lexerState,this.results=this.finish()},i.prototype.rewind=function(a){if(!this.options.keepHistory)throw new Error("set option `keepHistory` to enable rewinding");this.restore(this.table[a])},i.prototype.finish=function(){var a=[],A=this.grammar.start,R=this.table[this.table.length-1];return R.states.forEach(function(N){N.rule.name===A&&N.dot===N.rule.symbols.length&&N.reference===0&&N.data!==i.fail&&a.push(N)}),a.map(function(N){return N.data})};function o(a){var A=typeof a;if(A==="string")return a;if(A==="object"){if(a.literal)return JSON.stringify(a.literal);if(a instanceof RegExp)return"character matching "+a;if(a.type)return a.type+" token";if(a.test)return"token matching "+String(a.test);throw new Error("Unknown symbol type: "+a)}}function S(a){var A=typeof a;if(A==="string")return a;if(A==="object"){if(a.literal)return JSON.stringify(a.literal);if(a instanceof RegExp)return a.toString();if(a.type)return"%"+a.type;if(a.test)return"<"+String(a.test)+">";throw new Error("Unknown symbol type: "+a)}}return{Parser:i,Grammar:s,Rule:t}})})(Bt)),Bt.exports}var qA=KA();const JA=to(qA);function QA(e){return e.map(zA).map(ZA).map(eS).map(tS).map(ES)}const zA=(e,t,r)=>{if(Kn(e.type)){const n=rS(r,t);if(n&&n.type===M.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:M.IDENTIFIER,text:e.raw});const s=Je(r,t);if(s&&s.type===M.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:M.IDENTIFIER,text:e.raw})}return e},ZA=(e,t,r)=>{if(e.type===M.RESERVED_FUNCTION_NAME){const n=Je(r,t);if(!n||!es(n))return Object.assign(Object.assign({},e),{type:M.IDENTIFIER,text:e.raw})}return e},eS=(e,t,r)=>{if(e.type===M.RESERVED_DATA_TYPE){const n=Je(r,t);if(n&&es(n))return Object.assign(Object.assign({},e),{type:M.RESERVED_PARAMETERIZED_DATA_TYPE})}return e},tS=(e,t,r)=>{if(e.type===M.IDENTIFIER){const n=Je(r,t);if(n&&ts(n))return Object.assign(Object.assign({},e),{type:M.ARRAY_IDENTIFIER})}return e},ES=(e,t,r)=>{if(e.type===M.RESERVED_DATA_TYPE){const n=Je(r,t);if(n&&ts(n))return Object.assign(Object.assign({},e),{type:M.ARRAY_KEYWORD})}return e},rS=(e,t)=>Je(e,t,-1),Je=(e,t,r=1)=>{let n=1;for(;e[t+n*r]&&nS(e[t+n*r]);)n++;return e[t+n*r]},es=e=>e.type===M.OPEN_PAREN&&e.text==="(",ts=e=>e.type===M.OPEN_PAREN&&e.text==="[",nS=e=>e.type===M.BLOCK_COMMENT||e.type===M.LINE_COMMENT;class Es{constructor(t){this.tokenize=t,this.index=0,this.tokens=[],this.input=""}reset(t,r){this.input=t,this.index=0,this.tokens=this.tokenize(t)}next(){return this.tokens[this.index++]}save(){}formatError(t){const{line:r,col:n}=Zn(this.input,t.start);return`Parse error at token: ${t.text} at line ${r} column ${n}`}has(t){return t in M}}var b;(function(e){e.statement="statement",e.clause="clause",e.set_operation="set_operation",e.function_call="function_call",e.parameterized_data_type="parameterized_data_type",e.array_subscript="array_subscript",e.property_access="property_access",e.parenthesis="parenthesis",e.between_predicate="between_predicate",e.case_expression="case_expression",e.case_when="case_when",e.case_else="case_else",e.limit_clause="limit_clause",e.all_columns_asterisk="all_columns_asterisk",e.literal="literal",e.identifier="identifier",e.keyword="keyword",e.data_type="data_type",e.parameter="parameter",e.operator="operator",e.comma="comma",e.line_comment="line_comment",e.block_comment="block_comment",e.disable_comment="disable_comment"})(b=b||(b={}));function uE(e){return e[0]}const w=new Es(e=>[]),Be=([[e]])=>e,Re=e=>({type:b.keyword,tokenType:e.type,text:e.text,raw:e.raw}),dn=e=>({type:b.data_type,text:e.text,raw:e.raw}),Ae=(e,{leading:t,trailing:r})=>(t!=null&&t.length&&(e=Object.assign(Object.assign({},e),{leadingComments:t})),r!=null&&r.length&&(e=Object.assign(Object.assign({},e),{trailingComments:r})),e),sS=(e,{leading:t,trailing:r})=>{if(t!=null&&t.length){const[n,...s]=e;e=[Ae(n,{leading:t}),...s]}if(r!=null&&r.length){const n=e.slice(0,-1),s=e[e.length-1];e=[...n,Ae(s,{trailing:r})]}return e},oS={Lexer:w,ParserRules:[{name:"main$ebnf$1",symbols:[]},{name:"main$ebnf$1",symbols:["main$ebnf$1","statement"],postprocess:e=>e[0].concat([e[1]])},{name:"main",symbols:["main$ebnf$1"],postprocess:([e])=>{const t=e[e.length-1];return t&&!t.hasSemicolon?t.children.length>0?e:e.slice(0,-1):e}},{name:"statement$subexpression$1",symbols:[w.has("DELIMITER")?{type:"DELIMITER"}:DELIMITER]},{name:"statement$subexpression$1",symbols:[w.has("EOF")?{type:"EOF"}:EOF]},{name:"statement",symbols:["expressions_or_clauses","statement$subexpression$1"],postprocess:([e,[t]])=>({type:b.statement,children:e,hasSemicolon:t.type===M.DELIMITER})},{name:"expressions_or_clauses$ebnf$1",symbols:[]},{name:"expressions_or_clauses$ebnf$1",symbols:["expressions_or_clauses$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"expressions_or_clauses$ebnf$2",symbols:[]},{name:"expressions_or_clauses$ebnf$2",symbols:["expressions_or_clauses$ebnf$2","clause"],postprocess:e=>e[0].concat([e[1]])},{name:"expressions_or_clauses",symbols:["expressions_or_clauses$ebnf$1","expressions_or_clauses$ebnf$2"],postprocess:([e,t])=>[...e,...t]},{name:"clause$subexpression$1",symbols:["limit_clause"]},{name:"clause$subexpression$1",symbols:["select_clause"]},{name:"clause$subexpression$1",symbols:["other_clause"]},{name:"clause$subexpression$1",symbols:["set_operation"]},{name:"clause",symbols:["clause$subexpression$1"],postprocess:Be},{name:"limit_clause$ebnf$1$subexpression$1$ebnf$1",symbols:["free_form_sql"]},{name:"limit_clause$ebnf$1$subexpression$1$ebnf$1",symbols:["limit_clause$ebnf$1$subexpression$1$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"limit_clause$ebnf$1$subexpression$1",symbols:[w.has("COMMA")?{type:"COMMA"}:COMMA,"limit_clause$ebnf$1$subexpression$1$ebnf$1"]},{name:"limit_clause$ebnf$1",symbols:["limit_clause$ebnf$1$subexpression$1"],postprocess:uE},{name:"limit_clause$ebnf$1",symbols:[],postprocess:()=>null},{name:"limit_clause",symbols:[w.has("LIMIT")?{type:"LIMIT"}:LIMIT,"_","expression_chain_","limit_clause$ebnf$1"],postprocess:([e,t,r,n])=>{if(n){const[s,T]=n;return{type:b.limit_clause,limitKw:Ae(Re(e),{trailing:t}),offset:r,count:T}}else return{type:b.limit_clause,limitKw:Ae(Re(e),{trailing:t}),count:r}}},{name:"select_clause$subexpression$1$ebnf$1",symbols:[]},{name:"select_clause$subexpression$1$ebnf$1",symbols:["select_clause$subexpression$1$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"select_clause$subexpression$1",symbols:["all_columns_asterisk","select_clause$subexpression$1$ebnf$1"]},{name:"select_clause$subexpression$1$ebnf$2",symbols:[]},{name:"select_clause$subexpression$1$ebnf$2",symbols:["select_clause$subexpression$1$ebnf$2","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"select_clause$subexpression$1",symbols:["asteriskless_free_form_sql","select_clause$subexpression$1$ebnf$2"]},{name:"select_clause",symbols:[w.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT,"select_clause$subexpression$1"],postprocess:([e,[t,r]])=>({type:b.clause,nameKw:Re(e),children:[t,...r]})},{name:"select_clause",symbols:[w.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT],postprocess:([e])=>({type:b.clause,nameKw:Re(e),children:[]})},{name:"all_columns_asterisk",symbols:[w.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK],postprocess:()=>({type:b.all_columns_asterisk})},{name:"other_clause$ebnf$1",symbols:[]},{name:"other_clause$ebnf$1",symbols:["other_clause$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"other_clause",symbols:[w.has("RESERVED_CLAUSE")?{type:"RESERVED_CLAUSE"}:RESERVED_CLAUSE,"other_clause$ebnf$1"],postprocess:([e,t])=>({type:b.clause,nameKw:Re(e),children:t})},{name:"set_operation$ebnf$1",symbols:[]},{name:"set_operation$ebnf$1",symbols:["set_operation$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"set_operation",symbols:[w.has("RESERVED_SET_OPERATION")?{type:"RESERVED_SET_OPERATION"}:RESERVED_SET_OPERATION,"set_operation$ebnf$1"],postprocess:([e,t])=>({type:b.set_operation,nameKw:Re(e),children:t})},{name:"expression_chain_$ebnf$1",symbols:["expression_with_comments_"]},{name:"expression_chain_$ebnf$1",symbols:["expression_chain_$ebnf$1","expression_with_comments_"],postprocess:e=>e[0].concat([e[1]])},{name:"expression_chain_",symbols:["expression_chain_$ebnf$1"],postprocess:uE},{name:"expression_chain$ebnf$1",symbols:[]},{name:"expression_chain$ebnf$1",symbols:["expression_chain$ebnf$1","_expression_with_comments"],postprocess:e=>e[0].concat([e[1]])},{name:"expression_chain",symbols:["expression","expression_chain$ebnf$1"],postprocess:([e,t])=>[e,...t]},{name:"andless_expression_chain$ebnf$1",symbols:[]},{name:"andless_expression_chain$ebnf$1",symbols:["andless_expression_chain$ebnf$1","_andless_expression_with_comments"],postprocess:e=>e[0].concat([e[1]])},{name:"andless_expression_chain",symbols:["andless_expression","andless_expression_chain$ebnf$1"],postprocess:([e,t])=>[e,...t]},{name:"expression_with_comments_",symbols:["expression","_"],postprocess:([e,t])=>Ae(e,{trailing:t})},{name:"_expression_with_comments",symbols:["_","expression"],postprocess:([e,t])=>Ae(t,{leading:e})},{name:"_andless_expression_with_comments",symbols:["_","andless_expression"],postprocess:([e,t])=>Ae(t,{leading:e})},{name:"free_form_sql$subexpression$1",symbols:["asteriskless_free_form_sql"]},{name:"free_form_sql$subexpression$1",symbols:["asterisk"]},{name:"free_form_sql",symbols:["free_form_sql$subexpression$1"],postprocess:Be},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["asteriskless_andless_expression"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["logic_operator"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["comma"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["comment"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["other_keyword"]},{name:"asteriskless_free_form_sql",symbols:["asteriskless_free_form_sql$subexpression$1"],postprocess:Be},{name:"expression$subexpression$1",symbols:["andless_expression"]},{name:"expression$subexpression$1",symbols:["logic_operator"]},{name:"expression",symbols:["expression$subexpression$1"],postprocess:Be},{name:"andless_expression$subexpression$1",symbols:["asteriskless_andless_expression"]},{name:"andless_expression$subexpression$1",symbols:["asterisk"]},{name:"andless_expression",symbols:["andless_expression$subexpression$1"],postprocess:Be},{name:"asteriskless_andless_expression$subexpression$1",symbols:["atomic_expression"]},{name:"asteriskless_andless_expression$subexpression$1",symbols:["between_predicate"]},{name:"asteriskless_andless_expression$subexpression$1",symbols:["case_expression"]},{name:"asteriskless_andless_expression",symbols:["asteriskless_andless_expression$subexpression$1"],postprocess:Be},{name:"atomic_expression$subexpression$1",symbols:["array_subscript"]},{name:"atomic_expression$subexpression$1",symbols:["function_call"]},{name:"atomic_expression$subexpression$1",symbols:["property_access"]},{name:"atomic_expression$subexpression$1",symbols:["parenthesis"]},{name:"atomic_expression$subexpression$1",symbols:["curly_braces"]},{name:"atomic_expression$subexpression$1",symbols:["square_brackets"]},{name:"atomic_expression$subexpression$1",symbols:["operator"]},{name:"atomic_expression$subexpression$1",symbols:["identifier"]},{name:"atomic_expression$subexpression$1",symbols:["parameter"]},{name:"atomic_expression$subexpression$1",symbols:["literal"]},{name:"atomic_expression$subexpression$1",symbols:["data_type"]},{name:"atomic_expression$subexpression$1",symbols:["keyword"]},{name:"atomic_expression",symbols:["atomic_expression$subexpression$1"],postprocess:Be},{name:"array_subscript",symbols:[w.has("ARRAY_IDENTIFIER")?{type:"ARRAY_IDENTIFIER"}:ARRAY_IDENTIFIER,"_","square_brackets"],postprocess:([e,t,r])=>({type:b.array_subscript,array:Ae({type:b.identifier,quoted:!1,text:e.text},{trailing:t}),parenthesis:r})},{name:"array_subscript",symbols:[w.has("ARRAY_KEYWORD")?{type:"ARRAY_KEYWORD"}:ARRAY_KEYWORD,"_","square_brackets"],postprocess:([e,t,r])=>({type:b.array_subscript,array:Ae(Re(e),{trailing:t}),parenthesis:r})},{name:"function_call",symbols:[w.has("RESERVED_FUNCTION_NAME")?{type:"RESERVED_FUNCTION_NAME"}:RESERVED_FUNCTION_NAME,"_","parenthesis"],postprocess:([e,t,r])=>({type:b.function_call,nameKw:Ae(Re(e),{trailing:t}),parenthesis:r})},{name:"parenthesis",symbols:[{literal:"("},"expressions_or_clauses",{literal:")"}],postprocess:([e,t,r])=>({type:b.parenthesis,children:t,openParen:"(",closeParen:")"})},{name:"curly_braces$ebnf$1",symbols:[]},{name:"curly_braces$ebnf$1",symbols:["curly_braces$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"curly_braces",symbols:[{literal:"{"},"curly_braces$ebnf$1",{literal:"}"}],postprocess:([e,t,r])=>({type:b.parenthesis,children:t,openParen:"{",closeParen:"}"})},{name:"square_brackets$ebnf$1",symbols:[]},{name:"square_brackets$ebnf$1",symbols:["square_brackets$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"square_brackets",symbols:[{literal:"["},"square_brackets$ebnf$1",{literal:"]"}],postprocess:([e,t,r])=>({type:b.parenthesis,children:t,openParen:"[",closeParen:"]"})},{name:"property_access$subexpression$1",symbols:["identifier"]},{name:"property_access$subexpression$1",symbols:["array_subscript"]},{name:"property_access$subexpression$1",symbols:["all_columns_asterisk"]},{name:"property_access$subexpression$1",symbols:["parameter"]},{name:"property_access",symbols:["atomic_expression","_",w.has("PROPERTY_ACCESS_OPERATOR")?{type:"PROPERTY_ACCESS_OPERATOR"}:PROPERTY_ACCESS_OPERATOR,"_","property_access$subexpression$1"],postprocess:([e,t,r,n,[s]])=>({type:b.property_access,object:Ae(e,{trailing:t}),operator:r.text,property:Ae(s,{leading:n})})},{name:"between_predicate",symbols:[w.has("BETWEEN")?{type:"BETWEEN"}:BETWEEN,"_","andless_expression_chain","_",w.has("AND")?{type:"AND"}:AND,"_","andless_expression"],postprocess:([e,t,r,n,s,T,i])=>({type:b.between_predicate,betweenKw:Re(e),expr1:sS(r,{leading:t,trailing:n}),andKw:Re(s),expr2:[Ae(i,{leading:T})]})},{name:"case_expression$ebnf$1",symbols:["expression_chain_"],postprocess:uE},{name:"case_expression$ebnf$1",symbols:[],postprocess:()=>null},{name:"case_expression$ebnf$2",symbols:[]},{name:"case_expression$ebnf$2",symbols:["case_expression$ebnf$2","case_clause"],postprocess:e=>e[0].concat([e[1]])},{name:"case_expression",symbols:[w.has("CASE")?{type:"CASE"}:CASE,"_","case_expression$ebnf$1","case_expression$ebnf$2",w.has("END")?{type:"END"}:END],postprocess:([e,t,r,n,s])=>({type:b.case_expression,caseKw:Ae(Re(e),{trailing:t}),endKw:Re(s),expr:r||[],clauses:n})},{name:"case_clause",symbols:[w.has("WHEN")?{type:"WHEN"}:WHEN,"_","expression_chain_",w.has("THEN")?{type:"THEN"}:THEN,"_","expression_chain_"],postprocess:([e,t,r,n,s,T])=>({type:b.case_when,whenKw:Ae(Re(e),{trailing:t}),thenKw:Ae(Re(n),{trailing:s}),condition:r,result:T})},{name:"case_clause",symbols:[w.has("ELSE")?{type:"ELSE"}:ELSE,"_","expression_chain_"],postprocess:([e,t,r])=>({type:b.case_else,elseKw:Ae(Re(e),{trailing:t}),result:r})},{name:"comma$subexpression$1",symbols:[w.has("COMMA")?{type:"COMMA"}:COMMA]},{name:"comma",symbols:["comma$subexpression$1"],postprocess:([[e]])=>({type:b.comma})},{name:"asterisk$subexpression$1",symbols:[w.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK]},{name:"asterisk",symbols:["asterisk$subexpression$1"],postprocess:([[e]])=>({type:b.operator,text:e.text})},{name:"operator$subexpression$1",symbols:[w.has("OPERATOR")?{type:"OPERATOR"}:OPERATOR]},{name:"operator",symbols:["operator$subexpression$1"],postprocess:([[e]])=>({type:b.operator,text:e.text})},{name:"identifier$subexpression$1",symbols:[w.has("IDENTIFIER")?{type:"IDENTIFIER"}:IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[w.has("QUOTED_IDENTIFIER")?{type:"QUOTED_IDENTIFIER"}:QUOTED_IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[w.has("VARIABLE")?{type:"VARIABLE"}:VARIABLE]},{name:"identifier",symbols:["identifier$subexpression$1"],postprocess:([[e]])=>({type:b.identifier,quoted:e.type!=="IDENTIFIER",text:e.text})},{name:"parameter$subexpression$1",symbols:[w.has("NAMED_PARAMETER")?{type:"NAMED_PARAMETER"}:NAMED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[w.has("QUOTED_PARAMETER")?{type:"QUOTED_PARAMETER"}:QUOTED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[w.has("NUMBERED_PARAMETER")?{type:"NUMBERED_PARAMETER"}:NUMBERED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[w.has("POSITIONAL_PARAMETER")?{type:"POSITIONAL_PARAMETER"}:POSITIONAL_PARAMETER]},{name:"parameter$subexpression$1",symbols:[w.has("CUSTOM_PARAMETER")?{type:"CUSTOM_PARAMETER"}:CUSTOM_PARAMETER]},{name:"parameter",symbols:["parameter$subexpression$1"],postprocess:([[e]])=>({type:b.parameter,key:e.key,text:e.text})},{name:"literal$subexpression$1",symbols:[w.has("NUMBER")?{type:"NUMBER"}:NUMBER]},{name:"literal$subexpression$1",symbols:[w.has("STRING")?{type:"STRING"}:STRING]},{name:"literal",symbols:["literal$subexpression$1"],postprocess:([[e]])=>({type:b.literal,text:e.text})},{name:"keyword$subexpression$1",symbols:[w.has("RESERVED_KEYWORD")?{type:"RESERVED_KEYWORD"}:RESERVED_KEYWORD]},{name:"keyword$subexpression$1",symbols:[w.has("RESERVED_KEYWORD_PHRASE")?{type:"RESERVED_KEYWORD_PHRASE"}:RESERVED_KEYWORD_PHRASE]},{name:"keyword$subexpression$1",symbols:[w.has("RESERVED_JOIN")?{type:"RESERVED_JOIN"}:RESERVED_JOIN]},{name:"keyword",symbols:["keyword$subexpression$1"],postprocess:([[e]])=>Re(e)},{name:"data_type$subexpression$1",symbols:[w.has("RESERVED_DATA_TYPE")?{type:"RESERVED_DATA_TYPE"}:RESERVED_DATA_TYPE]},{name:"data_type$subexpression$1",symbols:[w.has("RESERVED_DATA_TYPE_PHRASE")?{type:"RESERVED_DATA_TYPE_PHRASE"}:RESERVED_DATA_TYPE_PHRASE]},{name:"data_type",symbols:["data_type$subexpression$1"],postprocess:([[e]])=>dn(e)},{name:"data_type",symbols:[w.has("RESERVED_PARAMETERIZED_DATA_TYPE")?{type:"RESERVED_PARAMETERIZED_DATA_TYPE"}:RESERVED_PARAMETERIZED_DATA_TYPE,"_","parenthesis"],postprocess:([e,t,r])=>({type:b.parameterized_data_type,dataType:Ae(dn(e),{trailing:t}),parenthesis:r})},{name:"logic_operator$subexpression$1",symbols:[w.has("AND")?{type:"AND"}:AND]},{name:"logic_operator$subexpression$1",symbols:[w.has("OR")?{type:"OR"}:OR]},{name:"logic_operator$subexpression$1",symbols:[w.has("XOR")?{type:"XOR"}:XOR]},{name:"logic_operator",symbols:["logic_operator$subexpression$1"],postprocess:([[e]])=>Re(e)},{name:"other_keyword$subexpression$1",symbols:[w.has("WHEN")?{type:"WHEN"}:WHEN]},{name:"other_keyword$subexpression$1",symbols:[w.has("THEN")?{type:"THEN"}:THEN]},{name:"other_keyword$subexpression$1",symbols:[w.has("ELSE")?{type:"ELSE"}:ELSE]},{name:"other_keyword$subexpression$1",symbols:[w.has("END")?{type:"END"}:END]},{name:"other_keyword",symbols:["other_keyword$subexpression$1"],postprocess:([[e]])=>Re(e)},{name:"_$ebnf$1",symbols:[]},{name:"_$ebnf$1",symbols:["_$ebnf$1","comment"],postprocess:e=>e[0].concat([e[1]])},{name:"_",symbols:["_$ebnf$1"],postprocess:([e])=>e},{name:"comment",symbols:[w.has("LINE_COMMENT")?{type:"LINE_COMMENT"}:LINE_COMMENT],postprocess:([e])=>({type:b.line_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[w.has("BLOCK_COMMENT")?{type:"BLOCK_COMMENT"}:BLOCK_COMMENT],postprocess:([e])=>({type:b.block_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[w.has("DISABLE_COMMENT")?{type:"DISABLE_COMMENT"}:DISABLE_COMMENT],postprocess:([e])=>({type:b.disable_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})}],ParserStart:"main"},{Parser:TS,Grammar:iS}=JA;function aS(e){let t={};const r=new Es(s=>[...QA(e.tokenize(s,t)),$n(s.length)]),n=new TS(iS.fromCompiled(oS),{lexer:r});return{parse:(s,T)=>{t=T;const{results:i}=n.feed(s);if(i.length===1)return i[0];throw i.length===0?new Error("Parse error: Invalid SQL"):new Error(`Parse error: Ambiguous grammar
163
+ `)},i.prototype.displayStateStack=function(a,A){for(var R,N=0,O=0;O<a.length;O++){var c=a[O],C=c.rule.toString(c.dot);C===R?N++:(N>0&&A.push(" ^ "+N+" more lines identical to this"),N=0,A.push(" "+C)),R=C}},i.prototype.getSymbolDisplay=function(a){return o(a)},i.prototype.buildFirstStateStack=function(a,A){if(A.indexOf(a)!==-1)return null;if(a.wantedBy.length===0)return[a];var R=a.wantedBy[0],N=[a].concat(A),O=this.buildFirstStateStack(R,N);return O===null?null:[a].concat(O)},i.prototype.save=function(){var a=this.table[this.current];return a.lexerState=this.lexerState,a},i.prototype.restore=function(a){var A=a.index;this.current=A,this.table[A]=a,this.table.splice(A+1),this.lexerState=a.lexerState,this.results=this.finish()},i.prototype.rewind=function(a){if(!this.options.keepHistory)throw new Error("set option `keepHistory` to enable rewinding");this.restore(this.table[a])},i.prototype.finish=function(){var a=[],A=this.grammar.start,R=this.table[this.table.length-1];return R.states.forEach(function(N){N.rule.name===A&&N.dot===N.rule.symbols.length&&N.reference===0&&N.data!==i.fail&&a.push(N)}),a.map(function(N){return N.data})};function o(a){var A=typeof a;if(A==="string")return a;if(A==="object"){if(a.literal)return JSON.stringify(a.literal);if(a instanceof RegExp)return"character matching "+a;if(a.type)return a.type+" token";if(a.test)return"token matching "+String(a.test);throw new Error("Unknown symbol type: "+a)}}function S(a){var A=typeof a;if(A==="string")return a;if(A==="object"){if(a.literal)return JSON.stringify(a.literal);if(a instanceof RegExp)return a.toString();if(a.type)return"%"+a.type;if(a.test)return"<"+String(a.test)+">";throw new Error("Unknown symbol type: "+a)}}return{Parser:i,Grammar:s,Rule:t}})})(Bt)),Bt.exports}var qA=KA();const JA=eo(qA);function QA(e){return e.map(zA).map(ZA).map(eS).map(tS).map(ES)}const zA=(e,t,r)=>{if(Kn(e.type)){const n=rS(r,t);if(n&&n.type===M.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:M.IDENTIFIER,text:e.raw});const s=Je(r,t);if(s&&s.type===M.PROPERTY_ACCESS_OPERATOR)return Object.assign(Object.assign({},e),{type:M.IDENTIFIER,text:e.raw})}return e},ZA=(e,t,r)=>{if(e.type===M.RESERVED_FUNCTION_NAME){const n=Je(r,t);if(!n||!es(n))return Object.assign(Object.assign({},e),{type:M.IDENTIFIER,text:e.raw})}return e},eS=(e,t,r)=>{if(e.type===M.RESERVED_DATA_TYPE){const n=Je(r,t);if(n&&es(n))return Object.assign(Object.assign({},e),{type:M.RESERVED_PARAMETERIZED_DATA_TYPE})}return e},tS=(e,t,r)=>{if(e.type===M.IDENTIFIER){const n=Je(r,t);if(n&&ts(n))return Object.assign(Object.assign({},e),{type:M.ARRAY_IDENTIFIER})}return e},ES=(e,t,r)=>{if(e.type===M.RESERVED_DATA_TYPE){const n=Je(r,t);if(n&&ts(n))return Object.assign(Object.assign({},e),{type:M.ARRAY_KEYWORD})}return e},rS=(e,t)=>Je(e,t,-1),Je=(e,t,r=1)=>{let n=1;for(;e[t+n*r]&&nS(e[t+n*r]);)n++;return e[t+n*r]},es=e=>e.type===M.OPEN_PAREN&&e.text==="(",ts=e=>e.type===M.OPEN_PAREN&&e.text==="[",nS=e=>e.type===M.BLOCK_COMMENT||e.type===M.LINE_COMMENT;class Es{constructor(t){this.tokenize=t,this.index=0,this.tokens=[],this.input=""}reset(t,r){this.input=t,this.index=0,this.tokens=this.tokenize(t)}next(){return this.tokens[this.index++]}save(){}formatError(t){const{line:r,col:n}=Zn(this.input,t.start);return`Parse error at token: ${t.text} at line ${r} column ${n}`}has(t){return t in M}}var b;(function(e){e.statement="statement",e.clause="clause",e.set_operation="set_operation",e.function_call="function_call",e.parameterized_data_type="parameterized_data_type",e.array_subscript="array_subscript",e.property_access="property_access",e.parenthesis="parenthesis",e.between_predicate="between_predicate",e.case_expression="case_expression",e.case_when="case_when",e.case_else="case_else",e.limit_clause="limit_clause",e.all_columns_asterisk="all_columns_asterisk",e.literal="literal",e.identifier="identifier",e.keyword="keyword",e.data_type="data_type",e.parameter="parameter",e.operator="operator",e.comma="comma",e.line_comment="line_comment",e.block_comment="block_comment",e.disable_comment="disable_comment"})(b=b||(b={}));function uE(e){return e[0]}const w=new Es(e=>[]),Be=([[e]])=>e,Re=e=>({type:b.keyword,tokenType:e.type,text:e.text,raw:e.raw}),dn=e=>({type:b.data_type,text:e.text,raw:e.raw}),Ae=(e,{leading:t,trailing:r})=>(t!=null&&t.length&&(e=Object.assign(Object.assign({},e),{leadingComments:t})),r!=null&&r.length&&(e=Object.assign(Object.assign({},e),{trailingComments:r})),e),sS=(e,{leading:t,trailing:r})=>{if(t!=null&&t.length){const[n,...s]=e;e=[Ae(n,{leading:t}),...s]}if(r!=null&&r.length){const n=e.slice(0,-1),s=e[e.length-1];e=[...n,Ae(s,{trailing:r})]}return e},oS={Lexer:w,ParserRules:[{name:"main$ebnf$1",symbols:[]},{name:"main$ebnf$1",symbols:["main$ebnf$1","statement"],postprocess:e=>e[0].concat([e[1]])},{name:"main",symbols:["main$ebnf$1"],postprocess:([e])=>{const t=e[e.length-1];return t&&!t.hasSemicolon?t.children.length>0?e:e.slice(0,-1):e}},{name:"statement$subexpression$1",symbols:[w.has("DELIMITER")?{type:"DELIMITER"}:DELIMITER]},{name:"statement$subexpression$1",symbols:[w.has("EOF")?{type:"EOF"}:EOF]},{name:"statement",symbols:["expressions_or_clauses","statement$subexpression$1"],postprocess:([e,[t]])=>({type:b.statement,children:e,hasSemicolon:t.type===M.DELIMITER})},{name:"expressions_or_clauses$ebnf$1",symbols:[]},{name:"expressions_or_clauses$ebnf$1",symbols:["expressions_or_clauses$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"expressions_or_clauses$ebnf$2",symbols:[]},{name:"expressions_or_clauses$ebnf$2",symbols:["expressions_or_clauses$ebnf$2","clause"],postprocess:e=>e[0].concat([e[1]])},{name:"expressions_or_clauses",symbols:["expressions_or_clauses$ebnf$1","expressions_or_clauses$ebnf$2"],postprocess:([e,t])=>[...e,...t]},{name:"clause$subexpression$1",symbols:["limit_clause"]},{name:"clause$subexpression$1",symbols:["select_clause"]},{name:"clause$subexpression$1",symbols:["other_clause"]},{name:"clause$subexpression$1",symbols:["set_operation"]},{name:"clause",symbols:["clause$subexpression$1"],postprocess:Be},{name:"limit_clause$ebnf$1$subexpression$1$ebnf$1",symbols:["free_form_sql"]},{name:"limit_clause$ebnf$1$subexpression$1$ebnf$1",symbols:["limit_clause$ebnf$1$subexpression$1$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"limit_clause$ebnf$1$subexpression$1",symbols:[w.has("COMMA")?{type:"COMMA"}:COMMA,"limit_clause$ebnf$1$subexpression$1$ebnf$1"]},{name:"limit_clause$ebnf$1",symbols:["limit_clause$ebnf$1$subexpression$1"],postprocess:uE},{name:"limit_clause$ebnf$1",symbols:[],postprocess:()=>null},{name:"limit_clause",symbols:[w.has("LIMIT")?{type:"LIMIT"}:LIMIT,"_","expression_chain_","limit_clause$ebnf$1"],postprocess:([e,t,r,n])=>{if(n){const[s,T]=n;return{type:b.limit_clause,limitKw:Ae(Re(e),{trailing:t}),offset:r,count:T}}else return{type:b.limit_clause,limitKw:Ae(Re(e),{trailing:t}),count:r}}},{name:"select_clause$subexpression$1$ebnf$1",symbols:[]},{name:"select_clause$subexpression$1$ebnf$1",symbols:["select_clause$subexpression$1$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"select_clause$subexpression$1",symbols:["all_columns_asterisk","select_clause$subexpression$1$ebnf$1"]},{name:"select_clause$subexpression$1$ebnf$2",symbols:[]},{name:"select_clause$subexpression$1$ebnf$2",symbols:["select_clause$subexpression$1$ebnf$2","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"select_clause$subexpression$1",symbols:["asteriskless_free_form_sql","select_clause$subexpression$1$ebnf$2"]},{name:"select_clause",symbols:[w.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT,"select_clause$subexpression$1"],postprocess:([e,[t,r]])=>({type:b.clause,nameKw:Re(e),children:[t,...r]})},{name:"select_clause",symbols:[w.has("RESERVED_SELECT")?{type:"RESERVED_SELECT"}:RESERVED_SELECT],postprocess:([e])=>({type:b.clause,nameKw:Re(e),children:[]})},{name:"all_columns_asterisk",symbols:[w.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK],postprocess:()=>({type:b.all_columns_asterisk})},{name:"other_clause$ebnf$1",symbols:[]},{name:"other_clause$ebnf$1",symbols:["other_clause$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"other_clause",symbols:[w.has("RESERVED_CLAUSE")?{type:"RESERVED_CLAUSE"}:RESERVED_CLAUSE,"other_clause$ebnf$1"],postprocess:([e,t])=>({type:b.clause,nameKw:Re(e),children:t})},{name:"set_operation$ebnf$1",symbols:[]},{name:"set_operation$ebnf$1",symbols:["set_operation$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"set_operation",symbols:[w.has("RESERVED_SET_OPERATION")?{type:"RESERVED_SET_OPERATION"}:RESERVED_SET_OPERATION,"set_operation$ebnf$1"],postprocess:([e,t])=>({type:b.set_operation,nameKw:Re(e),children:t})},{name:"expression_chain_$ebnf$1",symbols:["expression_with_comments_"]},{name:"expression_chain_$ebnf$1",symbols:["expression_chain_$ebnf$1","expression_with_comments_"],postprocess:e=>e[0].concat([e[1]])},{name:"expression_chain_",symbols:["expression_chain_$ebnf$1"],postprocess:uE},{name:"expression_chain$ebnf$1",symbols:[]},{name:"expression_chain$ebnf$1",symbols:["expression_chain$ebnf$1","_expression_with_comments"],postprocess:e=>e[0].concat([e[1]])},{name:"expression_chain",symbols:["expression","expression_chain$ebnf$1"],postprocess:([e,t])=>[e,...t]},{name:"andless_expression_chain$ebnf$1",symbols:[]},{name:"andless_expression_chain$ebnf$1",symbols:["andless_expression_chain$ebnf$1","_andless_expression_with_comments"],postprocess:e=>e[0].concat([e[1]])},{name:"andless_expression_chain",symbols:["andless_expression","andless_expression_chain$ebnf$1"],postprocess:([e,t])=>[e,...t]},{name:"expression_with_comments_",symbols:["expression","_"],postprocess:([e,t])=>Ae(e,{trailing:t})},{name:"_expression_with_comments",symbols:["_","expression"],postprocess:([e,t])=>Ae(t,{leading:e})},{name:"_andless_expression_with_comments",symbols:["_","andless_expression"],postprocess:([e,t])=>Ae(t,{leading:e})},{name:"free_form_sql$subexpression$1",symbols:["asteriskless_free_form_sql"]},{name:"free_form_sql$subexpression$1",symbols:["asterisk"]},{name:"free_form_sql",symbols:["free_form_sql$subexpression$1"],postprocess:Be},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["asteriskless_andless_expression"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["logic_operator"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["comma"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["comment"]},{name:"asteriskless_free_form_sql$subexpression$1",symbols:["other_keyword"]},{name:"asteriskless_free_form_sql",symbols:["asteriskless_free_form_sql$subexpression$1"],postprocess:Be},{name:"expression$subexpression$1",symbols:["andless_expression"]},{name:"expression$subexpression$1",symbols:["logic_operator"]},{name:"expression",symbols:["expression$subexpression$1"],postprocess:Be},{name:"andless_expression$subexpression$1",symbols:["asteriskless_andless_expression"]},{name:"andless_expression$subexpression$1",symbols:["asterisk"]},{name:"andless_expression",symbols:["andless_expression$subexpression$1"],postprocess:Be},{name:"asteriskless_andless_expression$subexpression$1",symbols:["atomic_expression"]},{name:"asteriskless_andless_expression$subexpression$1",symbols:["between_predicate"]},{name:"asteriskless_andless_expression$subexpression$1",symbols:["case_expression"]},{name:"asteriskless_andless_expression",symbols:["asteriskless_andless_expression$subexpression$1"],postprocess:Be},{name:"atomic_expression$subexpression$1",symbols:["array_subscript"]},{name:"atomic_expression$subexpression$1",symbols:["function_call"]},{name:"atomic_expression$subexpression$1",symbols:["property_access"]},{name:"atomic_expression$subexpression$1",symbols:["parenthesis"]},{name:"atomic_expression$subexpression$1",symbols:["curly_braces"]},{name:"atomic_expression$subexpression$1",symbols:["square_brackets"]},{name:"atomic_expression$subexpression$1",symbols:["operator"]},{name:"atomic_expression$subexpression$1",symbols:["identifier"]},{name:"atomic_expression$subexpression$1",symbols:["parameter"]},{name:"atomic_expression$subexpression$1",symbols:["literal"]},{name:"atomic_expression$subexpression$1",symbols:["data_type"]},{name:"atomic_expression$subexpression$1",symbols:["keyword"]},{name:"atomic_expression",symbols:["atomic_expression$subexpression$1"],postprocess:Be},{name:"array_subscript",symbols:[w.has("ARRAY_IDENTIFIER")?{type:"ARRAY_IDENTIFIER"}:ARRAY_IDENTIFIER,"_","square_brackets"],postprocess:([e,t,r])=>({type:b.array_subscript,array:Ae({type:b.identifier,quoted:!1,text:e.text},{trailing:t}),parenthesis:r})},{name:"array_subscript",symbols:[w.has("ARRAY_KEYWORD")?{type:"ARRAY_KEYWORD"}:ARRAY_KEYWORD,"_","square_brackets"],postprocess:([e,t,r])=>({type:b.array_subscript,array:Ae(Re(e),{trailing:t}),parenthesis:r})},{name:"function_call",symbols:[w.has("RESERVED_FUNCTION_NAME")?{type:"RESERVED_FUNCTION_NAME"}:RESERVED_FUNCTION_NAME,"_","parenthesis"],postprocess:([e,t,r])=>({type:b.function_call,nameKw:Ae(Re(e),{trailing:t}),parenthesis:r})},{name:"parenthesis",symbols:[{literal:"("},"expressions_or_clauses",{literal:")"}],postprocess:([e,t,r])=>({type:b.parenthesis,children:t,openParen:"(",closeParen:")"})},{name:"curly_braces$ebnf$1",symbols:[]},{name:"curly_braces$ebnf$1",symbols:["curly_braces$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"curly_braces",symbols:[{literal:"{"},"curly_braces$ebnf$1",{literal:"}"}],postprocess:([e,t,r])=>({type:b.parenthesis,children:t,openParen:"{",closeParen:"}"})},{name:"square_brackets$ebnf$1",symbols:[]},{name:"square_brackets$ebnf$1",symbols:["square_brackets$ebnf$1","free_form_sql"],postprocess:e=>e[0].concat([e[1]])},{name:"square_brackets",symbols:[{literal:"["},"square_brackets$ebnf$1",{literal:"]"}],postprocess:([e,t,r])=>({type:b.parenthesis,children:t,openParen:"[",closeParen:"]"})},{name:"property_access$subexpression$1",symbols:["identifier"]},{name:"property_access$subexpression$1",symbols:["array_subscript"]},{name:"property_access$subexpression$1",symbols:["all_columns_asterisk"]},{name:"property_access$subexpression$1",symbols:["parameter"]},{name:"property_access",symbols:["atomic_expression","_",w.has("PROPERTY_ACCESS_OPERATOR")?{type:"PROPERTY_ACCESS_OPERATOR"}:PROPERTY_ACCESS_OPERATOR,"_","property_access$subexpression$1"],postprocess:([e,t,r,n,[s]])=>({type:b.property_access,object:Ae(e,{trailing:t}),operator:r.text,property:Ae(s,{leading:n})})},{name:"between_predicate",symbols:[w.has("BETWEEN")?{type:"BETWEEN"}:BETWEEN,"_","andless_expression_chain","_",w.has("AND")?{type:"AND"}:AND,"_","andless_expression"],postprocess:([e,t,r,n,s,T,i])=>({type:b.between_predicate,betweenKw:Re(e),expr1:sS(r,{leading:t,trailing:n}),andKw:Re(s),expr2:[Ae(i,{leading:T})]})},{name:"case_expression$ebnf$1",symbols:["expression_chain_"],postprocess:uE},{name:"case_expression$ebnf$1",symbols:[],postprocess:()=>null},{name:"case_expression$ebnf$2",symbols:[]},{name:"case_expression$ebnf$2",symbols:["case_expression$ebnf$2","case_clause"],postprocess:e=>e[0].concat([e[1]])},{name:"case_expression",symbols:[w.has("CASE")?{type:"CASE"}:CASE,"_","case_expression$ebnf$1","case_expression$ebnf$2",w.has("END")?{type:"END"}:END],postprocess:([e,t,r,n,s])=>({type:b.case_expression,caseKw:Ae(Re(e),{trailing:t}),endKw:Re(s),expr:r||[],clauses:n})},{name:"case_clause",symbols:[w.has("WHEN")?{type:"WHEN"}:WHEN,"_","expression_chain_",w.has("THEN")?{type:"THEN"}:THEN,"_","expression_chain_"],postprocess:([e,t,r,n,s,T])=>({type:b.case_when,whenKw:Ae(Re(e),{trailing:t}),thenKw:Ae(Re(n),{trailing:s}),condition:r,result:T})},{name:"case_clause",symbols:[w.has("ELSE")?{type:"ELSE"}:ELSE,"_","expression_chain_"],postprocess:([e,t,r])=>({type:b.case_else,elseKw:Ae(Re(e),{trailing:t}),result:r})},{name:"comma$subexpression$1",symbols:[w.has("COMMA")?{type:"COMMA"}:COMMA]},{name:"comma",symbols:["comma$subexpression$1"],postprocess:([[e]])=>({type:b.comma})},{name:"asterisk$subexpression$1",symbols:[w.has("ASTERISK")?{type:"ASTERISK"}:ASTERISK]},{name:"asterisk",symbols:["asterisk$subexpression$1"],postprocess:([[e]])=>({type:b.operator,text:e.text})},{name:"operator$subexpression$1",symbols:[w.has("OPERATOR")?{type:"OPERATOR"}:OPERATOR]},{name:"operator",symbols:["operator$subexpression$1"],postprocess:([[e]])=>({type:b.operator,text:e.text})},{name:"identifier$subexpression$1",symbols:[w.has("IDENTIFIER")?{type:"IDENTIFIER"}:IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[w.has("QUOTED_IDENTIFIER")?{type:"QUOTED_IDENTIFIER"}:QUOTED_IDENTIFIER]},{name:"identifier$subexpression$1",symbols:[w.has("VARIABLE")?{type:"VARIABLE"}:VARIABLE]},{name:"identifier",symbols:["identifier$subexpression$1"],postprocess:([[e]])=>({type:b.identifier,quoted:e.type!=="IDENTIFIER",text:e.text})},{name:"parameter$subexpression$1",symbols:[w.has("NAMED_PARAMETER")?{type:"NAMED_PARAMETER"}:NAMED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[w.has("QUOTED_PARAMETER")?{type:"QUOTED_PARAMETER"}:QUOTED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[w.has("NUMBERED_PARAMETER")?{type:"NUMBERED_PARAMETER"}:NUMBERED_PARAMETER]},{name:"parameter$subexpression$1",symbols:[w.has("POSITIONAL_PARAMETER")?{type:"POSITIONAL_PARAMETER"}:POSITIONAL_PARAMETER]},{name:"parameter$subexpression$1",symbols:[w.has("CUSTOM_PARAMETER")?{type:"CUSTOM_PARAMETER"}:CUSTOM_PARAMETER]},{name:"parameter",symbols:["parameter$subexpression$1"],postprocess:([[e]])=>({type:b.parameter,key:e.key,text:e.text})},{name:"literal$subexpression$1",symbols:[w.has("NUMBER")?{type:"NUMBER"}:NUMBER]},{name:"literal$subexpression$1",symbols:[w.has("STRING")?{type:"STRING"}:STRING]},{name:"literal",symbols:["literal$subexpression$1"],postprocess:([[e]])=>({type:b.literal,text:e.text})},{name:"keyword$subexpression$1",symbols:[w.has("RESERVED_KEYWORD")?{type:"RESERVED_KEYWORD"}:RESERVED_KEYWORD]},{name:"keyword$subexpression$1",symbols:[w.has("RESERVED_KEYWORD_PHRASE")?{type:"RESERVED_KEYWORD_PHRASE"}:RESERVED_KEYWORD_PHRASE]},{name:"keyword$subexpression$1",symbols:[w.has("RESERVED_JOIN")?{type:"RESERVED_JOIN"}:RESERVED_JOIN]},{name:"keyword",symbols:["keyword$subexpression$1"],postprocess:([[e]])=>Re(e)},{name:"data_type$subexpression$1",symbols:[w.has("RESERVED_DATA_TYPE")?{type:"RESERVED_DATA_TYPE"}:RESERVED_DATA_TYPE]},{name:"data_type$subexpression$1",symbols:[w.has("RESERVED_DATA_TYPE_PHRASE")?{type:"RESERVED_DATA_TYPE_PHRASE"}:RESERVED_DATA_TYPE_PHRASE]},{name:"data_type",symbols:["data_type$subexpression$1"],postprocess:([[e]])=>dn(e)},{name:"data_type",symbols:[w.has("RESERVED_PARAMETERIZED_DATA_TYPE")?{type:"RESERVED_PARAMETERIZED_DATA_TYPE"}:RESERVED_PARAMETERIZED_DATA_TYPE,"_","parenthesis"],postprocess:([e,t,r])=>({type:b.parameterized_data_type,dataType:Ae(dn(e),{trailing:t}),parenthesis:r})},{name:"logic_operator$subexpression$1",symbols:[w.has("AND")?{type:"AND"}:AND]},{name:"logic_operator$subexpression$1",symbols:[w.has("OR")?{type:"OR"}:OR]},{name:"logic_operator$subexpression$1",symbols:[w.has("XOR")?{type:"XOR"}:XOR]},{name:"logic_operator",symbols:["logic_operator$subexpression$1"],postprocess:([[e]])=>Re(e)},{name:"other_keyword$subexpression$1",symbols:[w.has("WHEN")?{type:"WHEN"}:WHEN]},{name:"other_keyword$subexpression$1",symbols:[w.has("THEN")?{type:"THEN"}:THEN]},{name:"other_keyword$subexpression$1",symbols:[w.has("ELSE")?{type:"ELSE"}:ELSE]},{name:"other_keyword$subexpression$1",symbols:[w.has("END")?{type:"END"}:END]},{name:"other_keyword",symbols:["other_keyword$subexpression$1"],postprocess:([[e]])=>Re(e)},{name:"_$ebnf$1",symbols:[]},{name:"_$ebnf$1",symbols:["_$ebnf$1","comment"],postprocess:e=>e[0].concat([e[1]])},{name:"_",symbols:["_$ebnf$1"],postprocess:([e])=>e},{name:"comment",symbols:[w.has("LINE_COMMENT")?{type:"LINE_COMMENT"}:LINE_COMMENT],postprocess:([e])=>({type:b.line_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[w.has("BLOCK_COMMENT")?{type:"BLOCK_COMMENT"}:BLOCK_COMMENT],postprocess:([e])=>({type:b.block_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})},{name:"comment",symbols:[w.has("DISABLE_COMMENT")?{type:"DISABLE_COMMENT"}:DISABLE_COMMENT],postprocess:([e])=>({type:b.disable_comment,text:e.text,precedingWhitespace:e.precedingWhitespace})}],ParserStart:"main"},{Parser:TS,Grammar:iS}=JA;function aS(e){let t={};const r=new Es(s=>[...QA(e.tokenize(s,t)),$n(s.length)]),n=new TS(iS.fromCompiled(oS),{lexer:r});return{parse:(s,T)=>{t=T;const{results:i}=n.feed(s);if(i.length===1)return i[0];throw i.length===0?new Error("Parse error: Invalid SQL"):new Error(`Parse error: Ambiguous grammar
164
164
  ${JSON.stringify(i,void 0,2)}`)}}}var D;(function(e){e[e.SPACE=0]="SPACE",e[e.NO_SPACE=1]="NO_SPACE",e[e.NO_NEWLINE=2]="NO_NEWLINE",e[e.NEWLINE=3]="NEWLINE",e[e.MANDATORY_NEWLINE=4]="MANDATORY_NEWLINE",e[e.INDENT=5]="INDENT",e[e.SINGLE_INDENT=6]="SINGLE_INDENT"})(D=D||(D={}));class rs{constructor(t){this.indentation=t,this.items=[]}add(...t){for(const r of t)switch(r){case D.SPACE:this.items.push(D.SPACE);break;case D.NO_SPACE:this.trimHorizontalWhitespace();break;case D.NO_NEWLINE:this.trimWhitespace();break;case D.NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(D.NEWLINE);break;case D.MANDATORY_NEWLINE:this.trimHorizontalWhitespace(),this.addNewline(D.MANDATORY_NEWLINE);break;case D.INDENT:this.addIndentation();break;case D.SINGLE_INDENT:this.items.push(D.SINGLE_INDENT);break;default:this.items.push(r)}}trimHorizontalWhitespace(){for(;RS(st(this.items));)this.items.pop()}trimWhitespace(){for(;AS(st(this.items));)this.items.pop()}addNewline(t){if(this.items.length>0)switch(st(this.items)){case D.NEWLINE:this.items.pop(),this.items.push(t);break;case D.MANDATORY_NEWLINE:break;default:this.items.push(t);break}}addIndentation(){for(let t=0;t<this.indentation.getLevel();t++)this.items.push(D.SINGLE_INDENT)}toString(){return this.items.map(t=>this.itemToString(t)).join("")}getLayoutItems(){return this.items}itemToString(t){switch(t){case D.SPACE:return" ";case D.NEWLINE:case D.MANDATORY_NEWLINE:return`
165
165
  `;case D.SINGLE_INDENT:return this.indentation.getSingleIndent();default:return t}}}const RS=e=>e===D.SPACE||e===D.SINGLE_INDENT,AS=e=>e===D.SPACE||e===D.SINGLE_INDENT||e===D.NEWLINE;function Cn(e,t){if(t==="standard")return e;let r=[];return e.length>=10&&e.includes(" ")&&([e,...r]=e.split(" ")),t==="tabularLeft"?e=e.padEnd(9," "):e=e.padStart(9," "),e+["",...r].join(" ")}function Ln(e){return bT(e)||e===M.RESERVED_CLAUSE||e===M.RESERVED_SELECT||e===M.RESERVED_SET_OPERATION||e===M.RESERVED_JOIN||e===M.LIMIT}const pE="top-level",SS="block-level";class ns{constructor(t){this.indent=t,this.indentTypes=[]}getSingleIndent(){return this.indent}getLevel(){return this.indentTypes.length}increaseTopLevel(){this.indentTypes.push(pE)}increaseBlockLevel(){this.indentTypes.push(SS)}decreaseTopLevel(){this.indentTypes.length>0&&st(this.indentTypes)===pE&&this.indentTypes.pop()}decreaseBlockLevel(){for(;this.indentTypes.length>0&&this.indentTypes.pop()===pE;);}}class lS extends rs{constructor(t){super(new ns("")),this.expressionWidth=t,this.length=0,this.trailingSpace=!1}add(...t){if(t.forEach(r=>this.addToLength(r)),this.length>this.expressionWidth)throw new yE;super.add(...t)}addToLength(t){if(typeof t=="string")this.length+=t.length,this.trailingSpace=!1;else{if(t===D.MANDATORY_NEWLINE||t===D.NEWLINE)throw new yE;t===D.INDENT||t===D.SINGLE_INDENT||t===D.SPACE?this.trailingSpace||(this.length++,this.trailingSpace=!0):(t===D.NO_NEWLINE||t===D.NO_SPACE)&&this.trailingSpace&&(this.trailingSpace=!1,this.length--)}}}class yE extends Error{}class Ht{constructor({cfg:t,dialectCfg:r,params:n,layout:s,inline:T=!1}){this.inline=!1,this.nodes=[],this.index=-1,this.cfg=t,this.dialectCfg=r,this.inline=T,this.params=n,this.layout=s}format(t){for(this.nodes=t,this.index=0;this.index<this.nodes.length;this.index++)this.formatNode(this.nodes[this.index]);return this.layout}formatNode(t){this.formatComments(t.leadingComments),this.formatNodeWithoutComments(t),this.formatComments(t.trailingComments)}formatNodeWithoutComments(t){switch(t.type){case b.function_call:return this.formatFunctionCall(t);case b.parameterized_data_type:return this.formatParameterizedDataType(t);case b.array_subscript:return this.formatArraySubscript(t);case b.property_access:return this.formatPropertyAccess(t);case b.parenthesis:return this.formatParenthesis(t);case b.between_predicate:return this.formatBetweenPredicate(t);case b.case_expression:return this.formatCaseExpression(t);case b.case_when:return this.formatCaseWhen(t);case b.case_else:return this.formatCaseElse(t);case b.clause:return this.formatClause(t);case b.set_operation:return this.formatSetOperation(t);case b.limit_clause:return this.formatLimitClause(t);case b.all_columns_asterisk:return this.formatAllColumnsAsterisk(t);case b.literal:return this.formatLiteral(t);case b.identifier:return this.formatIdentifier(t);case b.parameter:return this.formatParameter(t);case b.operator:return this.formatOperator(t);case b.comma:return this.formatComma(t);case b.line_comment:return this.formatLineComment(t);case b.block_comment:return this.formatBlockComment(t);case b.disable_comment:return this.formatBlockComment(t);case b.data_type:return this.formatDataType(t);case b.keyword:return this.formatKeywordNode(t)}}formatFunctionCall(t){this.withComments(t.nameKw,()=>{this.layout.add(this.showFunctionKw(t.nameKw))}),this.formatNode(t.parenthesis)}formatParameterizedDataType(t){this.withComments(t.dataType,()=>{this.layout.add(this.showDataType(t.dataType))}),this.formatNode(t.parenthesis)}formatArraySubscript(t){let r;switch(t.array.type){case b.data_type:r=this.showDataType(t.array);break;case b.keyword:r=this.showKw(t.array);break;default:r=this.showIdentifier(t.array);break}this.withComments(t.array,()=>{this.layout.add(r)}),this.formatNode(t.parenthesis)}formatPropertyAccess(t){this.formatNode(t.object),this.layout.add(D.NO_SPACE,t.operator),this.formatNode(t.property)}formatParenthesis(t){const r=this.formatInlineExpression(t.children);r?(this.layout.add(t.openParen),this.layout.add(...r.getLayoutItems()),this.layout.add(D.NO_SPACE,t.closeParen,D.SPACE)):(this.layout.add(t.openParen,D.NEWLINE),je(this.cfg)?(this.layout.add(D.INDENT),this.layout=this.formatSubExpression(t.children)):(this.layout.indentation.increaseBlockLevel(),this.layout.add(D.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseBlockLevel()),this.layout.add(D.NEWLINE,D.INDENT,t.closeParen,D.SPACE))}formatBetweenPredicate(t){this.layout.add(this.showKw(t.betweenKw),D.SPACE),this.layout=this.formatSubExpression(t.expr1),this.layout.add(D.NO_SPACE,D.SPACE,this.showNonTabularKw(t.andKw),D.SPACE),this.layout=this.formatSubExpression(t.expr2),this.layout.add(D.SPACE)}formatCaseExpression(t){this.formatNode(t.caseKw),this.layout.indentation.increaseBlockLevel(),this.layout=this.formatSubExpression(t.expr),this.layout=this.formatSubExpression(t.clauses),this.layout.indentation.decreaseBlockLevel(),this.layout.add(D.NEWLINE,D.INDENT),this.formatNode(t.endKw)}formatCaseWhen(t){this.layout.add(D.NEWLINE,D.INDENT),this.formatNode(t.whenKw),this.layout=this.formatSubExpression(t.condition),this.formatNode(t.thenKw),this.layout=this.formatSubExpression(t.result)}formatCaseElse(t){this.layout.add(D.NEWLINE,D.INDENT),this.formatNode(t.elseKw),this.layout=this.formatSubExpression(t.result)}formatClause(t){this.isOnelineClause(t)?this.formatClauseInOnelineStyle(t):je(this.cfg)?this.formatClauseInTabularStyle(t):this.formatClauseInIndentedStyle(t)}isOnelineClause(t){return je(this.cfg)?this.dialectCfg.tabularOnelineClauses[t.nameKw.text]:this.dialectCfg.onelineClauses[t.nameKw.text]}formatClauseInIndentedStyle(t){this.layout.add(D.NEWLINE,D.INDENT,this.showKw(t.nameKw),D.NEWLINE),this.layout.indentation.increaseTopLevel(),this.layout.add(D.INDENT),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatClauseInOnelineStyle(t){this.layout.add(D.NEWLINE,D.INDENT,this.showKw(t.nameKw),D.SPACE),this.layout=this.formatSubExpression(t.children)}formatClauseInTabularStyle(t){this.layout.add(D.NEWLINE,D.INDENT,this.showKw(t.nameKw),D.SPACE),this.layout.indentation.increaseTopLevel(),this.layout=this.formatSubExpression(t.children),this.layout.indentation.decreaseTopLevel()}formatSetOperation(t){this.layout.add(D.NEWLINE,D.INDENT,this.showKw(t.nameKw),D.NEWLINE),this.layout.add(D.INDENT),this.layout=this.formatSubExpression(t.children)}formatLimitClause(t){this.withComments(t.limitKw,()=>{this.layout.add(D.NEWLINE,D.INDENT,this.showKw(t.limitKw))}),this.layout.indentation.increaseTopLevel(),je(this.cfg)?this.layout.add(D.SPACE):this.layout.add(D.NEWLINE,D.INDENT),t.offset?(this.layout=this.formatSubExpression(t.offset),this.layout.add(D.NO_SPACE,",",D.SPACE),this.layout=this.formatSubExpression(t.count)):this.layout=this.formatSubExpression(t.count),this.layout.indentation.decreaseTopLevel()}formatAllColumnsAsterisk(t){this.layout.add("*",D.SPACE)}formatLiteral(t){this.layout.add(t.text,D.SPACE)}formatIdentifier(t){this.layout.add(this.showIdentifier(t),D.SPACE)}formatParameter(t){this.layout.add(this.params.get(t),D.SPACE)}formatOperator({text:t}){this.cfg.denseOperators||this.dialectCfg.alwaysDenseOperators.includes(t)?this.layout.add(D.NO_SPACE,t):t===":"?this.layout.add(D.NO_SPACE,t,D.SPACE):this.layout.add(t,D.SPACE)}formatComma(t){this.inline?this.layout.add(D.NO_SPACE,",",D.SPACE):this.layout.add(D.NO_SPACE,",",D.NEWLINE,D.INDENT)}withComments(t,r){this.formatComments(t.leadingComments),r(),this.formatComments(t.trailingComments)}formatComments(t){t&&t.forEach(r=>{r.type===b.line_comment?this.formatLineComment(r):this.formatBlockComment(r)})}formatLineComment(t){LE(t.precedingWhitespace||"")?this.layout.add(D.NEWLINE,D.INDENT,t.text,D.MANDATORY_NEWLINE,D.INDENT):this.layout.getLayoutItems().length>0?this.layout.add(D.NO_NEWLINE,D.SPACE,t.text,D.MANDATORY_NEWLINE,D.INDENT):this.layout.add(t.text,D.MANDATORY_NEWLINE,D.INDENT)}formatBlockComment(t){t.type===b.block_comment&&this.isMultilineBlockComment(t)?(this.splitBlockComment(t.text).forEach(r=>{this.layout.add(D.NEWLINE,D.INDENT,r)}),this.layout.add(D.NEWLINE,D.INDENT)):this.layout.add(t.text,D.SPACE)}isMultilineBlockComment(t){return LE(t.text)||LE(t.precedingWhitespace||"")}isDocComment(t){const r=t.split(/\n/);return/^\/\*\*?$/.test(r[0])&&r.slice(1,r.length-1).every(n=>/^\s*\*/.test(n))&&/^\s*\*\/$/.test(st(r))}splitBlockComment(t){return this.isDocComment(t)?t.split(/\n/).map(r=>/^\s*\*/.test(r)?" "+r.replace(/^\s*/,""):r):t.split(/\n/).map(r=>r.replace(/^\s*/,""))}formatSubExpression(t){return new Ht({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:this.layout,inline:this.inline}).format(t)}formatInlineExpression(t){const r=this.params.getPositionalParameterIndex();try{return new Ht({cfg:this.cfg,dialectCfg:this.dialectCfg,params:this.params,layout:new lS(this.cfg.expressionWidth),inline:!0}).format(t)}catch(n){if(n instanceof yE){this.params.setPositionalParameterIndex(r);return}else throw n}}formatKeywordNode(t){switch(t.tokenType){case M.RESERVED_JOIN:return this.formatJoin(t);case M.AND:case M.OR:case M.XOR:return this.formatLogicalOperator(t);default:return this.formatKeyword(t)}}formatJoin(t){je(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(D.NEWLINE,D.INDENT,this.showKw(t),D.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(D.NEWLINE,D.INDENT,this.showKw(t),D.SPACE)}formatKeyword(t){this.layout.add(this.showKw(t),D.SPACE)}formatLogicalOperator(t){this.cfg.logicalOperatorNewline==="before"?je(this.cfg)?(this.layout.indentation.decreaseTopLevel(),this.layout.add(D.NEWLINE,D.INDENT,this.showKw(t),D.SPACE),this.layout.indentation.increaseTopLevel()):this.layout.add(D.NEWLINE,D.INDENT,this.showKw(t),D.SPACE):this.layout.add(this.showKw(t),D.NEWLINE,D.INDENT)}formatDataType(t){this.layout.add(this.showDataType(t),D.SPACE)}showKw(t){return Ln(t.tokenType)?Cn(this.showNonTabularKw(t),this.cfg.indentStyle):this.showNonTabularKw(t)}showNonTabularKw(t){switch(this.cfg.keywordCase){case"preserve":return Gt(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}showFunctionKw(t){return Ln(t.tokenType)?Cn(this.showNonTabularFunctionKw(t),this.cfg.indentStyle):this.showNonTabularFunctionKw(t)}showNonTabularFunctionKw(t){switch(this.cfg.functionCase){case"preserve":return Gt(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}showIdentifier(t){if(t.quoted)return t.text;switch(this.cfg.identifierCase){case"preserve":return t.text;case"upper":return t.text.toUpperCase();case"lower":return t.text.toLowerCase()}}showDataType(t){switch(this.cfg.dataTypeCase){case"preserve":return Gt(t.raw);case"upper":return t.text;case"lower":return t.text.toLowerCase()}}}class IS{constructor(t,r){this.dialect=t,this.cfg=r,this.params=new jA(this.cfg.params)}format(t){const r=this.parse(t);return this.formatAst(r).trimEnd()}parse(t){return aS(this.dialect.tokenizer).parse(t,this.cfg.paramTypes||{})}formatAst(t){return t.map(r=>this.formatStatement(r)).join(`
166
166
  `.repeat(this.cfg.linesBetweenQueries+1))}formatStatement(t){const r=new Ht({cfg:this.cfg,dialectCfg:this.dialect.formatOptions,params:this.params,layout:new rs(new ns(kA(this.cfg)))}).format(t.children);return t.hasSemicolon&&(this.cfg.newlineBeforeSemicolon?r.add(D.NEWLINE,";"):r.add(D.NO_NEWLINE,";")),r.toString()}}class bt extends Error{}function OS(e){const t=["multilineLists","newlineBeforeOpenParen","newlineBeforeCloseParen","aliasAs","commaPosition","tabulateAlias"];for(const r of t)if(r in e)throw new bt(`${r} config is no more supported.`);if(e.expressionWidth<=0)throw new bt(`expressionWidth config must be positive number. Received ${e.expressionWidth} instead.`);if(e.params&&!NS(e.params)&&console.warn('WARNING: All "params" option values should be strings.'),e.paramTypes&&!cS(e.paramTypes))throw new bt("Empty regex given in custom paramTypes. That would result in matching infinite amount of parameters.");return e}function NS(e){return(e instanceof Array?e:Object.values(e)).every(r=>typeof r=="string")}function cS(e){return e.custom&&Array.isArray(e.custom)?e.custom.every(t=>t.regex!==""):!0}var dS=function(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var s=0,n=Object.getOwnPropertySymbols(e);s<n.length;s++)t.indexOf(n[s])<0&&Object.prototype.propertyIsEnumerable.call(e,n[s])&&(r[n[s]]=e[n[s]]);return r};const ss={bigquery:"bigquery",clickhouse:"clickhouse",db2:"db2",db2i:"db2i",duckdb:"duckdb",hive:"hive",mariadb:"mariadb",mysql:"mysql",n1ql:"n1ql",plsql:"plsql",postgresql:"postgresql",redshift:"redshift",spark:"spark",sqlite:"sqlite",sql:"sql",tidb:"tidb",trino:"trino",transactsql:"transactsql",tsql:"transactsql",singlestoredb:"singlestoredb",snowflake:"snowflake"},CS=Object.keys(ss),LS={tabWidth:2,useTabs:!1,keywordCase:"preserve",identifierCase:"preserve",dataTypeCase:"preserve",functionCase:"preserve",indentStyle:"standard",logicalOperatorNewline:"before",expressionWidth:50,linesBetweenQueries:1,denseOperators:!1,newlineBeforeSemicolon:!1},_S=(e,t={})=>{if(typeof t.language=="string"&&!CS.includes(t.language))throw new bt(`Unsupported SQL dialect: ${t.language}`);const r=ss[t.language||"sql"];return uS(e,Object.assign(Object.assign({},t),{dialect:fA[r]}))},uS=(e,t)=>{var{dialect:r}=t,n=dS(t,["dialect"]);if(typeof e!="string")throw new Error("Invalid query argument. Expected string, instead got "+typeof e);const s=OS(Object.assign(Object.assign({},LS),n));return new IS(WA(r),s).format(e)};function pS({warehouseColumns:e,warehouseRows:t,warehouseRowCount:r,busy:n,t:s,onCancel:T,onCombine:i,suggestedPlan:o}){const[S,a]=l.useState([]),[A,R]=l.useState(!0),[N,O]=l.useState(null),[c,C]=l.useState(""),[I,d]=l.useState(""),[L,f]=l.useState(""),[v,U]=l.useState("left"),[F,h]=l.useState(!1),[p,G]=l.useState(!1);l.useEffect(()=>{let B=!1;return R(!0),Q.getDatasets().then(ee=>{if(B)return;const le=ee.datasets.filter(x=>x.storageMode!=="staged");a(le);const Ie=le.find(x=>x.id===(o==null?void 0:o.datasetId)||x.alias===(o==null?void 0:o.localDataset));C(x=>{var u;return x||(Ie==null?void 0:Ie.id)||((u=le[0])==null?void 0:u.id)||""})}).catch(ee=>{B||O(ee instanceof Error?ee.message:String(ee))}).finally(()=>{B||R(!1)}),()=>{B=!0}},[o==null?void 0:o.datasetId,o==null?void 0:o.localDataset]);const y=S.find(B=>B.id===c),V=l.useMemo(()=>y?Ms(e,y.profile.columns):[],[y,e]);l.useEffect(()=>{if(y&&(y.id===(o==null?void 0:o.datasetId)||y.alias===(o==null?void 0:o.localDataset))&&o){d(e.includes(o.warehouseKey)?o.warehouseKey:""),f(y.profile.columns.some(le=>le.name===o.localKey)?o.localKey:""),h(!1),G(!1);return}const ee=V[0];d((ee==null?void 0:ee.warehouseKey)??""),f((ee==null?void 0:ee.localKey)??""),h(!1),G(!1)},[y,c,o,V,e]);const k=y==null?void 0:y.profile.columns.find(B=>B.name===L),Z=ms({warehouseRows:t,warehouseKey:I,localDistinctCount:k==null?void 0:k.distinctCount,localSampledRows:y==null?void 0:y.profile.sampledRows}),g=Z==="many_to_many",K=V.length===0,j=!!(y&&I&&L&&(!g||F)&&(!K||p));return E.jsxs("div",{style:{padding:12,borderBottom:`1px solid ${s.cellBorder}`,background:`${s.accent}08`,display:"grid",gap:10},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[E.jsx(Fn,{size:14,color:s.accent}),E.jsxs("div",{style:{flex:1},children:[E.jsx("div",{style:{color:s.textPrimary,font:`800 12px ${s.font}`},children:"Combine warehouse result with local data"}),E.jsx("div",{style:{color:s.textMuted,font:`10px ${s.font}`},children:"The warehouse query is staged with limits, then the join runs in the local analysis workspace."}),o&&E.jsxs("div",{style:{color:s.accent,font:`700 10px ${s.font}`,marginTop:2},children:["AI prepared this handoff · confirm ",o.warehouseKey," = ",o.localKey]})]}),E.jsx("button",{"aria-label":"Close combine data",onClick:T,style:{border:0,background:"transparent",color:s.textMuted,cursor:"pointer"},children:E.jsx(Hn,{size:15})})]}),A?E.jsx("div",{style:{color:s.textMuted,fontSize:11},children:"Loading local datasets…"}):N?E.jsx("div",{style:{color:s.error,fontSize:11},children:N}):S.length===0?E.jsxs("div",{style:{border:`1px dashed ${s.btnBorder}`,borderRadius:7,padding:12,color:s.textSecondary,fontSize:11},children:["Import a CSV from ",E.jsx("strong",{children:"Import data"})," first, then return to this warehouse result."]}):E.jsxs(E.Fragment,{children:[E.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(145px, 1fr))",gap:8,alignItems:"end"},children:[E.jsx(pt,{label:"Local dataset",t:s,children:E.jsx("select",{value:c,onChange:B=>C(B.target.value),style:Dt(s),children:S.map(B=>E.jsxs("option",{value:B.id,children:[B.name," · ",B.profile.rowCount.toLocaleString()," rows"]},B.id))})}),E.jsx(pt,{label:"Warehouse key",t:s,children:E.jsxs("select",{value:I,onChange:B=>{d(B.target.value),h(!1)},style:Dt(s),children:[!I&&E.jsx("option",{value:"",children:"Choose warehouse key…"}),e.map(B=>E.jsx("option",{value:B,children:B},B))]})}),E.jsx(pt,{label:"Local key (=)",t:s,children:E.jsxs("select",{value:L,onChange:B=>{f(B.target.value),h(!1)},style:Dt(s),children:[!L&&E.jsx("option",{value:"",children:"Choose local key…"}),y==null?void 0:y.profile.columns.map(B=>E.jsx("option",{value:B.name,children:B.name},B.name))]})}),E.jsx(pt,{label:"Join",t:s,children:E.jsxs("select",{value:v,onChange:B=>U(B.target.value),style:Dt(s),children:[E.jsx("option",{value:"left",children:"Keep warehouse rows"}),E.jsx("option",{value:"inner",children:"Matching rows only"})]})})]}),E.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:7,alignItems:"center",color:s.textMuted,font:`10px ${s.font}`},children:[E.jsxs("span",{children:[E.jsx(vt,{size:11,style:{verticalAlign:"-2px"}})," Up to ",r.toLocaleString()," current rows"]}),E.jsx("span",{children:"· staging limits 100,000 rows / 250 MB / 120 sec"}),E.jsxs("span",{children:["· CSV refreshed ",y?new Date(y.refreshedAt).toLocaleString():"—"]}),E.jsxs("span",{children:["· sample relationship: ",Z.replace(/_/g," ")]}),V[0]&&I===V[0].warehouseKey&&L===V[0].localKey&&E.jsxs("span",{style:{color:s.accent},children:["· suggested: ",V[0].reason.toLowerCase()]})]}),g&&E.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:7,padding:9,border:`1px solid ${s.warning}`,borderRadius:7,color:s.warning,font:`10px ${s.font}`},children:[E.jsx(_r,{size:13,style:{flexShrink:0}}),E.jsx("input",{type:"checkbox",checked:F,onChange:B=>h(B.target.checked)}),"Both keys repeat in the bounded samples. This may multiply rows. Confirm that repeated matches are expected before continuing."]}),K&&E.jsxs("label",{style:{display:"flex",alignItems:"flex-start",gap:7,padding:9,border:`1px solid ${s.warning}`,borderRadius:7,color:s.warning,font:`10px ${s.font}`},children:[E.jsx(_r,{size:13,style:{flexShrink:0}}),E.jsx("input",{type:"checkbox",checked:p,onChange:B=>G(B.target.checked)}),"No likely business key was found. Choose both keys and confirm they represent the same entity. If they do not, refine the warehouse query or ask Notebook AI instead of forcing a join."]}),E.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:8,alignItems:"center"},children:[E.jsx("span",{style:{color:s.warning,font:`700 10px ${s.font}`},children:"Local mixed-source analysis · review required · never auto-certified"}),E.jsxs("div",{style:{display:"flex",gap:7},children:[E.jsx("button",{onClick:T,style:DS(s),children:"Cancel"}),E.jsx("button",{disabled:!j||n,onClick:()=>y&&i({dataset:y,warehouseKey:I,localKey:L,joinType:v,cardinality:Z}),style:{...PS(s),opacity:j&&!n?1:.5},children:n?"Staging and building…":o?"Create joined analysis":"Stage and create analysis"})]})]})]})]})}function pt({label:e,t,children:r}){return E.jsxs("label",{style:{display:"grid",gap:4,color:t.textMuted,font:`700 9px ${t.font}`,textTransform:"uppercase",letterSpacing:".05em"},children:[e,r]})}function Dt(e){return{width:"100%",minWidth:0,height:30,border:`1px solid ${e.btnBorder}`,borderRadius:5,background:e.cellBg,color:e.textPrimary,padding:"0 7px",font:`11px ${e.font}`}}function DS(e){return{border:`1px solid ${e.btnBorder}`,borderRadius:5,background:e.btnBg,color:e.textSecondary,padding:"6px 10px",cursor:"pointer",font:`700 10px ${e.font}`}}function PS(e){return{border:`1px solid ${e.accent}`,borderRadius:5,background:e.accent,color:"#fff",padding:"6px 11px",cursor:"pointer",font:`800 10px ${e.font}`}}const _n=["string","number","boolean","date","string[]","number[]","date[]"],MS=["dynamic","optional","static","business","derived"];function mS({source:e,onSourceChange:t,t:r}){const n=l.useMemo(()=>fs(e),[e]),s=/\btype\s*=\s*"semantic"/i.test(e),[T,i]=l.useState(!1),[o,S]=l.useState(""),[a,A]=l.useState(""),[R,N]=l.useState(!1),[O,c]=l.useState("string"),C=(d,L)=>{t(lr(Ir(e),{name:d.name,type:L.type??d.type,required:L.required??d.required,defaultText:L.defaultText??ar(d),policy:L.policy??d.policy}))},I=()=>{const d=o.trim().toLowerCase().replace(/[^a-z0-9_]+/g,"_").replace(/^_+|_+$/g,"");if(!d)return;const L=Ir(e),f=s?Rr(L,[...Ar(L).requestedFilters,d]):L;t(lr(f,{name:d,type:O,required:R,defaultText:a,policy:R?"dynamic":"optional"})),S(""),A(""),N(!1),c("string"),i(!1)};return E.jsxs("div",{style:{padding:"7px 10px",borderBottom:`1px solid ${r.cellBorder}`,background:`${r.tableHeaderBg}35`},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,minHeight:24},children:[E.jsx("span",{style:{fontSize:10.5,fontWeight:800,color:r.textSecondary},children:"Parameters"}),n.length>0&&E.jsx("span",{style:{fontSize:9.5,color:r.textMuted},children:n.length}),s&&E.jsx("span",{style:{fontSize:9.5,color:r.textMuted},children:"New parameters bind to semantic filters with the same field name."}),E.jsx("span",{style:{flex:1}}),E.jsx("button",{type:"button",onClick:()=>i(d=>!d),style:GE(r),children:T?"Cancel":"+ Add"})]}),n.length>0&&E.jsx("div",{style:{display:"grid",gap:6,marginTop:6},children:n.map(d=>E.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(110px, 1fr) 92px minmax(115px, 1.2fr) auto 92px auto",gap:6,alignItems:"center",overflowX:"auto"},children:[E.jsx("span",{title:"Parameter names are stable; remove and add again to rename.",style:{fontFamily:r.fontMono,fontSize:10.5,color:r.textPrimary,overflow:"hidden",textOverflow:"ellipsis"},children:d.name}),E.jsx("select",{"aria-label":`${d.name} type`,value:d.type,onChange:L=>C(d,{type:L.target.value}),style:$e(r),children:_n.map(L=>E.jsx("option",{value:L,children:L},L))}),E.jsx("input",{"aria-label":`${d.name} default`,value:ar(d),disabled:d.required,placeholder:d.required?"Required at run time":"Default value",onChange:L=>C(d,{defaultText:L.target.value}),style:{...$e(r),opacity:d.required?.6:1}}),E.jsxs("label",{style:{display:"flex",alignItems:"center",gap:3,fontSize:9.5,color:r.textMuted,whiteSpace:"nowrap"},children:[E.jsx("input",{type:"checkbox",checked:d.required,onChange:L=>C(d,{required:L.target.checked})})," Req"]}),E.jsx("select",{"aria-label":`${d.name} policy`,value:d.policy,onChange:L=>C(d,{policy:L.target.value}),style:$e(r),children:MS.map(L=>E.jsx("option",{value:L,children:L},L))}),E.jsx("button",{type:"button",title:`Remove ${d.name}`,onClick:()=>{var f;const L=hs(e,d.name);t(((f=d.binding)==null?void 0:f.kind)==="semantic_filter"?Rr(L,Ar(e).requestedFilters.filter(v=>v!==d.name)):L)},style:fS(r),children:"Remove"})]},d.name))}),T&&E.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(110px, 1fr) 92px minmax(115px, 1.2fr) auto auto",gap:6,alignItems:"center",marginTop:7},children:[E.jsx("input",{"aria-label":"New parameter name",autoFocus:!0,value:o,placeholder:s?"semantic_field":"parameter_name",onChange:d=>{S(d.target.value),a||c(Sr("",d.target.value))},style:$e(r)}),E.jsx("select",{"aria-label":"New parameter type",value:O,onChange:d=>c(d.target.value),style:$e(r),children:_n.map(d=>E.jsx("option",{value:d,children:d},d))}),E.jsx("input",{"aria-label":"New parameter default",value:a,disabled:R,placeholder:R?"Required at run time":"Default value",onChange:d=>{A(d.target.value),c(Sr(d.target.value,o))},style:{...$e(r),opacity:R?.6:1}}),E.jsxs("label",{style:{display:"flex",alignItems:"center",gap:4,fontSize:9.5,color:r.textMuted,whiteSpace:"nowrap"},children:[E.jsx("input",{type:"checkbox",checked:R,onChange:d=>N(d.target.checked)})," Required"]}),E.jsx("button",{type:"button",disabled:!o.trim(),onClick:I,style:{...GE(r),opacity:o.trim()?1:.5},children:"Add"})]})]})}function $e(e){return{width:"100%",minWidth:0,boxSizing:"border-box",background:e.inputBg,border:`1px solid ${e.inputBorder}`,borderRadius:5,color:e.textPrimary,padding:"4px 6px",fontSize:10.5,fontFamily:e.font}}function GE(e){return{border:`1px solid ${e.btnBorder}`,borderRadius:4,background:"transparent",color:e.accent,padding:"2px 7px",fontSize:10,fontWeight:700,cursor:"pointer"}}function fS(e){return{...GE(e),color:e.textMuted,paddingInline:5}}const hS=new Set(["AMBIGUOUS_NOTEBOOK_DEPENDENCY","CROSS_ENGINE_JOIN_REQUIRED","EXECUTION_TARGET_MISMATCH","SEMANTIC_SOURCE_DRIFT","STALE_CELL_EXECUTION","UPSTREAM_RESULT_UNAVAILABLE","UNAUTHORIZED"]),US=/(?:permission|not authorized|unauthori[sz]ed|access denied|authentication|credential|policy|unsafe|read[- ]only|cancel(?:led|ed)|required parameters?|provide required|cross[- ]engine|upstream (?:cell|result)|notebook dependency|target mismatch|source drift|matched more than one schema)/i;function un(e){var r,n,s;if(!e.error||e.type!=="sql"&&e.type!=="dql")return!1;const t=(s=(n=(r=e.execution)==null?void 0:r.error)==null?void 0:n.code)==null?void 0:s.trim().toUpperCase();return t&&hS.has(t)||US.test(e.error)?!1:e.type==="sql"?!/\{\{[^}]+\}\}/.test(e.content):/^\s*@block\(/i.test(e.content)?!1:/\bblock\b/i.test(e.content)&&/\bquery\b/i.test(e.content)&&!/\btype\s*=\s*"semantic"/i.test(e.content)}function xS(e){const r=(e instanceof Error?e.message:String(e??"")).replace(/\s+/g," ").trim();return r?r.length>420?`${r.slice(0,419)}…`:r:"Automatic repair could not finish safely. Edit this cell and run again."}function he({cell:e,t,onRun:r,onMoveUp:n,onMoveDown:s,onDelete:T,children:i}){const[o,S]=l.useState(!1),a=is(e,t),A=Ts[e.type]??t.accent,R=e.name?E.jsx("span",{style:{color:t.textSecondary,fontSize:12,fontFamily:t.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:200},children:e.name}):void 0,N=o?E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:2},children:[r&&E.jsx(ue,{title:"Run cell (Shift+Enter)",onClick:r,t,run:!0,children:E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}),E.jsx(ue,{title:"Move up",onClick:n,t,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M3.47 7.78a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1-1.06 1.06L8.75 4.81v7.44a.75.75 0 0 1-1.5 0V4.81L4.53 7.78a.75.75 0 0 1-1.06 0Z"})})}),E.jsx(ue,{title:"Move down",onClick:s,t,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M12.53 8.22a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L2.97 9.28a.75.75 0 0 1 1.06-1.06l2.72 2.97V3.75a.75.75 0 0 1 1.5 0v7.44l2.72-2.97a.75.75 0 0 1 1.06 0Z"})})}),E.jsx(ue,{title:"Delete cell",onClick:T,t,danger:!0,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M11 1.75V3h2.25a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1 0-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75ZM4.496 6.675l.66 6.6a.25.25 0 0 0 .249.225h5.19a.25.25 0 0 0 .249-.225l.66-6.6a.75.75 0 0 1 1.492.149l-.66 6.6A1.748 1.748 0 0 1 10.595 15h-5.19a1.75 1.75 0 0 1-1.741-1.575l-.66-6.6a.75.75 0 1 1 1.492-.15ZM6.5 1.75V3h3V1.75a.25.25 0 0 0-.25-.25h-2.5a.25.25 0 0 0-.25.25Z"})})})]}):void 0;return E.jsx(vn,{typeLabel:os[e.type]??e.type.toUpperCase(),typeColor:A,accent:a,idleBorder:t.cellBorder,background:t.cellBg,headerBackground:`${t.tableHeaderBg}80`,active:o||e.status!=="idle",title:R,actions:N,status:E.jsx(as,{cell:e,t}),onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),children:i})}const os={sql:"QUERY",markdown:"MD",dql:"DQL",param:"PARAM",chart:"CHART",pivot:"PIVOT",single_value:"SINGLE VALUE",filter:"FILTER",table:"TABLE",map:"MAP",writeback:"WRITEBACK",python:"PYTHON",chat:"CHAT"};function Oe(e,t){return typeof window>"u"?t:getComputedStyle(document.documentElement).getPropertyValue(e).trim()||t}function gS(){return{sql:Oe("--cell-sql","#3b8ef0"),markdown:Oe("--cell-md","#2fb97a"),dql:Oe("--cell-insight","#ffc857"),param:Oe("--cell-inputs","#9aa0ae"),chart:Oe("--cell-chart","#b067f7"),pivot:Oe("--cell-pivot","#e5a84d"),single_value:Oe("--cell-single","#b067f7"),filter:Oe("--cell-filter","#f26a6a"),table:Oe("--cell-table","#5dd1c8"),map:Oe("--cell-goal","#61d095"),writeback:Oe("--cell-callout","#ff7ac6"),python:Oe("--cell-sql","#3b8ef0"),chat:Oe("--cell-chat","#8a8f9b")}}const Ts=new Proxy({},{get(e,t){return gS()[t]}}),yS={map:{title:"Map",subtitle:"Geospatial visualization — lat/lon points and choropleths from an upstream dataframe. Lands in v0.11 on the dql-compiler geo pipeline.",color:"#7ce38b",badge:"v0.11"},writeback:{title:"Writeback",subtitle:"Governed output sink — writes a dataframe back to your warehouse with block tests gating the commit. Lands in v0.11.",color:"#d2a8ff",badge:"v0.11"},python:{title:"Python (legacy)",subtitle:"This legacy cell is preserved for compatibility. Execution stays disabled until a secure kernel, dependency environment, cancellation, resource limits, and dataframe exchange are available.",color:"#3572a5",badge:"Unavailable"}};function is(e,t){if(e.blockBinding)return e.blockBinding.state==="forked"?t.warning:t.success;switch(e.status){case"running":return t.cellBorderRunning;case"success":return t.success;case"error":return t.error;default:return t.cellBorder}}function as({cell:e,t}){var T;const{status:r}=e;if(r==="idle"&&e.executionCount===void 0)return null;let n=t.textMuted,s="";if(r==="running")n=t.cellBorderRunning,s="Running…";else if(r==="error")n=t.error,s="Error";else if(e.executionCount!==void 0)if(n=t.success,((T=e.result)==null?void 0:T.executionTime)!==void 0){const i=e.result.executionTime;s=i<1e3?`${Math.max(1,Math.round(i))}ms`:`${(i/1e3).toFixed(1)}s`}else s=`[${e.executionCount}]`;return E.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:5,fontSize:10,fontFamily:t.font,color:t.textMuted,flexShrink:0},children:[E.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:n,boxShadow:r==="running"?`0 0 0 3px ${n}33`:void 0,animation:r==="running"?"pulse 1.2s ease-in-out infinite":void 0,flexShrink:0}}),s,E.jsx("style",{children:"@keyframes pulse { 0%,100%{opacity:1} 50%{opacity:0.5} }"})]})}function GS(e){if(!/^\s*block\s+"/i.test(e.trim()))return null;const t=s=>{var T;return((T=e.match(new RegExp(`\\b${s}\\s*=\\s*"([^"]*)"`,"i")))==null?void 0:T[1])??""},r=e.match(/\btags\s*=\s*\[([^\]]*)\]/i),n=r?(r[1].match(/"([^"]*)"/g)??[]).map(s=>s.slice(1,-1)):[];return{domain:t("domain"),owner:t("owner"),description:t("description"),blockType:t("type")||"custom",tags:n}}function DE(e,t,r){const n=new RegExp(`(\\b${t}\\s*=\\s*)"[^"]*"`,"i");return n.test(e)?e.replace(n,`$1"${r.replace(/"/g,'\\"')}"`):e}function BS(e,t){const r=t.map(s=>`"${s}"`).join(", "),n=/(\btags\s*=\s*)\[[^\]]*\]/i;return n.test(e)?e.replace(n,`$1[${r}]`):e}function bS({binding:e,t,onChange:r}){const[n,s]=l.useState([]),[T,i]=l.useState(!1);l.useEffect(()=>{let A=!1;return i(!1),Q.openBlockStudio(e.path).then(R=>{A||s(R.validation.parameters??[])}).catch(()=>{A||(s([]),i(!0))}),()=>{A=!0}},[e.path]);const o=e.parameterValues??{},S=new Set(n.map(A=>A.name)),a=Object.keys(o).filter(A=>!S.has(A));return n.length===0&&a.length===0&&!T?null:E.jsxs("div",{style:{padding:"8px 10px",borderBottom:`1px solid ${t.cellBorder}`,background:t.appBg},children:[E.jsxs("div",{style:{marginBottom:6,fontSize:10.5,fontWeight:750,color:t.textSecondary},children:["Block inputs ",E.jsx("span",{style:{fontWeight:400,color:t.textMuted},children:"· defaults come from the block; notebook overrides stay here"})]}),T&&E.jsx("div",{style:{marginBottom:6,fontSize:10.5,color:t.error},children:"Could not load this block's parameter contract. The saved overrides were not changed."}),a.length>0&&E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,marginBottom:7,fontSize:10.5,color:t.warning},children:[E.jsxs("span",{children:["Block definition changed. Unknown overrides: ",a.join(", "),"."]}),E.jsx("button",{type:"button",onClick:()=>r(Object.fromEntries(Object.entries(o).filter(([A])=>S.has(A)))),style:Ft(t,t.warning),children:"Remove stale"})]}),E.jsx(bn,{parameters:n,values:o,onChange:(A,R)=>r({...o,[A]:R}),onReset:A=>{const R={...o};delete R[A],r(R)},t})]})}function FS({source:e,values:t,t:r,onChange:n}){const[s,T]=l.useState([]);return l.useEffect(()=>{let i=!1;const o=window.setTimeout(()=>{Q.validateBlockStudio(e).then(S=>{i||T(S.parameters??[])}).catch(()=>{i||T([])})},200);return()=>{i=!0,window.clearTimeout(o)}},[e]),s.length===0?null:E.jsxs("div",{style:{padding:"8px 10px",borderBottom:`1px solid ${r.cellBorder}`,background:r.appBg},children:[E.jsxs("div",{style:{marginBottom:6,fontSize:10.5,fontWeight:750,color:r.textSecondary},children:["Run with ",E.jsx("span",{style:{fontWeight:400,color:r.textMuted},children:"· change values for this notebook without changing DQL defaults"})]}),E.jsx(bn,{parameters:s,values:t,onChange:(i,o)=>n({...t,[i]:o}),onReset:i=>{const o={...t};delete o[i],n(o)},t:r})]})}function HS({binding:e,t,onRevert:r,onCustomize:n,onUnbind:s}){const T=e.state==="forked",i=T?t.warning:t.success,o=T?"FORKED":"BOUND",S=T?"Local edits have diverged from the block file — Revert to discard, or Save as Block to promote as a new version.":"This cell mirrors the block file. Edit to fork locally.";return E.jsxs("div",{title:S,style:{display:"flex",alignItems:"center",gap:8,padding:"4px 10px",borderBottom:`1px solid ${t.cellBorder}`,background:`${i}10`,fontFamily:t.fontMono,fontSize:11},children:[E.jsx("span",{style:{fontSize:9,fontWeight:700,letterSpacing:"0.08em",color:i,background:`${i}24`,border:`1px solid ${i}55`,borderRadius:3,padding:"1px 5px"},children:o}),E.jsx("span",{style:{color:t.textSecondary},children:e.path}),e.version&&E.jsxs("span",{style:{color:t.textMuted},children:["· v",e.version]}),!T&&E.jsx("span",{title:"Bound cells track the block file — edits fork locally",style:{color:t.textMuted},children:"🔒"}),E.jsx("div",{style:{flex:1}}),T&&E.jsx("button",{onClick:r,title:"Discard local edits and restore the block file body",style:Ft(t,i),children:"Revert"}),!T&&E.jsx("button",{onClick:n,title:"Load the block source into this notebook and customize a local copy",style:Ft(t,i),children:"Customize copy"}),E.jsx("button",{onClick:s,title:"Detach this cell from the block file",style:Ft(t,t.btnBorder),children:"Unbind"})]})}function Ft(e,t){return{background:"transparent",border:`1px solid ${t}`,borderRadius:4,color:e.textSecondary,fontSize:10,fontFamily:e.font,fontWeight:600,letterSpacing:"0.04em",padding:"1px 7px",cursor:"pointer"}}function vS({content:e,onChange:t,t:r}){const n=GS(e);if(!n)return null;const s={background:r.cellBg,border:`1px solid ${r.btnBorder}`,borderRadius:6,color:r.textPrimary,fontSize:11,fontFamily:r.fontMono,padding:"3px 7px",outline:"none"},T={fontSize:9,fontWeight:700,color:r.textMuted,fontFamily:r.font,letterSpacing:"0.05em",textTransform:"uppercase",marginRight:4,flexShrink:0},i={display:"flex",alignItems:"center",gap:4};return E.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"4px 12px",padding:"5px 10px",borderBottom:`1px solid ${r.cellBorder}`,background:`${r.tableHeaderBg}40`},children:[E.jsxs("div",{style:i,children:[E.jsx("span",{style:T,children:"domain"}),E.jsx("input",{style:{...s,width:80},value:n.domain,placeholder:"e.g. finance",onChange:o=>t(DE(e,"domain",o.target.value))})]}),E.jsxs("div",{style:i,children:[E.jsx("span",{style:T,children:"owner"}),E.jsx("input",{style:{...s,width:90},value:n.owner,placeholder:"e.g. data-team",onChange:o=>t(DE(e,"owner",o.target.value))})]}),E.jsxs("div",{style:i,children:[E.jsx("span",{style:T,children:"tags"}),E.jsx(gs,{style:{...s,width:110},values:n.tags,placeholder:"revenue, kpi",onChange:o=>t(BS(e,o))})]}),E.jsxs("div",{style:{...i,flex:1},children:[E.jsx("span",{style:T,children:"description"}),E.jsx("input",{style:{...s,flex:1,minWidth:120},value:n.description,placeholder:"What this block measures",onChange:o=>t(DE(e,"description",o.target.value))})]})]})}function YS({cellType:e,cellName:t,t:r,onCancel:n}){const[s,T]=l.useState(0);l.useEffect(()=>{const S=Date.now(),a=window.setInterval(()=>T(Date.now()-S),250);return()=>window.clearInterval(a)},[]);const i=s<1e3?`${Math.max(1,Math.round(s))}ms`:`${(s/1e3).toFixed(1)}s`,o=e==="dql"?s<1200?"Preparing DQL block":s<5e3?"Executing generated SQL":"Waiting for warehouse response":s<1200?"Preparing SQL":s<5e3?"Executing query":"Waiting for database response";return E.jsxs("div",{role:"status","aria-live":"polite",style:{display:"grid",gap:10,padding:14,minHeight:92,background:`${r.cellBorderRunning}0f`,borderTop:`1px solid ${r.cellBorder}`},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[E.jsx("span",{"aria-hidden":!0,style:{width:10,height:10,borderRadius:999,background:r.cellBorderRunning,boxShadow:`0 0 0 4px ${r.cellBorderRunning}22`,animation:"pulse 1.2s ease-in-out infinite",flexShrink:0}}),E.jsxs("div",{style:{minWidth:0,flex:1},children:[E.jsx("div",{style:{fontSize:13,fontWeight:800,color:r.textPrimary,fontFamily:r.font},children:o}),E.jsxs("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.fontMono,marginTop:3},children:[t||e.toUpperCase()," · ",i]})]}),E.jsx("button",{onClick:n,style:{border:`1px solid ${r.error}`,background:`${r.error}12`,color:r.error,borderRadius:4,padding:"4px 8px",fontSize:11,fontFamily:r.font,fontWeight:700,cursor:"pointer"},children:"Cancel"})]}),E.jsx("div",{style:{fontSize:11,color:r.textMuted,fontFamily:r.font,lineHeight:1.45},children:"The result table will appear here when execution finishes. Errors will replace this status card with details."})]})}const VS=new Set(["sql","dql","param","writeback","python","chat"]);function WS({state:e,t,onClick:r}){const n=XS(e,t);return E.jsxs("button",{type:"button",title:e.title,"aria-label":`${e.label}. ${e.title}`,onClick:s=>{s.stopPropagation(),r()},style:{height:22,maxWidth:170,minWidth:0,border:`1px solid ${n}55`,background:`${n}12`,color:n,borderRadius:4,padding:"0 7px",display:"inline-flex",alignItems:"center",gap:5,fontSize:10,fontFamily:t.font,fontWeight:800,cursor:"pointer",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",flexShrink:1},children:[E.jsx(qe,{size:11,strokeWidth:2.2,style:{flexShrink:0},"aria-hidden":"true"}),E.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis"},children:e.label})]})}function wS(e){return e.kind==="changed"||e.kind==="missing"||e.kind==="blocked"}function XS(e,t){switch(e.kind){case"changed":case"review_sql":case"review_context":case"complete":return t.warning;case"missing":case"blocked":return t.error;case"reuse":case"cert_ready":case"done":return t.success;case"draft_ready":case"run_preview":return t.accent;case"new":case"unknown":default:return t.textMuted}}function Pt(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function kS({cell:e,t}){var A,R,N,O,c;const r=e.execution;if(!r)return null;const n=r.status==="success"?t.success:r.status==="cancelled"||r.status==="blocked"?t.warning:t.error,s=((A=e.dqlArtifact)==null?void 0:A.source)??(e.type==="dql"?e.content:void 0),T=((R=r.executionTarget)==null?void 0:R.target)==="local"?"Local DuckDB":(N=r.executionTarget)!=null&&N.connectionName?`Connection: ${r.executionTarget.connectionName}`:"No target recorded",i=((O=r.semanticTrace)==null?void 0:O.steps)??[],o=((c=r.semanticTrace)==null?void 0:c.bindings)??[],S={margin:"5px 0 0",padding:"7px 8px",maxHeight:190,overflow:"auto",whiteSpace:"pre-wrap",overflowWrap:"anywhere",border:`1px solid ${t.cellBorder}`,borderRadius:6,background:t.editorBg,color:t.textSecondary,fontFamily:t.fontMono,fontSize:10.5,lineHeight:1.45},a={color:t.textMuted,fontSize:9.5,fontWeight:800,letterSpacing:".045em",textTransform:"uppercase"};return E.jsxs("details",{style:{borderTop:`1px solid ${t.cellBorder}`,padding:"7px 12px",background:`${t.tableHeaderBg}28`},children:[E.jsxs("summary",{style:{cursor:"pointer",listStyle:"none",display:"flex",alignItems:"center",gap:7,color:t.textSecondary,fontSize:11,fontWeight:750},children:[E.jsx(Gn,{size:12,color:n}),"Trust & Steps",E.jsx("span",{style:{color:n,textTransform:"capitalize"},children:r.status}),E.jsxs("span",{style:{color:t.textMuted,fontWeight:500},children:[r.engine??(e.type==="dql"?"DQL compiler":"warehouse SQL")," · ",r.durationMs," ms"]}),E.jsx("span",{title:r.runId,style:{marginLeft:"auto",maxWidth:190,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:t.textMuted,fontFamily:t.fontMono,fontSize:9.5,fontWeight:500},children:r.runId})]}),E.jsxs("div",{style:{display:"grid",gap:10,paddingTop:9,fontFamily:t.font},children:[E.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(145px, 1fr))",gap:6},children:[["Cell",r.cellId],["Route",r.route],["Target",T],["Started",r.startedAt]].map(([C,I])=>E.jsxs("div",{style:{minWidth:0,border:`1px solid ${t.cellBorder}`,borderRadius:6,padding:"6px 7px",background:t.cellBg},children:[E.jsx("div",{style:a,children:C}),E.jsx("div",{title:I,style:{marginTop:2,color:t.textSecondary,fontFamily:C==="Started"?t.font:t.fontMono,fontSize:10.5,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:I})]},C))}),s&&E.jsxs("div",{children:[E.jsx("div",{style:a,children:"1 · Governed DQL request"}),E.jsx("pre",{style:S,children:s})]}),r.compiledSql&&E.jsxs("div",{children:[E.jsxs("div",{style:a,children:[s?"2":"1"," · Compiled SQL"]}),E.jsx("pre",{style:S,children:r.compiledSql})]}),r.executedSql&&r.executedSql!==r.compiledSql&&E.jsxs("div",{children:[E.jsx("div",{style:a,children:"Executed SQL"}),E.jsx("pre",{style:S,children:r.executedSql})]}),(i.length>0||o.length>0)&&E.jsxs("div",{children:[E.jsx("div",{style:a,children:"Semantic compiler trace"}),i.length>0&&E.jsx("ol",{style:{margin:"6px 0 0",paddingLeft:20,color:t.textSecondary,fontSize:10.5,lineHeight:1.55},children:i.map((C,I)=>E.jsxs("li",{children:[E.jsx("strong",{children:C.label??C.id??`Step ${I+1}`}),C.status?` · ${C.status}`:"",C.detail?` — ${C.detail}`:""]},C.id??`${I}:${C.label??"step"}`))}),o.length>0&&E.jsx("pre",{style:S,children:Pt(o)})]}),(r.targetBinding||r.executionReceipt)&&E.jsxs("div",{children:[E.jsx("div",{style:a,children:"Target binding & execution receipt"}),E.jsx("pre",{style:S,children:Pt({targetBinding:r.targetBinding,executionReceipt:r.executionReceipt})})]}),r.repair&&E.jsxs("div",{style:{border:`1px solid ${t.warning}55`,borderRadius:6,padding:"7px 8px",background:`${t.warning}0d`},children:[E.jsxs("div",{style:{...a,color:t.warning},children:["Background repair · ",r.repair.mode]}),E.jsx("div",{style:{marginTop:4,color:t.textSecondary,fontSize:11,lineHeight:1.45},children:"The original failed run remains below for review. The repair changed only this notebook cell and reran it on the same target."}),E.jsx("pre",{style:S,children:Pt({sourceRunId:r.repair.sourceRunId,originalError:r.repair.originalError,originalSource:r.repair.originalSource,originalCompiledSql:r.repair.originalCompiledSql,originalExecutedSql:r.repair.originalExecutedSql})})]}),r.error&&E.jsxs("div",{style:{border:`1px solid ${t.error}55`,borderRadius:6,padding:"7px 8px",background:`${t.error}0d`},children:[E.jsxs("div",{style:{...a,color:t.error},children:["Failure · ",r.error.code??"EXECUTION_FAILED",r.error.phase?` · ${r.error.phase}`:""]}),E.jsx("div",{style:{marginTop:4,color:t.textPrimary,fontSize:11,lineHeight:1.45},children:r.error.message}),r.error.details!==void 0&&E.jsx("pre",{style:S,children:Pt(r.error.details)})]})]})]})}function jS({cell:e,index:t,onStartResearch:r,researchState:n}){var KE,qE,JE,QE,zE,ZE,er,tr,Er,rr,nr,sr;const s=Fe(Rt(m=>({activeFile:m.activeFile,appMode:m.appMode,schemaTables:m.schemaTables,themeMode:m.themeMode}))),T=Vt(),i=Kt.getState().cells,o=se[s.themeMode],{executeCell:S,executeDependents:a,cancelCell:A}=BE(),[R,N]=l.useState(!1),[O,c]=l.useState(!1),[C,I]=l.useState(e.name??""),[d,L]=l.useState(!0),[f,v]=l.useState("table"),[U,F]=l.useState(null),[h,p]=l.useState(!1),[G,y]=l.useState(!1),[V,k]=l.useState(!1),[Z,g]=l.useState(null),[K,j]=l.useState(!1),[B,ee]=l.useState(!1),[le,Ie]=l.useState(""),[x,u]=l.useState("note"),[W,P]=l.useState([]),[Y,z]=l.useState("default"),[$,q]=l.useState(!1),[te,re]=l.useState(!!e.mixedSourcePlan),[ce,Qe]=l.useState(!1),[ne,Me]=l.useState(null),[de,ve]=l.useState(null),YE=l.useRef(e);YE.current=e,l.useEffect(()=>{if(e.type!=="sql"&&e.type!=="dql")return;let m=!1;return Q.getConnections().then(H=>{m||(P(Object.keys(H.connections??{})),z(H.default||"default"))}).catch(()=>{}),()=>{m=!0}},[e.type]);const ze=l.useMemo(()=>{var m;return K?(m=e.dqlArtifact)!=null&&m.source?{content:e.dqlArtifact.source,suggestedName:e.dqlArtifact.name,derivedFromUpstream:!0}:lT(e,i):null},[K,e,i]),Is=e.type==="sql"||e.type==="dql"||e.type==="chart"||e.type==="pivot"||e.type==="single_value"||e.type==="filter"||e.type==="table",VE=is(e,o),Ye=e.type!=="markdown"&&e.type!=="param",St=l.useRef(null),WE=l.useRef(e.content),[Os,lt]=l.useState(!1),Ns=l.useMemo(()=>s.schemaTables.length>0?Object.fromEntries(s.schemaTables.map(m=>[m.name,m.columns.map(H=>H.name)])):void 0,[s.schemaTables]);l.useEffect(()=>{if(e.status==="success"&&e.result){const m=ME(e.result,e.chartConfig);F(m!=="table"?m:null),v(m!=="table"?"chart":"table")}},[e.status,e.result,e.chartConfig]);const wE=l.useCallback(()=>{Ye&&(ve(null),Me(null),S(e.id))},[e.id,S,Ye]),Ve=l.useCallback(m=>{const H={content:m},X=e.blockBinding;if((X==null?void 0:X.originalContent)!==void 0){const oe=m.trim()!==X.originalContent.trim()?"forked":"bound";oe!==X.state&&(H.blockBinding={...X,state:oe})}T({type:"UPDATE_CELL",id:e.id,updates:H}),lt(m!==WE.current),ve(null),Me(null)},[e.id,e.blockBinding,T]),cs=l.useCallback(()=>{var H;const m=WE.current;T({type:"UPDATE_CELL",id:e.id,updates:{content:m}}),(H=St.current)==null||H.resetTo(m),lt(!1)},[e.id,T]),jt=l.useCallback(()=>{if(e.content.trim())try{const m=_S(e.content,{language:"sql",tabWidth:2,keywordCase:"upper",linesBetweenQueries:1});T({type:"UPDATE_CELL",id:e.id,updates:{content:m}})}catch{}},[e.content,e.id,T]),ds=l.useCallback(()=>{jt(),setTimeout(()=>S(e.id),80)},[jt,S,e.id]),Cs=l.useCallback(async()=>{var _e,Te;if(!un(e)||!e.error||ce)return;const m=e.content,H=e.execution,X=e.error,ae=new Date().toISOString(),oe=Date.now(),Ee=`cellrepair_${e.id}_${oe}`;Qe(!0),Me(null),ve(null);try{const J=await Q.repairNotebookCellExecution(e,e.error,{notebookPath:(_e=s.activeFile)==null?void 0:_e.path,cellId:e.id,cellName:e.name,source:e.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",runId:Ee}),fe=YE.current;if(fe.content!==m||fe.error!==X||((Te=fe.execution)==null?void 0:Te.runId)!==(H==null?void 0:H.runId))throw new Error("The cell changed while repair was running. Its stale repair was not applied.");const pe=new Date().toISOString(),or=Date.now()-oe,$t={...J.result,executionTime:J.result.executionTime??or,rowCount:J.result.rowCount??J.result.rows.length},Tr=e.blockBinding?{...e.blockBinding,state:"forked"}:void 0,ir=e.type==="dql"&&e.dqlArtifact?{...e.dqlArtifact,source:J.source,sql:J.repairedSql,compiledSql:J.compiledSql??J.repairedSql,trustState:"review_required",reviewState:"review_required"}:e.dqlArtifact;T({type:"UPDATE_CELL",id:e.id,updates:{content:J.source,status:"success",result:$t,error:void 0,executionCount:(e.executionCount??0)+1,executionTarget:J.executionTarget??e.executionTarget,stale:!1,fromSnapshot:!1,...Tr?{blockBinding:Tr}:{},...ir?{dqlArtifact:ir}:{},execution:{version:1,runId:Ee,cellId:e.id,route:e.type==="dql"?"notebook_dql_cell":"notebook_sql_cell",status:"success",startedAt:ae,completedAt:pe,durationMs:or,executionTarget:J.executionTarget??e.executionTarget,compiledSql:J.compiledSql??J.repairedSql,executedSql:J.executedSql??J.repairedSql,executionReceipt:J.executionReceipt,repair:{mode:J.repairMode,sourceRunId:H==null?void 0:H.runId,originalSource:m,originalCompiledSql:H==null?void 0:H.compiledSql,originalExecutedSql:H==null?void 0:H.executedSql,originalError:(H==null?void 0:H.error)??{message:X,phase:"execution"}}}}}),T({type:"APPEND_QUERY_LOG",entry:{id:Us(),cellName:e.name??e.id,rows:$t.rowCount,time:$t.executionTime,ts:new Date}}),lt(!0),ve(J.source===m?"Retried successfully.":`Fixed and reran. Review the changed ${e.type==="dql"?"DQL":"SQL"} before saving.`)}catch(J){Me(xS(J))}finally{Qe(!1)}},[e,T,ce,(KE=s.activeFile)==null?void 0:KE.path]),Ce=l.useCallback(m=>T({type:"UPDATE_CELL",id:e.id,updates:m}),[T,e.id]),It=l.useCallback(m=>{var Te;let H=(Te=e.name)==null?void 0:Te.trim();if(!H){const J=`result_${t+1}`;H=J;let fe=2;for(;Kt.getState().cells.some(pe=>pe.id!==e.id&&pe.name===H);)H=`${J}_${fe}`,fe+=1;T({type:"UPDATE_CELL",id:e.id,updates:{name:H}})}const X=Se(m);X.upstream=H,X.dependencies=[{cellId:e.id,output:H}];const oe=`${H}_${m==="single_value"?"kpi":m}`;let Ee=oe,_e=2;for(;Kt.getState().cells.some(J=>J.name===Ee);)Ee=`${oe}_${_e}`,_e+=1;X.name=Ee,m==="filter"&&X.filterConfig&&(X.filterConfig={...X.filterConfig,upstream:H}),m==="pivot"&&X.pivotConfig&&(X.pivotConfig={...X.pivotConfig,upstream:H}),m==="single_value"&&X.singleValueConfig&&(X.singleValueConfig={...X.singleValueConfig,upstream:H}),T({type:"ADD_CELL",cell:X,afterId:e.id})},[e.id,e.name,T,t]),Ls=l.useCallback(async()=>{var ae,oe,Ee;if(!e.result)return;k(!0),g(null);const m=await Q.recommendVisualization({resultSchema:{columns:e.result.columns},rowSample:e.result.rows.slice(0,5),prompt:[e.name,e.content].filter(Boolean).join(" ").slice(0,600)});if(k(!1),!m.ok){g(m.error);return}const H=KS(m.display.defaultVisualization),X=m.display.fieldHints??{};F(H!=="table"?H:null),v(H!=="table"?"chart":"table"),Ce({chartConfig:{...e.chartConfig,chart:H,x:X.x??X.label??((ae=e.chartConfig)==null?void 0:ae.x),y:X.y??X.value??((oe=e.chartConfig)==null?void 0:oe.y),color:X.color??((Ee=e.chartConfig)==null?void 0:Ee.color)}}),g(`${m.display.component} · ${m.display.defaultVisualization}`)},[e.chartConfig,e.content,e.name,e.result,Ce]),_s=l.useCallback(async()=>{var X,ae,oe,Ee,_e;if(!e.content.trim()||$)return;const m=((X=e.result)==null?void 0:X.rowCount)??((ae=e.result)==null?void 0:ae.rows.length)??0;if(window.confirm(`Copy a bounded warehouse result into the local analysis workspace?
@@ -168,14 +168,14 @@ ${JSON.stringify(i,void 0,2)}`)}}}var D;(function(e){e[e.SPACE=0]="SPACE",e[e.NO
168
168
  Current result: ${m.toLocaleString()} rows
169
169
  Limits: 100,000 rows, 250 MB, 120 seconds
170
170
 
171
- The staged snapshot is ignored by Git, records lineage, and expires after 7 days.`)){q(!0);try{const J=(await Q.stageDataset({sql:e.content,connectionName:((oe=e.executionTarget)==null?void 0:oe.connectionName)??Y,name:`${e.name??"warehouse_result"} snapshot`,confirmed:!0,blockPath:((Ee=e.blockBinding)==null?void 0:Ee.path)??((_e=e.dqlArtifact)==null?void 0:_e.sourcePath)})).dataset,fe=qS(J);T({type:"ADD_CELL",cell:fe,afterId:e.id}),T({type:"SET_SCHEMA",tables:[...s.schemaTables.filter(pe=>pe.name!==J.alias),{name:J.alias,path:J.sourcePath,source:"file",objectType:"staged_dataset",columns:J.profile.columns.map(pe=>({name:pe.name,type:pe.type}))}]})}catch(Te){window.alert(Te instanceof Error?Te.message:String(Te))}finally{q(!1)}}},[e,Y,T,$,s.schemaTables]),us=l.useCallback(async m=>{var H,X,ae;if(!(!e.content.trim()||$)){q(!0);try{const Ee=(await Q.stageDataset({sql:e.content,connectionName:((H=e.executionTarget)==null?void 0:H.connectionName)??Y,name:`${e.name??"warehouse_result"} snapshot`,confirmed:!0,blockPath:((X=e.blockBinding)==null?void 0:X.path)??((ae=e.dqlArtifact)==null?void 0:ae.sourcePath)})).dataset,_e=xs({staged:{...Ee,columns:Ee.profile.columns.map(Te=>Te.name)},local:{...m.dataset,columns:m.dataset.profile.columns.map(Te=>Te.name)},warehouseKey:m.warehouseKey,localKey:m.localKey,joinType:m.joinType,sourceCell:e});T({type:"ADD_CELL",cell:_e,afterId:e.id}),T({type:"SET_SCHEMA",tables:[...s.schemaTables.filter(Te=>Te.name!==Ee.alias),{name:Ee.alias,path:Ee.sourcePath,source:"file",objectType:"staged_dataset",datasetId:Ee.id,fileFingerprint:Ee.fileFingerprint,storageMode:Ee.storageMode,refreshedAt:Ee.refreshedAt,trustState:Ee.trustState,columns:Ee.profile.columns.map(Te=>({name:Te.name,type:Te.type}))}]}),re(!1)}catch(oe){window.alert(oe instanceof Error?oe.message:String(oe))}finally{q(!1)}}},[e,Y,T,$,s.schemaTables]),XE=()=>{T({type:"DELETE_CELL",id:e.id})},kE=()=>{T({type:"MOVE_CELL",id:e.id,direction:"up"})},jE=()=>{T({type:"MOVE_CELL",id:e.id,direction:"down"})},me={cell:e,t:o,onMoveUp:kE,onMoveDown:jE,onDelete:XE};if(s.appMode!=="studio"&&VS.has(e.type))return E.jsxs("div",{style:{marginTop:8,marginBottom:8,padding:"6px 10px",borderRadius:6,border:`1px dashed ${o.cellBorder}`,background:o.cellBg,color:o.textMuted,fontSize:11,fontFamily:o.font,display:"flex",alignItems:"center",gap:8},children:[E.jsx("span",{style:{opacity:.7},children:"◎"}),E.jsxs("span",{children:[e.type.toUpperCase()," cell hidden in App view",e.name?` · ${e.name}`:""]})]});if(e.type==="param")return E.jsx(he,{...me,onRun:()=>a(e.id),children:E.jsx(xo,{cell:e,themeMode:s.themeMode,onApplyParam:a})});if(e.type==="pivot")return E.jsx(he,{...me,children:E.jsx(Qo,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});if(e.type==="single_value")return E.jsx(he,{...me,children:E.jsx(Ko,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});if(e.type==="filter")return E.jsx(he,{...me,children:E.jsx(Wo,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});if(e.type==="chart")return E.jsx(he,{...me,children:E.jsx(Ho,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});if(e.type==="table")return E.jsx(he,{...me,children:E.jsx(Zo,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});if(e.type==="chat")return E.jsx(he,{...me,children:E.jsx(tT,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});const Ze=yS[e.type];if(Ze)return E.jsx(he,{...me,children:E.jsx(go,{cell:e,themeMode:s.themeMode,title:Ze.title,subtitle:Ze.subtitle,color:Ze.color,badge:Ze.badge})});const $E=()=>{c(!1),T({type:"UPDATE_CELL",id:e.id,updates:{name:C.trim()||void 0}})},ps=(e.result||e.error||e.status==="running")&&e.type!=="markdown";return e.result&&ME(e.result,e.chartConfig),E.jsxs("div",{onMouseEnter:()=>N(!0),onMouseLeave:()=>N(!1),style:{display:"flex",gap:0,marginBottom:2},children:[K&&ze&&E.jsx(Js,{cell:e,initialContent:ze.derivedFromUpstream?ze.content:void 0,initialName:ze.suggestedName,initialDescription:ze.suggestedDescription,onClose:()=>j(!1),onSaved:({path:m,name:H})=>{T({type:"FILE_ADDED",file:{name:H,path:m,type:"block",folder:"blocks"}})}}),E.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${R||e.status!=="idle"?VE:o.cellBorder}`,background:o.cellBg,boxShadow:e.status!=="idle"?`0 0 0 3px ${VE}14, 0 1px 2px rgba(0,0,0,0.04)`:"0 1px 2px rgba(0,0,0,0.02)",overflow:"hidden",transition:"border-color 0.2s"},children:[E.jsxs("div",{style:{minHeight:38,display:"flex",alignItems:"center",padding:"7px 12px",gap:8,rowGap:6,background:"transparent",flexWrap:"wrap"},children:[E.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:8,minWidth:0,flex:"1 1 260px"},children:[E.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:Ts[e.type]??o.accent,flexShrink:0}}),E.jsx("span",{title:e.type==="dql"?"DQL cell — write a governed block (type, owner, description, tests) or use @metric()/@dim() refs":e.type==="sql"?"SQL cell — write raw SQL, reference other cells with {{name}}":void 0,style:{fontSize:11,fontWeight:700,letterSpacing:0,color:o.textSecondary,flexShrink:0,whiteSpace:"nowrap"},children:os[e.type]}),O?E.jsx("input",{autoFocus:!0,value:C,onChange:m=>I(m.target.value),onBlur:$E,onKeyDown:m=>{m.key==="Enter"&&$E(),m.key==="Escape"&&c(!1)},style:{background:o.appBg,border:`1px solid ${o.cellBorderActive}`,borderRadius:5,color:o.textSecondary,fontSize:12,fontFamily:o.fontMono,padding:"2px 6px",outline:"none",width:170,minWidth:100}}):e.name?E.jsx("span",{onClick:()=>{I(e.name??""),c(!0)},title:"Click to rename",style:{color:o.textSecondary,fontSize:12,fontFamily:o.fontMono,cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:260,minWidth:0},children:e.name}):null,E.jsx(as,{cell:e,t:o}),(e.type==="sql"||e.type==="dql")&&E.jsx(Go,{cells:i,index:t,content:e.content,themeMode:s.themeMode,onInsertHandle:m=>{const H=`{{${m}}}`,X=e.content??"";if(X.includes(H))return;const ae=X.trim().length===0?`SELECT * FROM ${H}`:`${X.replace(/\s*$/,"")} ${H}`;Ve(ae)}}),n&&wS(n)&&r&&E.jsx(WS,{state:n,t:o,onClick:()=>r(e.id)}),e.stale&&E.jsx("span",{title:"An upstream cell changed. Run this cell again.",style:{color:o.warning,fontSize:10,fontWeight:700},children:"stale"})]}),E.jsxs("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"flex-end",gap:5,flex:"0 0 auto",marginLeft:"auto"},children:[R&&(e.type==="sql"||e.type==="dql")&&E.jsx(rT,{themeMode:s.themeMode,cellType:e.type,onInsert:m=>Ve(m)}),R&&(e.type==="sql"||e.type==="dql")&&E.jsx("button",{type:"button",title:"Format SQL (clean up whitespace and keywords)",onClick:jt,style:tt(o),children:"Format"}),Os&&(e.type==="sql"||e.type==="dql")&&E.jsx("button",{type:"button",title:"Reset to last saved version (discard changes)",onClick:cs,style:tt(o,"danger"),children:"Reset"}),R&&r&&(e.type==="sql"||e.type==="dql")&&E.jsx("button",{type:"button",title:"Ask AI to explain, fix, find reuse, or prepare DQL from this cell",onClick:()=>r(e.id),style:tt(o,"accent"),children:"Ask AI"}),R&&Is&&E.jsx("button",{type:"button",title:"Save this cell as a reusable block",onClick:()=>j(!0),style:tt(o),children:"Save Block"}),(R||B||(((qE=e.annotations)==null?void 0:qE.length)??0)>0)&&E.jsxs("button",{type:"button",title:"Add or review a cell note",onClick:()=>ee(m=>!m),style:tt(o,B?"accent":void 0),children:[E.jsx(Eo,{size:11,"aria-hidden":"true"}),"Note",(JE=e.annotations)!=null&&JE.length?` ${e.annotations.length}`:""]}),R&&!e.name&&!O&&E.jsx(ue,{title:"Name this cell",onClick:()=>{I(""),c(!0)},t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M11.013 1.427a1.75 1.75 0 0 1 2.474 0l1.086 1.086a1.75 1.75 0 0 1 0 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 0 1-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61Zm.176 4.823L9.75 4.81l-6.286 6.287a.253.253 0 0 0-.064.108l-.558 1.953 1.953-.558a.253.253 0 0 0 .108-.064Zm1.238-3.763a.25.25 0 0 0-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 0 0 0-.354Z"})})}),R&&Ye&&e.status==="running"?E.jsx(ue,{title:"Cancel execution",onClick:()=>A(e.id),t:o,danger:!0,children:E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1"})})}):R&&Ye?E.jsx(ue,{title:"Run cell (Shift+Enter)",onClick:wE,t:o,run:!0,children:E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}):null,R&&E.jsxs(E.Fragment,{children:[E.jsx(ue,{title:"Move up",onClick:kE,t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M3.47 7.78a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1-1.06 1.06L8.75 4.81v7.44a.75.75 0 0 1-1.5 0V4.81L4.53 7.78a.75.75 0 0 1-1.06 0Z"})})}),E.jsx(ue,{title:"Move down",onClick:jE,t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M12.53 8.22a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L2.97 9.28a.75.75 0 0 1 1.06-1.06l2.72 2.97V3.75a.75.75 0 0 1 1.5 0v7.44l2.72-2.97a.75.75 0 0 1 1.06 0Z"})})}),E.jsx(ue,{title:"Delete cell",onClick:XE,t:o,danger:!0,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M11 1.75V3h2.25a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1 0-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75ZM4.496 6.675l.66 6.6a.25.25 0 0 0 .249.225h5.19a.25.25 0 0 0 .249-.225l.66-6.6a.75.75 0 0 1 1.492.149l-.66 6.6A1.748 1.748 0 0 1 10.595 15h-5.19a1.75 1.75 0 0 1-1.741-1.575l-.66-6.6a.75.75 0 1 1 1.492-.15ZM6.5 1.75V3h3V1.75a.25.25 0 0 0-.25-.25h-2.5a.25.25 0 0 0-.25.25Z"})})})]})]})]}),(e.type==="sql"||e.type==="dql")&&E.jsx(JS,{cell:e,connectionNames:W,defaultConnection:Y,t:o,onChange:m=>Ce({executionTarget:m})}),e.type==="dql"&&E.jsx(vS,{content:e.content,onChange:Ve,t:o}),e.blockBinding&&E.jsx(HS,{binding:e.blockBinding,t:o,onRevert:async()=>{var H;const m=e.blockBinding;if(m)try{const X=await Q.openBlockStudio(m.path),ae=`@block(${JSON.stringify(X.metadata.name)})`;T({type:"UPDATE_CELL",id:e.id,updates:{content:ae,blockBinding:{...m,state:"bound",originalContent:ae}}}),(H=St.current)==null||H.resetTo(ae)}catch(X){console.error("Failed to revert bound cell",X)}},onCustomize:async()=>{var H;const m=e.blockBinding;if(m)try{const X=await Q.openBlockStudio(m.path);T({type:"UPDATE_CELL",id:e.id,updates:{content:X.source,dqlParameterValues:{...m.parameterValues??{}},blockBinding:{...m,state:"forked"}}}),(H=St.current)==null||H.resetTo(X.source),lt(!0)}catch(X){console.error("Failed to customize bound cell",X)}},onUnbind:()=>{T({type:"UPDATE_CELL",id:e.id,updates:{blockBinding:void 0}})}}),e.type==="dql"&&(!e.blockBinding||e.blockBinding.state==="forked")&&E.jsxs(E.Fragment,{children:[E.jsx(mS,{source:e.content,onSourceChange:Ve,t:o}),E.jsx(FS,{source:e.content,values:e.dqlParameterValues??{},t:o,onChange:m=>T({type:"UPDATE_CELL",id:e.id,updates:{dqlParameterValues:m}})})]}),((QE=e.blockBinding)==null?void 0:QE.state)==="bound"&&E.jsx(bS,{binding:e.blockBinding,t:o,onChange:m=>T({type:"UPDATE_CELL",id:e.id,updates:{blockBinding:{...e.blockBinding,parameterValues:m}}})}),e.type==="markdown"?E.jsx(js,{value:e.content,onChange:Ve,themeMode:s.themeMode}):E.jsx(ks,{value:e.content,onChange:Ve,onRun:wE,themeMode:s.themeMode,schema:Ns,errorMessage:e.status==="error"?e.error:void 0,editorRef:St}),e.dqlArtifact&&(e.type==="sql"||e.type==="dql")&&E.jsxs("details",{style:{borderTop:`1px solid ${o.cellBorder}`,padding:"6px 12px",background:`${o.tableHeaderBg}40`},children:[E.jsxs("summary",{style:{cursor:"pointer",listStyle:"none",display:"flex",alignItems:"center",gap:6,fontSize:11,fontWeight:700,color:o.textSecondary},children:[E.jsx(Gn,{size:12,color:o.accent}),"Governed DQL",e.dqlArtifact.sourcePath?E.jsx("span",{style:{fontWeight:400,color:o.textMuted,fontFamily:o.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.dqlArtifact.sourcePath}):E.jsx("button",{type:"button",title:"Save this governed DQL as a reusable block",onClick:m=>{m.preventDefault(),m.stopPropagation(),j(!0)},style:{marginLeft:"auto",border:"none",background:"transparent",cursor:"pointer",color:o.accent,fontFamily:o.font,fontSize:10.5,fontWeight:700,padding:"1px 4px"},children:"Save as DQL block"})]}),E.jsx("pre",{style:{margin:"6px 0 0",fontFamily:o.fontMono,fontSize:11,whiteSpace:"pre-wrap",color:o.textSecondary,maxHeight:200,overflow:"auto"},children:e.dqlArtifact.source})]}),(e.type==="sql"||e.type==="dql")&&(e.correctionProvenance&&!((zE=e.dqlArtifact)!=null&&zE.sourcePath||((ZE=e.dqlArtifact)==null?void 0:ZE.persistence)==="saved"||((er=e.dqlArtifact)==null?void 0:er.trustState)==="certified"||((tr=e.dqlArtifact)==null?void 0:tr.reviewState)==="certified")?Ke(e).reason==="ready"?E.jsx(ZS,{cell:e,t:o}):E.jsxs("div",{"data-teach-state":Ke(e).reason,style:{borderTop:`1px solid ${o.cellBorder}`,padding:"5px 12px",background:`${o.accent}0A`,color:o.textMuted,font:`500 10.5px ${o.font}`},children:[E.jsx("strong",{style:{color:o.textSecondary},children:"AI draft."})," ",Ke(e).reason==="missing_generated_sql"?E.jsx(E.Fragment,{children:"Original SQL evidence is missing. Reopen this draft from Ask or Notebook AI before teaching it."}):Ke(e).reason==="run_required"||Ke(e).reason==="execution_mismatch"?E.jsxs(E.Fragment,{children:["Draft changed. Run this exact cell successfully to unlock ",E.jsx("strong",{style:{color:o.accent},children:"Teach DQL"}),"."]}):E.jsxs(E.Fragment,{children:["Edit this cell and run it successfully; then ",E.jsx("strong",{style:{color:o.accent},children:"Teach DQL"})," appears below the editor. Teaching creates a review candidate and never certifies automatically."]})]}):e.dqlArtifact&&(e.dqlArtifact.sourcePath||e.dqlArtifact.persistence==="saved"||e.dqlArtifact.trustState==="certified"||e.dqlArtifact.reviewState==="certified")?E.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`,padding:"5px 12px",background:`${o.warning}0A`,color:o.textMuted,font:`500 10.5px ${o.font}`},children:[E.jsx("strong",{style:{color:o.textSecondary},children:"Saved governed DQL."})," ","Notebook edits are a draft for block review and recertification; they do not create Teach DQL learning or overwrite the source automatically."]}):null),E.jsx(kS,{cell:e,t:o}),B&&E.jsx(QS,{cell:e,value:le,kind:x,onValueChange:Ie,onKindChange:u,onAdd:()=>{const m=le.trim();m&&(Ce({annotations:[...e.annotations??[],{id:`note_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,body:m,kind:x,createdAt:new Date().toISOString()}]}),Ie(""))},onRemove:m=>Ce({annotations:(e.annotations??[]).filter(H=>H.id!==m)}),t:o}),ps&&E.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[E.jsxs("div",{style:{height:28,display:"flex",alignItems:"center",padding:"0 12px",gap:10,borderBottom:e.result&&d?`1px solid ${o.cellBorder}`:"none",background:`${o.tableHeaderBg}60`},children:[e.result&&E.jsxs("span",{style:{fontSize:11,fontFamily:o.font,color:o.textMuted},children:[(()=>{const m=e.result.rowCount??e.result.rows.length;return`${m.toLocaleString()} ${m===1?"row":"rows"}`})(),e.result.executionTime!==void 0&&E.jsxs(E.Fragment,{children:[" · ",e.result.executionTime<1e3?`${Number(e.result.executionTime.toFixed(1))}ms`:`${(e.result.executionTime/1e3).toFixed(2)}s`]})]}),e.fromSnapshot&&e.result&&E.jsx("span",{title:"Result loaded from the last saved run; re-run to refresh.",style:{fontSize:10,fontFamily:o.font,color:o.textMuted,border:`1px solid ${o.btnBorder}`,borderRadius:3,padding:"0 6px",lineHeight:"16px"},children:"cached"}),e.error&&E.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.error},children:"Error"}),e.result&&e.type==="sql"&&((Er=e.executionTarget)==null?void 0:Er.target)!=="local"&&E.jsxs(E.Fragment,{children:[E.jsx("button",{type:"button",disabled:$,onClick:()=>re(m=>!m),title:"Combine this warehouse result with an imported local dataset",style:{border:`1px solid ${te?o.accent:o.btnBorder}`,background:te?`${o.accent}18`:o.btnBg,color:te?o.accent:o.textSecondary,borderRadius:4,padding:"2px 7px",font:`800 10px ${o.font}`,cursor:$?"wait":"pointer"},children:e.mixedSourcePlan?"Finish CSV join":"Combine with local data"}),E.jsx("button",{type:"button",disabled:$,onClick:()=>void _s(),title:"Copy this bounded warehouse result into the local analysis workspace",style:{border:`1px solid ${o.btnBorder}`,background:o.btnBg,color:o.textSecondary,borderRadius:4,padding:"2px 7px",font:`700 10px ${o.font}`,cursor:$?"wait":"pointer"},children:$?"Staging…":"Stage only"})]}),e.result&&E.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:3},"aria-label":"Explore this result",children:[E.jsx("span",{style:{font:`700 9px ${o.font}`,color:o.textMuted,textTransform:"uppercase",letterSpacing:".05em"},children:"Explore"}),E.jsx(Mt,{label:"Filter",t:o,onClick:()=>It("filter")}),E.jsx(Mt,{label:"Pivot",t:o,onClick:()=>It("pivot")}),E.jsx(Mt,{label:"Chart",t:o,onClick:()=>It("chart")}),E.jsx(Mt,{label:"KPI",t:o,onClick:()=>It("single_value")})]}),E.jsx("div",{style:{flex:1}}),e.result&&d&&E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3,position:"relative"},children:[E.jsx("button",{onClick:()=>{v("table"),p(!1)},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${f==="table"?o.accent:o.btnBorder}`,background:f==="table"?`${o.accent}20`:"transparent",color:f==="table"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s"},children:"Table"}),E.jsx("button",{onClick:()=>{v("profile"),p(!1)},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${f==="profile"?o.accent:o.btnBorder}`,background:f==="profile"?`${o.accent}20`:"transparent",color:f==="profile"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s"},children:"Profile"}),E.jsxs("div",{style:{position:"relative"},children:[E.jsxs("button",{onClick:()=>{f==="chart"&&h?p(!1):(v("chart"),p(m=>!m))},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${f==="chart"?o.accent:o.btnBorder}`,background:f==="chart"?`${o.accent}20`:"transparent",color:f==="chart"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s",display:"flex",alignItems:"center",gap:3},children:[U?((rr=wt.find(m=>m.value===U))==null?void 0:rr.label)??"Chart":"Chart",E.jsx("svg",{width:"6",height:"6",viewBox:"0 0 8 8",fill:"currentColor",children:E.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),h&&E.jsx(el,{selected:U,onSelect:m=>{F(m),v("chart"),p(!1)},onClose:()=>p(!1),t:o})]}),E.jsx("button",{onClick:()=>void Ls(),disabled:V,title:"Recommend chart from result fields",style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${V?o.btnBorder:o.accent}`,background:V?"transparent":`${o.accent}14`,color:V?o.textMuted:o.accent,cursor:V?"wait":"pointer",transition:"all 0.15s"},children:V?"...":"Suggest"}),Z&&E.jsx("span",{title:Z,style:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:10,color:o.textMuted,fontFamily:o.font},children:Z}),f==="chart"&&E.jsx("button",{onClick:()=>y(m=>!m),title:"Chart configuration",style:{padding:"1px 5px",fontSize:11,borderRadius:3,cursor:"pointer",border:`1px solid ${G?o.accent:o.btnBorder}`,background:G?`${o.accent}20`:"transparent",color:G?o.accent:o.textMuted,transition:"all 0.15s",display:"flex",alignItems:"center"},children:E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.103-.303c.644-.176 1.392.021 1.82.63.27.386.506.798.704 1.23.315.698.043 1.44-.476 1.89l-.815.806a.338.338 0 0 0-.079.262c.02.267.02.538 0 .805a.338.338 0 0 0 .079.262l.815.806c.52.45.79 1.192.476 1.89a7.22 7.22 0 0 1-.704 1.23c-.428.609-1.176.806-1.82.63l-1.103-.303c-.066-.019-.176-.011-.299.071a5.09 5.09 0 0 1-.668.386c-.133.066-.194.158-.212.224l-.288 1.107c-.169.645-.715 1.196-1.458 1.26a8.006 8.006 0 0 1-1.402 0c-.743-.064-1.29-.614-1.458-1.26l-.289-1.106c-.018-.066-.079-.158-.212-.224a5.09 5.09 0 0 1-.668-.387c-.123-.082-.233-.09-.299-.071l-1.103.303c-.644.176-1.392-.021-1.82-.63a7.12 7.12 0 0 1-.704-1.23c-.315-.698-.043-1.44.476-1.89l.815-.806a.338.338 0 0 0 .079-.262 6.08 6.08 0 0 1 0-.805.338.338 0 0 0-.079-.262l-.815-.806c-.52-.45-.79-1.192-.476-1.89a7.22 7.22 0 0 1 .704-1.23c.428-.609 1.176-.806 1.82-.63l1.103.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386.133-.066.194-.158.212-.224L6.54 1.29C6.71.645 7.256.095 7.999.031 8.236.01 8.474 0 8.713 0H8ZM8 5a3 3 0 1 0 0 6 3 3 0 0 0 0-6Z"})})})]}),E.jsxs("button",{onClick:()=>L(m=>!m),style:{background:"transparent",border:"none",cursor:"pointer",color:o.textMuted,fontSize:11,fontFamily:o.font,padding:"2px 4px",display:"flex",alignItems:"center",gap:4},children:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:d?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:E.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),d?"Hide":"Show"]})]}),te&&e.result&&E.jsx(pS,{warehouseColumns:e.result.columns,warehouseRows:e.result.rows,warehouseRowCount:e.result.rowCount??e.result.rows.length,busy:$,t:o,onCancel:()=>re(!1),onCombine:m=>void us(m),suggestedPlan:e.mixedSourcePlan}),d&&E.jsxs(E.Fragment,{children:[de&&!e.error&&E.jsx("div",{role:"status",style:{padding:"8px 12px",borderLeft:`3px solid ${o.success}`,background:`${o.success}10`,color:o.textSecondary,font:`500 11px ${o.font}`},children:de}),e.status==="running"&&Ye&&E.jsx(YS,{cellType:e.type,cellName:e.name,t:o,onCancel:()=>A(e.id)}),e.error&&E.jsx(NT,{message:e.error,themeMode:s.themeMode,onFix:e.type==="sql"?ds:void 0,onBackgroundRepair:un(e)?()=>void Cs():void 0,repairing:ce,repairError:ne,editableArtifactLabel:e.type==="dql"?"DQL":"SQL",schemaTables:s.schemaTables}),e.result&&!e.error&&(f==="profile"?E.jsx(zS,{cell:e,t:o}):f==="chart"&&U?E.jsxs(E.Fragment,{children:[bE(U,e.result,s.themeMode,e.chartConfig),G&&E.jsx(tl,{columns:e.result.columns,chartConfig:e.chartConfig,onChange:m=>T({type:"UPDATE_CELL",id:e.id,updates:{chartConfig:{...e.chartConfig,...m}}}),t:o})]}):E.jsx(FE,{result:e.result,themeMode:s.themeMode}))]})]}),Ye&&E.jsx(mT,{cellContent:e.content,cellType:e.type,compiledSql:((nr=e.dqlArtifact)==null?void 0:nr.compiledSql)??((sr=e.dqlArtifact)==null?void 0:sr.sql),cellId:e.id,cellName:e.name,cells:i,themeMode:s.themeMode,t:o,onFocusNode:m=>{T({type:"SET_LINEAGE_FOCUS",nodeId:m}),T({type:"OPEN_LINEAGE_DRAWER",nodeId:m})}})]})]})}const $S=Yt.memo(jS,(e,t)=>e.cell===t.cell&&e.index===t.index&&e.onStartResearch===t.onStartResearch&&JSON.stringify(e.researchState??null)===JSON.stringify(t.researchState??null));function KS(e){const t=e.toLowerCase().replace(/-/g,"_"),r=t==="grouped_bar"?"grouped-bar":t==="stacked_bar"?"stacked-bar":t,n=wt.find(s=>s.value===r);return(n==null?void 0:n.value)??"table"}function qS(e){const t=Se("sql",`SELECT *
171
+ The staged snapshot is ignored by Git, records lineage, and expires after 7 days.`)){q(!0);try{const J=(await Q.stageDataset({sql:e.content,connectionName:((oe=e.executionTarget)==null?void 0:oe.connectionName)??Y,name:`${e.name??"warehouse_result"} snapshot`,confirmed:!0,blockPath:((Ee=e.blockBinding)==null?void 0:Ee.path)??((_e=e.dqlArtifact)==null?void 0:_e.sourcePath)})).dataset,fe=qS(J);T({type:"ADD_CELL",cell:fe,afterId:e.id}),T({type:"SET_SCHEMA",tables:[...s.schemaTables.filter(pe=>pe.name!==J.alias),{name:J.alias,path:J.sourcePath,source:"file",objectType:"staged_dataset",columns:J.profile.columns.map(pe=>({name:pe.name,type:pe.type}))}]})}catch(Te){window.alert(Te instanceof Error?Te.message:String(Te))}finally{q(!1)}}},[e,Y,T,$,s.schemaTables]),us=l.useCallback(async m=>{var H,X,ae;if(!(!e.content.trim()||$)){q(!0);try{const Ee=(await Q.stageDataset({sql:e.content,connectionName:((H=e.executionTarget)==null?void 0:H.connectionName)??Y,name:`${e.name??"warehouse_result"} snapshot`,confirmed:!0,blockPath:((X=e.blockBinding)==null?void 0:X.path)??((ae=e.dqlArtifact)==null?void 0:ae.sourcePath)})).dataset,_e=xs({staged:{...Ee,columns:Ee.profile.columns.map(Te=>Te.name)},local:{...m.dataset,columns:m.dataset.profile.columns.map(Te=>Te.name)},warehouseKey:m.warehouseKey,localKey:m.localKey,joinType:m.joinType,sourceCell:e});T({type:"ADD_CELL",cell:_e,afterId:e.id}),T({type:"SET_SCHEMA",tables:[...s.schemaTables.filter(Te=>Te.name!==Ee.alias),{name:Ee.alias,path:Ee.sourcePath,source:"file",objectType:"staged_dataset",datasetId:Ee.id,fileFingerprint:Ee.fileFingerprint,storageMode:Ee.storageMode,refreshedAt:Ee.refreshedAt,trustState:Ee.trustState,columns:Ee.profile.columns.map(Te=>({name:Te.name,type:Te.type}))}]}),re(!1)}catch(oe){window.alert(oe instanceof Error?oe.message:String(oe))}finally{q(!1)}}},[e,Y,T,$,s.schemaTables]),XE=()=>{T({type:"DELETE_CELL",id:e.id})},kE=()=>{T({type:"MOVE_CELL",id:e.id,direction:"up"})},jE=()=>{T({type:"MOVE_CELL",id:e.id,direction:"down"})},me={cell:e,t:o,onMoveUp:kE,onMoveDown:jE,onDelete:XE};if(s.appMode!=="studio"&&VS.has(e.type))return E.jsxs("div",{style:{marginTop:8,marginBottom:8,padding:"6px 10px",borderRadius:6,border:`1px dashed ${o.cellBorder}`,background:o.cellBg,color:o.textMuted,fontSize:11,fontFamily:o.font,display:"flex",alignItems:"center",gap:8},children:[E.jsx("span",{style:{opacity:.7},children:"◎"}),E.jsxs("span",{children:[e.type.toUpperCase()," cell hidden in App view",e.name?` · ${e.name}`:""]})]});if(e.type==="param")return E.jsx(he,{...me,onRun:()=>a(e.id),children:E.jsx(xo,{cell:e,themeMode:s.themeMode,onApplyParam:a})});if(e.type==="pivot")return E.jsx(he,{...me,children:E.jsx(Qo,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});if(e.type==="single_value")return E.jsx(he,{...me,children:E.jsx(Ko,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});if(e.type==="filter")return E.jsx(he,{...me,children:E.jsx(Wo,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});if(e.type==="chart")return E.jsx(he,{...me,children:E.jsx(Ho,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});if(e.type==="table")return E.jsx(he,{...me,children:E.jsx(Zo,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});if(e.type==="chat")return E.jsx(he,{...me,children:E.jsx(tT,{cell:e,cells:i,index:t,themeMode:s.themeMode,onUpdate:Ce})});const Ze=yS[e.type];if(Ze)return E.jsx(he,{...me,children:E.jsx(go,{cell:e,themeMode:s.themeMode,title:Ze.title,subtitle:Ze.subtitle,color:Ze.color,badge:Ze.badge})});const $E=()=>{c(!1),T({type:"UPDATE_CELL",id:e.id,updates:{name:C.trim()||void 0}})},ps=(e.result||e.error||e.status==="running")&&e.type!=="markdown";return e.result&&ME(e.result,e.chartConfig),E.jsxs("div",{onMouseEnter:()=>N(!0),onMouseLeave:()=>N(!1),style:{display:"flex",gap:0,marginBottom:2},children:[K&&ze&&E.jsx(Js,{cell:e,initialContent:ze.derivedFromUpstream?ze.content:void 0,initialName:ze.suggestedName,initialDescription:ze.suggestedDescription,onClose:()=>j(!1),onSaved:({path:m,name:H})=>{T({type:"FILE_ADDED",file:{name:H,path:m,type:"block",folder:"blocks"}})}}),E.jsxs("div",{style:{flex:1,minWidth:0,borderRadius:8,border:`1px solid ${R||e.status!=="idle"?VE:o.cellBorder}`,background:o.cellBg,boxShadow:e.status!=="idle"?`0 0 0 3px ${VE}14, 0 1px 2px rgba(0,0,0,0.04)`:"0 1px 2px rgba(0,0,0,0.02)",overflow:"hidden",transition:"border-color 0.2s"},children:[E.jsxs("div",{style:{minHeight:38,display:"flex",alignItems:"center",padding:"7px 12px",gap:8,rowGap:6,background:"transparent",flexWrap:"wrap"},children:[E.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:8,minWidth:0,flex:"1 1 260px"},children:[E.jsx("span",{"aria-hidden":!0,style:{width:6,height:6,borderRadius:999,background:Ts[e.type]??o.accent,flexShrink:0}}),E.jsx("span",{title:e.type==="dql"?"DQL cell — write a governed block (type, owner, description, tests) or use @metric()/@dim() refs":e.type==="sql"?"SQL cell — write raw SQL, reference other cells with {{name}}":void 0,style:{fontSize:11,fontWeight:700,letterSpacing:0,color:o.textSecondary,flexShrink:0,whiteSpace:"nowrap"},children:os[e.type]}),O?E.jsx("input",{autoFocus:!0,value:C,onChange:m=>I(m.target.value),onBlur:$E,onKeyDown:m=>{m.key==="Enter"&&$E(),m.key==="Escape"&&c(!1)},style:{background:o.appBg,border:`1px solid ${o.cellBorderActive}`,borderRadius:5,color:o.textSecondary,fontSize:12,fontFamily:o.fontMono,padding:"2px 6px",outline:"none",width:170,minWidth:100}}):e.name?E.jsx("span",{onClick:()=>{I(e.name??""),c(!0)},title:"Click to rename",style:{color:o.textSecondary,fontSize:12,fontFamily:o.fontMono,cursor:"text",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:260,minWidth:0},children:e.name}):null,E.jsx(as,{cell:e,t:o}),(e.type==="sql"||e.type==="dql")&&E.jsx(Go,{cells:i,index:t,content:e.content,themeMode:s.themeMode,onInsertHandle:m=>{const H=`{{${m}}}`,X=e.content??"";if(X.includes(H))return;const ae=X.trim().length===0?`SELECT * FROM ${H}`:`${X.replace(/\s*$/,"")} ${H}`;Ve(ae)}}),n&&wS(n)&&r&&E.jsx(WS,{state:n,t:o,onClick:()=>r(e.id)}),e.stale&&E.jsx("span",{title:"An upstream cell changed. Run this cell again.",style:{color:o.warning,fontSize:10,fontWeight:700},children:"stale"})]}),E.jsxs("div",{style:{display:"inline-flex",alignItems:"center",justifyContent:"flex-end",gap:5,flex:"0 0 auto",marginLeft:"auto"},children:[R&&(e.type==="sql"||e.type==="dql")&&E.jsx(rT,{themeMode:s.themeMode,cellType:e.type,onInsert:m=>Ve(m)}),R&&(e.type==="sql"||e.type==="dql")&&E.jsx("button",{type:"button",title:"Format SQL (clean up whitespace and keywords)",onClick:jt,style:tt(o),children:"Format"}),Os&&(e.type==="sql"||e.type==="dql")&&E.jsx("button",{type:"button",title:"Reset to last saved version (discard changes)",onClick:cs,style:tt(o,"danger"),children:"Reset"}),R&&r&&(e.type==="sql"||e.type==="dql")&&E.jsx("button",{type:"button",title:"Ask AI to explain, fix, find reuse, or prepare DQL from this cell",onClick:()=>r(e.id),style:tt(o,"accent"),children:"Ask AI"}),R&&Is&&E.jsx("button",{type:"button",title:"Save this cell as a reusable block",onClick:()=>j(!0),style:tt(o),children:"Save Block"}),(R||B||(((qE=e.annotations)==null?void 0:qE.length)??0)>0)&&E.jsxs("button",{type:"button",title:"Add or review a cell note",onClick:()=>ee(m=>!m),style:tt(o,B?"accent":void 0),children:[E.jsx(to,{size:11,"aria-hidden":"true"}),"Note",(JE=e.annotations)!=null&&JE.length?` ${e.annotations.length}`:""]}),R&&!e.name&&!O&&E.jsx(ue,{title:"Name this cell",onClick:()=>{I(""),c(!0)},t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M11.013 1.427a1.75 1.75 0 0 1 2.474 0l1.086 1.086a1.75 1.75 0 0 1 0 2.474l-8.61 8.61c-.21.21-.47.364-.756.445l-3.251.93a.75.75 0 0 1-.927-.928l.929-3.25c.081-.286.235-.547.445-.758l8.61-8.61Zm.176 4.823L9.75 4.81l-6.286 6.287a.253.253 0 0 0-.064.108l-.558 1.953 1.953-.558a.253.253 0 0 0 .108-.064Zm1.238-3.763a.25.25 0 0 0-.354 0L10.811 3.75l1.439 1.44 1.263-1.263a.25.25 0 0 0 0-.354Z"})})}),R&&Ye&&e.status==="running"?E.jsx(ue,{title:"Cancel execution",onClick:()=>A(e.id),t:o,danger:!0,children:E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("rect",{x:"2",y:"2",width:"6",height:"6",rx:"1"})})}):R&&Ye?E.jsx(ue,{title:"Run cell (Shift+Enter)",onClick:wE,t:o,run:!0,children:E.jsx("svg",{width:"11",height:"11",viewBox:"0 0 10 10",fill:"currentColor",children:E.jsx("path",{d:"M1.5 1.5l7 3.5-7 3.5V1.5Z"})})}):null,R&&E.jsxs(E.Fragment,{children:[E.jsx(ue,{title:"Move up",onClick:kE,t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M3.47 7.78a.75.75 0 0 1 0-1.06l4.25-4.25a.75.75 0 0 1 1.06 0l4.25 4.25a.75.75 0 0 1-1.06 1.06L8.75 4.81v7.44a.75.75 0 0 1-1.5 0V4.81L4.53 7.78a.75.75 0 0 1-1.06 0Z"})})}),E.jsx(ue,{title:"Move down",onClick:jE,t:o,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M12.53 8.22a.75.75 0 0 1 0 1.06l-4.25 4.25a.75.75 0 0 1-1.06 0L2.97 9.28a.75.75 0 0 1 1.06-1.06l2.72 2.97V3.75a.75.75 0 0 1 1.5 0v7.44l2.72-2.97a.75.75 0 0 1 1.06 0Z"})})}),E.jsx(ue,{title:"Delete cell",onClick:XE,t:o,danger:!0,children:E.jsx("svg",{width:"12",height:"12",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M11 1.75V3h2.25a.75.75 0 0 1 0 1.5H2.75a.75.75 0 0 1 0-1.5H5V1.75C5 .784 5.784 0 6.75 0h2.5C10.216 0 11 .784 11 1.75ZM4.496 6.675l.66 6.6a.25.25 0 0 0 .249.225h5.19a.25.25 0 0 0 .249-.225l.66-6.6a.75.75 0 0 1 1.492.149l-.66 6.6A1.748 1.748 0 0 1 10.595 15h-5.19a1.75 1.75 0 0 1-1.741-1.575l-.66-6.6a.75.75 0 1 1 1.492-.15ZM6.5 1.75V3h3V1.75a.25.25 0 0 0-.25-.25h-2.5a.25.25 0 0 0-.25.25Z"})})})]})]})]}),(e.type==="sql"||e.type==="dql")&&E.jsx(JS,{cell:e,connectionNames:W,defaultConnection:Y,t:o,onChange:m=>Ce({executionTarget:m})}),e.type==="dql"&&E.jsx(vS,{content:e.content,onChange:Ve,t:o}),e.blockBinding&&E.jsx(HS,{binding:e.blockBinding,t:o,onRevert:async()=>{var H;const m=e.blockBinding;if(m)try{const X=await Q.openBlockStudio(m.path),ae=`@block(${JSON.stringify(X.metadata.name)})`;T({type:"UPDATE_CELL",id:e.id,updates:{content:ae,blockBinding:{...m,state:"bound",originalContent:ae}}}),(H=St.current)==null||H.resetTo(ae)}catch(X){console.error("Failed to revert bound cell",X)}},onCustomize:async()=>{var H;const m=e.blockBinding;if(m)try{const X=await Q.openBlockStudio(m.path);T({type:"UPDATE_CELL",id:e.id,updates:{content:X.source,dqlParameterValues:{...m.parameterValues??{}},blockBinding:{...m,state:"forked"}}}),(H=St.current)==null||H.resetTo(X.source),lt(!0)}catch(X){console.error("Failed to customize bound cell",X)}},onUnbind:()=>{T({type:"UPDATE_CELL",id:e.id,updates:{blockBinding:void 0}})}}),e.type==="dql"&&(!e.blockBinding||e.blockBinding.state==="forked")&&E.jsxs(E.Fragment,{children:[E.jsx(mS,{source:e.content,onSourceChange:Ve,t:o}),E.jsx(FS,{source:e.content,values:e.dqlParameterValues??{},t:o,onChange:m=>T({type:"UPDATE_CELL",id:e.id,updates:{dqlParameterValues:m}})})]}),((QE=e.blockBinding)==null?void 0:QE.state)==="bound"&&E.jsx(bS,{binding:e.blockBinding,t:o,onChange:m=>T({type:"UPDATE_CELL",id:e.id,updates:{blockBinding:{...e.blockBinding,parameterValues:m}}})}),e.type==="markdown"?E.jsx(js,{value:e.content,onChange:Ve,themeMode:s.themeMode}):E.jsx(ks,{value:e.content,onChange:Ve,onRun:wE,themeMode:s.themeMode,schema:Ns,errorMessage:e.status==="error"?e.error:void 0,editorRef:St}),e.dqlArtifact&&(e.type==="sql"||e.type==="dql")&&E.jsxs("details",{style:{borderTop:`1px solid ${o.cellBorder}`,padding:"6px 12px",background:`${o.tableHeaderBg}40`},children:[E.jsxs("summary",{style:{cursor:"pointer",listStyle:"none",display:"flex",alignItems:"center",gap:6,fontSize:11,fontWeight:700,color:o.textSecondary},children:[E.jsx(Gn,{size:12,color:o.accent}),"Governed DQL",e.dqlArtifact.sourcePath?E.jsx("span",{style:{fontWeight:400,color:o.textMuted,fontFamily:o.fontMono,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.dqlArtifact.sourcePath}):E.jsx("button",{type:"button",title:"Save this governed DQL as a reusable block",onClick:m=>{m.preventDefault(),m.stopPropagation(),j(!0)},style:{marginLeft:"auto",border:"none",background:"transparent",cursor:"pointer",color:o.accent,fontFamily:o.font,fontSize:10.5,fontWeight:700,padding:"1px 4px"},children:"Save as DQL block"})]}),E.jsx("pre",{style:{margin:"6px 0 0",fontFamily:o.fontMono,fontSize:11,whiteSpace:"pre-wrap",color:o.textSecondary,maxHeight:200,overflow:"auto"},children:e.dqlArtifact.source})]}),(e.type==="sql"||e.type==="dql")&&(e.correctionProvenance&&!((zE=e.dqlArtifact)!=null&&zE.sourcePath||((ZE=e.dqlArtifact)==null?void 0:ZE.persistence)==="saved"||((er=e.dqlArtifact)==null?void 0:er.trustState)==="certified"||((tr=e.dqlArtifact)==null?void 0:tr.reviewState)==="certified")?Ke(e).reason==="ready"?E.jsx(ZS,{cell:e,t:o}):E.jsxs("div",{"data-teach-state":Ke(e).reason,style:{borderTop:`1px solid ${o.cellBorder}`,padding:"5px 12px",background:`${o.accent}0A`,color:o.textMuted,font:`500 10.5px ${o.font}`},children:[E.jsx("strong",{style:{color:o.textSecondary},children:"AI draft."})," ",Ke(e).reason==="missing_generated_sql"?E.jsx(E.Fragment,{children:"Original SQL evidence is missing. Reopen this draft from Ask or Notebook AI before teaching it."}):Ke(e).reason==="run_required"||Ke(e).reason==="execution_mismatch"?E.jsxs(E.Fragment,{children:["Draft changed. Run this exact cell successfully to unlock ",E.jsx("strong",{style:{color:o.accent},children:"Teach DQL"}),"."]}):E.jsxs(E.Fragment,{children:["Edit this cell and run it successfully; then ",E.jsx("strong",{style:{color:o.accent},children:"Teach DQL"})," appears below the editor. Teaching creates a review candidate and never certifies automatically."]})]}):e.dqlArtifact&&(e.dqlArtifact.sourcePath||e.dqlArtifact.persistence==="saved"||e.dqlArtifact.trustState==="certified"||e.dqlArtifact.reviewState==="certified")?E.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`,padding:"5px 12px",background:`${o.warning}0A`,color:o.textMuted,font:`500 10.5px ${o.font}`},children:[E.jsx("strong",{style:{color:o.textSecondary},children:"Saved governed DQL."})," ","Notebook edits are a draft for block review and recertification; they do not create Teach DQL learning or overwrite the source automatically."]}):null),E.jsx(kS,{cell:e,t:o}),B&&E.jsx(QS,{cell:e,value:le,kind:x,onValueChange:Ie,onKindChange:u,onAdd:()=>{const m=le.trim();m&&(Ce({annotations:[...e.annotations??[],{id:`note_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,body:m,kind:x,createdAt:new Date().toISOString()}]}),Ie(""))},onRemove:m=>Ce({annotations:(e.annotations??[]).filter(H=>H.id!==m)}),t:o}),ps&&E.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`},children:[E.jsxs("div",{style:{height:28,display:"flex",alignItems:"center",padding:"0 12px",gap:10,borderBottom:e.result&&d?`1px solid ${o.cellBorder}`:"none",background:`${o.tableHeaderBg}60`},children:[e.result&&E.jsxs("span",{style:{fontSize:11,fontFamily:o.font,color:o.textMuted},children:[(()=>{const m=e.result.rowCount??e.result.rows.length;return`${m.toLocaleString()} ${m===1?"row":"rows"}`})(),e.result.executionTime!==void 0&&E.jsxs(E.Fragment,{children:[" · ",e.result.executionTime<1e3?`${Number(e.result.executionTime.toFixed(1))}ms`:`${(e.result.executionTime/1e3).toFixed(2)}s`]})]}),e.fromSnapshot&&e.result&&E.jsx("span",{title:"Result loaded from the last saved run; re-run to refresh.",style:{fontSize:10,fontFamily:o.font,color:o.textMuted,border:`1px solid ${o.btnBorder}`,borderRadius:3,padding:"0 6px",lineHeight:"16px"},children:"cached"}),e.error&&E.jsx("span",{style:{fontSize:11,fontFamily:o.font,color:o.error},children:"Error"}),e.result&&e.type==="sql"&&((Er=e.executionTarget)==null?void 0:Er.target)!=="local"&&E.jsxs(E.Fragment,{children:[E.jsx("button",{type:"button",disabled:$,onClick:()=>re(m=>!m),title:"Combine this warehouse result with an imported local dataset",style:{border:`1px solid ${te?o.accent:o.btnBorder}`,background:te?`${o.accent}18`:o.btnBg,color:te?o.accent:o.textSecondary,borderRadius:4,padding:"2px 7px",font:`800 10px ${o.font}`,cursor:$?"wait":"pointer"},children:e.mixedSourcePlan?"Finish CSV join":"Combine with local data"}),E.jsx("button",{type:"button",disabled:$,onClick:()=>void _s(),title:"Copy this bounded warehouse result into the local analysis workspace",style:{border:`1px solid ${o.btnBorder}`,background:o.btnBg,color:o.textSecondary,borderRadius:4,padding:"2px 7px",font:`700 10px ${o.font}`,cursor:$?"wait":"pointer"},children:$?"Staging…":"Stage only"})]}),e.result&&E.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:3},"aria-label":"Explore this result",children:[E.jsx("span",{style:{font:`700 9px ${o.font}`,color:o.textMuted,textTransform:"uppercase",letterSpacing:".05em"},children:"Explore"}),E.jsx(Mt,{label:"Filter",t:o,onClick:()=>It("filter")}),E.jsx(Mt,{label:"Pivot",t:o,onClick:()=>It("pivot")}),E.jsx(Mt,{label:"Chart",t:o,onClick:()=>It("chart")}),E.jsx(Mt,{label:"KPI",t:o,onClick:()=>It("single_value")})]}),E.jsx("div",{style:{flex:1}}),e.result&&d&&E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3,position:"relative"},children:[E.jsx("button",{onClick:()=>{v("table"),p(!1)},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${f==="table"?o.accent:o.btnBorder}`,background:f==="table"?`${o.accent}20`:"transparent",color:f==="table"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s"},children:"Table"}),E.jsx("button",{onClick:()=>{v("profile"),p(!1)},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${f==="profile"?o.accent:o.btnBorder}`,background:f==="profile"?`${o.accent}20`:"transparent",color:f==="profile"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s"},children:"Profile"}),E.jsxs("div",{style:{position:"relative"},children:[E.jsxs("button",{onClick:()=>{f==="chart"&&h?p(!1):(v("chart"),p(m=>!m))},style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${f==="chart"?o.accent:o.btnBorder}`,background:f==="chart"?`${o.accent}20`:"transparent",color:f==="chart"?o.accent:o.textMuted,cursor:"pointer",transition:"all 0.15s",display:"flex",alignItems:"center",gap:3},children:[U?((rr=wt.find(m=>m.value===U))==null?void 0:rr.label)??"Chart":"Chart",E.jsx("svg",{width:"6",height:"6",viewBox:"0 0 8 8",fill:"currentColor",children:E.jsx("path",{d:"M1 2.5l3 3 3-3",stroke:"currentColor",fill:"none",strokeWidth:"1.2",strokeLinecap:"round"})})]}),h&&E.jsx(el,{selected:U,onSelect:m=>{F(m),v("chart"),p(!1)},onClose:()=>p(!1),t:o})]}),E.jsx("button",{onClick:()=>void Ls(),disabled:V,title:"Recommend chart from result fields",style:{padding:"1px 7px",fontSize:10,fontFamily:o.font,borderRadius:3,border:`1px solid ${V?o.btnBorder:o.accent}`,background:V?"transparent":`${o.accent}14`,color:V?o.textMuted:o.accent,cursor:V?"wait":"pointer",transition:"all 0.15s"},children:V?"...":"Suggest"}),Z&&E.jsx("span",{title:Z,style:{maxWidth:150,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:10,color:o.textMuted,fontFamily:o.font},children:Z}),f==="chart"&&E.jsx("button",{onClick:()=>y(m=>!m),title:"Chart configuration",style:{padding:"1px 5px",fontSize:11,borderRadius:3,cursor:"pointer",border:`1px solid ${G?o.accent:o.btnBorder}`,background:G?`${o.accent}20`:"transparent",color:G?o.accent:o.textMuted,transition:"all 0.15s",display:"flex",alignItems:"center"},children:E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 16 16",fill:"currentColor",children:E.jsx("path",{d:"M8 0a8.2 8.2 0 0 1 .701.031C9.444.095 9.99.645 10.16 1.29l.288 1.107c.018.066.079.158.212.224.231.114.454.243.668.386.123.082.233.09.299.071l1.103-.303c.644-.176 1.392.021 1.82.63.27.386.506.798.704 1.23.315.698.043 1.44-.476 1.89l-.815.806a.338.338 0 0 0-.079.262c.02.267.02.538 0 .805a.338.338 0 0 0 .079.262l.815.806c.52.45.79 1.192.476 1.89a7.22 7.22 0 0 1-.704 1.23c-.428.609-1.176.806-1.82.63l-1.103-.303c-.066-.019-.176-.011-.299.071a5.09 5.09 0 0 1-.668.386c-.133.066-.194.158-.212.224l-.288 1.107c-.169.645-.715 1.196-1.458 1.26a8.006 8.006 0 0 1-1.402 0c-.743-.064-1.29-.614-1.458-1.26l-.289-1.106c-.018-.066-.079-.158-.212-.224a5.09 5.09 0 0 1-.668-.387c-.123-.082-.233-.09-.299-.071l-1.103.303c-.644.176-1.392-.021-1.82-.63a7.12 7.12 0 0 1-.704-1.23c-.315-.698-.043-1.44.476-1.89l.815-.806a.338.338 0 0 0 .079-.262 6.08 6.08 0 0 1 0-.805.338.338 0 0 0-.079-.262l-.815-.806c-.52-.45-.79-1.192-.476-1.89a7.22 7.22 0 0 1 .704-1.23c.428-.609 1.176-.806 1.82-.63l1.103.303c.066.019.176.011.299-.071.214-.143.437-.272.668-.386.133-.066.194-.158.212-.224L6.54 1.29C6.71.645 7.256.095 7.999.031 8.236.01 8.474 0 8.713 0H8ZM8 5a3 3 0 1 0 0 6 3 3 0 0 0 0-6Z"})})})]}),E.jsxs("button",{onClick:()=>L(m=>!m),style:{background:"transparent",border:"none",cursor:"pointer",color:o.textMuted,fontSize:11,fontFamily:o.font,padding:"2px 4px",display:"flex",alignItems:"center",gap:4},children:[E.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"currentColor",style:{transform:d?"rotate(0deg)":"rotate(-90deg)",transition:"transform 0.15s"},children:E.jsx("path",{d:"M1 3l4 4 4-4",stroke:"currentColor",fill:"none",strokeWidth:"1.5"})}),d?"Hide":"Show"]})]}),te&&e.result&&E.jsx(pS,{warehouseColumns:e.result.columns,warehouseRows:e.result.rows,warehouseRowCount:e.result.rowCount??e.result.rows.length,busy:$,t:o,onCancel:()=>re(!1),onCombine:m=>void us(m),suggestedPlan:e.mixedSourcePlan}),d&&E.jsxs(E.Fragment,{children:[de&&!e.error&&E.jsx("div",{role:"status",style:{padding:"8px 12px",borderLeft:`3px solid ${o.success}`,background:`${o.success}10`,color:o.textSecondary,font:`500 11px ${o.font}`},children:de}),e.status==="running"&&Ye&&E.jsx(YS,{cellType:e.type,cellName:e.name,t:o,onCancel:()=>A(e.id)}),e.error&&E.jsx(NT,{message:e.error,themeMode:s.themeMode,onFix:e.type==="sql"?ds:void 0,onBackgroundRepair:un(e)?()=>void Cs():void 0,repairing:ce,repairError:ne,editableArtifactLabel:e.type==="dql"?"DQL":"SQL",schemaTables:s.schemaTables}),e.result&&!e.error&&(f==="profile"?E.jsx(zS,{cell:e,t:o}):f==="chart"&&U?E.jsxs(E.Fragment,{children:[bE(U,e.result,s.themeMode,e.chartConfig),G&&E.jsx(tl,{columns:e.result.columns,chartConfig:e.chartConfig,onChange:m=>T({type:"UPDATE_CELL",id:e.id,updates:{chartConfig:{...e.chartConfig,...m}}}),t:o})]}):E.jsx(FE,{result:e.result,themeMode:s.themeMode}))]})]}),Ye&&E.jsx(mT,{cellContent:e.content,cellType:e.type,compiledSql:((nr=e.dqlArtifact)==null?void 0:nr.compiledSql)??((sr=e.dqlArtifact)==null?void 0:sr.sql),cellId:e.id,cellName:e.name,cells:i,themeMode:s.themeMode,t:o,onFocusNode:m=>{T({type:"SET_LINEAGE_FOCUS",nodeId:m}),T({type:"OPEN_LINEAGE_DRAWER",nodeId:m})}})]})]})}const $S=Yt.memo(jS,(e,t)=>e.cell===t.cell&&e.index===t.index&&e.onStartResearch===t.onStartResearch&&JSON.stringify(e.researchState??null)===JSON.stringify(t.researchState??null));function KS(e){const t=e.toLowerCase().replace(/-/g,"_"),r=t==="grouped_bar"?"grouped-bar":t==="stacked_bar"?"stacked-bar":t,n=wt.find(s=>s.value===r);return(n==null?void 0:n.value)??"table"}function qS(e){const t=Se("sql",`SELECT *
172
172
  FROM "${e.alias.replace(/"/g,'""')}"
173
173
  LIMIT 100`);return t.name=`${e.alias}_analysis`,t.executionTarget={target:"local"},t.datasetRefs=[{id:e.id,alias:e.alias,role:"staged",fingerprint:e.fileFingerprint}],t}function JS({cell:e,connectionNames:t,defaultConnection:r,t:n,onChange:s}){var o,S,a,A;const T=((o=e.executionTarget)==null?void 0:o.target)==="local"?"local":`connection:${((S=e.executionTarget)==null?void 0:S.connectionName)??r}`,i=e.blockBinding?"Certified or draft block":/@(?:metric|dim)\s*\(/i.test(e.content)?"Semantic query":((a=e.executionTarget)==null?void 0:a.target)==="local"?"Local dataset SQL":"Warehouse SQL";return E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"5px 12px",borderTop:`1px solid ${n.cellBorder}`,background:`${n.tableHeaderBg}35`},children:[E.jsx(vt,{size:12,color:n.textMuted,"aria-hidden":"true"}),E.jsx("span",{style:{color:n.textMuted,fontSize:10,fontWeight:700},children:i}),E.jsx("span",{style:{color:n.textMuted,fontSize:10},children:"runs on"}),E.jsxs("select",{"aria-label":"Query execution target",value:T,onChange:R=>{R.target.value==="local"?s({target:"local"}):s({target:"connection",connectionName:R.target.value.slice(11)})},style:{background:n.inputBg,color:n.textSecondary,border:`1px solid ${n.inputBorder}`,borderRadius:5,padding:"2px 6px",font:`10px ${n.font}`},children:[E.jsx("option",{value:"local",children:"Local analysis workspace"}),t.map(R=>E.jsxs("option",{value:`connection:${R}`,children:[R,R===r?" (default)":""]},R)),t.length===0&&E.jsx("option",{value:`connection:${r}`,children:r})]}),(A=e.datasetRefs)!=null&&A.length?E.jsxs("span",{style:{marginLeft:"auto",color:n.textMuted,fontSize:10},children:[e.datasetRefs.length," dataset",e.datasetRefs.length===1?"":"s"]}):null]})}function QS({cell:e,value:t,kind:r,onValueChange:n,onKindChange:s,onAdd:T,onRemove:i,t:o}){return E.jsxs("div",{style:{borderTop:`1px solid ${o.cellBorder}`,background:`${o.tableHeaderBg}30`,padding:"9px 12px",display:"grid",gap:8},children:[(e.annotations??[]).map(S=>E.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start",color:o.textSecondary,fontSize:11},children:[E.jsxs("div",{style:{flex:1},children:[E.jsx("span",{style:{display:"inline-flex",marginBottom:4,border:`1px solid ${o.btnBorder}`,borderRadius:999,padding:"1px 6px",color:o.textMuted,font:`700 9px ${o.font}`,textTransform:"uppercase",letterSpacing:".04em"},children:S.kind??"note"}),E.jsx("div",{style:{whiteSpace:"pre-wrap"},children:S.body}),E.jsxs("div",{style:{color:o.textMuted,fontSize:9,marginTop:3},children:[S.author?`${S.author} · `:"",new Date(S.updatedAt??S.createdAt).toLocaleString()]})]}),E.jsx("button",{type:"button",onClick:()=>i(S.id),style:{border:0,background:"transparent",color:o.textMuted,cursor:"pointer",fontSize:10},children:"Remove"})]},S.id)),E.jsxs("div",{style:{display:"flex",gap:6,alignItems:"flex-start"},children:[E.jsxs("select",{"aria-label":"Research note type",value:r??"note",onChange:S=>s(S.target.value),style:{background:o.inputBg,color:o.textPrimary,border:`1px solid ${o.inputBorder}`,borderRadius:6,padding:"6px 7px",font:`11px ${o.font}`},children:[E.jsx("option",{value:"note",children:"Note"}),E.jsx("option",{value:"assumption",children:"Assumption"}),E.jsx("option",{value:"finding",children:"Finding"}),E.jsx("option",{value:"decision",children:"Decision"}),E.jsx("option",{value:"caveat",children:"Caveat"})]}),E.jsx("textarea",{"aria-label":"Cell note",value:t,onChange:S=>n(S.target.value),placeholder:"Record an assumption, validation note, or takeaway…",rows:2,style:{flex:1,resize:"vertical",background:o.inputBg,color:o.textPrimary,border:`1px solid ${o.inputBorder}`,borderRadius:6,padding:"6px 8px",font:`11px ${o.font}`}}),E.jsx("button",{type:"button",onClick:T,disabled:!t.trim(),style:{alignSelf:"flex-end",border:`1px solid ${o.accent}`,background:`${o.accent}14`,color:o.accent,borderRadius:5,padding:"5px 9px",font:`700 10px ${o.font}`,cursor:t.trim()?"pointer":"not-allowed",opacity:t.trim()?1:.5},children:"Add note"})]})]})}function zS({cell:e,t}){const r=e.result;if(!r)return null;const n=r.rows.slice(0,500);return E.jsx("div",{style:{padding:12,display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:8},children:r.columns.map(s=>{const i=n.map(a=>a[s]).filter(a=>a!=null&&a!==""),o=new Set(i.map(a=>String(a))).size,S=i.filter(a=>typeof a=="number"||typeof a=="string"&&a.trim()!==""&&Number.isFinite(Number(a)));return E.jsxs("div",{style:{border:`1px solid ${t.cellBorder}`,borderRadius:7,padding:9,background:t.cellBg},children:[E.jsx("div",{style:{color:t.textPrimary,font:`700 11px ${t.fontMono}`,overflow:"hidden",textOverflow:"ellipsis"},children:s}),E.jsxs("div",{style:{color:t.textMuted,fontSize:10,marginTop:6},children:[n.length-i.length," null · ",o," distinct in preview"]}),S.length===i.length&&S.length>0&&E.jsxs("div",{style:{color:t.textSecondary,fontSize:10,marginTop:3},children:["min ",Math.min(...S.map(Number)).toLocaleString()," · max"," ",Math.max(...S.map(Number)).toLocaleString()]})]},s)})})}function tt(e,t="default"){return Ne(e,{variant:t==="accent"?"accent":t==="danger"?"danger":"secondary",size:"xs"})}function Mt({label:e,t,onClick:r}){return E.jsx("button",{type:"button",onClick:r,title:`Create a reusable ${e.toLowerCase()} step from this result`,style:{border:`1px solid ${t.btnBorder}`,background:t.btnBg,color:t.textSecondary,borderRadius:4,padding:"2px 6px",font:`700 10px ${t.font}`,cursor:"pointer"},children:e})}function ZS({cell:e,t}){const[r,n]=l.useState("idle"),[s,T]=l.useState(null),[i,o]=l.useState(!1),{eligible:S,generatedSql:a,correctedSql:A,question:R}=Ke(e),N=l.useMemo(()=>iT(e,{question:R??"",previousSql:a,correctedSql:A,domain:typeof window<"u"?(()=>{const p=new URLSearchParams(window.location.search).get("domain");return p&&p!=="all"?p:void 0})():void 0}),[e,A,a,R]),[O,c]=l.useState(N.title),[C,I]=l.useState(N.guidance),[d,L]=l.useState(N.rationale),[f,v]=l.useState(N.lesson),[U,F]=l.useState(N.scope);if(!S||r==="dismissed")return null;if(r==="saved")return E.jsxs("div",{"data-teach-state":"saved",role:"status",style:{borderTop:`1px solid ${t.success}55`,borderBottom:`1px solid ${t.success}33`,background:`${t.success}10`,padding:"11px 14px",display:"flex",alignItems:"center",gap:9,color:t.success,fontFamily:t.font},children:[E.jsx(ys,{size:17,strokeWidth:2.4}),E.jsxs("div",{children:[E.jsx("div",{style:{fontSize:12,fontWeight:750},children:"Correction saved for review"}),E.jsx("div",{style:{marginTop:2,fontSize:10.5,color:t.textMuted},children:"It remains a candidate until it passes evaluation and you explicitly approve it in Agent learning."})]})]});const h=async()=>{if(!O.trim()||!C.trim()){T("Add a short title and reusable lesson before saving."),n("error");return}if(!we(U)){T("Confirm at least one domain, metric, dbt model, business term, or block so this learning cannot become project-wide by accident."),n("error");return}n("saving"),T(null);try{const p=await Q.recordAgentCorrection({question:R,wrongSql:a,correctedSql:A,title:O.trim(),guidance:C.trim(),lesson:{...f,version:1,rule:C.trim()},rationale:d.trim()||"Edited in the notebook and ran successfully.",scope:U});if(p.ok===!1){T(p.error??"Could not save this correction."),n("error");return}n("saved")}catch(p){T(p instanceof Error?p.message:String(p)),n("error")}};return E.jsxs("div",{"data-teach-state":r==="error"?"error":"ready",role:"region","aria-label":"Teach DQL correction",style:{borderTop:`2px solid ${r==="error"?t.error:t.accent}`,borderBottom:`1px solid ${r==="error"?`${t.error}44`:`${t.accent}44`}`,background:r==="error"?`${t.error}0D`:`linear-gradient(90deg, ${t.accent}18 0%, ${t.accent}09 72%, transparent 100%)`,padding:"13px 14px",display:"flex",alignItems:"center",gap:11,flexWrap:"wrap",fontFamily:t.font},children:[E.jsx("div",{"aria-hidden":"true",style:{width:32,height:32,flex:"0 0 32px",borderRadius:8,display:"grid",placeItems:"center",color:r==="error"?t.error:"#ffffff",background:r==="error"?`${t.error}18`:t.accent,border:`1px solid ${r==="error"?`${t.error}44`:t.accent}`},children:E.jsx(qe,{size:17,strokeWidth:2.3})}),E.jsxs("div",{style:{flex:"1 1 300px",minWidth:0},children:[E.jsx("div",{style:{color:r==="error"?t.error:t.textPrimary,fontSize:12.5,fontWeight:750},children:r==="error"?"This correction was not saved":"Teach DQL from this successful correction"}),E.jsx("div",{style:{marginTop:3,color:t.textMuted,fontSize:10.75,lineHeight:1.45},children:r==="error"?s??"DQL could not create the review candidate. Try again.":E.jsx(E.Fragment,{children:"Review the before/after SQL, explain the reusable lesson, and confirm where it applies. Saving creates a candidate only."})})]}),E.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:7,marginLeft:"auto"},children:[E.jsxs("button",{type:"button",onClick:()=>o(p=>!p),title:"Review the reusable lesson and its governed scope",style:Ne(t,{variant:"primary",size:"md"}),children:[E.jsx(qe,{size:14,"aria-hidden":"true"}),i?"Close review":"Review & teach"]}),E.jsx("button",{type:"button",onClick:()=>n("dismissed"),title:"Dismiss this suggestion",style:Ne(t,{variant:"ghost",size:"sm"}),children:"Not now"})]}),i?E.jsxs("div",{"data-teach-review":!0,style:{flex:"1 0 100%",display:"grid",gap:12,padding:"13px",border:`1px solid ${t.cellBorder}`,borderRadius:8,background:t.cellBg},children:[E.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(260px, 1fr))",gap:10},children:[E.jsxs("details",{open:!0,style:{border:`1px solid ${t.cellBorder}`,borderRadius:7,padding:9},children:[E.jsx("summary",{style:{cursor:"pointer",color:t.textSecondary,fontSize:11,fontWeight:700},children:"Before · AI draft"}),E.jsx("pre",{style:{margin:"8px 0 0",color:t.textMuted,fontFamily:t.fontMono,fontSize:10.5,whiteSpace:"pre-wrap",maxHeight:180,overflow:"auto"},children:a})]}),E.jsxs("details",{open:!0,style:{border:`1px solid ${t.success}55`,borderRadius:7,padding:9},children:[E.jsx("summary",{style:{cursor:"pointer",color:t.success,fontSize:11,fontWeight:700},children:"After · successful correction"}),E.jsx("pre",{style:{margin:"8px 0 0",color:t.textMuted,fontFamily:t.fontMono,fontSize:10.5,whiteSpace:"pre-wrap",maxHeight:180,overflow:"auto"},children:A})]})]}),E.jsxs("label",{style:{display:"grid",gap:4,color:t.textSecondary,fontSize:10.5,fontWeight:650},children:["Learning title",E.jsx("input",{value:O,onChange:p=>c(p.target.value),style:Ne(t,{size:"sm"})})]}),E.jsxs("label",{style:{display:"grid",gap:4,color:t.textSecondary,fontSize:10.5,fontWeight:650},children:["Reusable lesson",E.jsx("textarea",{value:C,onChange:p=>{I(p.target.value),v(G=>({...G,rule:p.target.value}))},rows:3,placeholder:"Explain the business or SQL rule that should guide similar questions.",style:{...Ne(t,{size:"sm"}),resize:"vertical",lineHeight:1.45}}),E.jsx("span",{style:{color:t.textMuted,fontWeight:400},children:"This reviewed lesson—not the raw comment—is what matching future questions receive."})]}),E.jsxs("details",{style:{border:`1px solid ${t.cellBorder}`,borderRadius:7,padding:"9px 10px"},children:[E.jsxs("summary",{style:{cursor:"pointer",color:t.textSecondary,fontSize:10.5,fontWeight:700},children:["Help DQL generalize this lesson ",E.jsx("span",{style:{color:t.textMuted,fontWeight:400},children:"(optional)"})]}),E.jsxs("div",{style:{display:"grid",gap:9,paddingTop:9},children:[E.jsxs("label",{style:{display:"grid",gap:4,color:t.textMuted,fontSize:10},children:["Lesson type",E.jsxs("select",{value:f.category,onChange:p=>v({...f,category:p.target.value}),style:Ne(t,{size:"sm"}),children:[E.jsx("option",{value:"semantic_rule",children:"Business definition"}),E.jsx("option",{value:"filter_rule",children:"Filter rule"}),E.jsx("option",{value:"join_rule",children:"Join rule"}),E.jsx("option",{value:"aggregation_rule",children:"Aggregation rule"}),E.jsx("option",{value:"grain_rule",children:"Grain rule"}),E.jsx("option",{value:"time_rule",children:"Time rule"}),E.jsx("option",{value:"relation_rule",children:"Table or column rule"}),E.jsx("option",{value:"dialect_rule",children:"SQL dialect rule"})]})]}),E.jsxs("label",{style:{display:"grid",gap:4,color:t.textMuted,fontSize:10},children:["Similar questions ",E.jsx("span",{children:"one per line; used for retrieval, never as automatic truth"}),E.jsx("textarea",{value:f.intentExamples.join(`
174
174
  `),onChange:p=>v({...f,intentExamples:p.target.value.split(/\r?\n/)}),onBlur:()=>v({...f,intentExamples:br(f.intentExamples.join(`
175
175
  `))}),rows:3,placeholder:`Revenue by region
176
176
  Which markets generate the most net sales?`,style:{...Ne(t,{size:"sm"}),resize:"vertical",lineHeight:1.4}})]}),E.jsxs("label",{style:{display:"grid",gap:4,color:t.textMuted,fontSize:10},children:["Avoid these known mistakes ",E.jsx("span",{children:"one per line"}),E.jsx("textarea",{value:f.avoid.join(`
177
177
  `),onChange:p=>v({...f,avoid:p.target.value.split(/\r?\n/)}),onBlur:()=>v({...f,avoid:br(f.avoid.join(`
178
- `))}),rows:2,placeholder:"Do not include refunded orders.",style:{...Ne(t,{size:"sm"}),resize:"vertical",lineHeight:1.4}})]}),E.jsxs("label",{style:{display:"grid",gap:4,color:t.textMuted,fontSize:10},children:["Expected outcome or result shape",E.jsx("input",{value:f.expectedOutcome??"",onChange:p=>v({...f,expectedOutcome:p.target.value||void 0}),placeholder:"One row per region using net revenue",style:Ne(t,{size:"sm"})})]})]})]}),E.jsxs("div",{children:[E.jsx("div",{style:{color:t.textSecondary,fontSize:10.5,fontWeight:700,marginBottom:6},children:"Where should this learning apply?"}),E.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(145px, 1fr))",gap:7},children:[["domain","Domain"],["metric","Metric"],["dbtModel","dbt model"],["term","Business term"],["block","Block"],["dialect","SQL dialect"]].map(([p,G])=>E.jsxs("label",{style:{display:"grid",gap:3,color:t.textMuted,fontSize:10},children:[G,E.jsx("input",{value:U[p]??"",onChange:y=>F({...U,[p]:y.target.value||void 0}),placeholder:`Optional ${G.toLowerCase()}`,style:Ne(t,{size:"sm"})})]},p))})]}),E.jsxs("label",{style:{display:"grid",gap:4,color:t.textSecondary,fontSize:10.5,fontWeight:650},children:["Why is this correct? ",E.jsx("span",{style:{color:t.textMuted,fontWeight:400},children:"(optional reviewer evidence)"}),E.jsx("textarea",{value:d,onChange:p=>L(p.target.value),rows:2,placeholder:"Example: Finance defines revenue as net amount and excludes refunded orders.",style:{...Ne(t,{size:"sm"}),resize:"vertical",lineHeight:1.45}})]}),E.jsxs("div",{style:{border:`1px solid ${we(U)?`${t.success}55`:`${t.warning}66`}`,borderRadius:7,padding:"9px 10px",background:we(U)?`${t.success}08`:`${t.warning}0A`,display:"grid",gap:4,fontSize:10.5},children:[E.jsxs("div",{style:{color:t.textPrimary,fontWeight:700},children:["Will apply to: ",Br(U).length?`questions matching ${Br(U).join(" · ")}`:"no confirmed scope yet"]}),E.jsx("div",{style:{color:t.textMuted},children:"Will not apply when a confirmed scope value differs. Relations and columns are derived from the corrected SQL and current project snapshot, then used for ranking, drift checks, and review evidence."}),we(U)?null:E.jsx("div",{style:{color:t.warning},children:"Add at least one domain, metric, model, term, or block before saving."})]}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[E.jsxs("button",{type:"button",onClick:()=>void h(),disabled:r==="saving"||!we(U),style:Ne(t,{variant:"primary",size:"md",disabled:r==="saving"||!we(U)}),children:[E.jsx(qe,{size:14,"aria-hidden":"true"}),r==="saving"?"Saving candidate…":"Save learning candidate"]}),E.jsx("span",{style:{color:t.textMuted,fontSize:10.25},children:"It remains inactive until evaluation and explicit approval in Agent learning."})]})]}):null]})}function ue({title:e,onClick:t,children:r,t:n,accent:s,danger:T,run:i}){const[o,S]=l.useState(!1),a=i?n.success:T?n.error:s?n.accent:void 0;return E.jsx("button",{title:e,"aria-label":e,onClick:t,onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),style:{width:26,height:26,display:"flex",alignItems:"center",justifyContent:"center",background:a?o?`${a}24`:`${a}12`:o?n.btnHover:"transparent",border:`1px solid ${a?o?`${a}66`:`${a}33`:o?n.btnBorder:"transparent"}`,borderRadius:6,cursor:"pointer",color:a??(o?n.textSecondary:n.textMuted),transition:"background 0.15s, border-color 0.15s, color 0.15s",padding:0},children:r})}function el({selected:e,onSelect:t,onClose:r,t:n}){const[s,T]=l.useState(null);return Yt.useEffect(()=>{const i=o=>{setTimeout(()=>r(),0)};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[r]),E.jsx("div",{onMouseDown:i=>i.stopPropagation(),style:{position:"absolute",top:24,right:0,zIndex:200,background:n.cellBg,border:`1px solid ${n.cellBorder}`,borderRadius:6,boxShadow:"0 8px 24px rgba(0,0,0,0.3)",padding:4,minWidth:130,maxHeight:280,overflowY:"auto",display:"flex",flexDirection:"column",gap:1},children:wt.map(({value:i,label:o})=>E.jsx("button",{onClick:()=>t(i),onMouseEnter:()=>T(i),onMouseLeave:()=>T(null),style:{background:e===i?`${n.accent}20`:s===i?n.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:e===i?n.accent:n.textSecondary,fontSize:11,fontFamily:n.font,fontWeight:e===i?600:400,padding:"4px 10px",textAlign:"left",transition:"background 0.1s"},children:o},i))})}function tl({columns:e,chartConfig:t,onChange:r,t:n}){const s={background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:4,color:n.textPrimary,fontSize:11,fontFamily:n.fontMono,padding:"3px 6px",outline:"none",minWidth:100,flex:1},T={fontSize:9,fontWeight:700,color:n.textMuted,fontFamily:n.font,letterSpacing:"0.05em",textTransform:"uppercase",minWidth:40,flexShrink:0};return E.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 16px",padding:"8px 12px",borderTop:`1px solid ${n.cellBorder}`,background:`${n.tableHeaderBg}40`},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:T,children:"X axis"}),E.jsxs("select",{style:s,value:(t==null?void 0:t.x)??"",onChange:i=>r({x:i.target.value||void 0}),children:[E.jsx("option",{value:"",children:"Auto"}),e.map(i=>E.jsx("option",{value:i,children:i},i))]})]}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:T,children:"Y axis"}),E.jsxs("select",{style:s,value:(t==null?void 0:t.y)??"",onChange:i=>r({y:i.target.value||void 0}),children:[E.jsx("option",{value:"",children:"Auto"}),e.map(i=>E.jsx("option",{value:i,children:i},i))]})]}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:T,children:"Color"}),E.jsxs("select",{style:s,value:(t==null?void 0:t.color)??"",onChange:i=>r({color:i.target.value||void 0}),children:[E.jsx("option",{value:"",children:"None"}),e.map(i=>E.jsx("option",{value:i,children:i},i))]})]}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:150},children:[E.jsx("span",{style:T,children:"Title"}),E.jsx("input",{style:{...s,fontFamily:n.font},value:(t==null?void 0:t.title)??"",placeholder:"Chart title",onChange:i=>r({title:i.target.value||void 0})})]})]})}function Rs({themeMode:e,onPick:t,autoFocus:r=!0,compact:n=!0}){const{state:s}=Pe(),T=se[e],[i,o]=l.useState([]),[S,a]=l.useState(!0),[A,R]=l.useState(""),[N,O]=l.useState(""),[c,C]=l.useState(""),I=l.useRef(null);l.useEffect(()=>{let h=!1;return a(!0),Q.getBlockLibrary().then(p=>{h||o(p.blocks)}).finally(()=>{h||a(!1)}),()=>{h=!0}},[]),l.useEffect(()=>{if(r){const h=setTimeout(()=>{var p;return(p=I.current)==null?void 0:p.focus()},30);return()=>clearTimeout(h)}},[r]);const d=l.useMemo(()=>Gs(s.authoredDomains),[s.authoredDomains]),L=l.useMemo(()=>Bs(s.authoredDomains),[s.authoredDomains]),f=l.useMemo(()=>i.some(h=>{var p;return!d.has(((p=h.domain)==null?void 0:p.trim())??"")}),[i,d]),v=l.useMemo(()=>[...new Set(i.map(h=>h.status))].sort(),[i]),U=l.useMemo(()=>i.filter(h=>{var p;if(A){const G=A.toLowerCase();if(![h.name,h.description,h.llmContext,h.domain,h.status,h.owner,...h.tags??[]].filter(Boolean).join(" ").toLowerCase().includes(G))return!1}return!(N==="uncategorized"&&d.has(((p=h.domain)==null?void 0:p.trim())??"")||N&&N!=="uncategorized"&&(!d.has(N)||h.domain!==N)||c&&h.status!==c)}).sort((h,p)=>+(p.status==="certified")-+(h.status==="certified")||h.name.localeCompare(p.name)),[i,A,N,c,d]),F={background:T.inputBg,border:`1px solid ${T.inputBorder}`,borderRadius:4,color:T.textPrimary,fontSize:11,fontFamily:T.font,padding:"4px 6px",outline:"none"};return E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:n?340:void 0},children:[E.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[E.jsx("input",{ref:I,value:A,onChange:h=>R(h.target.value),placeholder:"Search question, block, domain, owner, or tag…","aria-label":"Search existing blocks",style:{...F,flex:1,padding:"6px 8px"}}),E.jsxs("select",{"aria-label":"Filter blocks by domain",value:N,onChange:h=>O(h.target.value),style:F,children:[E.jsx("option",{value:"",children:"All domains"}),L.map(h=>E.jsx("option",{value:h.value,children:h.label},h.value)),f?E.jsx("option",{value:"uncategorized",children:"Unassigned"}):null]}),E.jsxs("select",{"aria-label":"Filter blocks by status",value:c,onChange:h=>C(h.target.value),style:F,children:[E.jsx("option",{value:"",children:"Any"}),v.map(h=>E.jsx("option",{value:h,children:h},h))]})]}),!S&&E.jsxs("div",{style:{fontSize:10,color:T.textMuted,fontFamily:T.font,padding:"0 2px"},children:[U.length," reusable ",U.length===1?"block":"blocks"," · certified results are listed first"]}),E.jsx("div",{style:{maxHeight:n?220:420,overflowY:"auto",display:"flex",flexDirection:"column",border:`1px solid ${T.cellBorder}`,borderRadius:4},children:S?E.jsx(pn,{t:T,children:"Loading blocks..."}):U.length===0?E.jsx(pn,{t:T,children:i.length===0?"No blocks yet. Save a cell as a block to get started.":"No blocks match your filters."}):U.map(h=>E.jsx(El,{block:h,onClick:()=>t(h),t:T,compact:n},h.path))})]})}function pn({children:e,t}){return E.jsx("div",{style:{padding:16,textAlign:"center",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:e})}function El({block:e,onClick:t,t:r,compact:n}){const[s,T]=l.useState(!1),i=Qs[e.status]??r.textMuted;return E.jsxs("button",{onClick:t,onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),style:{background:s?`${r.accent}14`:"transparent",border:"none",borderBottom:`1px solid ${r.cellBorder}`,cursor:"pointer",padding:n?"8px 10px":"10px 12px",textAlign:"left",fontFamily:r.font},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:3},children:[E.jsx("span",{style:{fontSize:12,fontWeight:600,color:r.textPrimary},children:e.name}),E.jsx("span",{style:{fontSize:9,fontWeight:600,color:i,background:`${i}18`,padding:"1px 6px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em"},children:e.status})]}),e.description&&E.jsx("div",{style:{fontSize:11,color:r.textMuted,lineHeight:1.3,marginBottom:3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.description}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:10,color:r.textMuted},children:[E.jsx("span",{style:{background:r.pillBg,padding:"1px 6px",borderRadius:4},children:e.domain||"no domain"}),e.owner&&E.jsxs("span",{children:["by ",e.owner]}),(e.tags??[]).slice(0,n?2:4).map(o=>E.jsxs("span",{style:{background:r.pillBg,padding:"1px 6px",borderRadius:4},children:["#",o]},o))]})]})}const rl=[{type:"block",label:"Block",Icon:Or,color:"#6b8afd"},{type:"ai_sql",label:"Ask AI",Icon:qe,color:"#f0883e"},{type:"dql",label:"DQL",Icon:Or,color:"#6b8afd"},{type:"sql",label:"SQL",Icon:bs,color:"#3b8ef0"},{type:"import_data",label:"Import",Icon:eo,color:"#5dd1c8"},{type:"markdown",label:"Note",Icon:gn,color:"#2fb97a"},{type:"param",label:"Input",Icon:Fs,color:"#9aa0ae"}];function Dn({afterId:e}){const{state:t,dispatch:r}=Pe(),n=se[t.themeMode],[s,T]=l.useState(!1),[i,o]=l.useState(!1),[S,a]=l.useState(!1),[A,R]=l.useState(!1),N=l.useRef(null);l.useEffect(()=>{if(!i)return;function I(d){N.current&&!N.current.contains(d.target)&&(o(!1),a(!1))}return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[i]);const O=()=>{o(!1),a(!1)},c=I=>{const d=Se(I);r({type:"ADD_CELL",cell:d,afterId:e}),O()},C=async I=>{try{await Q.openBlockStudio(I.path)}catch(f){console.error("Failed to bind block cell",f),window.alert(`Couldn't load block ${I.path}. Check the console for details.`),O();return}const d=`@block(${JSON.stringify(I.name)})`,L=Se("dql",d);L.name=I.name,L.blockBinding={path:I.path,state:"bound",originalContent:d},r({type:"ADD_CELL",cell:L,afterId:e}),O()};return E.jsxs("div",{ref:N,"data-testid":"add-cell-bar",onDragOver:I=>{I.dataTransfer.types.includes(Nr)&&(I.preventDefault(),R(!0))},onDragLeave:()=>R(!1),onDrop:I=>{const d=Hs(I.dataTransfer.getData(Nr));if(!d)return;I.preventDefault(),R(!1);const L=Se("sql",d.reference);r({type:"ADD_CELL",cell:L,afterId:e}),Q.trackUsage(d.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:d.name}}))},onMouseEnter:()=>T(!0),onMouseLeave:()=>{T(!1),R(!1)},onClick:I=>{I.target===I.currentTarget&&(T(!0),o(!0))},style:{position:"relative",height:28,display:"flex",alignItems:"center",justifyContent:"center",cursor:i?"default":"pointer"},children:[(s||i||A)&&E.jsxs("button",{"aria-label":"Add cell",onClick:()=>o(I=>!I),style:{position:"relative",zIndex:2,height:22,padding:"0 10px",borderRadius:11,border:`1px solid ${A?n.accent:n.cellBorderActive}`,background:A?`${n.accent}28`:`${n.accent}18`,color:n.accent,cursor:"pointer",fontSize:12,fontFamily:n.font,fontWeight:500,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s"},children:[E.jsx("span",{style:{fontSize:14,lineHeight:1,marginTop:-1},children:"+"}),"Add cell"]}),i&&E.jsxs("div",{style:{position:"absolute",top:26,left:"50%",transform:"translateX(-50%)",zIndex:100,background:n.modalBg,border:`1px solid ${n.cellBorder}`,borderRadius:10,boxShadow:"0 12px 32px rgba(0,0,0,0.35)",padding:8,display:"flex",flexDirection:"column",gap:8,width:S?"min(760px, calc(100vw - 48px))":"max-content",maxWidth:"calc(100vw - 48px)"},children:[E.jsx("div",{style:{display:"flex",gap:4,flexWrap:"nowrap",alignItems:"center",justifyContent:"flex-start",overflowX:"auto",overflowY:"hidden",maxWidth:"100%",paddingBottom:1},children:rl.map(I=>E.jsx(nl,{entry:I,active:I.type==="block"&&S,onClick:()=>{if(I.type==="block"){a(d=>!d);return}if(I.type==="ai_sql"){window.dispatchEvent(new CustomEvent("dql:open-notebook-ai",{detail:{afterId:e}})),O();return}if(I.type==="import_data"){window.dispatchEvent(new CustomEvent("dql:open-dataset-import",{detail:{afterId:e}})),O();return}c(I.type)},t:n},I.type))}),S&&E.jsx("div",{style:{padding:"6px 2px 2px",borderTop:`1px solid ${n.cellBorder}`},children:E.jsx(Rs,{themeMode:t.themeMode,onPick:I=>void C(I)})})]})]})}function nl({entry:e,onClick:t,t:r,active:n=!1}){const[s,T]=l.useState(!1),i=n||s,o=e.Icon;return E.jsxs("button",{"aria-label":e.type==="ai_sql"?"Ask AI":e.type==="import_data"?"Import data":`Add ${e.label} cell`,"data-testid":`add-cell-${e.type}`,onClick:t,onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),title:e.label,style:{background:i?`${e.color}18`:"transparent",border:`1px solid ${i?e.color:r.cellBorder}`,borderRadius:8,cursor:"pointer",color:i?e.color:r.textSecondary,fontSize:11,fontFamily:r.font,fontWeight:600,padding:"0 11px",width:"auto",minWidth:"max-content",height:40,flex:"0 0 auto",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"center",gap:7,transition:"all 0.12s"},children:[E.jsx("span",{style:{color:e.color,display:"flex",alignItems:"center",justifyContent:"center"},children:E.jsx(o,{size:16,strokeWidth:1.85})}),E.jsx("span",{style:{whiteSpace:"nowrap",letterSpacing:0},children:e.label})]})}function sl({registerCellRef:e,onStartResearch:t,researchRefreshKey:r}){var h;const n=Fe(Rt(p=>({activeFile:p.activeFile,appMode:p.appMode,cells:p.cells,inspectorOpen:p.inspectorOpen,themeMode:p.themeMode}))),s=Vt(),{executeCell:T}=BE(),i=se[n.themeMode],o=l.useMemo(()=>n.cells.map(Io).filter(p=>!!p),[n.cells]),S=l.useMemo(()=>new Map(o.map(p=>[p.id,p])),[o]),a=l.useMemo(()=>o.map(p=>`${p.id}:${p.fingerprint}`).join("|"),[o]),[A,R]=l.useState(new Map),[N,O]=l.useState(null),c=l.useRef(0),[C,I]=l.useState(null),[d,L]=l.useState(null);l.useCallback(p=>{O(p)},[]),l.useEffect(()=>{const p=G=>{var V;const y=(V=G.detail)==null?void 0:V.cellId;y&&(O(y),window.requestAnimationFrame(()=>{const k=Array.from(document.querySelectorAll("[data-cell-id]")).find(Z=>Z.dataset.cellId===y);k==null||k.scrollIntoView({behavior:"smooth",block:"center"})}))};return window.addEventListener(Lr,p),()=>window.removeEventListener(Lr,p)},[]),l.useEffect(()=>{N&&n.inspectorOpen&&s({type:"SET_INSPECTOR_CONTEXT",context:{kind:"cell",cellId:N}})},[N,n.inspectorOpen,s]),l.useEffect(()=>{var g;const p=(g=n.activeFile)==null?void 0:g.path;if(!p||o.length===0){R(new Map);return}let G=!1,y,V=!1;const k=()=>{V||document.visibilityState!=="visible"||(V=!0,Q.listNotebookResearchSourceCoverage({path:p,sourceCellIds:o.map(K=>K.id),sourceCells:o.map(K=>({id:K.id,name:K.name,type:K.type,fingerprint:K.fingerprint})),limit:Math.max(100,Math.min(2e3,o.length*4))}).then(K=>{if(G)return;const j=new Map;for(const B of K.runs)B.sourceCellId&&!j.has(B.sourceCellId)&&j.set(B.sourceCellId,B);R(j)}).catch(()=>{G||R(new Map)}).finally(()=>{V=!1}))};k();const Z=K=>{const j=K.detail;j!=null&&j.notebookPath&&j.notebookPath!==p||k()};return window.addEventListener(it,Z),y=window.setInterval(k,15e3),()=>{G=!0,window.removeEventListener(it,Z),y&&window.clearInterval(y)}},[r,a,(h=n.activeFile)==null?void 0:h.path]),l.useEffect(()=>{function p(G){var Z;if(!N)return;const y=G.target;if(y.tagName==="TEXTAREA"||y.tagName==="INPUT"||y.isContentEditable||y.closest(".cm-editor")){O(null);return}const V=n.cells,k=V.findIndex(g=>g.id===N);if(k!==-1)switch(G.key){case"a":{G.preventDefault();const g=Se("sql");if(k===0)s({type:"ADD_CELL",cell:g,afterId:V[0].id}),s({type:"MOVE_CELL",id:g.id,direction:"up"});else{const K=V[k-1].id;s({type:"ADD_CELL",cell:g,afterId:K})}O(g.id);break}case"b":{G.preventDefault();const g=Se("sql");s({type:"ADD_CELL",cell:g,afterId:N}),O(g.id);break}case"d":{G.preventDefault();const g=Date.now();if(g-c.current<=500){if(s({type:"DELETE_CELL",id:N}),V.length>1){const K=k>0?k-1:1;O(((Z=V[K])==null?void 0:Z.id)??null)}else O(null);c.current=0}else c.current=g;break}case"Enter":{if(G.shiftKey){G.preventDefault();const g=V[k];g&&g.type!=="markdown"&&T(g.id)}break}}}return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[N,n.cells,s,T]),l.useEffect(()=>{function p(G){G.target.closest("[data-cell-id]")||O(null)}return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[]);const f=l.useCallback((p,G)=>{I(G),p.dataTransfer.effectAllowed="move",p.dataTransfer.setData("text/plain",String(G));const y=p.currentTarget;setTimeout(()=>{y.style.opacity="0.4"},0)},[]),v=l.useCallback(p=>{p.currentTarget.style.opacity="1",I(null),L(null)},[]),U=l.useCallback((p,G)=>{p.preventDefault(),p.dataTransfer.dropEffect="move",L(G)},[]),F=l.useCallback((p,G)=>{p.preventDefault(),C!==null&&C!==G&&s({type:"REORDER_CELL",fromIndex:C,toIndex:G}),I(null),L(null)},[C,s]);return n.cells.length===0?E.jsx("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:E.jsx(ol,{t:i})}):E.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[n.appMode==="studio"&&E.jsx(Dn,{afterId:void 0}),n.cells.map((p,G)=>E.jsxs(Yt.Fragment,{children:[E.jsxs("div",{ref:y=>e(p.id,y),"data-cell-id":p.id,draggable:n.appMode==="studio",onDragStart:n.appMode==="studio"?y=>f(y,G):void 0,onDragEnd:n.appMode==="studio"?v:void 0,onDragOver:n.appMode==="studio"?y=>U(y,G):void 0,onDrop:n.appMode==="studio"?y=>F(y,G):void 0,onClick:y=>{const V=y.target;!V.closest(".cm-editor")&&!V.closest("textarea")&&!V.closest("input")&&O(p.id)},style:{outline:N===p.id?`2px solid ${i.accent}40`:"none",outlineOffset:2,borderRadius:10,transition:"outline 0.1s, transform 0.15s",position:"relative",...d===G&&C!==null&&C!==G?{borderTop:`2px solid ${i.accent}`}:{}},children:[E.jsx("div",{style:{position:"absolute",left:-20,top:8,width:16,height:24,display:"flex",alignItems:"center",justifyContent:"center",cursor:"grab",color:i.textMuted,opacity:0,transition:"opacity 0.15s",zIndex:5},className:"drag-handle",children:E.jsxs("svg",{width:"8",height:"14",viewBox:"0 0 8 14",fill:"currentColor",children:[E.jsx("circle",{cx:"2",cy:"2",r:"1.2"}),E.jsx("circle",{cx:"6",cy:"2",r:"1.2"}),E.jsx("circle",{cx:"2",cy:"7",r:"1.2"}),E.jsx("circle",{cx:"6",cy:"7",r:"1.2"}),E.jsx("circle",{cx:"2",cy:"12",r:"1.2"}),E.jsx("circle",{cx:"6",cy:"12",r:"1.2"})]})}),E.jsx($S,{cell:p,index:G,onStartResearch:t,researchState:co(S.get(p.id)??null,A.get(p.id)??null,No(A.get(p.id)??null,S))})]}),n.appMode==="studio"&&E.jsx(Dn,{afterId:p.id})]},p.id)),E.jsx("style",{children:`
178
+ `))}),rows:2,placeholder:"Do not include refunded orders.",style:{...Ne(t,{size:"sm"}),resize:"vertical",lineHeight:1.4}})]}),E.jsxs("label",{style:{display:"grid",gap:4,color:t.textMuted,fontSize:10},children:["Expected outcome or result shape",E.jsx("input",{value:f.expectedOutcome??"",onChange:p=>v({...f,expectedOutcome:p.target.value||void 0}),placeholder:"One row per region using net revenue",style:Ne(t,{size:"sm"})})]})]})]}),E.jsxs("div",{children:[E.jsx("div",{style:{color:t.textSecondary,fontSize:10.5,fontWeight:700,marginBottom:6},children:"Where should this learning apply?"}),E.jsx("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(145px, 1fr))",gap:7},children:[["domain","Domain"],["metric","Metric"],["dbtModel","dbt model"],["term","Business term"],["block","Block"],["dialect","SQL dialect"]].map(([p,G])=>E.jsxs("label",{style:{display:"grid",gap:3,color:t.textMuted,fontSize:10},children:[G,E.jsx("input",{value:U[p]??"",onChange:y=>F({...U,[p]:y.target.value||void 0}),placeholder:`Optional ${G.toLowerCase()}`,style:Ne(t,{size:"sm"})})]},p))})]}),E.jsxs("label",{style:{display:"grid",gap:4,color:t.textSecondary,fontSize:10.5,fontWeight:650},children:["Why is this correct? ",E.jsx("span",{style:{color:t.textMuted,fontWeight:400},children:"(optional reviewer evidence)"}),E.jsx("textarea",{value:d,onChange:p=>L(p.target.value),rows:2,placeholder:"Example: Finance defines revenue as net amount and excludes refunded orders.",style:{...Ne(t,{size:"sm"}),resize:"vertical",lineHeight:1.45}})]}),E.jsxs("div",{style:{border:`1px solid ${we(U)?`${t.success}55`:`${t.warning}66`}`,borderRadius:7,padding:"9px 10px",background:we(U)?`${t.success}08`:`${t.warning}0A`,display:"grid",gap:4,fontSize:10.5},children:[E.jsxs("div",{style:{color:t.textPrimary,fontWeight:700},children:["Will apply to: ",Br(U).length?`questions matching ${Br(U).join(" · ")}`:"no confirmed scope yet"]}),E.jsx("div",{style:{color:t.textMuted},children:"Will not apply when a confirmed scope value differs. Relations and columns are derived from the corrected SQL and current project snapshot, then used for ranking, drift checks, and review evidence."}),we(U)?null:E.jsx("div",{style:{color:t.warning},children:"Add at least one domain, metric, model, term, or block before saving."})]}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[E.jsxs("button",{type:"button",onClick:()=>void h(),disabled:r==="saving"||!we(U),style:Ne(t,{variant:"primary",size:"md",disabled:r==="saving"||!we(U)}),children:[E.jsx(qe,{size:14,"aria-hidden":"true"}),r==="saving"?"Saving candidate…":"Save learning candidate"]}),E.jsx("span",{style:{color:t.textMuted,fontSize:10.25},children:"It remains inactive until evaluation and explicit approval in Agent learning."})]})]}):null]})}function ue({title:e,onClick:t,children:r,t:n,accent:s,danger:T,run:i}){const[o,S]=l.useState(!1),a=i?n.success:T?n.error:s?n.accent:void 0;return E.jsx("button",{title:e,"aria-label":e,onClick:t,onMouseEnter:()=>S(!0),onMouseLeave:()=>S(!1),style:{width:26,height:26,display:"flex",alignItems:"center",justifyContent:"center",background:a?o?`${a}24`:`${a}12`:o?n.btnHover:"transparent",border:`1px solid ${a?o?`${a}66`:`${a}33`:o?n.btnBorder:"transparent"}`,borderRadius:6,cursor:"pointer",color:a??(o?n.textSecondary:n.textMuted),transition:"background 0.15s, border-color 0.15s, color 0.15s",padding:0},children:r})}function el({selected:e,onSelect:t,onClose:r,t:n}){const[s,T]=l.useState(null);return Yt.useEffect(()=>{const i=o=>{setTimeout(()=>r(),0)};return document.addEventListener("mousedown",i),()=>document.removeEventListener("mousedown",i)},[r]),E.jsx("div",{onMouseDown:i=>i.stopPropagation(),style:{position:"absolute",top:24,right:0,zIndex:200,background:n.cellBg,border:`1px solid ${n.cellBorder}`,borderRadius:6,boxShadow:"0 8px 24px rgba(0,0,0,0.3)",padding:4,minWidth:130,maxHeight:280,overflowY:"auto",display:"flex",flexDirection:"column",gap:1},children:wt.map(({value:i,label:o})=>E.jsx("button",{onClick:()=>t(i),onMouseEnter:()=>T(i),onMouseLeave:()=>T(null),style:{background:e===i?`${n.accent}20`:s===i?n.btnHover:"transparent",border:"none",borderRadius:4,cursor:"pointer",color:e===i?n.accent:n.textSecondary,fontSize:11,fontFamily:n.font,fontWeight:e===i?600:400,padding:"4px 10px",textAlign:"left",transition:"background 0.1s"},children:o},i))})}function tl({columns:e,chartConfig:t,onChange:r,t:n}){const s={background:n.inputBg,border:`1px solid ${n.inputBorder}`,borderRadius:4,color:n.textPrimary,fontSize:11,fontFamily:n.fontMono,padding:"3px 6px",outline:"none",minWidth:100,flex:1},T={fontSize:9,fontWeight:700,color:n.textMuted,fontFamily:n.font,letterSpacing:"0.05em",textTransform:"uppercase",minWidth:40,flexShrink:0};return E.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:"6px 16px",padding:"8px 12px",borderTop:`1px solid ${n.cellBorder}`,background:`${n.tableHeaderBg}40`},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:T,children:"X axis"}),E.jsxs("select",{style:s,value:(t==null?void 0:t.x)??"",onChange:i=>r({x:i.target.value||void 0}),children:[E.jsx("option",{value:"",children:"Auto"}),e.map(i=>E.jsx("option",{value:i,children:i},i))]})]}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:T,children:"Y axis"}),E.jsxs("select",{style:s,value:(t==null?void 0:t.y)??"",onChange:i=>r({y:i.target.value||void 0}),children:[E.jsx("option",{value:"",children:"Auto"}),e.map(i=>E.jsx("option",{value:i,children:i},i))]})]}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[E.jsx("span",{style:T,children:"Color"}),E.jsxs("select",{style:s,value:(t==null?void 0:t.color)??"",onChange:i=>r({color:i.target.value||void 0}),children:[E.jsx("option",{value:"",children:"None"}),e.map(i=>E.jsx("option",{value:i,children:i},i))]})]}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flex:1,minWidth:150},children:[E.jsx("span",{style:T,children:"Title"}),E.jsx("input",{style:{...s,fontFamily:n.font},value:(t==null?void 0:t.title)??"",placeholder:"Chart title",onChange:i=>r({title:i.target.value||void 0})})]})]})}function Rs({themeMode:e,onPick:t,autoFocus:r=!0,compact:n=!0}){const{state:s}=Pe(),T=se[e],[i,o]=l.useState([]),[S,a]=l.useState(!0),[A,R]=l.useState(""),[N,O]=l.useState(""),[c,C]=l.useState(""),I=l.useRef(null);l.useEffect(()=>{let h=!1;return a(!0),Q.getBlockLibrary().then(p=>{h||o(p.blocks)}).finally(()=>{h||a(!1)}),()=>{h=!0}},[]),l.useEffect(()=>{if(r){const h=setTimeout(()=>{var p;return(p=I.current)==null?void 0:p.focus()},30);return()=>clearTimeout(h)}},[r]);const d=l.useMemo(()=>Gs(s.authoredDomains),[s.authoredDomains]),L=l.useMemo(()=>Bs(s.authoredDomains),[s.authoredDomains]),f=l.useMemo(()=>i.some(h=>{var p;return!d.has(((p=h.domain)==null?void 0:p.trim())??"")}),[i,d]),v=l.useMemo(()=>[...new Set(i.map(h=>h.status))].sort(),[i]),U=l.useMemo(()=>i.filter(h=>{var p;if(A){const G=A.toLowerCase();if(![h.name,h.description,h.llmContext,h.domain,h.status,h.owner,...h.tags??[]].filter(Boolean).join(" ").toLowerCase().includes(G))return!1}return!(N==="uncategorized"&&d.has(((p=h.domain)==null?void 0:p.trim())??"")||N&&N!=="uncategorized"&&(!d.has(N)||h.domain!==N)||c&&h.status!==c)}).sort((h,p)=>+(p.status==="certified")-+(h.status==="certified")||h.name.localeCompare(p.name)),[i,A,N,c,d]),F={background:T.inputBg,border:`1px solid ${T.inputBorder}`,borderRadius:4,color:T.textPrimary,fontSize:11,fontFamily:T.font,padding:"4px 6px",outline:"none"};return E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:n?340:void 0},children:[E.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center"},children:[E.jsx("input",{ref:I,value:A,onChange:h=>R(h.target.value),placeholder:"Search question, block, domain, owner, or tag…","aria-label":"Search existing blocks",style:{...F,flex:1,padding:"6px 8px"}}),E.jsxs("select",{"aria-label":"Filter blocks by domain",value:N,onChange:h=>O(h.target.value),style:F,children:[E.jsx("option",{value:"",children:"All domains"}),L.map(h=>E.jsx("option",{value:h.value,children:h.label},h.value)),f?E.jsx("option",{value:"uncategorized",children:"Unassigned"}):null]}),E.jsxs("select",{"aria-label":"Filter blocks by status",value:c,onChange:h=>C(h.target.value),style:F,children:[E.jsx("option",{value:"",children:"Any"}),v.map(h=>E.jsx("option",{value:h,children:h},h))]})]}),!S&&E.jsxs("div",{style:{fontSize:10,color:T.textMuted,fontFamily:T.font,padding:"0 2px"},children:[U.length," reusable ",U.length===1?"block":"blocks"," · certified results are listed first"]}),E.jsx("div",{style:{maxHeight:n?220:420,overflowY:"auto",display:"flex",flexDirection:"column",border:`1px solid ${T.cellBorder}`,borderRadius:4},children:S?E.jsx(pn,{t:T,children:"Loading blocks..."}):U.length===0?E.jsx(pn,{t:T,children:i.length===0?"No blocks yet. Save a cell as a block to get started.":"No blocks match your filters."}):U.map(h=>E.jsx(El,{block:h,onClick:()=>t(h),t:T,compact:n},h.path))})]})}function pn({children:e,t}){return E.jsx("div",{style:{padding:16,textAlign:"center",fontSize:11,color:t.textMuted,fontFamily:t.font,fontStyle:"italic"},children:e})}function El({block:e,onClick:t,t:r,compact:n}){const[s,T]=l.useState(!1),i=Qs[e.status]??r.textMuted;return E.jsxs("button",{onClick:t,onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),style:{background:s?`${r.accent}14`:"transparent",border:"none",borderBottom:`1px solid ${r.cellBorder}`,cursor:"pointer",padding:n?"8px 10px":"10px 12px",textAlign:"left",fontFamily:r.font},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:3},children:[E.jsx("span",{style:{fontSize:12,fontWeight:600,color:r.textPrimary},children:e.name}),E.jsx("span",{style:{fontSize:9,fontWeight:600,color:i,background:`${i}18`,padding:"1px 6px",borderRadius:4,textTransform:"uppercase",letterSpacing:"0.04em"},children:e.status})]}),e.description&&E.jsx("div",{style:{fontSize:11,color:r.textMuted,lineHeight:1.3,marginBottom:3,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.description}),E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,fontSize:10,color:r.textMuted},children:[E.jsx("span",{style:{background:r.pillBg,padding:"1px 6px",borderRadius:4},children:e.domain||"no domain"}),e.owner&&E.jsxs("span",{children:["by ",e.owner]}),(e.tags??[]).slice(0,n?2:4).map(o=>E.jsxs("span",{style:{background:r.pillBg,padding:"1px 6px",borderRadius:4},children:["#",o]},o))]})]})}const rl=[{type:"block",label:"Block",Icon:Or,color:"#6b8afd"},{type:"ai_sql",label:"Ask AI",Icon:qe,color:"#f0883e"},{type:"dql",label:"DQL",Icon:Or,color:"#6b8afd"},{type:"sql",label:"SQL",Icon:bs,color:"#3b8ef0"},{type:"import_data",label:"Import",Icon:no,color:"#5dd1c8"},{type:"markdown",label:"Note",Icon:gn,color:"#2fb97a"},{type:"param",label:"Input",Icon:Fs,color:"#9aa0ae"}];function Dn({afterId:e}){const{state:t,dispatch:r}=Pe(),n=se[t.themeMode],[s,T]=l.useState(!1),[i,o]=l.useState(!1),[S,a]=l.useState(!1),[A,R]=l.useState(!1),N=l.useRef(null);l.useEffect(()=>{if(!i)return;function I(d){N.current&&!N.current.contains(d.target)&&(o(!1),a(!1))}return document.addEventListener("mousedown",I),()=>document.removeEventListener("mousedown",I)},[i]);const O=()=>{o(!1),a(!1)},c=I=>{const d=Se(I);r({type:"ADD_CELL",cell:d,afterId:e}),O()},C=async I=>{try{await Q.openBlockStudio(I.path)}catch(f){console.error("Failed to bind block cell",f),window.alert(`Couldn't load block ${I.path}. Check the console for details.`),O();return}const d=`@block(${JSON.stringify(I.name)})`,L=Se("dql",d);L.name=I.name,L.blockBinding={path:I.path,state:"bound",originalContent:d},r({type:"ADD_CELL",cell:L,afterId:e}),O()};return E.jsxs("div",{ref:N,"data-testid":"add-cell-bar",onDragOver:I=>{I.dataTransfer.types.includes(Nr)&&(I.preventDefault(),R(!0))},onDragLeave:()=>R(!1),onDrop:I=>{const d=Hs(I.dataTransfer.getData(Nr));if(!d)return;I.preventDefault(),R(!1);const L=Se("sql",d.reference);r({type:"ADD_CELL",cell:L,afterId:e}),Q.trackUsage(d.name),window.dispatchEvent(new CustomEvent("dql:semantic-used",{detail:{name:d.name}}))},onMouseEnter:()=>T(!0),onMouseLeave:()=>{T(!1),R(!1)},onClick:I=>{I.target===I.currentTarget&&(T(!0),o(!0))},style:{position:"relative",height:28,display:"flex",alignItems:"center",justifyContent:"center",cursor:i?"default":"pointer"},children:[(s||i||A)&&E.jsxs("button",{"aria-label":"Add cell",onClick:()=>o(I=>!I),style:{position:"relative",zIndex:2,height:22,padding:"0 10px",borderRadius:11,border:`1px solid ${A?n.accent:n.cellBorderActive}`,background:A?`${n.accent}28`:`${n.accent}18`,color:n.accent,cursor:"pointer",fontSize:12,fontFamily:n.font,fontWeight:500,display:"flex",alignItems:"center",gap:4,transition:"background 0.15s"},children:[E.jsx("span",{style:{fontSize:14,lineHeight:1,marginTop:-1},children:"+"}),"Add cell"]}),i&&E.jsxs("div",{style:{position:"absolute",top:26,left:"50%",transform:"translateX(-50%)",zIndex:100,background:n.modalBg,border:`1px solid ${n.cellBorder}`,borderRadius:10,boxShadow:"0 12px 32px rgba(0,0,0,0.35)",padding:8,display:"flex",flexDirection:"column",gap:8,width:S?"min(760px, calc(100vw - 48px))":"max-content",maxWidth:"calc(100vw - 48px)"},children:[E.jsx("div",{style:{display:"flex",gap:4,flexWrap:"nowrap",alignItems:"center",justifyContent:"flex-start",overflowX:"auto",overflowY:"hidden",maxWidth:"100%",paddingBottom:1},children:rl.map(I=>E.jsx(nl,{entry:I,active:I.type==="block"&&S,onClick:()=>{if(I.type==="block"){a(d=>!d);return}if(I.type==="ai_sql"){window.dispatchEvent(new CustomEvent("dql:open-notebook-ai",{detail:{afterId:e}})),O();return}if(I.type==="import_data"){window.dispatchEvent(new CustomEvent("dql:open-dataset-import",{detail:{afterId:e}})),O();return}c(I.type)},t:n},I.type))}),S&&E.jsx("div",{style:{padding:"6px 2px 2px",borderTop:`1px solid ${n.cellBorder}`},children:E.jsx(Rs,{themeMode:t.themeMode,onPick:I=>void C(I)})})]})]})}function nl({entry:e,onClick:t,t:r,active:n=!1}){const[s,T]=l.useState(!1),i=n||s,o=e.Icon;return E.jsxs("button",{"aria-label":e.type==="ai_sql"?"Ask AI":e.type==="import_data"?"Import data":`Add ${e.label} cell`,"data-testid":`add-cell-${e.type}`,onClick:t,onMouseEnter:()=>T(!0),onMouseLeave:()=>T(!1),title:e.label,style:{background:i?`${e.color}18`:"transparent",border:`1px solid ${i?e.color:r.cellBorder}`,borderRadius:8,cursor:"pointer",color:i?e.color:r.textSecondary,fontSize:11,fontFamily:r.font,fontWeight:600,padding:"0 11px",width:"auto",minWidth:"max-content",height:40,flex:"0 0 auto",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"center",gap:7,transition:"all 0.12s"},children:[E.jsx("span",{style:{color:e.color,display:"flex",alignItems:"center",justifyContent:"center"},children:E.jsx(o,{size:16,strokeWidth:1.85})}),E.jsx("span",{style:{whiteSpace:"nowrap",letterSpacing:0},children:e.label})]})}function sl({registerCellRef:e,onStartResearch:t,researchRefreshKey:r}){var h;const n=Fe(Rt(p=>({activeFile:p.activeFile,appMode:p.appMode,cells:p.cells,inspectorOpen:p.inspectorOpen,themeMode:p.themeMode}))),s=Vt(),{executeCell:T}=BE(),i=se[n.themeMode],o=l.useMemo(()=>n.cells.map(Io).filter(p=>!!p),[n.cells]),S=l.useMemo(()=>new Map(o.map(p=>[p.id,p])),[o]),a=l.useMemo(()=>o.map(p=>`${p.id}:${p.fingerprint}`).join("|"),[o]),[A,R]=l.useState(new Map),[N,O]=l.useState(null),c=l.useRef(0),[C,I]=l.useState(null),[d,L]=l.useState(null);l.useCallback(p=>{O(p)},[]),l.useEffect(()=>{const p=G=>{var V;const y=(V=G.detail)==null?void 0:V.cellId;y&&(O(y),window.requestAnimationFrame(()=>{const k=Array.from(document.querySelectorAll("[data-cell-id]")).find(Z=>Z.dataset.cellId===y);k==null||k.scrollIntoView({behavior:"smooth",block:"center"})}))};return window.addEventListener(Lr,p),()=>window.removeEventListener(Lr,p)},[]),l.useEffect(()=>{N&&n.inspectorOpen&&s({type:"SET_INSPECTOR_CONTEXT",context:{kind:"cell",cellId:N}})},[N,n.inspectorOpen,s]),l.useEffect(()=>{var g;const p=(g=n.activeFile)==null?void 0:g.path;if(!p||o.length===0){R(new Map);return}let G=!1,y,V=!1;const k=()=>{V||document.visibilityState!=="visible"||(V=!0,Q.listNotebookResearchSourceCoverage({path:p,sourceCellIds:o.map(K=>K.id),sourceCells:o.map(K=>({id:K.id,name:K.name,type:K.type,fingerprint:K.fingerprint})),limit:Math.max(100,Math.min(2e3,o.length*4))}).then(K=>{if(G)return;const j=new Map;for(const B of K.runs)B.sourceCellId&&!j.has(B.sourceCellId)&&j.set(B.sourceCellId,B);R(j)}).catch(()=>{G||R(new Map)}).finally(()=>{V=!1}))};k();const Z=K=>{const j=K.detail;j!=null&&j.notebookPath&&j.notebookPath!==p||k()};return window.addEventListener(it,Z),y=window.setInterval(k,15e3),()=>{G=!0,window.removeEventListener(it,Z),y&&window.clearInterval(y)}},[r,a,(h=n.activeFile)==null?void 0:h.path]),l.useEffect(()=>{function p(G){var Z;if(!N)return;const y=G.target;if(y.tagName==="TEXTAREA"||y.tagName==="INPUT"||y.isContentEditable||y.closest(".cm-editor")){O(null);return}const V=n.cells,k=V.findIndex(g=>g.id===N);if(k!==-1)switch(G.key){case"a":{G.preventDefault();const g=Se("sql");if(k===0)s({type:"ADD_CELL",cell:g,afterId:V[0].id}),s({type:"MOVE_CELL",id:g.id,direction:"up"});else{const K=V[k-1].id;s({type:"ADD_CELL",cell:g,afterId:K})}O(g.id);break}case"b":{G.preventDefault();const g=Se("sql");s({type:"ADD_CELL",cell:g,afterId:N}),O(g.id);break}case"d":{G.preventDefault();const g=Date.now();if(g-c.current<=500){if(s({type:"DELETE_CELL",id:N}),V.length>1){const K=k>0?k-1:1;O(((Z=V[K])==null?void 0:Z.id)??null)}else O(null);c.current=0}else c.current=g;break}case"Enter":{if(G.shiftKey){G.preventDefault();const g=V[k];g&&g.type!=="markdown"&&T(g.id)}break}}}return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[N,n.cells,s,T]),l.useEffect(()=>{function p(G){G.target.closest("[data-cell-id]")||O(null)}return document.addEventListener("mousedown",p),()=>document.removeEventListener("mousedown",p)},[]);const f=l.useCallback((p,G)=>{I(G),p.dataTransfer.effectAllowed="move",p.dataTransfer.setData("text/plain",String(G));const y=p.currentTarget;setTimeout(()=>{y.style.opacity="0.4"},0)},[]),v=l.useCallback(p=>{p.currentTarget.style.opacity="1",I(null),L(null)},[]),U=l.useCallback((p,G)=>{p.preventDefault(),p.dataTransfer.dropEffect="move",L(G)},[]),F=l.useCallback((p,G)=>{p.preventDefault(),C!==null&&C!==G&&s({type:"REORDER_CELL",fromIndex:C,toIndex:G}),I(null),L(null)},[C,s]);return n.cells.length===0?E.jsx("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:E.jsx(ol,{t:i})}):E.jsxs("div",{style:{maxWidth:1200,margin:"0 auto",padding:"0 24px",display:"flex",flexDirection:"column"},children:[n.appMode==="studio"&&E.jsx(Dn,{afterId:void 0}),n.cells.map((p,G)=>E.jsxs(Yt.Fragment,{children:[E.jsxs("div",{ref:y=>e(p.id,y),"data-cell-id":p.id,draggable:n.appMode==="studio",onDragStart:n.appMode==="studio"?y=>f(y,G):void 0,onDragEnd:n.appMode==="studio"?v:void 0,onDragOver:n.appMode==="studio"?y=>U(y,G):void 0,onDrop:n.appMode==="studio"?y=>F(y,G):void 0,onClick:y=>{const V=y.target;!V.closest(".cm-editor")&&!V.closest("textarea")&&!V.closest("input")&&O(p.id)},style:{outline:N===p.id?`2px solid ${i.accent}40`:"none",outlineOffset:2,borderRadius:10,transition:"outline 0.1s, transform 0.15s",position:"relative",...d===G&&C!==null&&C!==G?{borderTop:`2px solid ${i.accent}`}:{}},children:[E.jsx("div",{style:{position:"absolute",left:-20,top:8,width:16,height:24,display:"flex",alignItems:"center",justifyContent:"center",cursor:"grab",color:i.textMuted,opacity:0,transition:"opacity 0.15s",zIndex:5},className:"drag-handle",children:E.jsxs("svg",{width:"8",height:"14",viewBox:"0 0 8 14",fill:"currentColor",children:[E.jsx("circle",{cx:"2",cy:"2",r:"1.2"}),E.jsx("circle",{cx:"6",cy:"2",r:"1.2"}),E.jsx("circle",{cx:"2",cy:"7",r:"1.2"}),E.jsx("circle",{cx:"6",cy:"7",r:"1.2"}),E.jsx("circle",{cx:"2",cy:"12",r:"1.2"}),E.jsx("circle",{cx:"6",cy:"12",r:"1.2"})]})}),E.jsx($S,{cell:p,index:G,onStartResearch:t,researchState:co(S.get(p.id)??null,A.get(p.id)??null,No(A.get(p.id)??null,S))})]}),n.appMode==="studio"&&E.jsx(Dn,{afterId:p.id})]},p.id)),E.jsx("style",{children:`
179
179
  [data-cell-id]:hover .drag-handle { opacity: 0.5 !important; }
180
180
  [data-cell-id]:hover .drag-handle:hover { opacity: 1 !important; }
181
181
  `})]})}function ol({t:e}){const t=Fe(o=>o.themeMode),r=Vt(),[n,s]=l.useState(!1),T=async o=>{try{await Q.openBlockStudio(o.path)}catch(A){console.error("Failed to bind block cell",A),window.alert(`Couldn't load block ${o.path}.`);return}const S=`@block(${JSON.stringify(o.name)})`,a=Se("dql",S);a.name=o.name,a.blockBinding={path:o.path,state:"bound",originalContent:S},r({type:"ADD_CELL",cell:a}),s(!1)},i={minHeight:58,border:`1px solid ${e.cellBorder}`,background:e.cellBg,color:e.textPrimary,borderRadius:8,padding:"9px 11px",textAlign:"left",cursor:"pointer",fontFamily:e.font};return E.jsxs("div",{style:{display:"flex",flexDirection:"column",padding:"28px 0 56px",gap:16,color:e.textSecondary,width:"min(760px, 100%)",margin:"0 auto"},children:[E.jsxs("div",{children:[E.jsx("div",{style:{font:`750 18px ${e.font}`,color:e.textPrimary},children:"What are you researching?"}),E.jsx("div",{style:{marginTop:4,font:`12px/1.5 ${e.font}`,color:e.textMuted},children:"Start from trusted work when it exists, or explore directly with DQL, AI, and local data."})]}),E.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:8},children:[E.jsxs("button",{type:"button",style:{...i,borderColor:e.accent},onClick:()=>s(o=>!o),children:[E.jsx("strong",{style:{display:"block",color:e.accent},children:"Use existing block"}),E.jsx("span",{style:{display:"block",color:e.textMuted,fontSize:10.5,marginTop:3},children:"Search certified and draft reusable analysis."})]}),E.jsxs("button",{type:"button",style:i,onClick:()=>window.dispatchEvent(new CustomEvent("dql:open-notebook-ai")),children:[E.jsx("strong",{style:{display:"block"},children:"Ask Notebook AI"}),E.jsx("span",{style:{display:"block",color:e.textMuted,fontSize:10.5,marginTop:3},children:"Research blocks, semantic models, dbt, and data."})]}),E.jsxs("button",{type:"button",style:i,onClick:()=>r({type:"ADD_CELL",cell:Se("dql")}),children:[E.jsx("strong",{style:{display:"block"},children:"Create DQL query"}),E.jsx("span",{style:{display:"block",color:e.textMuted,fontSize:10.5,marginTop:3},children:"Build a governed or exploratory query."})]}),E.jsxs("button",{type:"button",style:i,onClick:()=>window.dispatchEvent(new CustomEvent("dql:open-dataset-import")),children:[E.jsx("strong",{style:{display:"block"},children:"Import local data"}),E.jsx("span",{style:{display:"block",color:e.textMuted,fontSize:10.5,marginTop:3},children:"Bring CSV, Parquet, or JSON into the research."})]})]}),n&&E.jsx("div",{style:{border:`1px solid ${e.cellBorder}`,borderRadius:10,padding:10,background:e.cellBg},children:E.jsx(Rs,{themeMode:t,compact:!1,onPick:o=>void T(o)})}),E.jsx("button",{type:"button",onClick:()=>r({type:"ADD_CELL",cell:Se("markdown",`## Research note
@@ -184,7 +184,7 @@ Which markets generate the most net sales?`,style:{...Ne(t,{size:"sm"}),resize:"
184
184
  `).map(n=>{const s=n.trim(),T=s.match(/^(#{1,6})\s+(.+)$/);if(T){const o=T[1].length;return`<div style="font-size:${["28px","22px","18px","16px","14px","13px"][o-1]};font-weight:${o<=2?700:600};color:${t.textPrimary};margin:8px 0 4px">${r(T[2])}</div>`}if(/^[-*_]{3,}$/.test(s))return`<hr style="border:none;border-top:1px solid ${t.cellBorder};margin:8px 0"/>`;if(!s)return'<div style="height:6px"></div>';let i=r(s);return i=i.replace(/\*{2}(.+?)\*{2}/g,"<strong>$1</strong>"),i=i.replace(/\*(.+?)\*/g,"<em>$1</em>"),i=i.replace(/`(.+?)`/g,`<code style="background:${t.editorBg};padding:1px 4px;border-radius:3px;font-size:0.9em">$1</code>`),`<div style="margin-bottom:4px">${i}</div>`}).join("")}const As=[{value:"draft",label:"Draft",dot:"#f59e0b"},{value:"in_review",label:"In review",dot:"#5b8def"},{value:"certified",label:"Certified",dot:"#4ade80"},{value:"deprecated",label:"Deprecated",dot:"#ef4444"}];function Al(e){return e?As.find(t=>t.value===e)??{value:e,label:e,dot:"#888"}:null}function Sl(){const{state:e,dispatch:t}=Pe(),r=se[e.themeMode],[n,s]=l.useState(null),T=l.useRef(null);if(l.useEffect(()=>{if(!n)return;const O=C=>{T.current&&!T.current.contains(C.target)&&s(null)},c=C=>{C.key==="Escape"&&s(null)};return document.addEventListener("mousedown",O),document.addEventListener("keydown",c),()=>{document.removeEventListener("mousedown",O),document.removeEventListener("keydown",c)}},[n]),!e.activeFile)return null;const i=e.activeFile.name.replace(/\.dqlnb$/,""),o=e.notebookMetadata,S=O=>{t({type:"UPDATE_NOTEBOOK_METADATA",updates:O})},a=Al(o.status),A=(o.categories??[]).length>0,R=!!o.description,N=!!o.projectFilter;return E.jsxs("div",{ref:T,style:{maxWidth:1080,margin:"0 auto",padding:"32px 48px 8px",display:"flex",flexDirection:"column",gap:12},children:[E.jsx("div",{style:{fontSize:22,fontWeight:650,color:r.textPrimary,fontFamily:r.font,letterSpacing:"-0.01em"},children:i}),E.jsxs("div",{style:{display:"grid",gap:5},children:[E.jsx("label",{htmlFor:"notebook-purpose",style:{font:`700 10px ${r.font}`,color:r.textMuted,textTransform:"uppercase",letterSpacing:".06em"},children:"Research purpose"}),E.jsx("textarea",{id:"notebook-purpose","aria-label":"Notebook research purpose",value:o.purpose??"",onChange:O=>S({purpose:O.target.value||void 0}),placeholder:"What business question or decision should this notebook answer? Include scope and important assumptions.",rows:2,style:{width:"100%",boxSizing:"border-box",resize:"vertical",border:`1px solid ${r.inputBorder}`,background:r.inputBg,color:r.textPrimary,borderRadius:7,padding:"8px 10px",font:`12px/1.45 ${r.font}`}})]}),E.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6,alignItems:"center",position:"relative"},children:[E.jsx(mt,{t:r,active:n==="status",filled:!!a,icon:E.jsx("span",{style:{color:(a==null?void 0:a.dot)??r.textMuted,fontSize:12},children:"●"}),label:(a==null?void 0:a.label)??"Add status",onClick:()=>s(n==="status"?null:"status"),children:n==="status"&&E.jsxs(ft,{t:r,children:[As.map(O=>E.jsxs("button",{onClick:()=>{S({status:O.value}),s(null)},style:mn(r,o.status===O.value),children:[E.jsx("span",{style:{color:O.dot,fontSize:12},children:"●"}),E.jsx("span",{children:O.label})]},O.value)),o.status&&E.jsx("button",{onClick:()=>{S({status:void 0}),s(null)},style:{...mn(r,!1),color:r.textMuted},children:E.jsx("span",{children:"Clear"})})]})}),E.jsx(mt,{t:r,active:n==="categories",filled:A,icon:E.jsx("span",{style:{fontFamily:r.fontMono,fontSize:10},children:"#"}),label:A?(o.categories??[]).slice(0,3).join(", ")+((o.categories??[]).length>3?"…":""):"Add categories",onClick:()=>s(n==="categories"?null:"categories"),children:n==="categories"&&E.jsx(ft,{t:r,width:260,children:E.jsx(Il,{t:r,value:o.categories??[],onChange:O=>S({categories:O.length?O:void 0})})})}),E.jsx(mt,{t:r,active:n==="description",filled:R,icon:E.jsx("span",{style:{fontFamily:r.fontMono,fontSize:10},children:"✎"}),label:R?Pn(o.description,48):"Add context",onClick:()=>s(n==="description"?null:"description"),children:n==="description"&&E.jsx(ft,{t:r,width:320,children:E.jsx(Mn,{multiline:!0,initial:o.description??"",onCommit:O=>S({description:O||void 0}),placeholder:"What does this notebook answer?",style:ll(r)})})}),E.jsx(mt,{t:r,active:n==="projectFilter",filled:N,icon:E.jsx("span",{style:{fontFamily:r.fontMono,fontSize:10},children:"⌕"}),label:N?Pn(o.projectFilter,32):"Add scope",onClick:()=>s(n==="projectFilter"?null:"projectFilter"),children:n==="projectFilter"&&E.jsx(ft,{t:r,width:280,children:E.jsx(Mn,{initial:o.projectFilter??"",onCommit:O=>S({projectFilter:O||void 0}),placeholder:"e.g. team:analytics",style:Ss(r)})})})]})]})}function Pn(e,t){return e.length>t?`${e.slice(0,t-1)}…`:e}function Mn({initial:e,onCommit:t,multiline:r,placeholder:n,style:s}){const[T,i]=l.useState(e),o=l.useRef(T);o.current=T;const S=()=>{const a=o.current.trim();a!==e.trim()&&t(a)};return l.useEffect(()=>()=>S(),[]),r?E.jsx("textarea",{autoFocus:!0,value:T,onChange:a=>i(a.target.value),onBlur:S,placeholder:n,rows:4,style:s}):E.jsx("input",{autoFocus:!0,value:T,onChange:a=>i(a.target.value),onBlur:S,onKeyDown:a=>{a.key==="Enter"&&(a.preventDefault(),a.target.blur())},placeholder:n,style:s})}function mt({t:e,active:t,filled:r,icon:n,label:s,onClick:T,children:i}){return E.jsxs("div",{style:{position:"relative"},children:[E.jsxs("button",{className:"dql-meta-pill",onClick:T,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"3px 9px",borderRadius:12,border:r?`1px solid ${e.cellBorder}`:`1px dashed ${e.cellBorder}`,background:t?`${e.accent}12`:r?e.pillBg:"transparent",color:r?e.textPrimary:e.textMuted,fontSize:11,fontFamily:e.font,cursor:"pointer",transition:"background-color 80ms, border-color 80ms","--dql-pill-hover-bg":`${e.accent}10`,"--dql-pill-hover-border":e.textMuted},children:[n,E.jsx("span",{children:s})]}),i]})}function ft({t:e,width:t=200,children:r}){return E.jsx("div",{style:{position:"absolute",top:"calc(100% + 6px)",left:0,zIndex:20,width:t,background:e.modalBg,border:`1px solid ${e.cellBorder}`,borderRadius:6,padding:6,boxShadow:"0 8px 24px rgba(0,0,0,0.35)",display:"flex",flexDirection:"column",gap:4},children:r})}function mn(e,t){return{display:"inline-flex",alignItems:"center",gap:8,padding:"6px 8px",borderRadius:4,border:"none",background:t?`${e.accent}18`:"transparent",color:e.textPrimary,fontSize:12,fontFamily:e.font,textAlign:"left",cursor:"pointer"}}function ll(e){return{width:"100%",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:4,color:e.textPrimary,fontSize:12,fontFamily:e.font,padding:8,outline:"none",resize:"vertical"}}function Ss(e){return{width:"100%",background:e.editorBg,border:`1px solid ${e.cellBorder}`,borderRadius:4,color:e.textPrimary,fontSize:12,fontFamily:e.fontMono,padding:"6px 8px",outline:"none"}}function Il({t:e,value:t,onChange:r}){const[n,s]=l.useState(""),T=()=>{const i=n.trim();if(i){if(t.includes(i)){s("");return}r([...t,i]),s("")}};return E.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[t.length>0&&E.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:t.map(i=>E.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",borderRadius:10,background:e.pillBg,border:`1px solid ${e.cellBorder}`,color:e.textPrimary,fontSize:11,fontFamily:e.font},children:[i,E.jsx("button",{onClick:()=>r(t.filter(o=>o!==i)),style:{background:"transparent",border:"none",color:e.textMuted,cursor:"pointer",padding:0,fontSize:12,lineHeight:1},"aria-label":`Remove ${i}`,children:"×"})]},i))}),E.jsx("input",{autoFocus:!0,value:n,onChange:i=>s(i.target.value),onKeyDown:i=>{i.key==="Enter"||i.key===","?(i.preventDefault(),T()):i.key==="Backspace"&&!n&&t.length>0&&r(t.slice(0,-1))},placeholder:"Add category, press Enter",style:Ss(e)})]})}function Ol({afterId:e,onClose:t}){const{state:r,dispatch:n}=Pe(),s=se[r.themeMode],[T,i]=l.useState("upload"),[o,S]=l.useState("local"),[a,A]=l.useState(null),[R,N]=l.useState(""),[O,c]=l.useState(!0),[C,I]=l.useState(""),[d,L]=l.useState(""),[f,v]=l.useState(""),[U,F]=l.useState(""),[h,p]=l.useState([]),[G,y]=l.useState(null),[V,k]=l.useState(!1),[Z,g]=l.useState(null),K=l.useRef(null),j=async()=>{const x=await Q.getDatasets();p(x.datasets),window.dispatchEvent(new CustomEvent("dql:datasets-changed",{detail:{count:x.datasets.length}}))};l.useEffect(()=>{j().catch(()=>{})},[]);const B=T==="upload"?!!a:!!R.trim(),ee=x=>{const u=Se("sql",`SELECT *
185
185
  FROM "${x.alias.replace(/"/g,'""')}"
186
186
  LIMIT 100`);u.name=`${x.alias}_query`,u.executionTarget={target:"local"},u.datasetRefs=[{id:x.id,alias:x.alias,role:x.storageMode==="staged"?"staged":"source",fingerprint:x.fileFingerprint}],n({type:"ADD_CELL",cell:u,afterId:e}),n({type:"SET_SCHEMA",tables:[...r.schemaTables.filter(W=>W.name!==x.alias),{name:x.alias,path:x.sourcePath,source:"file",objectType:"dataset",datasetId:x.id,fileFingerprint:x.fileFingerprint,storageMode:x.storageMode,refreshedAt:x.refreshedAt,trustState:x.trustState,columns:x.profile.columns.map(W=>({name:W.name,type:W.type}))}]}),t()},le=x=>{n({type:"SET_SCHEMA",tables:[...r.schemaTables.filter(u=>u.name!==x.alias),{name:x.alias,path:x.sourcePath,source:"file",objectType:x.storageMode==="staged"?"staged_dataset":"dataset",datasetId:x.id,fileFingerprint:x.fileFingerprint,storageMode:x.storageMode,refreshedAt:x.refreshedAt,trustState:x.trustState,columns:x.profile.columns.map(u=>({name:u.name,type:u.type}))}]})},Ie=async()=>{if(B){k(!0),g(null);try{const x=await Q.importDataset({filename:a==null?void 0:a.name,file:a??void 0,sourcePath:T==="path"?R.trim():void 0,storageMode:o,link:T==="path"&&o==="local"?O:!1,name:C.trim()||void 0,owner:d.trim()||void 0,description:f.trim()||void 0,tags:U.split(",").map(u=>u.trim()).filter(Boolean)});y(x.dataset),le(x.dataset),await j()}catch(x){g(x instanceof Error?x.message:String(x))}finally{k(!1)}}};return E.jsxs("section",{"aria-label":"Import data",style:{margin:"12px 18px 18px",border:`1px solid ${s.cellBorder}`,background:s.cellBg,borderRadius:10,boxShadow:"0 8px 24px rgba(0,0,0,.08)",overflow:"hidden"},children:[E.jsxs("header",{style:{minHeight:44,display:"flex",alignItems:"center",gap:9,padding:"0 14px",borderBottom:`1px solid ${s.cellBorder}`},children:[E.jsx(vt,{size:16,color:s.accent}),E.jsxs("div",{style:{flex:1},children:[E.jsx("div",{style:{color:s.textPrimary,fontSize:13,fontWeight:800},children:"Import data"}),E.jsx("div",{style:{color:s.textMuted,fontSize:10},children:"Create a reusable local dataset for research. CSV freshness is point-in-time."})]}),E.jsx("button",{"aria-label":"Close import data",onClick:t,style:{border:0,background:"transparent",color:s.textMuted,cursor:"pointer"},children:E.jsx(Hn,{size:16})})]}),E.jsx("div",{style:{display:"flex",borderBottom:`1px solid ${s.cellBorder}`},children:[["upload",ur,"Upload CSV"],["path",Fn,"Local path"],["existing",vs,"Available data"]].map(([x,u,W])=>E.jsxs("button",{onClick:()=>{i(x),y(null),g(null)},style:{flex:1,height:38,border:0,borderBottom:`2px solid ${T===x?s.accent:"transparent"}`,background:T===x?`${s.accent}0d`:"transparent",color:T===x?s.accent:s.textSecondary,cursor:"pointer",font:`700 11px ${s.font}`,display:"inline-flex",justifyContent:"center",alignItems:"center",gap:6},children:[E.jsx(u,{size:13})," ",W]},x))}),T==="existing"?E.jsx(cl,{datasets:h,busy:V,onUse:ee,onRefresh:async x=>{k(!0);try{y((await Q.refreshDataset(x.id)).dataset),await j()}finally{k(!1)}},onRename:async x=>{var W;const u=(W=window.prompt("Dataset name",x.name))==null?void 0:W.trim();if(!(!u||u===x.name)){k(!0);try{await Q.renameDataset(x.id,u),await j()}finally{k(!1)}}},onPin:async x=>{k(!0);try{await Q.pinDataset(x.id,!x.pinned),await j()}finally{k(!1)}},onRemove:async x=>{if(window.confirm(`Remove ${x.name}?`)){k(!0);try{await Q.removeDataset(x.id),n({type:"SET_SCHEMA",tables:r.schemaTables.filter(u=>u.name!==x.alias)}),await j()}finally{k(!1)}}},t:s}):G?E.jsx(Nl,{dataset:G,onAdd:()=>ee(G),onBack:()=>y(null),onUpdateSchema:async x=>{k(!0);try{const u=(await Q.updateDatasetSchema(G.id,x)).dataset;y(u),await j()}finally{k(!1)}},busy:V,t:s}):E.jsxs("div",{style:{padding:14,display:"grid",gap:12},children:[T==="upload"?E.jsxs("div",{children:[E.jsx("input",{ref:K,type:"file",accept:".csv,text/csv,.parquet,.json,.jsonl,.ndjson",hidden:!0,onChange:x=>{var W;const u=((W=x.target.files)==null?void 0:W[0])??null;A(u),u&&!C&&I(u.name.replace(/\.[^.]+$/,""))}}),E.jsxs("button",{onClick:()=>{var x;return(x=K.current)==null?void 0:x.click()},style:{width:"100%",minHeight:72,border:`1px dashed ${a?s.accent:s.inputBorder}`,background:a?`${s.accent}0c`:s.inputBg,color:a?s.accent:s.textSecondary,borderRadius:8,cursor:"pointer",font:`600 11px ${s.font}`},children:[E.jsx(ur,{size:18,style:{display:"block",margin:"0 auto 6px"}}),a?`${a.name} · ${dl(a.size)}`:"Choose a CSV file"]})]}):E.jsxs("label",{style:{display:"grid",gap:5,color:s.textSecondary,fontSize:11},children:["Local file path",E.jsx("input",{value:R,onChange:x=>N(x.target.value),placeholder:"/Users/me/Downloads/customers.csv",style:be(s)})]}),E.jsxs("div",{style:{display:"grid",gridTemplateColumns:"minmax(160px, 1fr) minmax(160px, 1fr)",gap:10},children:[E.jsxs("label",{style:ht(s),children:["Dataset name",E.jsx("input",{value:C,onChange:x=>I(x.target.value),placeholder:"Customer targets",style:be(s)})]}),E.jsxs("label",{style:ht(s),children:["Owner (optional)",E.jsx("input",{value:d,onChange:x=>L(x.target.value),placeholder:"analytics",style:be(s)})]}),E.jsxs("label",{style:ht(s),children:["Description",E.jsx("input",{value:f,onChange:x=>v(x.target.value),placeholder:"What this snapshot represents",style:be(s)})]}),E.jsxs("label",{style:ht(s),children:["Tags",E.jsx("input",{value:U,onChange:x=>F(x.target.value),placeholder:"forecast, local",style:be(s)})]})]}),E.jsxs("div",{style:{border:`1px solid ${s.cellBorder}`,borderRadius:7,padding:10},children:[E.jsx("div",{style:{color:s.textSecondary,fontSize:11,fontWeight:800,marginBottom:7},children:"Storage"}),E.jsxs("div",{style:{display:"flex",gap:8},children:[E.jsx(fn,{active:o==="local",title:"Local only",description:"Ignored by Git. Best for private or temporary analysis.",onClick:()=>S("local"),t:s}),E.jsx(fn,{active:o==="project",title:"Add to project",description:"Copies into data/ and writes data/sources.yml.",onClick:()=>{S("project"),c(!1)},t:s})]}),T==="path"&&o==="local"&&E.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,marginTop:8,color:s.textMuted,fontSize:10},children:[E.jsx("input",{type:"checkbox",checked:O,onChange:x=>c(x.target.checked)})," ","Link the original file instead of copying it"]})]}),Z&&E.jsx("div",{role:"alert",style:{color:s.error,fontSize:11},children:Z}),E.jsx("div",{style:{display:"flex",justifyContent:"flex-end"},children:E.jsx("button",{disabled:!B||V,onClick:()=>void Ie(),style:{border:`1px solid ${s.accent}`,background:s.accent,color:"#fff",borderRadius:6,padding:"7px 13px",cursor:B&&!V?"pointer":"not-allowed",opacity:B&&!V?1:.55,font:`700 11px ${s.font}`},children:V?"Profiling…":"Import and profile"})})]})]})}function Nl({dataset:e,onAdd:t,onBack:r,onUpdateSchema:n,busy:s,t:T}){const[i,o]=l.useState(e.schemaOverrides??{});return E.jsxs("div",{style:{padding:14,display:"grid",gap:10},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[E.jsxs("div",{style:{flex:1},children:[E.jsx("div",{style:{color:T.textPrimary,fontSize:13,fontWeight:800},children:e.name}),E.jsxs("div",{style:{color:T.textMuted,font:`10px ${T.fontMono}`},children:[e.alias," · ",e.profile.rowCount.toLocaleString()," rows · refreshed ",new Date(e.refreshedAt).toLocaleString()]})]}),E.jsx("span",{style:{color:e.trustState==="project_controlled"?T.success:T.warning,border:`1px solid ${e.trustState==="project_controlled"?T.success:T.warning}`,borderRadius:999,padding:"2px 7px",fontSize:9,fontWeight:800},children:e.trustState.replace(/_/g," ")})]}),e.profile.warnings.map(S=>E.jsx("div",{style:{color:T.warning,fontSize:10},children:S},S)),E.jsx("div",{style:{overflow:"auto",border:`1px solid ${T.cellBorder}`,borderRadius:7},children:E.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:10},children:[E.jsx("thead",{children:E.jsx("tr",{children:["Column","Type (editable)","Nulls in preview","Distinct","Signals"].map(S=>E.jsx("th",{style:{textAlign:"left",padding:6,color:T.textMuted,borderBottom:`1px solid ${T.cellBorder}`},children:S},S))})}),E.jsx("tbody",{children:e.profile.columns.map(S=>{var a;return E.jsxs("tr",{children:[E.jsx("td",{style:Et(T),children:S.name}),E.jsx("td",{style:Et(T),children:E.jsxs("select",{value:i[S.name]??S.type,onChange:A=>o(R=>({...R,[S.name]:A.target.value})),style:{...be(T),padding:"3px 5px",fontSize:9},children:[["VARCHAR","BOOLEAN","BIGINT","DOUBLE","DECIMAL(18,2)","DATE","TIMESTAMP","JSON"].map(A=>E.jsx("option",{value:A,children:A},A)),!["VARCHAR","BOOLEAN","BIGINT","DOUBLE","DECIMAL(18,2)","DATE","TIMESTAMP","JSON"].includes(S.type)&&E.jsx("option",{value:S.type,children:S.type})]})}),E.jsx("td",{style:Et(T),children:S.nullCount??0}),E.jsx("td",{style:Et(T),children:S.distinctCount??"—"}),E.jsx("td",{style:Et(T),children:((a=S.flags)==null?void 0:a.join(", "))||"—"})]},S.name)})})]})}),E.jsxs("div",{style:{display:"flex",justifyContent:"space-between",gap:8},children:[E.jsx("button",{onClick:r,style:hn(T),children:"Import another"}),E.jsxs("div",{style:{display:"flex",gap:7},children:[E.jsx("button",{disabled:s,onClick:()=>void n(i),style:hn(T),children:s?"Saving…":"Save types"}),E.jsxs("button",{onClick:t,style:ls(T),children:[E.jsx(Ws,{size:12})," Add starter query"]})]})]}),E.jsxs("div",{style:{color:T.textMuted,font:`10px ${T.font}`,textAlign:"right"},children:["To combine with warehouse data: run a warehouse Query cell, then choose ",E.jsx("strong",{children:"Combine with local data"})," on its result."]})]})}function cl({datasets:e,busy:t,onUse:r,onRefresh:n,onRename:s,onPin:T,onRemove:i,t:o}){const[S,a]=l.useState(""),A=l.useMemo(()=>e.filter(R=>`${R.name} ${R.alias} ${R.tags.join(" ")}`.toLowerCase().includes(S.toLowerCase())),[e,S]);return E.jsxs("div",{style:{padding:14,display:"grid",gap:8},children:[E.jsx("input",{value:S,onChange:R=>a(R.target.value),placeholder:"Search datasets",style:be(o)}),A.length===0?E.jsx("div",{style:{padding:24,textAlign:"center",color:o.textMuted,fontSize:11},children:"No imported datasets yet."}):A.map(R=>E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:9,border:`1px solid ${o.cellBorder}`,borderRadius:7,padding:9},children:[E.jsx(vt,{size:14,color:o.accent}),E.jsxs("div",{style:{minWidth:0,flex:1},children:[E.jsxs("div",{style:{color:o.textPrimary,fontSize:11,fontWeight:800},children:[R.name,R.pinned?" · pinned":""]}),E.jsxs("div",{style:{color:o.textMuted,fontSize:9},children:[R.alias," · ",R.profile.rowCount.toLocaleString()," ","rows · ",R.storageMode," ·"," ",new Date(R.refreshedAt).toLocaleString()]})]}),E.jsx("button",{disabled:t,title:"Refresh",onClick:()=>n(R),style:Ut(o),children:E.jsx(Ys,{size:12})}),E.jsx("button",{disabled:t,title:"Rename",onClick:()=>s(R),style:Ut(o),children:"Aa"}),R.storageMode==="staged"&&E.jsx("button",{disabled:t,title:R.pinned?"Unpin":"Pin",onClick:()=>T(R),style:Ut(o),children:R.pinned?"●":"○"}),E.jsx("button",{disabled:t,title:"Remove",onClick:()=>i(R),style:Ut(o),children:E.jsx(Vs,{size:12})}),E.jsx("button",{onClick:()=>r(R),style:ls(o),children:"Use"})]},R.id))]})}function fn({active:e,title:t,description:r,onClick:n,t:s}){return E.jsxs("button",{onClick:n,style:{flex:1,textAlign:"left",border:`1px solid ${e?s.accent:s.cellBorder}`,background:e?`${s.accent}0c`:"transparent",borderRadius:6,padding:8,cursor:"pointer"},children:[E.jsx("div",{style:{color:e?s.accent:s.textPrimary,fontSize:10,fontWeight:800},children:t}),E.jsx("div",{style:{color:s.textMuted,fontSize:9,marginTop:3},children:r})]})}function ht(e){return{display:"grid",gap:5,color:e.textSecondary,fontSize:10}}function be(e){return{background:e.inputBg,color:e.textPrimary,border:`1px solid ${e.inputBorder}`,borderRadius:6,padding:"7px 8px",font:`11px ${e.font}`}}function ls(e){return{border:`1px solid ${e.accent}`,background:`${e.accent}15`,color:e.accent,borderRadius:5,padding:"5px 9px",cursor:"pointer",font:`700 10px ${e.font}`,display:"inline-flex",alignItems:"center",gap:5}}function hn(e){return{border:`1px solid ${e.btnBorder}`,background:e.btnBg,color:e.textSecondary,borderRadius:5,padding:"5px 9px",cursor:"pointer",font:`700 10px ${e.font}`}}function Ut(e){return{width:26,height:26,border:`1px solid ${e.btnBorder}`,background:e.btnBg,color:e.textMuted,borderRadius:5,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center"}}function Et(e){return{padding:6,color:e.textSecondary,borderBottom:`1px solid ${e.cellBorder}`}}function dl(e){return e<1e6?`${(e/1e3).toFixed(1)} KB`:`${(e/1e6).toFixed(1)} MB`}const PE={total:0,active:0,blocked:0};function zl({onOpenFile:e,registerCellRef:t}){var x;const r=Fe(Rt(u=>({activeFile:u.activeFile,cells:u.cells,dashboardMode:u.dashboardMode,files:u.files,notebookMetadata:u.notebookMetadata,notebookTitle:u.notebookTitle,queryLog:u.queryLog,themeMode:u.themeMode}))),n=Vt(),s=zs(),T=se[r.themeMode],[i,o]=l.useState(!1),[S,a]=l.useState(!1),[A,R]=l.useState(null),[N,O]=l.useState(""),[c,C]=l.useState(void 0),[I,d]=l.useState(0),[L,f]=l.useState(PE),[v,U]=l.useState({open:!1}),[F,h]=l.useState([]),[p,G]=l.useState(()=>typeof window<"u"&&window.matchMedia("(max-width: 900px)").matches),y=(x=r.activeFile)==null?void 0:x.path,V=l.useMemo(()=>r.cells.find(u=>u.id===A)??null,[A,r.cells]),k=l.useMemo(()=>ul({notebookPath:y,notebookTitle:r.notebookTitle,notebookMetadata:r.notebookMetadata,cell:V,cells:r.cells,datasets:F}),[y,V,F,r.cells,r.notebookMetadata,r.notebookTitle]),Z=l.useCallback(u=>{R(null),O(""),C(void 0),o(!0),a(!0),e(u)},[e]);l.useEffect(()=>{if(!y){f(PE);return}let u=!1;return Q.listNotebookResearch({path:y,limit:1}).then(W=>{u||f({total:W.counts.total,active:W.counts.needsReview+W.counts.errors+W.counts.draftReady+W.counts.certificationReady,blocked:W.counts.blocked})}).catch(()=>{u||f(PE)}),()=>{u=!0}},[y,S,I,r.queryLog.length]),l.useEffect(()=>{const u=W=>{const P=W.detail;R((P==null?void 0:P.afterId)??null),O(""),C(void 0),a(!1),o(!0)};return window.addEventListener("dql:open-notebook-ai",u),()=>window.removeEventListener("dql:open-notebook-ai",u)},[]),l.useEffect(()=>{const u=()=>{Q.getDatasets().then(W=>h(W.datasets)).catch(()=>h([]))};return u(),window.addEventListener("dql:datasets-changed",u),()=>window.removeEventListener("dql:datasets-changed",u)},[y]),l.useEffect(()=>{var P;const u=window.matchMedia("(max-width: 900px)"),W=()=>G(u.matches);return W(),(P=u.addEventListener)==null||P.call(u,"change",W),()=>{var Y;return(Y=u.removeEventListener)==null?void 0:Y.call(u,"change",W)}},[]),l.useEffect(()=>{const u=W=>{const P=W.detail;U({open:!0,afterId:P==null?void 0:P.afterId})};return window.addEventListener("dql:open-dataset-import",u),()=>window.removeEventListener("dql:open-dataset-import",u)},[]);const g=l.useCallback((u,W,P)=>{const Y=(W==null?void 0:W.trim())??"";R(u),O(P!=null&&P.autoAsk?"":Y),C(P!=null&&P.autoAsk&&Y?{text:Y,nonce:Date.now()}:void 0),a(!1),o(!0)},[]),K=l.useCallback((u,W,P)=>{const Y=u.trim();if(!Y)return;const z=Se("sql",Y);z.name=rt(W??"AI SQL draft"),z.correctionProvenance=nt({question:P==null?void 0:P.question,generatedSql:Y,sourceRunId:P==null?void 0:P.sourceRunId});const $=F.filter(q=>new RegExp(`\\b${Un(q.alias)}\\b`,"i").test(Y)).map(q=>({id:q.id,alias:q.alias,role:q.storageMode==="staged"?"staged":"source",fingerprint:q.fileFingerprint}));$.length>0&&(z.executionTarget={target:"local"},z.datasetRefs=$),n({type:"ADD_CELL",cell:z,afterId:A??void 0}),Ot(z.id),R(z.id),o(!0)},[A,F,n]),j=l.useCallback(u=>{var $,q,te,re,ce,Qe;if(!r.activeFile){s(u,{datasets:F});return}const W=(u.sql??(($=u.dqlArtifact)==null?void 0:$.source)??"").trim();if(!W)return;if(u.mixedSourcePlan){const ne=u.mixedSourcePlan,Me=Se("markdown",[`### ${u.title??"Mixed-source analysis"}`,"",`This analysis combines a bounded warehouse extraction with the local dataset \`${ne.localDataset}\`.`,"",...(q=ne.warehouseRelations)!=null&&q.length?[`- Warehouse sources: ${ne.warehouseRelations.map(ve=>`\`${ve}\``).join(", ")}`]:[],`- Join: \`${ne.warehouseKey}\` = \`${ne.localKey}\``,"- Trust: local mixed-source analysis · review required","- Run the warehouse cell below, then confirm **Create joined analysis**."].join(`
187
- `));Me.name=rt("Analysis context");const de=Se("sql",W);de.name=rt(u.title??"Warehouse extraction"),de.mixedSourcePlan=ne,de.executionTarget={target:"connection"},de.datasetRefs=[{id:ne.datasetId??ne.localDataset,alias:ne.localDataset,role:"source"}],de.annotations=[{id:`note_${Date.now()}_mixed_source`,body:`AI prepared a bounded warehouse extraction for a local join with ${ne.localDataset} on ${ne.warehouseKey} = ${ne.localKey}. Review required.`,createdAt:new Date().toISOString(),author:"DQL"}],n({type:"ADD_CELL",cell:Me,afterId:A??void 0}),n({type:"ADD_CELL",cell:de,afterId:Me.id}),Ot(de.id),R(de.id),o(!0);return}const P=(re=(te=u.dqlArtifact)==null?void 0:te.source)==null?void 0:re.trim(),Y=Se(P?"dql":"sql",P||W);Y.name=rt(u.title??((ce=u.dqlArtifact)==null?void 0:ce.name)??"AI analysis"),u.result&&(Y.result=u.result,Y.status="success",Y.executionCount=1),u.chartConfig&&(Y.chartConfig=u.chartConfig),Y.correctionProvenance=nt({question:u.question,generatedSql:u.sql??((Qe=u.dqlArtifact)==null?void 0:Qe.compiledSql),generatedDql:P,sourceRunId:u.sourceRunId}),u.dqlArtifact&&(Y.dqlArtifact={source:u.dqlArtifact.source,sql:u.sql,name:u.dqlArtifact.name,sourcePath:u.dqlArtifact.sourcePath,kind:u.dqlArtifact.kind,metrics:u.dqlArtifact.metrics,dimensions:u.dqlArtifact.dimensions,parameters:u.dqlArtifact.parameters,parameterValues:u.dqlArtifact.parameterValues,persistence:u.dqlArtifact.persistence,trustState:u.dqlArtifact.trustState,compiledSql:u.dqlArtifact.compiledSql??u.sql,...u.question?{question:u.question}:{}},Y.dqlParameterValues=u.dqlArtifact.parameterValues);const z=F.filter(ne=>new RegExp(`\\b${Un(ne.alias)}\\b`,"i").test(W)).map(ne=>({id:ne.id,alias:ne.alias,role:ne.storageMode==="staged"?"staged":"source",fingerprint:ne.fileFingerprint}));z.length>0&&(Y.executionTarget={target:"local"},Y.datasetRefs=z,Y.dqlArtifact&&(Y.dqlArtifact.reviewState="review_required")),n({type:"ADD_CELL",cell:Y,afterId:A??void 0}),Ot(Y.id),R(Y.id),o(!0)},[A,F,n]),{executeCell:B}=BE(),ee=l.useCallback(u=>{var z,$,q,te,re;if(!A)return;const W=(u.sql??((z=u.dqlArtifact)==null?void 0:z.source)??"").trim(),P=(q=($=u.dqlArtifact)==null?void 0:$.source)==null?void 0:q.trim(),Y=P||W;if(Y&&(n({type:"UPDATE_CELL",id:A,updates:{type:P?"dql":"sql",content:Y,name:rt(u.title??((te=u.dqlArtifact)==null?void 0:te.name)??"AI edited cell"),execution:void 0,fromSnapshot:!1,...u.result?{result:u.result,status:"success",executionCount:1,stale:!1}:{result:void 0,status:"idle",executionCount:void 0},...u.chartConfig?{chartConfig:u.chartConfig}:{},correctionProvenance:nt({question:u.question,generatedSql:u.sql??((re=u.dqlArtifact)==null?void 0:re.compiledSql),generatedDql:P,sourceRunId:u.sourceRunId}),...u.dqlArtifact?{dqlArtifact:{source:u.dqlArtifact.source,sql:u.sql,name:u.dqlArtifact.name,sourcePath:u.dqlArtifact.sourcePath,kind:u.dqlArtifact.kind,metrics:u.dqlArtifact.metrics,dimensions:u.dqlArtifact.dimensions,parameters:u.dqlArtifact.parameters,parameterValues:u.dqlArtifact.parameterValues,persistence:u.dqlArtifact.persistence,trustState:u.dqlArtifact.trustState,compiledSql:u.dqlArtifact.compiledSql??u.sql,...u.question?{question:u.question}:{}},dqlParameterValues:u.dqlArtifact.parameterValues}:{dqlArtifact:void 0,dqlParameterValues:void 0}}}),Ot(A),!u.result)){const ce=A;setTimeout(()=>{B(ce)},80)}},[A,n,B]),le=l.useCallback(u=>{R(u.sourceCellId??null),O(u.question),C(void 0),a(!1),o(!0)},[]),Ie=l.useCallback(async(u,W)=>{if(W&&W!==y){const P=r.files.find(Y=>Y.path===W);P&&e(P)}try{const P=await Q.getNotebookResearch(u);R(P.sourceCellId??null),O(P.question),pr({notebookPath:P.notebookPath,sourceCellId:P.sourceCellId,runId:P.id,reason:"agent-run-open-research"})}catch{pr({notebookPath:W,runId:u,reason:"agent-run-open-research"})}C(void 0),d(Date.now()),a(!0),o(!0)},[y,e,r.files]);return r.activeFile?r.dashboardMode?E.jsx(Tl,{}):E.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:T.appBg},children:[E.jsx(Cl,{t:T,aiOpen:i,historyOpen:S,historyBadge:L,onToggleAi:()=>{R(null),O(""),C(void 0),o(u=>!u)},onToggleHistory:()=>{o(!0),a(u=>!u)}}),E.jsxs("div",{style:{flex:1,display:"flex",position:"relative",minHeight:0,overflow:"hidden"},children:[E.jsxs("div",{style:{flex:1,minWidth:0,overflow:"auto",padding:"0 0 40px",display:p&&i?"none":"block"},children:[E.jsx(Sl,{}),v.open&&E.jsx(Ol,{afterId:v.afterId,onClose:()=>U({open:!1})}),E.jsx(sl,{registerCellRef:t,researchRefreshKey:I,onStartResearch:g})]}),E.jsx("div",{style:{display:i?"contents":"none"},"aria-hidden":!i,children:E.jsx(Ll,{t:T,notebookPath:y,sourceCell:V,upstreamContext:k,initialInput:N,autoAsk:c,historyOpen:S,historyRefreshKey:I,onClose:()=>o(!1),onToggleHistory:()=>a(u=>!u),onInsertSql:K,onInsertDql:j,onReplaceDql:ee,onAskFromHistory:le,onOpenResearch:Ie,compact:p})})]})]}):E.jsx(Po,{onOpenFile:e,onOpenResearchFile:Z})}function Cl({t:e,aiOpen:t,historyOpen:r,historyBadge:n,onToggleAi:s,onToggleHistory:T}){const i=Fe(Rt(A=>({cellCount:A.cells.length,notebookDirty:A.notebookDirty}))),o=i.cellCount,S=n.blocked>0?e.error:n.active>0?e.warning:e.accent,a=n.total>0?[`${n.total} AI histor${n.total===1?"y item":"y items"}`,n.active>0?`${n.active} open`:void 0,n.blocked>0?`${n.blocked} blocked`:void 0].filter(Boolean).join(" · "):"Open notebook AI history";return E.jsxs("div",{style:{height:32,flexShrink:0,borderBottom:`1px solid ${e.headerBorder}`,background:e.cellBg,display:"flex",alignItems:"center",padding:"0 16px",gap:12},children:[E.jsx(Ml,{t:e}),E.jsx("div",{style:{flex:1}}),E.jsxs("button",{type:"button",title:t?"Hide notebook AI":"Ask AI about this notebook",onClick:s,style:{height:26,border:`1px solid ${t?e.accent:e.btnBorder}`,background:t?`${e.accent}16`:e.btnBg,color:t?e.accent:e.textSecondary,borderRadius:6,padding:"0 9px",display:"inline-flex",alignItems:"center",gap:6,fontSize:12,fontWeight:700,fontFamily:e.font,cursor:"pointer"},children:[E.jsx(qe,{size:14,strokeWidth:2,"aria-hidden":"true"}),"Notebook AI"]}),E.jsxs("button",{type:"button",title:a,onClick:T,style:{height:26,border:`1px solid ${r?S:e.btnBorder}`,background:r?`${S}12`:e.btnBg,color:r?S:e.textSecondary,borderRadius:6,padding:"0 9px",display:"inline-flex",alignItems:"center",gap:6,fontSize:12,fontWeight:700,fontFamily:e.font,cursor:"pointer"},children:[E.jsx(Yn,{size:14,strokeWidth:2,"aria-hidden":"true"}),"History",n.total>0&&E.jsx("span",{"aria-label":a,style:{minWidth:18,height:18,borderRadius:999,padding:"0 6px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:`1px solid ${S}`,background:`${S}14`,color:S,fontSize:10,fontWeight:800,lineHeight:1},children:n.total>99?"99+":n.total})]}),E.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font,display:"flex",alignItems:"center",gap:12},children:[E.jsxs("span",{children:[o," ",o===1?"cell":"cells"]}),i.notebookDirty&&E.jsx("span",{style:{color:e.warning},children:"● unsaved"})]})]})}function Ll({t:e,notebookPath:t,sourceCell:r,upstreamContext:n,initialInput:s,autoAsk:T,historyOpen:i,historyRefreshKey:o,onClose:S,onToggleHistory:a,onInsertSql:A,onInsertDql:R,onReplaceDql:N,onAskFromHistory:O,onOpenResearch:c,compact:C}){var K;const I=Fe(Rt(j=>({notebookTitle:j.notebookTitle,themeMode:j.themeMode}))),d=so(),L=qs(`notebook:${t??"notebook"}`),[f,v]=l.useState(!1),[U,F]=l.useState(!1),[h,p]=l.useState(0),G=r?`${r.type.toUpperCase()} cell${r.name?` · ${r.name}`:""}`:"Whole notebook",y=r?"This cell + dbt, semantic metadata, certified blocks, prior AI history":"Whole notebook + dbt, semantic metadata, certified blocks, prior AI history",V=(r==null?void 0:r.type)==="sql"?r.content.trim():(r==null?void 0:r.type)==="dql"?(K=xn(r.content))==null?void 0:K.trim():void 0,k=V?{cellSql:V}:void 0,Z=r?{kind:"cell",id:r.id,title:r.name,path:t}:t?{kind:"notebook",path:t,title:I.notebookTitle||"Notebook"}:void 0,g={...k??{},notebookPath:t,notebookTitle:I.notebookTitle,sourceCellId:r==null?void 0:r.id,sourceCellName:r==null?void 0:r.name,sourceCellType:r==null?void 0:r.type,notebookContext:n};return E.jsxs(ro,{t:e,title:"Notebook AI",subtitle:G,expanded:f,onToggleExpanded:()=>v(j=>!j),onClose:S,compact:C,onNewChat:()=>{L.resetThreadId(),p(j=>j+1)},running:U,ariaLabel:"Notebook AI",headerActions:E.jsx(no,{t:e,label:i?"Hide AI history":"Show AI history",onClick:a,active:i,children:E.jsx(Yn,{size:14})}),dock:"overlay",children:[i&&E.jsx(_l,{t:e,notebookPath:t,sourceCellId:r==null?void 0:r.id,refreshKey:o,onAskFromHistory:O}),E.jsx("div",{style:{flex:1,minHeight:0},children:E.jsx(Bn,{themeMode:I.themeMode,title:"Notebook AI",scopeHint:y,notebookPath:t,selectedObject:Z,workspaceContext:g,initialMode:"auto",initialInput:T?"":s,autoRun:T?{text:T.text,mode:"ask",nonce:T.nonce}:void 0,threadId:L.threadId,onThreadIdChange:L.onThreadIdChange,onRunningChange:F,onInsertSql:A,onInsertDql:R,onReplaceDql:r?N:void 0,answerFirstCards:!0,insertDqlActionLabel:"Add to notebook",replaceDqlActionLabel:r?T?"Apply fix & run":"Replace cell & run":void 0,onOpenBlock:(j,B)=>{d(j,B??j)},onOpenResearch:(j,B)=>{c(j,B)}},`auto:${t??"notebook"}:${(r==null?void 0:r.id)??"all"}:${h}`)})]})}function _l({t:e,notebookPath:t,sourceCellId:r,refreshKey:n,onAskFromHistory:s}){const[T,i]=l.useState([]),[o,S]=l.useState(!1),[a,A]=l.useState(null);return l.useEffect(()=>{if(!t){i([]);return}let R=!1;return S(!0),A(null),Q.listNotebookResearch({path:t,sourceCellId:r,sort:"updated_desc",limit:12}).then(N=>{R||i(N.runs)}).catch(N=>{R||A(N instanceof Error?N.message:String(N))}).finally(()=>{R||S(!1)}),()=>{R=!0}},[t,n,r]),E.jsxs("div",{style:{borderBottom:`1px solid ${e.headerBorder}`,background:e.appBg,maxHeight:260,overflow:"auto",padding:10},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[E.jsx(To,{size:14,color:e.textMuted}),E.jsx("div",{style:{fontSize:11,fontWeight:850,color:e.textSecondary,textTransform:"uppercase",letterSpacing:"0.04em"},children:"AI history"}),E.jsx("div",{style:{flex:1}}),o&&E.jsx("span",{style:{fontSize:11,color:e.textMuted},children:"Loading"})]}),a&&E.jsx("div",{style:{fontSize:11,color:e.error,lineHeight:1.4},children:a}),!o&&!a&&T.length===0&&E.jsxs("div",{style:{fontSize:12,color:e.textMuted,lineHeight:1.45},children:["No saved AI history for this ",r?"cell":"notebook"," yet."]}),E.jsx("div",{style:{display:"grid",gap:7},children:T.map(R=>E.jsxs("button",{type:"button",onClick:()=>s(R),style:{border:`1px solid ${e.cellBorder}`,background:e.cellBg,color:e.textPrimary,borderRadius:8,padding:"8px 9px",textAlign:"left",cursor:"pointer",display:"grid",gap:4},children:[E.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[E.jsx("span",{style:{fontSize:12,fontWeight:800,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:R.title||R.question}),E.jsx("span",{style:{marginLeft:"auto",fontSize:10,color:Pl(R,e),fontWeight:850},children:Dl(R)})]}),E.jsx("div",{style:{fontSize:11,color:e.textMuted,lineHeight:1.35,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:R.question}),E.jsxs("div",{style:{fontSize:10,color:e.textMuted,fontFamily:e.fontMono},children:[pl(R.updatedAt),R.generatedSql||R.reviewedSql?" · SQL saved":"",R.dqlPromotionAction?` · ${R.dqlPromotionAction.split("_").join(" ")}`:""]})]},R.id))})]})}function ul(e){var T,i,o,S,a,A,R,N;const t=[];t.push("Notebook AI contract:"),t.push(["- Use the same path for research, SQL generation, SQL repair, DQL reuse checks, and DQL draft planning.","- Always check certified DQL blocks, draft blocks, dbt/semantic metadata, and runtime schema before proposing new SQL.","- Return one clear outcome: Reuse certified block, Use existing draft, Review SQL preview, Fix SQL, Create DQL draft, Needs review, or Cannot answer yet.","- For review-required DQL artifacts, prefer reusable parameterizable SQL preview logic over hard-coded literals when the business question implies a reusable block.","- Keep DQL certification manual; do not claim SQL previews or drafts are certified.","- Imported CSV and staged warehouse snapshots are point-in-time local data. Never label a mixed local result certified.","- Before a cross-source join, state the governed source, local dataset, proposed join keys and cardinality, freshness mismatch, extraction scope, and review-required trust label.","- If join keys are ambiguous or likely many-to-many, ask a focused follow-up question instead of guessing.","- Never request or include complete dataset rows. Use the supplied schema/profile/lineage and only bounded redacted samples from explicit tools.","- Explain business purpose, grain, filters/parameters, technical lineage, duplicate/reuse evidence, preview status, and next action."].join(`
187
+ `));Me.name=rt("Analysis context");const de=Se("sql",W);de.name=rt(u.title??"Warehouse extraction"),de.mixedSourcePlan=ne,de.executionTarget={target:"connection"},de.datasetRefs=[{id:ne.datasetId??ne.localDataset,alias:ne.localDataset,role:"source"}],de.annotations=[{id:`note_${Date.now()}_mixed_source`,body:`AI prepared a bounded warehouse extraction for a local join with ${ne.localDataset} on ${ne.warehouseKey} = ${ne.localKey}. Review required.`,createdAt:new Date().toISOString(),author:"DQL"}],n({type:"ADD_CELL",cell:Me,afterId:A??void 0}),n({type:"ADD_CELL",cell:de,afterId:Me.id}),Ot(de.id),R(de.id),o(!0);return}const P=(re=(te=u.dqlArtifact)==null?void 0:te.source)==null?void 0:re.trim(),Y=Se(P?"dql":"sql",P||W);Y.name=rt(u.title??((ce=u.dqlArtifact)==null?void 0:ce.name)??"AI analysis"),u.result&&(Y.result=u.result,Y.status="success",Y.executionCount=1),u.chartConfig&&(Y.chartConfig=u.chartConfig),Y.correctionProvenance=nt({question:u.question,generatedSql:u.sql??((Qe=u.dqlArtifact)==null?void 0:Qe.compiledSql),generatedDql:P,sourceRunId:u.sourceRunId}),u.dqlArtifact&&(Y.dqlArtifact={source:u.dqlArtifact.source,sql:u.sql,name:u.dqlArtifact.name,sourcePath:u.dqlArtifact.sourcePath,kind:u.dqlArtifact.kind,metrics:u.dqlArtifact.metrics,dimensions:u.dqlArtifact.dimensions,parameters:u.dqlArtifact.parameters,parameterValues:u.dqlArtifact.parameterValues,persistence:u.dqlArtifact.persistence,trustState:u.dqlArtifact.trustState,compiledSql:u.dqlArtifact.compiledSql??u.sql,...u.question?{question:u.question}:{}},Y.dqlParameterValues=u.dqlArtifact.parameterValues);const z=F.filter(ne=>new RegExp(`\\b${Un(ne.alias)}\\b`,"i").test(W)).map(ne=>({id:ne.id,alias:ne.alias,role:ne.storageMode==="staged"?"staged":"source",fingerprint:ne.fileFingerprint}));z.length>0&&(Y.executionTarget={target:"local"},Y.datasetRefs=z,Y.dqlArtifact&&(Y.dqlArtifact.reviewState="review_required")),n({type:"ADD_CELL",cell:Y,afterId:A??void 0}),Ot(Y.id),R(Y.id),o(!0)},[A,F,n]),{executeCell:B}=BE(),ee=l.useCallback(u=>{var z,$,q,te,re;if(!A)return;const W=(u.sql??((z=u.dqlArtifact)==null?void 0:z.source)??"").trim(),P=(q=($=u.dqlArtifact)==null?void 0:$.source)==null?void 0:q.trim(),Y=P||W;if(Y&&(n({type:"UPDATE_CELL",id:A,updates:{type:P?"dql":"sql",content:Y,name:rt(u.title??((te=u.dqlArtifact)==null?void 0:te.name)??"AI edited cell"),execution:void 0,fromSnapshot:!1,...u.result?{result:u.result,status:"success",executionCount:1,stale:!1}:{result:void 0,status:"idle",executionCount:void 0},...u.chartConfig?{chartConfig:u.chartConfig}:{},correctionProvenance:nt({question:u.question,generatedSql:u.sql??((re=u.dqlArtifact)==null?void 0:re.compiledSql),generatedDql:P,sourceRunId:u.sourceRunId}),...u.dqlArtifact?{dqlArtifact:{source:u.dqlArtifact.source,sql:u.sql,name:u.dqlArtifact.name,sourcePath:u.dqlArtifact.sourcePath,kind:u.dqlArtifact.kind,metrics:u.dqlArtifact.metrics,dimensions:u.dqlArtifact.dimensions,parameters:u.dqlArtifact.parameters,parameterValues:u.dqlArtifact.parameterValues,persistence:u.dqlArtifact.persistence,trustState:u.dqlArtifact.trustState,compiledSql:u.dqlArtifact.compiledSql??u.sql,...u.question?{question:u.question}:{}},dqlParameterValues:u.dqlArtifact.parameterValues}:{dqlArtifact:void 0,dqlParameterValues:void 0}}}),Ot(A),!u.result)){const ce=A;setTimeout(()=>{B(ce)},80)}},[A,n,B]),le=l.useCallback(u=>{R(u.sourceCellId??null),O(u.question),C(void 0),a(!1),o(!0)},[]),Ie=l.useCallback(async(u,W)=>{if(W&&W!==y){const P=r.files.find(Y=>Y.path===W);P&&e(P)}try{const P=await Q.getNotebookResearch(u);R(P.sourceCellId??null),O(P.question),pr({notebookPath:P.notebookPath,sourceCellId:P.sourceCellId,runId:P.id,reason:"agent-run-open-research"})}catch{pr({notebookPath:W,runId:u,reason:"agent-run-open-research"})}C(void 0),d(Date.now()),a(!0),o(!0)},[y,e,r.files]);return r.activeFile?r.dashboardMode?E.jsx(Tl,{}):E.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",overflow:"hidden",background:T.appBg},children:[E.jsx(Cl,{t:T,aiOpen:i,historyOpen:S,historyBadge:L,onToggleAi:()=>{R(null),O(""),C(void 0),o(u=>!u)},onToggleHistory:()=>{o(!0),a(u=>!u)}}),E.jsxs("div",{style:{flex:1,display:"flex",position:"relative",minHeight:0,overflow:"hidden"},children:[E.jsxs("div",{style:{flex:1,minWidth:0,overflow:"auto",padding:"0 0 40px",display:p&&i?"none":"block"},children:[E.jsx(Sl,{}),v.open&&E.jsx(Ol,{afterId:v.afterId,onClose:()=>U({open:!1})}),E.jsx(sl,{registerCellRef:t,researchRefreshKey:I,onStartResearch:g})]}),E.jsx("div",{style:{display:i?"contents":"none"},"aria-hidden":!i,children:E.jsx(Ll,{t:T,notebookPath:y,sourceCell:V,upstreamContext:k,initialInput:N,autoAsk:c,historyOpen:S,historyRefreshKey:I,onClose:()=>o(!1),onToggleHistory:()=>a(u=>!u),onInsertSql:K,onInsertDql:j,onReplaceDql:ee,onAskFromHistory:le,onOpenResearch:Ie,compact:p})})]})]}):E.jsx(Po,{onOpenFile:e,onOpenResearchFile:Z})}function Cl({t:e,aiOpen:t,historyOpen:r,historyBadge:n,onToggleAi:s,onToggleHistory:T}){const i=Fe(Rt(A=>({cellCount:A.cells.length,notebookDirty:A.notebookDirty}))),o=i.cellCount,S=n.blocked>0?e.error:n.active>0?e.warning:e.accent,a=n.total>0?[`${n.total} AI histor${n.total===1?"y item":"y items"}`,n.active>0?`${n.active} open`:void 0,n.blocked>0?`${n.blocked} blocked`:void 0].filter(Boolean).join(" · "):"Open notebook AI history";return E.jsxs("div",{style:{height:32,flexShrink:0,borderBottom:`1px solid ${e.headerBorder}`,background:e.cellBg,display:"flex",alignItems:"center",padding:"0 16px",gap:12},children:[E.jsx(Ml,{t:e}),E.jsx("div",{style:{flex:1}}),E.jsxs("button",{type:"button",title:t?"Hide notebook AI":"Ask AI about this notebook",onClick:s,style:{height:26,border:`1px solid ${t?e.accent:e.btnBorder}`,background:t?`${e.accent}16`:e.btnBg,color:t?e.accent:e.textSecondary,borderRadius:6,padding:"0 9px",display:"inline-flex",alignItems:"center",gap:6,fontSize:12,fontWeight:700,fontFamily:e.font,cursor:"pointer"},children:[E.jsx(qe,{size:14,strokeWidth:2,"aria-hidden":"true"}),"Notebook AI"]}),E.jsxs("button",{type:"button",title:a,onClick:T,style:{height:26,border:`1px solid ${r?S:e.btnBorder}`,background:r?`${S}12`:e.btnBg,color:r?S:e.textSecondary,borderRadius:6,padding:"0 9px",display:"inline-flex",alignItems:"center",gap:6,fontSize:12,fontWeight:700,fontFamily:e.font,cursor:"pointer"},children:[E.jsx(Yn,{size:14,strokeWidth:2,"aria-hidden":"true"}),"History",n.total>0&&E.jsx("span",{"aria-label":a,style:{minWidth:18,height:18,borderRadius:999,padding:"0 6px",display:"inline-flex",alignItems:"center",justifyContent:"center",border:`1px solid ${S}`,background:`${S}14`,color:S,fontSize:10,fontWeight:800,lineHeight:1},children:n.total>99?"99+":n.total})]}),E.jsxs("span",{style:{fontSize:11,color:e.textMuted,fontFamily:e.font,display:"flex",alignItems:"center",gap:12},children:[E.jsxs("span",{children:[o," ",o===1?"cell":"cells"]}),i.notebookDirty&&E.jsx("span",{style:{color:e.warning},children:"● unsaved"})]})]})}function Ll({t:e,notebookPath:t,sourceCell:r,upstreamContext:n,initialInput:s,autoAsk:T,historyOpen:i,historyRefreshKey:o,onClose:S,onToggleHistory:a,onInsertSql:A,onInsertDql:R,onReplaceDql:N,onAskFromHistory:O,onOpenResearch:c,compact:C}){var K;const I=Fe(Rt(j=>({notebookTitle:j.notebookTitle,themeMode:j.themeMode}))),d=so(),L=qs(`notebook:${t??"notebook"}`),[f,v]=l.useState(!1),[U,F]=l.useState(!1),[h,p]=l.useState(0),G=r?`${r.type.toUpperCase()} cell${r.name?` · ${r.name}`:""}`:"Whole notebook",y=r?"This cell + dbt, semantic metadata, certified blocks, prior AI history":"Whole notebook + dbt, semantic metadata, certified blocks, prior AI history",V=(r==null?void 0:r.type)==="sql"?r.content.trim():(r==null?void 0:r.type)==="dql"?(K=xn(r.content))==null?void 0:K.trim():void 0,k=V?{cellSql:V}:void 0,Z=r?{kind:"cell",id:r.id,title:r.name,path:t}:t?{kind:"notebook",path:t,title:I.notebookTitle||"Notebook"}:void 0,g={...k??{},notebookPath:t,notebookTitle:I.notebookTitle,sourceCellId:r==null?void 0:r.id,sourceCellName:r==null?void 0:r.name,sourceCellType:r==null?void 0:r.type,notebookContext:n};return E.jsxs(Eo,{t:e,title:"Notebook AI",subtitle:G,expanded:f,onToggleExpanded:()=>v(j=>!j),onClose:S,compact:C,onNewChat:()=>{L.resetThreadId(),p(j=>j+1)},running:U,ariaLabel:"Notebook AI",headerActions:E.jsx(ro,{t:e,label:i?"Hide AI history":"Show AI history",onClick:a,active:i,children:E.jsx(Yn,{size:14})}),dock:"overlay",children:[i&&E.jsx(_l,{t:e,notebookPath:t,sourceCellId:r==null?void 0:r.id,refreshKey:o,onAskFromHistory:O}),E.jsx("div",{style:{flex:1,minHeight:0},children:E.jsx(Bn,{themeMode:I.themeMode,title:"Notebook AI",scopeHint:y,notebookPath:t,selectedObject:Z,workspaceContext:g,initialMode:"auto",initialInput:T?"":s,autoRun:T?{text:T.text,mode:"ask",nonce:T.nonce}:void 0,threadId:L.threadId,onThreadIdChange:L.onThreadIdChange,onRunningChange:F,onInsertSql:A,onInsertDql:R,onReplaceDql:r?N:void 0,answerFirstCards:!0,insertDqlActionLabel:"Add to notebook",replaceDqlActionLabel:r?T?"Apply fix & run":"Replace cell & run":void 0,onOpenBlock:(j,B)=>{d(j,B??j)},onOpenResearch:(j,B)=>{c(j,B)}},`auto:${t??"notebook"}:${(r==null?void 0:r.id)??"all"}:${h}`)})]})}function _l({t:e,notebookPath:t,sourceCellId:r,refreshKey:n,onAskFromHistory:s}){const[T,i]=l.useState([]),[o,S]=l.useState(!1),[a,A]=l.useState(null);return l.useEffect(()=>{if(!t){i([]);return}let R=!1;return S(!0),A(null),Q.listNotebookResearch({path:t,sourceCellId:r,sort:"updated_desc",limit:12}).then(N=>{R||i(N.runs)}).catch(N=>{R||A(N instanceof Error?N.message:String(N))}).finally(()=>{R||S(!1)}),()=>{R=!0}},[t,n,r]),E.jsxs("div",{style:{borderBottom:`1px solid ${e.headerBorder}`,background:e.appBg,maxHeight:260,overflow:"auto",padding:10},children:[E.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:8},children:[E.jsx(To,{size:14,color:e.textMuted}),E.jsx("div",{style:{fontSize:11,fontWeight:850,color:e.textSecondary,textTransform:"uppercase",letterSpacing:"0.04em"},children:"AI history"}),E.jsx("div",{style:{flex:1}}),o&&E.jsx("span",{style:{fontSize:11,color:e.textMuted},children:"Loading"})]}),a&&E.jsx("div",{style:{fontSize:11,color:e.error,lineHeight:1.4},children:a}),!o&&!a&&T.length===0&&E.jsxs("div",{style:{fontSize:12,color:e.textMuted,lineHeight:1.45},children:["No saved AI history for this ",r?"cell":"notebook"," yet."]}),E.jsx("div",{style:{display:"grid",gap:7},children:T.map(R=>E.jsxs("button",{type:"button",onClick:()=>s(R),style:{border:`1px solid ${e.cellBorder}`,background:e.cellBg,color:e.textPrimary,borderRadius:8,padding:"8px 9px",textAlign:"left",cursor:"pointer",display:"grid",gap:4},children:[E.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center"},children:[E.jsx("span",{style:{fontSize:12,fontWeight:800,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:R.title||R.question}),E.jsx("span",{style:{marginLeft:"auto",fontSize:10,color:Pl(R,e),fontWeight:850},children:Dl(R)})]}),E.jsx("div",{style:{fontSize:11,color:e.textMuted,lineHeight:1.35,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:R.question}),E.jsxs("div",{style:{fontSize:10,color:e.textMuted,fontFamily:e.fontMono},children:[pl(R.updatedAt),R.generatedSql||R.reviewedSql?" · SQL saved":"",R.dqlPromotionAction?` · ${R.dqlPromotionAction.split("_").join(" ")}`:""]})]},R.id))})]})}function ul(e){var T,i,o,S,a,A,R,N;const t=[];t.push("Notebook AI contract:"),t.push(["- Use the same path for research, SQL generation, SQL repair, DQL reuse checks, and DQL draft planning.","- Always check certified DQL blocks, draft blocks, dbt/semantic metadata, and runtime schema before proposing new SQL.","- Return one clear outcome: Reuse certified block, Use existing draft, Review SQL preview, Fix SQL, Create DQL draft, Needs review, or Cannot answer yet.","- For review-required DQL artifacts, prefer reusable parameterizable SQL preview logic over hard-coded literals when the business question implies a reusable block.","- Keep DQL certification manual; do not claim SQL previews or drafts are certified.","- Imported CSV and staged warehouse snapshots are point-in-time local data. Never label a mixed local result certified.","- Before a cross-source join, state the governed source, local dataset, proposed join keys and cardinality, freshness mismatch, extraction scope, and review-required trust label.","- If join keys are ambiguous or likely many-to-many, ask a focused follow-up question instead of guessing.","- Never request or include complete dataset rows. Use the supplied schema/profile/lineage and only bounded redacted samples from explicit tools.","- Explain business purpose, grain, filters/parameters, technical lineage, duplicate/reuse evidence, preview status, and next action."].join(`
188
188
  `)),t.push(`Notebook: ${e.notebookTitle||e.notebookPath||"Untitled notebook"}`),e.notebookPath&&t.push(`Path: ${e.notebookPath}`);const r=[e.notebookMetadata.purpose?`Purpose: ${Ue(e.notebookMetadata.purpose,1200)}`:"",e.notebookMetadata.description?`Business context: ${Ue(e.notebookMetadata.description,800)}`:"",e.notebookMetadata.status?`Notebook status: ${e.notebookMetadata.status}`:"",e.notebookMetadata.ownerDomain?`Owner domain: ${e.notebookMetadata.ownerDomain}`:"",(T=e.notebookMetadata.usesDomains)!=null&&T.length?`Uses domains: ${e.notebookMetadata.usesDomains.join(", ")}`:"",e.notebookMetadata.projectFilter?`Scope filter: ${e.notebookMetadata.projectFilter}`:"",(i=e.notebookMetadata.categories)!=null&&i.length?`Categories: ${e.notebookMetadata.categories.join(", ")}`:""].filter(Boolean);r.length>0&&t.push(r.join(`
189
189
  `));const n=e.cells.filter(O=>O.type==="markdown"&&O.content.trim()).slice(0,12).map((O,c)=>`${c+1}. ${Ue(O.content,700)}`);n.length>0&&(t.push("Notebook research narrative:"),t.push(n.join(`
190
190
  `)));const s=e.cells.filter(O=>{var c,C;return((c=O.annotations)==null?void 0:c.length)||O.upstream||((C=O.dependencies)==null?void 0:C.length)}).slice(0,30).map(O=>{var C,I;return`- ${[`${O.type.toUpperCase()}${O.name?` ${O.name}`:` ${O.id}`}`,O.upstream?`upstream=${O.upstream}`:"",(C=O.dependencies)!=null&&C.length?`dependencies=${O.dependencies.map(d=>d.output??d.cellId).join(",")}`:"",(I=O.annotations)!=null&&I.length?`research=${O.annotations.map(d=>`${d.kind??"note"}:${Ue(d.body,240)}`).join(" | ")}`:""].filter(Boolean).join(" · ")}`});if(s.length>0&&(t.push("Notebook dependency and research evidence:"),t.push(s.join(`